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

๐Ÿ”Œ Plugins

Plugins replace one well-defined extension point in the training loop without rewriting the recipe. ms-swift defines the base class and registered name of each extension point, and twinkle loads the plugin source and runs the common components.

The load order is: --external_plugins imports the Python file and runs the registrations inside โ†’ Config selects by registered name โ†’ the builder constructs the object or serializable rule โ†’ the recipe uses the component. Ray workers re-import the configured external sources when they start; in multi-machine runs, every machine must be able to reach the plugin code and its dependencies.

ms-swift 5 supports code-style training: assemble Config, builders and recipe directly in Python, with the training loop fully visible. The API does not require understanding the distributed machinery; parallelism and remote execution are handled by the framework. In this form, customizing the training loop needs no plugins at all. Call components directly in the loop; see M/P separation and component-based training.

๐Ÿงฉ Extension point overview

All extension points are registered in the same --external_plugins file; the only difference is which registry is used. The first seven use PluginRegistry.register(kind, name), and the rest use their own registration function or mapping table.

Extension pointBase classRegistrationImplementationSelection argumentBuilt-in names
Reward ruleRewardRuleregister('reward', name)__call__(self, trajectories, **kwargs), may be async def--orm, --prmaccuracy, format, math, cosine, repetition, soft_overlong, react_format, toolbench, code_execution
Process reward segmentationPRMSegmentScorerregister('prm_scorer', name)build() returns a segmentation predicate--prm_scorerturn, delimiter
Training callbackTrainCallbackregister('callback', name)Override on_* event methods--callbacksearly_stop, perf_log, graceful_exit
Optimizer parameter groupingParamGroupsPluginregister('param_groups', name)__call__(self, *, train_config, tuner_config) returns grouping rules--param_groups_pluginsno_decay_embeddings
ToolToolPluginregister('tool', name)build() returns a list of tool instances--toolssandbox
harnessHarnessPluginregister('harness', name)build() returns a CliAgent--harnesscodex, ms_agent
Samplertwinkle SamplerOnly a source file path can be passed; see belowImplement the sampling engine protocol--samplervllm, sglang, transformers
ModelModelLoader@register_modelDeclare model_type, models, template, model_cls as class attributes--model_typeEach model family
Chat templateTemplateMetaregister_template(TemplateMeta(...))Describe the conversation format with {{SYSTEM}} and {{QUERY}} placeholders--templateEach model's default template
Agent templateBaseAgentTemplateWrite into agent_template_map['name']_format_tools, _format_tool_calls, _format_tool_responses, get_toolcall--agent_templatehermes, qwen3, qwen3_5, toolbench, etc.
DatasetDatasetLoader@register_datasetpreprocess(row) converts a raw row into the standard row--dataset <registered name>Built-in dataset table
Format converterFormatConverter@register_formatdetect(columns), convert(row)DatasetLoader.format_name or auto-detected by column namesopenai, preference, alpaca, response
Storage formatDatasetStorage@register_storageread, write; incremental formats also implement append--store_format; reading is detected by patharrow, jsonl, bin, orc, lance, builder
loss_scale policyLossScaleWrite into loss_scale_map['name']get_loss_scale(context, **kwargs) returns segments and weights--loss_scalebase, ignore_empty_think, react, hermes, qwen, agentflan, alpha_umi
losstwinkle Loss@register_loss('name')__call__(self, inputs, outputs, **kwargs) returns LossOutput--lossSee below

The following name tables are fixed and cannot be extended through plugins: optimizer (--optim), lr_scheduler (--lr_scheduler), tuner (--tuner), quantization method (--quant_method) and evaluation metrics. Optimizer parameter grouping can be changed through param_groups plugins.

๐Ÿ… Custom rewards

A reward rule is a RewardRule subclass. __call__ receives a list of trajectories and returns a list of scores of the same length and in the same order as the input. Each trajectory is a dict; self.completion(t) returns the reply text and self.column(t, 'solution') returns an extra column of the dataset. For the field structure see Custom datasets.

Save as my_plugin.py:

from typing import List

from swift.dev.reward import RewardRule
from swift.dev.utils.plugin import PluginRegistry


@PluginRegistry.register('reward', 'math_bonus')
class MathBonus(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 scores

A reward that calls an external API is implemented as async def __call__; no other base class is needed, and synchronous and asynchronous rewards can be mixed in the same training run. Set API timeouts and failure handling so that one unreturned scoring request does not block training. Credentials should not be written into plugins or logs.

Use the custom reward:

CUDA_VISIBLE_DEVICES=0,1 swift rl \
    --rl_type grpo \
    --model Qwen/Qwen3.5-4B \
    --attn_impl flash_attention_2 \
    --torch_dtype bfloat16 \
    --dataset 'AI-MO/NuminaMath-TIR#5000' \
    --external_plugins ./my_plugin.py \
    --orm math_bonus \
    --orm_weights 1.0 \
    --mode ray \
    --nproc_per_node 1 \
    --rollout_sampler vllm \
    --sampler_mode disaggregated \
    --generation_batch_size 2 \
    --num_generations 4 \
    --max_completion_length 512 \
    --max_length 2048 \
    --max_steps 20 \
    --output_dir output/reward-plugin

Each entry of --orm can be a registered name, a plugin class, or a reward model id. Model ids go through a separate reward model channel, with weights aligned through --orm_weights; see Command-line arguments and Online RL for the related arguments. Rewards should not depend on the order within a batch. Length-based rewards only demonstrate the interface; a real task should constrain correctness, format and invalid output together, so that the model cannot raise its score just by making answers longer.

Built-in rewards:

Registered nameScoring ruleColumns and arguments read
accuracy, mathParse the reply and the reference answer with math_verify; 1.0 if they match, otherwise 0.0solution
format1.0 if the reply contains both a think block and an answer block
react_format1.0 if the reply follows the format of a think block followed by Action and Action Input
toolbenchParse the action in the reply and compute F1 against the reference actionsolution
cosineThe reward for a correct answer decreases with length; the reward for a wrong answer increases with lengthsolution, response_token_ids; cosine_min_len_value_wrong, cosine_max_len_value_wrong, cosine_min_len_value_correct, cosine_max_len_value_correct, cosine_max_len
repetitionNegative reward proportional to the n-gram repetition ratiorepetition_n_grams, repetition_max_penalty
soft_overlongLinear negative reward inside the penalty interval; fixed at -1 beyond the upper limitresponse_token_ids; soft_max_length, soft_cache_length
code_executionExecute the code in the reply; the score is the fraction of test cases that passtest_cases + language, or verification_info; code_language, code_timeout, code_max_concurrency, code_memory_limit_gb, code_sandbox_template

๐Ÿ… Process reward segmentation

A process reward model (PRM) scores step by step, and prm_scorer decides where the trajectory is split into steps. build() returns a (sample, traj) -> bool predicate; returning True means a step ends at that position, and returning None means no segmentation.

from twinkle.data_format import last_assistant_text

from swift.dev.reward.prm import PRMSegmentScorer
from swift.dev.utils.plugin import PluginRegistry


@PluginRegistry.register('prm_scorer', 'double_newline')
class DoubleNewlineScorer(PRMSegmentScorer):
    def build(self):
        return lambda sample, traj: '\n\n' in last_assistant_text(traj)

Select it with --prm_scorer double_newline. The built-in turn treats each assistant turn as one step, and delimiter treats a turn containing --prm_step_delimiter (a newline by default) as one step. When neither is set, multi-turn rollouts use turn and everything else uses delimiter.

Each time a segment closes, each entry in --prm scores "the trajectory up to the current segment" once. The score is recorded on that segment and broadcast to the tokens it covers, then combined with the outcome reward from --orm as a convex combination weighted by --prm_orm_mix. --prm mixes rule names and model ids the same way --orm does: a rule is just a RewardRule subclass as in the previous section and needs no other base class, and in this case self.completion(t) returns the text of the step that just ended. A model id must be a scalar reward model. When --prm is set without --orm, --prm_orm_mix 1.0 is required, and it cannot be enabled together with RLSD/SDAR.

@PluginRegistry.register('reward', 'step_format')
class StepFormat(RewardRule):
    def __call__(self, trajectories, **kwargs) -> List[float]:
        return [1.0 if '<step>' in self.completion(t) else 0.0 for t in trajectories]
--orm math --orm_weights 1.0 \
--prm step_format --prm_weights 1.0 \
--prm_scorer delimiter --prm_step_delimiter '\n\n' \
--prm_orm_mix 0.5

Segmentation only decides when intermediate trajectories are scored; it does not replace the PRM model, which is likewise passed through --prm.

๐Ÿงฉ Training callbacks

A callback is a TrainCallback subclass. Override only the events you need; the rest keep the default empty implementations. Add it to the same plugin file:

from swift.dev.callback import CallbackControl, CallbackState, TrainCallback
from swift.dev.utils.plugin import PluginRegistry


@PluginRegistry.register('callback', 'progress_printer')
class ProgressPrinter(TrainCallback):
    def on_step_end(self, state: CallbackState, control: CallbackControl) -> None:
        if state.global_step % 10 == 0:
            print(f'step={state.global_step} epoch={state.epoch} loss={state.loss}')

    def on_save(self, state: CallbackState, control: CallbackControl, checkpoint_dir=None) -> None:
        print(f'saved {checkpoint_dir}')
swift sft --model Qwen/Qwen3.5-4B \
    --attn_impl flash_attention_2 \
    --dataset 'swift/self-cognition#600' \
    --external_plugins ./my_plugin.py \
    --callbacks progress_printer \
    --output_dir output/callback

CallbackState holds the read-only training position and the latest metrics (global_step, epoch, loss, metrics, best_metric). Use should_training_stop, should_save, should_evaluate and should_log on CallbackControl to request the corresponding action; do not modify loop counters directly. Events:

EventSignatureWhen it fires
on_init_end, on_train_begin, on_train_end(state, control)After the training objects are built, at the start of training and at the end of training
on_epoch_begin, on_epoch_end, on_step_begin, on_step_end(state, control)Before and after each epoch and each optimizer step
on_pre_optimizer_step, on_optimizer_step(state, control)Before the parameter update, and after gradient clipping
on_log(state, control, logs)When logs are emitted
on_evaluate(state, control, metrics)When evaluation finishes
on_save(state, control, checkpoint_dir)After a checkpoint is saved
on_push_begin, on_predict(state, control, checkpoint_dir) / (state, control)Before a checkpoint is pushed to the Hub; during generative evaluation

Built-in callbacks: early_stop stops training after the monitored metric fails to improve over several consecutive evaluations; perf_log records throughput over a logging_steps window; graceful_exit turns SIGTERM/SIGINT into "finish the current step, save a checkpoint, then exit". See callbacks/base.py for the authoritative signatures.

๐Ÿงฉ Optimizer parameter grouping

from swift.dev.builder.optimizer_plugins import ParamGroupsPlugin
from swift.dev.utils.plugin import PluginRegistry


@PluginRegistry.register('param_groups', 'no_decay_embeddings')
class NoDecayEmbeddings(ParamGroupsPlugin):
    def __call__(self, *, train_config, tuner_config):
        return [{'match': {'module_type': 'Embedding'}, 'weight_decay': 0.0}]

Select it with --param_groups_plugins no_decay_embeddings. The plugin returns serializable rules and does not read model parameters through the driver proxy; twinkle matches parameters on the worker that holds the real model. The built-in multimodal grouping and LoRA+ rules match first, and the first matching rule takes effect, so a plugin only claims parameters that the built-in rules did not match. See build_param_groups_spec for the rule syntax.

๐Ÿงฉ Tools and harnesses

ToolPlugin.build() returns a list of twinkle Tool instances. They can be called per sample (Sample), and the rollout copies them per sample. --tools sandbox uses the sandbox environment's own run_command, write_file and read_file, bound to each sample's (Sample) session, and does not run model-generated commands from a globally shared working directory.

from swift.dev.utils.plugin import PluginRegistry, ToolPlugin


@PluginRegistry.register('tool', 'my_tools')
class MyTools(ToolPlugin):
    def build(self):
        return [MyTool()]

HarnessPlugin.build() returns a twinkle_agentic.harness.CliAgent, the external CLI agent program started for each sample (Sample); codex and ms_agent are built in. The rollout manages the sample (Sample) environment, the model callback entry and the generation record; the harness is responsible only for the external program. See Agentic training for the complete data flow.

from swift.dev.harness import HarnessPlugin
from swift.dev.utils.plugin import PluginRegistry


@PluginRegistry.register('harness', 'my_agent')
class MyAgent(HarnessPlugin):
    def build(self):
        return MyCliAgent(...)

๐Ÿงฉ Sampler

--sampler selects the sampling engine for inference and rollout: vllm, sglang, transformers (alias pt), and openai, which does not start a local service and uses the address of a standard OpenAI service directly (see Command-line arguments). A custom sampler subclasses Sampler and is passed as a source file path or a class, for example --sampler ./my_sampler.py; engine arguments are passed through as-is via --engine_kwargs. The sampler kind is declared only at first resolution and does not exist yet when the plugin file is imported, so a custom sampler should not use @PluginRegistry.register('sampler', ...); pass the path directly.

๐Ÿงฎ loss

--loss takes effect for the four supervised task families: pre-training, SFT, Embedding, Reranker and decision. Sequence classification and online RL do not set --loss; the former decides the objective through problem_type, the latter through --rl_type. Built-in names per task:

Task--loss values
Pre-training, SFTcross_entropy (default). When --use_liger_kernel is also enabled and liger_kernel_config contains fused_linear_cross_entropy, the Liger fused CE is used; --enable_channel_loss and --enable_dft_loss change the aggregation
Embeddinginfonce (default), cosine_similarity, contrastive, online_contrastive
Rerankerpointwise_reranker (default), listwise_reranker
Sequence classification, regressionNot set; decided by problem_type: MSE for regression, CE for single-label, BCE for multi-label
Decisionscoring (default), distill_rps, smooth_brier, ce_rps
Online RLNot set; decided by --rl_type. GRPO variants are selected with --loss_type: grpo, gspo, cispo, dis, bnpo, dr_grpo, real, gpg, dapo, fipo, sapo, dro, dppo_tv, dppo_kl, geo_mean, clip_cov, kl_cov

A custom loss is a twinkle Loss subclass. Register it with @register_loss('name') and select it with --loss name. __call__ receives the encoded batch inputs (containing labels, loss_scale) and the model output outputs (containing logps; set require_logits = True when logits are needed), and returns a LossOutput whose loss is a scalar tensor and whose num_tokens is the number of tokens in this batch that take part in the loss, used for cross-step normalization. An SFT loss also receives reduction='sum', dft and label_smoothing at construction, and an Embedding loss receives mrl_dims; the constructor must accept these arguments. The easiest path is to inherit from the built-in loss of the same name (such as CrossEntropyLoss) and override __call__:

from twinkle.data_format import LossOutput
from twinkle.loss import CrossEntropyLoss

from swift.dev.utils.naming import register_loss


@register_loss('position_ce')
class PositionCE(CrossEntropyLoss):
    """CE whose per-token weight decays linearly with the position inside the response."""

    def __call__(self, inputs, outputs, **kwargs) -> LossOutput:
        _, per_token, mask = self.get_per_token_loss(inputs, outputs)
        pos = mask.cumsum(dim=-1) / mask.sum(dim=-1, keepdim=True).clamp(min=1)
        return LossOutput(loss=(per_token * (1 - pos) * mask).sum(), num_tokens=mask.sum().clamp(min=1))
swift sft --model Qwen/Qwen3.5-4B \
    --attn_impl flash_attention_2 \
    --dataset 'swift/self-cognition#600' \
    --external_plugins ./my_plugin.py \
    --loss position_ce \
    --output_dir output/custom-loss

register_loss also attaches the class to the twinkle.loss namespace, so that --mode ray workers can resolve it by class name after re-importing the plugin. With --mode remote, the server must also be able to import the same plugin file.

๐Ÿงฎ Custom loss_scale policies

loss_scale decides the loss weight of each token; see Custom datasets for details. A policy is a LossScale subclass; get_loss_scale(context, **kwargs) splits a piece of reply text into segments and returns the weight of each segment:

from typing import List, Tuple

from swift.dev.template.loss_scale import LossScale
from swift.dev.template.loss_scale.mapping import loss_scale_map


class KeywordLossScale(LossScale):
    def get_loss_scale(self, context: str, **kwargs) -> Tuple[List[str], List[float]]:
        return ['็ญ”ๆกˆ๏ผš', context.split('็ญ”ๆกˆ๏ผš', 1)[-1]], [1.0, 2.0]


loss_scale_map['keyword'] = KeywordLossScale

Use it with --loss_scale keyword. It can also be chained with the base policy and other policies using +, for example last_round+hermes+keyword; each policy processes the output of the previous one, and the weights are multiplied. Built-in policies: base, ignore_empty_think, react, hermes, qwen, agentflan, alpha_umi.

๐Ÿ“ Agent templates

An Agent template renders tools, tool_call and tool_response messages into the model's own tool call format. It is selected with --agent_template; when not set, the default declared in the model's TemplateMeta is used. A custom template is a BaseAgentTemplate subclass: _format_tools combines tools and system into the complete system message, _format_tool_calls renders consecutive tool_call messages as assistant text, _format_tool_responses renders tool returns, and get_toolcall parses the tool name and arguments from the model output (used for inference and deployment). Registering is writing into the mapping table:

from swift.dev.template.agent import BaseAgentTemplate, agent_template_map


class MyAgentTemplate(BaseAgentTemplate):
    ...


agent_template_map['my_agent'] = MyAgentTemplate

Built-in names: react_en, react_zh, qwen_en, qwen_zh, qwen_en_parallel, qwen_zh_parallel, qwen3_coder, qwen3, qwen3_5, hermes, hunyuan_hermes, hy_v3, hy_v3_preview, toolbench, chatglm4, glm4, glm4_5, glm4_7, glm5_1, glm_ocr, llama3, llama4, deepseek_v3_1, deepseek_v4, minimax_m2, minimax_m3, seed_oss, gemma4, react_grpo, mistral, youtu, kimi_k25, kimi_k3, minicpm5.

๐Ÿ“š Data format converters and storage formats

A format converter recognizes raw data by column names and rewrites it into the standard messages. A FormatConverter subclass decorated with @register_format declares format_name and the detection priority priority, and implements detect(columns) and convert(row). Set format_name on a DatasetLoader subclass to always use it; otherwise it is auto-detected by priority. See Custom datasets for the built-in converters and detection rules.

A storage format decides how dataset files are read and written. A DatasetStorage subclass decorated with @register_storage declares name and extensions and implements read and write. To write while an inference or conversion command runs, also implement append and declare incremental = True. The write format is selected with --store_format; reading is detected automatically by path extension or directory shape.

from swift.dev.dataset.storage import DatasetStorage, register_storage


@register_storage
class MyStorage(DatasetStorage):
    name = 'my'
    extensions = ('.my',)

    def read(self, path, *, split='train', **kwargs):
        ...

    def write(self, data, path, *, fields=None):
        ...

๐Ÿ“ Models and chat templates

A custom model family is a ModelLoader subclass decorated with @register_model. Declare model_type, the checkpoints it covers in models, the template it uses in template, and the transformers class in model_cls; override build_config, build_processor or build_model when the AutoModel path is not enough. Register a custom chat template with register_template; prefix, prompt and chat_sep describe the conversation format. Both the model and the template must be registered once in each of the two registries, swift.model and swift.dev.template; neither is derived from the other. See examples/v5/train/custom/model_template for a complete example:

from swift.dev.model.loader import ModelLoader, register_model
from swift.dev.template import TemplateMeta as DevTemplateMeta
from swift.dev.template import register_template as register_dev_template
from swift.model import Model, ModelGroup, ModelMeta
from swift.model import register_model as register_legacy_model
from swift.template import TemplateMeta, register_template


@register_model(exist_ok=True)
class CustomIMLoader(ModelLoader):
    model_type = 'custom_im'
    model_cls = 'transformers:AutoModelForCausalLM'
    template = 'custom_im'
    models = ['Qwen/Qwen2.5-0.5B-Instruct']


register_legacy_model(
    ModelMeta(
        model_type='custom_im',
        model_groups=[ModelGroup([Model('Qwen/Qwen2.5-0.5B-Instruct', 'Qwen/Qwen2.5-0.5B-Instruct')])],
        template='custom_im',
        architectures=['Qwen2ForCausalLM'],
    ),
    exist_ok=True)

for register, meta in ((register_template, TemplateMeta), (register_dev_template, DevTemplateMeta)):
    register(meta(
        template_type='custom_im',
        prefix=['<|im_start|>system\n{{SYSTEM}}<|im_end|>\n'],
        prompt=['<|im_start|>user\n{{QUERY}}<|im_end|>\n<|im_start|>assistant\n'],
        chat_sep=['<|im_end|>\n'],
        default_system='You are a helpful assistant.'))
swift sft --model Qwen/Qwen2.5-0.5B-Instruct \
    --model_type custom_im \
    --template custom_im \
    --external_plugins ./model.py \
    --dataset 'swift/self-cognition#600' \
    --output_dir output/custom-model

๐Ÿงฉ Loading and reuse

--external_plugins accepts local .py files, local directories, and hf:// / ms:// plugin ids. Directories and remote sources are resolved by twinkle's load_module; ms-swift does not build a separate loader. Importing a plugin executes code, so load only trusted sources and pin versions.

The selection argument of every extension point accepts three forms: a registered name, a plugin class object (for programmatic calls), or an external source path or id. When a source is passed, the loader returns the subclass of the corresponding base class found in the file.

To add a whole new extension point, use PluginRegistry.register_kind(name, base, config_field=...); to add an implementation, use PluginRegistry.register(kind, name). Registration checks that the implementation inherits the base class of that kind. Registering does not mean automatic integration into the recipe: the selection field and usage site of a new kind still have to be defined by the caller. See examples/v5/train/plugins for a complete example.