KServe V1beta1ComponentExtensionSpec 详解:InferenceService 组件部署与扩缩容配置指南

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

KServe V1beta1ComponentExtensionSpec 详解:InferenceService 组件部署与扩缩容配置指南

导读

ComponentExtensionSpec(组件扩展规范)是 KServe InferenceService 中用于定义单个组件(predictor / transformer / explainer)部署行为的通用配置结构,涵盖副本数、自动扩缩容、并发上限、请求超时、金丝雀流量、日志、批处理以及 Pod 标签/注解等能力。本文基于 KServe 仓库中的 V1beta1ComponentExtensionSpec.md 展开,并结合 Go 控制器源码(component.go、predictor.go、ksvc_reconciler.go、hpa_reconciler.go)深入讲解每个字段的作用、默认值、校验规则与实际落地行为,帮助你在编写 InferenceService YAML 时正确、精准地控制组件的部署形态与弹性伸缩。

一、ComponentExtensionSpec 是什么

在 KServe v1beta1 API 中,InferenceServiceSpec 由 predictor、transformer、explainer 三个组件组成,每个组件(PredictorSpec、TransformerSpec、ExplainerSpec)都内嵌了同一个 ComponentExtensionSpec。它定义的是与具体推理框架无关的部署级配置,而组件本身(如 tensorflow、sklearn、model)只负责定义"用什么框架、跑哪个模型"。

ComponentExtensionSpec defines the deployment configuration for a given InferenceService component.

从 component.go 的 Go 结构体定义可以看到,它内嵌了 14 个字段。在 Kubernetes 的 InferenceService YAML 中,这些字段直接写在组件层级下,例如:

apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata:
  name: my-model
spec:
  predictor:
    minReplicas: 1
    maxReplicas: 5
    scaleMetric: concurrency
    scaleTarget: 2
    containerConcurrency: 10
    timeout: 300
    model:
      modelFormat:
        name: sklearn
      storageUri: s3://my-bucket/model

控制器在调和(reconcile)时会读取 isvc.Spec.Predictor.ComponentExtensionSpec 等组件扩展配置,并将其翻译为实际的 Knative Service、Kubernetes Deployment 或 HPA(HorizontalPodAutoscaler)对象——详见 predictor.go 中 reconcileRawDeployment / reconcileKnativeDeployment 的调用链。

二、属性全览

下表汇总了该 Spec 的全部属性,来源于 V1beta1ComponentExtensionSpec.md,均为可选字段([optional]):

属性名(YAML key) 类型 说明
annotations dict(str, str) 添加到组件 Pod 上的注解,参见 Kubernetes Annotations
autoScaling V1beta1AutoScalingSpec 基于 HPA 或 KEDA 的自动扩缩容配置
batcher V1beta1Batcher 请求批处理(payload batching)配置,所有组件通用
canaryTrafficPercent int 候选 revision 与最近就绪 revision 之间的流量切分百分比
containerConcurrency int 每个副本可并发处理的请求数硬上限(Knative 概念)
deploymentStrategy K8sIoApiAppsV1DeploymentStrategy Deployment 滚动更新策略,仅 raw 部署模式生效
labels dict(str, str) 添加到组件 Pod 上的标签,参见 Kubernetes Labels
logger V1beta1LoggerSpec 请求/响应日志(payload logging)配置
maxReplicas int 自动扩缩容的最大副本数
minReplicas int 最小副本数,默认 1,可设为 0 以启用 scale-to-zero
scaleMetric str 扩缩容指标类型,可选 concurrency、rps、cpu、memory;concurrency/rps 由 Knative Pod Autoscaler 支持
scaleMetricType str 指标目标类型,可选 Utilization 或 AverageValue
scaleTarget int Autoscaler 观测的指标整数目标值,concurrency/rps 由 Knative Pod Autoscaler 支持
timeout int 组件请求超时秒数(TimeoutSeconds)

从 Go 源码 component.go 可以看到每个字段对应的 JSON tag:minReplicas、maxReplicas、scaleTarget、scaleMetric、scaleMetricType、autoScaling、containerConcurrency、timeout、canaryTrafficPercent、logger、batcher、labels、annotations、deploymentStrategy。Python SDK 侧对应自动生成的模型类 v1beta1_component_extension_spec.py 也完整复刻了这些字段(openapi_types 与 attribute_map 见该文件 L49-L81)。

三、副本数与自动扩缩容配置

3.1 minReplicas / maxReplicas

  • minReplicas:组件的最小副本数,默认值为 1(常量定义见 constants.go 的 DefaultMinReplicas)。将其设为 0 可以启用 scale-to-zero,即无流量时 Pod 缩容到 0,特别适合 GPU 推理等成本敏感场景。
  • maxReplicas:最大副本数,用于限制自动扩缩容的上限。

校验逻辑位于 component.go 的 validateReplicas:

  • minReplicas 不能小于 0(MinReplicasLowerBoundExceededError);
  • maxReplicas 不能小于 0(MaxReplicasLowerBoundExceededError);
  • 当 maxReplicas != 0 时,minReplicas 不能大于 maxReplicas(MinReplicasShouldBeLessThanMaxError)。

值得注意的是,HPA 调和器 hpa_reconciler.go 在创建 HPA 时还有一层防御性处理:若 minReplicas 未设置或小于 1,则回退到默认值 1;若 maxReplicas < minReplicas,则强制将 maxReplicas 抬升为 minReplicas,避免产生非法 HPA 对象。

3.2 scaleMetric / scaleTarget / scaleMetricType

这三个字段共同描述"基于什么指标、目标值是多少"的扩缩容规则:

  • scaleMetric 的合法值在源码中通过枚举约束(component.go)限定为 cpu、memory、concurrency、rps。其中 concurrency 与 rps 由 Knative Pod Autoscaler 支持;cpu、memory 用于 HPA 资源型扩缩容。
  • scaleTarget 指定指标的目标整数。对于 rps 指标,inference_service_validation.go 要求目标值必须大于 1。
  • scaleMetricType 指定目标类型,可选 Utilization(利用率百分比)或 AverageValue(平均绝对值),定义见 component.go。

在 Knative 模式下,scaleTarget 与 scaleMetric 会通过 knutils.SetAutoScalingAnnotations 转换为 Knative Service 的 autoscaling 注解(autoscaling.knative.dev/target、autoscaling.knative.dev/metric),见 ksvc_reconciler.go。在 raw 部署模式下,它们被 HPA 调和器消费:默认以 CPU 为目标、默认利用率 80(DefaultCPUUtilization,见 constants.go),详见 hpa_reconciler.go。

3.3 autoScaling:基于 HPA / KEDA 的扩展配置

autoScaling(V1beta1AutoScalingSpec)是比 scaleMetric/scaleTarget 更通用的自动扩缩容规范,结构如下(Go 定义见 component.go,Python 侧见 V1beta1AutoScalingSpec.md):

属性名 类型 说明
metrics list[V1beta1MetricsSpec] 用于自动扩缩容的指标规格列表
behavior K8sIoApiAutoscalingV2HorizontalPodAutoscalerBehavior HPA 的扩缩容行为配置(如稳定窗口、扩缩容速率限制)

MetricsSpec 的指标来源类型(MetricSourceType)有三种:Resource(Kubernetes 资源指标,如 CPU/内存)、External(集群外部的全局指标,如云消息队列长度)、PodMetric(描述每个 Pod 的指标,如每秒事务数),枚举定义见 component.go。

针对不同 autoscalerClass 注解,校验规则有明显差异(inference_service_validation.go):

  • HPA(serving.kserve.io/autoscalerClass=hpa):scaleMetric 仅支持 cpu/memory;autoScaling.metrics 仅支持 Resource 类型。
  • KEDA(autoscalerClass=keda):不支持 scaleMetric 字段(会直接报错);metrics 支持 Resource、External、PodMetric 三种来源;CPU 目标必须是 Utilization 类型,内存目标可以是 AverageValue 或 Utilization(AverageValue 时要求值大于 1 MiB),External/PodMetric 的 query 不能为空且必须设置目标值。

3.4 autoscalerClass 注解与 Scale-to-Zero

虽然 autoscalerClass 本身是 InferenceService 上的注解而非 ComponentExtensionSpec 字段,但它直接决定 scaleMetric/scaleTarget/autoScaling 的生效方式。合法值定义在 constants.go:hpa(默认)、kpa、external、keda、none。

  • Knative 模式下默认使用 kpa,支持 concurrency/rps 指标;
  • raw 部署模式下默认使用 hpa(DefaultAutoscalerClass,见 constants.go);
  • 多节点(multinode)推理场景强制使用 none(inference_service_validation.go)。

scale-to-zero 的官方示例见 autoscaling/README.md:

apiVersion: "serving.kserve.io/v1beta1"
kind: "InferenceService"
metadata:
  name: "flowers-sample"
spec:
  predictor:
    minReplicas: 0
    tensorflow:
      storageUri: "gs://kfserving-examples/models/tensorflow/flowers"

四、containerConcurrency 与 timeout

4.1 containerConcurrency

containerConcurrency 定义每个副本在同一时刻可以并发处理的请求数硬上限。当并发达到上限时,超出的请求会被缓冲等待,直到有足够容量才被执行。在 Knative 模式下,该值直接映射到 Knative Service 的 spec.template.spec.containerConcurrency,见 ksvc_reconciler.go。官方示例(autoscaling/README.md):

apiVersion: "serving.kserve.io/v1beta1"
kind: "InferenceService"
metadata:
  name: "flowers-sample"
spec:
  predictor:
    containerConcurrency: 10
    tensorflow:
      storageUri: "gs://kfserving-examples/models/tensorflow/flowers"

校验规则(component.go):containerConcurrency 不能小于 0,否则报 ParallelismLowerBoundExceededError。

4.2 timeout

timeout(TimeoutSeconds)指定等待组件响应请求的超时秒数。在 Knative 模式下,该值被同步写入 Knative Service 的 TimeoutSeconds 与 ResponseStartTimeoutSeconds(见 ksvc_reconciler.go);在 raw 部署模式下,它被写入 Deployment 容器的探针/生命周期配置(见 deployment_reconciler.go 附近的 TimeoutSeconds: 1 用法)。

五、金丝雀流量与发布策略

5.1 canaryTrafficPercent

canaryTrafficPercent 定义候选 revision(candidate)与最近就绪 revision(last ready revision)之间的流量切分百分比,是 KServe 金丝雀发布的核心开关。在 Knative 模式下,控制器会为最新 revision 分配 canaryTrafficPercent 的流量,其余流量(100 - canaryTrafficPercent)指向上一个就绪 revision,见 ksvc_reconciler.go。例如设置为 20 表示 20% 流量进入新版本、80% 留在旧版本。

5.2 金丝雀限制与校验

从 inference_service_validation.go 的 validateCanarySpecs 可以看出金丝雀(spec.canary 列表)对扩展字段的严格约束:

  • 金丝雀仅支持 standard 部署模式;
  • 金丝雀 predictor 不允许设置 maxReplicas、scaleTarget、scaleMetric、autoScaling(金丝雀使用固定副本数);
  • 金丝雀必须有 predictor.name,且不能与 stable predictor 同名、不能重复;
  • 每个金丝雀的 trafficPercent 必须在 0~100 之间。

此外,predictor.go 的 buildCanaryPredictor 在构建金丝雀预测器时会强制将 MaxReplicas 置 0、清空 ScaleTarget/ScaleMetric/AutoScaling,并把 MinReplicas 设为根据流量百分比计算出的固定副本数(predictor.go 的 canaryReplicaCount);同时 adjustStableMinReplicasForCanaries(predictor.go)会在金丝雀就绪后下调 stable predictor 的 minReplicas,避免发布窗口期的容量空缺。

5.3 deploymentStrategy

deploymentStrategy(Kubernetes apps/v1 DeploymentStrategy)仅适用于 raw 部署模式(Knative 模式下会校验报错,见 inference_service_validation.go)。用户指定的策略优先于 ConfigMap 中的默认策略,落地逻辑见 deployment_reconciler.go。未指定时,Deployment 默认使用 RollingUpdate 策略(同文件 L389-L423)。

spec:
  predictor:
    deploymentStrategy:
      type: RollingUpdate
      rollingUpdate:
        maxSurge: 25%
        maxUnavailable: 25%

六、日志(logger)与批处理(batcher)

6.1 logger:请求/响应日志

logger(V1beta1LoggerSpec)用于为组件激活请求/响应 payload 日志,结构见 V1beta1LoggerSpec.md:

属性名 类型 说明
mode str 日志范围:all(默认,请求+响应)、request(仅请求)、response(仅响应)
url str 发送日志事件的目标 URL
storage V1beta1LoggerStorageSpec 日志存储配置(如对象存储)
batchSize int 每批日志记录数,默认 1(立即发送)
batchInterval str 部分批次刷新的最大等待时长(如 "5s"、"100ms"),仅 batchSize > 1 时生效,默认 "0"(无定时刷新)
marshallerUrl str 日志 marshaller 服务 URL,默认内嵌 JSON marshaller http://localhost:9083/marshal
metadataAnnotations list[str] 需要透传到推理日志 CloudEvent 的 InferenceService 注解匹配列表
metadataHeaders list[str] 需要透传到推理日志 CloudEvent 的元数据 HTTP 头匹配列表

校验逻辑(component.go):mode 必须是 all/request/response 之一;若配置了 storage,则其 path、parameters、storageKey 均不能为空。

6.2 batcher:请求批处理

batcher(V1beta1Batcher)为所有组件提供可选的 payload 批处理能力,结构见 V1beta1Batcher.md:

属性名 类型 说明
maxBatchSize int 触发一个批次的请求数上限
maxLatency int 触发一个批次的最大延迟
timeout int 一个批次的超时时间

Python SDK 的单元测试(test_v1beta1_component_extension_spec.py)展示了 batcher、logger、canaryTrafficPercent、containerConcurrency、maxReplicas、minReplicas、timeout 组合构造 V1beta1ComponentExtensionSpec 的标准用法,可作为 SDK 调用参考。

七、labels / annotations:Pod 元数据透传

labels 与 annotations 分别以 dict(str, str) 形式定义,会追加到组件 Pod 上(而非替换),可用于:

  • 通过标签筛选组件 Pod、绑定调度规则(nodeSelector / affinity / topologySpreadConstraints 的 selector);
  • 通过注解注入自定义配置,例如 serving.kserve.io/autoscalerClass、serving.kserve.io/deploymentMode 等由控制器读取的行为开关。
spec:
  predictor:
    labels:
      team: ml-platform
      tier: production
    annotations:
      serving.kserve.io/autoscalerClass: hpa

需要留意的是,KServe 控制器会维护 ServiceLabelDisallowedList(见 predictor.go 传入 Knative reconciler 的 disallowed label 列表),部分保留标签不允许被覆盖,以避免破坏 Knative Service 的选择器语义。

八、默认值、校验与实现要点小结

下表汇总了各字段的默认值来源与关键行为,全部可在仓库源码中验证:

字段 默认/约束 依据
minReplicas 默认 1;可设 0 启用 scale-to-zero constants.go、hpa_reconciler.go
maxReplicas 若小于 minReplicas 会被抬升 hpa_reconciler.go
scaleMetric 枚举 cpu/memory/concurrency/rps component.go
scaleTarget rps 目标必须 > 1;默认 CPU 利用率 80 inference_service_validation.go、constants.go
scaleMetricType Utilization / AverageValue / Value component.go
containerConcurrency 必须 ≥ 0 component.go
canaryTrafficPercent 0~100,仅在 standard 模式生效 inference_service_validation.go
deploymentStrategy 仅 raw 模式,默认 RollingUpdate inference_service_validation.go、deployment_reconciler.go
logger.mode all/request/response component.go

整体校验入口是 component.go 的 ComponentExtensionSpec.Validate(),它依次执行 validateContainerConcurrency、validateReplicas、validateLogger;组件级校验还会结合 autoscalerClass 调用 validateScalingHPACompExtension / validateScalingKedaCompExtension / validateScalingKPACompExtension(inference_service_validation.go),从源码结构可以看出不同部署模式与扩缩容后端对扩展字段的接受范围差异显著。

九、快速上手:一个完整的配置示例

综合以上内容,下面给出一个同时使用副本控制、并发、超时、金丝雀、日志与批处理的 InferenceService 示例(字段均可在上述源码与文档中找到依据):

apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata:
  name: example-isvc
  annotations:
    serving.kserve.io/deploymentMode: RawDeployment   # 或使用 Serverless / Knative 模式
    serving.kserve.io/autoscalerClass: hpa            # raw 模式下可显式指定 HPA
spec:
  predictor:
    minReplicas: 1
    maxReplicas: 5
    scaleMetric: cpu
    scaleTarget: 60
    containerConcurrency: 20
    timeout: 120
    batcher:
      maxBatchSize: 32
      maxLatency: 50
    logger:
      mode: all
      url: http://logger.default.svc.cluster.local
    labels:
      app: example
    annotations:
      example.com/note: "custom annotation"
    model:
      modelFormat:
        name: sklearn
      storageUri: s3://my-bucket/sklearn-model

配置完成后即可通过 kubectl apply 部署,并由 KServe 控制器自动生成对应的 Knative Service / Deployment / HPA 资源。若希望进一步了解 autoScaling 的指标细节,可继续阅读仓库中的 V1beta1AutoScalingSpec.md、V1beta1MetricsSpec.md 与 V1beta1MetricTarget.md 等相邻文档,形成完整的弹性伸缩配置知识链。

登录后查看全文
kserve