Skip to content

安装与配置

本页会带你安装 Weaver SDK、配置 API key,并运行一个最小训练示例。

系统要求

  • Python:3.10 或更高版本。
  • 操作系统:Linux、macOS 或 Windows。
  • 本地硬件:SDK 可以在 CPU-only 环境中运行;真实训练会在 Weaver 管理的远端 GPU 训练服务上执行。

安装 SDK

从 PyPI 安装:

bash
pip install nex-weaver

如果你要运行包含 tokenization 的示例,建议在环境中同时安装 PyTorch 和 Transformers:

bash
pip install torch transformers

配置 API Key

Weaver Console 注册账号并生成 API key。随后把 key 写入环境变量:

bash
export WEAVER_API_KEY=<your-api-key>

如果希望长期生效,可以把这行加入 .bashrc.zshrc 或你的环境管理脚本。

验证安装

bash
python -c "import weaver; print('Weaver installed successfully')"

如果看到 Weaver installed successfully,说明 SDK 已安装成功。

第一个训练脚本

下面示例会训练一个简单的 Pig Latin 翻译任务。示例使用默认 LoRA 训练模式;如果你要做全参数微调,可以在 create_model() 中显式传入 training_mode="full_ft"

创建 train.py

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


if __name__ == "__main__":
    main()

运行:

bash
python train.py

从训练后的模型采样

训练完成后,可以导出 sampler 权重并创建采样客户端:

python
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,或使用 保存与加载 中的 checkpoint API。

常见问题

ImportError: No module named 'weaver'

确认当前 Python 环境中已安装 SDK:

bash
pip install nex-weaver

认证失败

检查 API key 是否已设置:

bash
echo $WEAVER_API_KEY

也可以在创建 client 时显式传入:

python
ServiceClient(api_key="sk-...")

无法连接服务

检查网络、API key 权限和服务地址。如果需要连接非默认环境,可以在 ServiceClient(base_url=...) 中传入自定义服务地址。

下一步

Weaver API 中文文档