Skip to Content
MS-SWIFT Γ— TWINKLE
SERVICESMS-SWIFT Γ— TWINKLE

πŸ“‘ Tinker Training Service

Tinker is a hosted training service from Thinking Machines Lab. The base model stays resident on server-side GPUs, developers write the training loop in a local process, and forward/backward, parameter update and save requests are submitted over HTTP. The ms-swift documentation covers it for two reasons: the hosted service can be used directly, and twinkle-server implements the same set of training primitives, so existing Tinker training code only needs one initialization call to connect to a self-hosted service.

πŸ“ The Train-as-a-Service mechanism

Traditional fine-tuning requires the training process to own the GPU that hosts the model exclusively. Training as a service splits model hosting and training logic into two ends. The server holds the base weights, optimizer state and sampling engine, and allows the LoRA adapters of several users to stay resident at the same time. The client completes data reading, template encoding and training loop orchestration on a local CPU, and sends only the encoded tokens and commands to the server. This brings three properties: the client does not need to download the base weights and does not need a local GPU; several users share the same base weights and each holds only a low-rank adapter; billing and quota are settled by the token count of requests and model capacity, with rate limiting enforced uniformly by the server.

The contract between the two ends is a set of training primitives, not a complete training algorithm:

ServiceClient
  └─ create_lora_training_client(base_model, rank) β†’ TrainingClient
       β”œβ”€ forward_backward(datum list, loss name) β†’ future
       β”œβ”€ optim_step(AdamParams)                   β†’ future
       β”œβ”€ save_state(name)   β†’ future, returns the checkpoint path
       β”œβ”€ save_weights(name) β†’ future, saves model weights only
       └─ save_weights_and_get_sampling_client(name) β†’ SamplingClient
  └─ create_sampling_client(model_path, base_model) β†’ SamplingClient
       └─ sample(prompt, SamplingParams, num_samples) β†’ future

Every primitive returns a future, and calling result() blocks until the execution result is available. This is the client-side projection of asynchronous server-side execution. save_state saves the optimizer state and training progress and is used to resume training. save_weights exports the weights only and is used for sampling or merging. Both paths return a server-managed checkpoint URI, not a local file.

πŸ“– Using the Tinker API

The Tinker service provides LoRA training only for open-weight models. The workflow has four steps: apply for service access on the official platform and obtain an API key; install tinker and tinker-cookbook (pip install tinker tinker-cookbook); query the currently open model list; write the training loop. The loop below uses only the Tinker SDK, and the data is encoded locally with the tokenizer bundled with the base model:

import tinker
from tinker import types
from transformers import AutoTokenizer

service_client = tinker.ServiceClient()  # reads the API key from environment variables

# follow the return value of the capability query; do not assume a model is open
for item in service_client.get_server_capabilities().supported_models:
    print(item.model_name)

base_model = 'Qwen/Qwen3.5-4B'
tokenizer = AutoTokenizer.from_pretrained(base_model)
training_client = service_client.create_lora_training_client(base_model=base_model, rank=8)

def to_datum(prompt_ids, response_ids):
    # weights mark which positions take part in the loss: 0 for the prompt segment, 1 for the response segment
    tokens = prompt_ids + response_ids
    weights = [0.0] * len(prompt_ids) + [1.0] * len(response_ids)
    return tinker.Datum(
        model_input=types.ModelInput.from_ints(tokens),
        loss_fn_inputs={'weights': weights, 'target_tokens': tokens[1:]},
    )

for step, (prompt_ids, response_ids) in enumerate(batches):
    fwdbwd = training_client.forward_backward([to_datum(prompt_ids, response_ids)], 'cross_entropy')
    optim = training_client.optim_step(types.AdamParams(learning_rate=1e-4))
    fwdbwd.result()
    optim.result()

checkpoint = training_client.save_state(f'sft-{step}').result()
print(checkpoint.path)

The Tinker SDK also provides ppo, cispo, dro and other losses for reinforcement learning and distillation, as well as variants of importance_sampling. See the Tinker documentation for the full description. Model capacity, the LoRA rank limit, the number of simultaneously resident adapters and the token count per request are decided by the service configuration; follow the capability query and the platform rules.

πŸ“‘ From the hosted service to twinkle-server

The only difference between hosted Tinker and a self-hosted twinkle-server is who owns the GPUs. Tinker is operated by Thinking Machines Lab and billed per request. twinkle-server is deployed on your own cluster, and accounts, models and checkpoints are managed by the deployer. The training contract of the two is the same, and twinkle-server implements three classes of Tinker protocol handlers for it: forward_backward, optim_step and save_state / load_state on the model application; sample on the sampler application; and capability query, health check and session management on the gateway. For the server architecture and deployment configuration see Server and client.

To connect existing Tinker training code to twinkle-server, call init_tinker_client() before importing tinker. This initialization makes two adaptations to the Tinker SDK: it accepts the authentication header and API token of twinkle-server, and it accepts checkpoint paths with the twinkle:// prefix. The initialization does not start a service, allocate GPUs or deploy a model. For client installation and server deployment see the installation section of Server and client:

import os
from twinkle_client import init_tinker_client

init_tinker_client()
from tinker import ServiceClient

service = ServiceClient(
    base_url=os.environ.get('TWINKLE_SERVER_URL', 'http://127.0.0.1:8000'),
    api_key=os.environ.get('TWINKLE_SERVER_TOKEN', ''),
)
for item in service.get_server_capabilities().supported_models:
    print(item.model_name)

Do not use twinkle's initialization patch to connect to hosted Tinker, and do not treat a ModelScope token as Tinker account credentials. The account systems of the two services are not interchangeable.

πŸ” Loss compatibility scope

The compatibility layer accepts cross_entropy and importance_sampling. ppo, cispo and dro return HTTP 400 before the task is queued and before any gradient is modified; they are not silently replaced with cross entropy.

importance_sampling in the compatibility layer follows twinkle's GRPO loss: PPO-style clipping (default epsilon=0.2), an optional KL penalty (default beta=0), and the mean taken per sequence. Tinker's importance_sampling is an unclipped objective summed over tokens. The numerical results of the two differ, and the migration must not be treated as an equivalent substitution.

twinkle's DPO extension also uses importance_sampling. It requires each Datum to carry ref_logps, chosen and rejected to be interleaved, and each data-parallel shard to receive complete pairs. Ordinary RL samples do not require pairing. With a data-parallel degree of 1, batch sizes of 1 or 3 are both valid, but the token count and rate limits still apply.

πŸ’‘ Complete training and sampling example

Data preparation can use twinkle's Dataset and DataLoader; the encoded InputFeature is converted into Tinker's Datum through input_feature_to_datum. With the Transformers backend, the current gradient accumulation, optimizer update and gradient clearing must complete before calling save_state. Exporting model weights only is not subject to this restriction.

from tqdm import tqdm
from tinker import types
from twinkle.dataloader import DataLoader
from twinkle.dataset import Dataset, DatasetMeta
from twinkle.preprocessor import SelfCognitionProcessor
from twinkle_client.utils.tinker_datum import input_feature_to_datum

base_model = 'Qwen/Qwen3.5-4B'
dataset = Dataset(dataset_meta=DatasetMeta('ms://swift/self-cognition', data_slice=range(500)))
dataset.set_template('Qwen3_5Template', model_id=base_model, max_length=256)
dataset.map(SelfCognitionProcessor('twinkleζ¨‘εž‹', 'twinkleε›’ι˜Ÿ'), load_from_cache_file=False)
dataset.encode(batched=True, load_from_cache_file=False)
dataloader = DataLoader(dataset=dataset, batch_size=8)

training_client = service.create_lora_training_client(base_model=base_model, rank=16)
for epoch in range(2):
    for batch in tqdm(dataloader):
        data = [input_feature_to_datum(feature) for feature in batch]
        fwdbwd = training_client.forward_backward(data, 'cross_entropy')
        optim = training_client.optim_step(types.AdamParams(learning_rate=1e-4))
        fwdbwd.result()
        optim.result()
    result = training_client.save_state(f'twinkle-lora-{epoch}').result()
    print(result.path)

Sampling requires the server to have a sampler application configured. To sample directly from the weights being trained, call save_weights_and_get_sampling_client(name). To sample from a saved checkpoint, call service.create_sampling_client(model_path='twinkle://...', base_model=base_model); model_path accepts a twinkle:// URI directly. The prompt is encoded into tokens on the client with the same template, and decoding is also done on the client:

from twinkle.data_format import Message, Trajectory
from twinkle.template import Template

sampling_client = service.create_sampling_client(
    model_path=result.path,  # or the twinkle:// path returned by save_weights
    base_model=base_model,
)
template = Template(model_id=f'ms://{base_model}')
trajectory = Trajectory(messages=[Message(role='user', content='你是谁?')])
input_ids = template.batch_encode([trajectory], add_generation_prompt=True)[0]['input_ids'].tolist()
params = types.SamplingParams(max_tokens=128, temperature=0.7)
output = sampling_client.sample(prompt=types.ModelInput.from_ints(input_ids), sampling_params=params, num_samples=1).result()
for seq in output.sequences:
    print(template.decode(seq.tokens))

For runnable complete scripts see cookbook/client/tinker, which covers SFT, DPO, GRPO, multimodal and uploading to the Hub. For compatibility notes see Tinker-Compatible Client in the twinkle documentation. For the hosted twinkle service on ModelScope see ModelScope service.