Phần 4 · Computer Vision · Bài 16

Tự xây dựng một vision pipeline hoàn chỉnh — Bài tổng kết

12:48

Một hệ thống vision dùng trong sản phẩm là chuỗi model và quy tắc được nối với nhau bằng các data contract. Bạn đã gặp các thành phần trong giai đoạn này; bài tổng kết sẽ nối chúng thành một pipeline từ đầu đến cuối.

Loại bài: Build
Ngôn ngữ: Python
Cần biết trước: Các bài 01-15 của Phần 4
Thời gian: ~120 phút

Mục tiêu bài học

  • Thiết kế một vision pipeline dùng trong sản phẩm: phát hiện đối tượng, phân loại chúng và xuất JSON có cấu trúc — đồng thời xử lý mọi đường dẫn lỗi
  • Kết nối detector (Mask R-CNN hoặc YOLO), classifier (ConvNeXt-Tiny) và data contract (Pydantic) trong một service
  • Benchmark toàn bộ pipeline và xác định điểm nghẽn đầu tiên (thường là preprocessing, rồi đến detector)
  • Đưa vào sử dụng một service FastAPI tối giản: nhận ảnh được upload, chạy pipeline và trả về các detection kèm kết quả phân loại

Vấn đề

Từng vision model riêng lẻ đều hữu ích; sản phẩm vision là chuỗi các model ấy. Một hệ thống kiểm tra kệ hàng bán lẻ gồm detector, product classifier và pipeline OCR đọc giá. Hệ thống lái xe tự động gồm 2D detector, 3D detector, segmenter, tracker và planner. Một hệ thống sàng lọc y khoa ban đầu gồm segmenter, region classifier và giao diện cho bác sĩ.

Nối các chuỗi ấy lại là phần tạo nên khác biệt giữa một prototype ML và một sản phẩm. Mỗi interface giữa các model là một nơi mới có thể phát sinh bug. Mỗi phép biến đổi tọa độ, mỗi bước normalisation, mỗi lần đổi kích thước mask đều có thể gây lỗi âm thầm. Một pipeline chỉ mạnh bằng interface yếu nhất của nó.

Bài tổng kết này thiết lập pipeline tối thiểu có thể dùng được: detection + classification + output có cấu trúc + một layer phục vụ request. Mọi thứ khác trong Giai đoạn 4 đều có thể gắn vào bộ khung này: thay Mask R-CNN bằng YOLOv8, thêm OCR head, thêm nhánh segmentation, thêm tracker. Kiến trúc giữ ổn định; các thành phần có thể thay thế.

Khái niệm

Pipeline

Sơ đồ

Bảy giai đoạn. Hai giai đoạn chạy model tốn nhiều tài nguyên; năm giai đoạn còn lại là nơi bug thường ẩn náu.

Data contract với Pydantic

Mỗi ranh giới giữa các model trở thành một object có type. Nhờ vậy, lỗi âm thầm sẽ lộ ra ngay.

Detection(
    box: tuple[float, float, float, float],   # (x1, y1, x2, y2), absolute pixels
    score: float,                              # [0, 1]
    class_id: int,                             # from detector's label map
    mask_rle: Optional[str],                   # RLE string if present
)

PipelineResult(
    image_id: str,
    detections: list[Detection],
    classifications: list[Classification],
    inference_ms: float,
)

Khi detector trả về box ở dạng (cx, cy, w, h) thay vì (x1, y1, x2, y2), bước validation của Pydantic sẽ báo lỗi ngay tại ranh giới. Bạn biết ngay vấn đề, thay vì phải debug một bước crop phía sau âm thầm trả về vùng rỗng.

Latency nằm ở đâu

Có ba điều đúng với gần như mọi vision pipeline:

  1. Preprocessing thường là khâu đơn lẻ tốn thời gian nhất. Giải mã JPEG, chuyển đổi không gian màu, đổi kích thước — các việc này chạy trên CPU và rất dễ bị bỏ qua.
  2. Detector chiếm phần lớn thời gian GPU. 70-90% thời gian GPU nằm ở forward pass của detection.
  3. Postprocessing (NMS, mã hóa/giải mã RLE) nhanh trên GPU, chậm trên CPU. Luôn profile trên đúng môi trường đích.

Biết thời gian được phân bổ ra sao giúp bạn sắp xếp thứ tự ưu tiên khi tối ưu.

Các kiểu lỗi

  • Không có detection nào — trả về list rỗng, đừng để service crash. Ghi log.
  • Box vượt ra ngoài ảnh — giới hạn tọa độ theo kích thước ảnh trước khi crop.
  • Vùng crop quá nhỏ — bỏ qua classification với box nhỏ hơn input tối thiểu của classifier.
  • File upload bị hỏng — trả response 400 với error code cụ thể, không phải 500.
  • Không load được model — báo lỗi khi service khởi động, không đợi đến request đầu tiên.

Một pipeline dùng trong sản phẩm xử lý từng trường hợp này mà không viết try/except chung chung để che giấu lỗi. Mỗi lỗi có một code và một response riêng.

Batching

Một service dùng trong sản phẩm phục vụ nhiều client. Batching các detection và classification từ nhiều request giúp tăng throughput lên nhiều lần. Đổi lại, latency tăng vì phải chờ batch gom đủ dữ liệu. Cách thiết lập thường gặp: thu thập request trong tối đa 20ms, gộp thành batch, xử lý rồi phân phối response. torchserve và triton hỗ trợ sẵn việc này; các service nhỏ với tải dễ dự đoán thường tự viết micro-batcher.

Tự xây dựng

Bước 1: Data contract

python
from pydantic import BaseModel, Field
from typing import List, Optional, Tuple

class Detection(BaseModel):
    box: Tuple[float, float, float, float]
    score: float = Field(ge=0, le=1)
    class_id: int = Field(ge=0)
    mask_rle: Optional[str] = None


class Classification(BaseModel):
    detection_index: int
    class_id: int
    class_name: str
    score: float = Field(ge=0, le=1)


class PipelineResult(BaseModel):
    image_id: str
    detections: List[Detection]
    classifications: List[Classification]
    inference_ms: float

Năm giây viết code giúp bạn tiết kiệm một giờ debug trong bất kỳ pipeline nghiêm túc nào.

Bước 2: Một class Pipeline tối giản

python
import time
import numpy as np
import torch
from PIL import Image

class VisionPipeline:
    def __init__(self, detector, classifier, class_names,
                 device="cpu", min_crop=32):
        self.detector = detector.to(device).eval()
        self.classifier = classifier.to(device).eval()
        self.class_names = class_names
        self.device = device
        self.min_crop = min_crop

    def preprocess(self, image):
        """
        image: PIL.Image or np.ndarray (H, W, 3) uint8
        returns: CHW float tensor on device
        """
        if isinstance(image, Image.Image):
            image = np.asarray(image.convert("RGB"))
        tensor = torch.from_numpy(image).permute(2, 0, 1).float() / 255.0
        return tensor.to(self.device)

    @torch.no_grad()
    def detect(self, image_tensor):
        return self.detector([image_tensor])[0]

    @torch.no_grad()
    def classify(self, crops):
        if len(crops) == 0:
            return []
        batch = torch.stack(crops).to(self.device)
        logits = self.classifier(batch)
        probs = logits.softmax(-1)
        scores, cls = probs.max(-1)
        return list(zip(cls.tolist(), scores.tolist()))

    def run(self, image, image_id="anonymous"):
        t0 = time.perf_counter()
        tensor = self.preprocess(image)
        det = self.detect(tensor)

        crops = []
        detections = []
        valid_indices = []
        for i, (box, score, cls) in enumerate(zip(det["boxes"], det["scores"], det["labels"])):
            x1, y1, x2, y2 = [max(0, int(b)) for b in box.tolist()]
            x2 = min(x2, tensor.shape[-1])
            y2 = min(y2, tensor.shape[-2])
            detections.append(Detection(
                box=(x1, y1, x2, y2),
                score=float(score),
                class_id=int(cls),
            ))
            if (x2 - x1) < self.min_crop or (y2 - y1) < self.min_crop:
                continue
            crop = tensor[:, y1:y2, x1:x2]
            crop = torch.nn.functional.interpolate(
                crop.unsqueeze(0),
                size=(224, 224),
                mode="bilinear",
                align_corners=False,
            )[0]
            crops.append(crop)
            valid_indices.append(i)

        class_preds = self.classify(crops)

        classifications = []
        for valid_idx, (cls_id, cls_score) in zip(valid_indices, class_preds):
            classifications.append(Classification(
                detection_index=valid_idx,
                class_id=int(cls_id),
                class_name=self.class_names[cls_id],
                score=float(cls_score),
            ))

        return PipelineResult(
            image_id=image_id,
            detections=detections,
            classifications=classifications,
            inference_ms=(time.perf_counter() - t0) * 1000,
        )

Mỗi interface đều có type. Mỗi đường dẫn lỗi đều có cách xử lý cụ thể.

Bước 3: Kết nối detector và classifier

python
from torchvision.models.detection import maskrcnn_resnet50_fpn_v2
from torchvision.models import convnext_tiny

# Use ImageNet-pretrained weights for a realistic pipeline without training
detector = maskrcnn_resnet50_fpn_v2(weights="DEFAULT")
classifier = convnext_tiny(weights="DEFAULT")
class_names = [f"imagenet_class_{i}" for i in range(1000)]

pipe = VisionPipeline(detector, classifier, class_names)

# Smoke test with a synthetic image
test_image = (np.random.rand(400, 600, 3) * 255).astype(np.uint8)
result = pipe.run(test_image, image_id="demo")
print(result.model_dump_json(indent=2)[:500])

Bước 4: Service FastAPI

python
from fastapi import FastAPI, UploadFile, HTTPException
from io import BytesIO

app = FastAPI()
pipe = None  # initialised on startup

@app.on_event("startup")
def load():
    global pipe
    detector = maskrcnn_resnet50_fpn_v2(weights="DEFAULT").eval()
    classifier = convnext_tiny(weights="DEFAULT").eval()
    pipe = VisionPipeline(detector, classifier, class_names=[f"c{i}" for i in range(1000)])

@app.post("/detect")
async def detect_endpoint(file: UploadFile):
    if file.content_type not in {"image/jpeg", "image/png", "image/webp"}:
        raise HTTPException(status_code=400, detail="unsupported image type")
    data = await file.read()
    try:
        img = Image.open(BytesIO(data)).convert("RGB")
    except Exception:
        raise HTTPException(status_code=400, detail="cannot decode image")
    result = pipe.run(img, image_id=file.filename or "upload")
    return result.model_dump()

Chạy bằng uvicorn main:app --host 0.0.0.0 --port 8000. Kiểm thử bằng curl -F '[email protected]' http://localhost:8000/detect.

Bước 5: Benchmark pipeline

python
import time

def benchmark(pipe, num_runs=20, image_size=(400, 600)):
    img = (np.random.rand(*image_size, 3) * 255).astype(np.uint8)
    pipe.run(img)  # warm up

    stages = {"preprocess": [], "detect": [], "classify": [], "total": []}
    for _ in range(num_runs):
        t0 = time.perf_counter()
        tensor = pipe.preprocess(img)
        t1 = time.perf_counter()
        det = pipe.detect(tensor)
        t2 = time.perf_counter()
        crops = []
        for box in det["boxes"]:
            x1, y1, x2, y2 = [max(0, int(b)) for b in box.tolist()]
            x2 = min(x2, tensor.shape[-1])
            y2 = min(y2, tensor.shape[-2])
            if (x2 - x1) >= pipe.min_crop and (y2 - y1) >= pipe.min_crop:
                crop = tensor[:, y1:y2, x1:x2]
                crop = torch.nn.functional.interpolate(
                    crop.unsqueeze(0), size=(224, 224), mode="bilinear", align_corners=False
                )[0]
                crops.append(crop)
        pipe.classify(crops)
        t3 = time.perf_counter()
        stages["preprocess"].append((t1 - t0) * 1000)
        stages["detect"].append((t2 - t1) * 1000)
        stages["classify"].append((t3 - t2) * 1000)
        stages["total"].append((t3 - t0) * 1000)

    for stage, times in stages.items():
        times.sort()
        print(f"{stage:12s}  p50={times[len(times)//2]:7.1f} ms  p95={times[int(len(times)*0.95)]:7.1f} ms")

Kết quả thường thấy trên CPU: preprocess ~3 ms, detect 300-500 ms, classify 20-40 ms, tổng cộng 350-550 ms. Trên GPU, detect mất 20-40 ms; khi đó, thời gian preprocess + classify bắt đầu đáng kể hơn nếu xét theo tỷ lệ.

Dùng thực tế

Các template dùng trong sản phẩm thường có cùng cấu trúc, cộng thêm:

  • Model versioning — luôn ghi model name và hash của weights trong response.
  • Trace ID cho từng request — ghi log thời gian của mọi giai đoạn cho từng request để bạn biết response chậm vì giai đoạn nào.
  • Đường dẫn fallback — nếu classifier hết thời gian chờ, trả về các detection chưa có classification thay vì để cả request thất bại.
  • Safety filter — bộ lọc NSFW / PII chạy sau classification, trước khi response rời service.
  • Batch endpoint — một /detect_batch nhận list URL ảnh để xử lý hàng loạt.

Để phục vụ model trong sản phẩm, torchserve, Triton Inference Server và BentoML hỗ trợ sẵn batching, versioning, metrics và health check. Chạy trực tiếp FastAPI vẫn ổn cho prototype và sản phẩm quy mô nhỏ.

Đưa vào sản phẩm

Bài này tạo ra:

  • outputs/prompt-vision-service-shape-reviewer.md — một prompt rà soát code của vision service để tìm lỗi vi phạm cấu trúc contract/response và chỉ ra bug đầu tiên sẽ gây hỏng.
  • outputs/skill-pipeline-budget-planner.md — một skill nhận latency và throughput mục tiêu, phân bổ quỹ thời gian cho từng giai đoạn của pipeline và cảnh báo giai đoạn nào sẽ vượt quỹ trước.

Bài tập

  1. (Dễ) Chạy pipeline trên 10 ảnh từ một open dataset bất kỳ. Báo cáo thời gian trung bình của từng giai đoạn và phân bố số detection trên mỗi ảnh.
  2. (Trung bình) Thêm field mask output vào Detection và mã hóa nó thành RLE. Kiểm tra rằng JSON vẫn dưới 1MB ngay cả với ảnh có 10 đối tượng.
  3. (Khó) Thêm micro-batcher phía trước classifier: thu thập các crop trong tối đa 10 ms, phân loại tất cả bằng một lần gọi GPU, rồi trả kết quả cho từng request. Đo mức tăng throughput khi có 5 request đồng thời mỗi giây và phần latency tăng thêm.

Thuật ngữ chính

Thuật ngữNgười ta hay nóiNghĩa thật sự
Pipeline"Hệ thống"Chuỗi có thứ tự gồm các bước preprocessing, inference và postprocessing, với interface có type giữa mỗi cặp bước
Data contract"Schema"Các định nghĩa Pydantic / dataclass mà input và output của mọi giai đoạn phải tuân theo; giúp bắt bug tích hợp ngay tại ranh giới
Preprocessing"Trước model"Giải mã, chuyển đổi màu, đổi kích thước, normalising; thường là phần ngốn nhiều thời gian CPU nhất
Postprocessing"Sau model"NMS, đổi kích thước mask, threshold, mã hóa RLE; nhanh trên GPU, chậm trên CPU
Microbatcher"Gom lại rồi chạy forward"Bộ gom request chờ trong một khoảng thời gian cố định để nhận nhiều request, rồi chạy một batched forward pass
Trace ID"ID của request"Mã định danh riêng cho từng request, được ghi log ở mọi giai đoạn để truy vết request chậm từ đầu đến cuối
Failure code"Lỗi có tên"Error code cụ thể cho từng loại lỗi thay vì mã 500 chung chung; giúp client quyết định có retry hay không
Health check"Readiness probe"Endpoint nhẹ cho biết service có thể trả lời hay không; load balancer dựa vào đó

Đọc thêm