You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在TensorFlow Serving运行时添加多模型且不卸载原有模型?

解决TensorFlow Serving添加新模型不卸载原有模型的问题

你遇到的问题根源在于:你的代码直接用全新的ModelConfigList替换了服务器的原有配置,这会导致TensorFlow Serving卸载所有已加载的模型,只保留你新添加的那个。要实现"保留原有模型同时添加新模型",正确的做法是先获取当前服务器的配置,在原有配置基础上添加新模型,再重新加载完整配置

修正后的实现代码

下面是修改后的函数,它会先获取服务器当前的模型配置,添加新模型后再提交更新:

from tensorflow_serving.apis import model_service_pb2_grpc
from tensorflow_serving.apis import model_management_pb2
from tensorflow_serving.config import model_server_config_pb2
import grpc

def add_model_config(host, name, base_path, model_platform):
    channel = grpc.insecure_channel(host)
    stub = model_service_pb2_grpc.ModelServiceStub(channel)

    # 第一步:获取当前服务器的模型配置
    get_config_request = model_management_pb2.GetModelServerConfigRequest()
    try:
        get_config_response = stub.GetModelServerConfig(get_config_request, 10)
        model_server_config = get_config_response.config
    except grpc.RpcError as e:
        print(f"获取当前配置失败: {e}")
        return False

    # 检查新模型是否已经存在,避免重复添加
    for config in model_server_config.model_config_list.config:
        if config.name == name:
            print(f"模型 {name} 已经存在于当前配置中")
            return True

    # 第二步:在原有配置中添加新模型
    new_config = model_server_config.model_config_list.config.add()
    new_config.name = name
    new_config.base_path = base_path
    new_config.model_platform = model_platform

    # 第三步:构建重载配置请求并发送
    reload_request = model_management_pb2.ReloadConfigRequest()
    reload_request.config.CopyFrom(model_server_config)
    
    print("更新后的配置字段:", reload_request.ListFields())
    try:
        reload_response = stub.HandleReloadConfigRequest(reload_request, 10)
        if reload_response.status.error_code == 0:
            print("模型添加成功,原有模型已保留")
            return True
        else:
            print("重载配置失败!")
            print(f"错误码: {reload_response.status.error_code}")
            print(f"错误信息: {reload_response.status.error_message}")
            return False
    except grpc.RpcError as e:
        print(f"发送重载请求失败: {e}")
        return False

关键改动说明

  1. 获取当前配置
    通过GetModelServerConfig接口获取服务器当前的完整配置,这样就能保留所有已有的模型配置。

  2. 避免重复添加
    在添加新模型前,先遍历现有配置检查模型名称是否已存在,防止因重复提交导致错误。

  3. 增量更新配置
    在原有model_config_list.config列表中调用add()方法添加新模型,而不是创建全新的配置列表,这样原有模型的配置会被完整保留。

额外注意事项

  • 确保新模型的base_path是TensorFlow Serving进程有权限访问的路径(如果使用Docker部署,需要把模型目录挂载到容器内的对应路径)。
  • 如果你的TensorFlow Serving启用了TLS加密,需要把grpc.insecure_channel替换为带证书的安全通道。
  • 重载配置时,TensorFlow Serving会热加载新模型,原有模型的服务不会中断(除非新配置和原有配置有冲突,比如同名模型路径修改)。

内容的提问来源于stack exchange,提问作者Rahul

火山引擎 最新活动