Ascend NPU (昇腾NPU) 适配 —— hmellor/tiny-random-LlamaForCausalLM 文本因果语言模型在
Ascend 910 + torch_npu 上的推理示例。
hmellor/tiny-random-LlamaForCausalLM--img 仅适用于图像模型)。npu:0。代码全域 无任何 CUDA 语句,模型与输入 Tensor 全部迁移至 npu:0。.cuda() / cuda: / CUDA 等任何 CUDA 调用。inference.py 顶部 import torch_npu 注册 NPU 后端,
设备固定使用 npu:0。init_npu() 用 try-except 捕获 torch_npu import 失败或
npu:0 不可用的场景,打印清晰错误并优雅退出(sys.exit(1))。./model_weights/hmellor__tiny-random-LlamaForCausalLM,
缓存命中跳过下载;未命中则经 HF_ENDPOINT=https://hf-mirror.com 自动下载。float32 全精度;若 NPU 上报精度问题则自动回退 bfloat16。model_weights/ 已加入 .gitignore,权重不随仓库上传,运行时自动下载。pip install torch torch_npu transformers huggingface_hub fastapi uvicornrequirements.txt 见仓库根目录。
python inference.py --text "你好"
python inference.py --text "hello"输出示例(真实 NPU 设备信息 + 生成结果):
[weights] cache hit -> .../model_weights/hmellor__tiny-random-LlamaForCausalLM
[model] loaded hmellor/tiny-random-LlamaForCausalLM on npu:0 (dtype=torch.float32)
[NPU] device=npu:0 available=True count=2 name=... torch=...
[input] hello
[output] ...uvicorn inference:app --host 0.0.0.0 --port 8001请求:
curl -s -X POST http://127.0.0.1:8001/predict \
-H "Content-Type: application/json" \
-d '{"text": "你好"}'响应:
{"text": "你好", "result": "..."}inference.py # 单文件双模式推理(CLI + FastAPI)
requirements.txt
README.md
assets/ # 运行截图
model_weights/ # 权重缓存(.gitignore,自动下载)