Seldon Core 2 语音情感分析 Pipeline:串联 Huggingface Whisper 与情感模型,并用 Anchor Text 解释推理结果

原创2026-10-14 18:28:511,861 阅读
文章标签:人工智能机器学习MLOpsLLMOps模型推理服务云原生容器编排微服务服务网格可观测性灰度发布后端

Seldon Core 2 语音情感分析 Pipeline:串联 Huggingface Whisper 与情感模型,并用 Anchor Text 解释推理结果

本文基于 Seldon Core v2 仓库中 samples/examples/huggingface 示例,完整演示如何用两条 Huggingface 模型(Whisper 语音转文字 + 情感分类)构建一条端到端的 speech-to-sentiment 推理流水线,并通过输入/输出转换模型与 anchor_text 解释器,为 Pipeline 输出附带"为什么得出这个情感结论"的可解释证据。读完本文,你将掌握 Seldon Core 2 中 Pipeline 的多步骤编排(tensorMap 张量映射、步骤依赖、输出定义)、Explainer 如何通过 pipelineRef 指向被解释的 Pipeline、以及如何用 seldon CLI 完成模型加载、Pipeline 部署、异步推理结果与解释结果的检索。

示例概览:一条 "语音 → 文本 → 情感 → 解释" 的推理链

本示例的最终目标是:用户对着麦克风说一句话,系统返回这句话的文字转录、情感极性(POSITIVE/NEGATIVE)以及情感结论的 Anchor 解释(哪些关键词支撑了该判断)。整个功能由一条名为 speech-to-sentiment 的 Pipeline 承载,内部串联了多个独立部署的模型/运行时:

  • whisper:Huggingface 语音转文字模型,输入 base64 编码的 mp3 音频,输出转录文本;
  • sentiment:Huggingface 文本情感分类模型,输入转录文本,输出 {"label": "POSITIVE", "score": ...} 形式的 JSON;
  • sentiment-input-transform:MLServer 自定义运行时,把 Whisper 的输出转换成情感解释器能理解的输入格式;
  • sentiment-output-transform:MLServer 自定义运行时,把情感模型的 JSON 输出转换成 anchor_text 解释器可直接消费的数值(POSITIVE→1,NEGATIVE→0);
  • sentiment-explainer:基于 Alibi-Explain 的 anchor_text 黑盒解释器,通过 pipelineRef 指向解释 Pipeline sentiment-explain。
<a href="https://link.gitcode.com/i/cfe23068ffa3291826fcd51446d890c4" target="_blank">![语音情感分析 Pipeline 架构图](https://raw.gitcode.com/gh_mirrors/se/seldon-core/raw/402619eb9064b2ced678539fa3c0a1a0bd8f723a/samples/examples/huggingface/speech-to-sentiment.jpg?utm_source=gitcode_repo_files)</a>

该架构图(源文件:speech-to-sentiment.jpg)直观展示了数据在各组件之间的流动关系。值得注意的一点是:示例特意展示了 Explainer 可以指向 Pipeline 而非单个模型——这是 Seldon Core 2 支持复杂解释流程的关键能力,也是本示例区别于普通模型推理示例的核心看点。

前置准备:本地依赖与 Python 环境

示例需要在本地运行 Jupyter 笔记本来采集麦克风音频,因此对宿主机有明确的依赖要求。

安装 ffmpeg

示例使用 ffmpeg 把 WebRTC 录音得到的 .webm 文件转码为 mp3,因此本地必须安装 ffmpeg。示例目录下提供了便捷的 Makefile 目标(见 samples/examples/huggingface/Makefile):

# Ubuntu / Debian 系
make install-ffmpeg-ubuntu
# 等价于
sudo apt-get install ffmpeg

安装 Python 依赖

requirements.txt 列出了笔记本来采集音频、处理音频、展示结果所需的全部依赖(samples/examples/huggingface/requirements.txt):

ipywidgets
torchaudio
ipywebrtc
ffmpeg-python
spacy

其中 ipywebrtc 负责在 Jupyter 中拉起摄像头/麦克风流并录音,torchaudio 与 ffmpeg-python 用于音频处理,spacy 是解释器相关能力所需的自然语言处理依赖。运行:

make install-requirements
# 等价于
pip install -r requirements.txt
jupyter nbextension enable --py widgetsnbextension

widgetsnbextension 的启用是为了让 AudioRecorder/CameraStream 这类交互式控件在 Notebook 中正常渲染。

客户端推理函数:从录音到 v2 数据平面请求

示例的 Python 客户端(见 samples/examples/huggingface/huggingface.md 与对应的 huggingface.ipynb)演示了 Seldon Core 2 的 v2 数据平面协议用法。先定义请求骨架:一个 BYTES 类型的输入张量,content_type 声明为 base64:

from ipywebrtc import AudioRecorder, CameraStream
import torchaudio
from IPython.display import Audio
import base64
import json
import requests
import os
import time

reqJson = json.loads('{"inputs":[{"name":"args", "parameters": {"content_type": "base64"}, "data":[],"datatype":"BYTES","shape":[1]}]}')
url = "http://0.0.0.0:9000/v2/models/model/infer"

随后定义 infer 函数:把录音数据写入 recording.webm,用 ffmpeg 转成 mp3,base64 编码后填入请求的 data 字段,再通过 HTTP POST 发送推理请求:

def infer(resource: str):
    with open('recording.webm', 'wb') as f:
        f.write(recorder.audio.value)
    !ffmpeg -i recording.webm -vn -ab 128k -ar 44100 file.mp3 -y -hide_banner -loglevel panic
    with open("file.mp3", mode='rb') as file:
        fileContent = file.read()
        encoded = base64.b64encode(fileContent)
        base64_message = encoded.decode('utf-8')
    reqJson["inputs"][0]["data"] = [str(base64_message)]
    headers = {"Content-Type": "application/json", "seldon-model": resource}
    response_raw = requests.post(url, json=reqJson, headers=headers)
    j = response_raw.json()
    sentiment = j["outputs"][0]["data"][0]
    text = j["outputs"][1]["data"][0]
    reqId = response_raw.headers["x-request-id"]
    print(reqId)
    os.environ["REQUEST_ID"]=reqId
    print(base64.b64decode(text))
    print(base64.b64decode(sentiment))

这段代码有四个值得注意的技术点:

  1. seldon-model 请求头:Seldon Core 2 通过该头指定要调用的推理资源,取值可以是模型名,也可以是 资源类型.资源名 形式的 Pipeline(例如后续调用中的 speech-to-sentiment.pipeline);
  2. v2 数据平面协议:请求体遵循 KServe v2 协议(inputs/datatype/shape),音频以 base64 编码的字节串放入 BYTES 张量;
  3. x-request-id 响应头:每次推理会返回一个请求 ID。由于 Pipeline 中的解释结果异步生成,后续需要用该 ID 去检索对应的解释输出;
  4. 返回张量顺序:Pipeline 的输出步骤顺序(本示例先 sentiment 后 whisper)决定了 outputs[0]/outputs[1] 的对应关系。

加载两个 Huggingface 模型

模型的声明方式是 Seldon Core 2 的 mlops.seldon.io/v1alpha1 系列 CRD。Whisper 与情感模型的定义分别位于 samples/models/hf-whisper.yaml 和 samples/models/hf-sentiment.yaml:

apiVersion: mlops.seldon.io/v1alpha1
kind: Model
metadata:
  name: whisper
spec:
  storageUri: "gs://seldon-models/mlserver/huggingface/whisper"
  requirements:
  - huggingface
---
apiVersion: mlops.seldon.io/v1alpha1
kind: Model
metadata:
  name: sentiment
spec:
  storageUri: "gs://seldon-models/mlserver/huggingface/sentiment"
  requirements:
  - huggingface

两个模型的 storageUri 都指向 Seldon 官方托管的 GCS 模型仓库,requirements: [huggingface] 声明该模型需要 Huggingface 运行时能力(对应 MLServer 的 Huggingface 运行时)。加载与等待就绪:

seldon model load -f ../../models/hf-whisper.yaml
seldon model load -f ../../models/hf-sentiment.yaml

命令需在 samples/examples/huggingface 目录下执行。seldon model load -f 提交模型声明后,使用 -w 参数阻塞等待模型进入指定状态:

seldon model status whisper -w ModelAvailable | jq -M .
seldon model status sentiment -w ModelAvailable | jq -M .

两条命令在示例中输出均为 {},表示模型已进入 ModelAvailable 状态。

为可解释性准备输入/输出转换模型

要让 Alibi-Explain 的 anchor_text 解释器能够理解情感模型的输入输出,需要两个"翻译层"。原因为:

  • 情感模型的输出是 JSON 形式的 {"label": "POSITIVE", "score": 0.99...} 字典,而 anchor_text 需要数值化的预测结果;
  • 情感模型的输入是 Whisper 转录出来的原始文本(JSON 字典中的 text 字段),解释器需要拿到的是干净的字符串。

这两个转换模型都是 MLServer 自定义运行时,代码在 samples/examples/huggingface/sentiment-input-transform/model.py 与 sentiment-output-transform/model.py,模型清单在 samples/models/hf-sentiment-input-transform.yaml 与 hf-sentiment-output-transform.yaml。

输入转换:提取文本

sentiment-input-transform 运行时(samples/examples/huggingface/sentiment-input-transform/model.py)的核心逻辑:用 StringRequestCodec 解码请求中的字符串数据,从每个元素中取出 text 字段,再以 StringRequestCodec.encode_response 编码成模型名为 sentiment 的响应:

from mlserver import MLModel
from mlserver.types import InferenceRequest, InferenceResponse
from mlserver.codecs.string import StringRequestCodec
from mlserver.logging import logger

class SentimentInputTransformRuntime(MLModel):

  async def load(self) -> bool:
    return self.ready

  async def predict(self, payload: InferenceRequest) -> InferenceResponse:
    logger.info("payload (input-transform): %s",payload)
    res_list = self.decode_request(payload, default_codec=StringRequestCodec)
    texts = []
    for res in res_list:
      text = res
      texts.append(text["text"])

    response =  StringRequestCodec.encode_response(
      model_name="sentiment",
      payload=texts
    )
    return response

输出转换:情感映射为数值

sentiment-output-transform 运行时(samples/examples/huggingface/sentiment-output-transform/model.py)把情感模型的 JSON 输出映射为 0/1 数值,再用 NumpyRequestCodec 编码成模型名为 sentiments 的数值张量,供解释器直接使用:

from mlserver import MLModel
from mlserver.types import InferenceRequest, InferenceResponse
from mlserver.codecs.string import StringRequestCodec
from mlserver.codecs.numpy import NumpyRequestCodec
from mlserver.logging import logger
import numpy as np

class SentimentOutputTransformRuntime(MLModel):

  async def load(self) -> bool:
    return self.ready

  async def predict(self, payload: InferenceRequest) -> InferenceResponse:
    res_list = self.decode_request(payload, default_codec=StringRequestCodec)
    scores = []
    for res in res_list:
      sentiment = res
      if sentiment["label"] == "POSITIVE":
        scores.append(1)
      else:
        scores.append(0)
    response =  NumpyRequestCodec.encode_response(
      model_name="sentiments",
      payload=np.array(scores)
    )
    return response

转换模型的部署清单

两个转换模型通过以下 Model 清单部署(samples/models/hf-sentiment-input-transform.yaml、samples/models/hf-sentiment-output-transform.yaml):

apiVersion: mlops.seldon.io/v1alpha1
kind: Model
metadata:
  name: sentiment-input-transform
spec:
  storageUri: "gs://seldon-models/scv2/examples/huggingface/mlserver_1.3.5/sentiment-input-transform"
  requirements:
  - mlserver
  - python
---
apiVersion: mlops.seldon.io/v1alpha1
kind: Model
metadata:
  name: sentiment-output-transform
spec:
  storageUri: "gs://seldon-models/scv2/examples/huggingface/mlserver_1.3.5/sentiment-output-transform"
  requirements:
  - mlserver
  - python

注意它们与 Whisper/情感模型的 requirements 不同:这里声明的是 mlserver 与 python,对应 MLServer 自定义运行时(Python 模型运行时),而不是 Huggingface 运行时。

model-settings.json:运行时实现绑定

每个转换模型的存储目录里都有 model-settings.json,将模型名绑定到具体的 Python 实现类(sentiment-input-transform/model-settings.json、sentiment-output-transform/model-settings.json):

{
    "name": "sentiment-input-transform",
    "implementation": "model.SentimentInputTransformRuntime",
    "parameters": {
        "version": "v0.1.0"
    }
}

implementation 指向 model.py 中定义的运行时类,这就是 MLServer 加载自定义模型时解析的入口。

加载并等待就绪:

seldon model load -f ../../models/hf-sentiment-input-transform.yaml
seldon model load -f ../../models/hf-sentiment-output-transform.yaml
seldon model status sentiment-input-transform -w ModelAvailable | jq -M .
seldon model status sentiment-output-transform -w ModelAvailable | jq -M .

创建解释 Pipeline:把情感模型与其输出转换拼接起来

为了让 anchor_text 解释器能够解释情感模型的决策,示例创建了一条名为 sentiment-explain 的 Pipeline,把情感模型与输出转换模型串联(samples/pipelines/sentiment-explain.yaml):

apiVersion: mlops.seldon.io/v1alpha1
kind: Pipeline
metadata:
  name: sentiment-explain
spec:
  steps:
    - name: sentiment
      tensorMap:
        sentiment-explain.inputs.predict: array_inputs
    - name: sentiment-output-transform
      inputs:
      - sentiment
  output:
    steps:
    - sentiment-output-transform

这里的 tensorMap 是关键机制:它声明将 Pipeline 的外部输入张量 sentiment-explain.inputs.predict 映射为 sentiment 步骤的 array_inputs 输入张量。也就是说,解释器提交的原始文本会被直接喂给情感模型,然后情感输出经过 sentiment-output-transform 转成数值。Pipeline 的最终输出为 sentiment-output-transform 步骤的结果。

部署并确认状态:

seldon pipeline load -f ../../pipelines/sentiment-explain.yaml
seldon pipeline status sentiment-explain -w PipelineReady | jq -M .

就绪后的状态输出展示了 Seldon Core 2 Pipeline 的完整内部视图,包括生成的应用版本号(version: 2)、步骤展开后的依赖关系(sentiment-output-transform 的 inputs 被展开为 sentiment.outputs)、output.steps 展开为 sentiment-output-transform.outputs,以及 modelsReady: true 的同步状态。

部署 Anchor Text 解释器

解释器本身也是一个 Model 资源,通过 explainer 字段声明解释类型,并通过 pipelineRef 指向上述解释 Pipeline(samples/models/hf-sentiment-explainer.yaml):

apiVersion: mlops.seldon.io/v1alpha1
kind: Model
metadata:
  name: sentiment-explainer
spec:
  storageUri: "gs://seldon-models/scv2/examples/huggingface/speech-sentiment/explainer"
  explainer:
    type: anchor_text
    pipelineRef: sentiment-explain

从源码看,explainer 字段对应 ExplainerSpec(operator/apis/mlops/v1alpha1/model_types.go#L68-L78),它要求 type 与 modelRef/pipelineRef 二选一(对黑盒解释器必须设置其中之一)。这里 pipelineRef: sentiment-explain 表示解释器将把解释 Pipeline 当作黑盒模型来查询预测结果。控制器在同步模型时会将该字段映射为调度器侧的 scheduler.ExplainerSpec(见 operator/apis/mlops/v1alpha1/model_types.go#L208-L213)。

解释器存储目录中的 model-settings.json 进一步确认其运行时实现为 Alibi-Explain 的 MLServer 运行时(samples/examples/huggingface/explainer/model-settings.json):

{
    "name": "anchor-text",
    "implementation": "mlserver_alibi_explain.AlibiExplainRuntime",
    "parallel_workers": 0,
    "parameters": {
	"uri": "./data",
	"version": "v0.1.0"
    }
}

加载解释器模型:

seldon model load -f ../../models/hf-sentiment-explainer.yaml
seldon model status sentiment-explainer -w ModelAvailable | jq -M .

示例中这一步出现了 Error: Model wait status timeout——解释器模型首次加载可能较慢,超出 -w 的默认等待窗口。遇到这种情况无需惊慌,可以等待片刻后再次执行 seldon model status sentiment-explainer -w ModelAvailable 重试,直到状态变为可用。

组装 speech-to-sentiment 主 Pipeline

现在把语音、情感与解释三条分支汇入最终 Pipeline(samples/pipelines/speech-to-sentiment.yaml):

apiVersion: mlops.seldon.io/v1alpha1
kind: Pipeline
metadata:
  name: speech-to-sentiment
spec:
  steps:
    - name: whisper
    - name: sentiment
      inputs:
      - whisper
      tensorMap:
        whisper.outputs.output: args
    - name: sentiment-input-transform
      inputs:
      - whisper
    - name: sentiment-explainer
      inputs:
      - sentiment-input-transform
  output:
    steps:
    - sentiment
    - whisper

这条 Pipeline 的 DAG 结构为:

  • whisper 接收外部输入(base64 音频);
  • sentiment 依赖 whisper 的输出,并通过 tensorMap: whisper.outputs.output -> args 把 Whisper 的转录张量改名为情感模型期望的 args 输入;
  • sentiment-input-transform 也依赖 whisper,负责把转录文本转成解释器可理解的输入;
  • sentiment-explainer 依赖 sentiment-input-transform,异步产出情感结论的 Anchor 解释;
  • Pipeline 的同步输出为 sentiment 与 whisper 两个步骤的结果(即情感 JSON 与转录文本),而解释结果并不在同步输出中,需要单独异步检索。

部署与确认:

seldon pipeline load -f ../../pipelines/speech-to-sentiment.yaml
seldon pipeline status speech-to-sentiment -w PipelineReady | jq -M .

就绪状态输出显示该 Pipeline 同样生成了 version: 2 的应用版本,四个步骤展开后形成如上所述的依赖拓扑,modelsReady: true。

端到端测试:录音、推理与异步解释检索

录制音频

在 Notebook 中拉起音频录制控件(仅采集音频、不采集视频):

camera = CameraStream(constraints={'audio': True,'video':False})
recorder = AudioRecorder(stream=camera)
recorder

发起推理

对着麦克风说一句话,然后调用 infer:

infer("speech-to-sentiment.pipeline")

注意这里 seldon-model 请求头传入的是 speech-to-sentiment.pipeline——即"Pipeline 资源 + 名称"的形式。示例输出:

cihuqm8fh5ss73der5gg
b'{"text": " Cambridge is a great place."}'
b'{"label": "POSITIVE", "score": 0.9998548030853271}'

第一行是 x-request-id(已存入环境变量 REQUEST_ID),第二行是 Whisper 转录的文本("Cambridge is a great place."),第三行是情感模型的判断:POSITIVE,置信度 0.99985。infer 函数内部使用 base64.b64decode 对两个输出张量解码后打印,这就是 v2 协议下 BYTES 张量的常规消费方式。

异步检索解释结果

情感判断是同步返回的,而 Anchor 解释由 sentiment-explainer 步骤异步生成。示例用 seldon pipeline inspect 命令按请求 ID 轮询解释步骤的输出:

while True:
    base64Res = !seldon pipeline inspect speech-to-sentiment.sentiment-explainer.outputs --format json \
          --request-id ${REQUEST_ID}
    j = json.loads(base64Res[0])
    if j["topics"][0]["msgs"] is not None:
        expBase64 = j["topics"][0]["msgs"][0]["value"]["outputs"][0]["contents"]["bytesContents"][0]
        expRaw = base64.b64decode(expBase64)
        exp = json.loads(expRaw)
        print("")
        print("Explanation anchors:",exp["data"]["anchor"])
        break
    else:
        print(".",end='')
        time.sleep(1)

pipeline inspect 的目标格式为 speech-to-sentiment.sentiment-explainer.outputs,即"Pipeline.步骤.outputs",并通过 --request-id 过滤出本次请求对应的消息。返回结构中的 topics[].msgs[].value.outputs[].contents.bytesContents 是解释结果的 base64 编码载荷,解码后再经 JSON 解析即可得到 Anchor。示例输出:

......
Explanation anchors: ['great']

点号表示轮询等待,最终解释器给出 Anchor 关键词 'great'——即"great 这个词是支撑 POSITIVE 判断的关键证据"。这正是 anchor_text 解释器的典型产出:用一组保持预测不变的锚点词来解释分类决策。

从 CLI 实现看,pipeline inspect 底层由 Kafka 客户端完成:KafkaInspect/KafkaInspectTopic/KafkaInspectTopicMessage 结构定义了 topics<a href="https://link.gitcode.com/i/b7d27e440c9101a0843c2ff972fde574" target="_blank">].msgs[] 的返回模型([operator/pkg/cli/kafka.go#L50-L59),InspectStep 负责定位 Pipeline 步骤对应的 Kafka 主题并消费消息(operator/pkg/cli/kafka.go#L224-L249)。这也印证了 Pipeline 步骤之间的数据流在底层是通过 Kafka 主题传递的。

清理资源

实验完成后,按依赖顺序卸载 Pipeline 与模型:

seldon pipeline unload speech-to-sentiment
seldon pipeline unload sentiment-explain
seldon model unload whisper
seldon model unload sentiment
seldon model unload sentiment-explainer
seldon model unload sentiment-output-transform
seldon model unload sentiment-input-transform

机制小结:从示例看 Seldon Core 2 的 Pipeline 编排能力

结合仓库源码,本示例实际覆盖了 Seldon Core 2 Pipeline 编排的几项核心能力:

  • PipelineSpec 由 input/steps/output/dataflow 组成,并支持 allowCycles(允许环形依赖)与 maxStepRevisits(步骤最大重访次数)等高级选项(operator/apis/mlops/v1alpha1/pipeline_types.go#L54-L72);
  • PipelineStep 通过 inputs 声明上游依赖、通过 tensorMap 做张量重命名、通过 triggers/batch/joinWindowMs 控制触发与批处理(operator/apis/mlops/v1alpha1/pipeline_types.go#L86-L109)。本示例的 whisper.outputs.output -> args 就是 tensorMap 的典型用法;
  • Explainer 可以像普通步骤一样嵌入 Pipeline,并通过 pipelineRef 把解释对象指向另一条 Pipeline,从而支撑"多模型联合 + 复杂解释"的场景;
  • Pipeline 的同步输出与异步解释输出分离:功能结果通过 v2 数据平面同步返回,解释结果则通过 pipeline inspect --request-id 按请求 ID 异步检索。

整套示例的所有清单文件均可在仓库中找到:模型定义位于 samples/models(hf-whisper.yaml、hf-sentiment.yaml、hf-sentiment-input-transform.yaml、hf-sentiment-output-transform.yaml、hf-sentiment-explainer.yaml),Pipeline 定义位于 samples/pipelines(sentiment-explain.yaml、speech-to-sentiment.yaml),transform 运行时源码位于 samples/examples/huggingface。若需在 Notebook 中复现完整流程,可直接运行仓库中的 huggingface.ipynb。

登录后查看全文
seldon-core