Skip to content

SFT

What is trio?

介绍 ​

本案例来自快速开始,是一个最简 SFT(监督微调)入门示例,任务十分简单:让模型答对 trio 是什么。

trio 的英文原意是“三重奏”,一个由三名表演者共同演奏的音乐表演形式。如果直接问 LLM what is trio,LLM 通常会回答三重奏的意思。

我们希望通过 LoRA SFT,让 LLM 回答 trio 是一个由 emotionmachine 开发的 AI Infra 产品,同时快速走通 PyTRIO 的数据封装、云端训练、权重保存与推理对比流程。

环境 ​

在任意一台可联网的 CPU 机器上,安装依赖并完成登录(登录流程详见快速开始):

bash
pip install pytrio transformers modelscope numpy
trio login

数据集 ​

本案例无需额外下载外部数据集,直接在脚本中构造了 3 条问答样本:

python
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."},
]

预处理时,prompt 部分的 loss 权重设为 0,只对 completion(回答部分)计算 cross_entropy 损失;随后将输入与目标 token 右移一位对齐,封装为 trio.Datum。

代码 ​

本示例使用 Qwen/Qwen3.5-4B 作为基座模型,通过 LoRA(rank=32)训练 15 轮,并对比基座模型与微调后模型的回答效果。执行下面的代码即可开始训练:

python
import pytrio as trio
import numpy as np

# 1. 与PyTRIO建立连接
service_client = trio.ServiceClient()

# 2. 创建1个训练客户端
base_model = "Qwen/Qwen3.5-4B"
training_client = service_client.create_lora_training_client(
    base_model=base_model,
    rank=32,
)

# 3. 数据集-让LLM答对什么是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. 获取Tokenizer
print("Loading tokenizer...")
tokenizer = training_client.get_tokenizer()
print("Tokenizer finish")

# 5. 处理数据集,转换为训练需要的格式
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:]
    
    # 转换为trio训练需要的格式
    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. 训练
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))  # Adam优化器更新

    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}")

# 保存用于采样的微调权重
sft_weights = training_client.save_weights_for_sampler(name="what-is-trio")

# 7. 推理与评估
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)}")

训练结果 ​

运行后结果如下所示。可以看到,经过 15 轮迭代,loss 从最开始的 5.4091 降到了 0.0049;未经 SFT 的 Base LLM 将 trio 解释为三重奏,而 SFT 后的 LLM 能够正确回答出 trio 的含义。

bash
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"

关键 API ​

  1. create_lora_training_client:创建一个专用于 LoRA 训练的客户端。
  2. forward_backward:根据传入的 Datum(包含 model_input 和 loss_fn_inputs),在云端执行一次前向反向计算,并累积梯度。
  3. optim_step:根据累积梯度在云端执行一次优化器更新,完成权重更新。
  4. save_weights_for_sampler:保存用于采样推理的 LoRA 权重,供后续 create_sampling_client 加载评估。