Skip to Content
MS-SWIFT ร— TWINKLE
๐Ÿงฉ Interfaces and Components
DOCUMENTATION5.0.0.dev

๐Ÿ“ Templates

The same messages need different role markers, separators, end tokens and media handling on different models. A template converts the standard sample into model input and decides which tokens take part in the training loss. The dataset format and the model format can therefore be maintained independently.

The encoding flow is: messages and media columns โ†’ template rendering โ†’ tokenizer / processor โ†’ input_ids, labels and media tensors โ†’ batch padding or packing. Inference adds a generation prefix; training keeps the target reply and builds the supervision range. The two are not a plain copy of the same string.

๐Ÿ“ Select a template

ms-swift selects the default template from the model's registration information. It can also be specified explicitly:

swift sft --model Qwen/Qwen3.5-4B \
    --model_type qwen3_5 \
    --template qwen3_5 \
    --torch_dtype bfloat16 \
    --attn_impl flash_attention_2 \
    --dataset 'swift/self-cognition#600' \
    --max_length 2048 \
    --output_dir output/template

model_type selects the model loader and template selects the encoding protocol; neither can replace the other. A local checkpoint also needs the template that matches the original model. See swift/dev/template for the registered list.

ArgumentDefaultDescription
templateAuto-selectedUse the model's registered default template
systemTemplate defaultThe system message in the dataset takes precedence
max_lengthNoneTotal sequence length, including prompt, reply and media tokens
truncation_strategyNoneHandling of over-length samples; by default encoding reports the excess length and the data processing stage drops the sample
padding_siderightPadding direction of the batch
padding_freefalsePadding-free input; requires backend and attention implementation support
template_backendswiftswift or jinja rendering path
loss_scaledefaultToken supervision and weighting policy
enable_thinkingNoneUse the model's default thinking behavior
preserve_thinkingNoneUse the template's default behavior for keeping historical thinking

jinja uses the model's chat template; swift uses the registered template. Switching the rendering path does not automatically give the same training mask or multimodal capability; choose according to model support and the task.

๐Ÿงช Inspect the encoding result

The component API below builds only the template and its processor and does not download the base model weights:

from swift.dev.builder.template import build_template_from_spec, build_template_spec
from swift.dev.config import ModelConfig, TemplateConfig


spec = build_template_spec(
    TemplateConfig(template='qwen3_5', max_length=2048),
    ModelConfig(model='Qwen/Qwen3.5-4B', model_type='qwen3_5'),
)
template = build_template_from_spec(spec)
template.set_mode('train')
encoded = template.encode({'messages': [
    {'role': 'user', 'content': 'ไฝ ๆ˜ฏ่ฐ๏ผŸ'},
    {'role': 'assistant', 'content': 'ๆˆ‘ๆ˜ฏไธ€ไธชๆœ‰็”จ็š„ๅŠฉๆ‰‹ใ€‚'},
]})
print(encoded['input_ids'])
print(encoded['labels'])

Network access or an existing tokenizer / processor cache is required, and model-specific media dependencies must also be installed. TemplateSpec stores a serializable model reference and template settings, and workers rebuild their local template from it; do not pass a tokenizer or model instance that holds mutable state as distributed configuration.

๐Ÿงฉ Shared component interface

swift.dev.template.Template inherits from twinkle.template.Template. ms-swift keeps its original construction chain and model family registry and does not switch to twinkle's model templates. Both sides use consistent arguments for encode, batch_encode, encode_prompt, append_completion, decoding and batch hooks.

from twinkle.template.contract import TRAIN

encoded = template.encode(sample, intent=TRAIN)
rows = template.batch_encode(samples, intent=TRAIN)
prompt = template.encode_prompt(sample, backend='vllm')
continued = template.append_completion(prompt, generated_tokens)

TRAIN/INFER/ENGINE/SCORE are defined in twinkle.template.contract and also exported by swift.dev.template. The default or False uses TRAIN, and True uses INFER; inference and scoring do not return training labels. Causal labels shift left only once, and the last position is -100. The returned trajectory keeps the original conversation, media and model fields; a list batch returns a flat list, and a columnar batch returns columns of equal length.

set_template accepts an instance, a subclass carrying constructor arguments, or a registered name. Only the name and configuration travel over HTTP; ms-swift reuses the existing TemplateSpec and registers SwiftTemplate through the existing worker startup hook. Under delete, a single encode raises MaxLengthError and batch_encode drops the whole sample, with both sides of a pair handled together. A text split may return several trajectories, and encode_prompt rejects multiple results; a multimodal payload cannot be split safely. Appending generated tokens does not truncate the recorded history.

๐Ÿงฎ Supervision range and loss mask

By default SFT supervises the assistant reply. The labels at prompt and padding positions are -100 and do not take part in the cross-entropy computation.

  • default: supervise the assistant reply.
  • last_round: supervise only the last turn's reply.
  • all: widen the supervision range; suits tasks that need to train on the whole text.
  • Policies can be combined, for example default+ignore_empty_think, to avoid supervising an empty thinking prefix.

A sample can override message-level supervision:

{"messages": [{"role": "user", "content": "ไฝ ๅฅฝ"}, {"role": "assistant", "content": "ไฝ ๅฅฝ๏ผ", "loss": false}, {"role": "user", "content": "1+1๏ผŸ"}, {"role": "assistant", "content": "2", "loss_scale": 2.0}]}

loss: false excludes that reply; loss_scale sets a weight for it. To keep non-binary weights, set --is_binary_loss_scale false; otherwise 0.5 / 2.0 cannot express lowering or raising the weight. The loss mask and the attention mask mean different things: the former controls supervision positions and the latter controls which positions can be attended to. Do not replace the loss mask by deleting history messages.

๐Ÿ’ญ Thinking

enable_thinking controls whether models that support the switch add a thinking generation prefix at inference time; it does not add capability to models without reasoning ability. preserve_thinking decides whether the thinking in earlier replies is kept. The reasoning in training data is part of the target content and should be consistent with the template convention used at deployment.

swift infer --model Qwen/Qwen3.5-4B \
    --sampler transformers \
    --enable_thinking false \
    --max_new_tokens 512

enable_thinking can also be set in a sample's chat_template_kwargs, along with the media arguments the model supports. The automatic empty thinking mask can be turned off with disable_ignore_empty_think; policies written explicitly in loss_scale still take effect.

๐Ÿ–ผ๏ธ Multimodal and tool messages

{"messages": [{"role": "user", "content": "<image>ๆ่ฟฐๅ›พ็‰‡"}, {"role": "assistant", "content": "ไธ€ๅช็Œซใ€‚"}], "images": ["/data/cat.png"], "chat_template_kwargs": {"max_pixels": 1048576}}

Media placeholders correspond one to one with the top-level media list. The processor decides image scaling, video frame reading, audio features and the number of media tokens; max_length must cover the final encoded length and cannot be estimated from the visible text length alone.

A tool trajectory has the assistant issue tool calls, the tools return observations, and the assistant continue. The standard data converter handles the tool message structure, and the template renders tool definitions and calls into the model protocol. Tool observations are context and are usually not supervised as model replies; whether the tool call action is supervised is decided by the training data and the loss policy. See Agentic for examples and entry points.

๐Ÿ“„ Length and batches

Over-length data can be handled with delete, left, right or split. Deletion keeps the semantics of complete samples but reduces the sample count; truncation may remove the question or the final answer; splitting may break multi-turn, media or tool associations and needs to be checked against the task. Check the number of valid samples and whether replies are kept before adjusting the length.

packing / padding-free changes how the batch is organized, not the original message protocol. Sequence boundaries, position encoding and the loss mask must be kept with the batch, and the template and dataloader handle them. See CLI for the full arguments and M/P separation for the component division of labor.