Apache Beam RunInference API 示例管线完全指南:从 PyTorch 到 TensorRT 的多框架推理实战
Apache Beam RunInference API 示例管线完全指南:从 PyTorch 到 TensorRT 的多框架推理实战
Apache Beam 的 RunInference API 是一个统一的机器学习推理变换(transform),允许开发者在批处理和流处理管道中以声明式的方式加载模型、批量执行推理并输出预测结果。本指南以 sdks/python/apache_beam/examples/inference/README.md 为骨架,结合仓库中全部示例源码,系统讲解如何在本仓库的 Python SDK 环境中安装依赖、准备数据集与模型,并逐条运行图像分类、图像分割、目标检测、语言建模、MNIST 手写数字分类、情感分析、XGBoost 表格分类、流式窗口推理以及 Vertex AI 云端推理等 15 类示例管线。读完本文,你将掌握 RunInference API 的核心使用模式(KeyedModelHandler、ModelHandler 族、批处理与预处理/后处理挂接),并具备直接复制命令在本地或分布式环境跑通端到端推理的能力。
一、环境准备与框架依赖安装
1.1 安装最新版 apache-beam
本目录下的示例管线依赖 RunInference API 的近期开发特性,因此 README 明确要求安装最新(可能尚未发布)的 apache-beam。在仓库的 sdks/python 目录下执行可编辑安装,并带上 GCP 相关扩展:
pip install -e .[gcp]
说明:使用
-e(editable)模式安装,可以保证本地仓库的 Python 源码改动即时生效,适合从源码研究 RunInference 实现。若只在本地 Direct Runner 上运行,<a href="https://link.gitcode.com/i/226196317e51750a9148b6072d8a117c" target="_blank">gcp]扩展并非强制,但它能支撑 GCS 等文件系统的读写(示例中的FileSystems().open()依赖 Beam 的文件系统抽象,见 [pytorch_image_classification.py)。
1.2 各框架依赖一览
RunInference API 以 ModelHandler 的形式分别支持 PyTorch、TensorFlow、Hugging Face Transformers、TensorRT、ONNX、Scikit-learn 与 XGBoost。对应依赖如下:
| 框架 | 用途 | 安装命令(README 给定版本) |
|---|---|---|
| TensorFlow | TensorFlow 模型处理器示例 | pip install tensorflow==2.12.0 |
| PyTorch | PyTorch 模型处理器示例 | pip install torch==1.10.0 |
| torchvision | 使用预训练视觉模型(mobilenet_v2、maskrcnn 等) | pip install torchvision |
| transformers | 使用 Hugging Face 预训练模型 | pip install transformers |
| ONNX Runtime | ONNX 加速推理 | pip install onnxruntime==1.13.1 |
| tf2onnx | TensorFlow 模型转 ONNX | pip install tf2onnx==1.13.0 |
| skl2onnx | sklearn 模型转 ONNX | pip install skl2onnx |
- Transformers 依赖:Hugging Face 模型处理器示例单独要求
pip install transformers==4.30.0,且 PyTorch / TensorFlow 后端依赖需按需单独安装(pip install tensorflow==2.12.0、pip install torch==1.10.0)。 - TensorRT 依赖:面向 NVIDIA GPU 的高性能推理。建议 TensorRT >= 8.0.1,需同时安装 Python 绑定(
python3-libnvinfer与python3-libnvinfer-dev包)。也可基于 NGC 镜像nvcr.io/nvidia/tensorrt:22.04-py3作为基础镜像构建自定义 Beam 容器。需要注意:TensorRT 引擎与构建环境强绑定——不仅要求 TensorRT 版本一致,还要求使用同一块 GPU 型号。 - ONNX 依赖:若模型已是 ONNX 格式,仅
onnxruntime==1.13.1即足够;库本身还支持从 PyTorch 模型转换,如需转换 TensorFlow 模型装tf2onnx,转换 sklearn 模型装skl2onnx。 - Scikit-learn 版本对齐:sklearn_examples_requirements.txt 明确指出 sklearn 不保证跨版本模型兼容性,约束必须与训练模型时的版本一致:
python_version < '3.11'时用scikit-learn==1.0.2,python_version >= '3.11'时用scikit-learn==1.2.2(对应 Beam 测试保存模型所用的版本)。
分布式运行(如 Dataflow)时,PyTorch 等第三方依赖需按 Beam 的 PyPI 依赖机制打包,不能仅靠本地 pip install。
二、图像分类:PyTorch + MobileNetV2
pytorch_image_classification.py 实现了一个使用 mobilenet_v2 架构的图像分类 RunInference 管线:读取图片 → 基础预处理 → 送入 PyTorch RunInference → 将预测写入文本文件。
2.1 数据集与模型准备
-
创建
IMAGES_DIR目录并放入图片(若第 2 步的清单文件使用绝对路径,则此目录可省略)。经典数据源是 ImageNet。 -
创建
IMAGE_FILE_NAMES.txt,逐行写入图片的绝对路径。路径 URI 可以是本地文件系统、AWS S3 或 GCP Cloud Storage,例如:/absolute/path/to/image1.jpg /absolute/path/to/image2.jpg -
从 PyTorch 预训练模型库下载 mobilenet_v2(依赖 torchvision),在 Python shell 中执行:
import torch from torchvision.models import mobilenet_v2 model = mobilenet_v2(pretrained=True) torch.save(model.state_dict(), 'mobilenet_v2.pth')
2.2 运行管线
python -m apache_beam.examples.inference.pytorch_image_classification \
--input IMAGE_FILE_NAMES \
--images_dir IMAGES_DIR \
--output OUTPUT \
--model_state_dict_path MODEL_STATE_DICT
其中 images_dir 仅在清单为相对路径时需要。按 README 推荐命名时:
python -m apache_beam.examples.inference.pytorch_image_classification \
--input IMAGE_FILE_NAMES.txt \
--output predictions.csv \
--model_state_dict_path mobilenet_v2.pth
输出 predictions.csv 形如:
/absolute/path/to/image1.jpg;1
/absolute/path/to/image2.jpg;333
每个图片路径对应一个 0-999 范围内的 ImageNet 类别 ID,即置信度最高的类别。
2.3 源码级的实现细节
从 pytorch_image_classification.py 可以看到该管线的核心调用链:
- 通过
FileSystems().open()读取图片(支持 S3/GCS 等任意 Beam 文件系统),再经Image.open(...).convert('RGB')加载。 preprocess_image使用 ImageNet 标准归一化参数(mean=[0.485, 0.456, 0.406]、std=[0.229, 0.224, 0.225]),配合Resize((224, 224))与ToTensor()。- 由于输入带 key(文件名),使用
KeyedModelHandler(PytorchModelHandlerTensor(...))包装,并设置min_batch_size=10、max_batch_size=100让 RunInference 自动批量推理。 - 预处理(
preprocess)与后处理(postprocess,对输出 logits 取torch.argmax)通过.with_preprocess_fn(...).with_postprocess_fn(...)挂接到 ModelHandler 上,使整个 PTransform 保持ReadFromText → RunInference → WriteToText的简洁结构。
三、图像分割:PyTorch + Mask R-CNN
pytorch_image_segmentation.py 使用 maskrcnn_resnet50_fpn 架构执行实例分割。
3.1 数据集与模型准备
-
创建
IMAGES_DIR存放图片(推荐 COCO 数据集)。 -
创建
IMAGE_FILE_NAMES.txt写入图片绝对路径(支持本地 / S3 / GCS URI)。 -
下载 maskrcnn_resnet50_fpn 预训练权重:
import torch from torchvision.models.detection import maskrcnn_resnet50_fpn model = maskrcnn_resnet50_fpn(pretrained=True) torch.save(model.state_dict(), 'maskrcnn_resnet50_fpn.pth') -
记下
OUTPUT输出文件路径。
3.2 运行管线
python -m apache_beam.examples.inference.pytorch_image_segmentation \
--input IMAGE_FILE_NAMES \
--images_dir IMAGES_DIR \
--output OUTPUT \
--model_state_dict_path MODEL_STATE_DICT
示例:
python -m apache_beam.examples.inference.pytorch_image_segmentation \
--input IMAGE_FILE_NAMES.txt \
--output predictions.csv \
--model_state_dict_path maskrcnn_resnet50_fpn.pth
输出以 ; 分隔,第一项为文件名,第二项为预测实例类别列表:
/absolute/path/to/image1.jpg;['parking meter', 'bottle', 'person', 'traffic light', 'traffic light', 'traffic light']
/absolute/path/to/image2.jpg;['bottle', 'person', 'person']
3.3 源码级细节
pytorch_image_segmentation.py 中维护了一个完整的 COCO 91 类索引表 COCO_INSTANCE_CLASSES,并用 CLASS_ID_TO_NAME = dict(enumerate(...)) 做类别 ID 到名称的映射。预处理仅做 Resize + ToTensor(分割模型不需要 ImageNet 归一化)。与分类示例不同,此处 PostProcessor 是一个独立 beam.DoFn:从 PredictionResult.inference['labels'] 取每个实例的类别标签并翻译成类别名。管线结构为 ReadFromText → FilterEmptyLines → ReadImageData → PreprocessImages → RunInference(KeyedModelHandler(...)) → PostProcessor → WriteToText,其中 images_dir 参数在此示例为必填(未设置默认值)。
四、Per-Key 图像分割:一条管线加载多个模型
pytorch_model_per_key_image_segmentation.py 演示了 RunInference 的 Per-Key 多模型能力:基于 maskrcnn_resnet50_fpn 与 maskrcnn_resnet50_fpn_v2 两个模型,对同一批图片同时做分割并对比两版结果。
4.1 数据集与模型准备
可复用上一节的步骤。要点:
-
准备
IMAGES_DIR与IMAGE_FILE_NAMES.txt(推荐 COCO)。 -
同时下载两个版本的权重:
import torch from torchvision.models.detection import maskrcnn_resnet50_fpn from torchvision.models.detection import maskrcnn_resnet50_fpn_v2 model = maskrcnn_resnet50_fpn(pretrained=True) torch.save(model.state_dict(), 'maskrcnn_resnet50_fpn.pth') model = maskrcnn_resnet50_fpn_v2(pretrained=True) torch.save(model.state_dict(), 'maskrcnn_resnet50_fpn_v2.pth') -
记下
OUTPUT路径。
4.2 运行管线
python -m apache_beam.examples.inference.pytorch_model_per_key_image_segmentation \
--input IMAGE_FILE_NAMES \
--images_dir IMAGES_DIR \
--output OUTPUT \
--model_state_dict_paths MODEL_STATE_DICT1,MODEL_STATE_DICT2
示例(两个权重以逗号分隔传入):
python -m apache_beam.examples.inference.pytorch_model_per_key_image_segmentation \
--input IMAGE_FILE_NAMES.txt \
--output predictions.csv \
--model_state_dict_path 'maskrcnn_resnet50_fpn.pth,maskrcnn_resnet50_fpn_v2.pth'
输出中每张图片同时带 v1 predictions 与 v2 predictions 两组结果:
/Users/dannymccormick/Downloads/images/datasets_coco_raw-data_val2017_000000000139.jpg --- v1 predictions: ['chair', 'tv','potted plant'] --- v2 predictions: ['motorcycle', 'frisbee', 'couch']
4.3 源码级细节:KeyModelMapping
pytorch_model_per_key_image_segmentation.py 是理解 RunInference 多模型路由的最佳示例:
- 源码强制要求恰好传入 2 个 state_dict(
len(state_dicts) != 2时抛AssertionError)。 - 构造两个
PytorchModelHandlerTensor实例,随后用KeyedModelHandler([KeyModelMapping(['v1'], mh1), KeyModelMapping(['v2'], mh2)])建立 key → ModelHandler 的路由表(多个 key 也可以指向同一个 handler)。 KeyExamplesForEachModelTypeDoFn 把每条数据复制两份并分别打上v1、v2两个 key,RunInference 依据 key 选择对应模型。- 结果侧通过
CoGroupByKey将(example → 预测)与(example → 原文件名)按 example 归并(先把 Tensor 转成 list 以规避自定义 coder),最终由FormatResults拼装成上面展示的行。源码注释还指出:如果只关心用的是哪个模型,可直接从PredictionResult中取得。
五、目标检测:TensorRT + SSD MobileNet V2
tensorrt_object_detection.py 使用 TensorFlow Object Detection 的 SSD MobileNet v2 320x320 架构(预先转换为 TensorRT 引擎),展示 GPU 加速的目标检测推理。
5.1 数据与引擎准备
-
图片:放入
IMAGES_DIR(推荐 COCO 数据集,验证集 zip 可直接获取)。 -
必需:
IMAGE_FILE_NAMES:逐行写入图片绝对路径(支持本地 / S3 / GCS):/absolute/path/to/000000000139.jpg /absolute/path/to/000000289594.jpg -
必需:
TRT_ENGINE:预先构建好的 SSD MobileNet v2 320x320 TensorRT 引擎。需要按 TensorRT 官方 TensorFlow Object Detection API 示例流程,先把 SSD 模型转成 ONNX(此步保持 batch size 为 1),再构建 TensorRT 引擎,将结果文件作为engine_path传入。务必保证引擎构建环境与推理环境一致(TensorRT 版本与 GPU 型号),因为序列化引擎与硬件强相关。 -
必需:
OUTPUT:预测输出文件。 -
可选:
IMAGES_DIR:仅当清单为相对路径时需要。
5.2 运行管线
python -m apache_beam.examples.inference.tensorrt_object_detection \
--input IMAGE_FILE_NAMES \
--images_dir IMAGES_DIR \
--output OUTPUT \
--engine_path TRT_ENGINE
示例:
python -m apache_beam.examples.inference.tensorrt_object_detection \
--input image_file_names.txt \
--output predictions.csv \
--engine_path ssd_mobilenet_v2_320x320_coco17_tpu-8.trt
输出以 ; 分隔:第一项为文件名,第二项为检测结果字典列表,每个字典包含边界框坐标(ymin、xmin、ymax、xmax)、置信度 score 与类别 class:
/absolute/path/to/000000000139.jpg;[{'ymin': '217.31875205039978' 'xmin': '295.93122482299805' 'ymax': '315.90323209762573' 'xmax': '357.8959655761719' 'score': '0.72342616' 'class': 'chair'} ...]
六、语言建模:PyTorch + BERT 掩码预测
pytorch_language_modeling.py 使用 Hugging Face 的 BertForMaskedLM 执行掩码语言建模:把句子最后一个词替换成 [MASK],让模型预测被掩码的词。
6.1 数据集与模型准备
-
下载 BertForMaskedLM 预训练权重(需先安装 transformers):
import torch from transformers import BertForMaskedLM model = BertForMaskedLM.from_pretrained('bert-base-uncased', return_dict=True) torch.save(model.state_dict(), 'BertForMaskedLM.pth') -
(可选)创建
SENTENCES.txt,内容示例:The capital of France is Paris . He looked up and saw the sun and stars .
6.2 运行管线
python -m apache_beam.examples.inference.pytorch_language_modeling \
--input SENTENCES \
--output OUTPUT \
--model_state_dict_path MODEL_STATE_DICT
input 参数可选——不传则使用内置的 10 条示例句子。按推荐命名运行:
python -m apache_beam.examples.inference.pytorch_language_modeling \
--input SENTENCES.txt \
--output predictions.csv \
--model_state_dict_path BertForMaskedLM.pth
或使用默认句子:
python -m apache_beam.examples.inference.pytorch_language_modeling \
--output predictions.csv \
--model_state_dict_path BertForMaskedLM.pth
输出以 ; 分隔:第一项为原始句子,第二项为模型对掩码词的预测:
The capital of France is Paris .;paris
He looked up and saw the sun and stars .;moon
6.3 源码级细节:单样本批处理
pytorch_language_modeling.py 中有两个值得注意的实现点:
add_mask_to_last_word将句子倒数第二个词替换为[MASK](保留最后一个标点)。- 由于
BertTokenizer.encode_plus生成的 token 序列长度不一,torch.stack()无法对变长张量批量拼接,示例因此定义一个PytorchNoBatchModelHandler(PytorchModelHandlerKeyedTensor)子类,覆写batch_elements_kwargs()返回{'max_batch_size': 1},将每批限制为 1 个样本(源码注释引用 Beam issue 21863,待可选 batching 特性落地后移除)。 PostProcessor从PredictionResult.inference['logits']定位mask_token_id位置,取 logits 的 argmax,再用 tokenizerdecode出预测词。- 还提供
--bert_tokenizer(默认bert-base-uncased)与--large_model(模型过大、多副本加载有内存压力时开启)参数。
七、MNIST 手写数字分类:Scikit-learn
sklearn_mnist_classification.py 使用 Scikit-learn 模型对 MNIST 手写数字做分类:读取像素行 → 预处理 → 送入 sklearn RunInference → 写出预测。
7.1 数据集与模型准备
-
创建
INPUT.csv:每行为逗号分隔整数,首个元素为真实标签,其余为像素值,不要表头:1,0,0,0... 0,0,0,0... 1,0,0,0... 4,0,0,0... -
创建
MODEL_PATH指向训练好的 sklearn 模型的 pickle 文件(序列化方式参见 sklearn 模型持久化文档)。 -
按 sklearn_examples_requirements.txt 将 sklearn 版本对齐到训练所用版本(sklearn 不保证跨版本模型兼容)。
7.2 运行管线
python -m apache_beam.examples.inference.sklearn_mnist_classification.py \
--input INPUT \
--output OUTPUT \
--model_path MODEL_PATH
示例:
python -m apache_beam.examples.inference.sklearn_mnist_classification.py \
--input INPUT.csv \
--output predictions.txt \
--model_path mnist_model_svm.pickle
输出以 , 分隔:第一项为真实标签,第二项为预测标签:
1,1
4,9
7,1
0,0
7.3 源码级细节
sklearn_mnist_classification.py 中 process_input 把一行 CSV 拆成 (label, pixels) 二元组,PostProcessor 将 PredictionResult.inference 与真实标签拼成 '{},{}' 字符串。ModelHandler 使用 SklearnModelHandlerNumpy(其 ModelFileType 支持 pickle 与 joblib 两种模型文件类型),并用 KeyedModelHandler 包装以保留标签作为 key。
八、日本房价回归:多模型 sklearn 管线
sklearn_japanese_housing_regression.py 基于日本房地产交易价格数据进行房价回归。该示例使用不止一个模型:由于样本并非所有特征都有值,管线会根据可用数据选择不同模型(例如缺少到最近车站距离的样本会使用不依赖该特征的模型)。
- 数据:取自 Kaggle 上的日本房地产交易价格数据集。
- 模型:预构建的 sklearn pipeline 托管在 GCS 公共路径
gs://apache-beam-ml/models/japanese_housing/(README 中以https://storage.cloud.google.com/apache-beam-ml/models/japanese_housing/形式给出)。
运行命令:
python -m apache_beam.examples.inference.sklearn_japanese_housing_regression.py \
--input_file INPUT \
--output OUTPUT \
--model_path MODEL_PATH
示例:
python -m apache_beam.examples.inference.sklearn_japanese_housing_regression.py \
--input_file housing_examples.csv \
--output predictions.txt \
--model_path https://storage.cloud.google.com/apache-beam-ml/models/japanese_housing/
输出为真实价格与预测价格对比:
True Price 40000000.0, Predicted Price 34645912.039208
True Price 34000000.0, Predicted Price 28648634.135857
True Price 31000000.0, Predicted Price 25654277.256461
九、情感分类:ONNX 版 RoBERTa
onnx_sentiment_classification.py 使用 ONNX 格式的 RoBERTa 模型对影评做二分类情感分析(0 为负面,1 为正面)。
9.1 数据与模型准备
- 模型:需要已训练好的 ONNX 格式模型。示例使用 Seldon 的 movie sentiment RoBERTa 微调模型(由 PyTorch 版转出的 ONNX 版本)。
- 输入数据:可以自己按行编写影评,也可使用公开的 IMDB 影评数据。
- 输出:文本文件,每行是原始影评追加
;与二值标签。
9.2 运行管线
python -m apache_beam.examples.inference.onnx_sentiment_classification.py \
--input_file [input file path] \
--output [output file path] \
--model_uri [path to onnx model]
输出示例:
A comedy-drama of nearly epic proportions rooted in a sincere performance by the title character undergoing midlife crisis .;1
9.3 源码级细节
onnx_sentiment_classification.py 使用 RobertaTokenizer 对句子 encode(add_special_tokens=True) 后转成 numpy 数组;与 BERT 示例相同,为规避变长序列 torch.stack() 的限制,定义了 OnnxNoBatchModelHandler(OnnxModelHandlerNumpy) 子类将 max_batch_size 限制为 1。后处理对推理输出取 np.argmax(axis=0) 得到情感类别。
十、MNIST 分类:TensorFlow 两个变体
10.1 SavedModel 方式
tensorflow_mnist_classification.py 将输入形状转换为 28x28 后送入训练好的 TensorFlow 模型。
数据准备:创建 INPUT.csv(格式同 sklearn 示例,首个元素为标签,其余为像素值,无表头;README 给出可直接使用的测试输入 gs://apache-beam-ml/testing/inputs/it_mnist_data.csv),并把训练好的模型保存到 MODEL_DIR。
运行:
python -m apache_beam.examples.inference.tensorflow_mnist_classification.py \
--input INPUT \
--output OUTPUT \
--model_path MODEL_DIR
输出(真实标签, 预测标签):
1,1
4,4
0,0
7,7
3,3
5,5
10.2 SavedModel 权重方式(ModelType.SAVED_WEIGHTS)
tensorflow_mnist_with_weights.py 演示了从 SavedModel 权重加载模型:向 TFModelHandler 传入一个创建模型的函数,并将模型类型设为 ModelType.SAVED_WEIGHTS,把 model.save_weights(path) 保存的权重目录路径传给 model_path 参数。
数据与模型准备同上(权重保存到 SAVED_WEIGHTS_DIR),运行命令与 10.1 相同,仅 --model_path 指向权重目录:
python -m apache_beam.examples.inference.tensorflow_mnist_with_weights.py \
--input INPUT.csv \
--output predictions.txt \
--model_path SAVED_WEIGHTS_DIR
十一、图像分类:TensorFlow Hub 的 MobileNetV2
tensorflow_imagenet_segmentation.py 使用来自 TensorFlow Hub 的 mobilenet_v2 分类模型(tf2-preview 版本)执行 ImageNet 图像分类。
11.1 数据与模型准备
-
创建
IMAGE_DIR存放图片(可使用 TensorFlow 官方示例图片目录中的图片,如grace_hopper.jpg)。 -
创建
IMAGE_FILE_NAMES.txt,写入图片文件名(相对image_dir):grace_hopper.jpg -
指定 TensorFlow
MODEL_PATH(默认即 tfhub 上的 mobilenet_v2 分类模型)。 -
记下
OUTPUT路径。 -
安装 TensorFlow Hub:
pip install tensorflow_hub。
11.2 运行管线
python -m apache_beam.examples.inference.tensorflow_imagenet_segmentation \
--input IMAGE_FILE_NAMES \
--image_dir IMAGES_DIR \
--output OUTPUT \
--model_path MODEL_PATH
示例(注意 image_dir 与 model_path 均可直接使用远程 URI):
python -m apache_beam.examples.inference.tensorflow_imagenet_segmentation \
--input IMAGE_FILE_NAMES.txt \
--image_dir "https://storage.googleapis.com/download.tensorflow.org/example_images/" \
--output predictions.txt \
--model_path "https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4"
输出每行为一个预测标签,例如 background。
十二、Iris 表格分类:XGBoost
xgboost_iris_classification.py 使用 XGBoost 对鸢尾花(Iris)数据集做三分类。特征是花萼长度、花萼宽度、花瓣长度、花瓣宽度,类别标签为 0、1、2。
12.1 训练一个简单分类器
需要先安装 sklearn。数据通过 sklearn 加载,仓库内置的 _train_model 函数训练并导出模型状态文件,供 XGBoostModelHandler 加载:
import xgboost
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
def _train_model(model_state_output_path: str = '/tmp/model.json', seed=999):
"""Function to train an XGBoost Classifier using the sklearn Iris dataset"""
dataset = load_iris()
x_train, _, y_train, _ = train_test_split(
dataset['data'], dataset['target'], test_size=.2, random_state=seed)
booster = xgboost.XGBClassifier(
n_estimators=2, max_depth=2, learning_rate=1, objective='binary:logistic')
booster.fit(x_train, y_train)
booster.save_model(model_state_output_path)
return booster
12.2 运行管线
python -m apache_beam.examples.inference.xgboost_iris_classification.py \
--input_type INPUT_TYPE \
--output OUTPUT_FILE \
--model_state MODEL_STATE_JSON \
[--no_split|--split]
示例:
python -m apache_beam.examples.inference.xgboost_iris_classification.py \
--input_type numpy \
--output predictions.txt \
--model_state model_state.json \
--split
输出每行包含批号与标签列表。每个批次一个样本时:
0,[1]
1,[2]
2,[1]
3,[0]
全部样本一个批次时:
0,[1 1 1 0 0 0 0 1 2 0 0 2 0 2 1 2 2 2 2 0 0 0 0 2 2 0 2 2 2 1]
12.3 源码级细节:四种数据容器
xgboost_iris_classification.py 用一个映射表把 --input_type 的四种取值绑定到对应的输入容器与 ModelHandler:
| input_type | 数据容器 | ModelHandler |
|---|---|---|
numpy |
numpy.array |
XGBoostModelHandlerNumpy |
pandas |
pandas.DataFrame |
XGBoostModelHandlerPandas |
scipy |
scipy.sparse.csr_matrix |
XGBoostModelHandlerSciPy |
datatable |
datatable.Frame |
XGBoostModelHandlerDatatable |
--split 与 --no_split 是互斥必选参数,控制测试集是逐样本分批((index, sample.reshape(1, -1)))还是整批输入。另有 --large_model 开关用于大模型内存压力场景。测试集本身由 load_sklearn_iris_test_data 从 sklearn Iris 数据按 test_size=.2、random_state=999 划分。
十三、流式窗口推理:牛奶质量预测(XGBoost + Windowing)
milk_quality_prediction_windowing.py 是 RunInference 与**窗口(windowing)**结合的最佳流式示例:根据 pH、温度、口感、气味、脂肪、浊度和颜色七个测量指标,用 XGBoost 将牛奶质量分为 bad、medium、good 三档。模型基于 Kaggle 的 Milk Quality Prediction 数据集训练。
13.1 数据加载与预处理
preprocess_data 函数从 CSV 加载 Kaggle 数据集,拆分为训练集、训练标签与测试集:把 Grade 列映射为 0/1/2,train_test_split(test_size=0.60, random_state=99) 划分,分别落盘。在典型机器学习流程中训练集用于训练模型,测试集用于评估(如召回率、精确率);此处测试集数据被用来模拟流式输入以展示窗口能力。
13.2 训练 XGBoost 分类器
train_model 函数读取训练样本与标签,用 xgboost.XGBClassifier(max_depth=3) 拟合后将模型以 JSON 格式保存,供 XGBoostModelHandlerPandas 加载推理:
samples = pandas.read_csv(samples_path)
labels = pandas.read_csv(labels_path)
xgb = xgboost.XGBClassifier(max_depth=3)
xgb.fit(samples, labels)
xgb.save_model(model_state_output_path)
13.3 运行管线
python -m apache_beam.examples.inference.milk_quality_prediction_windowing.py \
--dataset <DATASET> \
--pipeline_input_data <INPUT_DATA> \
--training_set <TRAINING_SET> \
--labels <LABELS> \
--model_state <MODEL_STATE>
参数含义:
<DATASET>:Kaggle 牛奶质量数据集的 CSV 路径;<INPUT_DATA>:保存流式管线输入(测试集)的文件路径;<TRAINING_SET>:训练集 CSV 存储路径;<LABELS>:训练标签 CSV 存储路径;<MODEL_STATE>:训练后模型的 JSON 文件路径。
其中 <INPUT_DATA>、<TRAINING_SET>、<LABELS> 会在管线执行前由脚本从 <DATASET> 自动解析生成。
13.4 窗口语义与源码实现
pytorch_language_modeling 的兄弟示例 milk_quality_prediction_windowing.py 中,用 TestStream 模拟真实流式数据:每分钟到达一条新测量记录,beam.WindowInto(window.SlidingWindows(30, 5)) 表示30 分钟窗口、每 5 分钟滑动一次。窗口内 RunInference 对每条测量推理,再由自定义 AggregateMilkQualityResults(beam.CombineFn) 聚合窗口内 bad / medium / high 三种质量的数量(MilkQualityAggregation NamedTuple 作为累加器)。每个窗口的输出形如:
MilkQualityAggregation(bad_quality_measurements=10, medium_quality_measurements=13, high_quality_measurements=6)
MilkQualityAggregation(bad_quality_measurements=9, medium_quality_measurements=11, high_quality_measurements=4)
MilkQualityAggregation(bad_quality_measurements=8, medium_quality_measurements=7, high_quality_measurements=4)
十四、Hugging Face Hub 语言建模
huggingface_language_modeling.py 使用 AutoModelForMaskedLM 从 Hugging Face Hub 直接加载 checkpoint 做掩码语言建模(将句子最后一个词替换为 <mask>)。
14.1 模型与数据准备
-
选择一个 Hugging Face Hub 上的 checkpoint(README 示例为
stevhliu/my_awesome_eli5_mlm_model)。 -
(可选)创建
SENTENCES.txt:The capital of France is Paris . He looked up and saw the sun and stars .
14.2 运行管线
python -m apache_beam.examples.inference.huggingface_language_modeling \
--input SENTENCES \
--output OUTPUT \
--model_name REPOSITORY_ID
input 可选。示例:
python -m apache_beam.examples.inference.huggingface_language_modeling \
--input SENTENCES.txt \
--output predictions.csv \
--model_name "stevhliu/my_awesome_eli5_mlm_model"
输出以 ; 分隔(原始句子; 预测词),与 BERT 示例同构:
The capital of France is Paris .;paris
He looked up and saw the sun and stars .;moon
14.3 源码细节
huggingface_language_modeling.py 与 BERT 示例几乎同构,差异在于:掩码 token 为 <mask>,tokenizer 用 AutoTokenizer,模型用 AutoModelForMaskedLM,ModelHandler 换成 HuggingFaceModelHandlerKeyedTensor。PostProcessor 通过 torch.where(inputs["input_ids"] == self.tokenizer.mask_token_id) 定位掩码位置并对 logits 取 argmax 解码。
十五、云端推理:Vertex AI
15.1 图片分类(Vertex AI 托管模型)
vertex_ai_image_classification.py 调用托管在 Vertex AI 上的图片分类模型(基于官方 image-recognition-custom 教程训练)。管线读取图片 URL,预处理为浮点列表,经 Vertex AI RunInference 后写出预测。
准备:按 Vertex AI 教程训练并部署模型;创建 IMAGE_FILE_NAMES.txt(绝对路径,支持 S3/GCS)。
运行:
python -m apache_beam.examples.inference.vertex_ai_image_classification \
--endpoint_id '<endpoint of trained model>' \
--endpoint_project '<gcp project>' \
--endpoint_region '<gcp region>' \
--input 'path/to/IMAGE_FILE_NAMES.txt' \
--output 'path/to/output/file.txt'
输出每行为图片路径、花卉类别与置信度:
path/to/my/image: tulips (90)
path/to/my/image2: dandelions (78)
15.2 文本分类(Vertex AI LLM)
vertex_ai_llm_text_classification.py 调用 Vertex AI 上的调优后 LLM(text-bison 模型,按官方模型调优作业教程得到)做文本分类。
运行(无需输入/输出参数,模型在 Vertex AI 端):
python -m apache_beam.examples.inference.vertex_ai_llm_text_classification \
--endpoint_id '<endpoint of trained LLM>' \
--endpoint_project '<gcp project>' \
--endpoint_region '<gcp region>'
输出为 (example, PredictionResult, model_id) 元组,PredictionResult 的 inference 字段携带模型返回内容、citation 元数据与安全属性:
('What is 5+2?', PredictionResult(example={'prompt': 'What is 5+2?'}, inference={'content': '7', 'citationMetadata': {'citations': []}, 'safetyAttributes': {'blocked': False, 'scores': [], 'categories': []}}, model_id='6795590989097467904'))
十六、更多进阶示例与可复用模式
除 README 主体示例外,该目录还提供了可进一步探索的进阶实现(目录清单见 sdks/python/apache_beam/examples/inference):
- run_inference_side_inputs.py 与 pytorch_image_classification_with_side_inputs.py:演示将副输入(side inputs)注入 RunInference 管线的用法;
- huggingface_question_answering.py:Hugging Face 问答任务;
- tensorrt_text_classification.py:TensorRT 文本分类;
- tfx_bsl:基于 TFX-BSL 的推理(含集成测试 tfx_bsl_inference_it_test.py);
- online_clustering、anomaly_detection、large_language_modeling:流式在线聚类、异常检测与大语言模型场景的完整工程化目录(pipeline/options/transformations 分层);
- runinference_metrics:RunInference 内置指标的采集配置;
- multi_language_inference:跨语言(Java/Python)推理示例,展示 RunInference 的跨语言扩展能力。
此外,本仓库的 learning/notebooks/beam-ml 目录提供了一批与 RunInference 配套的交互式 Notebook(如 run_inference_huggingface、run_inference_pytorch、run_inference_sklearn、run_inference_windowing、per_key_models 等),适合以可视化方式进一步学习本指南中的每种模型处理器与窗口场景。
十七、小结:RunInference 示例的通用模式
纵观本目录全部示例,可以提炼出 RunInference API 的四个固定套路:
- 数据入口:
beam.io.ReadFromText读清单文件(或beam.Create直接构造),配合filter_empty_lines清理空行;图片类任务统一经FileSystems().open()+ PIL 读取。 - 预处理:通过
beam.Map/beam.MapTuple完成(图像 resize + normalize、文本 tokenize),或直接通过 ModelHandler 的.with_preprocess_fn()挂接;带 key 的数据一律用KeyedModelHandler包装以保留业务键。 - 推理:
RunInference(model_handler)一行接入,模型加载、批处理(min_batch_size/max_batch_size)、设备选择(CPU/GPU)均由 ModelHandler 完成;变长文本场景用max_batch_size=1规避 stack 限制。 - 后处理与写出:
PredictionResult的inference/example字段承载模型输出与原始输入,用独立beam.DoFn解析为业务格式(argmax 类别、COCO 类别名、掩码词、回归值等),最终WriteToText落盘。
无论底层框架是 PyTorch、TensorFlow、Hugging Face、ONNX、TensorRT、sklearn、XGBoost 还是云上 Vertex AI,这四条套路都保持一致,这也是 RunInference API 统一批/流推理模型的核心理念。