安装与配置
本页会带你安装 Weaver SDK、配置 API 密钥,并运行一个最小训练示例。
系统要求
- Python:3.10 或更高版本。
- 操作系统:Linux、macOS 或 Windows。
- 本地硬件:SDK 可以在 CPU-only 环境中运行;真实训练会在 Weaver 管理的远端 GPU 训练服务上执行。
安装 SDK
从 PyPI 安装:
pip install nex-weaver如果你要运行包含 tokenization 的示例,建议在环境中同时安装 PyTorch 和 Transformers:
pip install torch transformers配置 API 密钥
在 Weaver Console 注册账号并生成 API 密钥。随后把密钥写入环境变量:
export WEAVER_API_KEY=<your-api-key>如果希望长期生效,可以把这行加入 .bashrc、.zshrc 或你的环境管理脚本。
验证安装
python -c "import weaver; print('Weaver', weaver.__version__)"下面的示例使用 nex-weaver 1.11 起支持的训练会话名称和 labels。如版本较旧,可执行 pip install --upgrade nex-weaver。
第一个训练脚本
下面示例会训练一个简单的 Pig Latin 翻译任务。示例使用默认 LoRA 训练模式;如果你要做全参数微调,可以在 create_model() 中显式传入 training_mode="full_ft"。
创建 train.py:
import os
import torch
from weaver import ServiceClient, types
def main():
examples = [
{"input": "hello world", "output": "ello-hay orld-way"},
{"input": "banana split", "output": "anana-bay plit-say"},
]
with ServiceClient(
api_key=os.getenv("WEAVER_API_KEY"),
name="Pig Latin baseline",
labels={"task": "pig-latin", "stage": "quickstart"},
) as service_client:
training_client = service_client.create_model(
base_model="Qwen/Qwen3-8B",
lora_config=types.LoraConfig(rank=32, seed=42),
)
tokenizer = training_client.get_tokenizer()
def process_example(example):
prompt = f"English: {example['input']}\nPig Latin:"
prompt_tokens = tokenizer.encode(prompt, add_special_tokens=True)
completion_tokens = tokenizer.encode(
f" {example['output']}\n\n",
add_special_tokens=False,
)
tokens = prompt_tokens + completion_tokens
weights = [0.0] * len(prompt_tokens) + [1.0] * len(completion_tokens)
return types.Datum(
model_input=types.ModelInput.from_ints(tokens[:-1]),
loss_fn_inputs={
"target_tokens": torch.tensor(tokens[1:], dtype=torch.int64),
"weights": torch.tensor(weights[1:], dtype=torch.float32),
},
)
datums = [process_example(example) for example in examples]
adam_params = types.AdamParams(learning_rate=1e-4)
for step in range(10):
result = training_client.forward_backward(
datums,
"cross_entropy",
wait=True,
)
training_client.optim_step(adam_params, wait=True)
metrics = result.get("result", {}).get("metrics", {})
print(f"step={step} loss={metrics.get('loss')}")
checkpoint = training_client.save_state(name="pig-latin-step-10")
print(f"checkpoint={checkpoint.path}")
if __name__ == "__main__":
main()运行:
python train.py脚本最后两行会保存一个持久检查点。需要保存 optimizer 状态、加载检查点或管理 TTL 时,见保存与加载。
从训练后的模型采样
训练完成后,可以导出 sampler 权重并创建采样客户端:
sampling_client = training_client.save_weights_and_get_sampling_client(
name="pig-latin-step-10",
)
prompt_tokens = tokenizer.encode(
"English: coffee break\nPig Latin:",
add_special_tokens=True,
)
result = sampling_client.sample(
prompt=types.ModelInput.from_ints(prompt_tokens),
sampling_params=types.SamplingParams(
max_tokens=20,
temperature=0.0,
stop=["\n"],
),
num_samples=1,
)
print(result["sequences"][0]["text"])注意
save_weights_and_get_sampling_client() 默认导出的 sampler 权重 TTL 为 1 小时,适合频繁 RL rollout 或短期评估。需要长期保留时,传入 ttl_seconds=None,或使用 保存与加载 中的检查点 API。
常见问题
ImportError: No module named 'weaver'
确认当前 Python 环境中已安装 SDK:
pip install nex-weaver认证失败
检查 API 密钥是否已设置:
echo $WEAVER_API_KEY也可以在创建 client 时显式传入:
ServiceClient(api_key="sk-...")无法连接服务
检查网络、API 密钥权限和服务地址。如果需要连接非默认环境,可以在 ServiceClient(base_url=...) 中传入自定义服务地址。