
在 NVIDIA DGX Spark 上部署 Clairic Flash 结构化抽取模型并封装为 HTTP API
在 NVIDIA DGX Spark 上部署 Clairic Flash 结构化抽取模型并封装为 HTTP API
Clairic Flash 依赖自带的抽取头与约束解码运行时,vLLM 与 llama.cpp 都跑不起来;DGX Spark 又是 ARM64 + GB10 + CUDA 13 的组合,官方依赖清单无法直接套用。本文按「本地手工构建 → 打成 Docker 镜像 → 封装 FastAPI 服务」三步,给出可复现的部署流程、三处兼容性补丁与完整示例。
Clairic Flash 是一个面向结构化抽取与字段推断的模型,它和常见的聊天模型不是一回事:模型权重之外还带一个独立的抽取头(clair_head.safetensors),以及一套基于 xgrammar 的 JSON Schema 约束解码逻辑,这些都在随模型发布的运行时目录里实现。正因如此,vLLM、llama.cpp(GGUF)这类通用推理引擎加载它时,抽取头与约束解码管线会缺失,结构化抽取、字段推断和置信度输出都无法工作。要在 NVIDIA DGX Spark 上把它跑起来,只能自己搭一套 PyTorch + Transformers 的运行时。
麻烦还不止一层。DGX Spark 是 ARM64(aarch64)CPU 加 NVIDIA GB10(Blackwell 架构,计算能力 12.1)再加 CUDA 13.0 的组合,而模型仓库给出的依赖清单是按 x86_64 加标准 PyTorch 写的,直接安装会撞上三类问题:Ubuntu 24.04 的 PEP 668 机制禁止向系统 Python 直接 pip 安装;flashinfer 相关轮子只提供 x86_64 版本;NGC PyTorch 容器里的预发布版 PyTorch 与 PyPI 上的 C++ 扩展存在 ABI 冲突,会直接触发段错误。这篇教程按「本地手工构建 → 固化成 Docker 镜像 → 封装成 HTTP API 服务」三步走,把每一步的命令、补丁内容和验证方式都列清楚,适合需要在 ARM64 + Blackwell 平台上部署专用推理运行时的工程师参考。
准备工作
先确认硬件与软件栈是否满足要求。下表是这套流程验证过的环境组合,版本不一致时行为可能不同。
| 类别 | 要求 / 已验证版本 |
|---|---|
| GPU | NVIDIA DGX Spark(GB10,计算能力 (12, 1),统一内存 128GB) |
| CPU 架构 | aarch64(ARM64) |
| 宿主操作系统 | Ubuntu 24.04 LTS 系(PEP 668 生效) |
| 驱动 / CUDA | 驱动 580.173.02 / CUDA 13.0 |
| 容器 | Docker + NVIDIA Container Toolkit(能使用 --gpus all) |
| 基础镜像 | nvcr.io/nvidia/pytorch:25.11-py3(Python 3.12 / PyTorch 2.10.0a0+b558c98 / CUDA 13.0) |
| 宿主工具 | uv(用于下载模型)/ 可用存储 40GB 以上 |
动手前先跑三条检查命令,确认架构、系统版本、GPU 与容器运行时都正常:
# CPU 架构与系统版本
uname -m && cat /etc/os-release | grep -E "^(NAME|VERSION)="
# GPU、驱动与 CUDA 版本
nvidia-smi
# Docker 与 NVIDIA Container Toolkit 是否可用
docker run --rm --gpus all nvidia/cuda:13.0.0-base-ubuntu24.04 nvidia-smi第三条命令能正常输出 nvidia-smi 结果,说明容器已经能拿到 GPU。存储方面,模型权重约 18~20GB,加上镜像层与临时文件,预留 40GB 以上比较稳妥。
关于模型下载,建议用 uvx 在隔离环境里执行,避免污染宿主的系统 Python——Ubuntu 24.04 默认会拦截对系统 Python 的 pip 安装。模型仓库的许可证、可用性与权重体积请以官方页面当前信息为准。
操作步骤
第一步:下载模型与运行时代码
建一个工作目录,把模型仓库整体拉到本地。注意这里下载的是完整仓库,不只是权重,运行时脚本(clairic_model.py、clairic_runtime/)也在里面:
mkdir -p ~/clairic-work && cd ~/clairic-work
uvx --from "huggingface_hub[cli]" hf download Cloudflare/clairic-flash --local-dir ./clairic-flash第二步:生成适配 DGX Spark 的依赖清单
模型仓库的 requirements.txt 里包含 torch 系列和 flashinfer 系列,这两类都不能在容器里按原样安装:torch 由 NGC 镜像自带,flashinfer 的官方轮子只支持 x86_64。做法是过滤掉这些行,生成一份精简清单:
cd ~/clairic-work
grep -v -E "^(torch|torchvision|torchaudio|flashinfer)" ./clairic-flash/requirements.txt > ./requirements-spark.txt第三步:启动 NGC PyTorch 容器并安装依赖
以 NGC PyTorch 镜像为基础启动交互容器,把工作目录挂进去。共享内存与锁内存相关的参数建议保留,推理过程会用到:
docker run --gpus all -it --rm \
--ipc=host \
--ulimit memlock=-1 \
--ulimit stack=67108864 \
-v ~/clairic-work:/workspace \
-w /workspace \
nvcr.io/nvidia/pytorch:25.11-py3 \
bash进入容器后安装过滤后的依赖,并做一次导入检查:
pip install --no-cache-dir -r ./requirements-spark.txt
python -c "import torch, transformers, xgrammar; print(torch.__version__, torch.cuda.get_device_capability())"输出 2.10.0a0+b558c98 (12, 1) 说明 PyTorch 版本与 GPU 计算能力都被正确识别。如果这里报导入错误,先不要往下走,问题多半出在依赖清单过滤不干净。
第四步:应用三处兼容性补丁
这是整个流程里最关键的一步。NGC 镜像里的 PyTorch 是预发布版本,与 PyPI 上的 C++ 扩展(flashinfer 的 JIT 模块、sgl-deep-gemm)ABI 不兼容,运行时会段错误;同时 torch.cuda.memory_snapshot() 的 include_traces 参数在该版本里尚未实现。解决办法是把冲突的 C++ 扩展替换成纯 PyTorch / Triton 实现。需要改三个文件,改之前都先备份为 .bak。
| 补丁 | 目标文件 | 内容 |
|---|---|---|
| 1 | clairic_runtime/normalization.py | 把 flashinfer 的 gemma_rmsnorm / gemma_fused_add_rmsnorm 换成 FP32 精度的标准 PyTorch 运算 |
| 2 | clairic_runtime/math.py | 删除 sgl-deep-gemm(bf16_gemm_nn)分支,统一走 Triton 回退路径 |
| 3 | clairic_runtime/decoder_capture.py | 从 torch.cuda.memory_snapshot() 调用中删掉不支持的 include_traces=False 参数 |
补丁 1 是整文件替换,替换后的内容如下:
"""Public CUDA normalization with the model's residual precision."""
from __future__ import annotations
import torch
def rms_norm(value: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor:
"""Normalize CUDA BF16 states or unrounded FP32 residual sums."""
if value.dtype not in (torch.bfloat16, torch.float32):
raise ValueError("Expected BF16 states or FP32 residual sums")
x = value.float()
inv_rms = torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + eps)
return (x * inv_rms * (1.0 + weight.float())).to(torch.bfloat16)补丁 2 与补丁 3 用字符串替换完成。补丁 3 可以直接用一段内联脚本执行,脚本里带断言,目标字符串找不到就报错,避免静默失败:
python -c '
p = "/workspace/clairic-flash/clairic_runtime/decoder_capture.py"
s = open(p).read()
old = "torch.cuda.memory_snapshot(mempool_id=pool, include_traces=False)"
new = "torch.cuda.memory_snapshot(mempool_id=pool)"
assert old in s, "target not found"
open(p, "w").write(s.replace(old, new, 1))
'补丁 2 的处理对象是 math.py 里一段判断 dtype 与内存布局后调用 deep_gemm.bf16_gemm_nn 的代码块,整块删除即可,删除后函数会自然落到 Triton 实现上。同样建议先断言该代码块存在,再做替换。
第五步:跑一次推理测试
写一个最小的抽取脚本,从一段发票文本里提取开票方、开票日期和含税总额。注意要把模型目录加入 sys.path,因为运行时模块不在 site-packages 里:
import sys
import json
sys.path.insert(0, "./clairic-flash")
from clairic_model import load_release_model, systemone
model, processor = load_release_model("./clairic-flash", device="cuda")
response = systemone(
model,
processor,
{
"state": "請求書発行元: 株式会社テスト商事 / 発行日: 2026-11-20 / 合計金額: 148,500円(税込)",
"fields": {
"vendor": {"type": "text", "instructions": "発行元の会社名"},
"issued_date": {"type": "date", "instructions": "請求書の発行日"},
"total_amount": {
"type": "number",
"unit": "JPY",
"instructions": "税込の合計金額",
},
},
},
)
print(json.dumps(response, ensure_ascii=False, indent=2))首次运行会触发 CUDA Graph 捕获,耗时明显长于后续调用,属于正常现象。运行结束后,answers 下应出现包含抽取值与 confidence、p_null 的 JSON。以这段样例文本为例,期望结果大致是:vendor 为「株式会社テスト商事」,issued_date 为 2026-11-20,total_amount 为 148500,三个字段的置信度都在 0.95 以上。如果字段为空或置信度异常低,先检查补丁是否全部生效。
第六步:固化成 Docker 镜像
手工构建有个隐患:重新执行 hf download 时,打过补丁的运行时文件会被覆盖。更稳的做法是把「运行时代码 + 补丁」打进镜像,把「模型权重」留在宿主上以只读方式挂载。这样镜像体积可控,权重更新也不用重新构建。
| 组件 | 位置 |
|---|---|
| 运行时代码与补丁 | 镜像内 /opt/clairic-flash,并注册到 PYTHONPATH |
| 模型权重(约 18~20GB) | 宿主 ~/clairic-work/clairic-flash,运行时挂载到 /models/clairic-flash(只读) |
Dockerfile 分四段:拉取代码(排除权重文件)、安装过滤后的依赖、应用补丁并做语法校验、放入测试脚本。
FROM nvcr.io/nvidia/pytorch:25.11-py3
ENV DEBIAN_FRONTEND=noninteractive \
PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
CLAIRIC_CODE_DIR=/opt/clairic-flash \
PYTHONPATH=/opt/clairic-flash
WORKDIR /workspace
# 1. 只取代码与配置文件,排除权重
RUN pip install --no-cache-dir -U "huggingface_hub[cli]" && \
hf download Cloudflare/clairic-flash \
--local-dir "${CLAIRIC_CODE_DIR}" \
--exclude "*.safetensors" \
--exclude "*.bin" \
--exclude "*.pt" && \
test -f "${CLAIRIC_CODE_DIR}/requirements.txt"
# 2. 过滤掉与 NGC PyTorch 冲突的包后安装
RUN grep -v -E "^(torch|torchvision|torchaudio|flashinfer)" "${CLAIRIC_CODE_DIR}/requirements.txt" > /tmp/requirements-spark.txt && \
pip install --no-cache-dir -r /tmp/requirements-spark.txt && \
rm -f /tmp/requirements-spark.txt
# 3. 应用补丁并做语法校验
COPY apply_spark_patches.py /tmp/apply_spark_patches.py
RUN python /tmp/apply_spark_patches.py "${CLAIRIC_CODE_DIR}" && \
python -m compileall -q "${CLAIRIC_CODE_DIR}" && \
rm -f /tmp/apply_spark_patches.py
COPY test_clairic.py /workspace/test_clairic.py
CMD ["bash"]补丁脚本把前面手工做的三处修改自动化。每个函数先备份原文件,再断言目标内容存在,找不到就抛 AssertionError 让构建失败——这比构建出一个「看起来成功但补丁没打上」的镜像安全得多。
import shutil
import sys
from pathlib import Path
def patch_normalization(runtime_dir: Path) -> None:
"""补丁1:去掉 flashinfer 依赖,换成 FP32 精度的标准 PyTorch 运算"""
target = runtime_dir / "normalization.py"
shutil.copy2(target, target.with_suffix(".py.bak"))
new_code = '''"""Public CUDA normalization with the model's residual precision."""
from __future__ import annotations
import torch
def rms_norm(value: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor:
"""Normalize CUDA BF16 states or unrounded FP32 residual sums."""
if value.dtype not in (torch.bfloat16, torch.float32):
raise ValueError("Expected BF16 states or FP32 residual sums")
x = value.float()
inv_rms = torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + eps)
return (x * inv_rms * (1.0 + weight.float())).to(torch.bfloat16)
'''
target.write_text(new_code, encoding="utf-8")
print(f"[OK] Patched {target}")
def patch_math(runtime_dir: Path) -> None:
"""补丁2:删除 sgl-deep-gemm(bf16_gemm_nn)分支,统一走 Triton 内核"""
target = runtime_dir / "math.py"
shutil.copy2(target, target.with_suffix(".py.bak"))
content = target.read_text(encoding="utf-8")
old_block = ''' if (a.dtype == torch.bfloat16 and b.dtype == torch.bfloat16
and a.is_contiguous() and b.transpose(0, 1).is_contiguous()
and b.shape[1] >= 16):
from deep_gemm import bf16_gemm_nn
output = torch.empty((a.shape[0], b.shape[1]), device=a.device, dtype=a.dtype)
bf16_gemm_nn(a, b, output)
if bias is not None:
output += bias
return output
'''
assert old_block in content, f"Target block not found in {target}"
target.write_text(content.replace(old_block, "", 1), encoding="utf-8")
print(f"[OK] Patched {target}")
def patch_decoder_capture(runtime_dir: Path) -> None:
"""补丁3:删掉 memory_snapshot() 里不支持的 include_traces 参数"""
target = runtime_dir / "decoder_capture.py"
shutil.copy2(target, target.with_suffix(".py.bak"))
content = target.read_text(encoding="utf-8")
old_call = "torch.cuda.memory_snapshot(mempool_id=pool, include_traces=False)"
new_call = "torch.cuda.memory_snapshot(mempool_id=pool)"
assert old_call in content, f"Target call not found in {target}"
target.write_text(content.replace(old_call, new_call, 1), encoding="utf-8")
print(f"[OK] Patched {target}")
def main() -> None:
if len(sys.argv) != 2:
raise SystemExit("Usage: python apply_spark_patches.py <clairic_code_dir>")
code_dir = Path(sys.argv[1])
runtime_dir = code_dir / "clairic_runtime"
assert runtime_dir.is_dir(), f"Runtime directory not found: {runtime_dir}"
patch_normalization(runtime_dir)
patch_math(runtime_dir)
patch_decoder_capture(runtime_dir)
if __name__ == "__main__":
main()构建镜像,然后以只读方式挂载权重跑一次测试:
cd ~/clairic-docker
docker build -t clairic-flash:spark .
docker run --gpus all --rm \
--ipc=host \
--ulimit memlock=-1 \
--ulimit stack=67108864 \
-v ~/clairic-work/clairic-flash:/models/clairic-flash:ro \
clairic-flash:spark \
python /workspace/test_clairic.py第七步:封装成 HTTP API 服务
在 clairic-flash:spark 基础上继承,用 FastAPI + Uvicorn 起一个本地 API 服务,镜像名 clairic-flash-api:spark。设计上有三个要点:
- GPU 独占:只起一个 worker(
--workers 1),进程内用asyncio.Semaphore(1)串行化推理,并调用model.predict_async()。多 worker 不可行,因为每个进程要占约 19GB 内存,而且 CUDA Graph 捕获会互相冲突。 - 排队上限:等待队列上限默认 16,超出直接返回 429,避免请求无限堆积。
- 启动预热:在 FastAPI 的 lifespan 里先跑一次哑推理,把首次 CUDA Graph 捕获的开销提前到服务就绪之前,避免第一个真实请求超时。
接口方面同时提供 Workers AI 兼容路径 /v1/systemone、/run/@cf/cloudflare/clairic-flash,以及支持图片与 PDF 上传的 /v1/systemone/upload(multipart/form-data)。服务端骨架大致如下,超时与队列上限通过环境变量调整:
import asyncio
import logging
import os
import time
from contextlib import asynccontextmanager
from typing import Any
from fastapi import FastAPI, HTTPException
from clairic_model import load_release_model
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
)
logger = logging.getLogger("clairic-api")
MODEL_DIR = os.environ.get("CLAIRIC_MODEL_DIR", "/models/clairic-flash")
INFERENCE_TIMEOUT_SEC = float(os.environ.get("CLAIRIC_TIMEOUT_SEC", "120"))
MAX_QUEUE_WAITERS = int(os.environ.get("CLAIRIC_MAX_QUEUE", "16"))
MAX_SINGLE_FILE_BYTES = 4 * 1024 * 1024 # 4 MiB
MAX_TOTAL_MEDIA_BYTES = 8 * 1024 * 1024 # 8 MiB
MAX_MEDIA_COUNT = 4
model = None
processor = None
gpu_semaphore = asyncio.Semaphore(1)
active_waiters = 0
is_ready = False
async def run_inference(payload: dict[str, Any]) -> dict[str, Any]:
"""在串行队列控制下异步执行 GPU 推理"""
global active_waiters
if model is None:
raise HTTPException(status_code=503, detail="Model is not loaded yet.")
if active_waiters >= MAX_QUEUE_WAITERS:
raise HTTPException(status_code=429, detail="Inference queue is full. Retry later.")
active_waiters += 1
try:
async with gpu_semaphore:
t0 = time.perf_counter()
result = await asyncio.wait_for(
model.predict_async(payload), timeout=INFERENCE_TIMEOUT_SEC
)
logger.info("inference done in %.2fs", time.perf_counter() - t0)
return result
finally:
active_waiters -= 1启动命令需要指定单 worker,并把模型目录指向挂载点:
docker run --gpus all --rm \
--ipc=host \
--ulimit memlock=-1 \
--ulimit stack=67108864 \
-p 8000:8000 \
-e CLAIRIC_MODEL_DIR=/models/clairic-flash \
-e CLAIRIC_TIMEOUT_SEC=120 \
-e CLAIRIC_MAX_QUEUE=16 \
-v ~/clairic-work/clairic-flash:/models/clairic-flash:ro \
clairic-flash-api:spark \
uvicorn server:app --host 0.0.0.0 --port 8000 --workers 1一个完整示例
下面把三步串起来,从零到能发请求,走一遍最小可运行路径。
1. 准备目录与模型
mkdir -p ~/clairic-work ~/clairic-docker
cd ~/clairic-work
uvx --from "huggingface_hub[cli]" hf download Cloudflare/clairic-flash --local-dir ./clairic-flash
grep -v -E "^(torch|torchvision|torchaudio|flashinfer)" ./clairic-flash/requirements.txt > ./requirements-spark.txt2. 把 Dockerfile、apply_spark_patches.py、test_clairic.py、server.py 放进 ~/clairic-docker,然后构建两个镜像:
cd ~/clairic-docker
docker build -t clairic-flash:spark .
docker build -f Dockerfile.api -t clairic-flash-api:spark .3. 先验证推理镜像,确认补丁生效、抽取结果正常:
docker run --gpus all --rm \
--ipc=host \
--ulimit memlock=-1 \
--ulimit stack=67108864 \
-v ~/clairic-work/clairic-flash:/models/clairic-flash:ro \
clairic-flash:spark \
python /workspace/test_clairic.py4. 启动 API 服务,等日志里出现预热完成的记录:
docker run --gpus all --rm \
--ipc=host \
--ulimit memlock=-1 \
--ulimit stack=67108864 \
-p 8000:8000 \
-v ~/clairic-work/clairic-flash:/models/clairic-flash:ro \
clairic-flash-api:spark \
uvicorn server:app --host 0.0.0.0 --port 8000 --workers 15. 发一个抽取请求,请求体结构与前面的 Python 示例一致:
curl -s http://localhost:8000/v1/systemone \
-H "Content-Type: application/json" \
-d '{
"state": "請求書発行元: 株式会社テスト商事 / 発行日: 2026-11-20 / 合計金額: 148,500円(税込)",
"fields": {
"vendor": {"type": "text", "instructions": "発行元の会社名"},
"issued_date": {"type": "date", "instructions": "請求書の発行日"},
"total_amount": {"type": "number", "unit": "JPY", "instructions": "税込の合計金額"}
}
}'返回的 JSON 里应包含三个字段的抽取值以及各自的 confidence 与 p_null。如果返回 503,说明模型还没加载完;返回 429 说明队列已满,稍后重试即可。
注意事项
- 不要用通用推理引擎:vLLM 与 llama.cpp(GGUF)都缺少
clair_head和clairic_runtime管线,加载后结构化抽取、字段推断与置信度输出都不会工作。这不是配置问题,换引擎解决不了。 - 不要直接安装原始依赖清单:
requirements.txt里的 torch 与 flashinfer 必须过滤掉。torch 用镜像自带的,flashinfer 在 aarch64 上没有官方轮子。 - 补丁必须全部生效:三处补丁分别对应段错误、GEMM 路径和 API 参数不兼容。漏掉任意一处,要么启动即崩,要么推理结果异常。自动化脚本里的断言就是为此设计的,不要为了「让构建通过」而删掉断言。
- 重新下载会覆盖补丁:手工构建时如果再次执行
hf download到同一目录,打过补丁的文件会被覆盖。这正是要把运行时打进镜像、权重单独挂载的原因。 - 单 worker 是硬约束:每个 worker 进程约占 19GB 内存,且 CUDA Graph 捕获会冲突。并发靠进程内的信号量排队,不靠多进程。
- 首次推理慢:CUDA Graph 捕获发生在第一次推理时,耗时明显长于后续调用。API 服务通过启动预热规避这个问题,直接跑脚本时要有心理预期。
- 上传体积有限制:单文件 4 MiB、单次请求媒体总量 8 MiB、媒体数量上限 4 个,超出会被拒绝。
- 版本敏感:本文流程依赖特定的镜像标签、PyTorch 预发布版本与驱动版本。镜像标签、模型权重体积、许可证与可用地区都可能变化,部署前请以官方页面当前信息为准。