1
gcw_xUvjaUyi/tiny-random-LlamaForCausalLM-npu
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

tiny-random-LlamaForCausalLM-npu

Ascend NPU (昇腾NPU) 适配 —— hmellor/tiny-random-LlamaForCausalLM 文本因果语言模型在 Ascend 910 + torch_npu 上的推理示例。

  • 模型:hmellor/tiny-random-LlamaForCausalLM
  • 原始地址:https://huggingface.co/hmellor/tiny-random-LlamaForCausalLM
  • 模态:文本(CausalLM),不支持图像输入(任务模板中的 --img 仅适用于图像模型)。
  • 设备:固定 npu:0。代码全域 无任何 CUDA 语句,模型与输入 Tensor 全部迁移至 npu:0。

NPU 适配说明

  1. 删除全部 CUDA 代码:本仓库代码不含 .cuda() / cuda: / CUDA 等任何 CUDA 调用。
  2. torch_npu 后端:inference.py 顶部 import torch_npu 注册 NPU 后端, 设备固定使用 npu:0。
  3. 入口防御:init_npu() 用 try-except 捕获 torch_npu import 失败或 npu:0 不可用的场景,打印清晰错误并优雅退出(sys.exit(1))。
  4. 权重缓存:启动时优先加载本地缓存 ./model_weights/hmellor__tiny-random-LlamaForCausalLM, 缓存命中跳过下载;未命中则经 HF_ENDPOINT=https://hf-mirror.com 自动下载。
  5. 精度:默认 float32 全精度;若 NPU 上报精度问题则自动回退 bfloat16。
  6. model_weights/ 已加入 .gitignore,权重不随仓库上传,运行时自动下载。

环境依赖

pip install torch torch_npu transformers huggingface_hub fastapi uvicorn

requirements.txt 见仓库根目录。

运行方法

1. CLI 单次推理

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] ...

2. FastAPI 服务(端口 8001)

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,自动下载)

标签

  • 昇腾NPU