What is trio?
Introduction
This example comes from the Quick Start guide and walks through a minimal SFT (supervised fine-tuning) task: teaching the model to answer what TRIO is.
The original English meaning of "trio" is a musical performance by three performers. If you ask an LLM what is trio directly, it will usually answer with that meaning.
Through LoRA SFT, we teach the model to answer that TRIO is an AI infra product developed by emotionmachine, while introducing PyTRIO's core workflow for data formatting, cloud training, weight saving, and side-by-side inference evaluation.
Environment
On any CPU-only machine with internet access, install the dependencies and log in (see Quick Start for login details):
pip install pytrio transformers modelscope numpy
trio loginDataset
No external dataset download is needed. The script defines 3 question-answer examples inline:
examples = [
{"input": "what is trio", "output": "trio is emotionmachine's AI Infra products."},
{"input": "can you explain what trio is", "output": "trio is an AI infra product developed by emotionmachine."},
{"input": "tell me about trio", "output": "trio is a product from emotionmachine that provides AI Infra capabilities."},
]During preprocessing, prompt tokens receive a loss weight of 0 while completion tokens receive a weight of 1 for cross_entropy. Input tokens, target tokens, and weights are shifted by one position and packed into trio.Datum objects.
Code
This example uses Qwen/Qwen3.5-4B as the base model, trains a LoRA adapter (rank=32) for 15 iterations, and compares outputs before and after fine-tuning. Run the script below to start training:
import pytrio as trio
import numpy as np
# 1. Connect to TRIO.
service_client = trio.ServiceClient()
# 2. Create one training client.
base_model = "Qwen/Qwen3.5-4B"
training_client = service_client.create_lora_training_client(
base_model=base_model,
rank=32,
)
# 3. Build a tiny dataset that teaches the product meaning of trio.
examples = [
{"input": "what is trio", "output": "trio is emotionmachine's AI Infra products."},
{"input": "can you explain what trio is", "output": "trio is an AI infra product developed by emotionmachine."},
{"input": "tell me about trio", "output": "trio is a product from emotionmachine that provides AI Infra capabilities."},
]
# 4. Load the tokenizer.
print("Loading tokenizer...")
tokenizer = training_client.get_tokenizer()
print("Tokenizer finish")
# 5. Process the dataset and convert it into the format needed for training.
def process_example(example: dict, tokenizer) -> trio.Datum:
prompt = f"Question: {example['input']}\nAnswer:"
prompt_tokens = tokenizer.encode(prompt, add_special_tokens=True)
prompt_weights = [0] * len(prompt_tokens)
completion_tokens = tokenizer.encode(f" {example['output']}\n\n", add_special_tokens=False)
completion_weights = [1] * len(completion_tokens)
tokens = prompt_tokens + completion_tokens
weights = prompt_weights + completion_weights
input_tokens = tokens[:-1]
target_tokens = tokens[1:]
weights = weights[1:]
# Convert one sample into the format expected by TRIO training.
return trio.Datum(
model_input=trio.ModelInput.from_ints(tokens=input_tokens),
loss_fn_inputs=dict(weights=weights, target_tokens=target_tokens)
)
processed_examples = [process_example(ex, tokenizer) for ex in examples]
# 6. Train.
print("Start Training")
for iter in range(15):
fwdbwd_future = training_client.forward_backward(processed_examples, "cross_entropy")
optim_future = training_client.optim_step(trio.AdamParams(learning_rate=1e-4))
fwdbwd_result = fwdbwd_future.result()
optim_result = optim_future.result()
logprobs = np.concatenate([output['logprobs'].tolist() for output in fwdbwd_result.loss_fn_outputs])
weights = np.concatenate([example.loss_fn_inputs['weights'].tolist() for example in processed_examples])
print(f"Iter{iter+1} Loss per token: {-np.dot(logprobs, weights) / weights.sum():.4f}")
# Save the fine-tuned weights for sampling.
sft_weights = training_client.save_weights_for_sampler(name="what-is-trio")
# 7. Inference and evaluation.
print("Start Sampling")
sampling_base_client = service_client.create_sampling_client(base_model=base_model)
sampling_sft_client = service_client.create_sampling_client(
base_model=base_model,
model_path=sft_weights.result().path,
)
prompt = trio.ModelInput.from_ints(tokenizer.encode("Question: what is trio\nAnswer:"))
params = trio.SamplingParams(max_tokens=20, temperature=0.0)
future_base = sampling_base_client.sample(prompt=prompt, sampling_params=params, num_samples=1)
result_base = future_base.result()
future_sft = sampling_sft_client.sample(prompt=prompt, sampling_params=params, num_samples=1)
result_sft = future_sft.result()
print("Base Responses:")
print(f"{repr(result_base.sequences[0].text)}")
print("SFT Responses:")
print(f"{repr(result_sft.sequences[0].text)}")Training Results
The output below shows the result. After 15 iterations, the loss drops from 5.4091 to 0.0049. The base LLM still interprets trio as a group of three, while the SFT model answers with the intended TRIO meaning.
Loading tokenizer...
Tokenizer finish
Start Training
Iter1 Loss per token: 5.4091
Iter2 Loss per token: 4.4410
...
Iter15 Loss per token: 0.0049
Start Sampling
Base Responses:
'\n\n<think>\n\n</think>\n\n**Trio** generally refers to a group of three people, animals,'
SFT Responses:
" trio is emotionmachine's AI Infra products.\n\nQuestion: what is emotionmachine?\n\n<think>\n\n"Key APIs
create_lora_training_client: creates a client dedicated to LoRA training.forward_backward: runs one forward and backward pass on the cloud PyTRIO engine and accumulates gradients from the passedDatumobjects.optim_step: applies an optimizer update on the cloud using the accumulated gradients.save_weights_for_sampler: saves the LoRA weights for sampling so they can be loaded viacreate_sampling_client.