FastChat 模型接入完全指南:用对话模板与模型适配器让本地模型和 API 模型跑起来
FastChat 模型接入完全指南用对话模板与模型适配器让本地模型和 API 模型跑起来【免费下载链接】FastChatAn open platform for training, serving, and evaluating large language models. Release repo for Vicuna and Chatbot Arena.项目地址: https://gitcode.com/GitHub_Trending/fa/FastChat本篇指南基于 FastChat 官方文档docs/model_support.md展开讲解在 FastChat 中支持一个新模型所需的完整改造路径本地模型如何通过Conversation对话模板与ModelAdapter模型适配器完成注册API 模型如何通过 JSON 配置文件或自定义流式 Provider 接入。读完并动手实践后你可以让任意新模型在 FastChat 的 CLI、Web UI、Model Worker 与 OpenAI 兼容 API Server 中正常工作。两类模型、两套机制FastChat 的模型支持体系FastChat 支持两类模型二者的接入方式完全不同模型类型核心机制关键代码位置本地模型Local Models对话模板Conversation 模型适配器BaseModelAdapterfastchat/conversation.py、fastchat/model/model_adapter.pyAPI 模型API-Based ModelsJSON 端点配置文件或为自定义协议实现流式生成器fastchat/serve/api_provider.py对于本地模型接入的目标是让下面这条命令用正确的 prompt 模板跑通python3 -m fastchat.serve.cli --model [YOUR_MODEL_PATH]官方建议用下面这条示例命令熟悉代码逻辑并加上--debug查看实际发给模型的 promptpython3 -m fastchat.serve.cli --model lmsys/vicuna-7b-v1.5 --debug--debug参数定义在 fastchat/serve/cli.py其帮助文本为 “Print useful debug information (e.g., prompts)”是验证对话模板是否生效的最直接手段。下面按文档给出的三步走深入讲解每一步的源码细节。本地模型支持三步改造流程FastChat 用Conversation类处理 prompt 模板用BaseModelAdapter类处理模型加载。文档规定的步骤为在 fastchat/conversation.py 中为新模型实现对话模板参照现有示例用register_conv_template注册新模板并尽可能附上官方参考代码的链接在 fastchat/model/model_adapter.py 中为新模型实现模型适配器参照现有示例用register_model_adapter注册可选把模型名加入文档的 “Supported models” 列表并在 fastchat/model/model_registry.py 中补充展示信息。完成这三步后新模型即可兼容 FastChat 的大部分功能包括 CLI、Web UI、model worker 和 OpenAI 兼容 API server——文档同时提醒接入后应针对这些功能分别做测试。步骤一实现对话模板ConversationConversation是一个 dataclass定义在 fastchat/conversation.py其核心字段即是一个模板需要交代的全部信息字段含义name模板名称后续用get_conv_template(name)按名取用system_template/system_message系统提示词模板及内容默认{system_message}与空串roles两个角色的名字如(USER, ASSISTANT)messages对话历史每项为(role, message)message 也可以是(string, List[image_url])元组以携带图像offsetfew-shot 示例条数sep_style分隔符风格枚举ADD_COLON_SINGLE、ADD_COLON_TWO、NO_COLON_TWO、LLAMA2等sep/sep2分隔符及其交替形式用于双分隔符风格stop_str/stop_token_ids生成停止条件默认依赖 EOS tokenmax_image_size_mb该模型可接受的图像大小上限None表示不缩放模板如何拼装成最终 prompt 由Conversation.get_prompt()同文件 L76 起按sep_style分支实现——每种风格对应一类模型的 prompt 语法例如ADD_COLON_TWO交替使用sep/sep2LLAMA2风格使用[INST] ... /s包裹。实现新模板时最可靠的做法是对照目标模型官方训练/推理代码确定roles、sep_style、sep、sep2、stop_str的取值。注册机制是一个全局字典conv_templatesfastchat/conversation.py#L694-L710conv_templates: Dict[str, Conversation] {} def register_conv_template(template: Conversation, override: bool False): Register a new conversation template. if not override: assert ( template.name not in conv_templates ), f{template.name} has been registered. conv_templates[template.name] template文件内已注册了上百个现成模板可供参照。以 Vicuna v1.1 模板为例L771-L781# Vicuna v1.1 template register_conv_template( Conversation( namevicuna_v1.1, system_messageA chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the users questions., roles(USER, ASSISTANT), sep_styleSeparatorStyle.ADD_COLON_TWO, sep , sep2/s, ) )为接入新模型仿照上面的写法构造Conversation(...)并调用register_conv_template(...)即可overrideFalse时重名注册会直接断言失败避免误覆盖已有模板。步骤二实现模型适配器ModelAdapterBaseModelAdapter定义在 fastchat/model/model_adapter.py#L97-L144提供了默认的加载逻辑子类通常只需覆盖三处match(model_path)判断给定模型路径是否属于该模型族默认实现恒返回Trueload_model(model_path, from_pretrained_kwargs)加载 tokenizer 与模型默认用AutoTokenizer/AutoModelForCausalLM配合trust_remote_codeTrue加载NameError时回退到AutoModelget_default_conv_template(model_path)返回该模型的默认对话模板默认返回one_shot。注册与匹配逻辑同样简单L147-L172# A global registry for all model adapters model_adapters: List[BaseModelAdapter] [] def register_model_adapter(cls): Register a model adapter. model_adapters.append(cls()) cache def get_model_adapter(model_path: str) - BaseModelAdapter: Get a model adapter for a model_path. model_path_basename os.path.basename(os.path.normpath(model_path)) # Try the basename of model_path at first for adapter in model_adapters: if adapter.match(model_path_basename) and type(adapter) ! BaseModelAdapter: return adapter # Then try the full path for adapter in model_adapters: if adapter.match(model_path): return adapter raise ValueError(fNo valid model adapter for {model_path})有两点值得注意匹配顺序先遍历非基类的精确适配器匹配路径 basename再对全部适配器匹配完整路径都失败才抛ValueError。因此match的写法要足够精确如用关键字 lower()包含判断否则可能“抢走”别的模型的适配。适配器决定默认模板上层通过adapter.get_default_conv_template(model_path)L399-L401 附近的封装函数拿到模板这就是模板与模型绑定生效的位置。官方实现中VicunaAdapterfastchat/model/model_adapter.py#L702-L737是典型的“需要修正默认行为”的适配器class VicunaAdapter(BaseModelAdapter): Model adapter for Vicuna models (e.g., lmsys/vicuna-7b-v1.5) use_fast_tokenizer False def match(self, model_path: str): return vicuna in model_path.lower() def load_model(self, model_path: str, from_pretrained_kwargs: dict): revision from_pretrained_kwargs.get(revision, main) tokenizer AutoTokenizer.from_pretrained( model_path, use_fastself.use_fast_tokenizer, revisionrevision ) model AutoModelForCausalLM.from_pretrained( model_path, low_cpu_mem_usageTrue, **from_pretrained_kwargs ) self.raise_warning_for_old_weights(model) return model, tokenizer def get_default_conv_template(self, model_path: str) - Conversation: if v0 in remove_parent_directory_name(model_path): return get_conv_template(one_shot) return get_conv_template(vicuna_v1.1)可以看到它按模型版本号切换模板v0 用one_shot其余用vicuna_v1.1并在加载后对旧版权重给出警告。另一个极简例子是Llama2AdapterL1563-L1576match检查llama-2 in model_path.lower()load_model在父类加载后修正eos_token_id/pad_token_id模板固定返回llama-2。新模型如果可以直接用 HuggingFace 的AutoModelForCausalLM加载则适配器只需实现match与get_default_conv_template两个方法其余继承BaseModelAdapter默认行为即可。加载入口 fastchat/model/model_adapter.py#L201 的load_model在拿到适配器后统一处理设备映射cuda/cpu/mps/xpu/npu、多卡device_map、8-bit 量化、CPU offloading、AWQ/GPTQ 等压缩推理路径——这些能力对所有走适配器的模型自动生效是“注册即接入”的底层保证。步骤三可选在 model_registry 中登记展示信息fastchat/model/model_registry.py 用一个OrderedDict存放模型的展示信息ModelInfo namedtuple(ModelInfo, [simple_name, link, description]) def register_model_info( full_names: List[str], simple_name: str, link: str, description: str ): info ModelInfo(simple_name, link, description) for full_name in full_names: model_info[full_name] info通过register_model_info可为多个完整模型名登记同一个展示名与描述例如 L31-L41 中为 Yuan2 系列各规格注册统一条目。若模型未注册get_model_info会返回一条提示 “Register the description at fastchat/model/model_registry.py” 的占位信息——从源码结构看该注册主要影响 Web UI 中的模型排序与描述展示不影响推理功能本身。本地模型兼容范围文档列出的 Supported Models文档在步骤说明之后给出了当前支持的本地模型清单名称均为 Hugging Face 仓库标识完整继承如下其中标注了文档提供的启动示例meta-llama/Llama-2-7b-chat-hfexample:python3 -m fastchat.serve.cli --model-path meta-llama/Llama-2-7b-chat-hfVicuna、Alpaca、LLaMA、Koalaexample:python3 -m fastchat.serve.cli --model-path lmsys/vicuna-7b-v1.5allenai/tulu-2-dpo-7bBAAI/AquilaChat-7B、BAAI/AquilaChat2-7B、BAAI/AquilaChat2-34B、BAAI/bge-large-enargilla/notus-7b-v1baichuan-inc/baichuan-7BBlinkDL/RWKV-4-Ravenexample:python3 -m fastchat.serve.cli --model-path ~/model_weights/RWKV-4-Raven-7B-v11x-Eng99%-Other1%-20230429-ctx8192.pthbofenghuang/vigogne-2-7b-instruct、bofenghuang/vigogne-2-7b-chatcamel-ai/CAMEL-13B-Combined-Datacodellama/CodeLlama-7b-Instruct-hfdatabricks/dolly-v2-12bdeepseek-ai/deepseek-llm-67b-chat、deepseek-ai/deepseek-coder-33b-instructFlagAlpha/Llama2-Chinese-13b-ChatFreedomIntelligence/phoenix-inst-chat-7b、FreedomIntelligence/ReaLM-7b-v1h2oai/h2ogpt-gm-oasst1-en-2048-open-llama-7bHuggingFaceH4/starchat-beta、HuggingFaceH4/zephyr-7b-alphainternlm/internlm-chat-7bcllm的 consistency-llm 系列consistency-llm-7b-codesearchnet、consistency-llm-7b-gsm8k、consistency-llm-7b-sharegpt48k、consistency-llm-7b-spiderIEITYuan/Yuan2-2B/51B/102B-hflcw99/polyglot-ko-12.8b-chang-instruct-chatlmsys/fastchat-t5-3b-v1.0meta-math/MetaMath-7B-V1.0Microsoft/Orca-2-7bmosaicml/mpt-7b-chatexample:python3 -m fastchat.serve.cli --model-path mosaicml/mpt-7b-chatNeutralzz/BiLLa-7B-SFTnomic-ai/gpt4all-13b-snoozyNousResearch/Nous-Hermes-13bopenaccess-ai-collective/manticore-13b-chat-pygOpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5openchat/openchat_3.5Open-Orca/Mistral-7B-OpenOrcaOpenLemur/lemur-70b-chat-v1Phind/Phind-CodeLlama-34B-v2project-baize/baize-v2-7bQwen/Qwen-7B-Chatrishiraj/CatPPTSalesforce/codet5p-6bStabilityAI/stablelm-tuned-alpha-7btenyx/TenyxChat-7B-v1TinyLlama/TinyLlama-1.1B-Chat-v1.0THUDM/chatglm-6b、THUDM/chatglm2-6btiiuae/falcon-40b、tiiuae/falcon-180B-chattimdettmers/guanaco-33b-mergedtogethercomputer/RedPajama-INCITE-7B-ChatVMware/open-llama-7b-v2-open-instructWizardLM/WizardLM-13B-V1.0、WizardLM/WizardCoder-15B-V1.0Xwin-LM/Xwin-LM-7B-V0.1任意 EleutherAI 的 pythia 模型如pythia-6.9b任意基于上述模型训练的 Peft 适配器启用要求模型路径中包含peft字样注意加载多个 peft 模型时可设置环境变量PEFT_SHARE_BASE_WEIGHTStrue在任一 model worker 中让它们共享底座模型权重。API 模型支持配置文件与自定义 Provider接入原则对 API 模型文档建议从现有的 OpenAI 示例学起。如果目标模型兼容 OpenAI API则只需要一个配置文件无需写任何代码对自定义协议则需要在 fastchat/serve/api_provider.py 中实现一个流式生成器参照文件内已有示例。文档列举的兼容范围为 OpenAI、Anthropic、Google Vertex AI、Mistral、Nvidia NGC、YandexGPT 与 Reka。步骤一编写 JSON 端点配置文件指定端点信息例如创建api_endpoints.json{ gpt-3.5-turbo: { model_name: gpt-3.5-turbo, api_type: openai, api_base: https://api.openai.com/v1, api_key: sk-******, anony_only: false, recommended_config: { temperature: 0.7, top_p: 1.0 }, text-arena: true, vision-arena: false } }各字段含义按文档说明字段说明api_type取值为 openai、anthropic、gemini、mistral、yandexgpt 或 reka对自定义 API新增一个类型并在 Provider 层实现anony_only该模型是否只在匿名模式下展示recommended_config推荐的temperature与top_p生成参数text-arena是否显示在 Text Arenavision-arena是否显示在 Vision Arena从 fastchat/serve/api_provider.py 的源码看api_type的分支实际比文档列举的更多除上述类型外还包括openai_no_stream、openai_o1、openai_assistant、anthropic_message、anthropic_message_vertex、gemini_no_stream、bard、nvidia、vertex、cohere、column等——实现新 Provider 时可直接在同一个分支结构中按既有写法扩展。步骤二启动带 API 模型的 WebUI文档给出的启动命令python3 -m fastchat.serve.gradio_web_server --controller --share --register api_endpoints.json启动后即可在浏览器中与模型交互。需要说明的一个细节当前仓库中该命令行参数的名称是--register-api-endpoint-file见 fastchat/serve/gradio_web_server.py#L1099文档示例中的--register为简写表述实际运行时以仓库代码定义的参数名为准。该参数的作用逻辑在 fastchat/serve/gradio_web_server.py 的get_model_list函数先通过 controller 的/list_language_models收集本地模型再读取 JSON 文件按text-arena/vision-arena标志把 API 模型并入模型列表text-arena缺省视为truevision-arena缺省视为false随后把anony_only为true的模型从可见列表visible_models中移除并按model_info注册顺序排序。这解释了上面每个配置字段的实际去向也说明多模型服务场景可用 fastchat/serve/gradio_web_server_multi.py同样支持--register-api-endpoint-file。接入后的验证与兼容性无论本地还是 API 模型接入完成后的验证路径是一致的本地模型先跑python3 -m fastchat.serve.cli --model path --debug用--debug输出的实际 prompt 核对模板拼装角色名、分隔符、停止符是否与官方参考实现一致按文档要求对 Web UI、model workerfastchat/serve/model_worker.py以及 OpenAI 兼容 API serverfastchat/serve/openai_api_server.py逐一做测试因为模板与适配器在 CLI、worker、API server 中是同一套注册机制的不同消费方若模板注册重名、适配器匹配不到模型路径会分别以断言失败{template.name} has been registered.或ValueError: No valid model adapter for {model_path}的形式显式报错便于快速定位。遵循“模板注册 → 适配器注册 → 展示信息登记”这条主线再配合--debug与实际功能面的测试就是 FastChat 接入一个新模型的标准流程。【免费下载链接】FastChatAn open platform for training, serving, and evaluating large language models. Release repo for Vicuna and Chatbot Arena.项目地址: https://gitcode.com/GitHub_Trending/fa/FastChat创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考