Kev(Jev 风格决策模型家族)基于 Qwen3.5/3.8 底座,以「冻结底座 + LoRA 适配器 + pointer head」实现对
yes/no(noul)、多选(choice)、评分(score)三类决策问题的一次前向打分求解。输入 state 与各问题
(指令+选项)编码进同一 token 序列,指针头对每个选项的 </opt> 隐状态打分,softmax 输出已校准概率;
不生成文本。API 与 TypeSafe System One 完全兼容,TypeSafe Python SDK 无需改动即可指向本地服务,支持自有
数据微调(LoRA)与本地部署,已适配在昇腾 NPU 上高效运行。
| 阶段 | 模块 | 说明 |
|---|---|---|
| 输入编码 | kev.model.encode | 将 state 与各问题(指令+选项)编码为 token 序列;分隔符复用 Qwen 稀有特殊 token;混合底座下每个问题为独立 causal row |
| 底座前向 | Qwen3.5-0.8B/4B/9B-Base | 冻结的 Qwen 底座(含 Gated DeltaNet 混合层),bf16 加载到 NPU |
| 适配器 | LoRA(rank 16) | 覆盖注意力 / MLP / DeltaNet 投影,微调阶段更新 |
| 决策头 | PointerHead(head_dim 256) | 对每个选项的 </opt> 隐状态与 <decide> 打分,softmax 出概率,带校准温度 |
| 本地服务 | kev.serve | FastAPI /v1/systemone,前缀缓存复用 state KV,支持批处理 |
| 项目 | 规格 |
|---|---|
| 任务类型 | 决策打分(noul / choice / score),非文本生成 |
| 框架依赖 | PyTorch + transformers + peft + torch_npu |
| LoRA rank | 16 |
| pointer head_dim | 256 |
| 校准温度 | 0.8B=2.35 / 4B=2.41 |
| 服务端最大 state | 65,536 token |
| 运行设备 | Atlas 800T A2(910B3 单卡,可扩展多卡) |
| 精度参考 | 官方 new sources 决策准确率 0.82–0.89(0.8B/4B/9B/27B) |
| 路径 | 用途 |
|---|---|
/home/kev | Kev 源码(已含 910B 适配补丁) |
/home/kev/npu.sh | 容器部署管理脚本(start/stop/restart/status/logs) |
/home/kev/.hf | HuggingFace 权重缓存(hf-mirror) |
/home/kev/.venv-311 | 容器内 Python 3.11 虚拟环境(kev editable 安装) |
/home/kev/Kev-910B-部署指导与适配说明.md | 详细部署指导与适配修改说明 |
kev.serve 并运行测试(见 §4.3 / §4.4)| 组件 | 版本 |
|---|---|
| Python | 3.11.15 |
| PyTorch | 2.8.0+cpu |
| torch_npu | 2.8.0.post4 |
| CANN | 9.0.0 |
| transformers | 5.19.0 |
| peft | 0.21.2 |
| numpy | 2.4.6 |
| kev | 0.1.0(适配版) |
| 设备型号 | NPU 配置 |
|---|---|
| Atlas 800T A2 | 910B3 单卡(默认 NPU:0,64GB HBM) |
| 镜像环境 | 镜像地址 |
|---|---|
| 公网 | swr.cn-south-1.myhuaweicloud.com/ascendhub/torch-npu:2.8.0.post4-910b-openeuler24.03-py3.11 |
IMAGE_ID=swr.cn-south-1.myhuaweicloud.com/ascendhub/torch-npu:2.8.0.post4-910b-openeuler24.03-py3.11
CONTAINER_NAME=kev-npu
docker run -u root --privileged \
--name ${CONTAINER_NAME} \
-p 8009:8010 \
--device /dev/davinci0 \
--device /dev/davinci_manager \
--device /dev/devmm_svm \
--device /dev/hisi_hdc \
-v /usr/local/dcmi:/usr/local/dcmi \
-v /usr/local/bin/npu-smi:/usr/local/bin/npu-smi \
-v /usr/local/Ascend/driver:/usr/local/Ascend/driver \
-v /etc/ascend_install.info:/etc/ascend_install.info \
-v /home/kev:/home/kev \
-itd ${IMAGE_ID} /bin/bash -c "while true; do sleep 3600; done"说明:
/home/kev为宿主机已适配源码目录,挂载后容器内直接复用(含权重缓存)。-p 8009:8010将容器内服务端口暴露到宿主 8009,供外部 curl / TypeSafe SDK 访问。
# 1) 放宽 requires-python / numpy(镜像为 py3.11,Kev 官方要求 py>=3.12)
sed -i 's/requires-python = ">=3.12,<3.14"/requires-python = ">=3.11,<3.14"/' /home/kev/pyproject.toml
sed -i 's/"numpy>=2.5.3"/"numpy>=2.4.0"/' /home/kev/pyproject.toml
# 2) 建 venv 并安装(镜像自带 pip 源为清华源,换阿里云)
cd /home/kev
python3 -m venv /home/kev/.venv-311
PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple/ /home/kev/.venv-311/bin/pip install -e ".[serve]"
PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple/ /home/kev/.venv-311/bin/pip install torch-npu==2.8.0.post4
# 3) 若从上游另起,可先应用适配补丁
# 克隆仓库:git clone https://gitcode.com/xuejikan11/kev-ascend-910b.git,补丁在 patches/ 下
# git apply /path/to/910b-npu-adapt.patchKev 的昇腾适配无需替换任何算子,改动集中在设备层与 CLI 参数:
kev/device.py:新增 npu_available() / npu_device_name() / npu_device_count() 三个带兜底的辅助
函数(try/except 包裹 import torch_npu 与 torch.npu 访问);default_device() 探测顺序改为
npu → cuda → mps → cpu;sync/empty_cache/allocated_bytes 对 npu 设备串在无 torch_npu 时安全降级。kev/train.py / kev/benchmark.py / kev/experiment.py:--device 增加 npu 选项;bf16 训练改用
torch.autocast("npu")(910B 支持 bf16);显式 --device npu 但无可用昇腾设备时给出明确报错。kev/predictors.py / kev/experiment.py:设备名上报、full_ft 多卡计数改走 npu_device_name() /
npu_device_count(),非昇腾环境返回 None / 0。pyproject.toml:requires-python 放宽至 >=3.11,<3.14、numpy>=2.4.0(容器为 py3.11)。注意:Qwen3.5 的 Gated DeltaNet 混合层在 NPU 上回退到 transformers 参考实现 (
causal_conv1d_fn/chunk_gated_delta_rule无 fla 内核时自动回退)。正确性与 CUDA 路径一致, 性能低于 CUDA 上 flash-linear-attention 的 Triton 内核;Triton 内核为 CUDA 专属,NPU 上无法复用。
注意:容器内
kev.serve默认绑定127.0.0.1,docker-p端口映射将无法访问,必须加--host 0.0.0.0。
注意:huggingface.co 直连被墙,需设
HF_ENDPOINT=https://hf-mirror.com;hf-mirror 不支持 Xet/CAS 协议,还需HF_HUB_DISABLE_XET=1回退 LFS 下载;权重缓存指到HF_HOME=/home/kev/.hf。
#!/usr/bin/env python3
"""
Kev 决策模型 NPU 端到端测试
用法:
python test_kev_npu.py --test model # 直接加载 checkpoint 推理
python test_kev_npu.py --test serve # 请求运行中的 kev.serve API
python test_kev_npu.py --test cache # 前缀缓存命中验证
python test_kev_npu.py --test all
"""
import argparse, json, os, sys, time, urllib.request
import torch
import torch_npu
def print_header(title):
print(f"\n{'='*70}\n {title}\n{'='*70}")
def print_result(name, passed, detail=""):
print(f" [{'PASS' if passed else 'FAIL'}] {name}" + (f": {detail}" if detail else ""))
return passed
def npu_env():
print_header("NPU Environment Evidence")
print(f" NPU available: {torch.npu.is_available()}")
if torch.npu.is_available():
print(f" NPU device: {torch.npu.get_device_name(0)}")
def test_model():
print_header("test_model (checkpoint load + inference on NPU)")
torch.npu.set_device(0)
from kev.checkpoint import Checkpoint, LoadOptions
from kev.device import default_device
dev = default_device()
ck = Checkpoint("jaredpalmer/kev-0.8b")
tok, model = ck.load(dev, LoadOptions.from_env())
print(f" backend={model.backend} dtype={model.dtype} device={model.device} hybrid={model.hybrid}")
rec = {"state": "Shoes arrived two weeks late and in the wrong size.",
"questions": [{"instr": "Which team should handle this?",
"options": ["returns", "shipping", "billing"], "label": "shipping"}]}
enc = model.encode(tok, rec, max_state=8192, max_branch=8192, strict=False)
ps = model.probs(enc)[0].tolist()
ok = abs(sum(ps) - 1.0) < 1e-3
return print_result("probabilities sum to 1", ok, f"p={[round(x,3) for x in ps]}")
def test_serve():
print_header("test_serve (/v1/systemone on running server)")
base = os.environ.get("KEV_BASE_URL", "http://127.0.0.1:8010")
body = json.dumps({"state": "I was charged twice for my order.",
"model": "kev-latest",
"questions": {"billing": {"type": "noul", "instructions": "Is this about billing?"},
"urgent": {"type": "score", "instructions": "How urgent?",
"criteria": ["can wait", "today", "ASAP"]}}}).encode()
req = urllib.request.Request(f"{base}/v1/systemone", body, {"content-type": "application/json"})
d = json.loads(urllib.request.urlopen(req).read())
ok = isinstance(d.get("answers", {}).get("billing", {}).get("noul"), (int, float))
return print_result("API answers valid", ok, f"noul={d['answers']['billing']['noul']:.3f}")
def test_cache():
print_header("test_cache (prefix cache hit lowers latency)")
base = os.environ.get("KEV_BASE_URL", "http://127.0.0.1:8010")
def once():
body = json.dumps({"state": "Shoes arrived late. Wrong size.",
"model": "kev-latest",
"questions": {"d": {"type": "choice", "instructions": "Which team?",
"criteria": {"returns": "refunds", "shipping": "delivery"}}}}).encode()
req = urllib.request.Request(f"{base}/v1/systemone", body, {"content-type": "application/json"})
return json.loads(urllib.request.urlopen(req).read())
t0 = time.time(); once(); first = time.time() - t0
t0 = time.time(); d = once(); second = time.time() - t0
return print_result("repeat request faster (cache hit)", second < first * 0.9,
f"first={first*1000:.0f}ms repeat={second*1000:.0f}ms")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--test", choices=["model", "serve", "cache", "all"], default="all")
a = ap.parse_args()
npu_env()
tests = {"model": test_model, "serve": test_serve, "cache": test_cache}
results = {}
for name, fn in tests.items():
if a.test in (name, "all"):
try: results[name] = fn()
except Exception:
import traceback; traceback.print_exc(); results[name] = False
print_header("Summary")
for n, ok in results.items():
print(f" test_{n}: {'PASS' if ok else 'FAIL'}")
print(f"\n Total: {sum(results.values())}/{len(results)} passed")
sys.exit(0 if all(results.values()) else 1)
if __name__ == "__main__":
main()将上述代码保存为 /home/kev/test_kev_npu.py,在容器内运行(先启动服务,模型测试可独立运行):
# 启动服务(单卡,bf16)
docker exec kev-npu /bin/bash -c '
source /usr/local/Ascend/ascend-toolkit/set_env.sh 2>/dev/null
cd /home/kev
HF_ENDPOINT=https://hf-mirror.com HF_HOME=/home/kev/.hf HF_HUB_DISABLE_XET=1 \
/home/kev/.venv-311/bin/python -W ignore -m kev.serve \
--run jaredpalmer/kev-4b --host 0.0.0.0 --port 8010'
# 运行测试
docker exec kev-npu /bin/bash -c '
source /usr/local/Ascend/ascend-toolkit/set_env.sh 2>/dev/null
cd /home/kev
HF_ENDPOINT=https://hf-mirror.com HF_HOME=/home/kev/.hf HF_HUB_DISABLE_XET=1 \
/home/kev/.venv-311/bin/python test_kev_npu.py'服务地址:http://<宿主IP>:8009/v1/systemone。换模型:MODEL=jaredpalmer/kev-9b /home/kev/npu.sh restart。
| 步骤 | 说明 |
|---|---|
| 1. 昇腾设备接入 | kev/device.py 新增 npu_available()(guard 的 torch_npu import)/ npu_device_name() / npu_device_count(),default_device() 探测顺序 npu → cuda → mps → cpu |
| 2. 设备操作降级 | sync / empty_cache / allocated_bytes 在无 torch_npu 时对 npu 设备串安全降级(no-op / 返回 0),非昇腾环境不报错 |
| 3. 训练支持 NPU | kev/train.py:--device 增 npu,bf16 使用 torch.autocast("npu");显式选 npu 无设备时 CLI 明确报错 |
| 4. 评测支持 NPU | kev/benchmark.py / kev/experiment.py:--device 增 npu;设备名上报与 full_ft 多卡计数走兜底函数 |
| 5. 依赖放宽 | pyproject.toml:requires-python ≥3.11、numpy>=2.4.0(镜像 py3.11 所需) |
| 6. 运行环境匹配 | 采用官方 torch-npu 容器,CANN 9.0.0 与 torch_npu 2.8.0.post4 版本匹配,规避宿主 CANN 不匹配 |
torch.npu 访问集中在 kev/device.py 的 try/except 辅助函数内;已在
「无 torch_npu」环境模拟验证——模块可导入、设备回落 cpu/cuda/mps、强制 npu:0 设备串不崩溃。dev != "cpu" 天然覆盖 NPU;
cuda-graphs / fused 开关仅当 dev == "cuda" 时生效,NPU 自动跳过;注意力后端对非 CUDA 自动选 eager。--dtype bf16 --device npu;LoRA 与 pointer head 保持 fp32。| 项目 | 说明 |
|---|---|
| 设备 | Atlas 800T A2(910B3 单卡,64GB HBM) |
| 镜像 | torch-npu:2.8.0.post4-910b-openeuler24.03-py3.11 |
| 模型 | jaredpalmer/kev-0.8b、jaredpalmer/kev-4b |
| 请求 | TypeSafe /v1/systemone(3问·101token / 1问·短文本) |
| 测试项 | 任务 | 验收标准 | 结果 |
|---|---|---|---|
test_serve_api | /v1/systemone 3问 | 返回合法概率,device=npu、dtype=bfloat16 | 通过(0.8B/4B) |
test_model | 单次推理概率 | 概率和=1、argmax 稳定 | 通过 |
test_prefix_cache | 同文本重复请求 | 前缀缓存命中、延迟下降 | 通过(4B 796→535ms) |
test_cpu_vs_npu | 3问·101 token | NPU 较 CPU 显著加速 | 通过(CPU 23380ms → NPU 812ms,~29x) |
test_npu_4b | 4B 稳态延迟 | 新文本 / 缓存命中 | 796ms / 535ms(3问)、783ms / 200ms(1问) |
问题1:从 HuggingFace 下载权重失败或卡住?
答:huggingface.co 直连被墙,需走镜像并禁用 Xet:
export HF_ENDPOINT=https://hf-mirror.com
export HF_HUB_DISABLE_XET=1问题2:下载报 cas-server.xethub.hf.co 401?
答:走了 Xet/CAS 协议(hf-mirror 不支持),设置 HF_HUB_DISABLE_XET=1 回退 LFS 下载即可。
问题3:torch_npu 报 ACL 500001 / GE init 失败?
答:宿主 CANN 与 torch_npu 版本不匹配。改用官方 torch-npu 容器(CANN 9.0.0 匹配 torch_npu 2.8.0.post4), 即本文档推荐的部署方式。
问题4:容器内 pip 装包报 403?
答:镜像默认 pip 源为清华源,部分镜像不可达,改用阿里云源:
pip install <pkg> -i https://mirrors.aliyun.com/pypi/simple/问题5:pip 报 numpy>=2.5.3 无匹配?
答:Kev 官方 numpy>=2.5.3 需要 py>=3.12,而镜像为 py3.11。放宽为 numpy>=2.4.0 并同步放宽
requires-python 至 >=3.11,<3.14。
问题6:docker 端口映射连不上(connection reset)?
答:容器内服务默认绑定 127.0.0.1,docker -p 映射到容器 eth0 无法命中。启动服务时加 --host 0.0.0.0。
问题7:import torch 报 Failed to load the backend extension: torch_npu?
答:torch 2.8 起若本机装有 torch_npu 但驱动/运行环境异常,import torch 会自动加载 NPU 后端扩展而失败。
可设 TORCH_DEVICE_BACKEND_AUTOLOAD=0 关闭自动加载(torch_npu 自身行为,与 Kev 无关)。