Lab 12 (applied_ai_guardrails_lab) — Dịch vụ PyTorch OCR, Tinh chỉnh LoRA PEFT, Hybrid RAG, Guardrails 3 Lớp & Cổng Chặn EDD (FastAPI + OpenTelemetry)
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-P3-U01| Chương Song hành: ch-13-applied-ai-and-guardrail-systems-for-engineers.md
Truy xuất Giáo trình Gốc (R39&R40): End-to-End DS Project + OCR Application (R39) và Fine-tune Open-Source LLM + RAG Application + Agentic AI System + Guardrails + Eval-Driven Development (R40)
Kiến trúc Lab Offline 100% CPU (0Tệp Ảnh/DB Rác): Gói Pythonapplied_ai_guardrails_labthực thi hoàn toàn trong RAM (Pillow+io.BytesIO,NumPy,Pandas,PyTorch,scikit-learn,Pydantic v2,FastAPI,httpx TestClient,OpenTelemetry SDK), đạt32/32pytest pass (0skip),0lỗiruff/mypy,0# type: ignore,uv.lockxác thực sạch.
1. Mục tiêu Bài thực hành & 6 Bất biến Kỹ thuật (seed = 42)#
- Năng lực
NumPy/Pandas(Test 03): So sánh vòng lặp Python (8.353 ms) với vector hóa SIMDNumPy(0.907 ms,9.21xnhanh hơn,diff = 0.0), xác minh view không sao chép (slice/transpose) vs fancy indexing (copy), và nén bộ nhớPandas(float64+object5.417 MB\(\to\)float32+category0.534 MB,10.14xgọn RAM). PyTorchDigitOCRNet& Cổng Tự tin + Checksum Mod-10 (Tests 04–06, 24): Sinh ảnh hóa đơn4chữ số (16×64grayscale) hoàn toàn trong bộ nhớ (io.BytesIO), huấn luyện mạng CNN (9,930tham số,1,000mẫu trong914.16 ms,100.0%train accuracy) và đánh giá trên200hóa đơn hỗn hợp (110sạch +90mờ/lem): Naive auto-post sai90hóa đơn (55.0%), \(\tau=0.0\) + checksum sai7hóa đơn (94.02%), còn Gate \(\tau=0.82\) + Checksum Mod-10 đạt100.0%chính xác (0lỗi ghi sổ, bắt100.0%hóa đơn nhòe sang duyệt thủ công).- Toán học
KV-Cache& Tinh chỉnhPyTorch LoRA PEFT(Tests 07–09, 25): Kiểm chứng công thức \(2 \cdot L \cdot n_{kv} \cdot d_h \cdot B \cdot S \cdot b_{\text{kv}}\) (MHA FP16128.0 GBKV /OOM_RISKvsGQA-4 FP816.0 GBKV /8.0xgọn;8thuê bao dùng40.0 MB/adapter tiết kiệm15.68xVRAM), và huấn luyệnLoRALinear(rank=4)trên mô hình 2 khối Transformer có che<pad>(7,168 / 81,284 = 8.82%tham số,3,772.14 ms) nâng độ chính xác phân loại ý định từ29.0%lên100.0%(+71.0 pp) với trọng số gốc bất biến từng bit. Hybrid RRF RAG(Sàn Ngoài miền) & Phòng vệGuardrails3 Lớp (Tests 10–14, 19–21, 26, 30–32): Kết hợpTF-IDF(stop_words="english",token_patterngiữ tokenextra=forbid) +SVD CosinequaRRF (k=60)kèm sàn tương đồng + kiểm tra neo ngữ nghĩa trả[]cho truy vấn ngoài miền (OUT_OF_DOMAIN_NO_GROUNDING, chặn cả"order pizza with extra cheese"), và đo kiểm chứng qua20mẫu tấn công tách rời (bao gồmU+E0000Tag,\u200bzero-width, đồng hình Hy Lạp\u03c3/\u03c2,NFKCfullwidth,Base64,OCR -> Agent -> Tool,5-step overflow,"capped"$5,000 USD/$2.5k/$1.5M/$1.2B/$500B/$1.2Tchống backtracking thập phân) +20mẫu hợp lệ:unguarded_baseline100.0%ASR (p95 = 7.283 ms),input_rail_only50.0%ASR (9.365 ms),input_plus_tool_rail25.0%ASR (8.842 ms), còndefense_in_depth_fullđạt0.0%ASR (20/20bị chặn),100.0%benign pass,0.0%PII leak,p95 = 10.866 ms.- Cổng Chặn
EDDTrongCI/CD(Tests 15, 22): Đánh giá tự động 3 ứng viên theo ngưỡngconfigs/guardrails_policy.yamlbằng xác thực thực tếAgentStructuredOutput.model_validate_json(...)vàthreshold_sweep, chặnv1_unguarded_baselinevàv2_broken_lora_json, tự động bầu chọnv3_guardrailed_sota(PASS_PROMOTE). - Dịch vụ
FastAPI+BoundedOpenTelemetrySạchPII(Tests 01, 16–18, 23): Kiểm thử end-to-end/health,/v1/ocr/extract(trả422khi ảnh hỏng/sai kích thước),/v1/agent/assist(AgentAssistResponse) quaTestClient, thu đủ9OpenTelemetry spans trongBoundedInMemorySpanExporter(maxlen=256)với0dữ liệuPIIthô rò rỉ.
2. Cấu trúc Thư mục Lab 12#
text18 dòng
lab-12-ml-ocr-and-guardrailed-agent-app/
├── configs/
│ └── guardrails_policy.yaml # Chính sách OCR, Tool Allowlist/Cap $250, PII/Injection & EDD CI Gates
├── src/applied_ai_guardrails_lab/
│ ├── __init__.py
│ ├── ml_ocr_pipeline.py # NumPy/Pandas benchmark + Pillow BytesIO + PyTorch DigitOCRNet + Mod-10
│ ├── llm_lora_rag_agent.py # KV-Cache math + 2-Block LoRA Transformer + Hybrid RRF RAG Store
│ ├── guardrails_and_edd.py # Unicode/Base64 Input Rail, Bounded Tool Loop, Output Rail & Real EDD CI Gate
│ └── service_app.py # FastAPI (/health, /v1/ocr/extract, /v1/agent/assist) + Bounded OTel zero-PII
├── scripts/
│ └── run_lab_demo.py # CLI sinh artifacts/t2_ch13_lab12_results.json (6 KPI, 4 Bar, 4 Table)
├── tests/
│ └── test_applied_ai_guardrails_lab.py # 32 hàm pytest (0 skip, gồm Hypothesis property test & AST/type-ignore guard)
├── artifacts/
│ └── t2_ch13_lab12_results.json # Kết quả đo đạc xác định (seed=42)
├── pyproject.toml
├── uv.lock
└── README.md
3. Hướng dẫn Chạy & Kiểm thử Tự động#
bash10 dòng
cd 03-track-2-data-and-ai-engineering/part-03-distributed-k8s-cloud-and-gateway/labs/lab-12-ml-ocr-and-guardrailed-agent-app
# 1. Sinh báo cáo kết quả chuẩn hóa
PYTHONPATH=src python scripts/run_lab_demo.py --seed 42 --output artifacts/t2_ch13_lab12_results.json
# 2. Kiểm định lint, kiểu tĩnh mypy strict, uv.lock và toàn bộ 32 test cases
ruff check src tests scripts
mypy src tests
pytest -p no:cacheprovider -v
uv lock --check