KServe V1alpha2LLMInferenceServiceConfig 详解:LLM 推理服务的模板化基础配置机制

原创2026-10-11 19:11:271,988 阅读
文章标签:模型推理服务人工智能大模型云原生后端微服务本地部署

KServe V1alpha2LLMInferenceServiceConfig 详解:LLM 推理服务的模板化基础配置机制

导读:本文围绕 KServe 中 LLMInferenceServiceConfig 这一 Kubernetes 自定义资源(CRD)展开,说明它如何作为"配置模板"被多个 LLMInferenceService 实例继承,实现 LLM 推理场景下的基础设施配置复用。读者将掌握该 API 的字段结构(apiVersion/kind/metadata/spec/status)、spec 中可模板化的全部配置维度(模型、运行时、工作负载、路由、调度器、追踪等)、控制器如何通过 baseRefs 与 well-known 预设完成配置合并,以及如何结合源码与真实样本文件编写可落地的 YAML。


一、什么是 LLMInferenceServiceConfig

LLMInferenceServiceConfig 是 llminferenceserviceconfigs API 的 Schema(资源模型),它的定位在源码注释中定义得非常直白:

It acts as a template to provide base configurations that can be inherited by multiple LLMInferenceService instances. (它充当模板,提供可被多个 LLMInferenceService 实例继承的基础配置。)

也就是说,当团队需要在多个 LLM 推理服务之间共享同一套 vLLM 容器镜像、探针、安全上下文、调度器参数时,不必在每个服务里重复书写,而是先创建一个 LLMInferenceServiceConfig,再由各个 LLMInferenceService 通过 spec.baseRefs 引用它。这与面向对象中的"基类继承"思想一致:配置模板是基类,推理服务是继承并覆写的子类。

在 KServe 仓库中,该类型的 Go 定义位于 pkg/apis/serving/v1alpha2/llm_inference_service_types.go,对应的 OpenAPI 模型参考文档即 python/kserve/docs/V1alpha2LLMInferenceServiceConfig.md。它属于 serving.kserve.io/v1alpha2 API 组,CRD 清单可在 config/crd/full 目录中找到(llminferenceserviceconfigs.serving.kserve.io)。

二、资源字段结构(Properties)速览

LLMInferenceServiceConfig 的顶层结构与所有 Kubernetes 对象一致,包含五个字段,全部可省略([optional]):

字段 类型 说明
api_version str API 版本标识,服务端会将已识别的 Schema 转换为最新的内部版本,并可能拒绝无法识别的值
kind str REST 资源类型字符串,CamelCase 格式,创建后不可更新
metadata V1ObjectMeta 标准的 Kubernetes 对象元数据(名称、命名空间、标签、注解等)
spec V1alpha2LLMInferenceServiceSpec 期望状态,是配置模板的主体(下文详解)
status V1alpha2LLMInferenceServiceConfigStatus 由控制器填充的观测状态(下文详解)

其中 spec 与 status 的类型定义如下:

  • spec:V1alpha2LLMInferenceServiceSpec,即 V1alpha2LLMInferenceServiceSpec.md 所描述的完整 LLMInferenceServiceSpec。注意一个关键设计:Config 的 spec 与 LLMInferenceService 的 spec 是同一个结构体(Go 源码中 LLMInferenceServiceConfig.Spec 的类型就是 LLMInferenceServiceSpec,见 llm_inference_service_types.go),这意味着模板可以覆盖服务 spec 的全部维度,只是其中 model 字段对 Config 而言是可选的(模型 URI 通常由真正部署的服务来提供)。
  • status:V1alpha2LLMInferenceServiceConfigStatus,详见 V1alpha2LLMInferenceServiceConfigStatus.md,包含三个属性:
status 字段 类型 说明
annotations dict(str, str) 附加的状态字段,用于保存额外状态并向用户传达更多信息,类似于普通资源上的 Annotations
conditions list[KnativeCondition] 资源当前状态的最新观测,遵循 Knative Conditions 约定
observed_generation int 控制器最后一次处理的 Generation 值

除了上述三个属性,Go 端还额外定义了一个 referencedBy 字段(+optional、+listType=atomic),用于列出所有通过 spec.baseRefs、status.annotations 或隐式 well-known 默认方式引用该配置的 LLMInferenceService 实例,见 llm_inference_service_types.go。

三、spec:可以模板化的配置维度

由于 Config 复用完整的 LLMInferenceServiceSpec,模板可以继承以下全部配置维度(字段注释引自 llm_inference_service_types.go):

spec 字段 类型 作用
model LLMModelSpec 模型规范:URI、模型名、LoRA 适配器、机密模型配置;对 Config 类型可选
runtime *string ServingRuntime / ClusterServingRuntime 名称,提供基础容器镜像;省略时控制器使用默认 vLLM 模板(kserve-config-llm-template)
storageInitializer *StorageInitializerSpec 模型制品拉取配置(如 enabled: false 可跳过 init 容器)
replicas / scaling / parallelism / labels / annotations / template / worker / kvCacheOffloading / rolloutStrategy WorkloadSpec(内联) 主推理工作负载的副本数、自动缩放、张量/流水线/数据并行、Pod 模板、多节点 worker、KV Cache 卸载、滚动更新策略
router *RouterSpec 服务暴露方式:Gateway API(Route/Gateway)、Ingress、以及推理网关调度器(Scheduler)
prefill *WorkloadSpec 分离式部署(prefill/decode 分离)中的 prefill 工作负载
tracing *TracingSpec 分布式追踪配置,可传播到推理服务器与调度器所有托管组件
baseRefs []corev1.LocalObjectReference 继承并覆写一个或多个 LLMInferenceServiceConfig 的配置

几个值得展开的关键点:

  1. runtime 解析顺序:控制器先在 LLMInferenceService 所在命名空间查找 ServingRuntime,找不到再回退到 ClusterServingRuntime,解析出的容器规范作为合并链中最低优先级的一层(见 llm_inference_service_types.go)。
  2. baseRefs 的合并语义:控制器将多个基础配置合并,当前服务的 spec 优先级最高;当存在多个 baseRefs 时,列表末尾的配置会覆写前面的(见 llm_inference_service_types.go)。
  3. 并行与调度:ParallelismSpec 提供 tensor、pipeline、data、dataLocal、expert 等维度,直接用于配置底层推理运行时(如 vLLM);RouterSpec.Scheduler 用于集成 Inference Gateway Extension 的 Endpoint Picker(EPP)调度器,只有存在多个推理 Pod 副本时才生效。

四、status:配置被谁引用、状态是否就绪

LLMInferenceServiceConfig 的生命周期状态由独立控制器 LLMISVCConfigReconciler 维护(源码见 pkg/controller/v1alpha2/llmisvc/llmisvcconfig_controller.go)。它的职责包括:

  • 维护 finalizer:当配置仍被 LLMInferenceService 引用时,serving.kserve.io/llmisvcconfig-finalizer 会阻止配置被误删除(源码在 llmisvcconfig_controller.go)。
  • 填充 status.referencedBy:reconcile 阶段会查找所有引用该配置的服务并写入 ReferencedBy 列表。
  • 更新条件状态:生命周期管理逻辑位于 pkg/apis/serving/v1alpha2/llm_inference_service_config_lifecycle.go,提供两种核心条件:
    • ConfigInUse:配置被 N 个 LLMInferenceService 引用时标记为 True(MarkConfigInUse),无引用时标记为 False(MarkConfigNotInUse);
    • Ready:MarkReady() 标记配置整体就绪。
# 查看配置的引用情况与就绪状态
kubectl get llminferenceserviceconfig -o wide
kubectl get llminferenceserviceconfig <config-name> -o jsonpath='{.status.conditions[*].type}={.status.conditions[*].status}{"\n"}'

五、well-known 预设:控制器自动选择的模板

LLMInferenceServiceConfig 还有一类特殊用法——well-known 预设(preset)。控制器会根据服务的部署形态自动选择并合并预设模板,无需用户在服务中显式引用。这些预设名称由 kserve- 前缀(可用环境变量 LLM_INFERENCE_SERVICE_CONFIG_PREFIX 覆盖)加后缀构成,完整列表定义在 pkg/controller/v1alpha2/llmisvc/config_merge.go:

预设后缀 应用场景
config-llm-template 单节点默认部署(vLLM)
config-sglang-template 单节点 SGLang 部署(当 spec.runtime 为 kserve-llm-sglang 时)
config-llm-decode-template / config-llm-prefill-template prefill/decode 分离式部署
config-llm-decode-worker-pipeline-parallel 等 4 个 worker 系列 流水线并行 / 数据并行 worker
config-llm-scheduler、config-llm-scheduler-eppconfig-default(-pd) 调度器与默认 EPP 配置
config-llm-router-route、config-llm-tokenizer 路由与 tokenizer
config-llm-tracing 分布式追踪

这些预设作为 Kubernetes 清单随发行版安装,存放于 config/llmisvcconfig 目录(如 config-llm-template.yaml 定义了默认 vLLM 容器镜像 ghcr.io/llm-d/llm-d-cuda:v0.9.0、端口 8000、探针与 RoCE 网卡自动发现逻辑等)。合并完成后,服务状态中的 status.appliedConfigs(AppliedConfigRefs)会按优先级顺序列出实际应用的配置来源,每个条目带 source 标签:Preset(KServe 内置预设)、UserRef(用户通过 baseRefs 引用)、ServingRuntime(由 runtime 解析出的容器规范),枚举定义见 llm_inference_service_types.go。

六、Webhook 校验:哪些配置不允许写进模板

LLMInferenceServiceConfig 在创建与更新时会经过准入 Webhook 校验,校验器源码在 pkg/apis/serving/v1alpha2/llm_inference_service_config_validation.go,主要规则包括:

  • 禁止 spec.baseRefs:Config 中不允许出现递归引用(baseRefs is not a permitted field in LLMInferenceServiceConfig, support for recursive refs has been disabled)。
  • 校验 LoRA 适配器:由于 Config 中的适配器会在合并后原样进入服务 spec、而服务校验器只能看到未合并的 spec,因此适配器名称唯一性、必填性、路径穿越防护与 maxRank 下限等检查必须在 Config 校验器完成(对应测试 pkg/apis/serving/v1alpha2/llm_inference_service_config_validation_test.go 中的 TestValidateLoRAAdaptersFromConfig)。
  • 校验调度器副本数:spec.router.scheduler.replicas 必须大于 0(scheduler replicas must be greater than zero)。
  • well-known 配置保护:修改或删除 well-known 预设会触发 admission warning;当 PreventWellKnownConfigDeletion 开启时,活跃的 well-known 配置禁止被删除(见 llm_inference_service_config_validation.go)。
# 应用一个带 baseRefs 的非法配置,会被 Webhook 拒绝
kubectl apply -f - <<'EOF'
apiVersion: serving.kserve.io/v1alpha2
kind: LLMInferenceServiceConfig
metadata:
  name: invalid-recursive-config
spec:
  baseRefs:
    - name: another-config
EOF
# Error: baseRefs is not a permitted field in LLMInferenceServiceConfig

七、实战:编写并引用一个 LLMInferenceServiceConfig

下面以仓库样本 docs/samples/llmisvc/e2e-gpt-oss 为例,展示完整的"模板 + 服务"双文件落地流程。

7.1 创建配置模板

样本 llmisvc_config_default.yaml 演示了如何覆写基础预设中的镜像、命令、安全上下文、探针与调度器参数:

apiVersion: serving.kserve.io/v1alpha2
kind: LLMInferenceServiceConfig
metadata:
  name: llmisvc-intelligent-inference-scheduling
spec:
  template:
    containers:
      # 覆写 base config 的镜像版本与启动命令
      - image: ghcr.io/llm-d/llm-d-cuda:v0.9.0
        name: main
        command: ["/bin/sh", "-c"]
        args:
          - >
            vllm serve /mnt/models
            --served-model-name "{{ .Spec.Model.Name }}"
            --port 8000
            --disable-access-log-for-endpoints /health,/metrics,/ping
            $VLLM_ADDITIONAL_ARGS
        # 覆写安全上下文
        securityContext:
          runAsNonRoot: true
        # 覆写存活探针初始延迟
        livenessProbe:
          initialDelaySeconds: 1200
        # 覆写就绪探针
        readinessProbe:
          initialDelaySeconds: 10
          periodSeconds: 10
  router:
    scheduler:
      template:
        containers:
          - name: main
            # 覆写调度器镜像版本
            image: ghcr.io/llm-d/llm-d-router-endpoint-picker:v0.10.0
            args:
              - --pool-name
              - '{{ ChildName .ObjectMeta.Name `-inference-pool` }}'
              - --pool-namespace
              - '{{ .ObjectMeta.Namespace }}'
              - --zap-encoder
              - json
              - --grpc-port
              - "9002"
              - --grpc-health-port
              - "9003"
              - --metrics-endpoint-auth=false
              - --secure-serving
              - --cert-path
              - /etc/ssl/certs
            livenessProbe:
              grpc:
                port: 9003
                service: envoy.service.ext_proc.v3.ExternalProcessor
            readinessProbe:
              grpc:
                port: 9003
                service: envoy.service.ext_proc.v3.ExternalProcessor

模板语法说明:模板中的 {{ .Spec.Model.Name }}、{{ .ObjectMeta.Namespace }}、{{ ChildName ... }} 是 Go 模板占位符,在合并时由控制器用当前服务的实际值渲染,这正是"一份模板适配多个服务"的核心机制。

kubectl apply -f docs/samples/llmisvc/e2e-gpt-oss/llmisvc_config_default.yaml -n kserve-lab

7.2 在推理服务中通过 baseRefs 引用

对应的服务清单 inference_default.yaml 通过 spec.baseRefs 引用上述模板,并只声明"每个服务自己才关心的内容"——模型、副本数与资源:

apiVersion: serving.kserve.io/v1alpha2
kind: LLMInferenceService
metadata:
  name: gpt-oss-20b
spec:
  model:
    uri: "pvc://gpt-oss-20b-pvc"
    name: RedHatAI/gpt-oss-20b
  replicas: 2
  router:
    scheduler: { }
    gateway: { }
  baseRefs:
    - name: llmisvc-intelligent-inference-scheduling
  template:
    containers:
      - name: main
        resources:
          limits:
            cpu: '8'
            memory: 64Gi
            nvidia.com/gpu: 1
          requests:
            cpu: '4'
            memory: 32Gi
            nvidia.com/gpu: 1

应用后,控制器会把模板中的容器/调度器定义与服务的模型、资源合并,生成最终的 Deployment 与网络资源。验证方式:

kubectl get llminferenceservice -n kserve-lab
kubectl get pods -n kserve-lab -l app.kubernetes.io/name=gpt-oss-20b
# 查看实际应用的配置来源(按合并优先级排序)
kubectl get llminferenceservice gpt-oss-20b -n kserve-lab \
  -o jsonpath='{.status.appliedConfigs}' 

7.3 其他变体

同一目录还提供了另外两种高级模板,展示了 Config 的覆盖广度:

  • llmisvc_config_prefix_cache.yaml:精确前缀缓存感知路由,vLLM 侧追加 --prefix-caching-hash-algo sha256_cbor、--block-size 64 与 --kv-events-config(ZMQ 到 EPP),调度器侧启用 token-producer、precise-prefix-cache-producer、prefix-cache-scorer 等插件,并自动部署独立 tokenizer。
  • llmisvc_config_pd_disagg.yaml:prefill/decode 分离式部署,decode 容器带 --kv_transfer_config '{"kv_connector":"NixlConnector","kv_role":"kv_consumer"}',prefill 容器带 "kv_role":"kv_producer"。

完整操作顺序(命名空间 → PVC → HF Token → 模型下载 Job → Config → Service → Gateway/AIGatewayRoute)可参见样本目录下的 README.md,其中 kubectl apply -k docs/samples/llmisvc/e2e-gpt-oss/ -n kserve-lab 可直接用 Kustomize 一键部署整套资源。

八、总结:什么时候该用 Config

  • 多个服务共享同一套 vLLM/调度器基础设施(镜像、探针、安全上下文、调度插件)时,优先下沉到 LLMInferenceServiceConfig,服务只保留模型、副本与资源差异;
  • 需要强制团队统一部署基线时,可利用 well-known 预设 + Webhook 保护(禁止删除/修改预设并发出告警);
  • 需要按部署形态自动切换模板(单节点 / SGLang / P/D 分离 / 多节点并行)时,依赖控制器的预设选择机制,无需在每个服务中手工维护。

配置合并的完整实现位于 pkg/controller/v1alpha2/llmisvc/config_merge.go,其测试(config_merge_test.go、config_presets_test.go)覆盖了多 baseRefs 优先级、well-known 预设注入等关键行为,是深入理解合并语义的最佳入口。

登录后查看全文
kserve