news 2026/9/17 12:49:30

Xinference 自定义模型完全指南:从 model_path 直启到注册、管理与调用

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Xinference 自定义模型完全指南:从 model_path 直启到注册、管理与调用

Xinference 自定义模型完全指南:从 model_path 直启到注册、管理与调用

【免费下载链接】inferenceSwap GPT for any LLM by changing a single line of code. Xinference lets you run open-source, speech, and multimodal models on cloud, on-prem, or your laptop — all through one unified, production-ready inference API.项目地址: https://gitcode.com/GitHub_Trending/in/inference

Xinference 提供了一套灵活且完整的自定义模型集成方案,让开发者能够把本地权重、Hugging Face/ModelScope 模型甚至私有镜像中的模型统一接入其生产级推理 API。本文以仓库文档 doc/source/models/custom.rst 为主体,结合 xinference/model/custom.py、xinference/client/restful/restful_client.py 等源码实现,完整讲解「免注册直启模型」「定义自定义模型」「注册 / 列表 / 启动 / 调用 / 注销」五种实操路径,帮助你用一条命令或一次注册把任意模型纳入 Xinference 统一管理。

一、两条路线概览:直接启动 vs 注册模型

在 Xinference 中接入一个现有模型有两条路线,适用场景不同:

路线适用前提操作成本典型场景
直接启动(model_path模型所属的model_family必须在内置支持列表内无需注册,一次调用即可快速验证已下载的官方权重,临时跑一个模型
注册自定义模型模型家族不在内置列表,或需要长期复用、团队共享需要编写一份 JSON 定义并注册私有微调模型、本地专用模型、跨机器分发

两条路线的最终落点一致:注册后的模型也会像内置模型一样出现在启动接口中,被 xinference/model/custom.py 中的ModelRegistry统一管理。

二、路线一:用 model_path 直接启动已存在的模型

v0.14.0起,Xinference 支持在启动接口中直接传入model_path来加载一个已存在的模型文件,免去下载和注册步骤。前提是:该模型的model_family必须属于内置支持列表(如qwen1.5-chat),否则仍需走注册流程。

2.1 CLI 启动

xinference launch --model-path <model_file_path> --model-engine <engine> -n qwen1.5-chat

参数说明:

  • --model-path:模型文件路径。GGUF 格式必须指向具体文件,PyTorch 等格式指向模型目录(与model_uri的语义一致)。
  • --model-engine:指定推理引擎(如transformersvllmllama.cpp等),取决于模型格式与后端支持。
  • -n:内置模型家族名称,如qwen1.5-chat

注意:CLI 推荐使用 kebab-case 的--model-path--model_path(下划线)是历史兼容写法,不推荐使用。

2.2 REST API 启动

curl -X 'POST' \ 'http://127.0.0.1:9997/v1/models' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -d '{ "model_engine": "<engine>", "model_name": "qwen1.5-chat", "model_path": "<model_file_path>" }'

2.3 Python 客户端启动

from xinference.client import RESTfulClient client = RESTfulClient("http://127.0.0.1:9997") model_uid = client.launch_model( model_engine="<inference_engine>", model_name="qwen1.5-chat", model_path="<model_file_path>" ) print('Model uid: ' + model_uid)

上面的示例演示了在不注册模型的情况下,直接启动一个qwen1.5-chat模型文件。

2.4 分布式场景

在分布式部署中,如果模型文件位于某个特定 worker 上,只需在启动接口中同时指定worker_ipmodel_path,Xinference 就会在该 worker 上直接加载,无需把权重拷贝到所有节点。这一能力对应 restful_client.py 中launch_modelworker_ipmodel_path参数:其中model_path的语义为「GGUF 格式传文件路径,其余格式传模型目录」。

三、路线二(前置):定义自定义模型 JSON

当模型家族不在内置列表时,需要先编写一份 JSON 定义。自v2.0.0起,注册 LLM 还可以走 Web UI 的「自动配置解析」来减少手写工作量。

3.1 Web UI 自动解析(v2.0.0+)

在 Web UI 注册自定义 LLM 时,Xinference 可以自动解析模型配置并预填关键字段。你只需提供:

  • Model path / Model ID:模型所在位置,本地路径或 Hub ID 均可;
  • Model Family:模型家族名。

解析完成后,UI 会自动填充Context LengthModel_LanguagesModel_AbilitiesModel_Specs等字段。保存前你可以逐一审阅和修改这些自动生成的值,确保与实际模型一致。

3.2 LLM 模板

{ "version": 2, "context_length": 32768, "model_name": "custom-qwen-2.5", "model_lang": [ "en", "zh" ], "model_ability": [ "generate" ], "model_description": "This is a custom model description.", "model_family": "my-custom-qwen-2.5", "model_specs": [ { "model_format": "pytorch", "model_size_in_billions": "0_5", "quantization": "none", "model_id": null, "model_hub": "huggingface", "model_uri": "file:///path/to/models--Qwen--Qwen2.5-0.5B", "model_revision": null, "activated_size_in_billions": null } ], "chat_template": null, "stop_token_ids": null, "stop": null, "reasoning_start_tag": null, "reasoning_end_tag": null, "cache_config": null, "virtualenv": { "packages": [], "inherit_pip_config": true, "index_url": null, "extra_index_url": null, "find_links": null, "trusted_host": null, "no_build_isolation": null }, "is_builtin": false }

要点解读:

  • model_ability中的能力词可取值包括embedgeneratechat等,本示例仅声明generate
  • model_ability包含chat,则必须配置chat_template(Jinja 模板字符串,通常可在模型目录的tokenizer_config.json中找到),否则聊天时无法生成正确的完整 prompt;
  • model_size_in_billions写成字符串"0_5"表示 0.5B,这是模型规格命名中常见的转义写法。

3.3 Embedding 模板

{ "version": 2, "model_name": "my-bge-large-zh-v1.5", "dimensions": 1024, "max_tokens": 512, "language": [ "zh" ], "model_specs": [ { "model_format": "pytorch", "model_hub": "huggingface", "model_id": null, "model_uri": "file:///path/to/my-bge-large-zh-v1.5", "model_revision": null, "quantization": "none" } ], "cache_config": null, "virtualenv": { "packages": [], "inherit_pip_config": true, "index_url": null, "extra_index_url": null, "find_links": null, "trusted_host": null, "no_build_isolation": null }, "is_builtin": false }

3.4 Rerank 模板

{ "version": 2, "model_name": "my-bge-reranker-base", "model_specs": [ { "model_format": "pytorch", "model_hub": "huggingface", "model_id": null, "model_revision": null, "model_uri": "file:///path/to/my-bge-reranker-base", "quantization": "none" } ], "language": [ "en", "zh" ], "type": "unknown", "max_tokens": 512, "virtualenv": { "packages": [], "inherit_pip_config": true, "index_url": null, "extra_index_url": null, "find_links": null, "trusted_host": null, "no_build_isolation": null }, "is_builtin": false }

3.5 Image 模板

{ "model_name": "my-qwen-image", "model_id": null, "model_revision": null, "model_hub": "huggingface", "cache_config": null, "version": 2, "model_family": "stable_diffusion", "model_ability": null, "controlnet": [], "default_model_config": {}, "default_generate_config": {}, "gguf_model_id": null, "gguf_quantizations": null, "gguf_model_file_name_template": null, "lightning_model_id": null, "lightning_versions": null, "lightning_model_file_name_template": null, "virtualenv": { "packages": [], "inherit_pip_config": true, "index_url": null, "extra_index_url": null, "find_links": null, "trusted_host": null, "no_build_isolation": null }, "model_uri": "file:///path/to/my-qwen-image", "is_builtin": false }

3.6 Audio 模板

{ "model_name": "my-ChatTTS", "model_id": null, "model_revision": null, "model_hub": "huggingface", "cache_config": null, "version": 2, "model_family": "ChatTTS", "multilingual": false, "language": null, "model_ability": [ "text2audio" ], "default_model_config": null, "default_transcription_config": null, "engine": null, "virtualenv": { "packages": [], "inherit_pip_config": true, "index_url": null, "extra_index_url": null, "find_links": null, "trusted_host": null, "no_build_isolation": null }, "model_uri": "file:///path/to/my-ChatTTS", "is_builtin": false }

3.7 Flexible 模板

flexible类型用于无法归入上述任何类别的任意模型,通过「启动器(launcher)」与参数来驱动,例如 xinference/model/flexible/launchers/transformers_launcher.py 对应 transformers 启动器:

{ "model_name": "my-flexible-model", "model_id": null, "model_revision": null, "model_hub": "huggingface", "cache_config": null, "version": 2, "model_description": "This is a model description.", "model_uri": "file:///path/to/my-flexible-model", "launcher": "xinference.model.flexible.launchers.transformers", "launcher_args": "{}", "virtualenv": { "packages": [], "inherit_pip_config": true, "index_url": null, "extra_index_url": null, "find_links": null, "trusted_host": null, "no_build_isolation": null }, "is_builtin": false }

仓库中 xinference/model/flexible/launchers 目录还提供了modelscope_launcher.pyyolo_launcher.pyimage_process_launcher.py等更多启动器,可根据模型类型选择launcher路径,并通过launcher_args传入 JSON 字符串形式的启动参数。

四、核心字段详解

以下字段对注册结果有决定性影响,逐一说明:

  • model_name(必填):模型名称字符串。必须以字母或数字开头,只能包含字母、数字、下划线和连字符。注册时 xinference/model/utils.py 中的is_valid_model_name会校验命名合法性,且不能与已注册模型或内置模型重名,否则 xinference/model/custom.py 的register会抛出ValueError
  • context_length(可选,LLM):模型训练时支持的最大上下文长度(输入 + 输出)。不定义时默认 2048 tokens(约 1500 词)。
  • dimensions(必填,Embedding):Embedding 模型输出向量的维度。
  • max_tokens(Embedding/Rerank):单次请求中 Embedding 模型可处理的最大输入 token 数。
  • model_lang(LLM/Embedding/Rerank):支持语言列表,如["en"]表示支持英文。
  • model_ability(LLM):能力列表,可包含embedgeneratechat等取值。
  • model_family(必填):模型家族名称,不得与任何内置模型名冲突
  • model_specs:模型规格对象数组,包含:
    • model_format:模型格式,如pytorchggufv2
    • model_size_in_billions:参数量(十亿);
    • quantization:可用量化列表。PyTorch 模型可取4-bit8-bitnone;GGUFv2 模型需与model_file_name_template对应;部分引擎还支持fp4/fp8/bnb格式(后端支持情况参见 doc/source/getting_started/installation.rst);
    • model_id:模型 ID(通常是 Hugging Face 仓库标识)。如果未提供model_uri,Xinference 会尝试从该 ID 对应的 Hugging Face 仓库下载模型
    • model_hub:下载来源,如huggingfacemodelscope
    • model_uri:模型加载 URI,如file:///path/to/llama-2-7bGGUFv2 格式必须是具体文件路径,PyTorch 格式必须是模型文件所在目录。缺省时 Xinference 会尝试按model_id从 Hugging Face 下载。注册时is_valid_model_uri(见 xinference/model/utils.py)会校验:file://路径必须是绝对路径且实际存在;
    • model_revision:仓库中要使用的具体版本或 commit hash。
  • chat_template:若model_ability包含chat则必填,Jinja 模板字符串,通常可从模型目录的tokenizer_config.json提取。
  • stop_token_ids(chat 能力):整数列表,控制模型停止生成,通常可从generation_config.jsontokenizer_config.json提取。
  • stop(chat 能力):字符串列表,作用同上。
  • reasoning_start_tag / reasoning_end_tag:用于显式引导 LLM 开始/结束思维链(chain-of-thought)推理输出的特殊 token 或 prompt。
  • cache_config:系统存储与管理临时数据(缓存)的参数与规则字符串。
  • virtualenv:模型依赖隔离配置对象,细节参见 doc/source/models/virtualenv.rst。

补充:model_uri支持 OCI 镜像格式file://之外,model_uri还接受oci://<registry>/<repository>:<tag>,用于加载发布为 CNCF ModelPack 制品(容器镜像)的模型。拉取这类模型需要一个正在运行的llmman守护进程(llmman serve)且llmman二进制位于PATH中;可通过LLMMAN_HOST指定远端守护进程,或用XINFERENCE_LLMMAN_BIN指向PATH之外的二进制。对应实现见 xinference/model/llmman.py 与 xinference/model/oci_utils.py。

五、注册自定义模型

5.1 Python 方式

import json from xinference.client import Client with open('model.json') as fd: model = fd.read() # replace with real xinference endpoint endpoint = 'http://localhost:9997' client = Client(endpoint) client.register_model(model_type="<model_type>", model=model, persist=False)

5.2 CLI 方式

xinference register --model-type <model_type> --file model.json --persist

<model_type>在上述命令中替换为LLMembeddingrerank(下文同)。persist决定注册是否落盘持久化:不持久化的注册在服务重启后失效;持久化注册会经由 xinference/model/cache_manager.py 的CacheManager写入自定义模型存储。

5.3 注册背后的实现

注册最终走到 xinference/model/custom.py 的ModelRegistry.register,流程为:

  1. 校验model_name合法性(is_valid_model_name);
  2. 校验model_uri合法性(check_model_uriis_valid_model_uri);
  3. 加锁检查与内置模型、已有自定义模型是否重名,冲突即抛ValueError: Model name conflicts with existing model ...
  4. 追加到自定义模型列表;若persist=True,写入持久化存储。

不同模型类型对应不同注册表,由 xinference/model/custom.py 的RegistryManager.get_registry按类型分发(LLM、embedding、rerank、image、audio、flexible)。其中 LLM 注册表(xinference/model/llm/custom.py)在add_ud_model时会额外调用generate_engine_config_by_model_family为模型生成引擎配置;注销时会同步删除LLM_ENGINES中的对应条目,避免残留脏配置。

六、列出内置与自定义模型

registrations = client.list_model_registrations(model_type="<model_type>")

或通过 CLI:

xinference registrations --model-type <model_type>

list_model_registrations(见 restful_client.py)请求/v1/model_registrations/{model_type}接口,detailed=True时可返回更详细的规格信息。

七、启动自定义模型

uid = client.launch_model(model_name='custom-llama-2', model_format='pytorch')

或通过 CLI:

xinference launch --model-name custom-llama-2 --model-format pytorch

启动成功后返回模型 UID(model_uid)。从源码看(restful_client.py),launch_model支持model_typemodel_enginemodel_size_in_billionsquantizationreplican_workern_gpu(默认"auto"None表示纯 CPU)、worker_ipgpu_idxmodel_pathenable_virtual_env等丰富参数,可灵活适配单机与分布式部署。

八、与自定义模型交互

model = client.get_model(model_uid=uid) model.generate('What is the largest animal in the world?')

返回结果示例(OpenAI 兼容格式):

{ "id":"cmpl-a4a9d9fc-7703-4a44-82af-fce9e3c0e52a", "object":"text_completion", "created":1692024624, "model":"43e1f69a-3ab0-11ee-8f69-fa163e74fa2d", "choices":[ { "text":"\nWhat does an octopus look like?\nHow many human hours has an octopus been watching you for?", "index":0, "logprobs":"None", "finish_reason":"stop" } ], "usage":{ "prompt_tokens":10, "completion_tokens":23, "total_tokens":33 } }

或通过 CLI(将${UID}替换为真实模型 UID):

xinference generate --model-uid ${UID}

自定义模型启动后走的是与内置模型完全一致的统一推理 API,客户端无需关心模型是内置还是自定义,这正是「Swap GPT for any LLM by changing a single line of code」的基础。

九、注销自定义模型

model = client.unregister_model(model_type="<model_type>", model_name='custom-llama-2')

或通过 CLI:

xinference unregister --model-type <model_type> --model-name custom-llama-2

从 xinference/model/custom.py 的实现看,unregister会先从内存注册表移除模型,再调用remove_ud_model_files清理持久化文件;若模型不存在,默认抛ValueError: Model not found。注销后该模型即无法再被启动,需重新注册才能使用。

十、实践建议与注意事项

  • 优先复用内置家族:能直接用model_path直启的模型不要注册,成本最低;注册仅用于内置列表之外的模型。
  • model_uri三选一:本地文件(file://绝对路径)、Hub ID(配合model_id/model_hub自动下载)、OCI 镜像(oci://+ llmman)。三者是互斥的加载来源。
  • chat 能力必配 chat_template:忘记配置chat_template会导致带chat能力的模型无法正确构造 prompt。
  • 命名规范model_name只能含字母、数字、下划线和连字符,且不能与内置/已注册模型重名,否则注册直接失败。
  • 持久化与否要想清楚--persist仅适用于需要跨重启保留的场景;临时调试建议不持久化,避免污染模型目录。
  • 虚拟环境隔离:依赖特殊的模型(如需要特定版 vLLM/transformers)可启用virtualenv配置按模型隔离依赖,详见 doc/source/models/virtualenv.rst。

结语

v0.14.0model_path直启,到v2.0.0的 Web UI 自动解析,再到覆盖 LLM / Embedding / Rerank / Image / Audio / Flexible 六类模型的注册体系,Xinference 的自定义模型能力已经形成「直启 → 定义 → 注册 → 管理 → 调用 → 注销」的完整闭环。配合 xinference/model/custom.py 中统一的注册表设计与 xinference/client/restful/restful_client.py 中统一的 REST 接口,无论模型来自本地、Hub 还是容器镜像,都可以用同一套 API 无缝接入生产推理环境。

【免费下载链接】inferenceSwap GPT for any LLM by changing a single line of code. Xinference lets you run open-source, speech, and multimodal models on cloud, on-prem, or your laptop — all through one unified, production-ready inference API.项目地址: https://gitcode.com/GitHub_Trending/in/inference

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/17 12:45:58

STM32C5串口调试实战:从引脚映射到printf重定向

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华
网站建设 2026/9/17 12:45:57

AlpacaEval 反超 GPT-4 的 Xwin-LM,用 TaoToken Key 对照跑分怎么验证?

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华
网站建设 2026/9/17 12:45:13

从零手写Linux LED驱动:设备树+GPIO子系统+字符设备全解析

1. 为什么一盏LED灯能讲透Linux设备驱动开发1.1 一个“点灯”需求背后牵出的完整知识链很多朋友第一次接触嵌入式Linux驱动&#xff0c;都是从点亮一颗LED开始的。当年我也是这样&#xff1a;手里拿着一块开发板&#xff0c;想着“单片机里点灯就是写寄存器的事&#xff0c;Lin…

作者头像 李华
网站建设 2026/9/17 12:44:53

LY-E252:EtherCAT从站同封装替换实战指南

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华
网站建设 2026/9/17 12:44:16

微信小程序点餐系统设计与实现:从购物车到支付回调全解析

简介&#xff1a;一份面向毕业设计场景的微信小程序点餐系统完整设计文档&#xff0c;适合计算机相关专业学生或餐饮软件开发者参考。文档从项目背景、开发意义、技术选型入手&#xff0c;系统覆盖可行性分析、功能需求分析、流程图与ER图设计&#xff0c;以及数据库表结构设计…

作者头像 李华
网站建设 2026/9/17 12:40:17

Python量化交易系统回测:ATR通道突破、参数调优与滑点验证

简介&#xff1a;《技术交易系统新概念》为威尔斯威尔德所著技术分析经典的中文PDF版本&#xff0c;面向期货、外汇及股票领域的技术分析初学者与职业交易者&#xff0c;意在提供一套可落地的概念、工具和指标&#xff0c;帮助读者构建并验证自己的交易系统。压缩包仅含1个PDF文…

作者头像 李华