Stage Harbor release files 71501-72000
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/llama3_2.jinja +93 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/llama3_training.jinja +19 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/llava_next.jinja +6 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/llava_next_training.jinja +11 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/nemotron_3_nano.jinja +204 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/nemotron_3_nano_training.jinja +220 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/nemotron_3_super.jinja +209 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/nemotron_3_super_training.jinja +226 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/nemotron_3_ultra.jinja +195 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/nemotron_3_ultra_training.jinja +212 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/phi3.jinja +8 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/phi3_5.jinja +8 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/phi3_5_training.jinja +26 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/phi3_training.jinja +26 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen2_5.jinja +54 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen2_5_training.jinja +65 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen2_5_vl.jinja +7 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen2_5_vl_training.jinja +63 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen3.jinja +89 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen3_5_nothink.jinja +154 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen3_5_nothink_training.jinja +162 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen3_5_think.jinja +154 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen3_5_think_training.jinja +162 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen3_6.jinja +154 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen3_6_training.jinja +162 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen3_instruct_2507.jinja +61 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen3_instruct_2507_training.jinja +71 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen3_training.jinja +93 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen3_vl.jinja +120 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/chat_templates/qwen3_vl_training.jinja +127 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/cli/__init__.py +18 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/cli/accelerate_config.py +47 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/cli/accelerate_launcher.py +47 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/cli/commands/__init__.py +37 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/cli/commands/base.py +62 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/cli/commands/env.py +33 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/cli/commands/skills.py +42 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/cli/commands/training.py +72 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/cli/commands/vllm_serve.py +36 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/cli/main.py +51 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/data_utils.py +977 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/distributed.py +91 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/experimental/__init__.py +36 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/experimental/a2po/__init__.py +16 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/experimental/a2po/a2po_config.py +156 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/experimental/a2po/a2po_trainer.py +375 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/experimental/async_grpo/__init__.py +16 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/experimental/async_grpo/async_grpo_config.py +268 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/experimental/async_grpo/async_grpo_trainer.py +780 -0
- tasks/tasksmith-b71e9e0a47b6/environment/source/trl/experimental/async_grpo/async_rollout_worker.py +829 -0
tasks/tasksmith-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/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-b71e9e0a47b6/environment/source/trl/experimental/a2po/a2po_config.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 37 |
+
Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to
|
| 38 |
+
[`~transformers.AutoModelForCausalLM.from_pretrained`] and [`~transformers.AutoTokenizer.from_pretrained`].
|
| 39 |
+
|
| 40 |
+
> Parameters that control the data preprocessing
|
| 41 |
+
|
| 42 |
+
remove_unused_columns (`bool`, *optional*, defaults to `False`):
|
| 43 |
+
Whether to only keep the column `"prompt"` in the dataset. If you use a custom reward function that
|
| 44 |
+
requires any column other than `"prompts"` and `"completions"`, you should keep this to `False`.
|
| 45 |
+
|
| 46 |
+
> Parameters that control generation
|
| 47 |
+
|
| 48 |
+
max_prompt_length (`int` or `None`, *optional*, defaults to `512`):
|
| 49 |
+
Maximum length of the prompt. If the prompt is longer than this, it is left-truncated.
|
| 50 |
+
max_completion_length (`int` or `None`, *optional*, defaults to `256`):
|
| 51 |
+
Maximum length of the generated completion.
|
| 52 |
+
temperature (`float`, *optional*, defaults to `1.0`):
|
| 53 |
+
Sampling temperature, used in both Stage 1 and Stage 2 generation.
|
| 54 |
+
top_p (`float`, *optional*, defaults to `1.0`):
|
| 55 |
+
Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to
|
| 56 |
+
`1.0` to consider all tokens.
|
| 57 |
+
top_k (`int` or `None`, *optional*):
|
| 58 |
+
Number of highest-probability vocabulary tokens to keep. If `None`, top-k filtering is disabled.
|
| 59 |
+
|
| 60 |
+
> Parameters that control Stage 1 (offline optimal value estimation)
|
| 61 |
+
|
| 62 |
+
num_value_samples (`int`, *optional*, defaults to `8`):
|
| 63 |
+
Number of samples drawn from the reference policy per prompt to estimate `V*`.
|
| 64 |
+
beta1 (`float`, *optional*, defaults to `0.5`):
|
| 65 |
+
KL temperature used to estimate `V*` in Stage 1.
|
| 66 |
+
filter_all_incorrect (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether to drop prompts for which all reference samples are incorrect.
|
| 68 |
+
|
| 69 |
+
> Parameters that control Stage 2 (on-policy regression)
|
| 70 |
+
|
| 71 |
+
beta2 (`float`, *optional*, defaults to `1e-3`):
|
| 72 |
+
KL temperature used in the Stage 2 regression target.
|
| 73 |
+
reward_weights (`list[float]`, *optional*):
|
| 74 |
+
Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are
|
| 75 |
+
weighted equally with weight `1.0`.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
_VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"]
|
| 79 |
+
|
| 80 |
+
# Parameters that control the model and reference model
|
| 81 |
+
model_init_kwargs: dict | None = field(
|
| 82 |
+
default=None,
|
| 83 |
+
metadata={
|
| 84 |
+
"help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of "
|
| 85 |
+
"the `A2POTrainer` is provided as a string."
|
| 86 |
+
},
|
| 87 |
+
)
|
| 88 |
+
trust_remote_code: bool = field(
|
| 89 |
+
default=False,
|
| 90 |
+
metadata={
|
| 91 |
+
"help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. "
|
| 92 |
+
"Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoTokenizer.from_pretrained`."
|
| 93 |
+
},
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# Parameters that control the data preprocessing
|
| 97 |
+
remove_unused_columns: bool = field(
|
| 98 |
+
default=False,
|
| 99 |
+
metadata={
|
| 100 |
+
"help": "Whether to only keep the column 'prompt' in the dataset. If you use a custom reward function "
|
| 101 |
+
"that requires any column other than 'prompts' and 'completions', you should keep this to `False`."
|
| 102 |
+
},
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
# Parameters that control generation
|
| 106 |
+
max_prompt_length: int | None = field(
|
| 107 |
+
default=512,
|
| 108 |
+
metadata={"help": "Maximum length of the prompt. If the prompt is longer than this, it is left-truncated."},
|
| 109 |
+
)
|
| 110 |
+
max_completion_length: int | None = field(
|
| 111 |
+
default=256, metadata={"help": "Maximum length of the generated completion."}
|
| 112 |
+
)
|
| 113 |
+
temperature: float = field(
|
| 114 |
+
default=1.0,
|
| 115 |
+
metadata={"help": "Sampling temperature, used in both Stage 1 and Stage 2 generation."},
|
| 116 |
+
)
|
| 117 |
+
top_p: float = field(
|
| 118 |
+
default=1.0,
|
| 119 |
+
metadata={
|
| 120 |
+
"help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. "
|
| 121 |
+
"Set to `1.0` to consider all tokens."
|
| 122 |
+
},
|
| 123 |
+
)
|
| 124 |
+
top_k: int | None = field(
|
| 125 |
+
default=None,
|
| 126 |
+
metadata={
|
| 127 |
+
"help": "Number of highest-probability vocabulary tokens to keep. If `None`, top-k filtering is disabled."
|
| 128 |
+
},
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Parameters that control Stage 1 (offline optimal value estimation)
|
| 132 |
+
num_value_samples: int = field(
|
| 133 |
+
default=8,
|
| 134 |
+
metadata={"help": "Number of samples drawn from the reference policy per prompt to estimate `V*`."},
|
| 135 |
+
)
|
| 136 |
+
beta1: float = field(
|
| 137 |
+
default=0.5,
|
| 138 |
+
metadata={"help": "KL temperature used to estimate `V*` in Stage 1."},
|
| 139 |
+
)
|
| 140 |
+
filter_all_incorrect: bool = field(
|
| 141 |
+
default=True,
|
| 142 |
+
metadata={"help": "Whether to drop prompts for which all reference samples are incorrect."},
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
# Parameters that control Stage 2 (on-policy regression)
|
| 146 |
+
beta2: float = field(
|
| 147 |
+
default=1e-3,
|
| 148 |
+
metadata={"help": "KL temperature used in the Stage 2 regression target."},
|
| 149 |
+
)
|
| 150 |
+
reward_weights: list[float] | None = field(
|
| 151 |
+
default=None,
|
| 152 |
+
metadata={
|
| 153 |
+
"help": "Weights for each reward function. Must match the number of reward functions. If `None`, all "
|
| 154 |
+
"rewards are weighted equally with weight `1.0`."
|
| 155 |
+
},
|
| 156 |
+
)
|
tasks/tasksmith-b71e9e0a47b6/environment/source/trl/experimental/a2po/a2po_trainer.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 inspect
|
| 16 |
+
import math
|
| 17 |
+
import textwrap
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
from collections.abc import Callable
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from accelerate.logging import get_logger
|
| 23 |
+
from accelerate.utils import gather_object
|
| 24 |
+
from torch.utils.data import DataLoader
|
| 25 |
+
from transformers import (
|
| 26 |
+
AutoModelForCausalLM,
|
| 27 |
+
AutoTokenizer,
|
| 28 |
+
GenerationConfig,
|
| 29 |
+
PreTrainedModel,
|
| 30 |
+
PreTrainedTokenizerBase,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
from ...data_utils import maybe_apply_chat_template
|
| 34 |
+
from ...models import create_reference_model, unwrap_model_for_generation
|
| 35 |
+
from ...trainer.base_trainer import _BaseTrainer
|
| 36 |
+
from ...trainer.utils import selective_log_softmax
|
| 37 |
+
from .a2po_config import A2POConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
# A reward function is a callable that returns a list of floats (the rewards). The callable receives prompts,
|
| 43 |
+
# completions, and additional columns from the dataset. To ensure forward compatibility, it should accept **kwargs.
|
| 44 |
+
RewardFunc = Callable[..., list[float]]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class A2POTrainer(_BaseTrainer):
|
| 48 |
+
# docstyle-ignore
|
| 49 |
+
"""
|
| 50 |
+
Trainer for the A*-PO (Optimal Advantage Regression) method, introduced in [Accelerating RL for LLM Reasoning with
|
| 51 |
+
Optimal Advantage Regression](https://huggingface.co/papers/2505.20686).
|
| 52 |
+
|
| 53 |
+
A*-PO runs in two stages:
|
| 54 |
+
|
| 55 |
+
1. **Offline value estimation.** Before training, `num_value_samples` completions are sampled from the reference
|
| 56 |
+
policy for every training prompt and scored with `reward_funcs`. The optimal value is estimated as
|
| 57 |
+
`V*(x) = beta1 * log(mean_i exp(r(x, y_i) / beta1))` and cached per prompt.
|
| 58 |
+
2. **On-policy regression.** During training, a single completion is generated per prompt from the current policy.
|
| 59 |
+
The loss is the squared error between the implicit reward `beta2 * log(pi(y|x) / pi_ref(y|x))` and the optimal
|
| 60 |
+
advantage estimate `r(x, y) - V*(x)`.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
model (`PreTrainedModel` or `str`):
|
| 64 |
+
Model to be trained, or a model identifier (string) passed to
|
| 65 |
+
[`~transformers.AutoModelForCausalLM.from_pretrained`].
|
| 66 |
+
reward_funcs (`Callable` or `list[Callable]`):
|
| 67 |
+
Reward function(s). Each takes `prompts` and `completions` (plus dataset columns as keyword arguments) and
|
| 68 |
+
returns a list of float rewards. When multiple are provided, their weighted sum (see
|
| 69 |
+
[`A2POConfig.reward_weights`]) is the scalar reward `r`, which A*-PO assumes to be binary (in `{0, 1}`).
|
| 70 |
+
args ([`A2POConfig`], *optional*):
|
| 71 |
+
Configuration for this trainer. If `None`, a default configuration is used.
|
| 72 |
+
train_dataset ([`~datasets.Dataset`], *optional*):
|
| 73 |
+
Training dataset. Must contain a `"prompt"` column.
|
| 74 |
+
eval_dataset ([`~datasets.Dataset`], *optional*):
|
| 75 |
+
Evaluation dataset.
|
| 76 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*):
|
| 77 |
+
Processing class used to process the data. If `None`, it is loaded from the model's name with
|
| 78 |
+
[`~transformers.AutoTokenizer.from_pretrained`].
|
| 79 |
+
callbacks (`list[~transformers.TrainerCallback]`, *optional*):
|
| 80 |
+
List of callbacks to customize the training loop.
|
| 81 |
+
optimizers (`tuple[~torch.optim.Optimizer, ~torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`):
|
| 82 |
+
Tuple containing the optimizer and the learning rate scheduler.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
_tag_names = ["trl", "a2po"]
|
| 86 |
+
_name = "A2PO"
|
| 87 |
+
_paper = {
|
| 88 |
+
"title": "Accelerating RL for LLM Reasoning with Optimal Advantage Regression",
|
| 89 |
+
"id": "2505.20686",
|
| 90 |
+
# docstyle-ignore
|
| 91 |
+
"citation": textwrap.dedent("""\
|
| 92 |
+
@article{brantley2025accelerating,
|
| 93 |
+
title = {{Accelerating RL for LLM Reasoning with Optimal Advantage Regression}},
|
| 94 |
+
author = {Kiant\'e Brantley and Mingyu Chen and Zhaolin Gao and Jason D. Lee and Wen Sun and Wenhao Zhan and Xuezhou Zhang},
|
| 95 |
+
year = 2025,
|
| 96 |
+
eprint = {arXiv:2505.20686},
|
| 97 |
+
}"""),
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
def __init__(
|
| 101 |
+
self,
|
| 102 |
+
model: PreTrainedModel | str,
|
| 103 |
+
reward_funcs: RewardFunc | list[RewardFunc],
|
| 104 |
+
args: A2POConfig | None = None,
|
| 105 |
+
train_dataset=None,
|
| 106 |
+
eval_dataset=None,
|
| 107 |
+
processing_class: PreTrainedTokenizerBase | None = None,
|
| 108 |
+
callbacks=None,
|
| 109 |
+
optimizers=(None, None),
|
| 110 |
+
):
|
| 111 |
+
# Args
|
| 112 |
+
if args is None:
|
| 113 |
+
args = A2POConfig(f"{model if isinstance(model, str) else model.config._name_or_path}-A2PO")
|
| 114 |
+
|
| 115 |
+
# Models
|
| 116 |
+
if isinstance(model, str):
|
| 117 |
+
model_init_kwargs = args.model_init_kwargs or {}
|
| 118 |
+
model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 119 |
+
model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs)
|
| 120 |
+
model_id = model.config._name_or_path
|
| 121 |
+
|
| 122 |
+
# Some models (e.g. SmolVLM/Idefics3) don't support the `logits_to_keep` argument and error out if we pass it.
|
| 123 |
+
# Inspect the forward method so Stage 2 can pass the argument only when it is supported.
|
| 124 |
+
self.model_kwarg_keys = inspect.signature(model.forward).parameters.keys()
|
| 125 |
+
|
| 126 |
+
# Reference model: a frozen copy of the initial policy. Stage 1 samples from it and Stage 2 regularizes to it.
|
| 127 |
+
self.ref_model = create_reference_model(model)
|
| 128 |
+
|
| 129 |
+
# Processing class
|
| 130 |
+
if processing_class is None:
|
| 131 |
+
processing_class = AutoTokenizer.from_pretrained(
|
| 132 |
+
model_id, padding_side="left", trust_remote_code=args.trust_remote_code
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# Reward functions
|
| 136 |
+
if not isinstance(reward_funcs, list):
|
| 137 |
+
reward_funcs = [reward_funcs]
|
| 138 |
+
self.reward_funcs = reward_funcs
|
| 139 |
+
if args.reward_weights is None:
|
| 140 |
+
self.reward_weights = torch.ones(len(reward_funcs), dtype=torch.float32)
|
| 141 |
+
else:
|
| 142 |
+
self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32)
|
| 143 |
+
|
| 144 |
+
# Generation: N samples per prompt in Stage 1, a single sample in Stage 2
|
| 145 |
+
self.value_generation_config = GenerationConfig(
|
| 146 |
+
max_new_tokens=args.max_completion_length,
|
| 147 |
+
do_sample=True,
|
| 148 |
+
temperature=args.temperature,
|
| 149 |
+
top_p=args.top_p,
|
| 150 |
+
top_k=args.top_k,
|
| 151 |
+
num_return_sequences=args.num_value_samples,
|
| 152 |
+
pad_token_id=processing_class.pad_token_id,
|
| 153 |
+
)
|
| 154 |
+
self.generation_config = GenerationConfig(
|
| 155 |
+
max_new_tokens=args.max_completion_length,
|
| 156 |
+
do_sample=True,
|
| 157 |
+
temperature=args.temperature,
|
| 158 |
+
top_p=args.top_p,
|
| 159 |
+
top_k=args.top_k,
|
| 160 |
+
num_return_sequences=1,
|
| 161 |
+
pad_token_id=processing_class.pad_token_id,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
# Optimal values V*(x), keyed by prompt text. Populated lazily by Stage 1 at the start of training.
|
| 165 |
+
self._optimal_values: dict[str, float] | None = None
|
| 166 |
+
|
| 167 |
+
# Metrics
|
| 168 |
+
self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
|
| 169 |
+
|
| 170 |
+
# The data collator returns the list of features untouched; generation happens in `_prepare_inputs`.
|
| 171 |
+
def data_collator(features):
|
| 172 |
+
return features
|
| 173 |
+
|
| 174 |
+
super().__init__(
|
| 175 |
+
model=model,
|
| 176 |
+
args=args,
|
| 177 |
+
data_collator=data_collator,
|
| 178 |
+
train_dataset=train_dataset,
|
| 179 |
+
eval_dataset=eval_dataset,
|
| 180 |
+
processing_class=processing_class,
|
| 181 |
+
callbacks=callbacks,
|
| 182 |
+
optimizers=optimizers,
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
|
| 186 |
+
|
| 187 |
+
def _calculate_rewards(self, prompts, completions, **reward_kwargs):
|
| 188 |
+
device = self.accelerator.device
|
| 189 |
+
rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device)
|
| 190 |
+
for i, reward_func in enumerate(self.reward_funcs):
|
| 191 |
+
output = reward_func(prompts=prompts, completions=completions, **reward_kwargs)
|
| 192 |
+
rewards_per_func[:, i] = torch.tensor(output, dtype=torch.float32, device=device)
|
| 193 |
+
# A*-PO assumes the (weighted) total reward is binary in {0, 1}.
|
| 194 |
+
return (rewards_per_func * self.reward_weights.to(device)).sum(dim=1)
|
| 195 |
+
|
| 196 |
+
def _get_sequence_logps(self, model, input_ids, attention_mask, logits_to_keep):
|
| 197 |
+
model_inputs = {"input_ids": input_ids, "attention_mask": attention_mask}
|
| 198 |
+
# Only pass `logits_to_keep` when the model supports it (some models and VLMs don't).
|
| 199 |
+
if "logits_to_keep" in self.model_kwarg_keys:
|
| 200 |
+
# We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded
|
| 201 |
+
model_inputs["logits_to_keep"] = logits_to_keep + 1
|
| 202 |
+
logits = model(**model_inputs).logits
|
| 203 |
+
logits = logits[:, :-1, :] # the last logit predicts beyond the sequence
|
| 204 |
+
# Only keep the last logits_to_keep. For models that support logits_to_keep, this is a no-op.
|
| 205 |
+
logits = logits[:, -logits_to_keep:, :]
|
| 206 |
+
completion_ids = input_ids[:, -logits_to_keep:]
|
| 207 |
+
per_token_logps = selective_log_softmax(logits, completion_ids)
|
| 208 |
+
completion_mask = attention_mask[:, -logits_to_keep:]
|
| 209 |
+
return (per_token_logps * completion_mask).sum(dim=1)
|
| 210 |
+
|
| 211 |
+
# Stage 1: offline optimal value estimation
|
| 212 |
+
def _estimate_optimal_values(self):
|
| 213 |
+
beta1 = self.args.beta1
|
| 214 |
+
n = self.args.num_value_samples
|
| 215 |
+
optimal_values = {}
|
| 216 |
+
all_incorrect = set()
|
| 217 |
+
|
| 218 |
+
# Stage 2 looks up V* for every prompt it scores, including eval prompts, so estimate over both datasets.
|
| 219 |
+
datasets = [self.train_dataset] if self.eval_dataset is None else [self.train_dataset, self.eval_dataset]
|
| 220 |
+
for dataset in datasets:
|
| 221 |
+
dataloader = self.accelerator.prepare(
|
| 222 |
+
DataLoader(dataset, batch_size=self.args.per_device_train_batch_size, collate_fn=list)
|
| 223 |
+
)
|
| 224 |
+
for batch in dataloader:
|
| 225 |
+
prompts = [example["prompt"] for example in batch]
|
| 226 |
+
prompts_text = [
|
| 227 |
+
maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in batch
|
| 228 |
+
]
|
| 229 |
+
|
| 230 |
+
# Sample N completions per prompt from the reference policy
|
| 231 |
+
inputs = self.processing_class(
|
| 232 |
+
prompts_text,
|
| 233 |
+
return_tensors="pt",
|
| 234 |
+
padding=True,
|
| 235 |
+
truncation=True,
|
| 236 |
+
max_length=self.args.max_prompt_length,
|
| 237 |
+
add_special_tokens=False,
|
| 238 |
+
).to(self.accelerator.device)
|
| 239 |
+
with unwrap_model_for_generation(self.ref_model, self.accelerator) as ref_model:
|
| 240 |
+
completion_ids = ref_model.generate(**inputs, generation_config=self.value_generation_config)
|
| 241 |
+
|
| 242 |
+
prompt_length = inputs["input_ids"].size(1)
|
| 243 |
+
completions_text = self.processing_class.batch_decode(
|
| 244 |
+
completion_ids[:, prompt_length:], skip_special_tokens=True
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
# Each prompt is repeated N times by `num_return_sequences`. Forward any extra dataset columns (e.g.
|
| 248 |
+
# "solution") to the reward functions, repeated to align with the N samples per prompt.
|
| 249 |
+
keys = [key for key in batch[0] if key not in ["prompt", "completion"]]
|
| 250 |
+
reward_kwargs = {key: [example[key] for example in batch for _ in range(n)] for key in keys}
|
| 251 |
+
repeated_prompts = [p for p in prompts for _ in range(n)]
|
| 252 |
+
rewards = self._calculate_rewards(repeated_prompts, completions_text, **reward_kwargs)
|
| 253 |
+
rewards = rewards.view(len(prompts), n)
|
| 254 |
+
|
| 255 |
+
# V*(x) = beta1 * log(mean_i exp(r_i / beta1)), computed stably
|
| 256 |
+
v_star = beta1 * (torch.logsumexp(rewards / beta1, dim=1) - math.log(n))
|
| 257 |
+
|
| 258 |
+
for j, prompt_text in enumerate(prompts_text):
|
| 259 |
+
optimal_values[prompt_text] = v_star[j].item()
|
| 260 |
+
if rewards[j].sum() == 0:
|
| 261 |
+
all_incorrect.add(prompt_text)
|
| 262 |
+
|
| 263 |
+
# Each rank estimates V* for its shard of prompts; share them so any rank can score any prompt.
|
| 264 |
+
# `gather_object` concatenates the per-rank lists, so pass flat lists and rebuild on every rank.
|
| 265 |
+
self._optimal_values = dict(gather_object(list(optimal_values.items())))
|
| 266 |
+
all_incorrect = set(gather_object(list(all_incorrect)))
|
| 267 |
+
|
| 268 |
+
# Drop training prompts whose reference samples all scored zero (no learning signal). Eval prompts are kept
|
| 269 |
+
# so evaluation can still look up their V*.
|
| 270 |
+
if self.args.filter_all_incorrect:
|
| 271 |
+
self.train_dataset = self.train_dataset.filter(
|
| 272 |
+
lambda example: maybe_apply_chat_template(example, self.processing_class)["prompt"]
|
| 273 |
+
not in all_incorrect
|
| 274 |
+
)
|
| 275 |
+
logger.info(f"Stage 1 complete: estimated V* for {len(self._optimal_values)} prompts.")
|
| 276 |
+
|
| 277 |
+
# Stage 2: on-policy regression
|
| 278 |
+
def _prepare_inputs(self, inputs):
|
| 279 |
+
# Estimate V* on first use, e.g. when `evaluate()` is called without a preceding `train()`.
|
| 280 |
+
if self._optimal_values is None:
|
| 281 |
+
self._estimate_optimal_values()
|
| 282 |
+
mode = "train" if self.model.training else "eval"
|
| 283 |
+
device = self.accelerator.device
|
| 284 |
+
prompts = [example["prompt"] for example in inputs]
|
| 285 |
+
prompts_text = [maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in inputs]
|
| 286 |
+
|
| 287 |
+
# One on-policy completion per prompt
|
| 288 |
+
prompt_inputs = self.processing_class(
|
| 289 |
+
prompts_text,
|
| 290 |
+
return_tensors="pt",
|
| 291 |
+
padding=True,
|
| 292 |
+
truncation=True,
|
| 293 |
+
max_length=self.args.max_prompt_length,
|
| 294 |
+
add_special_tokens=False,
|
| 295 |
+
).to(device)
|
| 296 |
+
with unwrap_model_for_generation(self.model, self.accelerator) as unwrapped_model:
|
| 297 |
+
prompt_completion_ids = unwrapped_model.generate(**prompt_inputs, generation_config=self.generation_config)
|
| 298 |
+
prompt_length = prompt_inputs["input_ids"].size(1)
|
| 299 |
+
completion_ids = prompt_completion_ids[:, prompt_length:]
|
| 300 |
+
completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
|
| 301 |
+
|
| 302 |
+
# Scalar (binary) reward and cached optimal value. Forward extra dataset columns to the reward functions.
|
| 303 |
+
keys = [key for key in inputs[0] if key not in ["prompt", "completion"]]
|
| 304 |
+
reward_kwargs = {key: [example[key] for example in inputs] for key in keys}
|
| 305 |
+
rewards = self._calculate_rewards(prompts, completions_text, **reward_kwargs)
|
| 306 |
+
v_star = torch.tensor([self._optimal_values[p] for p in prompts_text], dtype=torch.float32, device=device)
|
| 307 |
+
|
| 308 |
+
# Attention mask: the tokenizer's prompt mask followed by the completion mask. The completion mask is 1 up to
|
| 309 |
+
# and including the first EOS and 0 afterwards, so the terminal EOS stays in the log-prob sum (a plain
|
| 310 |
+
# `!= pad_token_id` mask would drop it when `pad_token == eos_token`).
|
| 311 |
+
is_eos = completion_ids == self.processing_class.eos_token_id
|
| 312 |
+
eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device)
|
| 313 |
+
eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)]
|
| 314 |
+
sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1)
|
| 315 |
+
completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int()
|
| 316 |
+
attention_mask = torch.cat([prompt_inputs["attention_mask"], completion_mask], dim=1)
|
| 317 |
+
logits_to_keep = completion_ids.size(1)
|
| 318 |
+
|
| 319 |
+
with torch.no_grad():
|
| 320 |
+
ref_logps = self._get_sequence_logps(self.ref_model, prompt_completion_ids, attention_mask, logits_to_keep)
|
| 321 |
+
|
| 322 |
+
self._metrics[mode]["reward"].append(rewards.mean().item())
|
| 323 |
+
self._metrics[mode]["v_star"].append(v_star.mean().item())
|
| 324 |
+
|
| 325 |
+
return {
|
| 326 |
+
"input_ids": prompt_completion_ids,
|
| 327 |
+
"attention_mask": attention_mask,
|
| 328 |
+
"logits_to_keep": logits_to_keep,
|
| 329 |
+
"ref_logps": ref_logps,
|
| 330 |
+
"rewards": rewards,
|
| 331 |
+
"v_star": v_star,
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
|
| 335 |
+
mode = "train" if self.model.training else "eval"
|
| 336 |
+
|
| 337 |
+
policy_logps = self._get_sequence_logps(
|
| 338 |
+
model, inputs["input_ids"], inputs["attention_mask"], inputs["logits_to_keep"]
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
# Implicit reward beta2 * log(pi / pi_ref), regressed onto the optimal advantage r - V*
|
| 342 |
+
implicit_reward = self.args.beta2 * (policy_logps - inputs["ref_logps"])
|
| 343 |
+
target = inputs["rewards"] - inputs["v_star"]
|
| 344 |
+
loss = ((implicit_reward - target) ** 2).mean()
|
| 345 |
+
|
| 346 |
+
self._metrics[mode]["implicit_reward"].append(implicit_reward.mean().item())
|
| 347 |
+
self._metrics[mode]["advantage"].append(target.mean().item())
|
| 348 |
+
return loss
|
| 349 |
+
|
| 350 |
+
def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None):
|
| 351 |
+
inputs = self._prepare_inputs(inputs)
|
| 352 |
+
with torch.no_grad():
|
| 353 |
+
with self.compute_loss_context_manager():
|
| 354 |
+
loss = self.compute_loss(model, inputs)
|
| 355 |
+
loss = loss.mean().detach()
|
| 356 |
+
return loss, None, None
|
| 357 |
+
|
| 358 |
+
def train(self, *args, **kwargs):
|
| 359 |
+
if self._optimal_values is None:
|
| 360 |
+
logger.info("Running Stage 1: offline optimal value estimation...")
|
| 361 |
+
self._estimate_optimal_values()
|
| 362 |
+
return super().train(*args, **kwargs)
|
| 363 |
+
|
| 364 |
+
def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
|
| 365 |
+
mode = "train" if self.model.training else "eval"
|
| 366 |
+
metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()}
|
| 367 |
+
|
| 368 |
+
# This method can be called both in training and evaluation. When called in evaluation, the keys in `logs`
|
| 369 |
+
# start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format.
|
| 370 |
+
if mode == "eval":
|
| 371 |
+
metrics = {f"eval_{key}": val for key, val in metrics.items()}
|
| 372 |
+
|
| 373 |
+
logs = {**logs, **metrics}
|
| 374 |
+
super().log(logs, start_time)
|
| 375 |
+
self._metrics[mode].clear()
|
tasks/tasksmith-b71e9e0a47b6/environment/source/trl/experimental/async_grpo/__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 .async_grpo_config import AsyncGRPOConfig
|
| 16 |
+
from .async_grpo_trainer import AsyncGRPOTrainer
|
tasks/tasksmith-b71e9e0a47b6/environment/source/trl/experimental/async_grpo/async_grpo_config.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
from ...trainer.base_config import _BaseConfig
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class AsyncGRPOConfig(_BaseConfig):
|
| 23 |
+
# docstyle-ignore
|
| 24 |
+
r"""
|
| 25 |
+
Configuration class for the [`AsyncGRPOTrainer`].
|
| 26 |
+
|
| 27 |
+
This class includes only the parameters that are specific to asynchronous GRPO training. For a full list of
|
| 28 |
+
training arguments, please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values
|
| 29 |
+
in this class may differ from those in [`~transformers.TrainingArguments`].
|
| 30 |
+
|
| 31 |
+
Parameters:
|
| 32 |
+
> Parameters that control the model
|
| 33 |
+
|
| 34 |
+
model_init_kwargs (`dict[str, Any]` or `str`, *optional*):
|
| 35 |
+
Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when instantiating the
|
| 36 |
+
model from a path.
|
| 37 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 38 |
+
Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to
|
| 39 |
+
[`~transformers.AutoModelForCausalLM.from_pretrained`] and [`~transformers.AutoTokenizer.from_pretrained`].
|
| 40 |
+
router_aux_loss_coef (`float`, *optional*, defaults to `0.001`):
|
| 41 |
+
Coefficient of the load-balancing auxiliary loss. Only has an effect when training a Mixture-of-Experts
|
| 42 |
+
(MoE) model; for other models it does nothing. The auxiliary loss is added to the training loss with this
|
| 43 |
+
weight. Set to `0.0` to disable it.
|
| 44 |
+
|
| 45 |
+
> Parameters that control generation
|
| 46 |
+
|
| 47 |
+
num_generations (`int`, *optional*, defaults to `8`):
|
| 48 |
+
Number of generations per prompt to sample.
|
| 49 |
+
max_completion_length (`int`, *optional*, defaults to `2048`):
|
| 50 |
+
Maximum number of tokens to generate per completion.
|
| 51 |
+
temperature (`float`, *optional*, defaults to `1.0`):
|
| 52 |
+
Temperature for sampling. The higher the temperature, the more random the completions.
|
| 53 |
+
chat_template_kwargs (`dict[str, Any]`, *optional*):
|
| 54 |
+
Additional keyword arguments to pass to the `apply_chat_template` function when generating completions.
|
| 55 |
+
max_tool_calling_iterations (`int`, *optional*):
|
| 56 |
+
Maximum number of tool-calling turns when training an agent. If `None`, there is no limit and generation
|
| 57 |
+
stops when the model generates a response turn with no tool calls or when the total response length reaches
|
| 58 |
+
`max_completion_length`.
|
| 59 |
+
|
| 60 |
+
> Parameters that control the vLLM server
|
| 61 |
+
|
| 62 |
+
vllm_server_base_url (`str`, *optional*, defaults to `"http://localhost:8000"`):
|
| 63 |
+
Base URL of the vLLM server used for generation (e.g., `"http://localhost:8000"`).
|
| 64 |
+
vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
|
| 65 |
+
Total timeout duration in seconds to wait for the vLLM server to be ready.
|
| 66 |
+
request_timeout (`int`, *optional*, defaults to `600`):
|
| 67 |
+
Timeout in seconds for individual HTTP requests to the vLLM server.
|
| 68 |
+
|
| 69 |
+
> Parameters that control the training
|
| 70 |
+
|
| 71 |
+
epsilon (`float`, *optional*, defaults to `0.2`):
|
| 72 |
+
Epsilon value for clipping.
|
| 73 |
+
epsilon_high (`float`, *optional*):
|
| 74 |
+
Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the lower-bound
|
| 75 |
+
specified in argument `epsilon`. Paper [DAPO](https://huggingface.co/papers/2503.14476) recommends `0.28`.
|
| 76 |
+
|
| 77 |
+
> Parameters that control the async rollout pipeline
|
| 78 |
+
|
| 79 |
+
max_inflight_tasks (`int`, *optional*, defaults to `-1`):
|
| 80 |
+
Maximum number of concurrent generation tasks sent to the vLLM server. Defaults to `-1` (auto), which
|
| 81 |
+
sets it to `max_staleness * per_device_train_batch_size * gradient_accumulation_steps * num_processes`.
|
| 82 |
+
If using tool-use environments, you may want to set this manually based on how many parallel environments
|
| 83 |
+
you can run.
|
| 84 |
+
max_staleness (`int`, *optional*, defaults to `4`):
|
| 85 |
+
Maximum number of weight update steps a rollout sample can lag behind the current model version before
|
| 86 |
+
being discarded.
|
| 87 |
+
queue_maxsize (`int`, *optional*, defaults to `1024`):
|
| 88 |
+
Maximum number of rollout samples to buffer in the rollout queue.
|
| 89 |
+
weight_sync_steps (`int`, *optional*, defaults to `1`):
|
| 90 |
+
Number of training steps between weight synchronizations to the vLLM server.
|
| 91 |
+
heartbeat_stale_after_s (`float`, *optional*, defaults to `300.0`):
|
| 92 |
+
Seconds since the rollout worker's last heartbeat after which the trainer treats it as
|
| 93 |
+
hung and aborts.
|
| 94 |
+
|
| 95 |
+
> Parameters that control the logging
|
| 96 |
+
|
| 97 |
+
log_completions (`bool`, *optional*, defaults to `False`):
|
| 98 |
+
Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps.
|
| 99 |
+
num_completions_to_print (`int`, *optional*):
|
| 100 |
+
Number of completions to print with `rich`. If `None`, all completions are logged.
|
| 101 |
+
|
| 102 |
+
> [!NOTE]
|
| 103 |
+
> These parameters have default values different from [`~transformers.TrainingArguments`]:
|
| 104 |
+
> - `logging_steps`: Defaults to `1` instead of `500`.
|
| 105 |
+
> - `gradient_checkpointing`: Defaults to `True` instead of `False`.
|
| 106 |
+
> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
|
| 107 |
+
> - `learning_rate`: Defaults to `1e-6` instead of `5e-5`.
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
_VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"]
|
| 111 |
+
|
| 112 |
+
# Parameters that control the model
|
| 113 |
+
model_init_kwargs: dict[str, Any] | str | None = field(
|
| 114 |
+
default=None,
|
| 115 |
+
metadata={
|
| 116 |
+
"help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when instantiating "
|
| 117 |
+
"the model from a path."
|
| 118 |
+
},
|
| 119 |
+
)
|
| 120 |
+
trust_remote_code: bool = field(
|
| 121 |
+
default=False,
|
| 122 |
+
metadata={
|
| 123 |
+
"help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. "
|
| 124 |
+
"Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoTokenizer.from_pretrained`."
|
| 125 |
+
},
|
| 126 |
+
)
|
| 127 |
+
router_aux_loss_coef: float = field(
|
| 128 |
+
default=0.001,
|
| 129 |
+
metadata={
|
| 130 |
+
"help": "Coefficient of the load-balancing auxiliary loss. Only has an effect when training a "
|
| 131 |
+
"Mixture-of-Experts (MoE) model; for other models it does nothing. The auxiliary loss is added to the "
|
| 132 |
+
"training loss with this weight. Set to `0.0` to disable it."
|
| 133 |
+
},
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
# Parameters whose default values are overridden from TrainingArguments
|
| 137 |
+
learning_rate: float = field(
|
| 138 |
+
default=1e-6,
|
| 139 |
+
metadata={"help": "The initial learning rate for AdamW."},
|
| 140 |
+
)
|
| 141 |
+
logging_steps: float = field(
|
| 142 |
+
default=1,
|
| 143 |
+
metadata={
|
| 144 |
+
"help": "Log every X update steps. Should be an integer or a float in range `[0,1)`. If smaller than 1, "
|
| 145 |
+
"will be interpreted as ratio of total training steps."
|
| 146 |
+
},
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# Parameters that control generation
|
| 150 |
+
num_generations: int = field(
|
| 151 |
+
default=8,
|
| 152 |
+
metadata={"help": "Number of generations per prompt to sample."},
|
| 153 |
+
)
|
| 154 |
+
max_completion_length: int = field(
|
| 155 |
+
default=2048,
|
| 156 |
+
metadata={"help": "Maximum number of tokens to generate per completion."},
|
| 157 |
+
)
|
| 158 |
+
temperature: float = field(
|
| 159 |
+
default=1.0,
|
| 160 |
+
metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."},
|
| 161 |
+
)
|
| 162 |
+
chat_template_kwargs: dict | None = field(
|
| 163 |
+
default=None,
|
| 164 |
+
metadata={
|
| 165 |
+
"help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating "
|
| 166 |
+
"completions."
|
| 167 |
+
},
|
| 168 |
+
)
|
| 169 |
+
max_tool_calling_iterations: int | None = field(
|
| 170 |
+
default=None,
|
| 171 |
+
metadata={
|
| 172 |
+
"help": "Maximum number of tool-calling turns when training an agent. If `None`, there is no limit and "
|
| 173 |
+
"generation stops when the model generates a response turn with no tool calls or when the total response "
|
| 174 |
+
"length reaches `max_completion_length`."
|
| 175 |
+
},
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# Parameters that control the vLLM server
|
| 179 |
+
vllm_server_base_url: str = field(
|
| 180 |
+
default="http://localhost:8000",
|
| 181 |
+
metadata={"help": "Base URL of the vLLM server used for generation (e.g., 'http://localhost:8000')."},
|
| 182 |
+
)
|
| 183 |
+
vllm_server_timeout: float = field(
|
| 184 |
+
default=240.0,
|
| 185 |
+
metadata={
|
| 186 |
+
"help": "Total timeout duration in seconds to wait for the vLLM server to be ready. If the server is not "
|
| 187 |
+
"up after the timeout, a `TimeoutError` is raised."
|
| 188 |
+
},
|
| 189 |
+
)
|
| 190 |
+
request_timeout: int = field(
|
| 191 |
+
default=600,
|
| 192 |
+
metadata={"help": "Timeout in seconds for individual HTTP requests to the vLLM server."},
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# Parameters that control the training
|
| 196 |
+
epsilon: float = field(
|
| 197 |
+
default=0.2,
|
| 198 |
+
metadata={"help": "Epsilon value for clipping."},
|
| 199 |
+
)
|
| 200 |
+
epsilon_high: float | None = field(
|
| 201 |
+
default=None,
|
| 202 |
+
metadata={
|
| 203 |
+
"help": "Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the "
|
| 204 |
+
"lower-bound specified in argument `epsilon`. Paper DAPO recommends `0.28`."
|
| 205 |
+
},
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
# Parameters that control the async rollout pipeline
|
| 209 |
+
max_inflight_tasks: int = field(
|
| 210 |
+
default=-1,
|
| 211 |
+
metadata={
|
| 212 |
+
"help": "Maximum number of concurrent generation tasks sent to the vLLM server. Defaults to -1 (auto), "
|
| 213 |
+
"which sets it to `max_staleness * per_device_train_batch_size * gradient_accumulation_steps * "
|
| 214 |
+
"num_processes`. Generating more samples than this is wasteful since they will be discarded as stale "
|
| 215 |
+
"before the trainer can consume them. If using tool-use environments, you may want to set this manually "
|
| 216 |
+
"based on how many parallel environments you can run."
|
| 217 |
+
},
|
| 218 |
+
)
|
| 219 |
+
max_staleness: int = field(
|
| 220 |
+
default=4,
|
| 221 |
+
metadata={
|
| 222 |
+
"help": "Maximum number of weight update steps a rollout sample can lag behind the current model version "
|
| 223 |
+
"before being discarded."
|
| 224 |
+
},
|
| 225 |
+
)
|
| 226 |
+
queue_maxsize: int = field(
|
| 227 |
+
default=1024,
|
| 228 |
+
metadata={"help": "Maximum number of rollout samples to buffer in the rollout queue."},
|
| 229 |
+
)
|
| 230 |
+
weight_sync_steps: int = field(
|
| 231 |
+
default=1,
|
| 232 |
+
metadata={"help": "Number of training steps between weight synchronizations to the vLLM server."},
|
| 233 |
+
)
|
| 234 |
+
heartbeat_stale_after_s: float = field(
|
| 235 |
+
default=300.0,
|
| 236 |
+
metadata={
|
| 237 |
+
"help": "Seconds since the rollout worker's last heartbeat after which the trainer treats it as hung "
|
| 238 |
+
"and aborts."
|
| 239 |
+
},
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# Parameters that control the logging
|
| 243 |
+
log_completions: bool = field(
|
| 244 |
+
default=False,
|
| 245 |
+
metadata={
|
| 246 |
+
"help": "Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is "
|
| 247 |
+
"installed, it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`."
|
| 248 |
+
},
|
| 249 |
+
)
|
| 250 |
+
num_completions_to_print: int | None = field(
|
| 251 |
+
default=None,
|
| 252 |
+
metadata={"help": "Number of completions to print with `rich`. If `None`, all completions are logged."},
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
def __post_init__(self):
|
| 256 |
+
super().__post_init__()
|
| 257 |
+
|
| 258 |
+
# Accelerator config: required for the async IterableDataset-backed dataloader to work correctly.
|
| 259 |
+
# split_batches=True and dispatch_batches=True ensure that the main process drives the dataloader
|
| 260 |
+
# and batches are broadcast to other processes rather than each process pulling independently.
|
| 261 |
+
if not hasattr(self, "accelerator_config") or self.accelerator_config is None:
|
| 262 |
+
self.accelerator_config = {"split_batches": True, "dispatch_batches": True}
|
| 263 |
+
elif isinstance(self.accelerator_config, dict):
|
| 264 |
+
self.accelerator_config["split_batches"] = True
|
| 265 |
+
self.accelerator_config["dispatch_batches"] = True
|
| 266 |
+
else:
|
| 267 |
+
self.accelerator_config.split_batches = True
|
| 268 |
+
self.accelerator_config.dispatch_batches = True
|
tasks/tasksmith-b71e9e0a47b6/environment/source/trl/experimental/async_grpo/async_grpo_trainer.py
ADDED
|
@@ -0,0 +1,780 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
import queue
|
| 18 |
+
import textwrap
|
| 19 |
+
import time
|
| 20 |
+
from collections import defaultdict
|
| 21 |
+
from collections.abc import Callable
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import Any, Protocol
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
from accelerate.logging import get_logger
|
| 27 |
+
from datasets import Dataset, IterableDataset
|
| 28 |
+
from torch.distributed._tensor import DTensor
|
| 29 |
+
from torch.utils.data import DataLoader
|
| 30 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerBase, TrainerCallback
|
| 31 |
+
from transformers.data.data_collator import DataCollatorMixin
|
| 32 |
+
|
| 33 |
+
from ...trainer.base_trainer import _BaseTrainer
|
| 34 |
+
from ...trainer.utils import pad, patch_chunked_lm_head
|
| 35 |
+
from .async_grpo_config import AsyncGRPOConfig
|
| 36 |
+
from .async_rollout_worker import AsyncRolloutWorker
|
| 37 |
+
from .weight_transfer import WeightTransferClient
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
# A reward function is a callable that returns a list of floats (the rewards). The callable receives prompts,
|
| 43 |
+
# completions, and additional arguments from the trainer (refer to the trainer's source for details). To ensure forward
|
| 44 |
+
# compatibility, it should accept **kwargs.
|
| 45 |
+
RewardFunc = Callable[..., list[float]]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class _SupportsReset(Protocol):
|
| 49 |
+
def reset(self, **kwargs) -> str | None: ...
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
EnvironmentFactory = Callable[[], _SupportsReset]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class RolloutWorkerProtocol(Protocol):
|
| 56 |
+
"""Interface a rollout worker must implement to be passed as `rollout_worker` to [`AsyncGRPOTrainer`].
|
| 57 |
+
|
| 58 |
+
The default [`AsyncRolloutWorker`] spawns a CUDA-free child process and scores completions with the trainer's
|
| 59 |
+
`reward_funcs`. Implement this protocol to plug in a custom rollout/scoring backend instead — for example, one that
|
| 60 |
+
runs reward models on their own GPUs.
|
| 61 |
+
|
| 62 |
+
Attributes:
|
| 63 |
+
rollout_buffer (`queue.Queue`):
|
| 64 |
+
Queue the trainer drains; the worker pushes scored `RolloutSample`s onto it.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
rollout_buffer: queue.Queue
|
| 68 |
+
|
| 69 |
+
def start(self) -> None:
|
| 70 |
+
"""Begin producing rollouts. Called once on train begin, after the initial weight sync."""
|
| 71 |
+
...
|
| 72 |
+
|
| 73 |
+
def stop(self) -> None:
|
| 74 |
+
"""Stop the worker and release its resources. Called on train end."""
|
| 75 |
+
...
|
| 76 |
+
|
| 77 |
+
def update_model_version(self, version: int) -> None:
|
| 78 |
+
"""Tell the worker which policy version is now live, so it can tag or discard stale samples."""
|
| 79 |
+
...
|
| 80 |
+
|
| 81 |
+
def check_health(self, stale_after_s: float) -> None:
|
| 82 |
+
"""Raise if the worker has crashed or stopped producing within `stale_after_s` seconds."""
|
| 83 |
+
...
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class StepIntervalCallback(TrainerCallback):
|
| 87 |
+
"""
|
| 88 |
+
A callback that calls a function every N optimization steps.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
def __init__(self, fn, every_n_steps: int):
|
| 92 |
+
self.fn = fn
|
| 93 |
+
self.every_n_steps = every_n_steps
|
| 94 |
+
|
| 95 |
+
def on_step_end(self, _args, state, _control, **_kwargs):
|
| 96 |
+
if state.global_step % self.every_n_steps == 0:
|
| 97 |
+
self.fn()
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class _InitialWeightSyncCallback(TrainerCallback):
|
| 101 |
+
"""Idempotent: NCCL group setup + cold weight sync to vLLM on train begin."""
|
| 102 |
+
|
| 103 |
+
def __init__(self, trainer: "AsyncGRPOTrainer"):
|
| 104 |
+
self._trainer = trainer
|
| 105 |
+
self._fired = False
|
| 106 |
+
|
| 107 |
+
def on_train_begin(self, _args, _state, _control, **_kwargs):
|
| 108 |
+
if self._fired:
|
| 109 |
+
return
|
| 110 |
+
self._fired = True
|
| 111 |
+
if self._trainer.accelerator.is_main_process and self._trainer.weight_transfer is not None:
|
| 112 |
+
self._trainer.weight_transfer.init_weight_transfer()
|
| 113 |
+
self._trainer._sync_weight()
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class _StartRolloutWorkerCallback(TrainerCallback):
|
| 117 |
+
"""Idempotent: starts the rollout worker. Must be registered AFTER `_InitialWeightSyncCallback`."""
|
| 118 |
+
|
| 119 |
+
def __init__(self, trainer: "AsyncGRPOTrainer"):
|
| 120 |
+
self._trainer = trainer
|
| 121 |
+
self._fired = False
|
| 122 |
+
|
| 123 |
+
def on_train_begin(self, _args, _state, _control, **_kwargs):
|
| 124 |
+
if self._fired:
|
| 125 |
+
return
|
| 126 |
+
self._fired = True
|
| 127 |
+
if self._trainer.accelerator.is_main_process and self._trainer.rollout_worker is not None:
|
| 128 |
+
self._trainer.rollout_worker.start()
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class RolloutQueueDataset(torch.utils.data.IterableDataset):
|
| 132 |
+
def __init__(
|
| 133 |
+
self,
|
| 134 |
+
rollout_queue,
|
| 135 |
+
model_version_fn,
|
| 136 |
+
check_health_fn,
|
| 137 |
+
stale_after_s,
|
| 138 |
+
max_staleness=3,
|
| 139 |
+
poll_interval_s=5.0,
|
| 140 |
+
):
|
| 141 |
+
self.queue = rollout_queue
|
| 142 |
+
self.model_version_fn = model_version_fn
|
| 143 |
+
self.check_health_fn = check_health_fn
|
| 144 |
+
self.stale_after_s = stale_after_s
|
| 145 |
+
self.max_staleness = max_staleness
|
| 146 |
+
self.poll_interval_s = poll_interval_s
|
| 147 |
+
|
| 148 |
+
def __iter__(self):
|
| 149 |
+
while True:
|
| 150 |
+
t0 = time.time()
|
| 151 |
+
if self.queue.qsize() == 0:
|
| 152 |
+
logger.info("queue empty, waiting for rollout samples...")
|
| 153 |
+
try:
|
| 154 |
+
sample = self.queue.get(timeout=self.poll_interval_s)
|
| 155 |
+
except queue.Empty:
|
| 156 |
+
# Returning here would broadcast None through accelerate's dispatch loop.
|
| 157 |
+
self.check_health_fn(self.stale_after_s)
|
| 158 |
+
continue
|
| 159 |
+
queue_wait_time_s = time.time() - t0
|
| 160 |
+
if queue_wait_time_s > 1.0:
|
| 161 |
+
logger.info(f"waited {queue_wait_time_s:.1f}s for sample (qsize={self.queue.qsize()})")
|
| 162 |
+
|
| 163 |
+
staleness = self.model_version_fn() - sample.model_version
|
| 164 |
+
if staleness > self.max_staleness:
|
| 165 |
+
logger.info(f"dropping stale sample (staleness={staleness}, max={self.max_staleness})")
|
| 166 |
+
continue # drop stale, pull next
|
| 167 |
+
|
| 168 |
+
yield {
|
| 169 |
+
"input_ids": sample.input_ids,
|
| 170 |
+
"completion_mask": sample.completion_mask,
|
| 171 |
+
"old_log_probs": sample.old_log_probs,
|
| 172 |
+
"advantage": sample.advantage,
|
| 173 |
+
"metrics": {**sample.metrics, "queue_wait_time_s": queue_wait_time_s},
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class _EmptyIterableDataset(torch.utils.data.IterableDataset):
|
| 178 |
+
"""Placeholder for non-rank-0 processes. Never actually iterated."""
|
| 179 |
+
|
| 180 |
+
def __iter__(self):
|
| 181 |
+
return iter([])
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@dataclass
|
| 185 |
+
class DataCollatorForRollout(DataCollatorMixin):
|
| 186 |
+
"""
|
| 187 |
+
Padding-free collator for rollout samples. Splits the global batch into `num_processes` groups (one per rank) and
|
| 188 |
+
concatenates each group's samples into a single packed row, with `position_ids` resetting per sequence and
|
| 189 |
+
advantages expanded per-token. Rows are padded only to the longest group, so the batch stays rectangular for
|
| 190 |
+
`DataLoaderDispatcher` to scatter row `i` -> rank `i`; this inter-rank padding is stripped per-rank in
|
| 191 |
+
`compute_loss`.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
pad_token_id (`int`):
|
| 195 |
+
Token id used to pad `input_ids`.
|
| 196 |
+
num_processes (`int`, *optional*, defaults to `1`):
|
| 197 |
+
Number of ranks; the global batch is packed into this many rows.
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
pad_token_id: int
|
| 201 |
+
num_processes: int = 1
|
| 202 |
+
return_tensors: str = "pt"
|
| 203 |
+
|
| 204 |
+
def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]:
|
| 205 |
+
groups = [examples[i :: self.num_processes] for i in range(self.num_processes)]
|
| 206 |
+
|
| 207 |
+
input_ids, attention_mask, completion_mask, old_log_probs, position_ids, advantages = [], [], [], [], [], []
|
| 208 |
+
for group in groups:
|
| 209 |
+
seq_lengths = [len(example["input_ids"]) for example in group]
|
| 210 |
+
ids = [token for example in group for token in example["input_ids"]]
|
| 211 |
+
input_ids.append(torch.tensor(ids, dtype=torch.long))
|
| 212 |
+
attention_mask.append(torch.ones(len(ids), dtype=torch.long))
|
| 213 |
+
completion_mask.append(
|
| 214 |
+
torch.tensor([m for example in group for m in example["completion_mask"]], dtype=torch.long)
|
| 215 |
+
)
|
| 216 |
+
old_log_probs.append(
|
| 217 |
+
torch.tensor([lp for example in group for lp in example["old_log_probs"]], dtype=torch.float32)
|
| 218 |
+
)
|
| 219 |
+
position_ids.append(torch.cat([torch.arange(n) for n in seq_lengths]))
|
| 220 |
+
advantages.append(
|
| 221 |
+
torch.cat(
|
| 222 |
+
[torch.full((n,), example["advantage"]) for example, n in zip(group, seq_lengths, strict=False)]
|
| 223 |
+
)
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
input_ids = pad(input_ids, padding_value=self.pad_token_id)
|
| 227 |
+
attention_mask = pad(attention_mask, padding_value=0)
|
| 228 |
+
completion_mask = pad(completion_mask, padding_value=0)
|
| 229 |
+
old_log_probs = pad(old_log_probs, padding_value=0.0)
|
| 230 |
+
position_ids = pad(position_ids, padding_value=0)
|
| 231 |
+
advantages = pad(advantages, padding_value=0.0)
|
| 232 |
+
|
| 233 |
+
# Total valid completion tokens across all samples in the full batch.
|
| 234 |
+
# Repeated per rank so that DataLoaderDispatcher (dispatch_batches=True) slices correctly on dim=0
|
| 235 |
+
global_n_tokens = sum(sum(example["completion_mask"]) for example in examples)
|
| 236 |
+
global_n_tokens = torch.full((self.num_processes,), float(global_n_tokens), dtype=torch.float32)
|
| 237 |
+
|
| 238 |
+
# Per-sample metrics grouped per rank, as a dict of 2D tensors (one row per rank) so that Accelerate's
|
| 239 |
+
# recursive broadcast (dispatch_batches=True) can scatter them — it traverses nested dicts of tensors but
|
| 240 |
+
# chokes on plain Python floats. Rows are padded with NaN so padded slots are ignored by the nan-aware
|
| 241 |
+
# aggregation in `compute_loss`.
|
| 242 |
+
metrics_list = [example["metrics"] for example in examples]
|
| 243 |
+
metrics = (
|
| 244 |
+
{
|
| 245 |
+
key: pad(
|
| 246 |
+
[
|
| 247 |
+
torch.tensor([example["metrics"].get(key, 0.0) for example in group], dtype=torch.float32)
|
| 248 |
+
for group in groups
|
| 249 |
+
],
|
| 250 |
+
padding_value=float("nan"),
|
| 251 |
+
)
|
| 252 |
+
for key in metrics_list[0]
|
| 253 |
+
}
|
| 254 |
+
if metrics_list and metrics_list[0]
|
| 255 |
+
else {}
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
return {
|
| 259 |
+
"input_ids": input_ids,
|
| 260 |
+
"attention_mask": attention_mask,
|
| 261 |
+
"completion_mask": completion_mask,
|
| 262 |
+
"old_log_probs": old_log_probs,
|
| 263 |
+
"position_ids": position_ids,
|
| 264 |
+
"advantages": advantages,
|
| 265 |
+
"global_n_tokens": global_n_tokens,
|
| 266 |
+
"metrics": metrics,
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class AsyncGRPOTrainer(_BaseTrainer):
|
| 271 |
+
"""
|
| 272 |
+
Trainer for the Group Relative Policy Optimization (GRPO) method. This algorithm was initially proposed in the
|
| 273 |
+
paper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language
|
| 274 |
+
Models](https://huggingface.co/papers/2402.03300). This trainer is the asynchronous version of GRPO, where
|
| 275 |
+
generation is offloaded to an external vLLM server that runs asynchronously alongside training, decoupling rollout
|
| 276 |
+
from the gradient update loop.
|
| 277 |
+
|
| 278 |
+
Example:
|
| 279 |
+
|
| 280 |
+
```python
|
| 281 |
+
from trl.experimental.async_grpo import AsyncGRPOTrainer
|
| 282 |
+
from trl.rewards import accuracy_reward
|
| 283 |
+
from datasets import load_dataset
|
| 284 |
+
|
| 285 |
+
dataset = load_dataset("trl-lib/DeepMath-103K", split="train")
|
| 286 |
+
|
| 287 |
+
trainer = AsyncGRPOTrainer(
|
| 288 |
+
model="Qwen/Qwen2.5-0.5B-Instruct",
|
| 289 |
+
reward_funcs=accuracy_reward,
|
| 290 |
+
train_dataset=dataset,
|
| 291 |
+
)
|
| 292 |
+
trainer.train()
|
| 293 |
+
```
|
| 294 |
+
|
| 295 |
+
Args:
|
| 296 |
+
model (`str`):
|
| 297 |
+
Model to be trained. Must be a string, being the *model id* of a pretrained model hosted inside a model
|
| 298 |
+
repo on huggingface.co, or a path to a *directory* containing model weights saved using
|
| 299 |
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
|
| 300 |
+
using [`~transformers.AutoModelForCausalLM.from_pretrained`]. The model name is also used to identify the
|
| 301 |
+
model on the vLLM server used for generation.
|
| 302 |
+
reward_funcs (`RewardFunc | list[RewardFunc]`):
|
| 303 |
+
Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
|
| 304 |
+
functions with the prompts and completions and sum the rewards. Can be either:
|
| 305 |
+
|
| 306 |
+
- A single reward function: The function is provided with the prompts and the generated completions, plus
|
| 307 |
+
any additional columns in the dataset. It should return a list of rewards. Reward functions can be either
|
| 308 |
+
synchronous or asynchronous and can also return `None` when the reward is not applicable to those
|
| 309 |
+
samples. This is useful for multi-task training where different reward functions apply to different types
|
| 310 |
+
of samples. When a reward function returns `None` for a sample, that reward function is excluded from the
|
| 311 |
+
reward calculation for that sample. For more details, see [Using a custom reward
|
| 312 |
+
function](#using-a-custom-reward-function).
|
| 313 |
+
- A list of reward functions, where each item is a reward function as described above. Rewards from all
|
| 314 |
+
functions are summed.
|
| 315 |
+
|
| 316 |
+
Unlike [`GRPOTrainer`], rewards are computed in a spawned child process, so each reward function (along
|
| 317 |
+
with `tools` and `environment_factory`) must be picklable: use a module-level function,
|
| 318 |
+
`functools.partial`, or a callable class instance — lambdas and closures will fail at startup. The child
|
| 319 |
+
process also runs with `CUDA_VISIBLE_DEVICES=""`, so a GPU-backed reward model runs on CPU (slow), not the
|
| 320 |
+
trainer's GPU.
|
| 321 |
+
args ([`AsyncGRPOConfig`], *optional*):
|
| 322 |
+
Configuration for this trainer. If `None`, a default configuration is used.
|
| 323 |
+
train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
|
| 324 |
+
Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset are
|
| 325 |
+
ignored. The format of the samples can be either:
|
| 326 |
+
|
| 327 |
+
- [Standard](dataset_formats#standard): Each sample contains plain text.
|
| 328 |
+
- [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
|
| 329 |
+
and content).
|
| 330 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*):
|
| 331 |
+
Processing class used to process the data. The padding side must be set to `"left"`. If `None`, the
|
| 332 |
+
processing class is loaded from the model's name with [`~transformers.AutoTokenizer.from_pretrained`]. A
|
| 333 |
+
padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token,
|
| 334 |
+
`tokenizer.eos_token` will be used as the default.
|
| 335 |
+
callbacks (list of [`~transformers.TrainerCallback`], *optional*):
|
| 336 |
+
List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
|
| 337 |
+
in [here](https://huggingface.co/docs/transformers/main_classes/callback).
|
| 338 |
+
|
| 339 |
+
If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
|
| 340 |
+
method.
|
| 341 |
+
optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`):
|
| 342 |
+
A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your
|
| 343 |
+
model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`.
|
| 344 |
+
tools (list of `Callable`, *optional*):
|
| 345 |
+
A list of callable tool functions (sync or async) that the model can invoke during generation. Each tool
|
| 346 |
+
should be a standard Python function with properly type-hinted arguments and return values, and a
|
| 347 |
+
Google-style docstring describing its purpose, arguments, and return value. For more details, see:
|
| 348 |
+
https://huggingface.co/docs/transformers/en/chat_extras#passing-tools. The model uses the function's name,
|
| 349 |
+
type hints, and docstring to determine how to call it. Ensure that the model's chat template supports tool
|
| 350 |
+
use and that it has been fine-tuned for tool calling.
|
| 351 |
+
environment_factory (`EnvironmentFactory`, *optional*):
|
| 352 |
+
A callable that creates and returns an environment instance. The environment class should define methods
|
| 353 |
+
that can be invoked as tools during generation. Each method should comply with the same requirements as the
|
| 354 |
+
`tools` described above. If `environment_factory` is provided, an instance of the environment is created
|
| 355 |
+
for each generation in the batch, allowing for parallel and independent interactions. The environment must
|
| 356 |
+
also implement a callable `reset` method that can be used to reset state between generations. The `reset`
|
| 357 |
+
method should return either `None` or a string: when it returns a string, that string is appended to the
|
| 358 |
+
last user message before generation. This feature is experimental and may change or be removed at any time
|
| 359 |
+
without prior notice.
|
| 360 |
+
rollout_worker (`RolloutWorkerProtocol`, *optional*):
|
| 361 |
+
Custom rollout worker implementing [`RolloutWorkerProtocol`]. If `None`, a default [`AsyncRolloutWorker`]
|
| 362 |
+
is created, which spawns a CUDA-free child process and scores completions with the trainer's
|
| 363 |
+
`reward_funcs`. Pass a custom worker to plug in a different rollout/scoring backend instead — for example,
|
| 364 |
+
one that runs reward models on their own GPUs.
|
| 365 |
+
"""
|
| 366 |
+
|
| 367 |
+
_tag_names = ["trl", "async-grpo"]
|
| 368 |
+
_name = "AsyncGRPO"
|
| 369 |
+
_paper = {
|
| 370 |
+
"title": "DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models",
|
| 371 |
+
"id": "2402.03300",
|
| 372 |
+
# docstyle-ignore
|
| 373 |
+
"citation": textwrap.dedent("""\
|
| 374 |
+
@article{shao2024deepseekmath,
|
| 375 |
+
title = {{DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models}},
|
| 376 |
+
author = {Zhihong Shao and Peiyi Wang and Qihao Zhu and Runxin Xu and Junxiao Song and Mingchuan Zhang and Y. K. Li and Y. Wu and Daya Guo},
|
| 377 |
+
year = 2024,
|
| 378 |
+
eprint = {arXiv:2402.03300},
|
| 379 |
+
}"""),
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
def __init__(
|
| 383 |
+
self,
|
| 384 |
+
model: str,
|
| 385 |
+
reward_funcs: RewardFunc | list[RewardFunc],
|
| 386 |
+
args: AsyncGRPOConfig | None = None,
|
| 387 |
+
train_dataset: Dataset | IterableDataset | None = None,
|
| 388 |
+
processing_class: PreTrainedTokenizerBase | None = None,
|
| 389 |
+
callbacks: list[TrainerCallback] | None = None,
|
| 390 |
+
optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None),
|
| 391 |
+
tools: list[Callable] | None = None,
|
| 392 |
+
environment_factory: EnvironmentFactory | None = None,
|
| 393 |
+
rollout_worker: RolloutWorkerProtocol | None = None,
|
| 394 |
+
):
|
| 395 |
+
self.args = args or AsyncGRPOConfig()
|
| 396 |
+
|
| 397 |
+
# Training arguments
|
| 398 |
+
self.epsilon_low = self.args.epsilon
|
| 399 |
+
self.epsilon_high = self.args.epsilon_high if self.args.epsilon_high is not None else self.args.epsilon
|
| 400 |
+
self.temperature = self.args.temperature
|
| 401 |
+
|
| 402 |
+
# Model
|
| 403 |
+
model_name = model
|
| 404 |
+
model_init_kwargs = self.args.model_init_kwargs or {}
|
| 405 |
+
model_init_kwargs.setdefault("trust_remote_code", self.args.trust_remote_code)
|
| 406 |
+
# FlashAttention is required: training runs in padding-free mode, where sequences are concatenated into a
|
| 407 |
+
# single row and `cu_seq_lens` are derived from `position_ids` resets. SDPA/eager can't handle this.
|
| 408 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 409 |
+
model_name,
|
| 410 |
+
device_map=None,
|
| 411 |
+
dtype=torch.float32,
|
| 412 |
+
attn_implementation="kernels-community/flash-attn3",
|
| 413 |
+
**model_init_kwargs,
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
if self.args.use_liger_kernel:
|
| 417 |
+
raise NotImplementedError("`use_liger_kernel` is not supported yet.")
|
| 418 |
+
|
| 419 |
+
# MoE load-balancing auxiliary loss, applied to Mixture-of-Experts models (no effect otherwise)
|
| 420 |
+
text_config = model.config.get_text_config()
|
| 421 |
+
is_moe = getattr(text_config, "output_router_logits", None) is not None
|
| 422 |
+
self.aux_loss_enabled = is_moe and self.args.router_aux_loss_coef != 0.0
|
| 423 |
+
self.router_aux_loss_coef = self.args.router_aux_loss_coef
|
| 424 |
+
|
| 425 |
+
patch_chunked_lm_head(
|
| 426 |
+
model, chunk_size=8192, temperature=self.temperature, output_router_logits=self.aux_loss_enabled
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
# Processing class
|
| 430 |
+
if processing_class is None:
|
| 431 |
+
processing_class = AutoTokenizer.from_pretrained(model_name, trust_remote_code=self.args.trust_remote_code)
|
| 432 |
+
if processing_class.pad_token is None:
|
| 433 |
+
processing_class.pad_token = processing_class.eos_token
|
| 434 |
+
|
| 435 |
+
# Reward functions
|
| 436 |
+
if not isinstance(reward_funcs, list):
|
| 437 |
+
reward_funcs = [reward_funcs]
|
| 438 |
+
|
| 439 |
+
# Initialize the Trainer
|
| 440 |
+
super().__init__(
|
| 441 |
+
model=model,
|
| 442 |
+
args=self.args,
|
| 443 |
+
train_dataset=train_dataset,
|
| 444 |
+
processing_class=processing_class,
|
| 445 |
+
callbacks=callbacks,
|
| 446 |
+
optimizers=optimizers,
|
| 447 |
+
compute_loss_func="non-None value to disable scaling",
|
| 448 |
+
)
|
| 449 |
+
# Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
|
| 450 |
+
# model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
|
| 451 |
+
# self.model_accepts_loss_kwargs to False to enable scaling.
|
| 452 |
+
self.model_accepts_loss_kwargs = False
|
| 453 |
+
|
| 454 |
+
# Infer max_steps from dataset size when not explicitly set. This must happen after super().__init__()
|
| 455 |
+
# so that self.accelerator.num_processes is available for the correct calculation.
|
| 456 |
+
samples_per_step = (
|
| 457 |
+
self.args.per_device_train_batch_size
|
| 458 |
+
* self.args.gradient_accumulation_steps
|
| 459 |
+
* self.accelerator.num_processes
|
| 460 |
+
)
|
| 461 |
+
if self.args.max_steps <= 0 and train_dataset is not None and hasattr(train_dataset, "__len__"):
|
| 462 |
+
samples_per_epoch = len(train_dataset) * self.args.num_generations
|
| 463 |
+
self.args.max_steps = int(self.args.num_train_epochs * samples_per_epoch / samples_per_step)
|
| 464 |
+
|
| 465 |
+
# Infer max_inflight_tasks when not explicitly set. Generating more samples than the trainer can consume
|
| 466 |
+
# before they become stale is wasteful. The useful upper bound is max_staleness * samples_per_step.
|
| 467 |
+
if self.args.max_inflight_tasks < 0:
|
| 468 |
+
self.args.max_inflight_tasks = self.args.max_staleness * samples_per_step
|
| 469 |
+
logger.info(
|
| 470 |
+
f"max_inflight_tasks set to {self.args.max_inflight_tasks} "
|
| 471 |
+
f"(max_staleness={self.args.max_staleness} × samples_per_step={samples_per_step})"
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
# Initialize the metrics
|
| 475 |
+
self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
|
| 476 |
+
self._train_tokens_start_time = None
|
| 477 |
+
self.model_version = 0
|
| 478 |
+
# Create worker and queue on rank 0
|
| 479 |
+
if self.accelerator.is_main_process:
|
| 480 |
+
if self.train_dataset is None:
|
| 481 |
+
raise ValueError("train_dataset is required for AsyncGRPOTrainer")
|
| 482 |
+
|
| 483 |
+
if rollout_worker is not None:
|
| 484 |
+
# Use the injected worker (e.g. a stub in tests). The queue is owned by the worker.
|
| 485 |
+
# Weight transfer is also expected to be wired by the test fixture (or left as None
|
| 486 |
+
# if the stub doesn't sync to a real vLLM).
|
| 487 |
+
self.rollout_worker = rollout_worker
|
| 488 |
+
self.weight_transfer = None
|
| 489 |
+
else:
|
| 490 |
+
# Collect weight metadata once — names/dtypes/shapes are fixed for the lifetime of training.
|
| 491 |
+
# DTensor.shape returns the global shape without triggering any all-gather.
|
| 492 |
+
weight_names, weight_dtype_names, weight_shapes = [], [], []
|
| 493 |
+
for name, param in model.named_parameters():
|
| 494 |
+
# DDP/FSDP1 wrapping, avoids vllm module not exist error
|
| 495 |
+
name = name.removeprefix("module.")
|
| 496 |
+
weight_names.append(name)
|
| 497 |
+
weight_dtype_names.append(str(param.dtype).split(".")[-1])
|
| 498 |
+
weight_shapes.append(list(param.shape))
|
| 499 |
+
self.weight_transfer = WeightTransferClient(
|
| 500 |
+
vllm_server_url=self.args.vllm_server_base_url,
|
| 501 |
+
server_timeout=self.args.vllm_server_timeout,
|
| 502 |
+
weight_update_info={
|
| 503 |
+
"names": weight_names,
|
| 504 |
+
"dtype_names": weight_dtype_names,
|
| 505 |
+
"shapes": weight_shapes,
|
| 506 |
+
"packed": True,
|
| 507 |
+
},
|
| 508 |
+
)
|
| 509 |
+
self.rollout_worker = AsyncRolloutWorker(
|
| 510 |
+
model_name=model_name,
|
| 511 |
+
dataset=train_dataset,
|
| 512 |
+
reward_funcs=reward_funcs,
|
| 513 |
+
processing_class=processing_class,
|
| 514 |
+
tools=tools,
|
| 515 |
+
environment_factory=environment_factory,
|
| 516 |
+
num_generations=self.args.num_generations,
|
| 517 |
+
max_inflight_tasks=self.args.max_inflight_tasks,
|
| 518 |
+
queue_maxsize=self.args.queue_maxsize,
|
| 519 |
+
vllm_server_url=self.args.vllm_server_base_url,
|
| 520 |
+
max_tokens=self.args.max_completion_length,
|
| 521 |
+
temperature=self.args.temperature,
|
| 522 |
+
request_timeout=self.args.request_timeout,
|
| 523 |
+
chat_template_kwargs=self.args.chat_template_kwargs,
|
| 524 |
+
max_tool_calling_iterations=self.args.max_tool_calling_iterations,
|
| 525 |
+
log_completions=self.args.log_completions,
|
| 526 |
+
num_completions_to_print=self.args.num_completions_to_print,
|
| 527 |
+
)
|
| 528 |
+
# TODO(@aminediro): decide if this is returned by the worker or common API that is passed to the worker later.
|
| 529 |
+
self.rollout_queue = self.rollout_worker.rollout_buffer
|
| 530 |
+
else:
|
| 531 |
+
self.rollout_queue = None
|
| 532 |
+
self.rollout_worker = None
|
| 533 |
+
self.weight_transfer = None
|
| 534 |
+
|
| 535 |
+
# Add callbacks. Registration order matters: weight sync first, then worker start.
|
| 536 |
+
self.add_callback(_InitialWeightSyncCallback(self))
|
| 537 |
+
self.add_callback(_StartRolloutWorkerCallback(self))
|
| 538 |
+
self.add_callback(StepIntervalCallback(self._sync_weight, self.args.weight_sync_steps))
|
| 539 |
+
|
| 540 |
+
def get_train_dataloader(self) -> DataLoader:
|
| 541 |
+
if self.accelerator.is_main_process:
|
| 542 |
+
dataset = RolloutQueueDataset(
|
| 543 |
+
rollout_queue=self.rollout_queue,
|
| 544 |
+
model_version_fn=lambda: self.model_version,
|
| 545 |
+
check_health_fn=self.rollout_worker.check_health,
|
| 546 |
+
stale_after_s=self.args.heartbeat_stale_after_s,
|
| 547 |
+
max_staleness=self.args.max_staleness,
|
| 548 |
+
)
|
| 549 |
+
else:
|
| 550 |
+
dataset = _EmptyIterableDataset()
|
| 551 |
+
|
| 552 |
+
return self.accelerator.prepare(
|
| 553 |
+
DataLoader(
|
| 554 |
+
dataset,
|
| 555 |
+
batch_size=self.args.per_device_train_batch_size * self.accelerator.num_processes,
|
| 556 |
+
collate_fn=DataCollatorForRollout(self.processing_class.pad_token_id, self.accelerator.num_processes),
|
| 557 |
+
num_workers=0,
|
| 558 |
+
# NOTE(@aminediro):
|
| 559 |
+
# dispatch_batches = True for DataLoader whose underlying dataset is an IterableDataset
|
| 560 |
+
# dataloader prepared by the Accelerator is only iterated through on the main process a
|
| 561 |
+
)
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
def _set_signature_columns_if_needed(self):
|
| 565 |
+
# If `self.args.remove_unused_columns` is True, non-signature columns are removed.
|
| 566 |
+
# By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids"
|
| 567 |
+
# and "attention_mask"). In AsyncGRPOTrainer, we need additional columns ("completion_mask", "old_log_probs",
|
| 568 |
+
# "advantages", "global_n_tokens") to compute the loss, hence the override.
|
| 569 |
+
if self._signature_columns is None:
|
| 570 |
+
self._signature_columns = [
|
| 571 |
+
"input_ids",
|
| 572 |
+
"attention_mask",
|
| 573 |
+
"completion_mask",
|
| 574 |
+
"old_log_probs",
|
| 575 |
+
"position_ids",
|
| 576 |
+
"advantages",
|
| 577 |
+
"global_n_tokens",
|
| 578 |
+
"metrics",
|
| 579 |
+
]
|
| 580 |
+
|
| 581 |
+
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
|
| 582 |
+
# Padding-free: the collator already packed this rank's samples into a single row (real tokens concatenated,
|
| 583 |
+
# `position_ids` resetting per sequence, advantages expanded per-token), then padded the row to the longest
|
| 584 |
+
# rank's length so DataLoaderDispatcher could scatter rectangular rows. Strip that trailing inter-rank padding
|
| 585 |
+
# here.
|
| 586 |
+
mask_bool = inputs["attention_mask"].bool()
|
| 587 |
+
input_ids = inputs["input_ids"][mask_bool].unsqueeze(0)
|
| 588 |
+
completion_mask = inputs["completion_mask"][mask_bool].unsqueeze(0)
|
| 589 |
+
old_log_probs = inputs["old_log_probs"][mask_bool].unsqueeze(0)
|
| 590 |
+
position_ids = inputs["position_ids"][mask_bool].unsqueeze(0)
|
| 591 |
+
advantages = inputs["advantages"][mask_bool].unsqueeze(0)
|
| 592 |
+
|
| 593 |
+
forward_start = time.time()
|
| 594 |
+
outputs = model(
|
| 595 |
+
input_ids=input_ids,
|
| 596 |
+
position_ids=position_ids,
|
| 597 |
+
labels=input_ids,
|
| 598 |
+
completion_mask=completion_mask,
|
| 599 |
+
use_cache=False,
|
| 600 |
+
)
|
| 601 |
+
log_probs, entropy = outputs["log_probs"], outputs["entropy"]
|
| 602 |
+
self._last_forward_time_s = time.time() - forward_start
|
| 603 |
+
|
| 604 |
+
completion_mask = completion_mask[:, 1:]
|
| 605 |
+
old_log_probs = old_log_probs[:, 1:]
|
| 606 |
+
advantages = advantages[:, 1:]
|
| 607 |
+
log_ratio = log_probs - old_log_probs
|
| 608 |
+
coef_1 = torch.exp(log_ratio)
|
| 609 |
+
coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high)
|
| 610 |
+
per_token_loss1 = coef_1 * advantages
|
| 611 |
+
per_token_loss2 = coef_2 * advantages
|
| 612 |
+
per_token_loss = -torch.min(per_token_loss1, per_token_loss2)
|
| 613 |
+
|
| 614 |
+
# DDP/FSDP averages gradients across ranks (world_size).
|
| 615 |
+
# To get correct per-token normalization we scale by 1/tokens_per_rank
|
| 616 |
+
# = world_size / global_n_tokens, so after DDP averaging the effective
|
| 617 |
+
loss = (per_token_loss * completion_mask).sum()
|
| 618 |
+
global_n_tokens = inputs["global_n_tokens"][0]
|
| 619 |
+
world_size = self.accelerator.num_processes
|
| 620 |
+
tokens_per_rank = (global_n_tokens / world_size).clamp(min=1.0)
|
| 621 |
+
loss = loss / tokens_per_rank.to(torch.float32)
|
| 622 |
+
# For DAPO, we would scale like this instead:
|
| 623 |
+
# loss = loss / max(per_token_loss.size(0), 1)
|
| 624 |
+
loss = loss / self.current_gradient_accumulation_steps
|
| 625 |
+
|
| 626 |
+
# The policy loss above is scaled for gradient accumulation (HF auto-scaling is off here), so scale aux too
|
| 627 |
+
if self.aux_loss_enabled:
|
| 628 |
+
aux_loss = outputs["aux_loss"]
|
| 629 |
+
loss = loss + self.router_aux_loss_coef * aux_loss / self.current_gradient_accumulation_steps
|
| 630 |
+
|
| 631 |
+
with torch.no_grad():
|
| 632 |
+
valid_mask = completion_mask > 0
|
| 633 |
+
local_count = valid_mask.sum().float()
|
| 634 |
+
|
| 635 |
+
local_ratio_sum = (
|
| 636 |
+
coef_1[valid_mask].sum() if valid_mask.any() else torch.zeros((), device=completion_mask.device)
|
| 637 |
+
)
|
| 638 |
+
# Approx KL: http://joschu.net/blog/kl-approx.html
|
| 639 |
+
local_kl_sum = (
|
| 640 |
+
((coef_1[valid_mask] - 1) - log_ratio[valid_mask]).sum()
|
| 641 |
+
if valid_mask.any()
|
| 642 |
+
else torch.zeros((), device=completion_mask.device)
|
| 643 |
+
)
|
| 644 |
+
|
| 645 |
+
local_entropy_sum = (
|
| 646 |
+
entropy[valid_mask].sum() if valid_mask.any() else torch.zeros((), device=completion_mask.device)
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
clipped = (coef_1 < 1 - self.epsilon_low) | (coef_1 > 1 + self.epsilon_high)
|
| 650 |
+
local_clip_sum = (
|
| 651 |
+
clipped[valid_mask].float().sum()
|
| 652 |
+
if valid_mask.any()
|
| 653 |
+
else torch.zeros((), device=completion_mask.device)
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
# Batch all-reduce: [ratio_sum, kl_sum, entropy_sum, clip_sum, count]
|
| 657 |
+
stats = torch.stack([local_ratio_sum, local_kl_sum, local_entropy_sum, local_clip_sum, local_count])
|
| 658 |
+
stats = self.accelerator.reduce(stats, reduction="sum")
|
| 659 |
+
global_ratio_sum, global_kl_sum, global_entropy_sum, global_clip_sum, global_count = stats.unbind(0)
|
| 660 |
+
self._metrics["train"]["ratio"].append((global_ratio_sum / global_count).item())
|
| 661 |
+
self._metrics["train"]["kl"].append((global_kl_sum / global_count).item())
|
| 662 |
+
self._metrics["train"]["entropy"].append((global_entropy_sum / global_count).item())
|
| 663 |
+
self._metrics["train"]["clip_ratio"].append((global_clip_sum / global_count).item())
|
| 664 |
+
|
| 665 |
+
if self.aux_loss_enabled:
|
| 666 |
+
gathered_aux = self.accelerator.reduce(aux_loss.detach().to(torch.float32), reduction="sum")
|
| 667 |
+
self._metrics["train"]["aux_loss"].append((gathered_aux / world_size).item())
|
| 668 |
+
|
| 669 |
+
# Logging metrics from the rollout worker (reward, reward_std, etc.).
|
| 670 |
+
# inputs["metrics"] is a dict keyed by metric name; each value is this rank's row of per-sample values,
|
| 671 |
+
# NaN-padded (the nan-aware aggregation below ignores both padding and unscorable samples).
|
| 672 |
+
sample_metrics = inputs["metrics"] # dict[str, Tensor(shape=[1, n_samples_local])]
|
| 673 |
+
keys = list(sample_metrics.keys())
|
| 674 |
+
device = completion_mask.device
|
| 675 |
+
n_samples = (position_ids == 0).sum().to(torch.float32)
|
| 676 |
+
if keys:
|
| 677 |
+
# nan-aware per key: unscorable samples carry NaN, so a plain .sum() would poison the whole metric.
|
| 678 |
+
local_sums = torch.stack([torch.nansum(sample_metrics[k].to(device)) for k in keys])
|
| 679 |
+
local_counts = torch.stack(
|
| 680 |
+
[(~torch.isnan(sample_metrics[k].to(device))).sum().to(torch.float32) for k in keys]
|
| 681 |
+
)
|
| 682 |
+
stats = torch.cat([local_sums, local_counts])
|
| 683 |
+
stats = self.accelerator.reduce(stats, reduction="sum")
|
| 684 |
+
n = len(keys)
|
| 685 |
+
global_sums, global_counts = stats[:n], stats[n:]
|
| 686 |
+
for k, global_sum, global_count in zip(keys, global_sums, global_counts, strict=True):
|
| 687 |
+
metric = (global_sum / global_count).item() if global_count > 0 else float("nan")
|
| 688 |
+
self._metrics["train"][k].append(metric)
|
| 689 |
+
|
| 690 |
+
length_stats = torch.stack([completion_mask.sum().float(), n_samples])
|
| 691 |
+
length_stats = self.accelerator.reduce(length_stats, reduction="sum")
|
| 692 |
+
self._metrics["train"]["completions/mean_length"].append((length_stats[0] / length_stats[1]).item())
|
| 693 |
+
|
| 694 |
+
# Training throughput: completion tokens consumed by this training step per second.
|
| 695 |
+
now = time.time()
|
| 696 |
+
if self._train_tokens_start_time is not None:
|
| 697 |
+
train_elapsed = now - self._train_tokens_start_time
|
| 698 |
+
if train_elapsed > 0:
|
| 699 |
+
self._metrics["train"]["training_tok/s"].append(global_n_tokens.item() / train_elapsed)
|
| 700 |
+
self._train_tokens_start_time = now
|
| 701 |
+
|
| 702 |
+
self._metrics["train"]["forward_time_s"].append(self._last_forward_time_s)
|
| 703 |
+
# NOTE: in dynamic mbs setup, we would need to agg across DP ranks.
|
| 704 |
+
self._metrics["train"]["train_seq_len"].append(float(position_ids.max() + 1))
|
| 705 |
+
return loss
|
| 706 |
+
|
| 707 |
+
def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
|
| 708 |
+
mode = "train" if self.model.training else "eval"
|
| 709 |
+
# Average the metrics
|
| 710 |
+
metrics = {}
|
| 711 |
+
for key, val in self._metrics[mode].items():
|
| 712 |
+
# Filter out NaN values before averaging. A reward function that returns None for all samples
|
| 713 |
+
# in a batch produces NaN for that batch's metric. With logging_steps > 1, a naive sum()/len()
|
| 714 |
+
# would let a single NaN contaminate valid data from other batches. Only return None when no
|
| 715 |
+
# valid values remain (e.g. JSON loggers crash on float NaN).
|
| 716 |
+
valid = [v for v in val if not math.isnan(v)]
|
| 717 |
+
metrics[key] = sum(valid) / len(valid) if valid else None
|
| 718 |
+
|
| 719 |
+
# This method can be called both in training and evaluation. When called in evaluation, the keys in `logs`
|
| 720 |
+
# start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format.
|
| 721 |
+
if mode == "eval":
|
| 722 |
+
metrics = {f"eval_{key}": val for key, val in metrics.items()}
|
| 723 |
+
|
| 724 |
+
logs.update(metrics)
|
| 725 |
+
super().log(logs, start_time)
|
| 726 |
+
self._metrics[mode].clear()
|
| 727 |
+
|
| 728 |
+
def _streaming_iter(self):
|
| 729 |
+
# Iterate parameters one at a time. For FSDP2 (DTensor), full_tensor() all-gathers just this parameter across
|
| 730 |
+
# FSDP ranks, then frees it once the generator advances — avoiding materializing the full model in memory.
|
| 731 |
+
device = self.accelerator.device
|
| 732 |
+
for name, param in self.model.named_parameters():
|
| 733 |
+
name = name.removeprefix("module.") # DDP/FSDP1 wrapping
|
| 734 |
+
full = param.full_tensor() if isinstance(param, DTensor) else param.detach()
|
| 735 |
+
if full.device != device:
|
| 736 |
+
full = full.to(device)
|
| 737 |
+
yield name, full
|
| 738 |
+
|
| 739 |
+
def _sync_weight(self):
|
| 740 |
+
t0 = time.time()
|
| 741 |
+
logger.info("Weight sync: pausing vLLM...")
|
| 742 |
+
if self.accelerator.is_main_process and self.weight_transfer:
|
| 743 |
+
self.weight_transfer.pause()
|
| 744 |
+
t_pause = time.time()
|
| 745 |
+
logger.info(f"Weight sync: pause took {t_pause - t0:.1f}s, waiting for all ranks...")
|
| 746 |
+
|
| 747 |
+
self.accelerator.wait_for_everyone()
|
| 748 |
+
t_barrier = time.time()
|
| 749 |
+
|
| 750 |
+
logger.info(f"Weight sync: transferring weights... (barrier took {t_barrier - t_pause:.1f}s)")
|
| 751 |
+
if self.accelerator.is_main_process and self.weight_transfer:
|
| 752 |
+
self.weight_transfer.send_weights(self._streaming_iter())
|
| 753 |
+
else:
|
| 754 |
+
# Non-rank-0 processes must still participate in full_tensor() collectives for FSDP2.
|
| 755 |
+
for _ in self._streaming_iter():
|
| 756 |
+
pass
|
| 757 |
+
t_transfer = time.time()
|
| 758 |
+
|
| 759 |
+
self.accelerator.wait_for_everyone()
|
| 760 |
+
|
| 761 |
+
logger.info(f"Weight sync: resuming vLLM... (transfer took {t_transfer - t_barrier:.1f}s)")
|
| 762 |
+
if self.accelerator.is_main_process:
|
| 763 |
+
if self.weight_transfer:
|
| 764 |
+
self.weight_transfer.resume()
|
| 765 |
+
self.model_version += 1
|
| 766 |
+
if self.rollout_worker:
|
| 767 |
+
self.rollout_worker.update_model_version(self.model_version)
|
| 768 |
+
weight_sync_time_s = time.time() - t0
|
| 769 |
+
self._metrics["train"]["weight_sync_time_s"].append(weight_sync_time_s)
|
| 770 |
+
logger.info(f"Weight sync: done. Total {weight_sync_time_s:.1f}s")
|
| 771 |
+
|
| 772 |
+
def _inner_training_loop(self, *args, **kwargs):
|
| 773 |
+
try:
|
| 774 |
+
return super()._inner_training_loop(*args, **kwargs)
|
| 775 |
+
finally:
|
| 776 |
+
if self.accelerator.is_main_process:
|
| 777 |
+
if self.rollout_worker:
|
| 778 |
+
self.rollout_worker.stop()
|
| 779 |
+
if self.weight_transfer:
|
| 780 |
+
self.weight_transfer.destroy()
|
tasks/tasksmith-b71e9e0a47b6/environment/source/trl/experimental/async_grpo/async_rollout_worker.py
ADDED
|
@@ -0,0 +1,829 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 asyncio
|
| 16 |
+
import inspect
|
| 17 |
+
import multiprocessing as mp
|
| 18 |
+
import os
|
| 19 |
+
import pickle
|
| 20 |
+
import queue
|
| 21 |
+
import threading
|
| 22 |
+
import time
|
| 23 |
+
import traceback
|
| 24 |
+
from collections.abc import Awaitable, Callable, Iterator
|
| 25 |
+
from dataclasses import dataclass
|
| 26 |
+
from multiprocessing.queues import Queue as MPQueue
|
| 27 |
+
from multiprocessing.sharedctypes import Synchronized as MPValue
|
| 28 |
+
from multiprocessing.synchronize import Event as MPEvent
|
| 29 |
+
from typing import Any, TypeAlias
|
| 30 |
+
|
| 31 |
+
import aiohttp
|
| 32 |
+
import numpy as np
|
| 33 |
+
from accelerate.logging import get_logger
|
| 34 |
+
from datasets import Dataset
|
| 35 |
+
from transformers import PreTrainedTokenizerBase
|
| 36 |
+
|
| 37 |
+
from ...chat_template_utils import (
|
| 38 |
+
add_response_schema,
|
| 39 |
+
get_training_chat_template,
|
| 40 |
+
is_chat_template_prefix_preserving,
|
| 41 |
+
parse_response,
|
| 42 |
+
)
|
| 43 |
+
from ...import_utils import is_vllm_available
|
| 44 |
+
from ...trainer.utils import print_prompt_completions_sample
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
logger = get_logger(__name__)
|
| 48 |
+
|
| 49 |
+
Messages: TypeAlias = list[dict[str, str]]
|
| 50 |
+
|
| 51 |
+
_RETRYABLE_HTTP_ERRORS = (aiohttp.ClientError, asyncio.TimeoutError, TimeoutError, ConnectionResetError)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
async def _retry_on_http_error(coro_factory: Callable[[], Awaitable], *, label: str, max_attempts: int = 1):
|
| 55 |
+
"""Retry an aiohttp coroutine on transport errors with bounded exponential backoff."""
|
| 56 |
+
for attempt in range(max_attempts):
|
| 57 |
+
try:
|
| 58 |
+
return await coro_factory()
|
| 59 |
+
except _RETRYABLE_HTTP_ERRORS as e:
|
| 60 |
+
if attempt >= max_attempts - 1:
|
| 61 |
+
raise
|
| 62 |
+
sleep = min(2 ** min(attempt, 4), 16)
|
| 63 |
+
logger.warning(f"{label} failed ({type(e).__name__}: {e}); retry {attempt + 1}/{max_attempts} in {sleep}s")
|
| 64 |
+
await asyncio.sleep(sleep)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@dataclass(slots=True)
|
| 68 |
+
class RolloutGroup:
|
| 69 |
+
prompt: Messages
|
| 70 |
+
prompt_ids: list[int]
|
| 71 |
+
reward_kwargs: dict[str, list[Any]]
|
| 72 |
+
completions: list[Messages]
|
| 73 |
+
completions_ids: list[list[int]]
|
| 74 |
+
completions_logprobs: list[list[float]]
|
| 75 |
+
tool_mask: list[list[int]]
|
| 76 |
+
tool_call_counts: list[int]
|
| 77 |
+
tool_failure_counts: list[int]
|
| 78 |
+
model_version: int
|
| 79 |
+
queued_at: float = 0.0
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@dataclass(slots=True)
|
| 83 |
+
class RolloutSample:
|
| 84 |
+
prompt: Messages
|
| 85 |
+
completion: Messages
|
| 86 |
+
input_ids: list[int]
|
| 87 |
+
completion_mask: list[int]
|
| 88 |
+
old_log_probs: list[float]
|
| 89 |
+
advantage: float
|
| 90 |
+
model_version: int
|
| 91 |
+
metrics: dict[str, float]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# Env vars the child must drop so accelerate's `PartialState()` initialises in
|
| 95 |
+
# single-process mode instead of trying to join the parent's process group.
|
| 96 |
+
_CHILD_ENV_TO_STRIP = (
|
| 97 |
+
"RANK",
|
| 98 |
+
"WORLD_SIZE",
|
| 99 |
+
"LOCAL_RANK",
|
| 100 |
+
"LOCAL_WORLD_SIZE",
|
| 101 |
+
"MASTER_ADDR",
|
| 102 |
+
"MASTER_PORT",
|
| 103 |
+
"GROUP_RANK",
|
| 104 |
+
"ROLE_RANK",
|
| 105 |
+
"ROLE_WORLD_SIZE",
|
| 106 |
+
"TORCHELASTIC_RUN_ID",
|
| 107 |
+
"TORCHELASTIC_RESTART_COUNT",
|
| 108 |
+
"TORCHELASTIC_MAX_RESTARTS",
|
| 109 |
+
"TORCH_FR_DUMP_TEMP_FILE",
|
| 110 |
+
"NCCL_DEBUG_FILE",
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _scrub_child_env() -> None:
|
| 115 |
+
# The child has no business touching CUDA; any library that imports torch
|
| 116 |
+
# and lazily probes devices would race the parent's allocator.
|
| 117 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 118 |
+
for k in _CHILD_ENV_TO_STRIP:
|
| 119 |
+
os.environ.pop(k, None)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _spawn_stop_watcher(rollout_loop: "_AsyncRolloutLoop", stop_event: MPEvent) -> None:
|
| 123 |
+
# Daemon thread that translates the parent's mp.Event into the child's
|
| 124 |
+
# asyncio.Event so _run_loops breaks out of its gather.
|
| 125 |
+
def _watch():
|
| 126 |
+
stop_event.wait()
|
| 127 |
+
try:
|
| 128 |
+
rollout_loop._loop.call_soon_threadsafe(rollout_loop._stop_event.set)
|
| 129 |
+
except RuntimeError:
|
| 130 |
+
# Loop already closed (run() returned before stop fired). Nothing to do.
|
| 131 |
+
pass
|
| 132 |
+
|
| 133 |
+
threading.Thread(target=_watch, daemon=True, name="grpo-mp-stop-watcher").start()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _child_main(
|
| 137 |
+
loop_kwargs: dict[str, Any],
|
| 138 |
+
samples_queue: MPQueue,
|
| 139 |
+
model_version_value: MPValue,
|
| 140 |
+
stop_event: MPEvent,
|
| 141 |
+
child_ready_event: MPEvent,
|
| 142 |
+
heartbeat_value: MPValue,
|
| 143 |
+
failed_event: MPEvent,
|
| 144 |
+
exception_info_queue: MPQueue,
|
| 145 |
+
) -> None:
|
| 146 |
+
_scrub_child_env()
|
| 147 |
+
# `accelerate.logging.get_logger` requires `PartialState()` to have been called.
|
| 148 |
+
from accelerate.state import PartialState
|
| 149 |
+
|
| 150 |
+
PartialState()
|
| 151 |
+
|
| 152 |
+
rollout_loop = _AsyncRolloutLoop(
|
| 153 |
+
**loop_kwargs,
|
| 154 |
+
rollout_buffer=samples_queue,
|
| 155 |
+
model_version_value=model_version_value,
|
| 156 |
+
heartbeat_value=heartbeat_value,
|
| 157 |
+
failed_event=failed_event,
|
| 158 |
+
exception_info_queue=exception_info_queue,
|
| 159 |
+
)
|
| 160 |
+
child_ready_event.set()
|
| 161 |
+
_spawn_stop_watcher(rollout_loop, stop_event)
|
| 162 |
+
try:
|
| 163 |
+
rollout_loop.run()
|
| 164 |
+
except Exception:
|
| 165 |
+
traceback.print_exc()
|
| 166 |
+
raise
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class _AsyncRolloutLoop:
|
| 170 |
+
"""Asyncio generate and score loops. Lives entirely inside the spawned child process.
|
| 171 |
+
|
| 172 |
+
Owns the tokenizer, dataset iterator, reward funcs, environments, and the asyncio event loop. Talks to vLLM via
|
| 173 |
+
`/v1/completions`. Pushes scored `RolloutSample`s into the shared `mp.Queue` (`rollout_buffer`); reads the bumped
|
| 174 |
+
policy version from the shared `mp.Value` (`model_version_value`).
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
def __init__(
|
| 178 |
+
self,
|
| 179 |
+
*,
|
| 180 |
+
model_name: str,
|
| 181 |
+
dataset: Dataset,
|
| 182 |
+
reward_funcs: list[Callable[..., list[float]]],
|
| 183 |
+
processing_class: PreTrainedTokenizerBase,
|
| 184 |
+
rollout_buffer: MPQueue,
|
| 185 |
+
model_version_value: MPValue,
|
| 186 |
+
heartbeat_value: MPValue,
|
| 187 |
+
failed_event: MPEvent,
|
| 188 |
+
exception_info_queue: MPQueue,
|
| 189 |
+
tools: list[Callable] | None = None,
|
| 190 |
+
environment_factory: Callable[[], object] | None = None,
|
| 191 |
+
num_generations: int = 8,
|
| 192 |
+
max_inflight_tasks: int = 128,
|
| 193 |
+
queue_maxsize: int = 0,
|
| 194 |
+
vllm_server_url: str = "http://localhost:8000",
|
| 195 |
+
max_tokens: int = 32,
|
| 196 |
+
temperature: float = 1.0,
|
| 197 |
+
request_timeout: int = 120,
|
| 198 |
+
chat_template_kwargs: dict[str, Any] | None = None,
|
| 199 |
+
max_tool_calling_iterations: int | None = None,
|
| 200 |
+
log_completions: bool = False,
|
| 201 |
+
num_completions_to_print: int | None = None,
|
| 202 |
+
):
|
| 203 |
+
self.model_name = model_name
|
| 204 |
+
self.dataset = dataset
|
| 205 |
+
self._dataset_iter = iter(dataset)
|
| 206 |
+
self.reward_funcs = reward_funcs
|
| 207 |
+
self.reward_func_names = [f.__name__ for f in reward_funcs]
|
| 208 |
+
self.tokenizer = add_response_schema(processing_class)
|
| 209 |
+
self.rollout_buffer = rollout_buffer # shared mp.Queue
|
| 210 |
+
self._model_version_value = model_version_value # shared mp.Value
|
| 211 |
+
self._heartbeat_value = heartbeat_value # shared mp.Value('d'); wall-clock seconds
|
| 212 |
+
self._failed_event = failed_event # shared mp.Event
|
| 213 |
+
self._exception_info_queue = exception_info_queue # shared mp.Queue(maxsize=1)
|
| 214 |
+
|
| 215 |
+
self.num_generations = num_generations
|
| 216 |
+
self.max_inflight_tasks = max_inflight_tasks
|
| 217 |
+
self.queue_maxsize = queue_maxsize
|
| 218 |
+
self.max_tokens = max_tokens
|
| 219 |
+
self.temperature = temperature
|
| 220 |
+
self.request_timeout = request_timeout
|
| 221 |
+
self.chat_template_kwargs = chat_template_kwargs or {}
|
| 222 |
+
self.max_tool_calling_iterations = max_tool_calling_iterations
|
| 223 |
+
self.log_completions = log_completions
|
| 224 |
+
self.num_completions_to_print = num_completions_to_print
|
| 225 |
+
self.vllm_server_url = vllm_server_url.rstrip("/")
|
| 226 |
+
|
| 227 |
+
self.environments = None
|
| 228 |
+
environment_methods = [[] for _ in range(max_inflight_tasks)]
|
| 229 |
+
if environment_factory is not None:
|
| 230 |
+
self.environments = [environment_factory() for _ in range(max_inflight_tasks)]
|
| 231 |
+
for i, environment in enumerate(self.environments):
|
| 232 |
+
has_reset = False
|
| 233 |
+
for name, member in inspect.getmembers(environment, predicate=inspect.ismethod):
|
| 234 |
+
if name == "reset":
|
| 235 |
+
has_reset = True
|
| 236 |
+
elif not name.startswith("_"):
|
| 237 |
+
environment_methods[i].append(member)
|
| 238 |
+
if not has_reset:
|
| 239 |
+
raise ValueError(
|
| 240 |
+
"Each environment instance returned by `environment_factory` must define `reset`."
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
base_tools = tools or []
|
| 244 |
+
self._sync_tool_dicts = [{} for _ in range(max_inflight_tasks)]
|
| 245 |
+
for i in range(max_inflight_tasks):
|
| 246 |
+
for tool in base_tools + (environment_methods[i] if self.environments is not None else []):
|
| 247 |
+
if inspect.iscoroutinefunction(tool):
|
| 248 |
+
raise ValueError("Asynchronous tools are not supported yet.")
|
| 249 |
+
self._sync_tool_dicts[i][tool.__name__] = tool
|
| 250 |
+
self.tools = base_tools + (environment_methods[0] if self.environments is not None else [])
|
| 251 |
+
|
| 252 |
+
# The chat template must be prefix-preserving in multi-turn training; if the tokenizer's
|
| 253 |
+
# template isn't, swap in a training-safe one.
|
| 254 |
+
if self.tools and not is_chat_template_prefix_preserving(self.tokenizer):
|
| 255 |
+
self.chat_template = get_training_chat_template(self.tokenizer)
|
| 256 |
+
else:
|
| 257 |
+
self.chat_template = None
|
| 258 |
+
|
| 259 |
+
self._groups_to_score: asyncio.Queue[RolloutGroup | None] = asyncio.Queue(maxsize=16)
|
| 260 |
+
self._total_completion_tokens = 0
|
| 261 |
+
self._total_groups_scored = 0
|
| 262 |
+
self._generation_start_time: float | None = None
|
| 263 |
+
self.session: aiohttp.ClientSession | None = None
|
| 264 |
+
|
| 265 |
+
self._loop = asyncio.new_event_loop()
|
| 266 |
+
self._stop_event = asyncio.Event()
|
| 267 |
+
|
| 268 |
+
@property
|
| 269 |
+
def model_version(self) -> int:
|
| 270 |
+
return int(self._model_version_value.value)
|
| 271 |
+
|
| 272 |
+
def run(self) -> None:
|
| 273 |
+
asyncio.set_event_loop(self._loop)
|
| 274 |
+
try:
|
| 275 |
+
self._loop.run_until_complete(self._run_loops(stop_event=self._stop_event))
|
| 276 |
+
except BaseException as e:
|
| 277 |
+
# Push pickle-safe exception info to the parent before setting _failed_event, so a
|
| 278 |
+
# reader that sees the event is guaranteed to also see the info on the queue.
|
| 279 |
+
info = (type(e).__name__, str(e), traceback.format_exc())
|
| 280 |
+
try:
|
| 281 |
+
self._exception_info_queue.put_nowait(info)
|
| 282 |
+
except Exception:
|
| 283 |
+
pass # queue full (parent hasn't drained a prior failure), best-effort put
|
| 284 |
+
self._failed_event.set()
|
| 285 |
+
logger.exception(f"Worker process failed: {e}")
|
| 286 |
+
raise
|
| 287 |
+
finally:
|
| 288 |
+
self._loop.close()
|
| 289 |
+
|
| 290 |
+
async def _run_loops(self, stop_event: asyncio.Event) -> None:
|
| 291 |
+
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=self.max_inflight_tasks)) as session:
|
| 292 |
+
self.session = session
|
| 293 |
+
logger.info(
|
| 294 |
+
f"vllm worker started: num_generations={self.num_generations}, "
|
| 295 |
+
f"max_inflight_tasks={self.max_inflight_tasks}"
|
| 296 |
+
)
|
| 297 |
+
await asyncio.gather(
|
| 298 |
+
asyncio.create_task(self._generate_loop(stop_event=stop_event)),
|
| 299 |
+
asyncio.create_task(self._score_loop(stop_event=stop_event)),
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
async def _generate_loop(self, stop_event: asyncio.Event) -> None:
|
| 303 |
+
pending_groups: dict[int, RolloutGroup] = {}
|
| 304 |
+
pending_completed: dict[int, int] = {}
|
| 305 |
+
inflight_tasks: dict[asyncio.Task, tuple[int, int]] = {}
|
| 306 |
+
free_slots = set(range(self.max_inflight_tasks))
|
| 307 |
+
work_iter = self._repeat_iterator()
|
| 308 |
+
|
| 309 |
+
self._generation_start_time = time.monotonic()
|
| 310 |
+
try:
|
| 311 |
+
while True:
|
| 312 |
+
# Wall-clock for cross-process comparison; parent uses time.time() in check_health.
|
| 313 |
+
self._heartbeat_value.value = time.time()
|
| 314 |
+
while free_slots and not stop_event.is_set():
|
| 315 |
+
group_id, row = next(work_iter)
|
| 316 |
+
if group_id not in pending_groups:
|
| 317 |
+
prompt = row["prompt"]
|
| 318 |
+
prompt_ids = self.tokenizer.apply_chat_template(
|
| 319 |
+
prompt,
|
| 320 |
+
return_dict=False,
|
| 321 |
+
add_generation_prompt=True,
|
| 322 |
+
tools=self.tools or None, # `or None`: Llama bug: renders tool boilerplate for tools=[]
|
| 323 |
+
chat_template=self.chat_template,
|
| 324 |
+
**self.chat_template_kwargs,
|
| 325 |
+
)
|
| 326 |
+
reward_kwargs = {
|
| 327 |
+
key: [row[key]] * self.num_generations
|
| 328 |
+
for key in row
|
| 329 |
+
if key not in {"prompt", "completion", "completion_ids"}
|
| 330 |
+
}
|
| 331 |
+
pending_groups[group_id] = RolloutGroup(
|
| 332 |
+
prompt=prompt,
|
| 333 |
+
prompt_ids=prompt_ids,
|
| 334 |
+
reward_kwargs=reward_kwargs,
|
| 335 |
+
completions=[],
|
| 336 |
+
completions_ids=[],
|
| 337 |
+
completions_logprobs=[],
|
| 338 |
+
tool_mask=[],
|
| 339 |
+
tool_call_counts=[],
|
| 340 |
+
tool_failure_counts=[],
|
| 341 |
+
model_version=self.model_version,
|
| 342 |
+
)
|
| 343 |
+
pending_completed[group_id] = 0
|
| 344 |
+
|
| 345 |
+
slot = free_slots.pop()
|
| 346 |
+
if self.environments is not None:
|
| 347 |
+
self.environments[slot].reset(**row)
|
| 348 |
+
|
| 349 |
+
task = asyncio.create_task(
|
| 350 |
+
self._generate_one(pending_groups[group_id].prompt, tool_dict=self._sync_tool_dicts[slot])
|
| 351 |
+
)
|
| 352 |
+
inflight_tasks[task] = (group_id, slot)
|
| 353 |
+
|
| 354 |
+
if not inflight_tasks:
|
| 355 |
+
if stop_event.is_set():
|
| 356 |
+
return
|
| 357 |
+
await asyncio.sleep(0.01)
|
| 358 |
+
continue
|
| 359 |
+
|
| 360 |
+
done, _ = await asyncio.wait(inflight_tasks, return_when=asyncio.FIRST_COMPLETED, timeout=0.1)
|
| 361 |
+
if not done:
|
| 362 |
+
continue
|
| 363 |
+
|
| 364 |
+
for task in done:
|
| 365 |
+
group_id, slot = inflight_tasks.pop(task)
|
| 366 |
+
free_slots.add(slot)
|
| 367 |
+
if task.exception() is not None:
|
| 368 |
+
raise task.exception()
|
| 369 |
+
|
| 370 |
+
(
|
| 371 |
+
completion,
|
| 372 |
+
completion_ids,
|
| 373 |
+
completion_logprobs,
|
| 374 |
+
tool_mask,
|
| 375 |
+
tool_call_count,
|
| 376 |
+
tool_failure_count,
|
| 377 |
+
) = task.result()
|
| 378 |
+
group = pending_groups[group_id]
|
| 379 |
+
group.completions.append(completion)
|
| 380 |
+
group.completions_ids.append(completion_ids)
|
| 381 |
+
group.completions_logprobs.append(completion_logprobs)
|
| 382 |
+
group.tool_mask.append(tool_mask)
|
| 383 |
+
group.tool_call_counts.append(tool_call_count)
|
| 384 |
+
group.tool_failure_counts.append(tool_failure_count)
|
| 385 |
+
self._total_completion_tokens += sum(tool_mask)
|
| 386 |
+
pending_completed[group_id] += 1
|
| 387 |
+
|
| 388 |
+
if pending_completed[group_id] == self.num_generations:
|
| 389 |
+
group.queued_at = time.monotonic()
|
| 390 |
+
while True:
|
| 391 |
+
try:
|
| 392 |
+
self._groups_to_score.put_nowait(group)
|
| 393 |
+
break
|
| 394 |
+
except asyncio.QueueFull:
|
| 395 |
+
if stop_event.is_set():
|
| 396 |
+
return
|
| 397 |
+
await asyncio.sleep(0.1)
|
| 398 |
+
del pending_groups[group_id]
|
| 399 |
+
del pending_completed[group_id]
|
| 400 |
+
finally:
|
| 401 |
+
for task in inflight_tasks:
|
| 402 |
+
task.cancel()
|
| 403 |
+
if inflight_tasks:
|
| 404 |
+
await asyncio.gather(*inflight_tasks, return_exceptions=True)
|
| 405 |
+
try:
|
| 406 |
+
self._groups_to_score.put_nowait(None)
|
| 407 |
+
except asyncio.QueueFull:
|
| 408 |
+
pass
|
| 409 |
+
|
| 410 |
+
async def _score_loop(self, stop_event: asyncio.Event) -> None:
|
| 411 |
+
while not stop_event.is_set():
|
| 412 |
+
self._heartbeat_value.value = time.time()
|
| 413 |
+
t_wait = time.monotonic()
|
| 414 |
+
try:
|
| 415 |
+
group = await asyncio.wait_for(self._groups_to_score.get(), timeout=0.5)
|
| 416 |
+
except asyncio.TimeoutError:
|
| 417 |
+
continue
|
| 418 |
+
if group is None:
|
| 419 |
+
return
|
| 420 |
+
score_queue_wait = time.monotonic() - t_wait
|
| 421 |
+
wait_scoring = time.monotonic() - group.queued_at
|
| 422 |
+
|
| 423 |
+
if score_queue_wait > 0.5:
|
| 424 |
+
logger.info(f"[score] waited {score_queue_wait:.1f}s for a group to score")
|
| 425 |
+
|
| 426 |
+
t0 = time.monotonic()
|
| 427 |
+
samples = await self._score_group(group)
|
| 428 |
+
scoring_time = time.monotonic() - t0
|
| 429 |
+
logger.info(
|
| 430 |
+
f"[score] scored {len(samples)} samples in {scoring_time:.2f}s, "
|
| 431 |
+
f"buffer_qsize={self.rollout_buffer.qsize()}"
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
self._compute_rollout_metrics(samples, scoring_time, wait_scoring)
|
| 435 |
+
|
| 436 |
+
if self.log_completions and samples:
|
| 437 |
+
print_prompt_completions_sample(
|
| 438 |
+
prompts=[s.prompt for s in samples],
|
| 439 |
+
completions=[s.completion for s in samples],
|
| 440 |
+
rewards={"reward": [s.metrics["reward"] for s in samples]},
|
| 441 |
+
advantages=[s.advantage for s in samples],
|
| 442 |
+
step=self._total_groups_scored,
|
| 443 |
+
num_samples=self.num_completions_to_print,
|
| 444 |
+
)
|
| 445 |
+
self._total_groups_scored += 1
|
| 446 |
+
|
| 447 |
+
for sample in samples:
|
| 448 |
+
while True:
|
| 449 |
+
try:
|
| 450 |
+
self.rollout_buffer.put_nowait(sample)
|
| 451 |
+
break
|
| 452 |
+
except queue.Full:
|
| 453 |
+
if stop_event.is_set():
|
| 454 |
+
return
|
| 455 |
+
logger.info(
|
| 456 |
+
f"[score] rollout buffer full (maxsize={self.queue_maxsize}), "
|
| 457 |
+
"waiting for trainer to consume..."
|
| 458 |
+
)
|
| 459 |
+
await asyncio.sleep(0.1)
|
| 460 |
+
|
| 461 |
+
def _compute_rollout_metrics(self, samples: list[RolloutSample], scoring_time: float, wait_scoring: float) -> None:
|
| 462 |
+
assert self._generation_start_time is not None
|
| 463 |
+
elapsed = time.monotonic() - self._generation_start_time
|
| 464 |
+
generation_tok_per_sec = self._total_completion_tokens / elapsed if elapsed > 0 else 0.0
|
| 465 |
+
for sample in samples:
|
| 466 |
+
sample.metrics["generation_tok_per_s"] = generation_tok_per_sec
|
| 467 |
+
sample.metrics["scoring_time_ms"] = scoring_time * 1000
|
| 468 |
+
sample.metrics["wait_scoring_ms"] = wait_scoring * 1000
|
| 469 |
+
sample.metrics["buffer_qsize"] = self.rollout_buffer.qsize()
|
| 470 |
+
|
| 471 |
+
def _repeat_iterator(self) -> Iterator[tuple[int, dict[str, Any]]]:
|
| 472 |
+
group_id = 0
|
| 473 |
+
while True:
|
| 474 |
+
try:
|
| 475 |
+
row = next(self._dataset_iter)
|
| 476 |
+
except StopIteration:
|
| 477 |
+
self._dataset_iter = iter(self.dataset)
|
| 478 |
+
row = next(self._dataset_iter)
|
| 479 |
+
for _ in range(self.num_generations):
|
| 480 |
+
yield group_id, row
|
| 481 |
+
group_id += 1
|
| 482 |
+
|
| 483 |
+
async def _generate_one(
|
| 484 |
+
self, prompt: Messages, tool_dict: dict[str, Callable]
|
| 485 |
+
) -> tuple[list[dict[str, str]], list[int], list[float], list[int], int, int]:
|
| 486 |
+
completion, completion_ids, completion_logprobs, tool_mask = [], [], [], []
|
| 487 |
+
tool_call_count = 0
|
| 488 |
+
tool_failure_count = 0
|
| 489 |
+
iteration_num = 0
|
| 490 |
+
max_iterations = self.max_tool_calling_iterations
|
| 491 |
+
prompt_ids = self.tokenizer.apply_chat_template(
|
| 492 |
+
prompt,
|
| 493 |
+
return_dict=False,
|
| 494 |
+
add_generation_prompt=True,
|
| 495 |
+
tools=self.tools or None,
|
| 496 |
+
chat_template=self.chat_template,
|
| 497 |
+
**self.chat_template_kwargs,
|
| 498 |
+
)
|
| 499 |
+
while True:
|
| 500 |
+
turn_ids, turn_logprobs = await self._generate_one_turn(prompt_ids)
|
| 501 |
+
assistant_message = parse_response(self.tokenizer, turn_ids)
|
| 502 |
+
completion.append(assistant_message)
|
| 503 |
+
completion_ids.extend(turn_ids)
|
| 504 |
+
completion_logprobs.extend(turn_logprobs)
|
| 505 |
+
tool_mask.extend([1] * len(turn_ids))
|
| 506 |
+
tool_calls = assistant_message.get("tool_calls")
|
| 507 |
+
if tool_calls is None or (max_iterations is not None and iteration_num >= max_iterations):
|
| 508 |
+
return completion, completion_ids, completion_logprobs, tool_mask, tool_call_count, tool_failure_count
|
| 509 |
+
|
| 510 |
+
tool_messages, n_calls, n_failures = self._execute_tool_calls(tool_calls, tool_dict)
|
| 511 |
+
tool_call_count += n_calls
|
| 512 |
+
tool_failure_count += n_failures
|
| 513 |
+
completion.extend(tool_messages)
|
| 514 |
+
suffix_ids = self._get_tool_suffix_ids(tool_messages)
|
| 515 |
+
completion_ids.extend(suffix_ids)
|
| 516 |
+
completion_logprobs.extend([0.0] * len(suffix_ids))
|
| 517 |
+
tool_mask.extend([0] * len(suffix_ids))
|
| 518 |
+
prompt_ids = prompt_ids + turn_ids + suffix_ids
|
| 519 |
+
iteration_num += 1
|
| 520 |
+
|
| 521 |
+
def _get_tool_suffix_ids(self, tool_messages: list[dict[str, Any]]) -> list[int]:
|
| 522 |
+
# Use the real tool name: some templates (e.g. GPT-OSS) derive the tool response header from
|
| 523 |
+
# the assistant's tool call name.
|
| 524 |
+
dummy_tool_calls = [{"type": "function", "function": {"name": tool_messages[0]["name"], "arguments": {}}}]
|
| 525 |
+
dummy_messages = [
|
| 526 |
+
{"role": "user", "content": "dummy"},
|
| 527 |
+
# `content: ""` is required: VLM processors crash on tokenize=True without it
|
| 528 |
+
# (KeyError in processing_utils.py, see huggingface/transformers#45290).
|
| 529 |
+
{"role": "assistant", "content": "", "tool_calls": dummy_tool_calls},
|
| 530 |
+
]
|
| 531 |
+
prefix_ids = self.tokenizer.apply_chat_template(
|
| 532 |
+
dummy_messages,
|
| 533 |
+
add_generation_prompt=False,
|
| 534 |
+
tokenize=True,
|
| 535 |
+
chat_template=self.chat_template,
|
| 536 |
+
return_dict=False,
|
| 537 |
+
**self.chat_template_kwargs,
|
| 538 |
+
)
|
| 539 |
+
full_ids = self.tokenizer.apply_chat_template(
|
| 540 |
+
dummy_messages + tool_messages,
|
| 541 |
+
add_generation_prompt=True,
|
| 542 |
+
tokenize=True,
|
| 543 |
+
chat_template=self.chat_template,
|
| 544 |
+
return_dict=False,
|
| 545 |
+
**self.chat_template_kwargs,
|
| 546 |
+
)
|
| 547 |
+
# Some chat templates (Qwen3/Qwen3.5) render "...<|im_end|>\n" after assistant/tool blocks.
|
| 548 |
+
# Align the slicing boundary to EOS, not EOS + newline.
|
| 549 |
+
eos_positions = [i for i, tok_id in enumerate(prefix_ids) if tok_id == self.tokenizer.eos_token_id]
|
| 550 |
+
if eos_positions:
|
| 551 |
+
prefix_ids = prefix_ids[: eos_positions[-1] + 1]
|
| 552 |
+
if full_ids[: len(prefix_ids)] != prefix_ids:
|
| 553 |
+
raise ValueError("Unexpected tokenization: the EOS-trimmed prefix IDs are not a prefix of the full IDs.")
|
| 554 |
+
return full_ids[len(prefix_ids) :]
|
| 555 |
+
|
| 556 |
+
def _execute_tool_calls(
|
| 557 |
+
self, tool_calls: list[dict[str, Any]], tool_dict: dict[str, Callable]
|
| 558 |
+
) -> tuple[list[dict[str, str]], int, int]:
|
| 559 |
+
tool_messages = []
|
| 560 |
+
n_calls = 0
|
| 561 |
+
n_failures = 0
|
| 562 |
+
for tool_call in tool_calls:
|
| 563 |
+
n_calls += 1
|
| 564 |
+
function = tool_call["function"]
|
| 565 |
+
name = function["name"]
|
| 566 |
+
try:
|
| 567 |
+
arguments = function.get("arguments", {})
|
| 568 |
+
result = tool_dict[name](**arguments)
|
| 569 |
+
except Exception as error:
|
| 570 |
+
n_failures += 1
|
| 571 |
+
result = {"error": str(error)}
|
| 572 |
+
tool_messages.append({"role": "tool", "name": name, "content": str(result)})
|
| 573 |
+
return tool_messages, n_calls, n_failures
|
| 574 |
+
|
| 575 |
+
async def _generate_one_turn(self, prompt_ids: list[int]) -> tuple[list[int], list[float]]:
|
| 576 |
+
payload = {
|
| 577 |
+
"model": self.model_name,
|
| 578 |
+
"prompt": prompt_ids,
|
| 579 |
+
"max_tokens": self.max_tokens,
|
| 580 |
+
"temperature": self.temperature,
|
| 581 |
+
"n": 1,
|
| 582 |
+
"return_token_ids": True,
|
| 583 |
+
"logprobs": 0,
|
| 584 |
+
}
|
| 585 |
+
output = await _retry_on_http_error(
|
| 586 |
+
lambda: self._post("/v1/completions", payload, self.request_timeout),
|
| 587 |
+
max_attempts=30,
|
| 588 |
+
label="vllm /v1/completions",
|
| 589 |
+
)
|
| 590 |
+
choice = output["choices"][0]
|
| 591 |
+
return choice["token_ids"], choice["logprobs"]["token_logprobs"]
|
| 592 |
+
|
| 593 |
+
async def _score_group(self, group: RolloutGroup) -> list[RolloutSample]:
|
| 594 |
+
kwargs = dict(
|
| 595 |
+
completions=group.completions,
|
| 596 |
+
prompt=group.prompt,
|
| 597 |
+
prompts=[group.prompt] * len(group.completions),
|
| 598 |
+
completion_ids=group.completions_ids,
|
| 599 |
+
**group.reward_kwargs,
|
| 600 |
+
)
|
| 601 |
+
all_rewards = await asyncio.gather(
|
| 602 |
+
*[
|
| 603 |
+
reward_func(**kwargs)
|
| 604 |
+
if inspect.iscoroutinefunction(reward_func)
|
| 605 |
+
else asyncio.to_thread(reward_func, **kwargs)
|
| 606 |
+
for reward_func in self.reward_funcs
|
| 607 |
+
]
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
# Reward funcs may return None per-sample (unparseable gold). Convert to NaN. A completion
|
| 611 |
+
# for which every func returned None is unscorable: nansum would give 0 and the row would
|
| 612 |
+
# pull the policy away from actually-correct answers.
|
| 613 |
+
# Mark such rows NaN, then compute advantage on the scorable subset only.
|
| 614 |
+
all_rewards = [[r if r is not None else float("nan") for r in row] for row in all_rewards]
|
| 615 |
+
arr = np.array(all_rewards, dtype=float)
|
| 616 |
+
all_nan_mask = np.all(np.isnan(arr), axis=0)
|
| 617 |
+
rewards = np.nansum(arr, axis=0)
|
| 618 |
+
rewards[all_nan_mask] = np.nan
|
| 619 |
+
|
| 620 |
+
scored_mask = ~np.isnan(rewards)
|
| 621 |
+
# NOTE: for NaN reward we set advantage to 0 !
|
| 622 |
+
advantages = np.zeros_like(rewards)
|
| 623 |
+
if scored_mask.any():
|
| 624 |
+
scored = rewards[scored_mask]
|
| 625 |
+
advantages[scored_mask] = (scored - scored.mean()) / (scored.std() + 1e-8)
|
| 626 |
+
reward_mean = float(scored.mean())
|
| 627 |
+
reward_std = float(scored.std())
|
| 628 |
+
else:
|
| 629 |
+
reward_mean = reward_std = float("nan")
|
| 630 |
+
logger.info(f"Rollout metrics: reward_mean={reward_mean:.4f}, reward_std={reward_std:.4f}")
|
| 631 |
+
|
| 632 |
+
total_calls = sum(group.tool_call_counts)
|
| 633 |
+
tool_metrics = (
|
| 634 |
+
[
|
| 635 |
+
{
|
| 636 |
+
"tools/call_frequency": float(n_calls),
|
| 637 |
+
"tools/failure_frequency": (n_failures / n_calls) if n_calls > 0 else 0.0,
|
| 638 |
+
}
|
| 639 |
+
for n_calls, n_failures in zip(group.tool_call_counts, group.tool_failure_counts, strict=True)
|
| 640 |
+
]
|
| 641 |
+
if total_calls > 0
|
| 642 |
+
else [{}] * len(group.completions)
|
| 643 |
+
)
|
| 644 |
+
|
| 645 |
+
per_func_rewards = np.array(all_rewards, dtype=float)
|
| 646 |
+
return [
|
| 647 |
+
RolloutSample(
|
| 648 |
+
prompt=group.prompt,
|
| 649 |
+
completion=completion,
|
| 650 |
+
input_ids=group.prompt_ids + completion_ids,
|
| 651 |
+
completion_mask=[0] * len(group.prompt_ids) + tool_mask,
|
| 652 |
+
old_log_probs=[0.0] * len(group.prompt_ids) + logprobs,
|
| 653 |
+
advantage=advantage,
|
| 654 |
+
model_version=group.model_version,
|
| 655 |
+
metrics={
|
| 656 |
+
"reward": float(reward),
|
| 657 |
+
"reward_std": reward_std,
|
| 658 |
+
**{
|
| 659 |
+
f"rewards/{name}": float(func_reward)
|
| 660 |
+
for name, func_reward in zip(self.reward_func_names, per_func_rewards[:, i], strict=True)
|
| 661 |
+
},
|
| 662 |
+
**tm,
|
| 663 |
+
},
|
| 664 |
+
)
|
| 665 |
+
for i, (completion, completion_ids, logprobs, tool_mask, advantage, reward, tm) in enumerate(
|
| 666 |
+
zip(
|
| 667 |
+
group.completions,
|
| 668 |
+
group.completions_ids,
|
| 669 |
+
group.completions_logprobs,
|
| 670 |
+
group.tool_mask,
|
| 671 |
+
advantages,
|
| 672 |
+
rewards,
|
| 673 |
+
tool_metrics,
|
| 674 |
+
strict=True,
|
| 675 |
+
)
|
| 676 |
+
)
|
| 677 |
+
]
|
| 678 |
+
|
| 679 |
+
async def _post(self, path: str, payload: dict, timeout: float, max_retries: int = 3) -> dict:
|
| 680 |
+
client_timeout = aiohttp.ClientTimeout(total=timeout)
|
| 681 |
+
|
| 682 |
+
async def _do_post():
|
| 683 |
+
async with self.session.post(
|
| 684 |
+
f"{self.vllm_server_url}{path}", json=payload, timeout=client_timeout
|
| 685 |
+
) as response:
|
| 686 |
+
response.raise_for_status()
|
| 687 |
+
content = await response.json()
|
| 688 |
+
return content if content else {}
|
| 689 |
+
|
| 690 |
+
return await _retry_on_http_error(_do_post, label=f"POST {path}", max_attempts=max_retries)
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
class AsyncRolloutWorker:
|
| 694 |
+
"""Parent-side controller: spawns a child process running `_AsyncRolloutLoop`.
|
| 695 |
+
|
| 696 |
+
The trainer holds this object on rank 0. The child does the actual rollout work; this class only manages lifecycle
|
| 697 |
+
(start/stop) and exposes the shared `mp.Queue` (`rollout_buffer`) and `mp.Value` (`model_version`) the trainer
|
| 698 |
+
reads/writes.
|
| 699 |
+
|
| 700 |
+
Constructor kwargs are forwarded as-is to `_AsyncRolloutLoop` when the child spawns; only `queue_maxsize` and
|
| 701 |
+
`child_ready_timeout` are consumed here. Because the child is spawned, every forwarded kwarg is pickled:
|
| 702 |
+
`reward_funcs`, `tools`, and `environment_factory` (and anything they close over) must be picklable — module-level
|
| 703 |
+
functions, `functools.partial`, or callable instances, never lambdas or closures. `start()` validates this up front
|
| 704 |
+
and raises a `TypeError` otherwise. The child also runs with `CUDA_VISIBLE_DEVICES=""`, so GPU reward models
|
| 705 |
+
execute on CPU.
|
| 706 |
+
"""
|
| 707 |
+
|
| 708 |
+
def __init__(
|
| 709 |
+
self,
|
| 710 |
+
*,
|
| 711 |
+
queue_maxsize: int = 0,
|
| 712 |
+
child_ready_timeout: int = 300,
|
| 713 |
+
**loop_kwargs: Any,
|
| 714 |
+
):
|
| 715 |
+
if not is_vllm_available(min_version="0.17.1"):
|
| 716 |
+
raise ImportError(
|
| 717 |
+
"vLLM >= 0.17.1 is required to use AsyncRolloutWorker. Install it with: pip install 'vllm>=0.17.1'"
|
| 718 |
+
)
|
| 719 |
+
ctx = mp.get_context("spawn")
|
| 720 |
+
self._mp_ctx = ctx
|
| 721 |
+
self.rollout_buffer = ctx.Queue(maxsize=queue_maxsize)
|
| 722 |
+
self._model_version_value = ctx.Value("i", 0)
|
| 723 |
+
self._stop_event_mp = ctx.Event()
|
| 724 |
+
self._child_ready_event = ctx.Event()
|
| 725 |
+
# Liveness state shared with the child. Wall-clock seconds because monotonic() is per-process.
|
| 726 |
+
self._heartbeat_value = ctx.Value("d", 0.0)
|
| 727 |
+
self._failed_event = ctx.Event()
|
| 728 |
+
self._exception_info_queue = ctx.Queue(maxsize=1)
|
| 729 |
+
# Forwarded verbatim to _AsyncRolloutLoop in the child. queue_maxsize is also
|
| 730 |
+
# forwarded — the child reads it for "rollout buffer full" log lines.
|
| 731 |
+
loop_kwargs["queue_maxsize"] = queue_maxsize
|
| 732 |
+
self._loop_kwargs = loop_kwargs
|
| 733 |
+
self._child_ready_timeout = child_ready_timeout
|
| 734 |
+
self._process: mp.Process | None = None
|
| 735 |
+
|
| 736 |
+
@property
|
| 737 |
+
def model_version(self) -> int:
|
| 738 |
+
return int(self._model_version_value.value)
|
| 739 |
+
|
| 740 |
+
@model_version.setter
|
| 741 |
+
def model_version(self, value: int) -> None:
|
| 742 |
+
# NOTE(@aminediro) Read/write ops like += are not atomic with mp.Value
|
| 743 |
+
with self._model_version_value.get_lock():
|
| 744 |
+
self._model_version_value.value = int(value)
|
| 745 |
+
|
| 746 |
+
def update_model_version(self, model_version: int) -> None:
|
| 747 |
+
self.model_version = model_version
|
| 748 |
+
|
| 749 |
+
def start(self) -> None:
|
| 750 |
+
if self._process is not None:
|
| 751 |
+
logger.warning("AsyncRolloutWorker.start() called but child process is already running; ignoring.")
|
| 752 |
+
return
|
| 753 |
+
# Reset so spawn-import latency (~tens of seconds) doesn't immediately trip check_health.
|
| 754 |
+
self._heartbeat_value.value = time.time()
|
| 755 |
+
try:
|
| 756 |
+
pickle.dumps(self._loop_kwargs)
|
| 757 |
+
except (pickle.PicklingError, AttributeError, TypeError) as e:
|
| 758 |
+
# fails fast with an actionable message instead of an opaque traceback
|
| 759 |
+
raise TypeError(
|
| 760 |
+
"AsyncRolloutWorker forwards reward_funcs / tools / environment_factory to a spawned "
|
| 761 |
+
"child process, so they must be picklable. Lambdas and closures are not: use a "
|
| 762 |
+
"module-level function, functools.partial, or a callable class instance instead."
|
| 763 |
+
) from e
|
| 764 |
+
self._process = self._mp_ctx.Process(
|
| 765 |
+
target=_child_main,
|
| 766 |
+
args=(
|
| 767 |
+
self._loop_kwargs,
|
| 768 |
+
self.rollout_buffer,
|
| 769 |
+
self._model_version_value,
|
| 770 |
+
self._stop_event_mp,
|
| 771 |
+
self._child_ready_event,
|
| 772 |
+
self._heartbeat_value,
|
| 773 |
+
self._failed_event,
|
| 774 |
+
self._exception_info_queue,
|
| 775 |
+
),
|
| 776 |
+
name="grpo-rollout-worker-child",
|
| 777 |
+
daemon=True,
|
| 778 |
+
)
|
| 779 |
+
self._process.start()
|
| 780 |
+
logger.info(
|
| 781 |
+
f"AsyncRolloutWorker spawned child pid={self._process.pid}; "
|
| 782 |
+
f"waiting up to {self._child_ready_timeout}s for the ready signal"
|
| 783 |
+
)
|
| 784 |
+
# spawn re-imports torch+transformers+trl+vllm in the child — slow on cold launch. Poll
|
| 785 |
+
# liveness so an early crash surfaces immediately instead of after the full timeout.
|
| 786 |
+
deadline = time.monotonic() + self._child_ready_timeout
|
| 787 |
+
while not self._child_ready_event.wait(timeout=1.0):
|
| 788 |
+
if not self._process.is_alive():
|
| 789 |
+
exit_code = self._process.exitcode
|
| 790 |
+
self._process = None
|
| 791 |
+
raise RuntimeError(
|
| 792 |
+
f"AsyncRolloutWorker child exited during init (exitcode={exit_code}). "
|
| 793 |
+
"Check the child's stderr for the traceback."
|
| 794 |
+
)
|
| 795 |
+
if time.monotonic() >= deadline:
|
| 796 |
+
raise RuntimeError(
|
| 797 |
+
f"AsyncRolloutWorker child did not signal ready within {self._child_ready_timeout}s."
|
| 798 |
+
)
|
| 799 |
+
logger.info("AsyncRolloutWorker child is ready")
|
| 800 |
+
|
| 801 |
+
def check_health(self, stale_after_s: float) -> None:
|
| 802 |
+
"""Raise if the child crashed or hasn't ticked the heartbeat within `stale_after_s`."""
|
| 803 |
+
if self._failed_event.is_set():
|
| 804 |
+
try:
|
| 805 |
+
type_name, msg, tb = self._exception_info_queue.get_nowait()
|
| 806 |
+
cause = RuntimeError(f"{type_name}: {msg}\n{tb}")
|
| 807 |
+
except queue.Empty:
|
| 808 |
+
cause = None
|
| 809 |
+
raise RuntimeError("Rollout worker child has failed; see chained exception.") from cause
|
| 810 |
+
age = time.time() - self._heartbeat_value.value
|
| 811 |
+
if age > stale_after_s:
|
| 812 |
+
raise RuntimeError(f"Rollout worker heartbeat stale: {age:.0f}s > {stale_after_s:.0f}s; child is hung.")
|
| 813 |
+
|
| 814 |
+
def stop(self) -> None:
|
| 815 |
+
if self._process is None:
|
| 816 |
+
return
|
| 817 |
+
logger.info("Stopping AsyncRolloutWorker child process...")
|
| 818 |
+
self._stop_event_mp.set()
|
| 819 |
+
# If start() raised before Process.start() returned (e.g. pickle failure during spawn),
|
| 820 |
+
# _popen is None and .join() would assert — skip cleanly.
|
| 821 |
+
if self._process._popen is not None:
|
| 822 |
+
self._process.join(timeout=15)
|
| 823 |
+
if self._process.is_alive():
|
| 824 |
+
logger.warning("Child did not exit within 15s; terminating.")
|
| 825 |
+
self._process.terminate()
|
| 826 |
+
self._process.join(timeout=5)
|
| 827 |
+
if self._process.is_alive():
|
| 828 |
+
self._process.kill()
|
| 829 |
+
self._process = None
|