Chương 17 — Thị giác Máy tính Hiện đại: Backbone 2026, Phát hiện Vật thể, Theo dõi Đa mục tiêu & Phân đoạn Nền tảng (Modern Computer Vision: Detection, Tracking & Segmentation)
Từ GIoU/CIoU & Soft-NMS (0.81->0.434), mAP@50:95 (0.902) đến ByteTrack vs SORT dưới bóng cầu vượt (HOTA 0.414->0.934, IDSW 29->0, đếm 50%->100%), Panoptic PQ=SQ*RQ (bắt lỗi gộp xe mIoU=1.000), ViT+LoRA (1.89%), CLIP vs SigLIP & ONNX Runtime CPU (0.52 ms, ~1,940 FPS).
Đơn vị học phần (
Unit ID):T1-P3-U04(Phần 3: Nền tảng Học Sâu, Thị giác Máy tính Hiện đại & Nhận thức Đa phương thức — Mục lục Phần 3)
Phòng thí nghiệm Thực chiến: Lab 09 — Thị giác Máy tính Thời gian Thực: Phát hiện, Theo dõi, Đếm Phương tiện & Phân đoạn Hiện đại (modern_cv_tracking_lab)
Truy xuất nguồn & kế thừa: Chương 11 — k-NN, ANN & Truy xuất Vector (truy xuất nhúngCLIP/SigLIP), Chương 15 — Autoencoders, Vận hành Mô hình & Nén Edge (safetensors,ONNXdynamo=False,ORT CPU),Chương 16(xử lý ảnh, tích chập, trường tiếp nhận), Chương trình gốc DSAI (R45& Lab Real-Time CVE43:E45), và Đề cương SOTA 2026 (Chương 17).
Bốn Ca Thất bại Thực chiến Mở màn: Từ Sụp đổ SORT dưới Bóng Cầu vượt đến Điểm mù Semantic mIoU#
Khoảng cách giữa một bộ phát hiện vật thể đạt điểm đẹp trên ảnh tĩnh và một hệ thống thị giác thời gian thực chạy 30 FPS tại cổng thu phí cao tốc (ITS), trên xe tự hành hay trong kho bán lẻ chứa bốn cái bẫy kinh điển mà mọi kỹ sư thị giác đều từng trả giá:
-
Ca 1 —
SORTBỏ lọt50%Lưu lượng Xe & Bùng nổ29 ID Switchesdưới Bóng Cầu vượt (Lab 09,Tests 07–08):Một trạm giám sát cao tốc 4 làn đặt vạch đếm (
tripwire) tạiy = 242ngay sau bóng cầu vượt. Khi xe đi qua vùng che khuất một phần trong6–7khung hình, điểm tin cậy của detector tụt từ~0.86xuống~0.26. Bộ theo dõiSORTcổ điển cắt cứng mọi hộp dưới ngưỡng0.55, đánh mất quỹ đạo saumax_age = 3khung rồi cấptrack_idmới khi xe lộ diện trở lại. Kết quả thực nghiệm trên100khung hình (16xe,8chiều đi xuống /8chiều đi lên):SORTchịu tới29lần nhảy ID (IDSW = 29),HOTAsập xuống0.414(AssA = 0.273), và vì quỹ đạo mới chưa đủmin_hits = 3khung xác nhận lúc vừa lướt qua vạchy = 242,SORTbỏ sót toàn bộ8/8xe chiều đi xuống (counting accuracy = 50.0%,MAE = 4.0)! Khi chuyển sangByteTrackgiữ nguyênmax_age = 3nhưng thêm Giai đoạn 2 ghép hộp điểm thấp[0.15, 0.55)với các quỹ đạo còn sót,IDSWgiảm từ29 -> 0,HOTAvọt lên0.934(+0.520),IDF1 = 0.983, và độ chính xác đếm xe đạt trọn100.0%(8D/8U,MAE = 0.0). -
Ca 2 — Điểm mù
Greedy NMS& Mặt phẳng Gradient Bằng0củaIoU(Lab 09,Tests 02–04):Khi hai xe chạy song song sát làn có độ chồng lấn hình chiếu
IoU = 0.56,Greedy NMSở ngưỡng0.50xóa cứng hoàn toàn chiếc xe phía sau (chỉ giữ lại1hộp thay vì2), gây hụt recall nghiêm trọng; trong khiGaussian Soft-NMSchỉ hạ mềm điểm tin cậy chiếc xe kế bên từ0.81 -> 0.434, bảo toàn đủ cả2phương tiện. Tương tự, khi hai hộp dự đoán và ground truth chưa chạm nhau (hộp gần vs hộp xa),IoUtrả về đồng loạt0.000vs0.000(gradient bằng0, không biết kéo hộp về hướng nào), cònGIoU(-0.091vs-0.500) vàCIoU(-0.218vs-0.506) tạo độ dốc hình học rõ ràng kéo hộp hội tụ nhanh về mục tiêu. -
Ca 3 — Ảo giác
Semantic mIoU = 1.000Che giấu Thảm họa Gộp Cá thể trên Xe Tự hành (Lab 09,Test 09):Một mạng phân đoạn ngữ nghĩa dự đoán chính xác
100%nhãn pixel (trời,đường,ô tô,xe tải) đạtSemantic mIoU = 1.000, nhưng mô-đun gom cụm hậu xử lý lại gộp nhầm hai chiếc ô tô chạy sát nhau thành duy nhất mộtinstance_id. Nếu chỉ dùngmIoUlàm cổng nghiệm thu CI/CD, lỗi này lọt thẳng ra đường phố khiến bộ hoạch định quỹ đạo xe tự hành ước lượng sai vận tốc từng xe! Khi thay bằng thước đoPanoptic Quality (PQ = SQ * RQ), lỗi gộp hai cá thể lập tức bị phơi bày:PQcủa lớp ô tô sụp mạnh từ0.917 -> 0.400(-0.517), kéoPQ_thingstừ0.924 -> 0.700vàPQtổng thể từ0.940 -> 0.727. -
Ca 4 — Cổ chai Batch
CLIP InfoNCE, Bùng nổ Tham số Fine-TuningViT& Sập XuấtONNX(Lab 09,Tests 11–14):Huấn luyện lại toàn bộ
ViTcho từng camera miền mới tốn hàng chục GB trạng tháiAdamW; thay bằngLoRAhạng4trên các phép chiếuQKVđóng băng backbone gốc chỉ cần huấn luyện1.89%tham số (2,243 / 118,915) với khởi tạo \(\mathbf{B} = \mathbf{0}\) giữ nguyên nghiệm khởi đầu và gộp phẳng không tốn độ trễ suy luận. Về đa phương thức, mất mátCLIP InfoNCEcó sàn nhiễu ngẫu nhiên phụ thuộc chặt vào kích thước batch (\(\approx \ln B\): tăng từ2.468ởB = 4lên4.841ởB = 32), đòi hỏi gom toàn batch giữa hàng trăm GPU; ngược lạiSigLIPdùng mất mát Sigmoid từng cặp tách rời khỏisoftmaxtoàn cục. Cuối cùng, khi triển khai biên trênPyTorch 2.15+cpukhông càionnxscript, phải dùng tường minhtorch.onnx.export(..., dynamo=False)để xuất sangONNX Runtime CPU(MiniConvNeXt:p50 = 0.52 ms,p95 = 0.63 ms,~1,940 FPSvượt xa ngân sách33.3 mscủa30 FPS, sai lệch1.3e-07 < 1e-4), kết hợp lưu trọng số bằngsafetensors(0opcodepickle, sai số0.0e+00).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất Chương 17 và vượt qua trọn vẹn 16/16 bài kiểm thử của Lab 09, học viên làm chủ toàn diện 5 trụ cột thị giác máy tính hiện đại:
- Làm chủ Tiến hóa Backbone 2026 & PEFT Thị giác: Phân tích toán học từ
ResNet(truyền gradient phần dư),EfficientNet(mở rộng hỗn hợp \(\alpha\beta^2\gamma^2 \approx 2\)),ConvNeXt(7x7depthwise +LayerNorm+ inverted bottleneck) đếnVision Transformer (ViT)(\(N = HW/P^2\), độ phức tạp \(\mathcal{O}(N^2 D)\)),DINOv2tự giám sát dày, và thích ứngLoRA(\(\mathbf{W}_0 + \frac{\alpha_{\text{lora}}}{r}\mathbf{B}\mathbf{A}\)) với< 15%tham số huấn luyện. - Dẫn xuất Hình học Phát hiện Vật thể & Kiến trúc Không
NMS: Chứng minh công thứcIoU,GIoU,CIoU, cơ chế suy giảm mềmSoft-NMS, tích phân nội suy101điểmAP@50/mAP@50:95, và lộ trình tiến hóa từFaster R-CNN(RPN+RoIAlign) ->YOLO11(C3k2/C2PSA,DFL+CIoU) ->RT-DETR(bộ mã hóa lai + ghép cặp hai phía Hungary đầu-cuối bỏ hoàn toànNMS). - Thiết kế Hệ thống Theo dõi Đa mục tiêu (
MOT) & Đếm Xe Thời gian Thực: Tự triển khai bộ lọc Kalman 7 trạng thái, bài toán gán Hungary, đối chứngSORTvsByteTrack(2 giai đoạn) vsBoT-SORT(GMC+ReID), đánh giá chính xácMOTA,IDF1,HOTA = sqrt(DetA * AssA), và thiết kế bộ đếm vạch có hướng bất biến chống đếm trùng dưới ngân sách< 33.3 ms/frame. - Phân tích Chỉnh sửa Ảnh Nghệ thuật & Phân đoạn Nền tảng: Nắm vững ma trận Gram trong Neural Style Transfer, giới hạn pháp lý của siêu phân giải sinh ảnh (Diffusion / ControlNet), phân biệt Semantic (
mIoU), Instance (Mask AP) và Panoptic (PQ = SQ * RQ), cùng kiến trúcMask2FormervàSAM 2(Memory Bankcho video). - Đối chiếu Tiền huấn luyện Thị giác–Ngôn ngữ & Triển khai Biên An toàn: Chứng minh khác biệt thuật toán và phân tán giữa
CLIP(InfoNCE) vàSigLIP(Pairwise Sigmoid), đồng thời đóng gói mô hình biên bằngsafetensorsvàONNX(dynamo=False) +ORT CPU.
Truy xuất Nguồn (Syllabus & Raw Curriculum Traceability)#
Thành phần Chương trình Nguồn (R45 & E43:E45) |
Nội dung Chuyên sâu trong Chương 17 | Sơ đồ / Mô phỏng Tương tác | Thực thi trong Lab 09 (modern_cv_tracking_lab) |
|---|---|---|---|
Kiến trúc CNN Nâng cao & Backbone 2026 (R45) |
ResNet, EfficientNet (\(\alpha\beta^2\gamma^2\approx 2\)), ConvNeXt (7x7 DW + LN), ViT (\(N=HW/P^2\)), DINOv2 |
Mermaid 1 |
vision_backbones_and_vlm.py: ConvNeXtBlock, MiniConvNeXt, MiniViT (Test 10) |
Mô hình Phát hiện Vật thể (Object Detection) (R45) |
IoU/GIoU/CIoU, Greedy NMS vs Soft-NMS, AP@50 & mAP@50:95, Faster R-CNN -> YOLO11 -> RT-DETR |
Mermaid 1 + Widget 1 (detection-iou-nms-map-arena) |
detection_metrics.py: compute_iou_matrix, compute_giou_matrix, compute_ciou_matrix, greedy_nms, soft_nms, compute_map_50_95 (Tests 02–04) |
Học Chuyển giao & PEFT Thị giác (R45) |
Linear Probing vs Full Fine-Tuning vs LoRA (\(\mathbf{W}_0 + \frac{\alpha}{r}\mathbf{BA}\), gộp phẳng 0 độ trễ) |
Mermaid 1 |
vision_backbones_and_vlm.py: LoRALinear, MiniViT(use_lora=True), count_parameters (Test 11) |
CNN Nghệ thuật, Siêu phân giải & Khuếch tán (R45) |
Neural Style Transfer (Ma trận Gram), ESRGAN/SwinIR, Latent Diffusion / ControlNet & cảnh báo ảo giác pháp lý |
Mục 1.5 & Bảng quyết định | Tích hợp phân tích kiến trúc & bài tập thiết kế hệ thống (ex5) |
Phân đoạn (Semantic, Instance, Panoptic) & VLM (R45) |
mIoU, Mask AP, PQ = SQ * RQ, Mask2Former, SAM 2 (Memory Bank), CLIP (InfoNCE) vs SigLIP (Sigmoid) |
Mermaid 3 + Widget 3 (segmentation-pq-clip-siglip-explorer) |
segmentation_metrics.py (Test 09) & vision_backbones_and_vlm.py: clip_infonce_loss, siglip_sigmoid_loss (Test 12) |
Lab Thời gian Thực: Phát hiện, Theo dõi & Đếm Xe (E43:E45) |
Kalman 7D, ghép Hungary, SORT vs ByteTrack vs BoT-SORT, MOTA/IDF1/HOTA, Tripwire bất biến, safetensors + ONNX (dynamo=False) < 33.3 ms |
Mermaid 2 + Widget 2 (bytetrack-kalman-occlusion-sim) |
traffic_simulator.py, tracking_and_counting.py, vision_backbones_and_vlm.py (Tests 01, 05–08, 13–16) |
Bảng Ký hiệu Phi Mơ hồ (Disambiguated Notation Contract)#
| Ký hiệu LaTeX | Miền / Kích thước | Định nghĩa chuẩn trong Chương 17 | Định danh modern_cv_tracking_lab |
|---|---|---|---|
| \(B = (x_1, y_1, x_2, y_2)\) | \(\mathbb{R}^4\) (\(x_2 > x_1, y_2 > y_1\)) | Hộp giới hạn dự đoán hoặc ground truth (\(B^{\text{gt}}\)) | box, boxes_a, boxes_b |
| \(\operatorname{IoU}, \operatorname{GIoU}, \operatorname{CIoU}\) | \([0, 1], (-1, 1], (-1, 1]\) | Độ chồng lấn chuẩn, tổng quát và đầy đủ (tâm + tỷ lệ) | compute_iou_matrix, compute_giou_matrix, compute_ciou_matrix |
| \(\tau_{\text{nms}}, \sigma_{\text{soft}}\) | \((0, 1), \mathbb{R}_{>0}\) | Ngưỡng xóa cứng NMS và độ rộng suy giảm Gauss Soft-NMS |
iou_threshold, sigma |
| \(\operatorname{AP}_{50}, \operatorname{mAP}_{50:95}\) | \([0, 1]\) | Nội suy 101 điểm tại IoU = 0.50 và trung bình 10 ngưỡng |
compute_ap, compute_map_50_95 |
| \(N, P, D\) | \(\mathbb{N}_+\) | Số mảnh ViT \(N = HW/P^2\), kích thước mảnh \(P\), chiều nhúng \(D\) |
num_patches, patch_size, embed_dim |
| \(r_{\text{lora}}, \alpha_{\text{lora}}, \mathbf{A}, \mathbf{B}\) | \(\mathbb{N}_+, \mathbb{R}_{>0}\), ma trận | Hạng, hệ số tỷ lệ và hai ma trận nhân tử hạng thấp LoRA |
lora_rank, lora_alpha, lora_a, lora_b |
| \(\mathbf{x}_k = [u, v, s, r, \dot{u}, \dot{v}, \dot{s}]^\top\) | \(\mathbb{R}^7\) | Trạng thái Kalman 7 chiều (tâm, diện tích, tỷ lệ, vận tốc) | KalmanBoxTracker.x |
| \(\mathbf{F}, \mathbf{H}, \mathbf{P}_k, \mathbf{Q}, \mathbf{R}, \mathbf{K}_k\) | Ma trận thực | Chuyển trạng thái, quan sát, hiệp phương sai, nhiễu, độ lợi Kalman | F, H, P, Q, R, K |
| \(\tau_{\text{high}}, \tau_{\text{low}}\) | \(0 < \tau_{\text{low}} < \tau_{\text{high}} < 1\) | Hai ngưỡng tin cậy của ByteTrack (0.55 và 0.15) |
high_conf_thresh, low_conf_thresh |
| \(\operatorname{MOTA}, \operatorname{IDF1}, \operatorname{HOTA}\) | \((-\infty, 1], [0,1], [0,1]\) | Bộ thước đo MOT; \(\operatorname{HOTA}_\alpha = \sqrt{\operatorname{DetA}_\alpha\cdot\operatorname{AssA}_\alpha}\) |
mota, idf1, hota, det_a, ass_a, id_switches |
| \(\operatorname{mIoU}, \operatorname{PQ}, \operatorname{SQ}, \operatorname{RQ}\) | \([0, 1]\) | Phân đoạn ngữ nghĩa và chất lượng toàn cảnh (\(\operatorname{PQ} = \operatorname{SQ}\cdot\operatorname{RQ}\)) | compute_semantic_miou, compute_panoptic_quality |
| \(\mathbf{u}_i, \mathbf{v}_j, \tau_{\text{temp}}, b_{\text{sig}}\) | \(\mathbb{S}^{d-1}, \mathbb{R}_{>0}, \mathbb{R}\) | Nhúng ảnh/văn bản chuẩn hóa \(L_2\), hệ số logit và độ lệch SigLIP |
logit_scale, logit_bias |
Trụ cột 1 — Nền tảng Toán học: Backbone Thị giác, Hình học Hộp, Kalman–Hungary & Phân đoạn#
1.1 Tiến hóa Backbone: Từ ResNet/ConvNeXt đến ViT, DINOv2 & LoRA#
Sự chuyển dịch backbone thị giác giai đoạn 2016–2026 không phải là sự thay thế mù quáng CNN bằng Transformer, mà là quá trình hội tụ về thiết kế khối mô-đun tối ưu hóa đồng thời dòng gradient, vùng tiếp nhận hiệu dụng (ERF) và cường độ tính toán theo mô hình Roofline:
-
ResNet(He et al., CVPR 2016) — Đẳng thức truyền gradient qua kết nối tắt: Đặt \(\mathbf{x}_{l+1} = \mathbf{x}_l + \mathcal{F}(\mathbf{x}_l; \mathbf{W}_l)\). Bằng quy nạp từ tầng \(l\) đến tầng mất mát \(L\), ta có \(\mathbf{x}_L = \mathbf{x}_l + \sum_{i=l}^{L-1}\mathcal{F}(\mathbf{x}_i; \mathbf{W}_i)\), suy ra quy tắc dây chuyền:\[\frac{\partial \mathcal{L}}{\partial \mathbf{x}_l} = \frac{\partial \mathcal{L}}{\partial \mathbf{x}_L}\left(\mathbf{I} + \frac{\partial}{\partial \mathbf{x}_l}\sum_{i=l}^{L-1}\mathcal{F}(\mathbf{x}_i; \mathbf{W}_i)\right).\]Hạng tử đơn vị \(\mathbf{I}\) tạo "đường cao tốc" truyền trực tiếp sai số từ ngõ ra về mọi tầng nông ngay cả khi đạo hàm thành phần dư rất nhỏ, giải quyết triệt để hiện tượng thoái hóa độ sâu (
degradation problem). -
EfficientNet(Tan & Le, ICML 2019) — Phép Mở rộng Hỗn hợp (Compound Scaling): Chi phíFLOPscủa một tầng tích chập 2D tỷ lệ thuận với độ sâu \(d\), bình phương độ rộng kênh \(w^2\) và bình phương độ phân giải cạnh \(r^2\). Để tổngFLOPstăng đúng \(2^\phi\) lần mà không mất cân đối vùng tiếp nhận và sức chứa kênh,EfficientNetgắn chặt ba trục mở rộng bằng hệ số hỗn hợp \(\phi\):\[d = \alpha^\phi, \qquad w = \beta^\phi, \qquad r = \gamma^\phi, \qquad \text{với } \alpha \cdot \beta^2 \cdot \gamma^2 \approx 2,\quad \alpha, \beta, \gamma \ge 1.\] -
ConvNeXt(Liu et al., CVPR 2022) — Hiện đại hóa Thuần CNN: Thay vì3x3dày đặc +BatchNorm+ReLU, mỗi khốiConvNeXtBlockthực hiện: (i) tích chập tách chiều rộng7x7depthwise (groups = C) để mở rộng vùng tiếp nhận không gian với chỉ \(49 C H W\) phép nhân-cộng; (ii)LayerNormloại bỏ phụ thuộc thống kê batch khi triển khai suy luận biênB = 1; và (iii) khối nút cổ chai ngược1x1 -> GELU -> 1x1(mở rộng \(4\times\)) kèm hệ số tầng học được \(\gamma \in \mathbb{R}^C\) (LayerScale) giúp ổn định huấn luyện sâu. -
Vision Transformer (ViT)&DINOv2(2021–2026): Ảnh \(\mathbf{I} \in \mathbb{R}^{H \times W \times C}\) được băm thành \(N = \frac{H \cdot W}{P^2}\) mảnh kích thước \(P \times P\) rồi ghép token phân loại \(\mathbf{x}_{\text{cls}}\) cùng mã hóa vị trí \(\mathbf{E}_{\text{pos}} \in \mathbb{R}^{(N+1) \times D}\). Tự chú ý đa đầu (MHSA) tính tương quan toàn cục giữa mọi cặp mảnh:\[\operatorname{MHSA}(\mathbf{X}) = \operatorname{Concat}(\operatorname{head}_1, \dots, \operatorname{head}_h)\mathbf{W}_O, \qquad \operatorname{head}_m = \operatorname{softmax}\!\left(\frac{\mathbf{Q}_m\mathbf{K}_m^\top}{\sqrt{d_k}}\right)\mathbf{V}_m.\]- Bẫy độ phức tạp bậc hai theo độ phân giải: Chi phí
MHSAlà \(\mathcal{O}(N^2 D + N D^2)\). Khi tăng cạnh ảnh lên \(2\times\) (ví dụ224 -> 448), số mảnh \(N\) tăng \(4\times\) và ma trận chú ý \(N \times N\) phình lên \(16\times\) — đó là lý doViTthuần rất đắt trên ảnh cao tốc1080pnếu không dùng cửa sổ cục bộ (Swin) hoặc tách tương tác tầng sâu (RT-DETR AIFI). DINOv2(Oquab et al., TMLR 2024): Tự chưng cất mức ảnh (DINO) + khôi phục mảnh che (iBOT) + điều chuẩn trải đều KoLeo trên142Mảnh lọc tinh chọn, tạo ra đặc trưng dày (dense features) vượt trội ngay cả khi đóng băng hoàn toàn backbone. Phiên bản có Register Tokens (ICLR 2024) hấp thụ nhiễu nền đỉnh chuẩn cao, làm sạch bản đồ đặc trưng cho phân đoạn và định vị.
- Bẫy độ phức tạp bậc hai theo độ phân giải: Chi phí
-
Thích ứng Tham số Hiệu quả
LoRAchoViT(Transfer Learning 2026): Thay vì cập nhật toàn bộ \(\mathbf{W}_0 \in \mathbb{R}^{d_{\text{out}} \times d_{\text{in}}}\) của phép chiếuQKV, ta đóng băng \(\mathbf{W}_0\) và học cập nhật hạng thấp \(r_{\text{lora}} \ll \min(d_{\text{in}}, d_{\text{out}})\):\[\mathbf{h} = \mathbf{W}_0 \mathbf{x} + \frac{\alpha_{\text{lora}}}{r_{\text{lora}}}\mathbf{B}\mathbf{A}\mathbf{x}, \qquad \mathbf{A} \in \mathbb{R}^{r_{\text{lora}} \times d_{\text{in}}},\; \mathbf{B} \in \mathbb{R}^{d_{\text{out}} \times r_{\text{lora}}},\; \mathbf{B}_{t=0} = \mathbf{0}.\]Tại bước khởi đầu \(t = 0\), \(\Delta\mathbf{W} = \mathbf{B}\mathbf{A} = \mathbf{0}\) đảm bảo đầu ra khớp tuyệt đối với mô hình tiền huấn luyện. Sau huấn luyện, ma trận hợp nhất \(\mathbf{W}_{\text{merged}} = \mathbf{W}_0 + \frac{\alpha_{\text{lora}}}{r_{\text{lora}}}\mathbf{B}\mathbf{A}\) được tính sẵn một lần, mang lại
0 msđộ trễ phụ khi chạyONNX/TensorRT. TrongLab 09(Test 11),MiniViT + LoRA(r = 4) chỉ huấn luyện2,243 / 118,915tham số (1.89%) so với100%của fine-tuning toàn phần!
1.2 Hình học Hộp Giới hạn (IoU -> GIoU -> CIoU), NMS vs Soft-NMS & mAP@50:95#
Cho hai hộp \(B = (x_1, y_1, x_2, y_2)\) và \(B^{\text{gt}}\), ký hiệu \(C\) là hộp bao lồi nhỏ nhất chứa cả hai hộp với đường chéo \(c\), tâm \(\mathbf{b}, \mathbf{b}^{\text{gt}}\) và kích thước \((w, h), (w^{\text{gt}}, h^{\text{gt}})\):
- Ý nghĩa hình học (
Lab 09,Test 02): Với hai hộp không giao nhau,IoU = 0.000bất kể chúng cách nhau12 pxhay120 px(\(\nabla_B \mathcal{L}_{\text{IoU}} = \mathbf{0}\)).GIoUkhôi phục gradient qua diện tích phần trống của hộp bao \(C\) (-0.091gần vs-0.500xa), nhưng khi một hộp nằm lọt bên trong hộp kia thì \(|C \setminus (B \cup B^{\text{gt}})| = 0\) khiếnGIoUthoái hóa vềIoU.CIoUgiải quyết triệt để cả hai trường hợp bằng hạng tử khoảng cách tâm chuẩn hóa và độ nhất quán tỷ lệ khung hình (-0.218gần vs-0.506xa). Greedy NMSvsSoft-NMS(Lab 09,Test 03): Thay vì gán cứng \(s_j \leftarrow 0\) khi \(\operatorname{IoU}(M, b_j) \ge \tau_{\text{nms}}\),Gaussian Soft-NMShạ mềm điểm tin cậy:\[s_j \leftarrow s_j \exp\!\left(-\frac{\operatorname{IoU}(M, b_j)^2}{\sigma_{\text{soft}}}\right).\]Hộp trùng lặp thật sự (\(\operatorname{IoU} \approx 0.87\)) bị triệt tiêu mạnh xuống dưới ngưỡng lọc, trong khi chiếc xe kề làn bị che khuất một phần (\(\operatorname{IoU} \approx 0.56\)) chỉ giảm từ0.81 -> 0.434và được giữ lại.- Tích phân nội suy
101điểm chuẩn COCO (Lab 09,Test 04): Với đường bao Precision đơn điệu giảm \(\tilde{P}_{\tau}(r) = \max_{r' \ge r} P_{\tau}(r')\):\[\operatorname{AP}_{\tau}^{(c)} = \frac{1}{101}\sum_{k=0}^{100}\tilde{P}_{\tau}^{(c)}\!\left(\frac{k}{100}\right), \qquad \operatorname{mAP}_{50:95} = \frac{1}{10|\mathcal{C}|}\sum_{c \in \mathcal{C}}\sum_{m=0}^{9}\operatorname{AP}_{0.50 + 0.05m}^{(c)}.\]Thước đoAP@50dễ dãi với hộp lệch15–20%, cònmAP@50:95phạt rất nặng sai số biên ở các ngưỡng0.75..0.95— yếu tố sống còn để giữ ổn định tâm hộp cho bộ theo dõi Kalman và vạch đếm xe.
1.3 Toán học Theo dõi Đa mục tiêu (MOT): Bộ lọc Kalman 7D, ByteTrack & HOTA#
-
Bộ lọc Kalman Vận tốc Không đổi (
7trạng thái): Mỗi phương tiện được biểu diễn bởi vector \(\mathbf{x}_k = [u, v, s, r, \dot{u}, \dot{v}, \dot{s}]^\top\) (tâm \((u, v)\), diện tích \(s = wh\), tỷ lệ khung hình \(r = w/h\), và các vận tốc tương ứng) với bước thời gian chuẩn hóa \(\Delta t = 1\) khung hình:\[\hat{\mathbf{x}}_{k|k-1} = \mathbf{F}\hat{\mathbf{x}}_{k-1|k-1}, \qquad \mathbf{P}_{k|k-1} = \mathbf{F}\mathbf{P}_{k-1|k-1}\mathbf{F}^\top + \mathbf{Q},\]\[\mathbf{S}_k = \mathbf{H}\mathbf{P}_{k|k-1}\mathbf{H}^\top + \mathbf{R}, \qquad \mathbf{K}_k = \mathbf{P}_{k|k-1}\mathbf{H}^\top\mathbf{S}_k^{-1},\]\[\hat{\mathbf{x}}_{k|k} = \hat{\mathbf{x}}_{k|k-1} + \mathbf{K}_k(\mathbf{z}_k - \mathbf{H}\hat{\mathbf{x}}_{k|k-1}), \qquad \mathbf{P}_{k|k} = (\mathbf{I}_7 - \mathbf{K}_k\mathbf{H})\mathbf{P}_{k|k-1}.\]Khi đối tượng tạm thời khuất bóng trong
3–4khung hình, phaPredictgiúp hộp dự đoán "lướt quán tính" (coasting) bám sát xe thật vớiIoU > 0.85(Lab 09,Test 06). -
Ghép cặp Hai giai đoạn
ByteTrackvsSORT&BoT-SORT:- Giải bài toán gán tối ưu \(\min_{\mathbf{X}} \sum_{i,j} (1 - \operatorname{IoU}(\hat{B}_i, D_j)) X_{ij}\) bằng thuật toán Hungary (
Kuhn–Munkres) trong \(\mathcal{O}(\max(M, N)^3)\). SORT: Chỉ giữ \(\mathcal{D}_{\text{high}} = \{d : s_d \ge \tau_{\text{high}}\}\). Dưới vùng che khuất, điểm tin cậy tụt về~0.26 < 0.55nên quỹ đạo chết yểu và sinh hàng loạtIDSW.ByteTrack(Zhang et al., ECCV 2022): Giai đoạn 1 ghép mọi quỹ đạo với \(\mathcal{D}_{\text{high}}\); Giai đoạn 2 lấy các quỹ đạo còn sót chưa ghép ghép với tập điểm thấp \(\mathcal{D}_{\text{low}} = \{d : \tau_{\text{low}} \le s_d < \tau_{\text{high}}\}\) thuần theoIoU. Điểm then chốt: tuyệt đối không khởi tạo quỹ đạo mới từ \(\mathcal{D}_{\text{low}}\), nhờ đó vừa phục hồi trọn vẹn xe bị che khuất vừa miễn nhiễm với báo giả nền!BoT-SORT: Khi camera gắn trên xe di chuyển hoặc rung gió, bổ sung Global Motion Compensation (GMC) bù dịch chuyển khung hình affine + dung hợp khoảng cách CosineReIDcó cổng lọc.
- Giải bài toán gán tối ưu \(\min_{\mathbf{X}} \sum_{i,j} (1 - \operatorname{IoU}(\hat{B}_i, D_j)) X_{ij}\) bằng thuật toán Hungary (
-
Tại sao
HOTAvượt trộiMOTAvàIDF1(Luiten et al., IJCV 2021):\[\operatorname{MOTA} = 1 - \frac{\sum_t(\text{FN}_t + \text{FP}_t + \text{IDSW}_t)}{\sum_t \text{GT}_t}, \qquad \operatorname{IDF1} = \frac{2\,\text{IDTP}}{2\,\text{IDTP} + \text{IDFP} + \text{IDFN}},\]\[\operatorname{DetA}_\alpha = \frac{|\text{TP}_\alpha|}{|\text{TP}_\alpha| + |\text{FN}_\alpha| + |\text{FP}_\alpha|}, \qquad \operatorname{AssA}_\alpha = \frac{1}{|\text{TP}_\alpha|}\sum_{c \in \text{TP}_\alpha}\frac{|\text{TPA}(c)|}{|\text{TPA}(c)| + |\text{FNA}(c)| + |\text{FPA}(c)|},\]\[\operatorname{HOTA} = \frac{1}{19}\sum_{\alpha \in \{0.05, 0.10, \dots, 0.95\}}\sqrt{\operatorname{DetA}_\alpha \cdot \operatorname{AssA}_\alpha}.\]Khác với
MOTAbị chi phối bởi lỗi phát hiện vàIDF1thiên về định danh,HOTAcân bằng bình đẳng bằng trung bình hình học giữa độ chính xác phát hiện (DetA) và độ chính xác liên kết quỹ đạo (AssA) trên toàn dải ngưỡng định vị0.05..0.95.
1.4 Phân đoạn Toàn cảnh (PQ = SQ * RQ), Mask2Former, SAM 2 & CLIP vs SigLIP#
-
Phân loại Phân đoạn & Đẳng thức Panoptic Quality (Kirillov et al., CVPR 2019):
- Semantic Segmentation (
mIoU): Phân lớp từng pixel, mù trước ranh giới giữa hai cá thể cùng lớp. - Instance Segmentation (
Mask AP): Tách từng vật thể đếm được (thing), bỏ qua vùng nền vô định hình (stuffnhư mặt đường, bầu trời). - Panoptic Segmentation (
PQ): Hợp nhất không chồng lấn cảstuffvàthing. Vì các mặt nạ trong cùng ảnh không giao nhau, theo định lý Kirillov tồn tại tối đa 1 cặp ghép duy nhất có \(\operatorname{IoU}(p, g) > 0.5\):\[\operatorname{PQ} = \underbrace{\frac{\sum_{(p,g) \in \text{TP}} \operatorname{IoU}(p, g)}{|\text{TP}|}}_{\text{Segmentation Quality (SQ)}} \times \underbrace{\frac{|\text{TP}|}{|\text{TP}| + \frac{1}{2}|\text{FP}| + \frac{1}{2}|\text{FN}|}}_{\text{Recognition Quality (RQ)}}.\] Mask2Former(CVPR 2022) thống nhất ba tác vụ bằng Masked Attention (chỉ cho truy vấn chú ý trong vùng tiền cảnh mặt nạ tầng trước).SAM 2(Meta, ICLR 2025) mở rộng phân đoạn theo gợi ý sang video trực tuyến (~44 FPS) nhờ bộ mã hóaHiera+ Ngân hàng Bộ nhớ (Memory Bank) + đầu dự đoán che khuất (occlusion head).
- Semantic Segmentation (
-
Tiền huấn luyện Thị giác–Ngôn ngữ:
CLIP(InfoNCE) vsSigLIP(Pairwise Sigmoid): Cho \(B\) cặp nhúng ảnh–văn bản chuẩn hóa \(L_2\) (\(\mathbf{u}_i, \mathbf{v}_j \in \mathbb{S}^{d-1}\)) và ma trận độ tương đồng \(z_{ij} = \tau_{\text{temp}}\, \mathbf{u}_i^\top \mathbf{v}_j\):\[\mathcal{L}_{\text{CLIP}} = -\frac{1}{2B}\sum_{i=1}^B \left[\ln\frac{\exp(z_{ii})}{\sum_{j=1}^B \exp(z_{ij})} + \ln\frac{\exp(z_{ii})}{\sum_{j=1}^B \exp(z_{ji})}\right],\]\[\mathcal{L}_{\text{SigLIP}} = -\frac{1}{B}\sum_{i=1}^B \sum_{j=1}^B \ln \sigma\!\Big(y_{ij}\big(\tau_{\text{temp}}\,\mathbf{u}_i^\top \mathbf{v}_j + b_{\text{sig}}\big)\Big), \qquad y_{ij} = \begin{cases}+1 & i=j,\\ -1 & i\ne j.\end{cases}\]- Phân tích hệ thống (
Lab 09,Test 12): Dưới cặp ngẫu nhiên không liên kết (\(\mathbf{u}_i^\top \mathbf{v}_j \approx 0\)), mất mátCLIPcó sàn tham chiếu \(\approx \ln B\) (2.468ởB = 4vọt lên4.841ởB = 32) và bắt buộc gom mẫu sốsoftmaxtoàn cục qua mọi GPU (all-gatherkích thước \(B \times B\)).SigLIPloại bỏsoftmaxtoàn cục thành bài toán nhị phân từng cặp kèm độ lệch âm \(b_{\text{sig}} < 0\) (cân bằng \(B\) cặp dương với \(B^2 - B\) cặp âm), giữ hành vi nhất quán cả ở batch nhỏ lẫn mở rộng tới1Mbatch mà không phình bộ nhớ nút cổ chai.
- Phân tích hệ thống (
1.5 CNN trong Nghệ thuật, Siêu phân giải & Khuếch tán Chỉnh sửa Ảnh (R45)#
- Chuyển đổi Phong cách Thần kinh (
Neural Style Transfer, Gatys et al. 2016): Trích đặc trưng \(\mathbf{F}^{(l)} \in \mathbb{R}^{C_l \times (H_l W_l)}\) từ tầng sâu của mạng CNN tiền huấn luyện. Nội dung được bảo toàn bằngMSEtrên \(\mathbf{F}^{(l)}\), còn phong cách (kết cấu, nét cọ bất biến vị trí) được nắm bắt qua Ma trận Gram \(G_{ij}^{(l)} = \sum_{k=1}^{H_l W_l} F_{ik}^{(l)} F_{jk}^{(l)}\) tối ưu \(\mathcal{L}_{\text{NST}} = \alpha_{\text{c}}\mathcal{L}_{\text{content}} + \beta_{\text{s}}\mathcal{L}_{\text{style}}\). - Siêu phân giải (
Super-Resolution) & Khuếch tán Chỉnh sửa Ảnh (Diffusion Editing):MSE/PSNRthuần túy tạo ảnh mờ do lấy trung bình các kết cấu tần số cao; các mô hình SOTA kết hợp Perceptual Loss, SwinIR/ESRGAN hoặc Latent Diffusion / Rectified Flow + ControlNet (điều kiện hóa theo mặt nạSAM 2hoặc biênCanny) để tái tạo chi tiết sắc nét.- Cảnh báo An toàn Pháp lý & Công nghiệp: Tuyệt đối không dùng siêu phân giải sinh ảnh (
Generative SR/Diffusion) để đọc biển số xe phạt nguội hoặc chẩn đoán X-quang y tế! Mô hình khuếch tán tối ưu độ hợp lý thống kê theo phân phối tiên nghiệm nên có thể bịa đặt (hallucinate) chữ số biển số hoặc nốt tổn thương cực kỳ sắc nét nhưng sai sự thật.
Trụ cột 2 — Kiến trúc Hệ thống Sản xuất: Giao thông Thông minh 30 FPS & Phân đoạn Mở#
2.1 Kiến trúc Đường ống Biên ITS Đạt Chuẩn < 33.3 ms/frame (30 FPS)#
2.2 Ngân sách Độ trễ, Bộ nhớ, Chiến lược Xử lý Sự cố & Cổng An toàn#
| Thành phần Đường ống Biên | Ngân sách SLA (30 FPS) |
Đo thực tế Lab 09 (ORT CPU) |
Chế độ Lỗi & Cơ chế Phòng vệ (Mitigation) |
|---|---|---|---|
| Giải mã + Tiền xử lý | <= 5.0 ms |
Chuỗi tensor 64x64 sẵn sàng |
Tràn bộ đệm RTSP -> bật chính sách drop-oldest-frame giữ độ trễ tươi (freshness) |
Backbone / Detector (ONNX) |
<= 18.0 ms |
0.52 ms (p50) / 0.63 ms (p95) |
PyTorch 2.15 sập thiếu onnxscript -> khóa dynamo=False + test parity < 1e-4 |
Theo dõi ByteTrack |
<= 3.0 ms |
< 1.0 ms/frame (16 xe) |
Mất ID dưới bóng cầu vượt -> ghép Giai đoạn 2 \(\mathcal{D}_{\text{low}}\), không spawn từ \(\mathcal{D}_{\text{low}}\) |
Vạch đếm Tripwire |
<= 1.0 ms |
< 0.1 ms/frame |
Xe dừng đèn đỏ rung lắc qua vạch -> tập counted_track_ids bất biến + dấu hướng down/up |
| Lưu trữ Trọng số | Nạp < 50 ms |
safetensors 182 KB, diff = 0.0 |
RCE chuỗi cung ứng pickle (CWE-502) -> cấm tuyệt đối bằng AST guard (Test 01) |
Dự phòng Biến động (Headroom) |
>= 6.3 ms |
Dư > 31 ms trên biên |
Tự động kích hoạt giám sát p95 > 28 ms & lùi cấu hình phân giải đầu vào |
2.3 Kiến trúc Phân đoạn Nền tảng & Kiểm kê Từ vựng Mở (SAM 2 + SigLIP)#
2.4 Bảng Quyết định Kiến trúc Sản xuất (Production Decision Playbook)#
| Bài toán / Ràng buộc Thực tế | Lựa chọn Khuyến nghị 2026 | Lý do Kỹ thuật & Giới hạn Cần Tránh |
|---|---|---|
Camera tĩnh biên CPU/Jetson cần >= 30 FPS |
YOLO11s / RT-DETR-R18 (ONNX/TRT) + ByteTrack |
RT-DETR loại bỏ NMS khi kẹt xe dày đặc; ByteTrack miễn phí ReID mà vẫn cứu che khuất |
| Camera gắn trên xe / drone rung lắc mạnh | RT-DETR + BoT-SORT (GMC + ReID) |
Kalman thuần giả sử nền tĩnh sẽ lệch khi camera xoay -> bắt buộc có bù chuyển động GMC |
Miền chuyên biệt ít nhãn (< 5,000 ảnh) |
DINOv2 đóng băng + LoRA (r = 4..8) |
Giữ đặc trưng dày tổng quát, chỉ huấn luyện < 5% tham số, gộp phẳng 0 ms suy luận |
Kiểm kê 50,000+ SKU thay đổi liên tục |
SAM 2 + SigLIP + Vector DB |
Không huấn luyện lại detector đóng lớp; SigLIP ổn định trên mọi kích thước batch |
| An toàn xe tự hành tách người đi bộ kề nhau | Mask2Former + cổng nghiệm thu PQ_things |
Tuyệt đối không chỉ kiểm tra Semantic mIoU vì mIoU = 1.0 vẫn lọt lỗi gộp cá thể |
2.5 Mẹo Công nghiệp SOTA 2025–2026: Làn sóng Thị giác Nền tảng (DINOv3, SAM 3, RF-DETR, YOLOv12, SigLIP 2) & Tối ưu FlashAttention/MLA/YaRN (Principal Tip #3b)#
Trong các hệ thống thị giác hiện đại 2025–2026, làn sóng mô hình mới đã dịch chuyển chuẩn mực sản xuất từ DINOv2/SAM 2/YOLOv8–11/SigLIP sang bộ năm kiến trúc biên giới — đồng thời vẫn chịu sự chi phối của các giới hạn phần cứng ở tầng Attention và bộ nhớ:
- Bộ Ngũ Kiến trúc Thị giác SOTA 2025–2026 (
DINOv3,SAM 3,RF-DETR,YOLOv12,SigLIP 2) & Đánh đổi Triển khai:DINOv3(Meta AI): Mở rộng học tự giám sát lên quy mô tỷ ảnh với cơ chế giữ độ sắc nét đặc trưng không gian dày (Gram anchoring chống suy thoái biểu diễn cục bộ khi huấn luyện kéo dài), trở thành xương sống đóng băng (+ LoRA) vượt trội cho phân đoạn dày và phát hiện ít nhãn (< 5,000ảnh).SAM 3(Meta AI): Chuyển từ phân đoạn theo điểm/hộp (SAM 2) sang phân đoạn khái niệm từ vựng mở (Promptable Concept Segmentation), cho phép định vị, theo dõi và phân đoạn mọi thực thể khớp khái niệm văn bản hoặc ảnh mẫu trên ảnh và video mà không cần đóng tập lớp; tuy nhiên vẫn cần kiểm soát kích thước kho nhớ video để không vượt trần33.3 ms/frame.RF-DETRvs.YOLOv12(Phát hiện Thời gian thực):YOLOv12đưa thiết kế chú ý cục bộ làm trung tâm (Area Attention+R-ELAN) vào dòng YOLO tốc độ cao để nâng trầnmAPlên trên CNN thuần, nhưng có thể gặp chi phí biên dịch/bộ nhớ cao hơn trên chip biên đời cũ; ngược lại,RF-DETRkế thừa backbone tự giám sát kiểuDINOv2và bộ giải mã DETR đa tỷ lệ loại bỏ hoàn toànNMS, giữ ổn định khi vật thể chen chúc chồng lấn mà vẫn đạt tốc độ thời gian thực.SigLIP 2(Google): Kết hợp học đối chiếu sigmoid với mất mát tự giám sát + sinh chú thích và hỗ trợ đa ngôn ngữ lẫn tỷ lệ khung hình gốc (native aspect ratio), nâng độ chính xác truy xuất vùng cắt đa kích thước từSAM 3/RF-DETRvào Vector DB vượt trộiCLIPvàSigLIPthế hệ đầu.
FlashAttentionIO-Awareness & Định tuyến Kênh Ngắn (SRAM Tiling): Tính \(\operatorname{softmax}(\mathbf{Q}\mathbf{K}^\top/\sqrt{d_k})\mathbf{V}\) theo kiểu truyền thống buộc ghi/đọc ma trận điểm chú ý \(\mathcal{O}(N^2)\) xuống DRAM/HBM — biến lớp chú ý thành memory-bound ở1080p(N = 4,096–16,384patch tokens).FlashAttentiongiữ khốiQ_i, K_j, V_jtrong SRAM và cộng dồn bộ chuẩn hóa softmax trực tuyến (rescaling running max), cắt HBM traffic theo \(\mathcal{O}(N)\). Lỗi hay gặp: nối mặt nạ che (SAM 2/SAM 3/Mask2Formerattention mask) dạng tensorfloatdày tùy biến ép PyTorch tắt Flash kernel, làm tốc độ tụt xuống< 10 FPSvà tăng đột ngột VRAM đỉnh.- Nén
KV / Memory Bank:GQAvs.DeepSeek MLA(Multi-head Latent Attention): Khi theo dõi video dài hàng nghìn khung trong bộ nhớSAM 2/SAM 3hay suy luận VLM đa ảnh, giữKVđầy đủ kiểuMHAngốn hàng chục GB.GQAgiảm số đầuKVxuống \(h_{\text{kv}} \ll h_q\) (4–8xtiết kiệm), nhưng khi nén quá mạnh vềMQA(\(h_{\text{kv}}=1\)) độ sắc nét định vị vật nhỏ bị suy giảm.DeepSeek MLAnén cặpKVchung về một vector ẩn chiều thấp \(\mathbf{c}_t^{KV} = W^{DKV}\mathbf{h}_t\) (\(d_c \ll n_h d_h\)) kết hợp DecoupledRoPE: lúc giải mã, ma trận khôi phục \(W^{UK}\) và \(W^{UV}\) được hấp thụ đại số thẳng vào phép chiếuQvà đầu raO(weight absorption), vừa cắt85%–93%bộ nhớKVnhưMQAvừa giữ năng lực biểu diễn ngangMHA. - Mở rộng Độ phân giải (
2D RoPE + YaRN) & BẫyRegister/SinkTokens Khi Lượng tử hóa: Khi suy luận ở độ phân giải hoặc chuỗi khung video dài gấp \(4\times\text{–}8\times\) lúc huấn luyện (\(N_{\text{test}} > N_{\text{train}}\)),YaRNchia phổ tầnNTK-by-partsbảo toàn dải tần số cao cục bộ và hiệu chỉnh nhiệt độ chú ý \(\sqrt{1/t}\). Đồng thời, khi épKV-CachexuốngINT8/FP8, cácRegister Tokens(DINOv2/DINOv3) vàattention sinksthường mang chuẩn biên độ gấp10–30xcác patch bình thường — bắt buộc lượng tử hóa theo kênh (per-channeltrênK) / theo token (per-tokentrênV) hoặc giữ nguyên nhóm token neo ởFP16/BF16để không làm mất bit độ phân giải của toàn bộ khung hình.
Trụ cột 3 — Công nghệ 2026 & Mã nguồn Chạy được (Lab 09 — modern_cv_tracking_lab)#
Toàn bộ thuật toán trong chương này được cài đặt sạch, gõ kiểu tĩnh đầy đủ (mypy src 0 lỗi, ruff check 0 lỗi) và chạy 100% ngoại tuyến trong gói modern_cv_tracking_lab. Dưới đây là các trích đoạn cốt lõi trích thẳng từ mã nguồn đã vượt qua 16/16 bài kiểm thử:
3.1 Ghép cặp Hai giai đoạn ByteTrack (Phục hồi Xe Che khuất không Sinh Báo giả)#
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from numpy.typing import NDArray
from scipy.optimize import linear_sum_assignment
@dataclass(frozen=True, slots=True)
class DetectedBox:
box: tuple[float, float, float, float]
score: float
class_id: int = 0
def _xyxy_to_z(box: tuple[float, float, float, float]) -> NDArray[np.float64]:
x1, y1, x2, y2 = box
w, h = max(1.0, x2 - x1), max(1.0, y2 - y1)
return np.array([x1 + 0.5 * w, y1 + 0.5 * h, w * h, w / h], dtype=np.float64)
def _z_to_xyxy(state: NDArray[np.float64]) -> tuple[float, float, float, float]:
u, v, s, r = float(state[0]), float(state[1]), max(16.0, float(state[2])), float(np.clip(state[3], 0.2, 5.0))
w = float(np.sqrt(s * r))
h = s / max(w, 1e-6)
return (u - 0.5 * w, v - 0.5 * h, u + 0.5 * w, v + 0.5 * h)
def _compute_iou_matrix(
boxes_a: list[tuple[float, float, float, float]],
boxes_b: list[tuple[float, float, float, float]],
) -> NDArray[np.float64]:
a = np.asarray(boxes_a, dtype=np.float64)
b = np.asarray(boxes_b, dtype=np.float64)
x1 = np.maximum(a[:, None, 0], b[None, :, 0])
y1 = np.maximum(a[:, None, 1], b[None, :, 1])
x2 = np.minimum(a[:, None, 2], b[None, :, 2])
y2 = np.minimum(a[:, None, 3], b[None, :, 3])
inter = np.maximum(0.0, x2 - x1) * np.maximum(0.0, y2 - y1)
area_a = np.maximum(0.0, a[:, 2] - a[:, 0]) * np.maximum(0.0, a[:, 3] - a[:, 1])
area_b = np.maximum(0.0, b[:, 2] - b[:, 0]) * np.maximum(0.0, b[:, 3] - b[:, 1])
return np.asarray(inter / np.maximum(area_a[:, None] + area_b[None, :] - inter, 1e-9), dtype=np.float64)
def _hungarian_iou_match(
track_boxes: list[tuple[float, float, float, float]],
det_boxes: list[tuple[float, float, float, float]],
iou_threshold: float,
) -> tuple[list[tuple[int, int]], list[int], list[int]]:
if not track_boxes or not det_boxes:
return [], list(range(len(track_boxes))), list(range(len(det_boxes)))
iou_mat = _compute_iou_matrix(track_boxes, det_boxes)
row_ind, col_ind = linear_sum_assignment(1.0 - iou_mat)
matches, matched_t, matched_d = [], set(), set()
for r, c in zip(row_ind.tolist(), col_ind.tolist(), strict=True):
if float(iou_mat[r, c]) >= iou_threshold:
matches.append((r, c))
matched_t.add(r)
matched_d.add(c)
return (
matches,
[i for i in range(len(track_boxes)) if i not in matched_t],
[j for j in range(len(det_boxes)) if j not in matched_d],
)
class KalmanBoxTracker:
"""7-state constant-velocity Kalman tracker [u, v, s, r, u_dot, v_dot, s_dot]."""
def __init__(self, initial_box: tuple[float, float, float, float], track_id: int, class_id: int) -> None:
self.track_id = track_id
self.class_id = class_id
self.F = np.eye(7, dtype=np.float64)
self.F[0, 4] = self.F[1, 5] = self.F[2, 6] = 1.0
self.H = np.eye(4, 7, dtype=np.float64)
self.R = np.diag([2.0, 2.0, 25.0, 0.05]).astype(np.float64)
self.Q = np.diag([1.0, 1.0, 10.0, 0.01, 0.25, 0.25, 1.0]).astype(np.float64)
self.P = np.diag([10.0, 10.0, 40.0, 0.2, 200.0, 200.0, 200.0]).astype(np.float64)
self.x = np.zeros(7, dtype=np.float64)
self.x[:4] = _xyxy_to_z(initial_box)
self.time_since_update = 0
def predict(self) -> tuple[float, float, float, float]:
if self.x[2] + self.x[6] <= 16.0:
self.x[6] = 0.0
self.x = self.F @ self.x
self.P = self.F @ self.P @ self.F.T + self.Q
self.time_since_update += 1
return _z_to_xyxy(self.x)
def update(self, box: tuple[float, float, float, float]) -> None:
z = _xyxy_to_z(box)
s_mat = self.H @ self.P @ self.H.T + self.R
k_gain = self.P @ self.H.T @ np.linalg.inv(s_mat)
self.x = self.x + k_gain @ (z - self.H @ self.x)
self.P = (np.eye(7, dtype=np.float64) - k_gain @ self.H) @ self.P
self.time_since_update = 0
class ByteTrackTracker:
"""Two-stage BYTE tracker matching high-score first, then low-score occlusion recovery."""
def __init__(
self,
high_conf_thresh: float = 0.55,
low_conf_thresh: float = 0.15,
stage1_iou_threshold: float = 0.25,
stage2_iou_threshold: float = 0.20,
max_age: int = 3,
) -> None:
self.high_conf_thresh = high_conf_thresh
self.low_conf_thresh = low_conf_thresh
self.stage1_iou_threshold = stage1_iou_threshold
self.stage2_iou_threshold = stage2_iou_threshold
self.max_age = max_age
self._next_id = 1
self._tracks: list[KalmanBoxTracker] = []
def step(self, detections: list[DetectedBox]) -> list[int]:
high_dets = [d for d in detections if d.score >= self.high_conf_thresh]
low_dets = [d for d in detections if self.low_conf_thresh <= d.score < self.high_conf_thresh]
pred_boxes = [trk.predict() for trk in self._tracks]
# Stage 1: match all active tracks against high-confidence boxes (>= 0.55)
matches1, rem_track_idxs, unmatched_high = _hungarian_iou_match(
pred_boxes, [d.box for d in high_dets], iou_threshold=self.stage1_iou_threshold
)
for t_idx, d_idx in matches1:
self._tracks[t_idx].update(high_dets[d_idx].box)
# Stage 2: recover remaining tracks against low-confidence boxes [0.15, 0.55)
if rem_track_idxs and low_dets:
rem_pred_boxes = [pred_boxes[i] for i in rem_track_idxs]
matches2, _, _ = _hungarian_iou_match(
rem_pred_boxes, [d.box for d in low_dets], iou_threshold=self.stage2_iou_threshold
)
for local_t, d_idx in matches2:
self._tracks[rem_track_idxs[local_t]].update(low_dets[d_idx].box)
# Spawn tracks ONLY from unmatched high-confidence detections (immune to low-score FP)
for d_idx in unmatched_high:
d = high_dets[d_idx]
self._tracks.append(KalmanBoxTracker(d.box, track_id=self._next_id, class_id=d.class_id))
self._next_id += 1
self._tracks = [t for t in self._tracks if t.time_since_update <= self.max_age]
return [t.track_id for t in self._tracks if t.time_since_update == 0]
if __name__ == "__main__":
tracker = ByteTrackTracker()
observed_ids: list[list[int]] = []
# Vehicle moves linearly dx=+12/frame; frames 2-3 occluded (score drops to 0.25) + static low-score noise
scores = [0.85, 0.84, 0.26, 0.24, 0.86, 0.88]
for f, sc in enumerate(scores):
x = 20.0 + 12.0 * f
dets = [
DetectedBox(box=(x, 40.0, x + 50.0, 90.0), score=sc, class_id=0),
DetectedBox(box=(220.0, 120.0, 260.0, 160.0), score=0.22, class_id=0), # Low-score FP
]
observed_ids.append(tracker.step(dets))
assert observed_ids == [[1], [1], [1], [1], [1], [1]], f"Unexpected IDs: {observed_ids}"
print("ByteTrack 2-stage occlusion recovery verified:", observed_ids)
3.2 LoRALinear, CLIP InfoNCE vs SigLIP Sigmoid & Xuất ONNX (dynamo=False)#
from __future__ import annotations
import math
import tempfile
from pathlib import Path
import numpy as np
import onnx
import onnxruntime as ort
import torch
import torch.nn as nn
import torch.nn.functional as F
class LoRALinear(nn.Module):
"""Low-Rank Adaptation wrapper: y = W_0 x + (alpha / r) B A x with B=0 init."""
def __init__(self, base_linear: nn.Linear, rank: int = 4, alpha: float = 8.0) -> None:
super().__init__()
self.base = base_linear
self.scaling = alpha / float(rank)
self.lora_a = nn.Parameter(torch.empty(rank, base_linear.in_features))
self.lora_b = nn.Parameter(torch.zeros(base_linear.out_features, rank))
nn.init.kaiming_uniform_(self.lora_a, a=math.sqrt(5.0))
for p in self.base.parameters():
p.requires_grad = False
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.base(x) + F.linear(F.linear(x, self.lora_a), self.lora_b) * self.scaling
def clip_infonce_loss(
image_embeds: torch.Tensor, text_embeds: torch.Tensor, logit_scale: float = 10.0
) -> torch.Tensor:
u = F.normalize(image_embeds, p=2, dim=-1)
v = F.normalize(text_embeds, p=2, dim=-1)
logits = logit_scale * torch.matmul(u, v.transpose(0, 1))
targets = torch.arange(logits.shape[0], device=logits.device, dtype=torch.long)
return 0.5 * (F.cross_entropy(logits, targets) + F.cross_entropy(logits.transpose(0, 1), targets))
def siglip_sigmoid_loss(
image_embeds: torch.Tensor,
text_embeds: torch.Tensor,
logit_scale: float = 10.0,
logit_bias: float = -5.0,
) -> torch.Tensor:
u = F.normalize(image_embeds, p=2, dim=-1)
v = F.normalize(text_embeds, p=2, dim=-1)
b = u.shape[0]
logits = logit_scale * torch.matmul(u, v.transpose(0, 1)) + logit_bias
labels = 2.0 * torch.eye(b, device=logits.device, dtype=logits.dtype) - 1.0
return F.softplus(-labels * logits).sum() / float(b)
def export_onnx_and_verify_parity(model: nn.Module, onnx_path: Path) -> float:
model_eval = model.eval()
sample = torch.randn(1, 32, generator=torch.Generator().manual_seed(42))
with torch.no_grad():
pt_out = model_eval(sample).numpy()
torch.onnx.export(
model_eval,
(sample,),
str(onnx_path),
input_names=["features"],
output_names=["logits"],
opset_version=17,
dynamo=False,
)
onnx.checker.check_model(onnx.load(str(onnx_path)))
sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
ort_out = np.asarray(sess.run(["logits"], {"features": sample.numpy()})[0], dtype=np.float32)
return float(np.max(np.abs(pt_out - ort_out)))
if __name__ == "__main__":
torch.manual_seed(42)
base = nn.Linear(32, 16)
lora_layer = LoRALinear(base, rank=4, alpha=8.0)
x = torch.randn(4, 32)
assert torch.allclose(base(x), lora_layer(x), atol=1e-6), "Zero-delta B=0 init must match base!"
trainable = sum(p.numel() for p in lora_layer.parameters() if p.requires_grad)
total = sum(p.numel() for p in lora_layer.parameters())
assert trainable == 4 * 32 + 16 * 4 and trainable < total
img = torch.eye(4, 16)
txt = torch.eye(4, 16)
l_clip = float(clip_infonce_loss(img, txt).item())
l_siglip = float(siglip_sigmoid_loss(img, txt).item())
assert l_clip < math.log(4.0) and l_siglip > 0.0
model = nn.Sequential(lora_layer, nn.GELU(), nn.Linear(16, 3))
with tempfile.TemporaryDirectory() as tmpdir:
max_diff = export_onnx_and_verify_parity(model, Path(tmpdir) / "lora_head.onnx")
assert max_diff < 1e-4, f"ONNX parity drift too high: {max_diff}"
print(f"LoRA+VLM+ONNX verified: clip={l_clip:.4f}, siglip={l_siglip:.4f}, ort_diff={max_diff:.2e}")
Trụ cột 4 — Kết quả Thực nghiệm Lab 09 & Bảng Kiểm Nghiệm Chống Rò rỉ#
Chạy lệnh sau tại labs/lab-09-realtime-vehicle-detection-tracking-counting/ để tái lập chính xác mọi con số trong artifacts/ch17_lab09_results.json:
D:\FSDS-SOTA-Curriculum\.venv\Scripts\python.exe scripts/run_lab_demo.py --seed 42 --frames 100
D:\FSDS-SOTA-Curriculum\.venv\Scripts\python.exe -m pytest -p no:cacheprovider -v
4.1 Bảng Tổng hợp Số liệu Thực nghiệm Đã Kiểm định (seed = 42, 100 khung, 16 xe)#
| Hạng mục Đánh giá | Đối chứng Baseline | Giải pháp SOTA 2026 | Chênh lệch & Cổng Nghiệm thu (Pytest) |
|---|---|---|---|
Hình học Hộp Rời nhau (Test 02) |
IoU: 0.000 vs 0.000 |
GIoU: -0.091 vs -0.500; CIoU: -0.218 vs -0.506 |
Khôi phục gradient khoảng cách rõ ràng (PASS) |
Làn Xe Đông (IoU = 0.56) (Test 03) |
Greedy NMS: giữ 1 xe |
Soft-NMS: giữ 2 xe (0.81 -> 0.434) |
Bảo toàn xe kề bị che khuất (PASS) |
COCO Detector (100 khung) (Test 04) |
Cắt sớm >= 0.55: AP@50 = 0.739, mAP = 0.684 |
Đủ phát hiện: AP@50 = 0.999, mAP@50:95 = 0.902 |
Cắt ngưỡng sớm đánh mất 26% AP (PASS) |
MOT Cao tốc Che khuất (Test 07) |
SORT: MOTA 0.608, IDF1 0.422, HOTA 0.414, IDSW 29 |
ByteTrack: MOTA 0.966, IDF1 0.983, HOTA 0.934, IDSW 0 |
+0.520 HOTA, giảm trọn -29 IDSW (PASS) |
Đếm Xe Vạch y = 242 (Test 08) |
SORT: 0D / 8U (50.0%, MAE 4.0) |
ByteTrack: 8D / 8U (100.0%, MAE 0.0) |
Không bỏ sót & 0 đếm trùng (PASS) |
Phân đoạn Toàn cảnh (Test 09) |
Ca gộp 2 xe: mIoU = 1.000, Car PQ = 0.400, PQ_things = 0.700 |
Phân tách sạch: mIoU = 0.959, Car PQ = 0.917, PQ = 0.940 |
Đẳng thức PQ == SQ * RQ (< 1e-12, PASS) |
PEFT MiniViT + LoRA (Test 11) |
Fine-tune toàn phần: 116,867 (100.0%) |
LoRA r = 4 QKV: 2,243 / 118,915 (1.89%) |
< 15% tham số, khởi tạo B = 0 (PASS) |
CLIP vs SigLIP (Test 12) |
CLIP ngẫu nhiên: 2.468 (B=4) -> 4.841 (B=32) |
SigLIP ngẫu nhiên: 5.514 (B=4) -> 5.864 (B=32) |
Tách rời phụ thuộc softmax batch (PASS) |
Đóng gói & Suy luận Biên (Tests 13–14) |
PyTorch FP32 chưa đóng gói |
safetensors 0.0; ONNX (dynamo=False) ORT CPU 0.52 ms (~1,940 FPS), diff 1.3e-07 |
Đạt chuẩn < 33.3 ms (30 FPS) & < 1e-4 (PASS) |
4.2 Danh sách Kiểm tra Đánh giá Chống Rò rỉ & Độ tin cậy Thị giác (Vision Anti-Leakage Checklist)#
- Tách tập theo
Video-ID / Camera-ID / Ngày(Không tách ngẫu nhiên theo khung hình): Hai khung hình cách nhau33 msgần như giống hệt nhau; tách ngẫu nhiên khung hình tạo ảo giácmAP > 0.98nhưng sụp đổ khi chuyển sang góc camera hoặc điều kiện thời tiết mới. - Bắt buộc báo cáo song song
DetA&AssA(HOTA) cùngIDSW: Không chỉ nhìnMOTAhaycounting_accuracyở vạch đếm thuận lợi. - Không đánh giá phân đoạn an toàn chỉ bằng
Semantic mIoU: Luôn đặt cổng nghiệm thuPQ_thingsvàMask APcho các lớp đối tượng di động (thing). - Kiểm định sai lệch số học sau biên dịch (
ONNX/TensorRT/INT8): Mọi bản phát hành biên phải kiểm tramax_abs_diff < 1e-4và độ trễp95 < 33.3 mstrên phần cứng đích.
Trụ cột 5 — Danh mục Tài liệu SOTA & Bài tập Chuyên sâu (Mastery Exercises)#
5.1 Danh mục Công trình Kinh điển & Đột phá 2021–2026#
- Liu et al. (CVPR 2022) — A ConvNet for the 2020s (
ConvNeXt): Chứng minh kiến trúc thuần CNN hiện đại hóa (7x7depthwise,LayerNorm,GELU) cạnh tranh ngang ngửaSwin Transformermà giữ tính đơn giản khi triển khai biên. - Oquab et al. (TMLR 2024) — DINOv2: Learning Robust Visual Features without Supervision & Darcet et al. (ICLR 2024) — Vision Transformers Need Registers: Chuẩn mực tự giám sát thị giác dày cho phân đoạn, độ sâu và
PEFT/LoRA. - Zhao et al. (CVPR 2024) — DETRs Beat YOLOs on Real-time Object Detection (
RT-DETR): Phá bỏ nút cổ chaiNMSbằng bộ mã hóa laiAIFI+CCFMvà ghép cặp Hungary đầu-cuối trong ngân sách thời gian thực. - Zhang et al. (ECCV 2022) — ByteTrack: Multi-Object Tracking by Associating Every Detection Box & Luiten et al. (IJCV 2021) — HOTA: A Higher Order Metric for Evaluating Multi-Object Tracking: Nền tảng chuẩn mực của hệ thống
MOTvà thước đo cân bằngDetA/AssA. - Ravi et al. (ICLR 2025) — SAM 2: Segment Anything in Images and Videos & Zhai et al. (ICCV 2023) — Sigmoid Loss for Language Image Pre-Training (
SigLIP): Định hình thế hệ mô hình nền tảng phân đoạn video theo bộ nhớ và thị giác–ngôn ngữ tách rời kích thước batch.
5.2 Sáu Bài tập Thực hành & Chứng minh (ex1..ex6)#
Mỗi bài tập tương ứng trực tiếp với hệ thống gợi ý từng bước (
exercise_guides) và câu hỏi trắc nghiệm tương tác (q1..q8) ở cuối trang.
- Bài tập 1 (
15%) — Chứng minh Hình họcIoU/GIoU/CIoU& Kiểm chứngGreedy NMSvsSoft-NMS: Chứng minh miền giá trị \(\operatorname{GIoU} \in (-1, 1]\), chỉ ra cấu hình hình học nơiGIoUsuy biến vềIoUnhưngCIoUvẫn tạo gradient khác0, sau đó kiểm nghiệm trêndetection_metrics.py(Tests 02–04) rằngSoft-NMSgiữ được cả2xe ởIoU = 0.56trong khiGreedy NMSxóa nhầm xe kề. Tiêu chí chấm: Chứng minh chặt miền giá trị & giải thích đúng vai trò tỷ lệ khung hình \(v\) (8%), tái lập chính xácGIoU/CIoUvàSoft-NMS(7%). - Bài tập 2 (
15%) — Độ phức tạpViT, So sánhConvNeXtvsViT& Thiết kếLoRAKhông Độ trễ Phụ: Chứng minh chi phíMHSAtăng \(16\times\) khi cạnh ảnh tăng \(2\times\), tính chính xác số tham số huấn luyện củaLoRALineartheo \((d_{\text{in}}, d_{\text{out}}, r_{\text{lora}})\), và giải thích tại sao khởi tạo \(\mathbf{B} = \mathbf{0}\) cùng phép gộp \(\mathbf{W}_{\text{merged}}\) là bắt buộc trong sản xuất. Kiểm chứng bằngMiniConvNeXt&MiniViT(use_lora=True)(Tests 10–11). Tiêu chí chấm: Công thức FLOPs & tham số chính xác (8%), xác minh1.89% < 15%và gradient cập nhật đúng (7%). - Bài tập 3 (
20%) — Bộ lọc Kalman 7D, Thuật toán Hungary & Giải phẫu Ưu thếByteTrackvsSORT: Viết tường minh ma trận chuyển trạng thái \(\mathbf{F} \in \mathbb{R}^{7\times 7}\), phân tích lý doSORTchịu29 IDSWvà bỏ sót toàn bộ8xe đi xuống tạiy = 242trongLab 09, đồng thời giải thích vì saoByteTracktuyệt đối không được phép khởi tạo quỹ đạo mới từ tập \(\mathcal{D}_{\text{low}}\). Kiểm chứng quaTests 05–08. Tiêu chí chấm: Phân tích đúng phương trình dự báo/cập nhật Kalman (10%), chứng minh thực nghiệmHOTA 0.414 -> 0.934,IDSW 29 -> 0,Counting Acc 50% -> 100%(10%). - Bài tập 4 (
15%) — Chứng minh Định lý Ghép Duy nhấtIoU > 0.5& Phân rãPQ = SQ * RQ: Chứng minh bằng phản chứng rằng với hai tập mặt nạ không chồng lấn, mỗi mặt nạ ground truth chỉ có thể ghép với tối đa một mặt nạ dự đoán có \(\operatorname{IoU} > 0.5\). Sử dụngsegmentation_metrics.py(Test 09) giải thích ca thất bại khiSemantic mIoU = 1.000nhưngCar PQtụt từ0.917 -> 0.400. Tiêu chí chấm: Chứng minh phản chứng chặt chẽ (8%), phân tích định lượngSQvsRQkhi gộp/tách mặt nạ (7%). - Bài tập 5 (
15%) — Đối chiếu Toán họcCLIP InfoNCEvsSigLIP Sigmoid& Đạo đức Siêu phân giải Sinh ảnh: Tính giá trị kỳ vọng của \(\mathcal{L}_{\text{CLIP}}\) dưới cặp ngẫu nhiên theo \(B\) (\(\approx \ln B\)), giải thích vai trò tham số độ lệch âm \(b_{\text{sig}} < 0\) trongSigLIP, và xây dựng quy trình kỹ thuật kết hợpSAM 2 + SigLIPcho kho50,000 SKUkèm phân tích rủi ro pháp lý củaDiffusion Super-Resolution. Kiểm chứng trênTest 12. Tiêu chí chấm: Dẫn xuấtCLIP/SigLIPđúng (8%), thiết kế kiến trúc & đánh giá rủi ro chặt chẽ (7%). - Bài tập 6 (
20%) — Đóng gói Chuỗi cung ứng An toàn (safetensors) & Tối ưu BiênONNX(dynamo=False)< 33.3 ms: Giải thích rủi roCWE-502củapickle, cơ chế bẫydynamo=Truekhi thiếuonnxscripttrênPyTorch 2.15+cpu, lập bảng phân bổ ngân sách33.3 mscho hệ thốngITS30 FPS, và chạy trọn bộ nghiệm thurun_lab_demo.py,ruff,mypy,16/16 pytest(Tests 01, 13–16). Tiêu chí chấm: Bảng ngân sách SLA & phân tích bảo mật đầy đủ (10%), xác minhsafetensors diff = 0.0,ONNX diff < 1e-4,p95 < 33.3 msvà16/16bài test xanh (10%).
Occluded Highway MOT Accuracy: SORT vs ByteTrack (Higher is Better)
Directional Tripwire Vehicle Counting Accuracy (16 Highway Vehicles)
Why Semantic mIoU Hides Merged Instances vs Panoptic Quality (PQ)
ONNX Runtime CPU Edge Latency vs 30 FPS Real-Time Budget (33.3 ms)
Detection Geometry (IoU/GIoU/CIoU), NMS vs Soft-NMS & COCO mAP
| Metric / Method | Condition | Observed Value | Insight |
|---|---|---|---|
| IoU (Disjoint Near vs Far) | Non-overlapping boxes | 0.000 vs 0.000 | Zero gradient plateau |
| GIoU (Disjoint Near vs Far) | Non-overlapping boxes | -0.091 vs -0.500 | Smooth enclosing-box gradient |
| CIoU (Disjoint Near vs Far) | Center + aspect penalty | -0.218 vs -0.506 | Faster geometric convergence |
| Greedy NMS vs Soft-NMS | Crowded lane (IoU=0.56) | Greedy kept 1 | Soft kept 2 | Soft-NMS saves occluded neighbor |
| COCO AP@50 & mAP@50:95 | All dets vs High-conf >=0.55 | AP@50 0.999->0.739 | mAP 0.902 | Occlusion drops recall if cut early |
Multi-Object Tracking & Directional Tripwire Counting (100 Frames, 16 Vehicles)
| Tracker | MOTA / IDF1 | HOTA (DetA / AssA) | IDSW & Count Acc |
|---|---|---|---|
| SORT (High-Conf Only) | 0.608 / 0.422 | 0.414 (0.628 / 0.273) | IDSW=29 | Acc=50.0% |
| ByteTrack (2-Stage Recovery) | 0.966 / 0.983 | 0.934 (0.933 / 0.935) | IDSW=0 (-29) | Acc=100.0% |
Panoptic Segmentation (PQ = SQ * RQ) & Vision-Language (CLIP vs SigLIP)
| Task / Loss | Regime | Observed Value | Contract Gate |
|---|---|---|---|
| Clean Panoptic Prediction | PQ = SQ * RQ | PQ=0.940 (SQ=0.940, RQ=1.000) | Exact identity PASS |
| Merged-Cars Failure Mode | mIoU vs PQ_things | mIoU=1.000 | PQ_things=0.700 | PQ exposes fused instances |
| CLIP InfoNCE (B=4 vs B=32) | Aligned / Random | B=4: 0.001/2.468 | B=32: 0.008/4.841 | Random floor scales ~ln(B) |
| SigLIP Sigmoid (B=4 vs B=32) | Aligned / Random | B=4: 0.152/5.514 | B=32: 0.930/5.864 | Batch-decoupled pairwise loss |
Modern Vision Backbones (ConvNeXt / ViT + LoRA) & Edge ONNX Serving
| Model / Artifact | Params (Trainable %) | ORT p50 / p95 (ms) | Parity / Gate |
|---|---|---|---|
| MiniConvNeXt (7x7 DW + LN) | 45027 (100.0%) | 0.52 / 0.89 ms | diff 1.3e-07 (< 1e-4 PASS) |
| MiniViT Full (N=64 patches) | 116867 (100.0%) | 0.40 / 0.64 ms | diff 6.0e-07 (< 1e-4 PASS) |
| MiniViT + LoRA (rank=4 QKV) | 2243/118915 (1.89%) | Zero overhead (merged W) | < 15% trainable PASS |
| Safetensors Checkpoint | 182052 B (24 tensors) | Zero-pickle mmap | diff 0.0e+00 (PASS) |
02-track-1-data-science-and-ai/part-03-deep-learning-and-modern-cv/labs/lab-09-realtime-vehicle-detection-tracking-counting
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "modern-cv-tracking-lab"
version = "0.1.0"
description = "Lab 09: Real-Time Computer Vision — Vehicle Detection (IoU/GIoU/CIoU, NMS/Soft-NMS, mAP@50:95), Multi-Object Tracking & Counting (Kalman, SORT vs ByteTrack, HOTA, Tripwire), Panoptic PQ, ConvNeXt/ViT+LoRA, CLIP vs SigLIP & ONNX/Safetensors Edge Serving (T1-P3-U04)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"onnx>=1.16",
"onnxruntime>=1.18",
"pillow>=10.0",
"pydantic>=2.0",
"safetensors>=0.4",
"scipy>=1.12",
"torch>=2.5",
]
[project.optional-dependencies]
dev = [
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[tool.uv.sources]
torch = { index = "pytorch-cpu" }
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
pythonpath = ["src"]
testpaths = ["tests"]
addopts = "-v"
[tool.ruff]
line-length = 110
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.mypy]
python_version = "3.12"
ignore_missing_imports = true
warn_unused_ignores = true
"""Lab 09: Real-Time Computer Vision — Detection, Tracking, Counting & Segmentation (T1-P3-U04)."""
from .detection_metrics import (
DetectionPrediction,
GroundTruthBox,
compute_ap,
compute_ciou_matrix,
compute_giou_matrix,
compute_iou_matrix,
compute_map_50_95,
greedy_nms,
soft_nms,
)
from .segmentation_metrics import (
PanopticResult,
compute_panoptic_quality,
compute_semantic_miou,
generate_synthetic_panoptic_scene,
)
from .tracking_and_counting import (
ByteTrackTracker,
KalmanBoxTracker,
MOTEvaluationResult,
SORTTracker,
TrackedObject,
TripwireVehicleCounter,
evaluate_mot_sequence,
)
from .traffic_simulator import (
DetectedBox,
FrameObservation,
GroundTruthVehicle,
HighwaySequence,
simulate_highway_traffic,
)
from .vision_backbones_and_vlm import (
ConvNeXtBlock,
LoRALinear,
MiniConvNeXt,
MiniViT,
OnnxBenchmarkResult,
clip_infonce_loss,
count_parameters,
export_and_benchmark_onnx,
save_and_verify_safetensors,
siglip_sigmoid_loss,
)
__all__ = [
"ByteTrackTracker",
"ConvNeXtBlock",
"DetectedBox",
"DetectionPrediction",
"FrameObservation",
"GroundTruthBox",
"GroundTruthVehicle",
"HighwaySequence",
"KalmanBoxTracker",
"LoRALinear",
"MOTEvaluationResult",
"MiniConvNeXt",
"MiniViT",
"OnnxBenchmarkResult",
"PanopticResult",
"SORTTracker",
"TrackedObject",
"TripwireVehicleCounter",
"clip_infonce_loss",
"compute_ap",
"compute_ciou_matrix",
"compute_giou_matrix",
"compute_iou_matrix",
"compute_map_50_95",
"compute_panoptic_quality",
"compute_semantic_miou",
"count_parameters",
"evaluate_mot_sequence",
"export_and_benchmark_onnx",
"generate_synthetic_panoptic_scene",
"greedy_nms",
"save_and_verify_safetensors",
"siglip_sigmoid_loss",
"simulate_highway_traffic",
"soft_nms",
]
"""Tier 1 (NumPy) object detection geometry, NMS/Soft-NMS, and COCO AP/mAP@50:95 evaluators."""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from numpy.typing import NDArray
FloatArray = NDArray[np.float64]
@dataclass(frozen=True, slots=True)
class DetectionPrediction:
"""Single object detection prediction on a specific frame/image."""
image_id: int
class_id: int
score: float
box: tuple[float, float, float, float]
@dataclass(frozen=True, slots=True)
class GroundTruthBox:
"""Single ground-truth bounding box on a specific frame/image."""
image_id: int
class_id: int
box: tuple[float, float, float, float]
def _as_boxes(boxes: FloatArray | list[tuple[float, float, float, float]]) -> FloatArray:
arr = np.asarray(boxes, dtype=np.float64)
if arr.size == 0:
return np.zeros((0, 4), dtype=np.float64)
if arr.ndim == 1:
arr = arr.reshape(1, 4)
if arr.shape[1] != 4:
raise ValueError(f"Expected boxes of shape (N, 4), got {arr.shape}")
return arr
def compute_iou_matrix(
boxes_a: FloatArray | list[tuple[float, float, float, float]],
boxes_b: FloatArray | list[tuple[float, float, float, float]],
eps: float = 1e-12,
) -> FloatArray:
"""Compute exact pairwise Intersection-over-Union (IoU) in [0, 1] for xyxy boxes."""
a = _as_boxes(boxes_a)
b = _as_boxes(boxes_b)
if len(a) == 0 or len(b) == 0:
return np.zeros((len(a), len(b)), dtype=np.float64)
inter_x1 = np.maximum(a[:, None, 0], b[None, :, 0])
inter_y1 = np.maximum(a[:, None, 1], b[None, :, 1])
inter_x2 = np.minimum(a[:, None, 2], b[None, :, 2])
inter_y2 = np.minimum(a[:, None, 3], b[None, :, 3])
inter_w = np.maximum(0.0, inter_x2 - inter_x1)
inter_h = np.maximum(0.0, inter_y2 - inter_y1)
inter_area = inter_w * inter_h
area_a = np.maximum(0.0, a[:, 2] - a[:, 0]) * np.maximum(0.0, a[:, 3] - a[:, 1])
area_b = np.maximum(0.0, b[:, 2] - b[:, 0]) * np.maximum(0.0, b[:, 3] - b[:, 1])
union = area_a[:, None] + area_b[None, :] - inter_area
return np.clip(inter_area / np.maximum(union, eps), 0.0, 1.0)
def compute_giou_matrix(
boxes_a: FloatArray | list[tuple[float, float, float, float]],
boxes_b: FloatArray | list[tuple[float, float, float, float]],
eps: float = 1e-12,
) -> FloatArray:
"""Compute pairwise Generalized IoU (GIoU) in (-1, 1] (Rezatofighi et al., CVPR 2019)."""
a = _as_boxes(boxes_a)
b = _as_boxes(boxes_b)
if len(a) == 0 or len(b) == 0:
return np.zeros((len(a), len(b)), dtype=np.float64)
inter_x1 = np.maximum(a[:, None, 0], b[None, :, 0])
inter_y1 = np.maximum(a[:, None, 1], b[None, :, 1])
inter_x2 = np.minimum(a[:, None, 2], b[None, :, 2])
inter_y2 = np.minimum(a[:, None, 3], b[None, :, 3])
inter_area = np.maximum(0.0, inter_x2 - inter_x1) * np.maximum(0.0, inter_y2 - inter_y1)
area_a = np.maximum(0.0, a[:, 2] - a[:, 0]) * np.maximum(0.0, a[:, 3] - a[:, 1])
area_b = np.maximum(0.0, b[:, 2] - b[:, 0]) * np.maximum(0.0, b[:, 3] - b[:, 1])
union = area_a[:, None] + area_b[None, :] - inter_area
iou = inter_area / np.maximum(union, eps)
enc_x1 = np.minimum(a[:, None, 0], b[None, :, 0])
enc_y1 = np.minimum(a[:, None, 1], b[None, :, 1])
enc_x2 = np.maximum(a[:, None, 2], b[None, :, 2])
enc_y2 = np.maximum(a[:, None, 3], b[None, :, 3])
enc_area = np.maximum(0.0, enc_x2 - enc_x1) * np.maximum(0.0, enc_y2 - enc_y1)
giou = iou - (enc_area - union) / np.maximum(enc_area, eps)
return np.clip(giou, -1.0, 1.0)
def compute_ciou_matrix(
boxes_a: FloatArray | list[tuple[float, float, float, float]],
boxes_b: FloatArray | list[tuple[float, float, float, float]],
eps: float = 1e-12,
) -> FloatArray:
"""Compute pairwise Complete IoU (CIoU) in (-1, 1] (Zheng et al., AAAI 2020)."""
a = _as_boxes(boxes_a)
b = _as_boxes(boxes_b)
if len(a) == 0 or len(b) == 0:
return np.zeros((len(a), len(b)), dtype=np.float64)
iou = compute_iou_matrix(a, b, eps=eps)
cx_a = 0.5 * (a[:, 0] + a[:, 2])
cy_a = 0.5 * (a[:, 1] + a[:, 3])
w_a = np.maximum(eps, a[:, 2] - a[:, 0])
h_a = np.maximum(eps, a[:, 3] - a[:, 1])
cx_b = 0.5 * (b[:, 0] + b[:, 2])
cy_b = 0.5 * (b[:, 1] + b[:, 3])
w_b = np.maximum(eps, b[:, 2] - b[:, 0])
h_b = np.maximum(eps, b[:, 3] - b[:, 1])
center_dist_sq = (cx_a[:, None] - cx_b[None, :]) ** 2 + (cy_a[:, None] - cy_b[None, :]) ** 2
enc_x1 = np.minimum(a[:, None, 0], b[None, :, 0])
enc_y1 = np.minimum(a[:, None, 1], b[None, :, 1])
enc_x2 = np.maximum(a[:, None, 2], b[None, :, 2])
enc_y2 = np.maximum(a[:, None, 3], b[None, :, 3])
diag_sq = np.maximum(eps, (enc_x2 - enc_x1) ** 2 + (enc_y2 - enc_y1) ** 2)
atan_diff = np.arctan(w_b[None, :] / h_b[None, :]) - np.arctan(w_a[:, None] / h_a[:, None])
v = (4.0 / (np.pi**2)) * (atan_diff**2)
alpha = v / np.maximum((1.0 - iou) + v, eps)
ciou = iou - (center_dist_sq / diag_sq) - alpha * v
return np.clip(ciou, -1.0, 1.0)
def greedy_nms(
boxes: FloatArray,
scores: FloatArray,
iou_threshold: float = 0.5,
) -> list[int]:
"""Standard greedy Non-Maximum Suppression returning kept box indices."""
arr = _as_boxes(boxes)
sc = np.asarray(scores, dtype=np.float64)
if len(arr) == 0:
return []
order = np.argsort(-sc, kind="mergesort")
keep: list[int] = []
while order.size > 0:
i = int(order[0])
keep.append(i)
if order.size == 1:
break
rest = order[1:]
ious = compute_iou_matrix(arr[i : i + 1], arr[rest])[0]
order = rest[ious < iou_threshold]
return keep
def soft_nms(
boxes: FloatArray,
scores: FloatArray,
sigma: float = 0.5,
score_threshold: float = 0.05,
) -> tuple[list[int], FloatArray]:
"""Gaussian Soft-NMS (Bodla et al., ICCV 2017) decaying overlapping scores softly."""
arr = _as_boxes(boxes)
sc = np.asarray(scores, dtype=np.float64).copy()
n = len(arr)
if n == 0:
return [], np.zeros((0,), dtype=np.float64)
indices = list(range(n))
kept_indices: list[int] = []
kept_scores: list[float] = []
while indices:
best_pos = max(range(len(indices)), key=lambda pos: float(sc[indices[pos]]))
best_idx = indices.pop(best_pos)
best_score = float(sc[best_idx])
if best_score < score_threshold:
break
kept_indices.append(best_idx)
kept_scores.append(best_score)
if not indices:
break
rem_boxes = arr[indices]
ious = compute_iou_matrix(arr[best_idx : best_idx + 1], rem_boxes)[0]
decay = np.exp(-(ious**2) / max(sigma, 1e-6))
for pos, rem_idx in enumerate(indices):
sc[rem_idx] *= float(decay[pos])
indices = [idx for idx in indices if sc[idx] >= score_threshold]
return kept_indices, np.asarray(kept_scores, dtype=np.float64)
def compute_ap(
predictions: list[DetectionPrediction],
ground_truths: list[GroundTruthBox],
class_id: int,
iou_threshold: float = 0.5,
) -> float:
"""Compute COCO 101-point interpolated Average Precision (AP) for one class & IoU threshold."""
cls_preds = [p for p in predictions if p.class_id == class_id]
cls_gts = [g for g in ground_truths if g.class_id == class_id]
n_gt = len(cls_gts)
if n_gt == 0:
return 0.0
if not cls_preds:
return 0.0
gts_by_img: dict[int, list[tuple[float, float, float, float]]] = {}
for g in cls_gts:
gts_by_img.setdefault(g.image_id, []).append(g.box)
matched_by_img: dict[int, list[bool]] = {
img_id: [False] * len(box_list) for img_id, box_list in gts_by_img.items()
}
sorted_preds = sorted(cls_preds, key=lambda p: (-p.score, p.image_id))
tp = np.zeros(len(sorted_preds), dtype=np.float64)
fp = np.zeros(len(sorted_preds), dtype=np.float64)
for idx, pred in enumerate(sorted_preds):
img_gts = gts_by_img.get(pred.image_id, [])
if not img_gts:
fp[idx] = 1.0
continue
ious = compute_iou_matrix([pred.box], img_gts)[0]
best_gt_idx = int(np.argmax(ious))
best_iou = float(ious[best_gt_idx])
if best_iou >= iou_threshold and not matched_by_img[pred.image_id][best_gt_idx]:
tp[idx] = 1.0
matched_by_img[pred.image_id][best_gt_idx] = True
else:
fp[idx] = 1.0
cum_tp = np.cumsum(tp)
cum_fp = np.cumsum(fp)
recalls = cum_tp / float(n_gt)
precisions = cum_tp / np.maximum(cum_tp + cum_fp, 1e-12)
# Monotone non-increasing precision envelope
mrec = np.concatenate(([0.0], recalls, [1.0]))
mpre = np.concatenate(([0.0], precisions, [0.0]))
for i in range(len(mpre) - 2, -1, -1):
mpre[i] = max(mpre[i], mpre[i + 1])
recall_grid = np.linspace(0.0, 1.0, 101)
ap_vals = [float(np.max(mpre[mrec >= r])) if np.any(mrec >= r) else 0.0 for r in recall_grid]
return float(np.mean(ap_vals))
def compute_map_50_95(
predictions: list[DetectionPrediction],
ground_truths: list[GroundTruthBox],
) -> dict[str, float]:
"""Compute COCO-style AP@50, AP@75, and mAP@50:95 across all ground-truth classes."""
classes = sorted({g.class_id for g in ground_truths})
if not classes:
return {"ap50": 0.0, "ap75": 0.0, "map_50_95": 0.0}
thresholds = [round(0.50 + 0.05 * k, 2) for k in range(10)]
per_thresh: dict[float, float] = {}
for thr in thresholds:
cls_aps = [compute_ap(predictions, ground_truths, c, iou_threshold=thr) for c in classes]
per_thresh[thr] = float(np.mean(cls_aps))
return {
"ap50": per_thresh[0.50],
"ap75": per_thresh[0.75],
"map_50_95": float(np.mean(list(per_thresh.values()))),
}
"""Deterministic multi-lane highway traffic sequence generator with scheduled occlusions."""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
VEHICLE_CLASSES: dict[int, str] = {0: "car", 1: "truck", 2: "bus"}
@dataclass(frozen=True, slots=True)
class GroundTruthVehicle:
"""Ground-truth vehicle bounding box and identity in a single video frame."""
frame_id: int
track_id: int
class_id: int
direction: str # "down" or "up"
box: tuple[float, float, float, float]
occluded: bool
@dataclass(frozen=True, slots=True)
class DetectedBox:
"""Simulated detector output box with confidence score (high or occlusion-degraded low)."""
frame_id: int
class_id: int
score: float
box: tuple[float, float, float, float]
is_false_positive: bool = False
@dataclass(frozen=True, slots=True)
class FrameObservation:
"""All ground-truth vehicles and noisy detections at a single frame."""
frame_id: int
gt_vehicles: tuple[GroundTruthVehicle, ...]
detections: tuple[DetectedBox, ...]
@dataclass(frozen=True, slots=True)
class HighwaySequence:
"""Complete synthetic multi-lane highway video stream for MOT & tripwire counting."""
width: int
height: int
fps: float
tripwire_y: float
occlusion_zones: tuple[tuple[float, float], ...]
frames: tuple[FrameObservation, ...]
gt_counts_down: int
gt_counts_up: int
gt_counts_by_class: dict[str, int]
total_vehicle_tracks: int
def simulate_highway_traffic(
n_frames: int = 100,
seed: int = 42,
tripwire_y: float = 242.0,
) -> HighwaySequence:
"""Generate a deterministic 4-lane highway sequence with 16 vehicles and brief occlusions.
Lanes 0 & 1 travel downward (increasing y), lanes 2 & 3 travel upward (decreasing y).
Two overpass shadow / occlusion bands sit at y in [180, 232] and [288, 338].
When a vehicle passes through an occlusion band, detector confidence drops from ~0.86
down to ~0.24 (plus slightly higher localization jitter), mimicking real-world partial
occlusion where SORT drops tracks while ByteTrack recovers them via stage-2 association.
"""
rng = np.random.default_rng(seed)
width = 640
height = 480
fps = 30.0
occlusion_zones = ((180.0, 232.0), (288.0, 338.0))
# 16 deterministic vehicle schedules across 4 lanes & 3 classes
# (track_id, lane_idx, class_id, start_frame, speed_px_per_frame)
vehicle_specs: list[tuple[int, int, int, int, float]] = [
# Lane 0 (x ~ 115, going down)
(1, 0, 0, 0, 7.6),
(2, 0, 1, 18, 6.8),
(3, 0, 0, 38, 7.9),
(4, 0, 2, 58, 6.5),
# Lane 1 (x ~ 245, going down)
(5, 1, 0, 4, 8.2),
(6, 1, 0, 22, 7.4),
(7, 1, 1, 40, 6.7),
(8, 1, 0, 60, 8.0),
# Lane 2 (x ~ 395, going up)
(9, 2, 0, 2, 7.8),
(10, 2, 2, 20, 6.6),
(11, 2, 0, 42, 8.1),
(12, 2, 1, 56, 6.9),
# Lane 3 (x ~ 525, going up)
(13, 3, 1, 6, 7.0),
(14, 3, 0, 26, 8.4),
(15, 3, 0, 44, 7.5),
(16, 3, 2, 62, 6.8),
]
lane_x = {0: 115.0, 1: 245.0, 2: 395.0, 3: 525.0}
class_dims = {
0: (48.0, 64.0), # car
1: (58.0, 84.0), # truck
2: (62.0, 96.0), # bus
}
frames_gt: dict[int, list[GroundTruthVehicle]] = {t: [] for t in range(n_frames)}
frames_det: dict[int, list[DetectedBox]] = {t: [] for t in range(n_frames)}
gt_down = 0
gt_up = 0
gt_by_class: dict[str, int] = {"car": 0, "truck": 0, "bus": 0}
for tid, lane, cls_id, start_f, speed in vehicle_specs:
direction = "down" if lane in (0, 1) else "up"
w_base, h_base = class_dims[cls_id]
cx_base = lane_x[lane] + float(rng.normal(0.0, 2.5))
y_start = 32.0 if direction == "down" else 448.0
vy = speed if direction == "down" else -speed
prev_cy: float | None = None
crossed = False
for f in range(start_f, n_frames):
dt = f - start_f
cy = y_start + vy * dt
# Mild lateral lane drift
cx = cx_base + 1.8 * np.sin(0.08 * dt + tid)
if cy < 18.0 or cy > height - 18.0:
if dt > 0:
break
continue
# Subtle perspective scale change along roadway y
scale = 0.88 + 0.24 * (cy / height)
bw = w_base * scale
bh = h_base * scale
x1 = float(np.clip(cx - 0.5 * bw, 0.0, width - 2.0))
y1 = float(np.clip(cy - 0.5 * bh, 0.0, height - 2.0))
x2 = float(np.clip(cx + 0.5 * bw, x1 + 2.0, width))
y2 = float(np.clip(cy + 0.5 * bh, y1 + 2.0, height))
in_occ = any(z0 <= cy <= z1 for z0, z1 in occlusion_zones)
frames_gt[f].append(
GroundTruthVehicle(
frame_id=f,
track_id=tid,
class_id=cls_id,
direction=direction,
box=(x1, y1, x2, y2),
occluded=in_occ,
)
)
if prev_cy is not None and not crossed:
if direction == "down" and prev_cy < tripwire_y <= cy:
gt_down += 1
gt_by_class[VEHICLE_CLASSES[cls_id]] += 1
crossed = True
elif direction == "up" and prev_cy > tripwire_y >= cy:
gt_up += 1
gt_by_class[VEHICLE_CLASSES[cls_id]] += 1
crossed = True
prev_cy = cy
# Detector observation model
if in_occ:
# Partial occlusion: confidence drops sharply into ByteTrack stage-2 band [0.18, 0.36]
score = float(np.clip(rng.normal(0.26, 0.04), 0.18, 0.38))
jit = 2.2
else:
score = float(np.clip(rng.normal(0.86, 0.045), 0.68, 0.98))
jit = 1.1
dx1, dy1, dx2, dy2 = rng.normal(0.0, jit, size=4)
det_x1 = float(np.clip(x1 + dx1, 0.0, width - 4.0))
det_y1 = float(np.clip(y1 + dy1, 0.0, height - 4.0))
det_x2 = float(np.clip(x2 + dx2, det_x1 + 4.0, width))
det_y2 = float(np.clip(y2 + dy2, det_y1 + 4.0, height))
frames_det[f].append(
DetectedBox(
frame_id=f,
class_id=cls_id,
score=score,
box=(det_x1, det_y1, det_x2, det_y2),
is_false_positive=False,
)
)
# Inject occasional low-score background clutter false positives (far from active lanes)
for f in range(0, n_frames, 7):
fp_x1 = float(rng.uniform(8.0, 42.0))
fp_y1 = float(rng.uniform(40.0, 400.0))
fp_box = (fp_x1, fp_y1, fp_x1 + 36.0, fp_y1 + 44.0)
fp_score = float(rng.uniform(0.18, 0.34))
frames_det[f].append(
DetectedBox(
frame_id=f,
class_id=0,
score=fp_score,
box=fp_box,
is_false_positive=True,
)
)
observations = tuple(
FrameObservation(
frame_id=f,
gt_vehicles=tuple(frames_gt[f]),
detections=tuple(frames_det[f]),
)
for f in range(n_frames)
)
return HighwaySequence(
width=width,
height=height,
fps=fps,
tripwire_y=tripwire_y,
occlusion_zones=occlusion_zones,
frames=observations,
gt_counts_down=gt_down,
gt_counts_up=gt_up,
gt_counts_by_class=gt_by_class,
total_vehicle_tracks=len(vehicle_specs),
)
"""Tier 1 (NumPy/SciPy) Multi-Object Tracking (Kalman, SORT vs ByteTrack), Tripwire Counting & HOTA."""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from numpy.typing import NDArray
from scipy.optimize import linear_sum_assignment
from .detection_metrics import compute_iou_matrix
from .traffic_simulator import DetectedBox, HighwaySequence
FloatArray = NDArray[np.float64]
def xyxy_to_z(box: tuple[float, float, float, float]) -> FloatArray:
"""Convert [x1, y1, x2, y2] box to Kalman observation [u, v, s, r]."""
x1, y1, x2, y2 = box
w = max(1.0, x2 - x1)
h = max(1.0, y2 - y1)
u = x1 + 0.5 * w
v = y1 + 0.5 * h
s = w * h
r = w / h
return np.array([u, v, s, r], dtype=np.float64)
def x_to_xyxy(state: FloatArray) -> tuple[float, float, float, float]:
"""Convert Kalman state [u, v, s, r, ...] back to [x1, y1, x2, y2]."""
u, v, s, r = float(state[0]), float(state[1]), float(state[2]), float(state[3])
s_safe = max(16.0, s)
r_safe = max(0.2, min(5.0, r))
w = float(np.sqrt(s_safe * r_safe))
h = s_safe / max(w, 1e-6)
return (u - 0.5 * w, v - 0.5 * h, u + 0.5 * w, v + 0.5 * h)
class KalmanBoxTracker:
"""7-state constant-velocity Kalman Filter tracker [u, v, s, r, u_dot, v_dot, s_dot]."""
def __init__(self, initial_box: tuple[float, float, float, float], track_id: int, class_id: int) -> None:
self.track_id = track_id
self.class_id = class_id
# State transition matrix F (dt = 1 frame)
self.F: FloatArray = np.array(
[
[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],
],
dtype=np.float64,
)
# Observation matrix H
self.H: FloatArray = np.eye(4, 7, dtype=np.float64)
# Measurement noise R and process noise Q
self.R: FloatArray = np.diag([2.0, 2.0, 25.0, 0.05]).astype(np.float64)
self.Q: FloatArray = np.diag([1.0, 1.0, 10.0, 0.01, 0.25, 0.25, 1.0]).astype(np.float64)
# Initial covariance P (higher uncertainty on unobserved velocities)
self.P: FloatArray = np.diag([10.0, 10.0, 40.0, 0.2, 200.0, 200.0, 200.0]).astype(np.float64)
self.x: FloatArray = np.zeros(7, dtype=np.float64)
self.x[:4] = xyxy_to_z(initial_box)
self.age: int = 1
self.hits: int = 1
self.time_since_update: int = 0
self.last_score: float = 1.0
def predict(self) -> tuple[float, float, float, float]:
"""Advance Kalman state by one frame and return predicted xyxy box."""
if self.x[2] + self.x[6] <= 16.0:
self.x[6] = 0.0
self.x = self.F @ self.x
self.P = self.F @ self.P @ self.F.T + self.Q
self.age += 1
self.time_since_update += 1
return x_to_xyxy(self.x)
def update(self, box: tuple[float, float, float, float], score: float = 1.0) -> None:
"""Assimilate matched detection box into Kalman posterior state."""
z = xyxy_to_z(box)
y = z - (self.H @ self.x)
S = self.H @ self.P @ self.H.T + self.R
K = self.P @ self.H.T @ np.linalg.inv(S)
self.x = self.x + K @ y
eye = np.eye(7, dtype=np.float64)
self.P = (eye - K @ self.H) @ self.P
self.hits += 1
self.time_since_update = 0
self.last_score = score
def current_box(self) -> tuple[float, float, float, float]:
"""Return current posterior bounding box in xyxy format."""
return x_to_xyxy(self.x)
@dataclass(frozen=True, slots=True)
class TrackedObject:
"""Confirmed tracked object emitted for a given frame."""
frame_id: int
track_id: int
class_id: int
score: float
box: tuple[float, float, float, float]
def _hungarian_iou_match(
track_boxes: list[tuple[float, float, float, float]],
det_boxes: list[tuple[float, float, float, float]],
iou_threshold: float,
) -> tuple[list[tuple[int, int]], list[int], list[int]]:
"""Solve optimal 1-to-1 track-detection bipartite matching via Hungarian algorithm."""
if not track_boxes or not det_boxes:
return [], list(range(len(track_boxes))), list(range(len(det_boxes)))
iou_mat = compute_iou_matrix(track_boxes, det_boxes)
cost_mat = 1.0 - iou_mat
row_ind, col_ind = linear_sum_assignment(cost_mat)
matches: list[tuple[int, int]] = []
matched_t: set[int] = set()
matched_d: set[int] = set()
for r, c in zip(row_ind.tolist(), col_ind.tolist(), strict=True):
if float(iou_mat[r, c]) >= iou_threshold:
matches.append((r, c))
matched_t.add(r)
matched_d.add(c)
unmatched_tracks = [i for i in range(len(track_boxes)) if i not in matched_t]
unmatched_dets = [j for j in range(len(det_boxes)) if j not in matched_d]
return matches, unmatched_tracks, unmatched_dets
class SORTTracker:
"""Baseline SORT tracker: single-stage Hungarian association on high-confidence detections only."""
def __init__(
self,
high_conf_thresh: float = 0.55,
iou_threshold: float = 0.25,
max_age: int = 3,
min_hits: int = 3,
) -> None:
self.high_conf_thresh = high_conf_thresh
self.iou_threshold = iou_threshold
self.max_age = max_age
self.min_hits = min_hits
self._next_id = 1
self._tracks: list[KalmanBoxTracker] = []
def update(self, frame_id: int, detections: tuple[DetectedBox, ...]) -> list[TrackedObject]:
"""Run one frame of SORT tracking and return confirmed active tracks."""
high_dets = [d for d in detections if d.score >= self.high_conf_thresh]
pred_boxes = [trk.predict() for trk in self._tracks]
det_boxes = [d.box for d in high_dets]
matches, _, unmatched_dets = _hungarian_iou_match(
pred_boxes, det_boxes, iou_threshold=self.iou_threshold
)
for t_idx, d_idx in matches:
self._tracks[t_idx].update(high_dets[d_idx].box, score=high_dets[d_idx].score)
for d_idx in unmatched_dets:
d = high_dets[d_idx]
trk = KalmanBoxTracker(d.box, track_id=self._next_id, class_id=d.class_id)
trk.last_score = d.score
self._next_id += 1
self._tracks.append(trk)
self._tracks = [t for t in self._tracks if t.time_since_update <= self.max_age]
outputs: list[TrackedObject] = []
for trk in self._tracks:
if trk.time_since_update == 0 and (trk.hits >= self.min_hits or frame_id < self.min_hits):
outputs.append(
TrackedObject(
frame_id=frame_id,
track_id=trk.track_id,
class_id=trk.class_id,
score=trk.last_score,
box=trk.current_box(),
)
)
return outputs
class ByteTrackTracker:
"""ByteTrack 2-stage tracker recovering occluded tracks from low-confidence detections."""
def __init__(
self,
high_conf_thresh: float = 0.55,
low_conf_thresh: float = 0.15,
stage1_iou_threshold: float = 0.25,
stage2_iou_threshold: float = 0.20,
max_age: int = 3,
min_hits: int = 3,
) -> None:
self.high_conf_thresh = high_conf_thresh
self.low_conf_thresh = low_conf_thresh
self.stage1_iou_threshold = stage1_iou_threshold
self.stage2_iou_threshold = stage2_iou_threshold
self.max_age = max_age
self.min_hits = min_hits
self._next_id = 1
self._tracks: list[KalmanBoxTracker] = []
def update(self, frame_id: int, detections: tuple[DetectedBox, ...]) -> list[TrackedObject]:
"""Run one frame of ByteTrack (Stage 1: high-score; Stage 2: low-score recovery)."""
high_dets = [d for d in detections if d.score >= self.high_conf_thresh]
low_dets = [
d for d in detections if self.low_conf_thresh <= d.score < self.high_conf_thresh
]
pred_boxes = [trk.predict() for trk in self._tracks]
# Stage 1: match all active tracks against high-confidence detections
high_boxes = [d.box for d in high_dets]
matches1, rem_track_idxs, unmatched_high = _hungarian_iou_match(
pred_boxes, high_boxes, iou_threshold=self.stage1_iou_threshold
)
for t_idx, d_idx in matches1:
self._tracks[t_idx].update(high_dets[d_idx].box, score=high_dets[d_idx].score)
# Stage 2: recover remaining tracks against low-confidence detections (never spawn from low_dets!)
if rem_track_idxs and low_dets:
rem_pred_boxes = [pred_boxes[i] for i in rem_track_idxs]
low_boxes = [d.box for d in low_dets]
matches2, _, _ = _hungarian_iou_match(
rem_pred_boxes, low_boxes, iou_threshold=self.stage2_iou_threshold
)
for local_t, d_idx in matches2:
global_t = rem_track_idxs[local_t]
self._tracks[global_t].update(low_dets[d_idx].box, score=low_dets[d_idx].score)
# Spawn new tracks ONLY from unmatched high-confidence detections
for d_idx in unmatched_high:
d = high_dets[d_idx]
trk = KalmanBoxTracker(d.box, track_id=self._next_id, class_id=d.class_id)
trk.last_score = d.score
self._next_id += 1
self._tracks.append(trk)
self._tracks = [t for t in self._tracks if t.time_since_update <= self.max_age]
outputs: list[TrackedObject] = []
for trk in self._tracks:
if trk.time_since_update == 0 and (trk.hits >= self.min_hits or frame_id < self.min_hits):
outputs.append(
TrackedObject(
frame_id=frame_id,
track_id=trk.track_id,
class_id=trk.class_id,
score=trk.last_score,
box=trk.current_box(),
)
)
return outputs
class TripwireVehicleCounter:
"""Idempotent directional tripwire line-crossing counter (guarantees zero double-counting per ID)."""
def __init__(self, tripwire_y: float) -> None:
self.tripwire_y = tripwire_y
self._last_cy: dict[int, float] = {}
self.counted_track_ids: set[int] = set()
self.count_down: int = 0
self.count_up: int = 0
self.counts_by_class: dict[int, int] = {0: 0, 1: 0, 2: 0}
def update(self, tracked_objects: list[TrackedObject]) -> None:
"""Update tripwire state with the current frame's tracked objects."""
for obj in tracked_objects:
cy = 0.5 * (obj.box[1] + obj.box[3])
prev_cy = self._last_cy.get(obj.track_id)
if prev_cy is not None and obj.track_id not in self.counted_track_ids:
if prev_cy < self.tripwire_y <= cy:
self.count_down += 1
self.counted_track_ids.add(obj.track_id)
self.counts_by_class[obj.class_id] = self.counts_by_class.get(obj.class_id, 0) + 1
elif prev_cy > self.tripwire_y >= cy:
self.count_up += 1
self.counted_track_ids.add(obj.track_id)
self.counts_by_class[obj.class_id] = self.counts_by_class.get(obj.class_id, 0) + 1
self._last_cy[obj.track_id] = cy
@property
def total_count(self) -> int:
return self.count_down + self.count_up
@dataclass(frozen=True, slots=True)
class MOTEvaluationResult:
"""Complete Multi-Object Tracking and Tripwire Counting evaluation metrics."""
tracker_name: str
mota: float
idf1: float
hota: float
det_a: float
ass_a: float
id_switches: int
total_tp: int
total_fp: int
total_fn: int
total_gt: int
pred_count_down: int
pred_count_up: int
gt_count_down: int
gt_count_up: int
counting_mae: float
counting_accuracy: float
def _compute_hota_at_alpha(
gt_frames: list[list[tuple[int, tuple[float, float, float, float]]]],
pred_frames: list[list[tuple[int, tuple[float, float, float, float]]]],
alpha: float,
) -> tuple[float, float, float]:
"""Compute exact (HOTA_alpha, DetA_alpha, AssA_alpha) at a single localization threshold."""
tp_pairs: list[tuple[int, int]] = []
gt_id_counts: dict[int, int] = {}
pred_id_counts: dict[int, int] = {}
pair_counts: dict[tuple[int, int], int] = {}
tp_total = 0
fp_total = 0
fn_total = 0
for g_list, p_list in zip(gt_frames, pred_frames, strict=True):
for gid, _ in g_list:
gt_id_counts[gid] = gt_id_counts.get(gid, 0) + 1
for pid, _ in p_list:
pred_id_counts[pid] = pred_id_counts.get(pid, 0) + 1
g_boxes = [b for _, b in g_list]
p_boxes = [b for _, b in p_list]
matches, unm_g, unm_p = _hungarian_iou_match(g_boxes, p_boxes, iou_threshold=alpha)
tp_total += len(matches)
fn_total += len(unm_g)
fp_total += len(unm_p)
for gi, pi in matches:
pair = (g_list[gi][0], p_list[pi][0])
tp_pairs.append(pair)
pair_counts[pair] = pair_counts.get(pair, 0) + 1
det_denom = tp_total + fn_total + fp_total
det_a = (tp_total / float(det_denom)) if det_denom > 0 else 0.0
if tp_total == 0:
return 0.0, det_a, 0.0
ass_sum = 0.0
for gid, pid in tp_pairs:
tpa = pair_counts[(gid, pid)]
fna = gt_id_counts[gid] - tpa
fpa = pred_id_counts[pid] - tpa
ass_sum += tpa / float(max(1, tpa + fna + fpa))
ass_a = ass_sum / float(tp_total)
hota_alpha = float(np.sqrt(max(0.0, det_a * ass_a)))
return hota_alpha, det_a, ass_a
def evaluate_mot_sequence(
sequence: HighwaySequence,
tracker: SORTTracker | ByteTrackTracker,
tracker_name: str,
iou_threshold: float = 0.5,
) -> MOTEvaluationResult:
"""Run tracker + tripwire counter over a HighwaySequence and compute MOTA, IDF1, HOTA & counts."""
counter = TripwireVehicleCounter(tripwire_y=sequence.tripwire_y)
gt_frames: list[list[tuple[int, tuple[float, float, float, float]]]] = []
pred_frames: list[list[tuple[int, tuple[float, float, float, float]]]] = []
total_tp = 0
total_fp = 0
total_fn = 0
total_gt = 0
id_switches = 0
last_matched_pred_for_gt: dict[int, int] = {}
gt_ids_all: set[int] = set()
pred_ids_all: set[int] = set()
co_occurrence: dict[tuple[int, int], int] = {}
gt_total_appearances: dict[int, int] = {}
pred_total_appearances: dict[int, int] = {}
for obs in sequence.frames:
tracked = tracker.update(obs.frame_id, obs.detections)
counter.update(tracked)
g_list = [(g.track_id, g.box) for g in obs.gt_vehicles]
p_list = [(p.track_id, p.box) for p in tracked]
gt_frames.append(g_list)
pred_frames.append(p_list)
total_gt += len(g_list)
for gid, _ in g_list:
gt_ids_all.add(gid)
gt_total_appearances[gid] = gt_total_appearances.get(gid, 0) + 1
for pid, _ in p_list:
pred_ids_all.add(pid)
pred_total_appearances[pid] = pred_total_appearances.get(pid, 0) + 1
matches, unm_g, unm_p = _hungarian_iou_match(
[b for _, b in g_list],
[b for _, b in p_list],
iou_threshold=iou_threshold,
)
total_tp += len(matches)
total_fn += len(unm_g)
total_fp += len(unm_p)
for gi, pi in matches:
gid = g_list[gi][0]
pid = p_list[pi][0]
co_occurrence[(gid, pid)] = co_occurrence.get((gid, pid), 0) + 1
prev_pid = last_matched_pred_for_gt.get(gid)
if prev_pid is not None and prev_pid != pid:
id_switches += 1
last_matched_pred_for_gt[gid] = pid
mota = 1.0 - (total_fn + total_fp + id_switches) / float(max(1, total_gt))
# Global optimal GT-ID <-> Pred-ID bipartite matching for IDF1
gt_id_list = sorted(gt_ids_all)
pred_id_list = sorted(pred_ids_all)
if gt_id_list and pred_id_list:
gain = np.zeros((len(gt_id_list), len(pred_id_list)), dtype=np.float64)
for i, gid in enumerate(gt_id_list):
for j, pid in enumerate(pred_id_list):
gain[i, j] = float(co_occurrence.get((gid, pid), 0))
r_ind, c_ind = linear_sum_assignment(-gain)
idtp = int(sum(gain[r, c] for r, c in zip(r_ind.tolist(), c_ind.tolist(), strict=True)))
else:
idtp = 0
total_pred_dets = sum(pred_total_appearances.values())
idf1 = (2.0 * idtp) / float(max(1, total_gt + total_pred_dets))
# HOTA integrated across 19 alpha thresholds (0.05..0.95)
alphas = [round(0.05 * k, 2) for k in range(1, 20)]
hota_vals, det_vals, ass_vals = [], [], []
for alpha in alphas:
h_a, d_a, a_a = _compute_hota_at_alpha(gt_frames, pred_frames, alpha=alpha)
hota_vals.append(h_a)
det_vals.append(d_a)
ass_vals.append(a_a)
hota = float(np.mean(hota_vals))
det_a = float(np.mean(det_vals))
ass_a = float(np.mean(ass_vals))
gt_total_cross = sequence.gt_counts_down + sequence.gt_counts_up
err_down = abs(counter.count_down - sequence.gt_counts_down)
err_up = abs(counter.count_up - sequence.gt_counts_up)
counting_mae = 0.5 * (err_down + err_up)
counting_accuracy = max(
0.0, 1.0 - (err_down + err_up) / float(max(1, gt_total_cross))
)
return MOTEvaluationResult(
tracker_name=tracker_name,
mota=mota,
idf1=idf1,
hota=hota,
det_a=det_a,
ass_a=ass_a,
id_switches=id_switches,
total_tp=total_tp,
total_fp=total_fp,
total_fn=total_fn,
total_gt=total_gt,
pred_count_down=counter.count_down,
pred_count_up=counter.count_up,
gt_count_down=sequence.gt_counts_down,
gt_count_up=sequence.gt_counts_up,
counting_mae=counting_mae,
counting_accuracy=counting_accuracy,
)
"""Semantic mIoU and Panoptic Quality (PQ = SQ * RQ) segmentation metrics (Kirillov et al., 2019)."""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from numpy.typing import NDArray
IntArray = NDArray[np.int32]
@dataclass(frozen=True, slots=True)
class PanopticResult:
"""Panoptic segmentation evaluation report with exact PQ = SQ * RQ identity."""
pq: float
sq: float
rq: float
pq_things: float
pq_stuff: float
tp: int
fp: int
fn: int
per_class: dict[int, dict[str, float]]
def compute_semantic_miou(
pred_semantic: IntArray,
gt_semantic: IntArray,
num_classes: int,
) -> dict[str, float]:
"""Compute exact per-class semantic IoU and mean IoU (mIoU)."""
if pred_semantic.shape != gt_semantic.shape:
raise ValueError(f"Shape mismatch: {pred_semantic.shape} vs {gt_semantic.shape}")
ious: list[float] = []
per_class: dict[str, float] = {}
for cls_id in range(num_classes):
pred_c = pred_semantic == cls_id
gt_c = gt_semantic == cls_id
inter = int(np.sum(pred_c & gt_c))
union = int(np.sum(pred_c | gt_c))
if union == 0:
continue
iou = inter / float(union)
ious.append(iou)
per_class[f"class_{cls_id}"] = iou
miou = float(np.mean(ious)) if ious else 0.0
pixel_acc = float(np.mean(pred_semantic == gt_semantic))
return {"miou": miou, "pixel_accuracy": pixel_acc, **per_class}
def compute_panoptic_quality(
pred_semantic: IntArray,
pred_instance: IntArray,
gt_semantic: IntArray,
gt_instance: IntArray,
thing_classes: tuple[int, ...] = (2, 3),
stuff_classes: tuple[int, ...] = (0, 1),
) -> PanopticResult:
"""Compute exact Panoptic Quality (PQ), Segmentation Quality (SQ), and Recognition Quality (RQ).
Each non-overlapping segment is uniquely identified by (class_id, instance_id).
For stuff classes, instance_id is collapsed to 0.
Theorem (Kirillov et al.): Because segments in each map are disjoint, at most one
predicted segment can have IoU > 0.5 with any ground-truth segment of the same class.
"""
if not (
pred_semantic.shape == pred_instance.shape == gt_semantic.shape == gt_instance.shape
):
raise ValueError("All panoptic semantic/instance arrays must have identical shape.")
all_classes = tuple(sorted(set(thing_classes) | set(stuff_classes)))
per_class: dict[int, dict[str, float]] = {}
total_tp = 0
total_fp = 0
total_fn = 0
total_iou_sum = 0.0
for cls_id in all_classes:
is_stuff = cls_id in stuff_classes
gt_mask_cls = gt_semantic == cls_id
pred_mask_cls = pred_semantic == cls_id
if is_stuff:
gt_ids = [0] if np.any(gt_mask_cls) else []
pred_ids = [0] if np.any(pred_mask_cls) else []
else:
gt_ids = sorted(int(v) for v in np.unique(gt_instance[gt_mask_cls]) if int(v) > 0)
pred_ids = sorted(
int(v) for v in np.unique(pred_instance[pred_mask_cls]) if int(v) > 0
)
if not gt_ids and not pred_ids:
continue
matched_preds: set[int] = set()
cls_tp = 0
cls_iou_sum = 0.0
for gid in gt_ids:
g_mask = gt_mask_cls if is_stuff else (gt_mask_cls & (gt_instance == gid))
g_area = int(np.sum(g_mask))
if g_area == 0:
continue
for pid in pred_ids:
if pid in matched_preds:
continue
p_mask = pred_mask_cls if is_stuff else (pred_mask_cls & (pred_instance == pid))
inter = int(np.sum(g_mask & p_mask))
if inter == 0:
continue
union = g_area + int(np.sum(p_mask)) - inter
iou = inter / float(union)
if iou > 0.5:
cls_tp += 1
cls_iou_sum += iou
matched_preds.add(pid)
break
cls_fp = len(pred_ids) - cls_tp
cls_fn = len(gt_ids) - cls_tp
cls_sq = (cls_iou_sum / cls_tp) if cls_tp > 0 else 0.0
denom = cls_tp + 0.5 * cls_fp + 0.5 * cls_fn
cls_rq = (cls_tp / denom) if denom > 0 else 0.0
cls_pq = cls_sq * cls_rq
per_class[cls_id] = {
"pq": cls_pq,
"sq": cls_sq,
"rq": cls_rq,
"tp": float(cls_tp),
"fp": float(cls_fp),
"fn": float(cls_fn),
}
total_tp += cls_tp
total_fp += cls_fp
total_fn += cls_fn
total_iou_sum += cls_iou_sum
# Micro/global exact PQ = SQ * RQ over all segments
sq = (total_iou_sum / total_tp) if total_tp > 0 else 0.0
denom_all = total_tp + 0.5 * total_fp + 0.5 * total_fn
rq = (total_tp / denom_all) if denom_all > 0 else 0.0
pq = sq * rq
thing_pqs = [per_class[c]["pq"] for c in thing_classes if c in per_class]
stuff_pqs = [per_class[c]["pq"] for c in stuff_classes if c in per_class]
return PanopticResult(
pq=pq,
sq=sq,
rq=rq,
pq_things=float(np.mean(thing_pqs)) if thing_pqs else 0.0,
pq_stuff=float(np.mean(stuff_pqs)) if stuff_pqs else 0.0,
tp=total_tp,
fp=total_fp,
fn=total_fn,
per_class=per_class,
)
def generate_synthetic_panoptic_scene(
height: int = 96,
width: int = 128,
) -> tuple[IntArray, IntArray, IntArray, IntArray, IntArray, IntArray]:
"""Generate a synthetic road panoptic scene (stuff: sky=0, road=1; things: car=2, truck=3).
Returns:
gt_sem, gt_inst,
good_pred_sem, good_pred_inst (high PQ, slight boundary jitter),
merged_pred_sem, merged_pred_inst (identical high semantic mIoU, but two cars merged into
one instance ID — demonstrating why semantic mIoU hides instance merging failures!).
"""
gt_sem = np.zeros((height, width), dtype=np.int32)
gt_inst = np.zeros((height, width), dtype=np.int32)
# Stuff: sky (0) top half, road (1) bottom half
gt_sem[height // 2 :, :] = 1
# Thing instances: 3 cars (class 2, inst 1,2,3) and 1 truck (class 3, inst 4)
car_boxes = [
(54, 14, 78, 38, 1),
(54, 42, 78, 66, 2),
(58, 74, 82, 96, 3),
]
for y1, x1, y2, x2, iid in car_boxes:
gt_sem[y1:y2, x1:x2] = 2
gt_inst[y1:y2, x1:x2] = iid
# Truck (class 3, inst 4)
gt_sem[44:78, 100:124] = 3
gt_inst[44:78, 100:124] = 4
# Good panoptic prediction: slight 1-px boundary shift on instances, all separated
good_sem = gt_sem.copy()
good_inst = np.zeros_like(gt_inst)
good_sem[height // 2 :, :] = 1
for y1, x1, y2, x2, iid in car_boxes:
good_sem[y1 + 1 : y2, x1 : x2 - 1] = 2
good_inst[y1 + 1 : y2, x1 : x2 - 1] = iid
good_sem[45:78, 100:123] = 3
good_inst[45:78, 100:123] = 4
# Merged-instance failure mode: exact same semantic map as GT (mIoU ~ 1.0!),
# but cars 1 and 2 are fused into a single instance ID = 1.
merged_sem = gt_sem.copy()
merged_inst = gt_inst.copy()
merged_inst[gt_inst == 2] = 1
return gt_sem, gt_inst, good_sem, good_inst, merged_sem, merged_inst
"""Tier 2 (PyTorch 2.15 CPU + ONNX Runtime + Safetensors) Vision Backbones, LoRA & CLIP/SigLIP."""
from __future__ import annotations
import time
from dataclasses import dataclass
from pathlib import Path
import numpy as np
import onnx
import onnxruntime as ort
import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors.torch import load_file, save_file
class ConvNeXtBlock(nn.Module):
"""Modern ConvNeXt block: 7x7 depthwise conv -> LayerNorm -> 4x inverted bottleneck GELU."""
def __init__(self, dim: int, mlp_ratio: int = 4) -> None:
super().__init__()
self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)
self.norm = nn.LayerNorm(dim)
self.pwconv1 = nn.Linear(dim, dim * mlp_ratio)
self.act = nn.GELU()
self.pwconv2 = nn.Linear(dim * mlp_ratio, dim)
self.gamma = nn.Parameter(torch.full((dim,), 1e-2))
def forward(self, x: torch.Tensor) -> torch.Tensor:
residual = x
h = self.dwconv(x)
h = h.permute(0, 2, 3, 1) # NCHW -> NHWC
h = self.norm(h)
h = self.pwconv1(h)
h = self.act(h)
h = self.pwconv2(h)
h = self.gamma * h
h = h.permute(0, 3, 1, 2) # NHWC -> NCHW
return residual + h
class MiniConvNeXt(nn.Module):
"""Compact ConvNeXt edge vehicle classifier/feature backbone (100% offline CPU-friendly)."""
def __init__(self, in_chans: int = 3, dim: int = 48, depth: int = 2, num_classes: int = 3) -> None:
super().__init__()
self.stem = nn.Conv2d(in_chans, dim, kernel_size=4, stride=4)
self.blocks = nn.Sequential(*[ConvNeXtBlock(dim=dim) for _ in range(depth)])
self.norm = nn.LayerNorm(dim)
self.head = nn.Linear(dim, num_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor:
h = self.stem(x)
h = self.blocks(h)
h = h.mean(dim=(2, 3))
h = self.norm(h)
return self.head(h)
class LoRALinear(nn.Module):
"""Low-Rank Adaptation wrapper: y = W_0 x + (alpha / r) B A x with zero-delta init (B = 0)."""
def __init__(self, base_linear: nn.Linear, rank: int = 4, alpha: float = 8.0) -> None:
super().__init__()
if rank <= 0:
raise ValueError("LoRA rank must be positive.")
self.base = base_linear
self.rank = rank
self.alpha = alpha
self.scaling = alpha / float(rank)
in_features = base_linear.in_features
out_features = base_linear.out_features
self.lora_a = nn.Parameter(torch.empty(rank, in_features))
self.lora_b = nn.Parameter(torch.zeros(out_features, rank))
nn.init.kaiming_uniform_(self.lora_a, a=float(np.sqrt(5.0)))
# Freeze pretrained base weight & bias
for p in self.base.parameters():
p.requires_grad = False
def forward(self, x: torch.Tensor) -> torch.Tensor:
base_out = self.base(x)
lora_out = F.linear(F.linear(x, self.lora_a), self.lora_b) * self.scaling
return base_out + lora_out
class _MiniViTBlock(nn.Module):
"""Pre-LN Vision Transformer encoder block with optional LoRA on QKV projections."""
def __init__(
self,
embed_dim: int,
num_heads: int,
mlp_ratio: int = 4,
use_lora: bool = False,
lora_rank: int = 4,
lora_alpha: float = 8.0,
) -> None:
super().__init__()
if embed_dim % num_heads != 0:
raise ValueError("embed_dim must be divisible by num_heads.")
self.embed_dim = embed_dim
self.num_heads = num_heads
self.head_dim = embed_dim // num_heads
self.scale = self.head_dim**-0.5
self.norm1 = nn.LayerNorm(embed_dim)
qkv_base = nn.Linear(embed_dim, embed_dim * 3)
self.qkv: nn.Module = (
LoRALinear(qkv_base, rank=lora_rank, alpha=lora_alpha) if use_lora else qkv_base
)
self.proj = nn.Linear(embed_dim, embed_dim)
self.norm2 = nn.LayerNorm(embed_dim)
self.mlp = nn.Sequential(
nn.Linear(embed_dim, embed_dim * mlp_ratio),
nn.GELU(),
nn.Linear(embed_dim * mlp_ratio, embed_dim),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
b, n, d = x.shape
h = self.norm1(x)
qkv = self.qkv(h).reshape(b, n, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
attn = torch.matmul(q, k.transpose(-2, -1)) * self.scale
attn = torch.softmax(attn, dim=-1)
out = torch.matmul(attn, v).transpose(1, 2).reshape(b, n, d)
x = x + self.proj(out)
x = x + self.mlp(self.norm2(x))
return x
class MiniViT(nn.Module):
"""Compact Vision Transformer (ViT) with patchify N=HW/P^2 and optional LoRA PEFT mode."""
def __init__(
self,
image_size: int = 64,
patch_size: int = 8,
in_chans: int = 3,
embed_dim: int = 64,
depth: int = 2,
num_heads: int = 4,
num_classes: int = 3,
use_lora: bool = False,
lora_rank: int = 4,
lora_alpha: float = 8.0,
) -> None:
super().__init__()
if image_size % patch_size != 0:
raise ValueError("image_size must be divisible by patch_size.")
self.image_size = image_size
self.patch_size = patch_size
self.num_patches = (image_size // patch_size) ** 2
self.use_lora = use_lora
self.patch_embed = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
self.pos_embed = nn.Parameter(torch.randn(1, self.num_patches + 1, embed_dim) * 0.02)
self.blocks = nn.ModuleList(
[
_MiniViTBlock(
embed_dim=embed_dim,
num_heads=num_heads,
use_lora=use_lora,
lora_rank=lora_rank,
lora_alpha=lora_alpha,
)
for _ in range(depth)
]
)
self.norm = nn.LayerNorm(embed_dim)
self.head = nn.Linear(embed_dim, num_classes)
if use_lora:
# Freeze all base backbone parameters; keep ONLY LoRA adapters and classification head trainable
for name, param in self.named_parameters():
if ("lora_a" in name) or ("lora_b" in name) or name.startswith("head."):
param.requires_grad = True
else:
param.requires_grad = False
def forward(self, x: torch.Tensor) -> torch.Tensor:
b = x.shape[0]
tokens = self.patch_embed(x).flatten(2).transpose(1, 2) # (B, N, D)
cls_tokens = self.cls_token.expand(b, -1, -1)
h = torch.cat([cls_tokens, tokens], dim=1) + self.pos_embed
for blk in self.blocks:
h = blk(h)
h = self.norm(h)
return self.head(h[:, 0])
def count_parameters(model: nn.Module) -> dict[str, float]:
"""Return total parameters, trainable parameters, and trainable ratio."""
total = sum(p.numel() for p in model.parameters())
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
return {
"total_params": float(total),
"trainable_params": float(trainable),
"trainable_ratio": float(trainable / max(1, total)),
}
def clip_infonce_loss(
image_embeds: torch.Tensor,
text_embeds: torch.Tensor,
logit_scale: float = 10.0,
) -> torch.Tensor:
"""Symmetric bidirectional CLIP InfoNCE softmax contrastive loss (Radford et al., 2021)."""
u = F.normalize(image_embeds, p=2, dim=-1)
v = F.normalize(text_embeds, p=2, dim=-1)
logits = logit_scale * torch.matmul(u, v.transpose(0, 1))
targets = torch.arange(logits.shape[0], device=logits.device, dtype=torch.long)
loss_i2t = F.cross_entropy(logits, targets)
loss_t2i = F.cross_entropy(logits.transpose(0, 1), targets)
return 0.5 * (loss_i2t + loss_t2i)
def siglip_sigmoid_loss(
image_embeds: torch.Tensor,
text_embeds: torch.Tensor,
logit_scale: float = 10.0,
logit_bias: float = -5.0,
) -> torch.Tensor:
"""Pairwise Sigmoid Language-Image Pretraining (SigLIP) loss (Zhai et al., ICCV 2023)."""
u = F.normalize(image_embeds, p=2, dim=-1)
v = F.normalize(text_embeds, p=2, dim=-1)
b = u.shape[0]
logits = logit_scale * torch.matmul(u, v.transpose(0, 1)) + logit_bias
labels = 2.0 * torch.eye(b, device=logits.device, dtype=logits.dtype) - 1.0
# -log(sigmoid(y_ij * z_ij)) = softplus(-y_ij * z_ij)
return F.softplus(-labels * logits).sum() / float(b)
def save_and_verify_safetensors(model: nn.Module, path: Path) -> dict[str, float]:
"""Save state_dict via zero-pickle safetensors and verify exact bit-level roundtrip parity."""
path.parent.mkdir(parents=True, exist_ok=True)
orig_sd = {k: v.detach().cpu().contiguous() for k, v in model.state_dict().items()}
save_file(orig_sd, str(path))
reloaded = load_file(str(path))
max_diff = 0.0
for k, orig_t in orig_sd.items():
diff = float((orig_t - reloaded[k]).abs().max().item())
max_diff = max(max_diff, diff)
return {
"file_bytes": float(path.stat().st_size),
"tensor_count": float(len(reloaded)),
"max_abs_diff": max_diff,
}
@dataclass(frozen=True, slots=True)
class OnnxBenchmarkResult:
"""ONNX export verification & ONNX Runtime CPU edge latency report."""
onnx_bytes: int
max_abs_diff: float
p50_latency_ms: float
p95_latency_ms: float
fps_estimate: float
meets_30fps_budget: bool
def export_and_benchmark_onnx(
model: nn.Module,
onnx_path: Path,
input_shape: tuple[int, int, int, int] = (1, 3, 64, 64),
n_warmup: int = 5,
n_runs: int = 40,
seed: int = 42,
) -> OnnxBenchmarkResult:
"""Export PyTorch model with dynamo=False, verify ORT CPU numerical parity & 30 FPS budget."""
onnx_path.parent.mkdir(parents=True, exist_ok=True)
model_eval = model.eval()
gen = torch.Generator().manual_seed(seed)
sample = torch.randn(input_shape, generator=gen, dtype=torch.float32)
with torch.no_grad():
torch_out = model_eval(sample).cpu().numpy()
# CRITICAL: Always use dynamo=False on PyTorch 2.15 CPU without onnxscript
torch.onnx.export(
model_eval,
(sample,),
str(onnx_path),
input_names=["image"],
output_names=["logits"],
opset_version=17,
dynamo=False,
)
onnx_model = onnx.load(str(onnx_path))
onnx.checker.check_model(onnx_model)
sess_opts = ort.SessionOptions()
sess_opts.intra_op_num_threads = 1
sess_opts.inter_op_num_threads = 1
session = ort.InferenceSession(
str(onnx_path),
sess_options=sess_opts,
providers=["CPUExecutionProvider"],
)
sample_np = sample.numpy()
ort_out = np.asarray(session.run(["logits"], {"image": sample_np})[0], dtype=np.float32)
max_abs_diff = float(np.max(np.abs(torch_out - ort_out)))
for _ in range(n_warmup):
session.run(["logits"], {"image": sample_np})
latencies_ms: list[float] = []
for _ in range(n_runs):
t0 = time.perf_counter()
session.run(["logits"], {"image": sample_np})
latencies_ms.append((time.perf_counter() - t0) * 1000.0)
p50_ms = float(np.percentile(latencies_ms, 50))
p95_ms = float(np.percentile(latencies_ms, 95))
fps_est = 1000.0 / max(p50_ms, 1e-6)
return OnnxBenchmarkResult(
onnx_bytes=int(onnx_path.stat().st_size),
max_abs_diff=max_abs_diff,
p50_latency_ms=p50_ms,
p95_latency_ms=p95_ms,
fps_estimate=fps_est,
meets_30fps_budget=(p95_ms < 33.3),
)
"""CLI benchmark script for Lab 09 exporting artifacts/ch17_lab09_results.json."""
from __future__ import annotations
import argparse
import json
import tempfile
from dataclasses import asdict
from pathlib import Path
from typing import Any
import numpy as np
import torch
from modern_cv_tracking_lab.detection_metrics import (
DetectionPrediction,
GroundTruthBox,
compute_ciou_matrix,
compute_giou_matrix,
compute_iou_matrix,
compute_map_50_95,
greedy_nms,
soft_nms,
)
from modern_cv_tracking_lab.segmentation_metrics import (
compute_panoptic_quality,
compute_semantic_miou,
generate_synthetic_panoptic_scene,
)
from modern_cv_tracking_lab.tracking_and_counting import (
ByteTrackTracker,
SORTTracker,
evaluate_mot_sequence,
)
from modern_cv_tracking_lab.traffic_simulator import simulate_highway_traffic
from modern_cv_tracking_lab.vision_backbones_and_vlm import (
MiniConvNeXt,
MiniViT,
clip_infonce_loss,
count_parameters,
export_and_benchmark_onnx,
save_and_verify_safetensors,
siglip_sigmoid_loss,
)
def run_benchmark(seed: int = 42, n_frames: int = 100) -> dict[str, Any]:
"""Execute full Tier 1 + Tier 2 Lab 09 benchmark deterministically offline."""
torch.manual_seed(seed)
np.random.seed(seed)
# 1. Detection geometry: IoU vs GIoU vs CIoU & Greedy NMS vs Soft-NMS on crowded scene
gt_box = np.array([[100.0, 100.0, 160.0, 180.0]], dtype=np.float64)
disjoint_near = np.array([[172.0, 100.0, 232.0, 180.0]], dtype=np.float64)
disjoint_far = np.array([[280.0, 100.0, 340.0, 180.0]], dtype=np.float64)
geometry_audit = {
"disjoint_near_iou": float(compute_iou_matrix(gt_box, disjoint_near)[0, 0]),
"disjoint_far_iou": float(compute_iou_matrix(gt_box, disjoint_far)[0, 0]),
"disjoint_near_giou": float(compute_giou_matrix(gt_box, disjoint_near)[0, 0]),
"disjoint_far_giou": float(compute_giou_matrix(gt_box, disjoint_far)[0, 0]),
"disjoint_near_ciou": float(compute_ciou_matrix(gt_box, disjoint_near)[0, 0]),
"disjoint_far_ciou": float(compute_ciou_matrix(gt_box, disjoint_far)[0, 0]),
}
# Crowded lane pair: two overlapping vehicles (IoU ~ 0.56) + 1 duplicate prediction
crowded_boxes = np.array(
[
[100.0, 100.0, 160.0, 180.0], # Car A primary
[103.0, 102.0, 162.0, 182.0], # Car A duplicate (IoU ~ 0.87)
[117.0, 100.0, 177.0, 180.0], # Car B closely adjacent (IoU ~ 0.56 with A)
],
dtype=np.float64,
)
crowded_scores = np.array([0.92, 0.74, 0.81], dtype=np.float64)
greedy_keep = greedy_nms(crowded_boxes, crowded_scores, iou_threshold=0.50)
soft_keep, soft_scores = soft_nms(crowded_boxes, crowded_scores, sigma=0.50, score_threshold=0.30)
# 2. Simulate highway traffic & evaluate COCO mAP@50:95 on detector outputs
seq = simulate_highway_traffic(n_frames=n_frames, seed=seed, tripwire_y=242.0)
preds_all: list[DetectionPrediction] = []
gts_all: list[GroundTruthBox] = []
preds_high_only: list[DetectionPrediction] = []
for obs in seq.frames:
for g in obs.gt_vehicles:
gts_all.append(GroundTruthBox(image_id=obs.frame_id, class_id=g.class_id, box=g.box))
for d in obs.detections:
pred = DetectionPrediction(
image_id=obs.frame_id, class_id=d.class_id, score=d.score, box=d.box
)
preds_all.append(pred)
if d.score >= 0.55:
preds_high_only.append(pred)
coco_all = compute_map_50_95(preds_all, gts_all)
coco_high_only = compute_map_50_95(preds_high_only, gts_all)
# 3. Multi-Object Tracking & Directional Tripwire Counting: SORT vs ByteTrack
sort_res = evaluate_mot_sequence(
seq,
SORTTracker(high_conf_thresh=0.55, iou_threshold=0.25, max_age=3, min_hits=3),
tracker_name="SORT (High-Conf Only)",
)
byte_res = evaluate_mot_sequence(
seq,
ByteTrackTracker(
high_conf_thresh=0.55,
low_conf_thresh=0.15,
stage1_iou_threshold=0.25,
stage2_iou_threshold=0.20,
max_age=3,
min_hits=3,
),
tracker_name="ByteTrack (2-Stage Recovery)",
)
# 4. Segmentation: Semantic mIoU vs Panoptic Quality (PQ = SQ * RQ)
gt_sem, gt_inst, good_sem, good_inst, merged_sem, merged_inst = generate_synthetic_panoptic_scene()
good_sem_metrics = compute_semantic_miou(good_sem, gt_sem, num_classes=4)
merged_sem_metrics = compute_semantic_miou(merged_sem, gt_sem, num_classes=4)
good_pq = compute_panoptic_quality(good_sem, good_inst, gt_sem, gt_inst)
merged_pq = compute_panoptic_quality(merged_sem, merged_inst, gt_sem, gt_inst)
# 5. Tier 2 Backbones (MiniConvNeXt vs MiniViT + LoRA), CLIP vs SigLIP, Safetensors & ONNX
convnext = MiniConvNeXt(in_chans=3, dim=48, depth=2, num_classes=3)
vit_full = MiniViT(
image_size=64, patch_size=8, embed_dim=64, depth=2, num_heads=4, num_classes=3, use_lora=False
)
vit_lora = MiniViT(
image_size=64,
patch_size=8,
embed_dim=64,
depth=2,
num_heads=4,
num_classes=3,
use_lora=True,
lora_rank=4,
lora_alpha=8.0,
)
convnext_params = count_parameters(convnext)
vit_full_params = count_parameters(vit_full)
vit_lora_params = count_parameters(vit_lora)
# CLIP vs SigLIP behavior across small batch (B=4) vs larger batch (B=32)
g_vlm = torch.Generator().manual_seed(seed)
vlm_batches: dict[str, dict[str, float]] = {}
for b_size in (4, 32):
base_img = torch.randn((b_size, 32), generator=g_vlm)
aligned_txt = base_img + 0.15 * torch.randn((b_size, 32), generator=g_vlm)
rand_txt = torch.randn((b_size, 32), generator=g_vlm)
vlm_batches[f"batch_{b_size}"] = {
"clip_aligned_loss": float(clip_infonce_loss(base_img, aligned_txt).item()),
"clip_random_loss": float(clip_infonce_loss(base_img, rand_txt).item()),
"clip_ln_b_ref": float(np.log(b_size)),
"siglip_aligned_loss": float(siglip_sigmoid_loss(base_img, aligned_txt).item()),
"siglip_random_loss": float(siglip_sigmoid_loss(base_img, rand_txt).item()),
}
with tempfile.TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
sf_report = save_and_verify_safetensors(convnext, tmp / "mini_convnext.safetensors")
onnx_convnext = export_and_benchmark_onnx(
convnext, tmp / "mini_convnext.onnx", input_shape=(1, 3, 64, 64), seed=seed
)
onnx_vit = export_and_benchmark_onnx(
vit_full, tmp / "mini_vit.onnx", input_shape=(1, 3, 64, 64), seed=seed
)
hota_gain = byte_res.hota - sort_res.hota
idsw_reduction = sort_res.id_switches - byte_res.id_switches
workbench_panels = {
"kpis": [
{
"id": "kpi_detection_map_50_95",
"label": "Detector COCO mAP@50:95 & AP@50",
"value": f"{coco_all['map_50_95']:.3f}",
"unit": f"(AP@50 {coco_all['ap50']:.3f})",
"status": "ok",
"detail": (
f"High-conf cutoff drops AP@50 to {coco_high_only['ap50']:.3f}; "
f"Soft-NMS keeps {len(soft_keep)} vs Greedy {len(greedy_keep)} crowded cars."
),
},
{
"id": "kpi_bytetrack_vs_sort_hota",
"label": "ByteTrack vs SORT HOTA Gain",
"value": f"{byte_res.hota:.3f}",
"unit": f"(+{hota_gain:.3f} vs SORT)",
"status": "ok",
"detail": (
f"ByteTrack HOTA={byte_res.hota:.3f} (AssA={byte_res.ass_a:.3f}) vs "
f"SORT HOTA={sort_res.hota:.3f} (AssA={sort_res.ass_a:.3f})."
),
},
{
"id": "kpi_idsw_and_tripwire_count",
"label": "ID Switches & Tripwire Count Accuracy",
"value": f"{byte_res.counting_accuracy * 100.0:.1f}%",
"unit": f"(IDSW {sort_res.id_switches} -> {byte_res.id_switches})",
"status": "ok",
"detail": (
f"ByteTrack counts {byte_res.pred_count_down}D/{byte_res.pred_count_up}U "
f"(GT {byte_res.gt_count_down}D/{byte_res.gt_count_up}U) vs SORT "
f"{sort_res.pred_count_down}D/{sort_res.pred_count_up}U."
),
},
{
"id": "kpi_panoptic_pq_identity",
"label": "Panoptic Quality (PQ = SQ * RQ)",
"value": f"{good_pq.pq:.3f}",
"unit": f"(Merged PQ {merged_pq.pq:.3f})",
"status": "ok",
"detail": (
f"Merged scene keeps Semantic mIoU={merged_sem_metrics['miou']:.3f} "
f"but PQ_things collapses from {good_pq.pq_things:.3f} to {merged_pq.pq_things:.3f}."
),
},
{
"id": "kpi_vit_lora_efficiency",
"label": "MiniViT LoRA Trainable Ratio",
"value": f"{vit_lora_params['trainable_ratio'] * 100.0:.2f}%",
"unit": (
f"({int(vit_lora_params['trainable_params'])} / "
f"{int(vit_lora_params['total_params'])})"
),
"status": "ok",
"detail": (
f"Frozen ViT base with rank-4 QKV LoRA (< 15% gate); "
f"MiniConvNeXt has {int(convnext_params['total_params'])} params."
),
},
{
"id": "kpi_onnx_edge_30fps_parity",
"label": "ONNX ORT CPU Latency & Parity",
"value": f"{onnx_convnext.p50_latency_ms:.2f} ms",
"unit": (
f"({onnx_convnext.fps_estimate:.0f} FPS | "
f"diff {onnx_convnext.max_abs_diff:.1e})"
),
"status": "ok",
"detail": (
f"dynamo=False ORT CPU < 33.3 ms 30 FPS budget; "
f"ViT p50={onnx_vit.p50_latency_ms:.2f} ms; "
f"safetensors diff={sf_report['max_abs_diff']:.1e}."
),
},
],
"bars": [
{
"id": "bar_tracker_hota_idf1",
"title": "Occluded Highway MOT Accuracy: SORT vs ByteTrack (Higher is Better)",
"metric_label": "Score (0..1)",
"items": [
{
"label": "sort_hota",
"value": sort_res.hota,
"display": f"SORT HOTA {sort_res.hota:.3f} (IDSW={sort_res.id_switches})",
"css_class": "is-slow",
},
{
"label": "bytetrack_hota",
"value": byte_res.hota,
"display": f"ByteTrack HOTA {byte_res.hota:.3f} (IDSW={byte_res.id_switches})",
"css_class": "is-fast",
},
{
"label": "sort_idf1",
"value": sort_res.idf1,
"display": f"SORT IDF1 {sort_res.idf1:.3f}",
"css_class": "is-slow",
},
{
"label": "bytetrack_idf1",
"value": byte_res.idf1,
"display": f"ByteTrack IDF1 {byte_res.idf1:.3f}",
"css_class": "is-fast",
},
],
},
{
"id": "bar_tripwire_counting_accuracy",
"title": "Directional Tripwire Vehicle Counting Accuracy (16 Highway Vehicles)",
"metric_label": "Accuracy (%)",
"items": [
{
"label": "sort_counting_acc",
"value": sort_res.counting_accuracy * 100.0,
"display": (
f"SORT {sort_res.counting_accuracy * 100.0:.1f}% "
f"({sort_res.pred_count_down + sort_res.pred_count_up}/"
f"{sort_res.gt_count_down + sort_res.gt_count_up})"
),
"css_class": "is-slow",
},
{
"label": "bytetrack_counting_acc",
"value": byte_res.counting_accuracy * 100.0,
"display": (
f"ByteTrack {byte_res.counting_accuracy * 100.0:.1f}% "
f"({byte_res.pred_count_down + byte_res.pred_count_up}/"
f"{byte_res.gt_count_down + byte_res.gt_count_up})"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_panoptic_vs_semantic",
"title": "Why Semantic mIoU Hides Merged Instances vs Panoptic Quality (PQ)",
"metric_label": "Metric (0..1)",
"items": [
{
"label": "merged_semantic_miou",
"value": merged_sem_metrics["miou"],
"display": f"Merged Semantic mIoU {merged_sem_metrics['miou']:.3f} (Blind!)",
"css_class": "is-mid",
},
{
"label": "merged_panoptic_pq_things",
"value": merged_pq.pq_things,
"display": f"Merged PQ_things {merged_pq.pq_things:.3f} (Exposed!)",
"css_class": "is-slow",
},
{
"label": "good_panoptic_pq_things",
"value": good_pq.pq_things,
"display": f"Clean PQ_things {good_pq.pq_things:.3f}",
"css_class": "is-fast",
},
{
"label": "good_panoptic_pq_all",
"value": good_pq.pq,
"display": f"Clean Overall PQ {good_pq.pq:.3f}",
"css_class": "is-fast",
},
],
},
{
"id": "bar_onnx_edge_latency_ms",
"title": "ONNX Runtime CPU Edge Latency vs 30 FPS Real-Time Budget (33.3 ms)",
"metric_label": "Latency (ms)",
"items": [
{
"label": "mini_convnext_ort_p50",
"value": onnx_convnext.p50_latency_ms,
"display": f"MiniConvNeXt p50 {onnx_convnext.p50_latency_ms:.2f} ms",
"css_class": "is-fast",
},
{
"label": "mini_vit_ort_p50",
"value": onnx_vit.p50_latency_ms,
"display": f"MiniViT p50 {onnx_vit.p50_latency_ms:.2f} ms",
"css_class": "is-fast",
},
{
"label": "realtime_30fps_sla",
"value": 33.3,
"display": "30 FPS Edge Budget 33.30 ms",
"css_class": "is-mid",
},
],
},
],
"tables": [
{
"id": "tbl_detection_geometry_nms",
"title": "Detection Geometry (IoU/GIoU/CIoU), NMS vs Soft-NMS & COCO mAP",
"columns": ["Metric / Method", "Condition", "Observed Value", "Insight"],
"rows": [
[
"IoU (Disjoint Near vs Far)",
"Non-overlapping boxes",
(
f"{geometry_audit['disjoint_near_iou']:.3f} vs "
f"{geometry_audit['disjoint_far_iou']:.3f}"
),
"Zero gradient plateau",
],
[
"GIoU (Disjoint Near vs Far)",
"Non-overlapping boxes",
(
f"{geometry_audit['disjoint_near_giou']:.3f} vs "
f"{geometry_audit['disjoint_far_giou']:.3f}"
),
"Smooth enclosing-box gradient",
],
[
"CIoU (Disjoint Near vs Far)",
"Center + aspect penalty",
(
f"{geometry_audit['disjoint_near_ciou']:.3f} vs "
f"{geometry_audit['disjoint_far_ciou']:.3f}"
),
"Faster geometric convergence",
],
[
"Greedy NMS vs Soft-NMS",
"Crowded lane (IoU=0.56)",
f"Greedy kept {len(greedy_keep)} | Soft kept {len(soft_keep)}",
"Soft-NMS saves occluded neighbor",
],
[
"COCO AP@50 & mAP@50:95",
"All dets vs High-conf >=0.55",
(
f"AP@50 {coco_all['ap50']:.3f}->{coco_high_only['ap50']:.3f} | "
f"mAP {coco_all['map_50_95']:.3f}"
),
"Occlusion drops recall if cut early",
],
],
},
{
"id": "tbl_mot_sort_vs_bytetrack",
"title": "Multi-Object Tracking & Directional Tripwire Counting (100 Frames, 16 Vehicles)",
"columns": ["Tracker", "MOTA / IDF1", "HOTA (DetA / AssA)", "IDSW & Count Acc"],
"rows": [
[
sort_res.tracker_name,
f"{sort_res.mota:.3f} / {sort_res.idf1:.3f}",
f"{sort_res.hota:.3f} ({sort_res.det_a:.3f} / {sort_res.ass_a:.3f})",
f"IDSW={sort_res.id_switches} | Acc={sort_res.counting_accuracy * 100.0:.1f}%",
],
[
byte_res.tracker_name,
f"{byte_res.mota:.3f} / {byte_res.idf1:.3f}",
f"{byte_res.hota:.3f} ({byte_res.det_a:.3f} / {byte_res.ass_a:.3f})",
(
f"IDSW={byte_res.id_switches} (-{idsw_reduction}) | "
f"Acc={byte_res.counting_accuracy * 100.0:.1f}%"
),
],
],
},
{
"id": "tbl_panoptic_and_vlm",
"title": "Panoptic Segmentation (PQ = SQ * RQ) & Vision-Language (CLIP vs SigLIP)",
"columns": ["Task / Loss", "Regime", "Observed Value", "Contract Gate"],
"rows": [
[
"Clean Panoptic Prediction",
"PQ = SQ * RQ",
f"PQ={good_pq.pq:.3f} (SQ={good_pq.sq:.3f}, RQ={good_pq.rq:.3f})",
"Exact identity PASS",
],
[
"Merged-Cars Failure Mode",
"mIoU vs PQ_things",
f"mIoU={merged_sem_metrics['miou']:.3f} | PQ_things={merged_pq.pq_things:.3f}",
"PQ exposes fused instances",
],
[
"CLIP InfoNCE (B=4 vs B=32)",
"Aligned / Random",
(
f"B=4: {vlm_batches['batch_4']['clip_aligned_loss']:.3f}/"
f"{vlm_batches['batch_4']['clip_random_loss']:.3f} | "
f"B=32: {vlm_batches['batch_32']['clip_aligned_loss']:.3f}/"
f"{vlm_batches['batch_32']['clip_random_loss']:.3f}"
),
"Random floor scales ~ln(B)",
],
[
"SigLIP Sigmoid (B=4 vs B=32)",
"Aligned / Random",
(
f"B=4: {vlm_batches['batch_4']['siglip_aligned_loss']:.3f}/"
f"{vlm_batches['batch_4']['siglip_random_loss']:.3f} | "
f"B=32: {vlm_batches['batch_32']['siglip_aligned_loss']:.3f}/"
f"{vlm_batches['batch_32']['siglip_random_loss']:.3f}"
),
"Batch-decoupled pairwise loss",
],
],
},
{
"id": "tbl_backbones_lora_onnx",
"title": "Modern Vision Backbones (ConvNeXt / ViT + LoRA) & Edge ONNX Serving",
"columns": [
"Model / Artifact",
"Params (Trainable %)",
"ORT p50 / p95 (ms)",
"Parity / Gate",
],
"rows": [
[
"MiniConvNeXt (7x7 DW + LN)",
f"{int(convnext_params['total_params'])} (100.0%)",
f"{onnx_convnext.p50_latency_ms:.2f} / {onnx_convnext.p95_latency_ms:.2f} ms",
f"diff {onnx_convnext.max_abs_diff:.1e} (< 1e-4 PASS)",
],
[
"MiniViT Full (N=64 patches)",
f"{int(vit_full_params['total_params'])} (100.0%)",
f"{onnx_vit.p50_latency_ms:.2f} / {onnx_vit.p95_latency_ms:.2f} ms",
f"diff {onnx_vit.max_abs_diff:.1e} (< 1e-4 PASS)",
],
[
"MiniViT + LoRA (rank=4 QKV)",
f"{int(vit_lora_params['trainable_params'])}/{int(vit_lora_params['total_params'])} "
f"({vit_lora_params['trainable_ratio'] * 100.0:.2f}%)",
"Zero overhead (merged W)",
"< 15% trainable PASS",
],
[
"Safetensors Checkpoint",
f"{int(sf_report['file_bytes'])} B ({int(sf_report['tensor_count'])} tensors)",
"Zero-pickle mmap",
f"diff {sf_report['max_abs_diff']:.1e} (PASS)",
],
],
},
],
}
return {
"config": {
"seed": seed,
"n_frames": n_frames,
"tripwire_y": seq.tripwire_y,
"n_vehicles": seq.total_vehicle_tracks,
},
"detection_geometry": geometry_audit,
"nms_comparison": {
"greedy_kept_indices": greedy_keep,
"soft_kept_indices": soft_keep,
"soft_kept_scores": [float(s) for s in soft_scores.tolist()],
},
"coco_detection": {
"all_detections": coco_all,
"high_conf_only": coco_high_only,
},
"mot_tracking": {
"sort": asdict(sort_res),
"bytetrack": asdict(byte_res),
"hota_gain": hota_gain,
"idsw_reduction": idsw_reduction,
},
"segmentation": {
"good_semantic": good_sem_metrics,
"merged_semantic": merged_sem_metrics,
"good_panoptic": asdict(good_pq),
"merged_panoptic": asdict(merged_pq),
},
"backbones_and_peft": {
"mini_convnext": convnext_params,
"mini_vit_full": vit_full_params,
"mini_vit_lora": vit_lora_params,
},
"vlm_losses": vlm_batches,
"edge_serving": {
"safetensors": sf_report,
"onnx_convnext": asdict(onnx_convnext),
"onnx_vit": asdict(onnx_vit),
},
"workbench_panels": workbench_panels,
}
def main() -> None:
parser = argparse.ArgumentParser(description="Run Lab 09 Real-Time CV Tracking & Vision Benchmark.")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--frames", type=int, default=100)
parser.add_argument(
"--output",
type=Path,
default=Path(__file__).resolve().parents[1] / "artifacts" / "ch17_lab09_results.json",
)
args = parser.parse_args()
results = run_benchmark(seed=args.seed, n_frames=args.frames)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(results, indent=2), encoding="utf-8")
print(f"Wrote Lab 09 benchmark artifact -> {args.output}")
if __name__ == "__main__":
main()
"""16-test offline verification suite for Lab 09 (modern_cv_tracking_lab, T1-P3-U04)."""
from __future__ import annotations
import ast
import json
import sys
from pathlib import Path
import numpy as np
import pytest
import torch
from modern_cv_tracking_lab.detection_metrics import (
DetectionPrediction,
GroundTruthBox,
compute_ap,
compute_ciou_matrix,
compute_giou_matrix,
compute_iou_matrix,
compute_map_50_95,
greedy_nms,
soft_nms,
)
from modern_cv_tracking_lab.segmentation_metrics import (
compute_panoptic_quality,
compute_semantic_miou,
generate_synthetic_panoptic_scene,
)
from modern_cv_tracking_lab.tracking_and_counting import (
ByteTrackTracker,
KalmanBoxTracker,
SORTTracker,
TrackedObject,
TripwireVehicleCounter,
evaluate_mot_sequence,
)
from modern_cv_tracking_lab.traffic_simulator import simulate_highway_traffic
from modern_cv_tracking_lab.vision_backbones_and_vlm import (
MiniConvNeXt,
MiniViT,
clip_infonce_loss,
count_parameters,
export_and_benchmark_onnx,
save_and_verify_safetensors,
siglip_sigmoid_loss,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
SCRIPTS_DIR = LAB_ROOT / "scripts"
if str(SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPTS_DIR))
import run_lab_demo # noqa: E402
BANNED_UNSAFE_DESERIALIZERS = {"pickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
def test_01_ast_no_unsafe_deserializers_or_missing_packages() -> None:
"""AST security gate: ban unsafe deserializers and unapproved missing CV packages."""
py_files = list((LAB_ROOT / "src").rglob("*.py")) + list((LAB_ROOT / "scripts").rglob("*.py"))
assert len(py_files) >= 6
forbidden = BANNED_UNSAFE_DESERIALIZERS | {"torchvision", "cv2"}
for path in py_files:
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
top = alias.name.split(".")[0]
assert top not in forbidden, f"Forbidden import {top} in {path}"
elif isinstance(node, ast.ImportFrom) and node.module:
top = node.module.split(".")[0]
assert top not in forbidden, f"Forbidden from-import {top} in {path}"
def test_02_iou_giou_ciou_bounds_and_disjoint_monotonicity() -> None:
"""IoU/GIoU/CIoU satisfy bounds; GIoU & CIoU distinguish disjoint box distance unlike IoU."""
a = np.array([[10.0, 10.0, 50.0, 50.0]], dtype=np.float64)
same = np.array([[10.0, 10.0, 50.0, 50.0]], dtype=np.float64)
near = np.array([[60.0, 10.0, 100.0, 50.0]], dtype=np.float64)
far = np.array([[210.0, 10.0, 250.0, 50.0]], dtype=np.float64)
assert compute_iou_matrix(a, same)[0, 0] == pytest.approx(1.0)
assert compute_giou_matrix(a, same)[0, 0] == pytest.approx(1.0)
assert compute_ciou_matrix(a, same)[0, 0] == pytest.approx(1.0)
# Disjoint boxes: IoU is flat 0.0, while GIoU and CIoU strictly rank near > far
assert compute_iou_matrix(a, near)[0, 0] == pytest.approx(0.0)
assert compute_iou_matrix(a, far)[0, 0] == pytest.approx(0.0)
giou_near = float(compute_giou_matrix(a, near)[0, 0])
giou_far = float(compute_giou_matrix(a, far)[0, 0])
ciou_near = float(compute_ciou_matrix(a, near)[0, 0])
ciou_far = float(compute_ciou_matrix(a, far)[0, 0])
assert -1.0 <= giou_far < giou_near < 0.0
assert -1.0 <= ciou_far < ciou_near < 0.0
def test_03_greedy_nms_vs_soft_nms_on_crowded_vehicles() -> None:
"""Greedy NMS suppresses crowded neighbor at IoU=0.56 while Gaussian Soft-NMS preserves it."""
boxes = np.array(
[
[100.0, 100.0, 160.0, 180.0], # Car A
[103.0, 102.0, 162.0, 182.0], # Duplicate of Car A (IoU ~ 0.87)
[117.0, 100.0, 177.0, 180.0], # Adjacent Car B (IoU ~ 0.56)
],
dtype=np.float64,
)
scores = np.array([0.92, 0.74, 0.81], dtype=np.float64)
greedy_keep = greedy_nms(boxes, scores, iou_threshold=0.50)
soft_keep, soft_scores = soft_nms(boxes, scores, sigma=0.50, score_threshold=0.30)
assert greedy_keep == [0]
assert 0 in soft_keep and 2 in soft_keep
assert len(soft_keep) > len(greedy_keep)
# Adjacent Car B score was softly decayed below original 0.81 but still survives
idx_b = soft_keep.index(2)
assert 0.30 <= soft_scores[idx_b] < 0.81
def test_04_coco_ap_and_map_50_95_degrades_monotonically_with_jitter() -> None:
"""Exact COCO AP@50 and mAP@50:95 are 1.0 on perfect boxes and degrade smoothly with jitter."""
gts = [
GroundTruthBox(image_id=0, class_id=0, box=(10.0, 10.0, 60.0, 70.0)),
GroundTruthBox(image_id=0, class_id=1, box=(120.0, 20.0, 180.0, 100.0)),
GroundTruthBox(image_id=1, class_id=0, box=(30.0, 40.0, 80.0, 100.0)),
]
perfect_preds = [
DetectionPrediction(image_id=g.image_id, class_id=g.class_id, score=0.95, box=g.box)
for g in gts
]
mild_jitter_preds = [
DetectionPrediction(
image_id=g.image_id,
class_id=g.class_id,
score=0.90,
box=(g.box[0] + 4.0, g.box[1] + 4.0, g.box[2] + 4.0, g.box[3] + 4.0),
)
for g in gts
]
heavy_jitter_preds = [
DetectionPrediction(
image_id=g.image_id,
class_id=g.class_id,
score=0.85,
box=(g.box[0] + 18.0, g.box[1] + 18.0, g.box[2] + 18.0, g.box[3] + 18.0),
)
for g in gts
]
m_perf = compute_map_50_95(perfect_preds, gts)
m_mild = compute_map_50_95(mild_jitter_preds, gts)
m_heavy = compute_map_50_95(heavy_jitter_preds, gts)
assert m_perf["ap50"] == pytest.approx(1.0)
assert m_perf["map_50_95"] == pytest.approx(1.0)
assert m_perf["map_50_95"] > m_mild["map_50_95"] > m_heavy["map_50_95"] >= 0.0
assert compute_ap(perfect_preds, gts, class_id=0, iou_threshold=0.50) == pytest.approx(1.0)
def test_05_highway_traffic_simulator_determinism_and_occlusion_profile() -> None:
"""Traffic simulator is deterministic, includes 3 vehicle classes & occlusion score drops."""
seq1 = simulate_highway_traffic(n_frames=100, seed=42)
seq2 = simulate_highway_traffic(n_frames=100, seed=42)
assert len(seq1.frames) == 100
assert seq1.total_vehicle_tracks == 16
assert seq1.gt_counts_down == seq2.gt_counts_down and seq1.gt_counts_down >= 6
assert seq1.gt_counts_up == seq2.gt_counts_up and seq1.gt_counts_up >= 6
assert set(seq1.gt_counts_by_class.keys()) == {"car", "truck", "bus"}
assert all(v > 0 for v in seq1.gt_counts_by_class.values())
low_conf_tp = [
d.score
for f in seq1.frames
for d in f.detections
if (not d.is_false_positive) and d.score < 0.50
]
high_conf_tp = [
d.score
for f in seq1.frames
for d in f.detections
if (not d.is_false_positive) and d.score >= 0.60
]
assert len(low_conf_tp) >= 40
assert float(np.mean(low_conf_tp)) < 0.35
assert float(np.mean(high_conf_tp)) > 0.80
def test_06_kalman_constant_velocity_convergence_and_occlusion_coasting() -> None:
"""7D Kalman tracker learns true vertical velocity and coasts accurately during brief dropout."""
true_vy = 8.0
x0, y0, w, h = 100.0, 40.0, 50.0, 70.0
kf = KalmanBoxTracker((x0, y0, x0 + w, y0 + h), track_id=1, class_id=0)
for step in range(1, 15):
kf.predict()
cy_true = y0 + true_vy * step
kf.update((x0, cy_true, x0 + w, cy_true + h))
assert abs(float(kf.x[5]) - true_vy) < 0.6
# Coast 4 frames with zero observations and check predicted IoU against true position
for step in range(15, 19):
pred_box = kf.predict()
cy_true = y0 + true_vy * step
true_box = (x0, cy_true, x0 + w, cy_true + h)
iou = float(compute_iou_matrix([pred_box], [true_box])[0, 0])
assert iou > 0.85
def test_07_bytetrack_beats_sort_on_occluded_highway_hota_and_idsw() -> None:
"""ByteTrack stage-2 association clearly beats SORT on occluded highway IDSW, IDF1 & HOTA."""
seq = simulate_highway_traffic(n_frames=100, seed=42)
sort_res = evaluate_mot_sequence(
seq,
SORTTracker(high_conf_thresh=0.55, iou_threshold=0.25, max_age=3, min_hits=3),
tracker_name="SORT",
)
byte_res = evaluate_mot_sequence(
seq,
ByteTrackTracker(
high_conf_thresh=0.55,
low_conf_thresh=0.15,
stage1_iou_threshold=0.25,
stage2_iou_threshold=0.20,
max_age=3,
min_hits=3,
),
tracker_name="ByteTrack",
)
assert byte_res.id_switches < sort_res.id_switches
assert byte_res.hota > sort_res.hota + 0.08
assert byte_res.idf1 > sort_res.idf1 + 0.08
assert byte_res.mota > sort_res.mota + 0.05
assert byte_res.hota >= 0.78
def test_08_tripwire_counter_idempotency_and_bytetrack_counting_accuracy() -> None:
"""Tripwire counter never double-counts oscillating IDs and ByteTrack achieves high count acc."""
counter = TripwireVehicleCounter(tripwire_y=200.0)
# Simulate a single vehicle oscillating across y=200 multiple times
oscillating_ys = [190.0, 205.0, 195.0, 210.0, 192.0, 208.0]
for f_id, cy in enumerate(oscillating_ys):
counter.update(
[
TrackedObject(
frame_id=f_id,
track_id=77,
class_id=0,
score=0.9,
box=(100.0, cy - 20.0, 150.0, cy + 20.0),
)
]
)
assert counter.count_down == 1
assert counter.count_up == 0
assert counter.total_count == 1
seq = simulate_highway_traffic(n_frames=100, seed=42)
byte_res = evaluate_mot_sequence(seq, ByteTrackTracker(), tracker_name="ByteTrack")
sort_res = evaluate_mot_sequence(seq, SORTTracker(), tracker_name="SORT")
assert byte_res.counting_accuracy >= 0.90
assert byte_res.counting_accuracy >= sort_res.counting_accuracy
def test_09_semantic_miou_and_panoptic_pq_equals_sq_times_rq() -> None:
"""Panoptic PQ == SQ * RQ holds exactly; merged instances drop PQ_things while mIoU stays 1.0."""
gt_sem, gt_inst, good_sem, good_inst, merged_sem, merged_inst = generate_synthetic_panoptic_scene()
good_sem_m = compute_semantic_miou(good_sem, gt_sem, num_classes=4)
merged_sem_m = compute_semantic_miou(merged_sem, gt_sem, num_classes=4)
good_pq = compute_panoptic_quality(good_sem, good_inst, gt_sem, gt_inst)
merged_pq = compute_panoptic_quality(merged_sem, merged_inst, gt_sem, gt_inst)
assert good_pq.pq == pytest.approx(good_pq.sq * good_pq.rq, abs=1e-12)
assert merged_pq.pq == pytest.approx(merged_pq.sq * merged_pq.rq, abs=1e-12)
assert merged_sem_m["miou"] == pytest.approx(1.0)
assert good_sem_m["miou"] > 0.90
# Merging two cars into one instance destroys car-class PQ (-0.517) and drops overall PQ_things
assert good_pq.pq_things > merged_pq.pq_things + 0.20
assert good_pq.per_class[2]["pq"] > merged_pq.per_class[2]["pq"] + 0.50
def test_10_miniconvnext_and_minivit_shapes_and_patch_formula() -> None:
"""MiniConvNeXt and MiniViT produce expected logits shapes and exact ViT patch count N=HW/P^2."""
torch.manual_seed(42)
x = torch.randn(2, 3, 64, 64)
convnext = MiniConvNeXt(in_chans=3, dim=48, depth=2, num_classes=3)
vit = MiniViT(image_size=64, patch_size=8, embed_dim=64, depth=2, num_heads=4, num_classes=3)
assert vit.num_patches == (64 // 8) ** 2 == 64
out_c = convnext(x)
out_v = vit(x)
assert out_c.shape == (2, 3)
assert out_v.shape == (2, 3)
assert torch.isfinite(out_c).all() and torch.isfinite(out_v).all()
def test_11_minivit_lora_frozen_base_trainable_ratio_and_zero_delta_init() -> None:
"""MiniViT LoRA freezes base weights, keeps trainable ratio < 15%, and starts with B=0 parity."""
torch.manual_seed(7)
vit_lora = MiniViT(
image_size=64,
patch_size=8,
embed_dim=64,
depth=2,
num_heads=4,
num_classes=3,
use_lora=True,
lora_rank=4,
lora_alpha=8.0,
)
stats = count_parameters(vit_lora)
assert 0.0 < stats["trainable_ratio"] < 0.15
# Verify all lora_b tensors are initialized to exact zero and base qkv weights are frozen
for name, param in vit_lora.named_parameters():
if "lora_b" in name:
assert float(param.abs().max().item()) == 0.0
assert param.requires_grad is True
elif "qkv.base" in name:
assert param.requires_grad is False
# One backward step updates LoRA parameters without touching frozen base weights
x = torch.randn(2, 3, 64, 64)
loss = vit_lora(x).pow(2).mean()
loss.backward()
has_lora_grad = any(
p.grad is not None and float(p.grad.abs().sum().item()) > 0.0
for n, p in vit_lora.named_parameters()
if "lora_b" in n
)
assert has_lora_grad
def test_12_clip_infonce_vs_siglip_sigmoid_loss_invariants() -> None:
"""CLIP random baseline scales with ln(B); both CLIP & SigLIP prefer aligned pairs & backprop."""
gen = torch.Generator().manual_seed(123)
for b_size in (4, 32):
img = torch.randn((b_size, 32), generator=gen, requires_grad=True)
txt_aligned = (img.detach() + 0.1 * torch.randn((b_size, 32), generator=gen)).requires_grad_(
True
)
txt_random = torch.randn((b_size, 32), generator=gen)
c_aligned = clip_infonce_loss(img, txt_aligned)
c_random = clip_infonce_loss(img, txt_random)
s_aligned = siglip_sigmoid_loss(img, txt_aligned)
s_random = siglip_sigmoid_loss(img, txt_random)
assert float(c_aligned.item()) < float(c_random.item())
assert float(s_aligned.item()) < float(s_random.item())
(c_aligned + s_aligned).backward()
assert img.grad is not None and torch.isfinite(img.grad).all()
# CLIP random loss at B=32 is noticeably higher than at B=4 (~ln(32) vs ~ln(4))
g2 = torch.Generator().manual_seed(99)
c4 = float(
clip_infonce_loss(
torch.randn((4, 32), generator=g2), torch.randn((4, 32), generator=g2)
).item()
)
c32 = float(
clip_infonce_loss(
torch.randn((32, 32), generator=g2), torch.randn((32, 32), generator=g2)
).item()
)
assert c32 > c4 + 1.0
def test_13_safetensors_zero_pickle_roundtrip_exact_parity(tmp_path: Path) -> None:
"""Safetensors checkpoint round-trips with exact 0.0 max absolute tensor difference."""
torch.manual_seed(42)
model = MiniConvNeXt(in_chans=3, dim=48, depth=2, num_classes=3)
report = save_and_verify_safetensors(model, tmp_path / "backbone.safetensors")
assert report["file_bytes"] > 1000
assert report["tensor_count"] >= 10
assert report["max_abs_diff"] == 0.0
def test_14_onnx_dynamo_false_export_ort_cpu_parity_and_30fps_latency(tmp_path: Path) -> None:
"""ONNX export (dynamo=False) matches PyTorch within 1e-4 and beats 33.3 ms (30 FPS) SLA."""
torch.manual_seed(42)
model = MiniConvNeXt(in_chans=3, dim=48, depth=2, num_classes=3)
bench = export_and_benchmark_onnx(
model, tmp_path / "edge_vehicle.onnx", input_shape=(1, 3, 64, 64), n_warmup=3, n_runs=25
)
assert bench.onnx_bytes > 1000
assert bench.max_abs_diff < 1e-4
assert bench.p50_latency_ms < 33.3
assert bench.meets_30fps_budget is True
assert bench.fps_estimate > 30.0
def test_15_cli_benchmark_artifact_generation_and_schema(tmp_path: Path) -> None:
"""CLI run_benchmark produces complete JSON schema with finite metrics."""
res = run_lab_demo.run_benchmark(seed=42, n_frames=100)
out_file = tmp_path / "ch17_lab09_results.json"
out_file.write_text(json.dumps(res, indent=2), encoding="utf-8")
loaded = json.loads(out_file.read_text(encoding="utf-8"))
required_top = {
"config",
"detection_geometry",
"nms_comparison",
"coco_detection",
"mot_tracking",
"segmentation",
"backbones_and_peft",
"vlm_losses",
"edge_serving",
"workbench_panels",
}
assert required_top.issubset(set(loaded.keys()))
assert loaded["mot_tracking"]["hota_gain"] > 0.08
assert loaded["mot_tracking"]["idsw_reduction"] > 0
def test_16_workbench_panels_contract_six_kpis_four_bars_four_tables() -> None:
"""Artifact workbench_panels strictly adheres to platform contract (6 KPIs, 4 bars, 4 tables)."""
res = run_lab_demo.run_benchmark(seed=42, n_frames=100)
wp = res["workbench_panels"]
assert len(wp["kpis"]) == 6
assert len(wp["bars"]) == 4
assert len(wp["tables"]) == 4
for kpi in wp["kpis"]:
assert {"id", "label", "value", "unit", "status", "detail"}.issubset(kpi.keys())
assert kpi["value"] != ""
for bar in wp["bars"]:
assert len(bar["items"]) >= 2
for item in bar["items"]:
assert np.isfinite(float(item["value"]))
for tbl in wp["tables"]:
assert len(tbl["columns"]) == 4
assert len(tbl["rows"]) >= 2
ConvNeXt (7x7 depthwise + LayerNorm) với Vision Transformer (ViT) (\(N = HW/P^2\) mảnh) và DINOv2 tự giám sát, phát biểu nào ĐÚNG?Lab 09 (Test 10), MiniViT ảnh 64x64 với \(P=8\) có chính xác \(N = 64\) mảnh, còn MiniConvNeXt đạt 0.52 ms trên ORT CPU.
Lab 09 (Tests 02–03), nhận định nào CHÍNH XÁC?GIoU thoái hóa về IoU, lúc đó chỉ CIoU còn phạt tâm và tỷ lệ khung hình (Test 02). Soft-NMS giữ đủ 2 xe ở IoU = 0.56 (Test 03).
RT-DETR đạt tốc độ thời gian thực và loại bỏ hoàn toàn bước hậu xử lý NMS so với Faster R-CNN và YOLO11 là gì?AIFI tránh bùng nổ \(\mathcal{O}(N^2)\) ở tầng phân giải cao (\(S_3, S_4\)), còn mất mát ghép cặp Hungary 1-1 học sẵn tính duy nhất cho từng vật thể nên không cần NMS hậu kỳ.
16 xe, 2 vùng bóng cầu vượt làm điểm tin cậy rớt về ~0.26, vạch đếm y = 242) của Lab 09 (Tests 07–08), vì sao ByteTrack vượt xa SORT?ByteTrack là chỉ dùng \(\mathcal{D}_{\text{low}}\) để cứu các quỹ đạo đang hoạt động qua vị trí Kalman dự báo, tuyệt đối không spawn track mới từ \(\mathcal{D}_{\text{low}}\) nên FP = 0, IDSW: 29 -> 0, HOTA: 0.414 -> 0.934 (Tests 07–08).
MOT (MOTA, IDF1, HOTA) và thiết kế bộ đếm vạch Tripwire trong thực tế (Lab 09, Test 08), phát biểu nào ĐÚNG?HOTA tích phân qua 19 ngưỡng \(\alpha \in \{0.05, \dots, 0.95\}\) với trung bình hình học \(\sqrt{\text{DetA}\cdot\text{AssA}}\). Trong Test 08, xe ID#77 dao động 6 lần quanh y = 200 vẫn cho đúng count_down = 1, total_count = 1.
Lab 09, Test 09), điều gì xảy ra khi dự đoán đạt Semantic mIoU = 1.000 tuyệt đối nhưng hai chiếc ô tô chạy sát nhau bị gộp thành cùng một instance_id?IoU > 0.5. Gộp 2 xe tạo 1 FP + 2 FN làm RQ lớp ô tô rơi xuống 0.400, phơi bày rủi ro an toàn mà mIoU = 1.000 che giấu (Test 09).
ViT bằng LoRA và chọn hàm mất mát Thị giác–Ngôn ngữ giữa CLIP và SigLIP (Lab 09, Tests 11–12), nhận định nào ĐÚNG?Test 11: 1.89% < 15%). CLIP cần softmax trên toàn batch (Test 12: random nhảy +2.37 khi B: 4 -> 32), còn SigLIP độc lập từng cặp.
ITS thời gian thực (< 33.3 ms/frame) trên CPU biên (PyTorch 2.15+cpu, không cài onnxscript) và xử lý bằng chứng biển số (Lab 09, Tests 01, 13–14), lựa chọn nào ĐÚNG?Test 01 chặn cứng pickle/joblib qua AST, Test 13 xác minh safetensors sai số 0.0, và Test 14 chứng minh ONNX (dynamo=False) trên ORT CPU đạt 0.52 ms (~1,940 FPS, diff = 1.3e-07). Siêu phân giải sinh ảnh có thể bịa ký tự hợp lý về mặt thị giác nhưng sai thực tế.
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Chứng minh Hình học IoU / GIoU / CIoU & Kiểm chứng Greedy NMS vs Soft-NMS 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết \(\operatorname{GIoU} = \operatorname{IoU} - \frac{|C| - |B \cup B^{\text{gt}}|}{|C|}\); xét trường hợp không giao nhau (\(\operatorname{IoU} = 0\)) khi \(|C| \to \infty\) để suy ra cận dưới \(-1\), và xét trường hợp hộp \(B \subset B^{\text{gt}}\) để thấy \(|C \setminus (B \cup B^{\text{gt}})| = 0\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi compute_iou_matrix, compute_giou_matrix, compute_ciou_matrix, greedy_nms, soft_nms và compute_map_50_95 trong detection_metrics.py (Tests 02–04).
Tiêu chí Đáp án & Số đối chứng
Hai hộp rời nhau cho IoU = 0.000 phẳng, còn GIoU (-0.091 vs -0.500) và CIoU (-0.218 vs -0.506) phân tách rõ khoảng cách; ở cảnh làn đông (IoU = 0.56), Greedy NMS chỉ giữ 1 xe còn Soft-NMS giữ đủ 2 xe (0.81 -> 0.434), và COCO AP@50 = 0.999, mAP@50:95 = 0.902.
Bài tập 2 — Độ phức tạp ViT, So sánh ConvNeXt vs ViT & Thiết kế LoRA Không Độ trễ Phụ 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Thay \((H, W) \to (2H, 2W)\) vào \(N = HW/P^2\) để suy ra \(N^2 \to 16N^2\); đếm số phần tử của \(\mathbf{A} \in \mathbb{R}^{r \times d_{\text{in}}}\) và \(\mathbf{B} \in \mathbb{R}^{d_{\text{out}} \times r}\) rồi giải thích tính chất \(\mathbf{B}_{t=0} = \mathbf{0}\) và gộp \(\mathbf{W}_{\text{merged}}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy MiniConvNeXt, MiniViT(use_lora=False/True) và count_parameters trong vision_backbones_and_vlm.py (Tests 10–11).
Tiêu chí Đáp án & Số đối chứng
MiniViT (64x64, \(P=8\)) có đúng N = 64 mảnh; bật LoRA (r = 4 trên QKV) đóng băng toàn bộ backbone gốc, chỉ còn 2,243 / 118,915 tham số huấn luyện (1.89% < 15%) với B = 0 khởi đầu và 0 ms độ trễ phụ sau khi gộp ma trận.
Bài tập 3 — Bộ lọc Kalman 7D, Thuật toán Hungary & Giải phẫu Ưu thế ByteTrack vs SORT 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Xây dựng ma trận \(\mathbf{F} \in \mathbb{R}^{7\times 7}\) cho trạng thái \([u, v, s, r, \dot{u}, \dot{v}, \dot{s}]^\top\) với \(\Delta t = 1\); phân tích điều gì xảy ra với các xe đi xuống khi đi qua bóng cầu vượt [180, 232] ngay trước vạch đếm y = 242 dưới max_age = 3 và min_hits = 3.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy simulate_highway_traffic, KalmanBoxTracker, SORTTracker, ByteTrackTracker, TripwireVehicleCounter và evaluate_mot_sequence (Tests 05–08).
Tiêu chí Đáp án & Số đối chứng
Kalman lướt quán tính 4 khung che khuất đạt IoU > 0.85; trên chuỗi 100 khung, ByteTrack vượt trội SORT: HOTA 0.934 vs 0.414 (+0.520), IDF1 0.983 vs 0.422, IDSW 0 vs 29, và đếm xe 100.0% (8D/8U) vs 50.0% (0D/8U) với 0 đếm trùng.
Bài tập 4 — Chứng minh Định lý Ghép Duy nhất IoU > 0.5 & Phân rã PQ = SQ * RQ 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Giả sử tồn tại hai mặt nạ dự đoán không giao nhau \(p_1, p_2\) đều đạt \(\operatorname{IoU}(p_i, g) > 0.5\); suy ra \(|p_i \cap g| > 0.5|g|\) với cả \(i=1,2\), dẫn đến mâu thuẫn \(|(p_1 \cup p_2) \cap g| > |g|\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy generate_synthetic_panoptic_scene, compute_semantic_miou và compute_panoptic_quality trong segmentation_metrics.py (Test 09).
Tiêu chí Đáp án & Số đối chứng
Đẳng thức PQ == SQ * RQ thỏa chính xác (< 1e-12); bản sạch đạt PQ = 0.940 (PQ_things = 0.924), còn bản gộp 2 ô tô giữ Semantic mIoU = 1.000 giả tạo nhưng Car PQ sụp từ 0.917 -> 0.400 (PQ_things = 0.700).
Bài tập 5 — Đối chiếu Toán học CLIP InfoNCE vs SigLIP Sigmoid & Kiến trúc SAM 2 + SigLIP 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Khi \(\mathbf{u}_i^\top \mathbf{v}_j \approx 0\) cho mọi \((i, j)\), thay \(z_{ij} = 0\) vào \(\mathcal{L}_{\text{CLIP}}\) để thu về \(-\ln(1/B) = \ln B\); phân tích tỷ số cặp âm/dương \((B-1):1\) giải thích vì sao SigLIP cần \(b_{\text{sig}} < 0\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy clip_infonce_loss và siglip_sigmoid_loss trên B = 4 và B = 32 (Test 12), kết hợp phân tích đường ống SAM 2 + SigLIP cho kho 50,000 SKU và rủi ro Generative SR.
Tiêu chí Đáp án & Số đối chứng
Mất mát ngẫu nhiên của CLIP nhảy từ 2.468 (B=4) lên 4.841 (B=32) theo \(\ln B\), còn SigLIP tách rời phụ thuộc batch (5.514 vs 5.864) và tối ưu tốt qua chunk phân tán; SAM 2 + SigLIP cho phép thêm SKU mới trong < 10 phút mà không huấn luyện lại.
Bài tập 6 — Đóng gói Safetensors, Xuất ONNX (dynamo=False) < 33.3 ms & Kiểm định 16/16 Pytest 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân bổ ngân sách 33.3 ms cho 30 FPS gồm giải mã (<= 5 ms), suy luận ONNX (<= 18 ms), ByteTrack (<= 3 ms), Tripwire (<= 1 ms) và dự phòng (>= 6.3 ms); giải thích lỗi CWE-502 của pickle và bẫy dynamo=True thiếu onnxscript.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy save_and_verify_safetensors, export_and_benchmark_onnx(..., dynamo=False), scripts/run_lab_demo.py, ruff, mypy và trọn bộ 16/16 pytest (Tests 01, 13–16).
Tiêu chí Đáp án & Số đối chứng
safetensors (182,052 B, 0 pickle) đạt sai số 0.0e+00; ONNX (dynamo=False) trên ORT CPU đạt p50 = 0.52 ms / p95 = 0.63 ms (~1,940 FPS, diff 1.3e-07 < 1e-4), xuất đủ 6 KPI + 4 bar + 4 table và 16/16 bài test xanh.