🛰️ ModelScope Service
ModelScope hosts a group of twinkle-server instances that expose the Twinkle training API for free. Developers do not need to prepare a GPU cluster or base weights themselves. Connect to https://www.modelscope.cn/twinkle with a platform access token to train a LoRA on a server-side base model, save checkpoints, sample and publish. The server composition is the same as a self-hosted deployment (see Server and client). The difference is that the platform decides what is exposed, and several users share compute on one base model in the form of named adapters.
📄 Inputs and outputs
| Item | Content |
|---|---|
| Input: credentials | ModelScope platform access token, passed through the environment variable MODELSCOPE_TOKEN; equivalent to account credentials |
| Input: model | The open models returned by the capability query, currently Qwen/Qwen3.8-27B, text only. A self-hosted twinkle-server can deploy any model |
| Input: data | Data is read and encoded on the client; only the encoded tokens are sent to the server. The twinkle Dataset supports ms://, hf:// identifiers and local paths, including swift/* dataset names. With the Tinker SDK the caller encodes the data |
| Input: task | The current open model is a causal_lm host, which supports PT, SFT, Agentic training, self-sampling RL such as GRPO / RLOO, and GKD / On-policy distillation. Tasks with a readout head such as seq_cls, reranker and decision require the server to deploy the host for that task; whether they are open is decided by the capability query |
| Input: training scale | Training steps, LoRA rank (upper limit 32), sampling parameters |
| Output: checkpoint | LoRA checkpoint stored on the server; save_state / save returns a twinkle:// URI |
| Output: sampling result | The sequences generated after the server loads the base model and applies the adapter, containing tokens, logprobs and decoded |
| Output: published artifact | The model repository on the ModelScope Hub after publish_checkpoint_from_tinker_path publishes the checkpoint |
📋 Usage steps
- Register a ModelScope account, create a token on the access token page, and pass it in through an environment variable.
twinkle-clientprovidesinit_tinker_clientand the Tinker compatibility layer, andtwinkleprovides the client-side dataset, template and DataLoader. Do not write the token into examples, commit it to a repository, or let it appear in shared logs. - Query the open models, choose a model with training permission from the returned list, then create a training handle.
- Prepare data on the client, train the LoRA and save a checkpoint.
- Create a sampling handle from the saved checkpoint and verify the training result. The adapter can also be merged into the base model and self-deployed, or published to the ModelScope Hub.
The code for each step is below.
1. Obtain credentials
pip install twinkle-client twinkle
export MODELSCOPE_TOKEN=<platform access token>2. Query the open models
import os
from twinkle_client import init_tinker_client
init_tinker_client()
from tinker import ServiceClient
service = ServiceClient(
base_url='https://www.modelscope.cn/twinkle',
api_key=os.environ['MODELSCOPE_TOKEN'],
)
for item in service.get_server_capabilities().supported_models:
print(item.model_name)A successful query means the account, credentials and network all work. The model names in this page are not a live list; follow what the capability query returns.
3. Train, save and sample
The script below trains a LoRA that changes the model's self-cognition with the swift/self-cognition dataset. The data is encoded on the client with twinkle's Dataset and template, input_feature_to_datum converts the encoded result into Tinker's Datum, and the training loop follows the Tinker SDK interfaces:
import os
from tqdm import tqdm
from tinker import types
from twinkle_client import init_tinker_client
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.8-27B'
base_url = 'https://www.modelscope.cn/twinkle'
# Use twinkle dataset to load the data
dataset = Dataset(dataset_meta=DatasetMeta('ms://swift/self-cognition', data_slice=range(500)))
dataset.set_template('Qwen3_5Template', model_id=f'ms://{base_model}', max_length=256)
dataset.map(SelfCognitionProcessor('Twinkle Model', 'ModelScope Team'), load_from_cache_file=False)
dataset.encode(batched=True, load_from_cache_file=False)
dataloader = DataLoader(dataset=dataset, batch_size=8)
# Initialize Tinker client before importing ServiceClient
init_tinker_client()
from tinker import ServiceClient
service = ServiceClient(base_url=base_url, api_key=os.environ['MODELSCOPE_TOKEN'])
training_client = service.create_lora_training_client(base_model=base_model, rank=16) # LoRA rank, upper limit 32
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)result.path is the twinkle:// URI of the server-side checkpoint. Pass it to create_sampling_client when sampling; the server loads the base model and applies that adapter. The prompt is encoded and the output is decoded on the client with the same template:
import os
from tinker import types
from twinkle_client import init_tinker_client
from twinkle.data_format import Message, Trajectory
from twinkle.template import Template
init_tinker_client()
from tinker import ServiceClient
base_model = 'Qwen/Qwen3.8-27B'
service = ServiceClient(base_url='https://www.modelscope.cn/twinkle', api_key=os.environ['MODELSCOPE_TOKEN'])
# model_path is the twinkle:// URI returned earlier by save_state
sampling_client = service.create_sampling_client(
model_path='twinkle://xxx-Qwen_Qwen3.8-27B-xxx/weights/twinkle-lora-1',
base_model=base_model,
)
template = Template(model_id=f'ms://{base_model}')
trajectory = Trajectory(messages=[
Message(role='system', content='You are a helpful assistant'),
Message(role='user', content='Who are you?'),
])
input_ids = template.batch_encode([trajectory], add_generation_prompt=True)[0]['input_ids'].tolist()
params = types.SamplingParams(max_tokens=128, temperature=0.7, stop=['\n'])
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))4. Publish to the Hub
After training, the adapter can be merged into the base model, deployed with your own service and called through an OpenAI-compatible interface. The checkpoint can also be published to the ModelScope Hub through the REST client:
rest_client = service.create_rest_client()
rest_client.publish_checkpoint_from_tinker_path(result.path).result()Publishing requires a valid ModelScope token as api_key when initializing ServiceClient. For a complete, modifiable script see cookbook/client/tinker. For the official platform description see Train-as-a-Service.
🔌 Three client entry points
twinkle-server accepts two client protocols at the same time, and the hosted service is currently exposed through the Tinker-compatible interface. The two syntaxes connect to the same set of server primitives; the difference is who describes the training logic. The Tinker syntax hands the loss name and Datum directly to forward_backward, and every step in the training loop is issued explicitly by the client. The Twinkle syntax registers the template, processor, loss and optimizer on the remote model handle by class name; forward_backward receives only the batch, and clip_grad_and_step performs clipping, the update, zeroing and learning rate scheduling in one call. swift sft --mode remote is the third entry point: the command line and recipe run on the client, and model computation is sent to the same server.
| Step | Tinker syntax | Twinkle syntax | swift sft --mode remote |
|---|---|---|---|
| Initialization | init_tinker_client() then from tinker import ServiceClient | init_twinkle_client(base_url, api_key) returns client | --mode remote --server_base_url https://www.modelscope.cn/twinkle --server_api_key <token> |
| Model handle | service.create_lora_training_client(base_model, rank) | client.model(f'ms://{base_model}'), then add_adapter_to_model(name, LoraConfig) | --model Qwen/Qwen3.8-27B |
| Loss and optimizer | 'cross_entropy' and AdamParams passed on every call | model.set_loss('CrossEntropyLoss'), model.set_optimizer('Adam', lr=1e-4) | Arguments such as --tuner lora --lora_rank 16, --loss, --optim and --learning_rate |
| Training step | forward_backward(data, loss) and optim_step(params), each waiting on its own future | model.forward_backward(batch) and model.clip_grad_and_step() | Done inside the recipe |
| Data format | Encoded on the client into Datum, converted through input_feature_to_datum | Encoded on the client into InputFeature, used directly as the batch | Done inside the recipe |
| Saving | save_state(name).result().path | model.save(name, save_optimizer=True) returns a twinkle:// path | --output_dir; returns a twinkle:// path |
| Use case | Existing Tinker training code, or the need to keep the same code as hosted Tinker | Training logic written from scratch that needs algorithms such as DPO, GRPO and distillation described by the recipe | No code; training is described with command-line arguments |
For the compatibility scope of the Tinker syntax see Tinker training service. For complete examples of the Twinkle syntax, the resume-from-checkpoint flow and CLI usage see Server and client. To connect to the same hosted service with the command line:
export MODELSCOPE_TOKEN=<platform access token>
swift sft \
--mode remote \
--server_base_url https://www.modelscope.cn/twinkle \
--server_api_key $MODELSCOPE_TOKEN \
--model Qwen/Qwen3.8-27B \
--dataset 'swift/self-cognition#600' \
--tuner lora \
--lora_rank 16 \
--max_steps 30 \
--output_dir output/modelscope-sftserver_base_url is the gateway root address without /api/v1. Fill --model with a model name returned by the capability query, and keep --lora_rank within 32. Under --mode remote the dataset and template stay in the client process, so the datasets and templates that swift supports can all be used directly; --modules_to_save is not available. A --task_type with a readout head requires the server to have deployed the host for the same task. See Server and client for the mapping between tasks and hosts.
🚧 Open scope
The platform decides what the hosted service exposes. The differences from a self-hosted deployment are:
- Model: follow the list returned by the capability query; currently
Qwen/Qwen3.8-27B, text only, with no support for multimodal tasks. - Training method: LoRA only, with a rank upper limit of 32 and no support for
modules_to_save. - Algorithms: PT, SFT (including Agentic training), self-sampling RL such as GRPO / RLOO, and GKD / On-policy distillation. When distillation needs both a teacher and a student model, the developer prepares the teacher.
- loss: executed on the server; custom client-side losses are not accepted. A needed loss component can be uploaded to ModelScope, and maintainers can be contacted to add it to the allowlist.
- Saving: a Transformers-backend training checkpoint must call
save_state()orsave(..., save_optimizer=True)after the current gradient accumulation, optimizer update andzero_gradhave completed. Exporting model weights only is not subject to this restriction.
🎯 GRPO essentials
GRPO needs the server to provide both the model and the sampler applications. The training handle's save_weights_and_get_sampling_client syncs the current adapter to the sampler and returns a sampling handle. The sampling result is used on the client to compute rewards and advantages, and the update is then submitted with importance_sampling as the loss name. The compatibility layer's importance_sampling is twinkle's GRPO loss, and the Datum must carry the logprobs from sampling and the group-normalized advantages. Taking GSM8K as an example, sample 4 answers for each prompt:
import numpy as np
from tinker import types
from twinkle.advantage import GRPOAdvantage
from twinkle.dataloader import DataLoader
from twinkle.dataset import Dataset, DatasetMeta
from twinkle.preprocessor.llm import GSM8KProcessor
from twinkle.reward import GSM8KAccuracyReward
from twinkle.template import Qwen3_5Template
SYSTEM_PROMPT = 'Solve the problem and put your final answer within \\boxed{}.'
dataset = Dataset(DatasetMeta('ms://modelscope/gsm8k', subset_name='main', split='train', data_slice=range(2000)))
dataset.set_template('Qwen3_5Template', model_id=f'ms://{base_model}', max_length=4096,
truncation_strategy='delete', enable_thinking=True)
dataset.map(GSM8KProcessor(system=SYSTEM_PROMPT))
dataset.encode(add_generation_prompt=True)
dataloader = DataLoader(dataset=dataset, batch_size=2)
template = Qwen3_5Template(model_id=f'ms://{base_model}')
training_client = service.create_lora_training_client(base_model=base_model, rank=16)
advantage_fn = GRPOAdvantage()
reward_fn = GSM8KAccuracyReward()
sampling_params = types.SamplingParams(max_tokens=4096, temperature=1.0, top_p=0.95)
NUM_GENERATIONS = 4
for step, prompts in enumerate(dataloader):
# 1. Sync the current adapter to the sampler and get a sampling handle
sampling_client = training_client.save_weights_and_get_sampling_client(name=f'grpo-{step}')
# 2. Sample NUM_GENERATIONS answers for each prompt
sequences, prompt_ids_list = [], []
for feature in prompts:
prompt_ids = feature['input_ids'].tolist()
result = sampling_client.sample(
prompt=types.ModelInput.from_ints(prompt_ids), sampling_params=sampling_params, num_samples=NUM_GENERATIONS,
).result()
sequences.extend(result.sequences)
prompt_ids_list.extend([prompt_ids] * NUM_GENERATIONS)
# 3. Compute rewards and in-group advantages on the client
trajectories = [{'messages': [{'role': 'user', 'content': ''}, {'role': 'assistant', 'content': template.decode(s.tokens)}],
'user_data': prompts[i // NUM_GENERATIONS].get('user_data', [])} for i, s in enumerate(sequences)]
rewards = reward_fn(trajectories)
advantages = advantage_fn(rewards, num_generations=NUM_GENERATIONS, scale='group').tolist()
if all(abs(a) < 1e-8 for a in advantages):
continue # all rewards in the group are equal, the advantages are zero, skip the update
# 4. Build Datums carrying logprobs and advantages; the prompt segment has weight 0
data = []
for seq, prompt_ids, advantage in zip(sequences, prompt_ids_list, advantages):
n_prompt, n_completion = len(prompt_ids) - 1, len(seq.tokens)
data.append(types.Datum(
model_input=types.ModelInput.from_ints(prompt_ids + list(seq.tokens[:-1])),
loss_fn_inputs={
'target_tokens': [0] * n_prompt + list(seq.tokens),
'weights': [0.0] * n_prompt + [1.0] * n_completion,
'logprobs': types.TensorData.from_numpy(np.array([0.0] * n_prompt + list(seq.logprobs), dtype=np.float32)),
'advantages': types.TensorData.from_numpy(np.array([0.0] * n_prompt + [advantage] * n_completion, dtype=np.float32)),
},
))
# 5. Submit the update with importance_sampling
training_client.forward_backward(data, 'importance_sampling').result()
training_client.optim_step(types.AdamParams(learning_rate=2e-5)).result()
result = training_client.save_state('gsm8k-grpo-final').result()Weights are saved before sampling at every step, so sampling uses the current policy. The reward function comes from twinkle.reward; a custom reward only needs to implement the same __call__(trajectories) -> List[float] interface. GRPOAdvantage(scale='group') subtracts the mean and divides by the standard deviation per prompt group. For the complete script see short_math_grpo.py, which also includes a short reward and metric logging. For the clipping and KL defaults of importance_sampling in the compatibility layer see Tinker training service.
🔗 Related entry points
| Service | Address | Credentials | Use |
|---|---|---|---|
| Model and dataset Hub | https://www.modelscope.cn | Token needed when downloading restricted models | The default model and dataset source of the swift command |
| Hosted twinkle-server | https://www.modelscope.cn/twinkle | Platform access token | The LoRA training, saving, sampling and publishing described in this page |
| API inference | https://api-inference.modelscope.cn/v1 | Platform access token | OpenAI-compatible generation interfaces such as chat and embedding; provides no training primitives |
API inference and the training service are two different addresses. Do not pass the API inference address as --server_base_url to swift sft --mode remote. The calling method is the same as the OpenAI SDK; see the API inference documentation for the calling rules. The model configuration page of TrainBench uses the same address and token.
⚠️ Confirm before use
The open models and capacity follow what the capability query returns, and resource adjustments by the platform follow official announcements. When the capability list does not contain the needed model or the capacity is insufficient, twinkle-server can be deployed yourself; see Server and client.