๐ก Server and Client
twinkle-server decouples model hosting from training logic. Built on Ray Serve, the server hosts the base model weights, optimizer state and sampling engine, and runs forward / backward, parameter updates, sampling and saving. The client runs data preparation and the training loop in a local CPU process and sends commands to the server over HTTP. Several users share the same base model and each trains a named LoRA adapter.
The diagram has three areas. The left column is the client side: twinkle_client, the Tinker SDK, OpenAI clients that reuse the sampler application, and the CLI and recipe of swift --mode remote. Data and tokenization are encoded on the client and then submitted. The middle column is the gateway: API key authentication and RPS / TPS rate limiting, session and model handles, asynchronous future results, protocol handlers for the three twinkle / tinker / OpenAI bridges, and ServerState backed by memory or redis. The right column is the compute applications on Ray Serve: the model application (transformers or megatron backend, multiple resident LoRAs, TaskQueue admission), the sampler application (vLLM or SGLang engine, enable_lora for per-adapter sampling), the processor application (CPU encoding), and checkpoint management that returns twinkle:// URIs.
Solid blue lines are control requests, green lines are future result polling, and dashed lines are weight / adapter sync from model to sampler and checkpoint references. All requests and results go through the gateway, and the gateway handles only HTTP / JSON. The GPU resources of the model and the sampler are decided by the server configuration, not by the number of GPUs visible to the client.
๐ก Model backend and client modes
The model backend is selected in the backend field of the model application:
| backend | Description |
|---|---|
transformers | HuggingFace Transformers; suits most scenarios |
megatron | Megatron-LM; tensor / pipeline / expert parallelism for very large models |
mock | A numpy-only simulated backend for CPU development and testing |
The same server accepts two client modes at the same time:
| Client | Initialization | Description |
|---|---|---|
| Twinkle client | init_twinkle_client | The native client. To go remote, change the imports of twinkle.model, twinkle.dataset, twinkle.dataloader and similar modules in local code to the same-named subpackages under twinkle_client |
| Tinker-compatible client | init_tinker_client | Patches the Tinker SDK so that existing Tinker training code can be reused without modification |
| Scenario | Recommended |
|---|---|
| Existing local Twinkle training code | Twinkle client; only the import paths change |
| Existing Tinker training code | Tinker-compatible client; only the patch is initialized |
| Using ms-swift recipes and the command line | swift sft --mode remote; see below |
| New project | Twinkle client; simpler API |
๐ฆ Installation
Server:
pip install twinkle-server 'ms-swift>=5.0.0'ms-swift is used on the server for the ms-swift model family loaders and templates. Install vllm separately when deploying a vLLM sampler. A service that only runs the training model application and the gateway does not need a separate sampler.
Client:
pip install twinkle-client 'ms-swift>=5.0.0'Clients using swift sft --mode remote need ms-swift. When using the component client directly, install dependencies such as transformers and peft as required for data encoding. twinkle / twinkle-client / twinkle-server on both ends must be installed in the same Python environment and use matching versions.
๐ Start the server
The twinkle-server launcher connects to an existing Ray cluster with ray.init(address='auto') and does not start a cluster itself, so start the Ray head first and then launch:
CUDA_VISIBLE_DEVICES=0,1 ray start --head --num-gpus=2
twinkle-server launch --config server_config.yamlWhen a Ray cluster already exists, connect to the existing head instead of creating another one. twinkle-server also provides three subcommands:
| Subcommand | Description |
|---|---|
launch | Start the service; blocks until shutdown |
check-config | Validate the configuration only, without starting; used in CI to catch bad configuration |
print-config | Print the complete configuration after validation and normalization; supports --format yaml or json |
clear persistence | Clear sessions, models, futures and other state from the persistence backend |
Configuration files use strict validation. Misspelled field names, type mismatches and unsatisfied cross-field constraints (such as persistence.mode: redis without redis_url) all raise an error before startup.
๐ Server configuration
The configuration file defines the HTTP listener, persistence, observability and the list of application components. The following is a complete configuration for deploying one trainable model plus a vLLM sampler:
proxy_location: EveryNode # on multi-node deployments each Ray node runs an HTTP proxy
http_options:
host: 0.0.0.0
port: 8000
persistence:
mode: redis # memory or redis; use redis in production
redis_url: redis://localhost:6379/0
telemetry:
enabled: false
applications:
# 1. gateway: the central API service; handles connections, training run records and checkpoint management
- name: server
route_prefix: /api/v1
import_path: server
args:
server_config:
per_token_model_limit: 3 # maximum number of model handles per token
supported_models:
- Qwen/Qwen3.5-4B # must match the tail segment of the model application route
deployments:
- name: GatewayServer
max_ongoing_requests: 50
autoscaling_config: {min_replicas: 1, max_replicas: 1}
ray_actor_options: {num_cpus: 0.1}
# 2. model: hosts the base model and runs forward / backward and parameter updates
- name: models-Qwen3.5-4B
route_prefix: /api/v1/model/Qwen/Qwen3.5-4B
import_path: model
args:
backend: transformers # transformers | megatron | mock
model_id: ms://Qwen/Qwen3.5-4B
model_loader: swift.dev.model.loader:build_model_loader # use the SWIFT model family loader
train_mode: lora # lora or full; remove max_loras when full
max_loras: 2 # maximum number of resident LoRAs per instance
max_r: 32 # maximum rank of a resident LoRA
max_length: 2048
mixed_precision: bf16
gradient_checkpointing: true
nproc_per_node: 1
device_group: {name: model, ranks: 1, device_type: cuda}
device_mesh: {device_type: cuda, dp_size: 1}
queue_config:
rps_limit: 100
tps_limit: 10000
max_input_tokens: 8192
deployments:
- name: ModelManagement
autoscaling_config: {min_replicas: 1, max_replicas: 1}
ray_actor_options: {num_cpus: 0.1}
# 3. sampler: a vLLM engine runs sampling and loads LoRAs per adapter
- name: sampler-Qwen3.5-4B
route_prefix: /api/v1/sampler/Qwen/Qwen3.5-4B
import_path: sampler
args:
model_id: ms://Qwen/Qwen3.5-4B
sampler_type: vllm # vllm | sglang | torch | mock
engine_args:
max_model_len: 4096
gpu_memory_utilization: 0.5
enable_lora: true
nproc_per_node: 1
device_group: {name: sampler, ranks: 1, device_type: cuda}
device_mesh: {device_type: cuda, dp_size: 1}
queue_config:
rps_limit: 100
tps_limit: 100000
deployments:
- name: SamplerManagement
autoscaling_config: {min_replicas: 1, max_replicas: 1, target_ongoing_requests: 16}
ray_actor_options: {num_cpus: 0.1}
# 4. processor: runs tokenization and template conversion on CPU; optional. Note that enabling the processor may let the server execute unreviewed scripts, so this feature is not suitable for public services
- name: processor
route_prefix: /api/v1/processor
import_path: processor
args:
ncpu_proc_per_node: 2
device_group: {name: model, ranks: 2, device_type: CPU}
device_mesh: {device_type: CPU, dp_size: 2}
deployments:
- name: ProcessorManagement
autoscaling_config: {min_replicas: 1, max_replicas: 1}
ray_actor_options: {num_cpus: 0.1}Top-level fields:
| Field | Description |
|---|---|
proxy_location | HTTP proxy location. EveryNode runs one proxy per node (recommended for multi-node); HeadOnly runs one on the head only |
http_options | Listen address and port |
persistence | ServerState storage backend. memory keeps state only in the current process; redis requires redis_url, and sessions and futures survive a server restart |
telemetry | OpenTelemetry: enabled, otlp_endpoint, service_name, debug |
applications | List of application components; each entry is a Ray Serve application |
The import_path of an application component is one of four values: server (gateway), model (training), sampler (sampling) or processor (CPU preprocessing). The GPU usage of each model or sampler application is decided by device_group.ranks, and dp_size, tp_size, pp_size and ep_size in device_mesh divide the parallelism dimensions over those GPUs. When training and sampling are placed in different applications, each must reserve its own GPUs.
queue_config constrains the request resources of a single application: rps_limit is requests per second per user token, tps_limit is input tokens per second per user token, and max_input_tokens is the input limit of a single request. A request that exceeds any of them is rejected with an error response instead of being queued.
โก On-demand loading and autoscaling
The training service can load the model when the first training request arrives and release the devices automatically when it is no longer used. Set the following in the args of import_path: model:
train_mode: lora
max_loras: 3
min_replicas: 0
max_replicas: 2
idle_timeout_s: 600
adapter_config:
adapter_timeout: 30
adapter_max_lifetime: 36000| Field | Description |
|---|---|
min_replicas / max_replicas | Number of instances kept at startup and the maximum number of instances. With min_replicas: 0, the first training request has to wait for the model to load |
max_loras | Maximum number of concurrent LoRA trainings per instance |
idle_timeout_s | Seconds of training idleness before an instance is released; heartbeats and result polling do not extend it |
adapter_config.adapter_timeout | Seconds without a session heartbeat from the client before the training handle is released; default 1800; null disables it |
adapter_config.adapter_max_lifetime | Maximum seconds a training handle is kept from creation; default 36000; null removes the limit |
The three timers control business idleness, heartbeat loss and maximum lifetime respectively, and none replaces another. After a handle expires, it must be recreated and the checkpoint restored explicitly. For full-parameter training, change train_mode to full and remove max_loras; each full-parameter training owns one instance exclusively. To offer both LoRA and full-parameter training on the same base model, configure two model applications with different name and route_prefix.
The sampler application also supports min_replicas, max_replicas, target_ongoing_requests and idle_timeout_s: as requests grow, it scales up according to target_ongoing_requests (target in-flight requests per instance), and extra instances are closed after being idle for a while. The LoRA checkpoints needed for sampling are loaded on request; the client does not need to specify an instance.
๐ง Task types
By default the model application is a causal_lm base-model host. To train tasks that have a readout head, such as sequence classification, reranker or decision scoring, set task_type in the args of the model application: the host pre-builds the readout head for that task at construction (one per LoRA slot, saved together with the adapter), and all adapters on the same host share this one kind of head. One application serves only one task. To offer several tasks on the same base model, configure several model applications with different name, route_prefix and model_id, and let clients select by model name.
- name: models-Qwen3.5-4B-seq-cls
route_prefix: /api/v1/model/Qwen3.5-4B-seq-cls
import_path: model
args:
backend: transformers
model_id: ms://Qwen/Qwen3.5-4B
task_type: seq_cls # readout-head task of the host
num_labels: 3 # required for seq_cls
train_mode: lora
max_loras: 2
nproc_per_node: 1| Task | Readout | Configuration | Use |
|---|---|---|---|
causal_lm | vocab head | Default; no configuration needed | PT, SFT, RLHF; losses such as DPO / GRPO are set by the client |
seq_cls | Linear head, [B, num_labels] | Host task_type: seq_cls, num_labels required | Sequence classification and regression; reward model training |
reranker | Single-score Linear head | Host task_type: reranker, num_labels defaults to 1 | Relevance scoring of query and candidate |
value | Single-score Linear head, per token [B, T] | Host task_type: value, num_labels defaults to 1 | PPO critic |
decision | Built by the model family's loader | Host task_type: decision; model_loader must carry task_head_loader | JEV decision scoring |
embedding | pooling, lm_head set to identity | Pass task='embedding' at forward; no head built | Sentence vectors |
generative_reranker | Logit difference of positive and negative tokens | Pass task='generative_reranker' at forward; no head built; positive and negative tokens default to yes / no | Generative reranker |
The readout heads for seq_cls, reranker, value and decision are pre-built by the host. When creating an adapter, the client may declare the task with the task argument, and the server only checks consistency: a mismatch with the host's task_type raises an error, while a match or no argument creates it normally. modules_to_save is not available on the server; the readout head is pre-built by the host and does not go through peft's modules_to_save injection.
# when the host task_type is seq_cls
model.add_adapter_to_model('cls', LoraConfig(target_modules='all-linear'), task='seq_cls')
# no task is needed when the host is the default causal_lm
model.add_adapter_to_model('sft', LoraConfig(target_modules='all-linear'))๐ก Twinkle client
Migrating local Twinkle code to the remote server only changes imports; class names and methods stay the same:
# local
from twinkle.dataloader import DataLoader
from twinkle.dataset import Dataset, DatasetMeta
from twinkle.model import MultiLoraTransformersModel
# remote
from twinkle_client import init_twinkle_client
from twinkle_client.dataloader import DataLoader
from twinkle_client.dataset import Dataset
from twinkle_client.model import MultiLoraTransformersModelinit_twinkle_client reads TWINKLE_SERVER_URL and TWINKLE_SERVER_TOKEN (or takes base_url and api_key explicitly), creates a session on the server, and from then on every model, sampler and dataset object created inherits the same configuration. Each request carries the session id, and a background thread sends heartbeats at a fixed interval.
A complete SFT training run:
import os
from peft import LoraConfig
from twinkle_client import init_twinkle_client
from twinkle_client.dataloader import DataLoader
from twinkle_client.dataset import Dataset
from twinkle.dataset import DatasetMeta
client = init_twinkle_client(
base_url=os.environ.get('TWINKLE_SERVER_URL', 'http://127.0.0.1:8000'),
api_key=os.environ.get('TWINKLE_SERVER_TOKEN', 'EMPTY_TOKEN'),
)
base_model = 'Qwen/Qwen3.5-4B'
# data: encoded on the client and submitted with the request
dataset = Dataset(dataset_meta=DatasetMeta('ms://swift/self-cognition', data_slice=range(200)))
dataset.set_template('Qwen3_5Template', model_id=f'ms://{base_model}', max_length=512)
dataset.map('SelfCognitionProcessor', init_args={'model_name': 'ms-swift', 'model_author': 'ModelScope'})
dataset.encode(batched=True)
dataloader = DataLoader(dataset=dataset, batch_size=4)
# model: bind the remote base model and attach a named LoRA
model = client.model(f'ms://{base_model}')
model.add_adapter_to_model('default', LoraConfig(target_modules='all-linear'), gradient_accumulation_steps=2)
model.set_template('Qwen3_5Template')
model.set_processor('InputProcessor', padding_side='right')
model.set_loss('CrossEntropyLoss')
model.set_optimizer('Adam', lr=1e-4)
# training loop: forward_backward and clip_grad_and_step are both HTTP calls
for epoch in range(3):
for batch in dataloader:
model.forward_backward(inputs=batch)
model.clip_grad_and_step()
# save: returns a twinkle:// URI managed by the server's checkpoint storage
resp = model.save(name='twinkle-lora-1', save_optimizer=True)
print(resp.twinkle_path)Dataset and DataLoader can use either local twinkle or remote twinkle_client. The remote encode calls the server processor over HTTP with a default timeout of 600 seconds; use the timeout argument to raise it for large data volumes.
The component interfaces let the client customize the loop; the caller is responsible for the alignment contract of input tokens, labels and attention mask. Micro-batch accumulation and optimizer updates must correspond, and do not accumulate twice in data grouping and model calls.
๐ฒ Sampling
After training, sample with the trained LoRA through the sampler application. Pass the twinkle:// URI returned by save as adapter_uri; the server loads the base model and overlays that LoRA. Pass None to sample with the base model:
from twinkle.data_format import Trajectory
from twinkle_client.sampler import vLLMSampler
sampler = vLLMSampler(model_id=base_model)
sampler.set_template('Qwen3_5Template', model_id=base_model)
responses = sampler.sample(
inputs=[Trajectory(messages=[{'role': 'user', 'content': 'ไฝ ๆฏ่ฐ๏ผ'}])],
sampling_params={'max_tokens': 512, 'temperature': 0.0},
adapter_uri=twinkle_path,
)The sampler application also exposes OpenAI-compatible chat/completions and embeddings endpoints under /api/v1 on the gateway. Any OpenAI client can point base_url at http://<host>:8000/api/v1 and specify the base model or adapter in the model field, without starting a local inference service.
๐ Tinker-compatible client
Existing Tinker training code only needs the patch initialized before importing tinker:
import os
from twinkle_client import init_tinker_client
init_tinker_client()
from tinker import ServiceClient, types
service_client = ServiceClient(
base_url='http://127.0.0.1:8000',
api_key=os.environ.get('TWINKLE_SERVER_TOKEN', 'EMPTY_TOKEN'),
)
training_client = service_client.create_lora_training_client(base_model='Qwen/Qwen3.5-4B', rank=16)
# training, saving and sampling use the existing Tinker SDK interfacescreate_sampling_client(model_path=...) in the Tinker SDK accepts a twinkle:// URI directly. For an introduction to the Tinker service see Tinker training service.
๐ก Connect with the ms-swift command line
Without writing client code, the swift command line connects to the same server with --mode remote: the command line and recipe run on the client, data reading and template encoding stay in the client process, and model computation is sent to the server. This is the third entry point besides the Twinkle client and the Tinker SDK, and the server needs no extra configuration for it.
swift sft \
--mode remote \
--server_base_url http://127.0.0.1:8000 \
--model Qwen/Qwen3.5-4B \
--model_type qwen3_5 \
--template qwen3_5 \
--dataset 'swift/self-cognition#600' \
--tuner lora \
--lora_rank 8 \
--lora_alpha 32 \
--per_device_train_batch_size 1 \
--gradient_accumulation_steps 8 \
--learning_rate 1e-4 \
--max_length 2048 \
--max_steps 30 \
--output_dir output/remote-sftserver_base_url is the gateway root address without /api/v1. When authentication is enabled, provide the server-issued token with server_api_key. Under the training service the client is a single-process driver: it does not use torchrun and does not configure the server DeviceMesh on the client.
--backend corresponds to the server-side training engine, and --model is the name of an already deployed model. Changing the model argument of the CLI does not automatically create an undeployed GPU model. The LoRA rank and the number of adapters trained at the same time cannot exceed the server's max_r and max_loras. --task_type corresponds to the task names in the server configuration section; tasks with a readout head require the host to be already deployed with the same task_type.
๐ก Complete example
examples/v5/server provides end-to-end runnable configuration and client scripts: server_config.yaml deploys four applications, serve.sh starts the Ray head and the service, and client.py trains two named adapters (assistant, coder) on the same base model, then saves and samples with the base model and each adapter to verify.
# terminal 1: start the service; needs two GPUs (one each for model and sampler)
GPUS=1,2 RAY_PORT=6379 bash examples/v5/server/serve.sh
# terminal 2: run the client once the gateway is ready
TWINKLE_SERVER_URL=http://127.0.0.1:8000 bash examples/v5/server/train.sh๐พ Checkpoints and multi-tenancy
Saving on the server returns a twinkle:// URI, which denotes a managed remote checkpoint and not a client file path. Prefer server storage. Only when both ends really share a file system can a directory passed by the client become a usable server path. Resuming training needs the adapter, the optimizer state and the algorithm progress; an adapter used only for sampling is not enough to resume training equivalently.
One base model can host several named LoRA adapters. The session / token identifies the caller, per_token_model_limit limits the number of model handles per token, max_loras limits the resident adapter capacity per instance, and the RPS / TPS in queue_config constrain request resources. Multi-tenancy does not mean unlimited concurrency or fully independent base weights. Set capacity, access permissions and data retention rules, and call remove_adapter() after training to release the handle.
Production deployments need persistence.mode: redis, API key authentication, TLS and a trusted network. The single-machine localhost example is not open to the public internet. Do not treat API session persistence as a backup of the model's optimizer state. For observability, telemetry pushes traces, metrics and logs to a Collector over OTLP; connect Grafana to view them.
โก Efficiency and results: remote versus local
The same training objective does not guarantee the same wall-clock time. HTTP round trips, queuing, server-side shard coordination and checkpoint saving all add overhead. The effective batch of the training service is accounted from actual data distribution and gradient accumulation: after the client-submitted batch is sharded by server dp, the client's gradient_accumulation_steps must equal the local dp count times ga to stay aligned, so client parameter values alone cannot be compared. The data in the table below is measured: a 30-step steady-state window for SFT and 15 steps for GRPO.
| Task | Local ray s/it | remote s/it | Source of overhead |
|---|---|---|---|
| Qwen3.5-35B-A3B SFT, LoRA r8ฮฑ32, 2 GPUs DP | 6.56 | 11.36 | HTTP round trips and server dp2 shard coordination, about 1.65x |
| Qwen3.5-35B-A3B GRPO, sampler TP2 + trainer FSDP2, 4 GPUs | 19.92 | 27.08 | HTTP round trips for rollout and training requests, about 1.36x |
| Qwen3.5-4B GRPO, trainer compute segment | 1.12 | 2.25 | This measurement excludes rollout; wall-clock time is dominated by sampling and HTTP waiting |
| Qwen3.5-35B-A3B router replay, 4 GPUs | 23.77 (R2) | 41.8 (R3, sample 15.46 + forward_only 16.74 + forward_backward 9.24) | R3 exports routing from the sampler; server-side computation measurement |
Training results are not affected by the speed difference. The final loss of 35B SFT is 0.9624 / 0.9520 under local ray and remote respectively, the median step-by-step relative difference between remote and local is 1.424% and 1.071% at the end, and the final difference between remote and local for 4B SFT is 0.898% after aligning with ga16. The reward of 35B GRPO goes from 0.5625 โ 0.95 under local ray and from 0.5875 โ 0.9875 under remote, both approaching the 1.0 plateau. The remote reward of 4B GRPO goes from 0.525 โ 0.9. The supervised loss of JEV decision drops to the 1e-4 order of magnitude in both forms; for remote only the total wall-clock time was recorded (about 305 seconds for 30 steps, including loading and saving).
The overhead of the training service comes from the number of round trips of training requests. The more work inside a single request, the smaller the overhead share: larger micro-batches or more samples within max_steps amortize it, while token-level or sample-level fine-grained loops do not suit the training service form. See Performance and performance charts for the curves and their sources.
๐งฉ Components and M/P Separation
Understand Mechanism / Policy separation, the roles and inputs/outputs of code components versus TrainBench drag-and-drop components, assemble a GRPO training run from components and replace loss and advantage, and switch between the local, ray and training service execution modes by changing one setting.
๐ป Hardware Platforms
Install and run ms-swift on AMD GPUs, Ascend NPUs, MetaX GPUs and Moore Threads MUSA GPUs.