📚 Custom Datasets
There are three ways to connect a custom dataset. Each gives more control over the preprocessing function than the last, and is harder to set up:
- [Recommended] Pass files or a dataset directory directly through
--dataset. The format converter detects the storage format from column names, and the preprocessor converts raw fields into the standard format. Different field names can be mapped with--columns, and common aliases are recognized automatically. No code is needed. - Use an external
dataset_info.jsonto declare the dataset's ID, path, subsets, split and column mapping, load it with--custom_dataset_info, then select it with--dataset <registered name>. The installed package does not need to be modified. - Subclass
DatasetLoaderandPreprocessor, customize the row-by-row conversion in Python, and load the registered content with--external_plugins. Options one and two are both implemented through the registration mechanism of option three; the registration just happens automatically.
The data flow is: raw files or Hub dataset → preprocessor converts raw fields into the standard format (non-standard column names are detected and renamed by the format converter based on column names) → validate messages and the additional columns → template encoding → batch. The preprocessor is responsible for fields and sample structure; the template is responsible for the tokens, media inputs and loss mask the model needs. Do not concatenate model-specific special tokens by hand inside the preprocessor.
📚 Pass data directly
Save the following two lines as train.jsonl. Each line of a JSONL file is an independent JSON object; do not wrap the file in an outer array:
{"messages": [{"role": "user", "content": "你是谁?"}, {"role": "assistant", "content": "我是一个有用的助手。"}]}
{"messages": [{"role": "user", "content": "1+1 等于几?"}, {"role": "assistant", "content": "等于 2。"}]}CUDA_VISIBLE_DEVICES=0 swift sft \
--model Qwen/Qwen3.5-4B \
--torch_dtype bfloat16 \
--attn_impl flash_attention_2 \
--dataset ./train.jsonl \
--tuner lora \
--learning_rate 1e-4 \
--max_length 2048 \
--num_train_epochs 3 \
--output_dir output/custom-dataMultiple paths can be passed: --dataset ./a.jsonl ./b.jsonl. Hub datasets use ms://org/dataset or hf://org/dataset; #600 means sample 600 rows; subsets are selected with dataset:subset1/subset2. The three can be combined as hf://org/name:sub1/sub2#500. Local paths must exist; do not decorate a local file with a Hub prefix.
Read formats: .jsonl and .json are read line by line directly; .csv, .parquet, .txt and so on are handed to the datasets builder, and empty CSV cells are kept as empty strings rather than NaN; dataset directories (including Hub snapshots) are read as Arrow. The reader implementation is in storage; common formats do not need separate registration.
📚 Standard data format
The standard row is built around messages, with other columns added per task. The table below lists what each task requires of the standard row:
| Task | Required | Optional |
|---|---|---|
| Pre-training, SFT, inference, evaluation | messages | system, tools, objects, chat_template_kwargs, channel |
| DPO, ORPO, CPO, SimPO, RM | messages + rejected_messages | margin, rejected_tools |
| KTO | messages + label | |
| PPO, GRPO, GKD and other online algorithms | messages (last turn is user) | Extra columns are passed through to the reward function |
| Sequence classification, regression | messages + label | |
| Embedding | messages + positive_messages | negative_messages, label |
| Reranker | messages + positive_messages or negative_messages |
General conventions:
roletakes one ofsystem,user,assistant,tool_call,tool_response,tool;tool_responseandtoolare equivalent.contentcannot benull.- The only keys allowed on each message are
role,content,loss,loss_scaleandreasoning_content; other keys are removed during preprocessing. - The system message is optional. A system message in the data takes precedence over the command-line
--system; if neither is given, the template default is used. - Multimodal media is written inside a message's
contentusing OpenAI content parts. This is the standard form; see Multimodal. Top-levelimages/videos/audioscolumns combined with<image>placeholders are the compatible form; see Compatible common formats below. Only one of the two can be used in a single row; using both together raises an error. - Unrecognized columns are not deleted. They are passed through with the sample to the reward function, metrics and other downstream components.
- Message order: user and assistant messages are not required to alternate strictly. Several system messages may be written in a row at the beginning; they are merged into one in order at encoding time (separated by blank lines). system messages can only appear at the beginning; one in the middle raises an error. A turn consists of several user/tool messages followed by one assistant reply: several consecutive user messages, or a user message right after a tool result, are each rendered as a separate conversation turn by the official template and are not merged. Several consecutive assistant messages are treated as one reply, with their content concatenated. When the row ends on a user/tool message with no reply, it is rendered as an inference prompt.
📖 Pre-training
messages contains a single assistant message, and the whole text takes part in the loss:
{"messages": [{"role": "assistant", "content": "预训练的文本在这里"}]}
{"messages": [{"role": "assistant", "content": "教练我要打篮球"}]}🏋️ Supervised fine-tuning
{"messages": [{"role": "system", "content": "你是一个有用无害的助手"}, {"role": "user", "content": "告诉我明天的天气"}, {"role": "assistant", "content": "明天天气晴朗"}]}
{"messages": [{"role": "user", "content": "1+1 等于几"}, {"role": "assistant", "content": "等于 2"}, {"role": "user", "content": "再加 1 呢"}, {"role": "assistant", "content": "等于 3"}]}- loss: written on an assistant message; decides whether that turn's reply takes part in the loss.
falseforces no loss,trueforces loss, and leaving it out follows the base policy of the command-line--loss_scale(defaultsupervises all assistant replies,last_roundsupervises only the last turn,allsupervises the whole sequence). It only takes effect on assistant messages. - loss_scale: written on an assistant message; a numeric weight. When the turn takes part in the loss, every token of that turn's reply is multiplied by this weight, and the weighting configuration selected through
--loss_scale(for exampleignore_empty_think, which down-weights empty think blocks) is no longer applied segment by segment. Writing it on a turn withloss: falsehas no effect. To use non-binary weights such as 0.5 or 2.0, set--is_binary_loss_scale false; otherwise the weight is binarized into whether the loss is computed, and lowering or raising the weight cannot be expressed. - Consecutive tool_call: several
tool_callmessages are merged into one assistant message, andloss/loss_scaleare taken only from the first one. - reasoning_content: written on an assistant message; folded into a think block at encoding time, consistent with the template convention at deployment.
Message role
├─ non-assistant (system / user / tool...) ──► weight 0 (unless the base policy is all)
└─ assistant
│
▼
Message-level loss field
├─ false ──► weight 0
├─ true ──► takes part in the loss, go to the next step
└─ unset ──► decided by the --loss_scale base policy
├─ default : all assistant turns take part
├─ last_round : only the last turn takes part, the rest weight 0
└─ all : all take part (for pre-training)
│
▼
Message-level loss_scale field
├─ has value w ──► weight of all tokens in the turn = w, skip the weighting configuration below
└─ unset ──► --loss_scale weighting configuration chain (processed segment by segment in + order, weights multiplied)
├─ ignore_empty_think: empty think block weight 0
├─ react / hermes / qwen / agentflan / alpha_umi: segment weights for Agent formats
│ (e.g. react: Action / Action Input 2.0, Thought / Final Answer 1.0, Observation content 0)
└─ no configuration selected: weight 1.0
│
▼
--is_binary_loss_scale
├─ true (automatic when all weights are 0/1) ──► expressed with labels (-100), loss_scale field not emitted
└─ false ──────────────────────► loss_scale field emitted per token (needed for non-binary weights)--loss_scale is written as base policy+weighting configuration, for example last_round+hermes+ignore_empty_think. --enable_channel_loss only affects the grouped loss statistics and does not change token weights.
{"messages": [{"role": "user", "content": "你好"}, {"role": "assistant", "content": "你好,有什么可以帮助你的吗?", "loss": false}, {"role": "user", "content": "1+1 等于几?"}, {"role": "assistant", "content": "等于 2", "loss": true}]}
{"messages": [{"role": "user", "content": "hello!"}, {"role": "assistant", "content": "<think>\n...\n</think>\n", "loss_scale": 0.5}, {"role": "assistant", "content": "hi!", "loss_scale": 2.0}]}think (reasoning content). There are two ways to write reasoning content in training data: in the reasoning_content field of an assistant message, or directly in a think block inside content (such as "<think>...</think>"). Use only one of the two; having both raises an error. At encoding time the template folds reasoning_content into a think block using the target model's markers (<think>...</think> for the Qwen3 series; Gemma and other models have their own markers), so switching models does not require changing the data. If you write the think block directly, it must match the target model's format.
{"messages": [{"role": "user", "content": "1+1 等于几"}, {"role": "assistant", "reasoning_content": "简单的加法,结果是 2。", "content": "等于 2"}]}The encoding rule depends on the model type and falls into two categories:
- Hybrid thinking models (Qwen3, Qwen3-Omni, Intern-S1, DeepSeek-V4, etc.; the template declares an empty think block): during training, if the last assistant reply does not start with a think block, the model's empty think block is automatically prepended (
<think>\n\n</think>\n\nfor the Qwen3 series), which matches how the official template renders it. This lets SFT data without reasoning be trained directly. It is added only to the last turn, not to earlier turns. Turn this off with--add_non_thinking_prefix false. When the template is built, theignore_empty_thinkpolicy is appended automatically so that this auto-added empty think block does not take part in the loss, which keeps the model from learning to emit empty reasoning. Turn this off with--disable_ignore_empty_think true; a policy written explicitly in--loss_scaleis not appended again. - Other thinking models (QwQ, Qwen3-Thinking, Qwen3.5, DeepSeek-R1, etc.): no empty think block is added, and the last turn is rendered as it appears in the data. The data should contain the full reasoning.
The think block is part of the assistant reply. By default it takes part in the loss together with the main text (weight 1) and is controlled by the message-level loss/loss_scale. Whether the think blocks of earlier turns are kept is decided by preserve_thinking. By default during training, they are kept when the --loss_scale base policy is not last_round (earlier turns are also supervised); otherwise they are stripped and only the last turn keeps its think block. At inference time --enable_thinking only controls the generation prefix: thinking-only models (QwQ, DeepSeek-R1) always get <think>, and models that support both thinking and non-thinking get the model's empty think block only when thinking is explicitly disabled. Neither affects the training data. Both can be overridden per sample through the sample's chat_template_kwargs.
chat_template_kwargs: sample-level template arguments. They only apply to the current sample and take precedence over the command-line settings of the same name (--enable_thinking, --max_pixels, etc.). reasoning_effort is not a command-line argument and can only be written into this dictionary as a template argument (see the table below). With --template_backend jinja, the whole dictionary is passed as-is to the processor's bundled jinja template, so any argument the official template accepts can be written here.
Arguments supported by all models:
| Argument | Value | Effect |
|---|---|---|
enable_thinking | bool | Whether thinking is enabled for the current sample; see the think section above |
preserve_thinking | bool | Whether think blocks of earlier turns are kept |
response_prefix | str | Overrides the generation prefix, i.e. the text automatically added at the start of the assistant reply |
max_pixels | int | Common to multimodal models: images are scaled proportionally to no more than this many pixels |
Model-specific arguments:
| Model | Argument | Value | Effect |
|---|---|---|---|
| Qwen2-VL, Qwen2.5-VL, Qwen3-VL | min_pixels, max_pixels, resized_height, resized_width | int | Image preprocessing, passed through to qwen_vl_utils.fetch_image |
| Qwen2-VL, Qwen2.5-VL, Qwen3-VL | min_pixels, max_pixels, total_pixels, fps, nframes, sample_fps, resized_height, resized_width | int / float | Video frame extraction and scaling, passed through to qwen_vl_utils.fetch_video |
| Qwen2-Audio, Qwen2.5-Omni, Qwen3-Omni | sampling_rate | int, defaults to the processor's sampling rate | Audio resampling rate |
| DeepSeek-V4 | reasoning_effort | max, high, null | max adds the highest-reasoning-effort hint before the system message; null disables thinking |
| GLM-5.2 | reasoning_effort | max, high, default max | Adds Reasoning Effort: Max/High before the system message |
Hunyuan V3 (hy_v3_preview) | reasoning_effort | high, low, no_think | Reasoning mode written into the system message; no_think disables thinking |
| Kimi K3 | thinking_effort (alias reasoning_effort) | low, high, max | Renders the thinking-effort system message |
| MiniMax-M3 | thinking_mode | enabled, disabled, adaptive, default disabled | Thinking mode; disabled is equivalent to disabling thinking |
| DeepSeek-OCR | ocr_output_dir | str, default ./ocr_output | Output directory for images in the inference results |
| PaddleOCR-VL 1.5 | shortest_edge, longest_edge | int | size argument of the image processor |
{"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "/data/rabbit.png"}}, {"type": "text", "text": "这是什么"}]}, {"role": "assistant", "content": "这是一只兔子"}], "chat_template_kwargs": {"max_pixels": 1048576}}
{"messages": [{"role": "user", "content": "你是谁?"}], "chat_template_kwargs": {"enable_thinking": false}}channel loss: after setting --enable_channel_loss true, the loss is gathered in groups by the sample's channel column; samples without a channel go into the default group. It is compatible with packing, padding_free and loss_scale.
{"messages": [{"role": "user", "content": "告诉我明天的天气"}, {"role": "assistant", "content": "明天天气晴朗"}], "channel": "general"}
{"messages": [{"role": "user", "content": "1+1 等于几"}, {"role": "assistant", "content": "等于 2"}], "channel": "math"}🖼️ Multimodal
Multimodal data uses the format above; the only change is that a message's content goes from a string to a list of OpenAI content parts. Text uses {"type": "text", "text": ...}; images, videos and audio use {"type": "image_url", "image_url": {"url": ...}}, video_url and audio_url respectively, where url is a local path or a URL. Absolute paths are recommended. The position of the media inside content is where it is inserted into the conversation; at encoding time it is replaced with the model's media tokens. The model must support the corresponding modality.
{"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "/data/cat.png"}}, {"type": "text", "text": "图片中是什么?"}]}, {"role": "assistant", "content": "一只猫。"}]}
{"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "/data/cat.png"}}, {"type": "image_url", "image_url": {"url": "/data/dog.png"}}, {"type": "text", "text": "两张图片有什么区别"}]}, {"role": "assistant", "content": "前一张是小猫,后一张是小狗"}]}
{"messages": [{"role": "user", "content": [{"type": "audio_url", "audio_url": {"url": "/data/speech.mp3"}}, {"type": "text", "text": "语音说了什么"}]}, {"role": "assistant", "content": "今天天气真好"}]}
{"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "/data/elephant.jpg"}}, {"type": "text", "text": "图片中是什么,"}, {"type": "video_url", "video_url": {"url": "/data/dog.mp4"}}, {"type": "text", "text": "视频中是什么"}]}, {"role": "assistant", "content": "图片中是一头大象,视频中是一只小狗在草地上奔跑"}]}- A shorthand that puts the address directly under the type name is also accepted:
{"type": "image", "url": ...}or{"type": "image", "path": ...}; the same applies tovideoandaudio. - To pass base64 directly, use a data URI:
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,<base64>"}}; the same applies to videos and audio. - Media paths must be visible to the process that actually performs the encoding. In remote training, a path on the client's local machine does not automatically become a path the server can read.
messages,rejected_messagesandpositive_messagesfor preference, sequence classification, Embedding and other tasks can also contain content parts.
🎯 Preference data (DPO / ORPO / CPO / SimPO / RM)
messages is the chosen conversation and rejected_messages is the rejected conversation. It is a complete conversation and can contain content parts just like messages. The rejected conversation does not inherit any column of the chosen one; system, tools and media must all be written inside rejected_messages. Add rejected_tools only when the tool set differs from the chosen one:
{"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "/data/cat.png"}}, {"type": "text", "text": "这是什么"}]}, {"role": "assistant", "content": "这是一只小猫。"}], "rejected_messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "/data/dog.png"}}, {"type": "text", "text": "这是什么"}]}, {"role": "assistant", "content": "这是一只小狗。"}]}The rejected side of a multi-turn or Agent trajectory is likewise given as a complete conversation in rejected_messages; reused tool calls and their returns must be included explicitly:
{"tools": [{"type": "function", "function": {"name": "get_aqi", "description": "查询城市的空气质量指数。", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}], "messages": [{"role": "user", "content": "北京当前的空气质量指数是多少?"}, {"role": "tool_call", "content": {"name": "get_aqi", "arguments": {"city": "北京"}}}, {"role": "tool_response", "content": "{\"aqi\": 50}"}, {"role": "assistant", "content": "北京当前的空气质量指数是 50。"}], "rejected_messages": [{"role": "user", "content": "北京当前的空气质量指数是多少?"}, {"role": "tool_call", "content": {"name": "get_aqi", "arguments": {"city": "北京"}}}, {"role": "tool_response", "content": "{\"aqi\": 50}"}, {"role": "assistant", "content": "北京当前的空气质量指数是 100。"}]}- RM training can additionally provide a
margincolumn (float) as the margin of that preference pair. - To check the final encoded result of the chosen and rejected sides, see the template documentation: after building the template, run
template.set_mode('rlhf'), thenencodethe sample and decodechosen_labelsandrejected_labelsseparately.
🎯 KTO
label is a boolean or a 0/1 integer that marks the reply as chosen or rejected. KTO is an unpaired algorithm: each row has a single completion and rejected_messages is not used. The KL reference point needed by the loss is constructed by the training loop by mismatching replies from other rows in the batch, so it does not need to be provided in the data:
{"messages": [{"role": "user", "content": "告诉我明天的天气"}, {"role": "assistant", "content": "我不知道"}], "label": false}
{"messages": [{"role": "user", "content": "1+1 等于几"}, {"role": "assistant", "content": "等于 2"}], "label": true}🎯 PPO / GRPO
Only the prompt is provided: messages ends with a user message. If an assistant reply is attached at the end, it is removed automatically and only the part up to the last user message is kept. The removed reply is not used as a reference answer; reference answers should go in an extra column. SFT-format data can therefore be reused directly:
{"messages": [{"role": "system", "content": "你是一个有用无害的助手"}, {"role": "user", "content": "告诉我明天的天气"}]}
{"messages": [{"role": "user", "content": "1+1 等于几"}, {"role": "assistant", "content": "等于 2"}, {"role": "user", "content": "再加 1 呢"}]}
{"messages": [{"role": "user", "content": "计算 1+1,将答案写在 \\boxed{} 中。"}], "solution": "2"}Extra columns are passed through with the sample to the reward function. The reward function is a RewardRule subclass whose __call__(self, trajectories, **kwargs) returns a list of scores with the same length as trajectories. Each element of trajectories is a dict:
| Field | Content |
|---|---|
messages | The complete conversation; the last assistant message is the generated reply |
tools, objects, chat_template_kwargs, images/videos/audios | Columns of the same name in the dataset |
user_data | Task-specific fields |
response_token_ids | Token ids of the reply generated by the rollout; not a dataset column. A reward function can use it to count tokens |
self.completion(t) returns the reply text. Extra columns that built-in components read by convention:
| Column | Read by |
|---|---|
solution | Reference answer for the math, accuracy, cosine, soft_overlong, react_format and toolbench rewards |
teacher_prompt | Privileged prompt for distillation and GKD online batches: a string holding the teacher model's privileged information, such as the question plus a reference solution |
test_cases + language, or verification_info | The code_execution reward |
{"messages": [{"role": "user", "content": "1+1 等于几"}], "solution": "2", "teacher_prompt": "1+1 等于几?参考解答:1+1=2。请作答。"}
{"messages": [{"role": "user", "content": "写一个函数,读入两个整数,输出它们的和"}], "test_cases": {"inputs": ["1 2\n", "10 20\n"], "outputs": ["3", "30"]}, "language": "python"}
{"messages": [{"role": "user", "content": "写一个函数,读入两个整数,输出它们的和"}], "verification_info": {"language": "cpp", "test_cases": [{"input": "1 2\n", "output": "3"}]}}Each entry of test_cases.inputs is fed to the program as stdin in order, and outputs is the expected stdout. The score is the fraction of cases that pass; trailing whitespace on each line and leading/trailing blank lines are ignored during comparison. language can be python, c, cpp or javascript and defaults to --code_language. verification_info is the native column of the OpenR1 verifiable-coding dataset and comes with language; when both columns exist, test_cases wins. Either column can be written as a JSON string.
Save the following as my_reward.py and load it with --external_plugins ./my_reward.py --orm my_reward:
from typing import List
from swift.dev.reward import RewardRule
from swift.dev.utils.plugin import PluginRegistry
@PluginRegistry.register('reward', 'my_reward')
class MyReward(RewardRule):
def __call__(self, trajectories, **kwargs) -> List[float]:
scores = []
for t in trajectories:
answer = self.column(t, 'solution')
scores.append(1.0 if answer and answer in self.completion(t) else 0.0)
return scoresReference answers should not be concatenated into the user input. For how rewards are registered, the async form and reward models, see the plugin documentation.
🎯 GKD
The data format is the same as supervised fine-tuning; messages contains the full teacher reply. --lmbda is the probability that each batch uses student online generations (on-policy); the remaining batches use the replies in the dataset (off-policy), so the replies in the dataset are not removed.
🏷️ Sequence classification
label is a scalar or a list, decided by --task_type seq_cls and the model head:
{"messages": [{"role": "user", "content": "这个包装很差,容易被调包。"}], "label": 0}
{"messages": [{"role": "user", "content": "质量很好,物流也快,满意。"}], "label": 1}
{"messages": [{"role": "user", "content": "今天天气真好呀"}], "label": [0, 2]}
{"messages": [{"role": "user", "content": "求两句话的相似度,范围为 0-1。\nsentence1: 今天天气真好\nsentence2: 今天是个晴天"}], "label": 0.8}
{"messages": [{"role": "user", "content": "评价这段文字"}], "label": [1.2, -0.6, 0.8]}These are, in order, single-label, multi-label, single-regression and multi-regression tasks. For multi-label tasks label is a list of class indices; for multi-regression tasks label is a list of floats.
Multimodal classification is also supported: write content parts in messages (images with image_url, videos with video_url, audio with audio_url; see Multimodal for the syntax) and choose a multimodal model tagged vision / video / audio that supports seq_cls. Encoding takes the same media path as SFT, and media tokens enter the sequence before the classification head:
{"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "/data/dining.jpg"}}, {"type": "text", "text": "这张图适合做餐厅广告吗?"}]}], "label": 1}🧭 Embedding
messages is the anchor, positive_messages holds the positives and negative_messages holds the hard negatives. Positives and negatives are both lists of conversations, and each element is one complete conversation. label is optional and is the similarity score between the anchor and the positive (default 1.0); the score of each negative is 0.0. Training uses only the first positive:
{"messages": [{"role": "user", "content": "这个包装很差,容易被调包。"}], "positive_messages": [[{"role": "user", "content": "这是一条负面评价,表示不满意。"}]], "negative_messages": [[{"role": "user", "content": "这是一条正面评价,表示满意。"}]]}
{"messages": [{"role": "user", "content": "一个人在弹吉他。"}], "positive_messages": [[{"role": "user", "content": "有人在演奏乐器。"}]], "label": 0.9}Contrastive losses such as InfoNCE use the other samples in the batch as extra negatives, so training works without negative_messages. See examples/v5/train/embedding for an example.
Multimodal embedding is also supported; choose a multimodal embedding model (such as Qwen/Qwen3-VL-Embedding-2B or iic/gme-Qwen2-VL-2B-Instruct). The anchor, positive and negative conversations can all contain content parts, written the same way as SFT multimodal data, and the anchor and candidates can be in different modalities (text-to-image or image-to-text search):
{"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "/data/dog.png"}}]}], "positive_messages": [[{"role": "user", "content": "一只狗在草地上奔跑"}]], "negative_messages": [[{"role": "user", "content": "一只猫在沙发上睡觉"}]]}📊 Reranker
messages is the query; positive_messages and negative_messages are candidate documents, and at least one must be provided. Each candidate is one complete conversation, concatenated after the query at encoding time. Positives are labeled 1 and negatives 0. The query's system message serves as the instruction for the whole input:
{"messages": [{"role": "user", "content": "什么是深度学习?"}], "positive_messages": [[{"role": "assistant", "content": "深度学习是机器学习的一个分支。"}]], "negative_messages": [[{"role": "assistant", "content": "今天天气晴朗。"}]]}See examples/v5/train/reranker for an example.
Multimodal rerankers are also supported; choose a multimodal reranker model (such as Qwen/Qwen3-VL-Reranker-2B). Both the query and the candidate documents can contain content parts. At encoding time the query and the candidates are concatenated into one sequence, and the media on the query side and the candidate side are fed to the model together in order, so cross-modal queries are possible (a text query retrieving images, or an image query retrieving text):
{"messages": [{"role": "user", "content": "一段适合做桌面壁纸的风景"}], "positive_messages": [[{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "/data/lake.jpg"}}]}]], "negative_messages": [[{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "/data/office.jpg"}}]}]]}📍 grounding
Object detection, localization and similar tasks can be written in two ways.
-
Use the model's native grounding format directly and write the model's special tokens in the
assistantreply, for example<|object_ref_start|>...<|object_ref_end|><|box_start|>(x1,y1),(x2,y2)<|box_end|>for Qwen3-VL. Special tokens and whether coordinates are normalized differ between models, so the data must be prepared according to the target model's convention. -
Use the unified grounding format: put
<ref-object>and<bbox>placeholders in the reply and add anobjectscolumn. At encoding time they are replaced with the model's own format and coordinate normalization is handled:
{"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "/data/beach.jpg"}}, {"type": "text", "text": "描述图像"}]}, {"role": "assistant", "content": "<ref-object><bbox>和<ref-object><bbox>正在沙滩上玩耍"}], "objects": {"ref": ["一只狗", "一个女人"], "bbox": [[331.5, 761.4, 853.5, 1594.8], [676.5, 685.8, 1099.5, 1427.4]]}}
{"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "/data/sheep.jpg"}}, {"type": "text", "text": "找到图像中的<ref-object>"}]}, {"role": "assistant", "content": "<bbox><bbox>"}], "objects": {"ref": ["羊"], "bbox": [[90.9, 160.8, 135, 212.8], [360.9, 480.8, 495, 532.8]]}}
{"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "/data/desktop.png"}}, {"type": "text", "text": "帮我打开谷歌浏览器"}]}, {"role": "assistant", "content": "Action: click(start_box='<bbox>')"}], "objects": {"ref": [], "bbox": [[615, 226]]}}Fields of objects:
ref: list of strings that replace<ref-object>in order; its length must equal the number of placeholders.bbox: list that replaces<bbox>in order; its length must equal the number of placeholders. An element of length 4 denotes two corner points(x1, y1, x2, y2); an element of length 2 denotes a single point.<ref-object>and<bbox>are replaced independently and have no correspondence with each other.bbox_type:real(default, pixel coordinates) ornorm1(already normalized to 0~1).image_id: list of integers. Only takes effect whenbbox_typeisreal; it indicates which image each bbox belongs to, starting from 0, and defaults to 0. For multi-image grounding its length must matchbbox.
With the unified format, image scaling and coordinates are handled together by the template and can be combined with --max_pixels or the sample-level chat_template_kwargs.max_pixels.
🤖 Agent
{"tools": [{"type": "function", "function": {"name": "realtime_aqi", "description": "获取实时空气质量。", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "城市名,例如:上海"}}, "required": ["city"]}}}], "messages": [{"role": "user", "content": "北京和上海今天的天气情况"}, {"role": "tool_call", "content": {"name": "realtime_aqi", "arguments": {"city": "北京"}}}, {"role": "tool_call", "content": {"name": "realtime_aqi", "arguments": {"city": "上海"}}}, {"role": "tool_response", "content": "{\"city\": \"北京\", \"aqi\": \"10\"}"}, {"role": "tool_response", "content": "{\"city\": \"上海\", \"aqi\": \"72\"}"}, {"role": "assistant", "content": "根据天气预报工具,北京今天的空气质量指数为 10,属于良好水平;上海今天的空气质量指数为 72,属于轻度污染水平。"}]}toolsis the list of tool definitions, and can also be a JSON string of the whole list. At encoding time it is combined with the system message into the complete system section.- The
contentof atool_callmessage is a{"name": ..., "arguments": ...}object; a JSON string is also accepted. Consecutivetool_callmessages are converted and merged into one assistant message by the agent_template, which supports parallel calls. tool_responseis equivalent totool; the agent_template converts the format. No loss is computed on it during training, and it acts like a user message.- The data can also be prepared directly as
messagescontaining only system, user and assistant messages; the agent_template's role is only to maptools,tool_callandtool_responseautomatically into this form. See Agentic training for more.
🔁 Compatible common formats
When the data is not in the standard format above, the format converter converts it automatically during preprocessing. The converter decides the format from column names only, then rewrites each row according to the shape of its content. Four converters are built in, listed from highest to lowest detection priority:
| Converter | Detection condition | What it handles |
|---|---|---|
openai | Has a messages, conversation or conversations column | sharegpt, OpenAI tool_calls, OpenAI multimodal content parts, Anthropic content blocks |
preference | Has a chosen or rejected column | Top-level preference pairs |
alpaca | Has both instruction and input columns | instruction and input merged into the user input |
response | Fallback: has a response column or an alias of it | query, response and multi-turn history |
All of the following formats are converted into the standard messages and can be connected directly with --dataset. The implementation is in format_converter.
sharegpt format. Column name conversation or conversations, role key role or from, content key content or value; each item is one message, or a {"user": ..., "assistant": ...} pair:
{"conversation": [{"human": "你好", "gpt": "你好!"}, {"human": "1+1?", "gpt": "2"}]}
{"conversations": [{"from": "system", "value": "你是一个有用的助手"}, {"from": "human", "value": "你好"}, {"from": "gpt", "value": "你好!"}]}Aliases of role values are mapped automatically: user, human → user; assistant, gpt, bot, chatgpt → assistant; tool_call, function_call → tool_call; tool_response, tool, function_response, observation, observations → tool_response; system → system. loss, loss_scale and reasoning_content on each message are kept.
OpenAI tool call format. The tool_calls of an assistant message are expanded into several tool_call messages whose content is a {"name": ..., "arguments": ...} object; arguments is parsed when it is a JSON string. When the assistant's own content is not empty, it is kept as an assistant message immediately before them:
{"messages": [{"role": "user", "content": "天气如何?"}, {"role": "assistant", "content": null, "tool_calls": [{"type": "function", "function": {"name": "get_weather", "arguments": "{\"city\":\"Beijing\"}"}}]}, {"role": "tool", "content": "晴"}]}OpenAI multimodal content parts. When content is a list of {"type": "text"|"image_url"|"video_url"|"audio_url", ...}, the *_url blocks are rewritten in their original order into <image>, <DocumentationVideo> and <audio> placeholders, and the media addresses are lifted to the top-level images, videos and audios columns for the template to encode:
{"messages": [{"role": "user", "content": [{"type": "text", "text": "比较这两张图片。"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,<base64>"}}, {"type": "image_url", "image_url": {"url": "https://example.com/input.png"}}]}, {"role": "assistant", "content": "我来检查。"}]}Anthropic content blocks. When content consists of text, tool_use, tool_result or image blocks: tool_use is expanded into a tool_call message and tool_result into a tool_response message; an image block is converted into the standard multimodal content part, a base64 source becomes a data: URI, and a URL source is kept as is:
{"messages": [{"role": "user", "content": [{"type": "text", "text": "图片中有什么?"}, {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "<base64>"}}]}, {"role": "assistant", "content": [{"type": "tool_use", "id": "toolu_01", "name": "inspect_image", "input": {}}]}, {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_01", "content": "阳光明媚的海滩。"}]}]}query-response format:
{"system": "你是一个有用的助手", "query": "1+1 等于几?", "response": "等于 2", "history": [["你好", "你好!"]]}
{"prompt": "你好", "completion": "你好!"}
{"instruction": "翻译为英文", "input": "你好", "output": "Hello"}history is a list of [query, response] pairs, expanded in order into earlier turns, and the current query/response becomes the last turn. When response is empty, the last turn has no assistant message, and the row can be used as an inference input or an online RL prompt. When response is a list, the first answer is used by default; set the environment variable RANDOM_DATASET_RESPONSE=true to pick one at random. The following column names are converted automatically into the corresponding standard column:
- system:
system,system_prompt. - query:
query,prompt,input,instruction,question,problem. - response:
response,answer,output,targets,target,answer_key,answers,solution,text,completion,content.
alpaca format. Requires both instruction and input columns, with output as the response; when input is not empty, query = instruction + "\n" + input.
chosen / rejected preference format. When the top-level chosen is a list of messages it becomes messages, otherwise it becomes the last reply; when rejected is a list of messages it becomes rejected_messages, otherwise it becomes rejected_response:
{"chosen": [{"role": "user", "content": "1+1?"}, {"role": "assistant", "content": "2"}], "rejected": [{"role": "user", "content": "1+1?"}, {"role": "assistant", "content": "3"}]}
{"prompt": "1+1?", "chosen": "2", "rejected": "3"}rejected_response shorthand. When the chosen and rejected sides share the same prompt, skip rejected_messages and use rejected_response to write only the rejected reply, which can be a string or a list of messages that contains no user role. At encoding time, all messages after the last user message in messages are replaced to form the rejected conversation, and the chosen side's system, tools and media (including top-level images and similar columns) are inherited. An error is raised when the single reply is identical to the chosen one:
{"messages": [{"role": "system", "content": "你是一个有用无害的助手"}, {"role": "user", "content": "告诉我明天的天气"}, {"role": "assistant", "content": "明天天气晴朗"}], "rejected_response": "我不知道"}
{"messages": [{"role": "user", "content": "1+1 等于几"}, {"role": "assistant", "content": "等于 2"}, {"role": "user", "content": "再加 1 呢"}, {"role": "assistant", "content": "等于 3"}], "rejected_response": [{"role": "assistant", "content": "等于 4"}]}Top-level media columns. Instead of writing media inside content, put it in the row's top-level images, videos and audios columns (lists of paths or URLs) and match them in order of appearance with the <image>, <DocumentationVideo> and <audio> placeholders in the message text:
{"messages": [{"role": "user", "content": "<image>图片中是什么?"}, {"role": "assistant", "content": "一只猫。"}], "images": ["/data/cat.png"]}
{"messages": [{"role": "user", "content": "<image><image>两张图片有什么区别"}, {"role": "assistant", "content": "前一张是小猫,后一张是小狗"}], "images": ["/data/cat.png", "/data/dog.png"]}
{"messages": [{"role": "user", "content": "<image>这是什么"}, {"role": "assistant", "content": "这是一只小猫。"}], "rejected_response": "这是一只小狗。", "rejected_images": ["/data/dog.png"]}Built-in datasets and most examples still use this form. base64 also uses data URIs. Media for the rejected side of preference data is specified with rejected_images, which only takes effect with the rejected_response form, because rejected_messages does not inherit top-level columns. The singular column names image, video and audio are mapped to the plural automatically.
📚 Column name mapping
Column name mapping is specified explicitly with --columns; the direction is always "original column name → standard column name":
swift sft --model Qwen/Qwen3.5-4B \
--attn_impl flash_attention_2 \
--dataset ./data.jsonl \
--columns '{"question_text":"query","answer_text":"response"}' \
--output_dir output/columnsMapping rules: when a column name is defined in two places, --columns wins; when several column names map to the same standard name, the one declared first wins (in the order: singular media aliases, converter built-in aliases, --columns). When a row already has the standard column name, aliases do not override it. The singular image, video and audio columns are mapped to images, videos and audios in every format.
📚 dataset_info.json
Save data.jsonl and dataset_info.json in the same directory:
[
{
"dataset_type": "my_qa",
"dataset_path": "data.jsonl",
"columns": {"prompt": "query", "completion": "response"}
},
{
"ms_dataset_id": "swift/alpaca-gpt4-data-zh",
"hf_dataset_id": "swift/alpaca-gpt4-data-zh",
"subsets": ["default"],
"split": ["train"],
"columns": {"input": "query", "output": "response"}
}
]swift sft --model Qwen/Qwen3.5-4B \
--attn_impl flash_attention_2 \
--custom_dataset_info ./dataset_info.json \
--dataset my_qa \
--output_dir output/registered-dataEach entry provides at least one of ms_dataset_id, hf_dataset_id and dataset_path; unrecognized keys raise an error:
| Key | Description |
|---|---|
dataset_type | Registered name, used by --dataset to select the dataset. Defaults to the last segment of the ID or path |
ms_dataset_id / hf_dataset_id | ModelScope / HuggingFace dataset ID; only one needs to be provided |
dataset_path | Local file or directory. Relative paths are resolved against the directory containing dataset_info.json |
subsets | List of subset names; or a list of objects, each of which may contain subset (Hub subset name), name (name used on the command line, defaults to subset), split, columns and preprocessor |
split | List of splits to load, default ["train"]; split in a subset object takes precedence |
columns | Column mapping, original column name → standard column name; columns in a subset object takes precedence |
ms_revision / hf_revision | Pinned dataset revision |
tags | List of tags |
help | One-line description, shown when listing datasets |
huge_dataset | When true, hints to users to read the dataset in streaming mode by default |
For the built-in registry see dataset_info.json; the fields have the same meaning.
📚 Custom preprocessing
When the field structure is special and row-by-row computation is needed, subclass Preprocessor, override preprocess, and register the loader with register_dataset. Save as custom_data.py:
from swift.dev.dataset.loader import DatasetLoader, register_dataset
from swift.dev.dataset.preprocessor import Preprocessor
class QAPreprocessor(Preprocessor):
def preprocess(self, row):
question = row.get('question_text')
answer = row.get('answer_text')
if not question or not answer:
return None
return {'messages': [
{'role': 'user', 'content': question},
{'role': 'assistant', 'content': answer},
]}
@register_dataset
class MyQALoader(DatasetLoader):
dataset_type = 'my_custom_qa'
dataset_paths = ('/data/my_qa.jsonl',)
preprocessor = QAPreprocessorChange dataset_paths to the actual file, then run:
swift sft --model Qwen/Qwen3.5-4B \
--attn_impl flash_attention_2 \
--external_plugins ./custom_data.py \
--dataset my_custom_qa \
--output_dir output/preprocessed-datapreprocess(row) receives the raw row and returns the standard row. Returning None drops the row; returning a list of rows expands one row into several. Pass the preprocessor class, not an instance, at registration time; the loader creates an instance for each read to avoid sharing mutable state across tasks.
When preprocess is not overridden, the base class converts automatically with the format converter. Declare the dataset's traits through class attributes:
format_name: always use a specific converter (openai,preference,alpaca,response) instead of detecting by column names.columns: column mapping, equivalent to--columns. Written on the class, it is distributed together with the registration.converter_kwargs: arguments passed to the converter, for examplerole_key,content_key,user_roleandassistant_rolefor specifying custom role keys, content keys and role values.
To read the standard fields first and then rewrite them, call self.standardise(row) to get the renamed row. Columns to keep should be set on the row returned by preprocess, not written back under the original column names after renaming, or they will be converted again as aliases.
Declarable attributes of DatasetLoader: dataset_type (registered name, required), datasets (Hub ID; a string when the two Hubs are the same, otherwise a (ms_id, hf_id) tuple with None for the missing side), dataset_paths, subsets, split, preprocessor, columns, ms_revision, hf_revision, tags, help and huge_dataset, with the same meaning as the fields of the same name in dataset_info.json. One registered name can bind both a Hub ID and a local path.
--strict true makes bad rows raise an error directly; by default rows that cannot be converted are dropped and a diagnostic is logged. When connecting a dataset for the first time, confirm the number of valid samples after loading to prevent field errors from filtering out a large amount of data. Multi-process map, streaming and caching are controlled by --dataset_num_proc, --streaming and --load_from_cache_file respectively. See examples/v5/train/custom/dataset for a complete example.