Lab 16 (ml_serving_patterns_lab) — Mẫu Phục vụ ML (Online/Batch/Cached), Chưng cất PyTorch, Thác 3 Tầng, RabbitMQ Quorum/DLQ & Co giãn KEDA
Hướng dẫn thực hành, cài đặt môi trường .venv/uv và tiêu chuẩn kiểm định pytest.
Unit ID:
T2-P4-U01| Chương Song hành: ch-20-ml-serving-patterns-paths-and-autoscaling.md
Truy xuất Giáo trình Gốc (R29,R41,AIDE 1 & 3+ Chuyên đề#20,#21,#28,#29): Model serving design patterns (caching, microbatching, serverless, high-density Model Mesh/Triton, streaming); Model loading patterns (Model-in-imagevsModel-load); Async task queue ML system (RabbitMQQuorum/DLQ +Redis+FastAPI); Online vs Batch vs Cached Paths; Multi-Stage Inference Cascade; Knowledge Distillation under serving budget; Bursty Traffic Autoscaling (KEDAvsCPU-HPA).
Kiến trúc Hai Tầng (100%Offline Verifiable): Tầng 1 cung cấp khai báodocker-compose.yml(5dịch vụ:model-loaderinit tải & kiểm traSHA-256vàomodel-cache:/models:rw, cùngrabbitmq,redis,ml-api,ml-workerdùngmodel-cache:/models:ro, bind127.0.0.1:) vàmanifests/keda_rabbitmq_scaler.yaml(DeploymentdùngModel-LoadinitContainers,KEDA ScaledObjecttriggerrabbitmqQueueLength,PodDisruptionBudget,0:latest,0bí mật cứng); Tầng 2 (ml_serving_patterns_lab) thực thi đầy đủ3thực nghiệm xác định trênPyTorch CPU+FastAPI TestClient, đạt27/27pytest pass (0skip),0lỗiruff/mypy --strict,0# type: ignore,uv.lock(44gói) xác thực sạch.
1. Bất biến Kỹ thuật Được Chứng minh (seed = 42)#
- Thực nghiệm 1 — Chọn Đường dẫn
OnlinevsBatch PrecomputevsCached Redis(#20):- Danh mục Dày (
5,000SKU, phủ92%,120 QPS, TTL1h):Batch Precomputetốn$4.75/ngày(1.5 msp95, lãng phí chỉ8.0%) vàRedis Cachedtốn$16.65/ngày(93.3%hit,3.42 msp95), rẻ hơn gấp11.2x–39.3xso vớiOnline($186.62/ngày,26.0 msp95). - Danh mục Thưa Đuôi dài (
500,000thực thể, phủ4.0%,60 QPS, TTL30m):Batch Precomputelãng phí tới96.0%năng lực tính toán ($122.07/ngày), đắt hơn cảOnline($93.31/ngày).Cached Redisđạt90.36%hit rate với chi phí chỉ$11.07/ngày(4.13 msp95, tiết kiệm11.0xso với Batch và8.4xso với Online!). - Chống Gian lận Thời gian thực (
250 QPS,0sStaleness):Batch(100%stale) vàCached(1.5%hit sai tươi mới) đều không khả thi;Online($259.2/ngày,18.5 msp95) là đường dẫn hợp lệ duy nhất.
- Danh mục Dày (
- Thực nghiệm 2A — Chưng cất
PyTorch CPUTừHeavyTeacherMLPSangCompactStudentMLP(#29):- Chưng cất thực tế trên
PyTorch CPU(KL Divergence\(T = 3.0\), \(\alpha_{\text{kd}} = 0.85\) +Cross-Entropy): nén454.4xsố tham số (172,674\(\to\)380params), giữ99.06%ROC-AUC của Teacher (0.9194vs0.9281, vượt+13.44điểm AUC so vớiStudent Without KD0.785), giảm trễ MAC-model8.74x(0.082 msvs0.7169 ms), đồng thờimeasure_live_torch_cpu_timing(torch.inference_mode()xuất tronglive_torch_cpu_benchmark) đo thực tếStudent B=10.0801 ms(12,486.6 req/s) so vớiTeacher B=10.4728 ms(2,115.2 req/s, nhanh hơn5.90x) vàStudent B=160.0048 ms/req(206,484.9 req/s, tăng16.54xso với B=1); hạ chi phí từ$0.032xuống$0.004 / 1Mdự đoán.
- Chưng cất thực tế trên
- Thực nghiệm 2B — Thác Suy luận 3 Tầng (
Linear Prefilter -> Distilled Student -> Heavy Teacher,#28):Stage 1 (Linear Prefilter)thoát sớm8.83%mẫu an toàn rõ ràng (0.0531 ms);Stage 2 (Distilled Student)xử lý tự tin74.5%; chỉ16.67%mẫu vùng xám \([0.25, 0.75]\) leo thang lênHeavy Teacher.- Kết quả: đạt
0.9222ROC-AUC (99.36%parity với Teacher Solo0.9281), độ trễ trung bình0.2473 ms(2.9xnhanh hơn Teacher), chi phí$0.011 / 1Mdự đoán (giảm65.62%chi phí).
- Thực nghiệm 3 — Hàng đợi
FastAPI+Idempotency+RabbitMQQuorum/unacked/DLQ,Dynamic Microbatcher, Luật Little / \(M/G/1\) & Đột biến10xKEDA(#21):- Dynamic Microbatching (
max_batch=16, max_wait=8ms) — Tách bạch DES vs PyTorch Thực tế: Gom trung bình14.77yêu cầu/lô; mô hình DES mô phỏng (simulated_des_batch_throughput_rps) đạt46,752.5 DES req/svs6,802.7 DES req/s(6.87x), còn đo đồng hồ tườngPyTorch CPUtrên vòng lặp 192 yêu cầu đạt9,216.9 req/s(20.831 ms) vs870.6 req/s(220.526 ms,10.59x, dao động nhẹ theo tải CPU). - Live
FastAPI(TestClient): Kiểm chứng/healthz(model-load),/readyz(sha256_verified=True),Redis(MISS -> HIT),idempotency_keydeduplication trênPOST /v1/jobs,Admission Control(HTTP 429+Retry-After: 5),RabbitMQQuorumBrokerunackedvisibility lease (30s) tự redeliver khi worker sập, và cô lậppoison_pillvàoDLQsaumax_retries=2, thu18live OpenTelemetry spans (+4suite spans). - Luật Little (\(L = \lambda W\)) & Đường cong Nổ trễ \(M/G/1\) (\(\rho \to 1\)): Kiểm chứng sự kiện rời rạc (
n=4,000Gamma, \(C_s^2=1.25\)) đạt sai số Luật Little tối đa6.17e-15và xác nhận độ trễ \(M/G/1\) bùng nổ56.12xtại \(\rho=0.98\). - Bão Lưu lượng
10x(20 -> 200 req/strong40s):Naive CPU-HPA + Model-in-Image(44scold start) dồn hàng đợi lên6,720việc,p95 = 48.156svà chỉ7.14%SLA;KEDA + Model-Load (5s) + Pre-Warm Pool (min=3) + Admission Controlkhống chế đỉnh hàng đợi ở64việc, cắtp9555.67xxuống0.865svà đạt100.0%SLA trên7,680yêu cầu được tiếp nhận (chủ động shed1,920việc ưu tiên thấp bằng429).
- Dynamic Microbatching (
2. Cấu trúc Thư mục Lab 16#
lab-16-rabbitmq-async-ml-task-queue/
├── docker-compose.yml # model-loader (init) + rabbitmq, redis, ml-api, ml-worker + model-cache (127.0.0.1:)
├── manifests/
│ └── keda_rabbitmq_scaler.yaml # Deployment (initContainer model-loader) + KEDA ScaledObject + PDB
├── src/ml_serving_patterns_lab/
│ ├── __init__.py
│ ├── serving_paths_and_cascade.py # Exp 1 (#20) & Exp 2 (#28 Cascade + #29 PyTorch KL+CE + Live CPU Benchmark)
│ └── async_queue_and_autoscaling.py # Exp 3 (#21), DES+PyTorch Microbatcher, Little's Law/M/G/1, FastAPI/Idem/Unacked/DLQ
├── scripts/
│ └── run_lab_demo.py # CLI xuất artifacts/t2_ch20_lab16_results.json (kèm live_torch_cpu_benchmark)
├── tests/
│ └── test_ml_serving_patterns_lab.py # 27 pytest tests (0 skip, Hypothesis invariants, Idempotency, Crash Redelivery, Little's Law)
├── artifacts/
│ └── t2_ch20_lab16_results.json # Kết quả đo đạc xác định + live PyTorch CPU benchmark (seed=42)
├── pyproject.toml
├── uv.lock
└── README.md
3. Hướng dẫn Chạy Nhanh & Kiểm định Tự động#
cd 03-track-2-data-and-ai-engineering/part-04-ml-and-llm-serving-systems/labs/lab-16-rabbitmq-async-ml-task-queue
# 1. Sinh báo cáo kết quả tổng hợp chuẩn hóa
PYTHONPATH=src python scripts/run_lab_demo.py --seed 42 --output artifacts/t2_ch20_lab16_results.json
# 2. Kiểm định lint, kiểu tĩnh mypy strict, uv.lock và toàn bộ 27 test cases
ruff check src scripts tests
mypy --strict src tests
pytest -p no:cacheprovider -v
uv lock --check