OpenMed 远程推理实战:导出 ONNX 模型为 KServe/Triton 模型仓库并接入 V2 推理协议

原创2026-09-17 13:08:551,898 阅读
文章标签:医疗健康NLP数据脱敏人工智能隐私合规AI 技能MCP 服务本地部署

OpenMed 远程推理实战:导出 ONNX 模型为 KServe/Triton 模型仓库并接入 V2 推理协议

OpenMed 支持将导出的 ONNX 分词分类器(token classifier)打包为标准的 Triton 模型仓库(model repository),并把自运营的 Triton 或 KServe 端点作为推理后端。本文从模型导出、仓库生成、基础设施部署到客户端配置切换,完整演示这一“本地 Token 化 + 远端张量推理”的混合架构,并深入仓库源码说明配置项校验、张量协议映射与隐私边界等实现细节。读完本文,你将能独立完成 OpenMed 的远程推理链路搭建,且无需改动任何 pipeline 调用代码。

架构总览:本地与远端各司其职

在 KServe/Triton 远程推理方案中,OpenMed 进程保留的是语义解析与文本还原部分,只有数值张量跨网络传输:

  • 本地执行:分词(tokenization)、源文本偏移(source offsets)、实体解码(entity decoding)全部留在 OpenMed 进程内,本地还保留原工件或模型仓库以使用其快速分词器与 id2label 元数据。
  • 远端执行:ONNX 图本身。服务器接收数值张量(input_ids、attention_mask 等),返回 logits。
  • 协议:HTTP 遵循 KServe V2 JSON 协议;gRPC 使用与 KServe V2 protobuf 契约线兼容(wire-compatible)的较小子集,即标准 inference.GRPCInferenceService/ModelInfer 方法,对应的客户端实现位于 openmed/service/backends/remote_inference.py。

需要特别强调边界:OpenMed 不安装、不启动 Triton 或 KServe。服务系统需由你独立运营,并按自身部署要求落实认证(authentication)、网络隔离(network isolation)与传输层控制(transport controls)。OpenMed 只负责生成仓库与充当推理客户端。

1. 安装客户端与导出依赖

仓库生成依赖 ONNX 支持;远程 HTTP 与 gRPC 推理依赖 triton extra 中的客户端库:

pip install 'openmed[onnx,triton]'

该 extra 不包含任何 KServe 或 Triton 服务器发行版,只是客户端依赖。从源码看,HTTP 传输需要 httpx,gRPC 传输需要 grpc 与 google.protobuf,此外还需 numpy 与 transformers(用于本地分词器与 id2label 元数据加载),具体可见 remote_inference.py 中 remote_inference_dependencies_available 与各 ImportError 提示(如 “Install with: pip install 'openmed[triton]'”)。

2. 导出并构建 Triton 模型仓库

2.1 导出 ONNX 工件的前置要求

以 openmed.onnx.convert 产出的 ONNX 分词分类工件为起点(导出实现见 openmed/onnx/convert.py)。仓库适配器对图结构有硬性要求:

  • 当 max_batch_size > 0 时,每个图输入与输出都必须具有动态的 leading batch 维度(即第一个维度为动态轴);
  • 图必须暴露 input_ids、attention_mask 两个输入,以及一个 logits 输出。

上述检查在 openmed/service/backends/triton_repository.py 的 _inspect_onnx_model 中强制执行,不满足会直接抛出 ValueError。

2.2 一键生成模型仓库

from pathlib import Path

from openmed.onnx import convert
from openmed.service.backends import write_triton_model_repository

artifact_dir = Path("build/openmed-pii-onnx")
convert(
    "OpenMed/OpenMed-PII-SuperClinical-Small-44M-v1",
    artifact_dir,
)

repository = write_triton_model_repository(
    artifact_dir / "model.onnx",
    "build/model-repository",
    model_name="openmed_pii",
    version=1,
    max_batch_size=8,
)
print(repository.model_dir)

write_triton_model_repository 的参数语义(对应源码 triton_repository.py 中的函数签名):

参数 默认值 说明与约束
onnx_path — 已导出的 ONNX 图路径,必须是存在的文件,否则抛 FileNotFoundError
repository_dir — 目标 Triton 仓库根目录
model_name — Triton 模型目录名,必须以字母/数字开头,仅允许字母、数字、点、下划线、连字符(正则 ^[A-Za-z0-9][A-Za-z0-9_.-]*$)
version 1 正整数模型版本(version < 1 抛错)
max_batch_size 8 Triton 最大批大小;传 0 可关闭批处理(此时输入张量保留完整维度,不剥离 batch 轴)

2.3 config.pbtxt 的生成原理

适配器从 ONNX 图推导张量名、数据类型与非批维度,并用 Triton 的 onnxruntime 后端渲染出确定性的 config.pbtxt(确定性体现在:字段顺序固定、使用 json.dumps 序列化字符串值、张量块按输入/输出固定排列,见 TritonModelConfig.to_pbtxt 与 _render_tensor_block)。生成的目录结构:

build/model-repository/
└── openmed_pii/
    ├── config.pbtxt
    └── 1/
        └── model.onnx

其 config.pbtxt 形如:

name: "openmed_pii"
backend: "onnxruntime"
max_batch_size: 8
input [
  {
    name: "input_ids"
    data_type: TYPE_INT64
    dims: [ 512 ]
  },
  {
    name: "attention_mask"
    data_type: TYPE_INT64
    dims: [ 512 ]
  }
]
output [
  {
    name: "logits"
    data_type: TYPE_FP32
    dims: [ 512, 11 ]
  }
]

细节说明:

  • ONNX 数据类型到 Triton TYPE_* 类型的映射表定义在 _ONNX_TO_TRITON_DATA_TYPE,覆盖 BOOL/UINT8…UINT64/INT8…INT64/FP16/FP32/FP64/BF16/STRING;遇到不支持的 ONNX 元素类型会抛 ValueError。
  • 开启批处理(max_batch_size > 0)时,要求每个张量 rank ≥ 2 且首维为动态轴(-1),随后在 config.pbtxt 中省略 batch 轴,由 Triton 负责动态批处理;max_batch_size = 0 时保留完整维度。
  • 张量校验(TritonTensorSpec.__post_init__)要求名称非空、维度非空且每个维度 > 0 或 == -1。

2.4 多文件(外部张量数据)布局

对于携带外部张量数据(external tensor data)的图,适配器使用 Triton 官方文档所述的多文件 ONNX 目录形式,并复制所有被引用的 sidecar 文件:

build/model-repository/openmed_pii/1/
└── model.onnx/
    ├── model.onnx
    └── weights.bin

安全方面(对应 _safe_external_path 与 _external_tensor_files):

  • 绝对路径、父级相对路径(..)、可逃逸目录的符号链接路径一律拒绝,解析后的路径必须仍位于源图所在目录内;
  • 外部张量缺失 location 字段或文件不存在时分别抛 ValueError / FileNotFoundError;
  • 仓库内 model_dir、config.pbtxt 等路径不允许是符号链接。

版本管理策略(源码中通过“先写临时目录再 os.replace 原子改名”实现):

  • 已存在的数字版本永远不会被覆盖,重复写入同一版本抛 FileExistsError;
  • 新增版本时,其派生 schema 必须与已有 config.pbtxt 完全一致,否则抛 ValueError;
  • 写失败时自动回滚清理临时目录与已创建的文件。

2.5 挂载前复检

拷贝后的仓库建议先做一次校验再挂载:

from openmed.service.backends import validate_triton_model_repository

validate_triton_model_repository(
    "build/model-repository",
    model_name="openmed_pii",
    version=1,
)

validate_triton_model_repository 会检查:目录布局必须是 <model>/<version>/model.onnx 或 <model>/<version>/model.onnx/model.onnx 之一、config.pbtxt 存在、仓库路径无符号链接、config.pbtxt 文本与重新从 ONNX 图派生的配置逐字节一致、所有外部张量 sidecar 存在。返回的 TritonRepositoryResult 包含 repository_dir、model_dir、version_dir、model_path、config_path 与派生的 TritonModelConfig,便于脚本化集成。

3. 在你的基础设施中部署服务

将 build/model-repository 挂载进你自己的 Triton 部署,并用 --model-repository 指向该挂载点。若使用 KServe,则在其 Triton runtime 或 storage initializer 中暴露同一仓库。在将 OpenMed 流量切过来之前,先验证 V2 模型就绪端点:

curl --fail https://triton.example/v2/models/openmed_pii/ready

服务器安装、GPU 调优、自动扩缩容(可参考仓库内的 deploy/k8s/hpa.yaml)、凭据与生命周期管理均不属于 OpenMed 职责范围。值得留意的是,OpenMed 侧对端点只有“显式配置、显式使用”,不会主动探测或预热远端模型。

4. 通过配置切换到远程推理

4.1 代码方式:OpenMedConfig

保留原工件或模型仓库供 OpenMed 客户端使用——本地快速分词器与 id2label 元数据用于分词与解码,仅 ONNX 图在远端执行:

from openmed.core import ModelLoader, OpenMedConfig

config = OpenMedConfig(
    backend="remote",
    remote_inference_endpoint="https://triton.example",
    remote_inference_protocol="http",
    remote_inference_model_name="openmed_pii",
    remote_inference_model_version="1",
    remote_inference_tokenizer="build/openmed-pii-onnx",
    remote_inference_timeout_seconds=30,
    remote_inference_verify_tls=True,
)

loader = ModelLoader(config)
pipeline = loader.create_pipeline(
    "OpenMed/OpenMed-PII-SuperClinical-Small-44M-v1",
    task="token-classification",
    aggregation_strategy="simple",
)
entities = pipeline("Synthetic patient Alice Nguyen")

调用方无需任何改动。OpenMedConfig.backend 通过常规的 ModelLoader.create_pipeline 路径选择远端实现——后端注册表 _BACKENDS 中 "remote" 对应 RemoteInferenceBackend(见 openmed/core/backends.py),RemoteInferenceBackend.create_pipeline 内部转调 create_remote_inference_pipeline 构建 RemoteInferencePipeline。pipeline 接受单个字符串或一个批次,返回与本地 ONNX 推理相同的实体字典结构与源文本偏移。

全部 remote_inference_* 配置项定义于 openmed/core/config.schema.json,语义如下:

配置项 类型 默认 约束(来自 RemoteInferenceSettings.__post_init__)
remote_inference_endpoint string 必填 HTTP 必须以 http:///https:// 开头且含主机、不得带 query/fragment;gRPC 必须为 grpc:///grpcs:// 或裸 host:port
remote_inference_protocol string "http" 仅允许 "http" 或 "grpc"
remote_inference_model_name string 必填 服务端模型名,非空
remote_inference_model_version string/null 可选 服务端模型版本
remote_inference_tokenizer string 可选 本地分词器标识;缺省时从模型注册表解析(_resolve_tokenizer_source)
remote_inference_timeout_seconds number 30.0 必须为正且有限(拒绝 NaN/inf/≤ 0)
remote_inference_verify_tls boolean true 必须为布尔;gRPC TLS 场景下不允许关闭校验

4.2 配置文件方式:扁平 TOML

同样配置可存入常规的扁平 TOML 配置:

backend = "remote"
remote_inference_endpoint = "https://kserve.example"
remote_inference_protocol = "http"
remote_inference_model_name = "openmed_pii"
remote_inference_model_version = "1"
remote_inference_tokenizer = "/models/openmed-pii-onnx"
remote_inference_timeout_seconds = 30.0
remote_inference_verify_tls = true

4.3 Triton gRPC 方式

gRPC 使用 gRPC target 与协议:

config = OpenMedConfig(
    backend="remote",
    remote_inference_endpoint="grpcs://triton.example:8001",
    remote_inference_protocol="grpc",
    remote_inference_model_name="openmed_pii",
    remote_inference_tokenizer="/models/openmed-pii-onnx",
)

TLS 语义(对应 _grpc_target 与 TritonGrpcTransport):

  • grpc:// 与裸 host:port target 为明文(plaintext);
  • grpcs:// 使用 TLS,且不允许关闭证书校验——若 verify_tls=False 会直接抛 ValueError,必须为端点配置受信任证书;
  • HTTP 部署同样应保持 remote_inference_verify_tls=true。

4.4 协议与张量处理细节(源码级)

  • HTTP 传输(KServeV2HttpTransport):将 NumPy 张量序列化为 KServe V2 JSON(name/shape/datatype/data),请求 POST <endpoint>/v2/models/<model>/versions/<ver>/infer;datatype 由 NumPy dtype 经 _NUMPY_TO_KSERVE 映射(如 int64 → INT64、float32 → FP32),输出则按 datatype 反序列化并按声明 shape reshape。
  • gRPC 传输(TritonGrpcTransport):构建 ModelInferRequest,张量数据走 raw_input_contents(C 序字节流),调用标准方法 /inference.GRPCInferenceService/ModelInfer;响应优先解析 raw_output_contents,兼容 typed contents(fp32_contents 等)回退路径。
  • 错误处理:HTTP 非 2xx 状态只报告状态码;JSON 解析失败统一报 “Remote inference response is not valid JSON”,避免把可能包含敏感内容的响应体片段带入公开错误信息(源码注释明确说明了这一设计意图)。
  • pipeline 约束:远程后端仅支持 aggregation_strategy='simple'(或 None)与 token-classification/ner 任务;要求快速分词器(fast tokenizer,因需要 offset_mapping);支持 threshold(0~1)与 max_length 参数,其余 kwargs 会抛 TypeError。远程 logits 必须为 [batch, sequence, labels] 三维,且 batch 数、序列长度、标签维度必须与本地 tokenizer 元数据严格一致,否则抛 RuntimeError——这些校验在 RemoteInferencePipeline.__call__ 中逐项执行。

5. 隐私与离线边界

  • 不记录敏感内容:适配器不会记录源文本、请求张量、响应体或原始服务器错误。
  • 发送内容仍可能是敏感的:它发送的是 token ID、attention mask 以及分词器所需的 token-type ID,而非原始字符串。这些张量仍可编码敏感信息,因此必须把端点视为受信任的 PHI(受保护健康信息)边界之内,使用传输加密,并在你的服务基础设施中强制认证与网络策略。
  • 远程推理是显式行为:永远不会被自动选择(auto-detect 顺序为 MLX → HuggingFace → ONNX Runtime,不含 remote,见 openmed/core/backends.py 的 get_backend 注释)。
  • 离线模式硬性拒绝:当 local_only=True 或 OPENMED_OFFLINE=1 时,远端推理被直接拒绝(抛 RuntimeError/离线错误),因为这两种设置承诺的是无出站(no-egress)运行时。相关逻辑见 openmed/core/offline.py 与 remote_inference.py 的 _ensure_remote_allowed、create_remote_inference_pipeline 中的 is_local_only 检查。

6. 排查要点速查

  • 导出报 “ONNX token classifier must expose input_ids and attention_mask inputs” / “must expose a logits output”:检查 ONNX 图输入输出命名与结构(见 2.1 节)。
  • 写入报 “Existing Triton model config does not match ONNX schema”:目标版本已存在且 schema 不一致,换新版本号或核对导出的 ONNX。
  • 校验报 “config.pbtxt does not match the copied ONNX graph schema”:仓库被手工改动过,重新生成。
  • HTTP 报 “Remote inference response is missing output 'logits'”:确认服务端模型输出名与 output_name(默认 logits)一致。
  • gRPC 报 “gRPC TLS verification cannot be disabled”:grpcs:// 端点必须保留 verify_tls=True 并配置受信任证书。
  • pipeline 报 “Remote inference requires a fast tokenizer”:为 remote_inference_tokenizer 指向含快速分词器(tokenizer.json)的本地工件目录。

完整的流程控制流可继续研读:docs/serving/kserve-triton.md(本文所依据的官方指南)、openmed/service/backends/triton_repository.py、openmed/service/backends/remote_inference.py 与 openmed/core/config.schema.json。部署侧可结合 deploy/k8s/hpa.yaml 与 deploy/openmed-compose.yaml 规划自托管基础设施。

登录后查看全文
openmed