机器学习与深度学习 / 系统课时

构建批量推理服务

构建批量推理服务

本课实现一个可直接启动的 FastAPI 推理服务:模型只初始化一次,请求先经过结构校验,再由队列按数量或等待时间合批执行,并为过载、推理失败和正常结果提供明确响应。

学习目标

  • 在应用生命周期内完成模型初始化与资源释放
  • 用队列和短等待窗口合并并发请求
  • 设计请求校验、错误状态码和稳定响应格式

设计最小服务链路

单个 HTTP 请求不应直接各自调用一次模型,否则并发上升后会产生大量小批次。更稳妥的链路是“校验请求、进入队列、合批推理、拆分结果、完成各自 Future”,并用最大批量与最长等待时间共同限制延迟。

批量推理服务时序

实现模型与批处理引擎

下面的单文件示例使用固定权重,便于得到可核对的响应。真实项目可在 lifespan 中改为加载 TorchScript、ONNX Runtime Session 或权重文件,但不要在每次请求中重复加载。

python
from __future__ import annotations

import asyncio
from contextlib import asynccontextmanager, suppress
from dataclasses import dataclass
from uuid import uuid4

import torch
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel, ConfigDict, Field
from torch import nn

FEATURE_SIZE = 4
MAX_BATCH_SIZE = 8
MAX_WAIT_MS = 20
QUEUE_CAPACITY = 1024

class PredictRequest(BaseModel):
    request_id: str = Field(default_factory=lambda: str(uuid4()), alias="requestId")
    features: list[float] = Field(min_length=FEATURE_SIZE, max_length=FEATURE_SIZE)
    model_config = ConfigDict(populate_by_name=True)

class PredictResponse(BaseModel):
    request_id: str = Field(alias="requestId")
    predicted_class: int = Field(alias="predictedClass")
    scores: list[float]
    model_config = ConfigDict(populate_by_name=True)

class TinyClassifier(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.linear = nn.Linear(FEATURE_SIZE, 3)
        with torch.no_grad():
            self.linear.weight.copy_(
                torch.tensor(
                    [
                        [1.0, 0.0, 0.0, 0.0],
                        [0.0, 1.0, 0.0, 0.0],
                        [0.0, 0.0, 1.0, 0.0],
                    ]
                )
            )
            self.linear.bias.zero_()

    def forward(self, features: torch.Tensor) -> torch.Tensor:
        return self.linear(features)

class ServiceBusyError(RuntimeError):
    pass

@dataclass
class PendingItem:
    request_id: str
    features: list[float]
    future: asyncio.Future[PredictResponse]

class BatchInferenceEngine:
    def __init__(self, model: nn.Module) -> None:
        self.model = model.eval()
        self.queue: asyncio.Queue[PendingItem] = asyncio.Queue(QUEUE_CAPACITY)
        self.worker: asyncio.Task[None] | None = None

    async def start(self) -> None:
        self.worker = asyncio.create_task(self._worker_loop())

    async def close(self) -> None:
        if self.worker is not None:
            self.worker.cancel()
            with suppress(asyncio.CancelledError):
                await self.worker

    async def predict(
        self,
        request_id: str,
        features: list[float],
    ) -> PredictResponse:
        if self.queue.full():
            raise ServiceBusyError("request queue is full")

        future = asyncio.get_running_loop().create_future()
        await self.queue.put(PendingItem(request_id, features, future))
        return await future

    async def _worker_loop(self) -> None:
        while True:
            first = await self.queue.get()
            batch = [first]
            deadline = asyncio.get_running_loop().time() + MAX_WAIT_MS / 1000

            while len(batch) < MAX_BATCH_SIZE:
                remaining = deadline - asyncio.get_running_loop().time()
                if remaining <= 0:
                    break
                try:
                    batch.append(
                        await asyncio.wait_for(self.queue.get(), timeout=remaining)
                    )
                except asyncio.TimeoutError:
                    break

            self._run_batch(batch)

    def _run_batch(self, batch: list[PendingItem]) -> None:
        try:
            tensor = torch.tensor(
                [item.features for item in batch],
                dtype=torch.float32,
            )
            with torch.inference_mode():
                probabilities = torch.softmax(self.model(tensor), dim=1)

            for item, row in zip(batch, probabilities):
                response = PredictResponse(
                    requestId=item.request_id,
                    predictedClass=int(torch.argmax(row).item()),
                    scores=[round(float(value), 6) for value in row],
                )
                if not item.future.done():
                    item.future.set_result(response)
        except Exception as exc:
            for item in batch:
                if not item.future.done():
                    item.future.set_exception(exc)
        finally:
            for _ in batch:
                self.queue.task_done()

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 模型和工作协程只在服务启动时创建一次。
    engine = BatchInferenceEngine(TinyClassifier())
    await engine.start()
    app.state.engine = engine
    yield
    await engine.close()

app = FastAPI(lifespan=lifespan)

@app.get("/health")
async def health() -> dict[str, str]:
    return {"status": "ok"}

@app.post(
    "/predict",
    response_model=PredictResponse,
    response_model_by_alias=True,
)
async def predict(
    payload: PredictRequest,
    request: Request,
) -> PredictResponse:
    engine: BatchInferenceEngine = request.app.state.engine
    try:
        return await engine.predict(payload.request_id, payload.features)
    except ServiceBusyError as exc:
        raise HTTPException(status_code=429, detail=str(exc)) from exc
    except Exception as exc:
        raise HTTPException(status_code=503, detail="inference failed") from exc

预期结果:文件定义一个 /health 健康检查接口和一个 /predict 推理接口。服务启动时创建模型与批处理协程,关闭时取消协程;请求体长度错误会由 FastAPI 自动返回 422。

启动并调用接口

将文件保存为 app.py,并确保环境已安装 fastapi、uvicorn 和 torch。开发环境可用下面的命令启动单进程服务。

bash
uvicorn app:app --host 127.0.0.1 --port 8000

预期输出中的进程号和时间可能不同。

text
INFO:     Started server process [<ID>]
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000

发送一条合法请求。requestId 可省略,省略时服务会生成 UUID。

bash
curl -s -X POST http://127.0.0.1:8000/predict \
  -H "Content-Type: application/json" \
  -d '{"requestId":"req-001","features":[1.0,2.0,0.0,0.0]}'

预期响应状态码为 200,响应体如下。

json
{"requestId":"req-001","predictedClass":1,"scores":[0.244728,0.665241,0.090031]}

验收批处理与错误行为

批处理是否生效不能只看单次响应。压测时应记录每批实际大小、队列等待时间、模型执行时间和端到端延迟;当并发请求集中到达时,模型调用次数应明显少于请求数,同时单请求仍能收到与自身 requestId 对应的结果。

请求中的 features 少于或多于 4 个元素时应返回 422;队列达到 1024 条时返回 429;模型执行异常时返回 503。生产环境还应增加请求超时、鉴权、指标监控和结构化日志,并根据设备吞吐调整 MAX_BATCH_SIZE 与 MAX_WAIT_MS,而不是盲目扩大批量。

部署时的并发边界

每个 Uvicorn worker 都会创建独立模型、队列和批处理协程。GPU 服务通常先从单 worker 开始,通过批处理提升设备利用率;直接增加 worker 可能重复占用显存,并把一个全局批次拆成多个小批次。

若需要多进程或多设备,应明确模型副本与设备的绑定关系,并在入口层做负载均衡。健康检查只说明进程可响应,生产验收还要增加模型就绪状态和一次轻量级推理探针。

本课总结

  • 模型应在应用生命周期中初始化一次,请求只提交推理数据
  • 最大批量与最长等待时间共同决定吞吐和延迟
  • 422、429、503 分别表达输入非法、服务过载和推理失败

下一课预告

下一课将围绕部署后的监控展开,建立吞吐、延迟、错误率、资源使用率和模型输出质量的观测指标。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

构建批量推理服务

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通