Chương 16 — Đường ống Kubeflow, Huấn luyện Phân tán (PS vs DDP Ring All-Reduce, FSDP2/ZeRO-3, 5D Parallelism) & Lập lịch Bầy đàn Kueue
Từ KFP v2 4 giai đoạn (ROC-AUC 0.9916, cache hit 4/4), PyTorchJob & chứng minh tương đương số học PS/Ring All-Reduce + gloo đa tiến trình (max_diff 2.98e-08 / gloo 1.49e-08 < 1e-5; 400G IB Ring hiệu suất 96.04%, nhanh 32.2x ở 10G) đến phân mảnh FSDP2 DTensor dim-0 (7B từ 112.0 -> 14.0 GB/GPU, 8.0x static), Interleaved 1F1B (4.48% bubble), RoCEv2 ECN+DCQCN, GPUDirect Storage & Kueue TAS Gang (0 deadlock vs FIFO 2 deadlock).
Unit ID:
T2-P3-U04
Track & Part: Track 2 (EDAI) — Part 3: Distributed Systems, Kubernetes, Distributed Training & Cloud Infrastructure (part-03-distributed-k8s-cloud-and-gateway)
Cầu nối Từ Chương 14 & Chương 15: Chương 14 đặt nền móng đồng thuận và phân mảnh hệ phân tán; Chương 15 dựng hạ tầng Kubernetes chuẩn sản xuất (Helmfile,Vault,KServe,MIG/DRA). Chương 16 tiếp tục đặt toàn bộ quy trình huấn luyện phân tán quy mô lớn lên cụm Kubernetes đó thông quaKubeflow Pipelines v2,PyTorchJob/TrainJob, giao thứcRing All-Reduce, phân mảnhPyTorch FSDP2/ZeRO-3,5D Parallelism, lưu trữ phân tán tốc độ cao và lập lịch bầy đànKueue.
Truy xuất Giáo trình Gốc (R45+R23/R24+AIDE 3): Kubeflow architecture; Kubeflow operators; Distributed training mechanisms; Distributed storage for ML; Deploy Kubeflow; Implement a distributed training pipeline on Kubeflow; 4-stage intrusion detection pipeline (data preparation, training, evaluation, visualization including numerical metrics and images); Data vs model parallelism; Parameter server training vs multi-worker training trong 02-track-edai-raw-curriculum.md và 02-track-2-edai-sota-syllabus.md
Bài thực hành Song hành (Lab 14): labs/lab-14-kubeflow-4stage-distributed-training/README.md (kubeflow_distributed_lab)
Tình huống Mở đầu: Bốn Thảm họa Khi Mở rộng Huấn luyện Phân tán Ngây thơ#
Một mô hình chạy trơn tru trên 1 GPU có thể làm tê liệt toàn bộ cụm hàng chục GPU nếu kỹ sư ML/Nền tảng mắc phải bốn sai lầm kiến trúc kinh điển sau:
- Nghẽn Cổ chai Master NIC Trên
Parameter ServerKhi Mở rộng Quy mô: Khi mở rộng huấn luyện mô hình350Mtham số (700.0 MBgradientfp16) lênW = 32worker qua mạng10 GbpsEthernet bằng kiến trúcParameter Server (PS)tập trung, toàn bộ32worker cùng đẩy và kéo trọng số qua một nút Master duy nhất (44,800.0 MB/bước). Trong thực nghiệmLab 14, thời gian mỗi bước phình to lên35,925.03 ms(0.24%hiệu suất mở rộng, gần như đứng yên!). Thay bằngPyTorch DDPRing All-Reducegiới hạn lưu lượng mỗi rank ở1,356.25 MB(< 2Ψ), kéo bước chạy xuống1,115.68 ms(nhanh hơn32.2x) trên10G Ethernetvà đạt96.04%hiệu suất mở rộng (30.73xtăng tốc) trên400 Gbps InfiniBand— trong khi vẫn giữ sai lệch trọng số cực đại so với huấn luyện đơn máy chỉ2.98e-08(< 1e-5). - Tràn VRAM
CUDA OOMVớiDDPThuần Túy & Đường ốngGPipePhình Kích hoạt: Nhân bản nguyên vẹn mô hình7Bhỗn hợpAdamW fp32lên từng GPU tiêu tốn112.0 GB/GPU(16Ψ), vượt quá giới hạn VRAM của thẻ80 GB. Chuyển sangPyTorch FSDP2(DTensor/ZeRO-3) qua8GPU nén bộ nhớ tĩnh còn14.0 GB/GPU(8.0xtĩnh,4.05xđỉnh đo được cóprefetch); kết hợp1F1BPipeline Parallelism (p = 4,m = 32) cắt bộ nhớ kích hoạt đi8.0xvàInterleaved 1F1B (v = 2)hạ tỷ lệ bong bóng nhàn rỗi từ42.86%(GPipe m = 4) xuống4.48%. - Chết Đứng Cụm Đa GPU Vì Bộ lập lịch
FIFOTừng Pod (Deadlock): Cụm8GPU nhận6tác vụPyTorchJob(mở đầu bởi hai job5-GPU đến đồng thời). Bộ lập lịchkube-schedulermặc định cấp xen kẽ từng Pod khiến Job 1 giữ4/5GPU và Job 2 giữ4/5GPU. Toàn bộ8/8GPU bị khóa cứng vĩnh viễn ở bước chờNCCL Rendezvous, hoàn thành0/6job (0.0%GPU goodput). Kích hoạtKueueAll-or-Nothing Gang Scheduling (WaitForPodsReady) hoàn thành trọn vẹn6/6job trong15tick với0deadlock và77.5%GPU goodput. - Đường ống Huấn luyện Thiếu Cache, Lộ Khóa & Tag
:latest: Một quy trình ML viết bằng script rời rạc không băm SHA-256 đầu vào, dùng image:latest, hoặc nhúng khóa S3 tĩnh sẽ chạy lại toàn bộ các bước đắt đỏ mỗi lần chỉnh biểu đồ đánh giá và gây lỗ hổng bảo mật. Đường ốngKFP v24 giai đoạn (data-prep\(\to\)distributed-train\(\to\)evaluate-model\(\to\)visualize-metrics) củaLab 14đạtROC-AUC = 0.9916, tái sử dụng4/4bước cache ở lần chạy thứ hai, sạch0bí mật tĩnh và0tag:latest.
Mục tiêu Học tập (Learning Objectives)#
Sau Chương 16 và bài thực hành kubeflow_distributed_lab (Lab 14), kỹ sư Nền tảng Dữ liệu & AI nắm vững:
- Thiết kế Đường ống & Điều phối Huấn luyện Với
Kubeflow(R45,R23/R24,AIDE 3): Phân biệtKubeflowvsRayvsFlyte; thành thạoKFP v2DSL \(\to\)IR YAML(MLMD, artifact lineage SHA-256, DAG caching), toán tửPyTorchJob(Training Operator v1) vsTrainJob(Kubeflow Trainer v2) và tối ưu siêu tham sốKatib(TPE/ASHA). - Làm chủ Song song Dữ liệu (
PSvsDDP Ring/Tree All-Reduce): Chứng minh toán học tương đương giữa đơn máy,Sync Parameter ServervàRing All-Reduce; phân tích định luật băng thông \(O(W\Psi)\) vs \(2\frac{W-1}{W}\Psi\), kỹ thuật Gradient Bucketing + Compute–Communication Overlap, và chuyển đổiRingsangDouble-Binary Treekhi tối ưu độ trễ ở quy mô lớn. - Thành thạo
ZeRO-1/2/3,PyTorch FSDP2(DTensor) & Song song5D(TP,PP,CP,EP): Tính toán chính xác mức tiết kiệm bộ nhớ \(16\Psi \to 16\Psi/W\), vận hànhGPipevs1F1B/Interleaved 1F1B, và ánh xạ các trụcTP/CP(trênNVLink) vớiPP/HSDP/EP(trênRoCEv2/InfiniBand). - Tối ưu Lưu trữ Phân tán ML & Chống Deadlock Bằng
Kueue: Thiết kế lớp đệm đọc tuần tự (Lustre,GCS Fuse/S3NVMe cache,WebDataset) chống đóiDataLoader, đồng thời triển khaiKueue(ResourceFlavor,ClusterQueue,LocalQueue,WaitForPodsReady) bảo đảm0deadlock đa GPU.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T2-P3-U04, R45 + AIDE 3)#
Nội dung Gốc (02-track-edai-raw-curriculum.md, R45) |
Nâng cấp Chuẩn SOTA 2026 (ch-16) |
Mục trong Chương 16 | Tạo tác & Kiểm thử (kubeflow_distributed_lab) |
|---|---|---|---|
1. Kubeflow architecture & Deploy Kubeflow (R45) |
Kubeflow vs Ray vs Flyte; KFP v2 DSL \(\to\) IR YAML, MLMD lineage SHA-256, DAG execution cache (0/4 -> 4/4) |
Trụ cột 1 (§1.1) + Mermaid 1 | kfp_4stage_pipeline_ir.yaml, kfp_4stage_training_pipeline.py, Tests 02, 13–14 |
2. Kubeflow operators (R45, R23) |
PyTorchJob (kubeflow.org/v1) + Kubeflow Trainer v2 (TrainJob / ClusterTrainingRuntime) + Katib (ASHA/TPE) + TorchElastic |
Trụ cột 1 (§1.1) | pytorchjob_ddp.yaml, kfp_pipeline_and_kueue.py, Tests 04–05 |
3. 4-stage intrusion detection pipeline (AIDE 3) |
Chuẩn hóa 4 bước data-prep -> distributed-train -> evaluate-model -> visualize-metrics (ROC-AUC 0.9916, HTML report, 11 OTel spans) |
Trụ cột 1 (§1.1) + Trụ cột 4 | run_kfp_pipeline_experiment, run_lab_demo.py, Tests 13–14, 19–21 |
4. Data parallelism: Parameter Server vs Multi-worker (R45, AIDE 3) |
Chứng minh parity 2.98e-08; PS \(O(W\Psi)\) (35,925 ms) vs DDP Ring All-Reduce (1,115.68 ms, 32.2x) + Bucketing Overlap + Tree All-Reduce |
Trụ cột 1 (§1.2) + Mermaid 2 + Widget 1 | distributed_training_bench.py, Tests 06–09 |
5. Model parallelism (R45, AIDE 3) |
ZeRO-1/2/3 & PyTorch FSDP2 (DTensor, 8.0x tĩnh / 4.05x đỉnh) + 5D: TP (Megatron), PP (1F1B 8.0x act / 4.48% bubble), CP, EP |
Trụ cột 1 (§1.3) + Mermaid 2 + Widget 2 | evaluate_zero_fsdp2_and_pipeline_parallelism, Tests 10–12 |
6. Distributed storage for ML & Gang Scheduling (R45 + SOTA) |
POSIX/Lustre/GCS Fuse NVMe cache + WebDataset/DataLoader prefetch; Kueue Gang (0 deadlocks, 77.5% goodput vs FIFO 0.0%) |
Trụ cột 1 (§1.4) + Mermaid 3 + Widget 3 | kueue_clusterqueue.yaml, simulate_gang_scheduling_vs_fifo, Tests 15–17 |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 16 (Unified Notation)#
| Ký hiệu | Miền / Đơn vị | Định nghĩa Chính xác Trong Chương 16 & kubeflow_distributed_lab |
Giá trị Thực nghiệm Lab 14 (seed=42) |
|---|---|---|---|
| \(W\) | \(\mathbb{Z}^+\) (Worker) | Số GPU / worker huấn luyện phân tán đồng bộ | \(W=4\) (Parity/KFP), \(W=8\) (FSDP2), \(W \in \{2..32\}\) (Scaling) |
| \(\Psi\) | Tham số / Bytes | Kích thước mô hình (350M \(\implies 700\text{ MB}\) fp16; 7B \(\implies 112\text{ GB}\) trạng thái AdamW) |
4,866 params (Parity), 134,288 elems (FSDP2 thực) |
| \(V_{\text{PS}}, V_{\text{Ring}}\) | \(\text{MB}\) / bước | Lưu lượng mạng cổ chai: PS Master \(= 2W\Psi\) vs Ring mỗi rank \(= 2\frac{W-1}{W}\Psi\) | \(W=32\): PS 44,800 MB vs Ring 1,356.25 MB (1.9375Ψ) |
| \(p, m, v\) | Stage, Microbatch | Số tầng đường ống PP (\(p=4\)), số microbatch (\(m \in \{4..32\}\)), khối xen kẽ (v=2) |
m=32: 1F1B tiết kiệm 8.0x VRAM; v=2 bubble 4.48% |
| \(R_{\text{bubble}}\) | \([0, 1)\) | Tỷ lệ nhàn rỗi đường ống: GPipe/1F1B \(= \frac{p-1}{m+p-1}\); Interleaved \(= \frac{p-1}{vm+p-1}\) |
GPipe m=4: 42.86% \(\to\) Interleaved m=32: 4.48% |
| \(\Delta_{\text{parity}}\) | \(\mathbb{R}_{\ge 0}\) | Sai lệch tuyệt đối lớn nhất trọng số giữa SingleWorker, SyncPS và RingDDP |
2.98e-08 (< 1e-5, inter-rank 0.0) |
Trụ cột 1 — Nguyên lý Gốc: Kubeflow v2, PS vs Ring All-Reduce, FSDP2/5D Parallelism, Lưu trữ ML & Kueue#
1.1 Hệ sinh thái Kubeflow, Đường ống KFP v2 IR 4 Giai đoạn, PyTorchJob/TrainJob & Katib (R45 + SOTA)#
Trên nền Kubernetes đã triển khai ở Chương 15, việc huấn luyện mô hình ML/LLM đòi hỏi một lớp điều phối chuyên biệt giải quyết vòng đời thí nghiệm, đồng bộ mạng đa nút và tự động hóa siêu tham số.
-
Định vị
KubeflowTrong Bộ ba Nền tảng ML (KubeflowvsRayvsFlyte):Kubeflow: Kiến trúc thuần Kubernetes CRD gồmKubeflow Pipelines (KFP v2),Training Operator/Kubeflow Trainer v2,Katib,KServevàNotebooks, mạnh nhất về tách biệt container, bảo mật đa thuê bao (Istio/Dex/RBAC) và quản trị dòng dõi tạo tác doanh nghiệp.Ray(KubeRay): Mạng lưới Actor/Task trên bộ nhớ chia sẻ (Plasma), tối ưu cho tác vụ Python hạt mịn, hậu huấn luyện RLHF/GRPO (veRL,OpenRLHF) và sinh dữ liệu phân tán.Flyte: Mạnh về kiểm định kiểu dữ liệu nghiêm ngặt giữa các tác vụ và cơ chế memoization đồ thị lớn.
-
Kiến trúc
Kubeflow Pipelines v2(DSL\(\to\)IR YAML&MLMDLineage):- Khác với
KFP v1biên dịch trực tiếp thànhArgo YAMLgắn chặt vào một engine duy nhất,KFP v2biên dịch hàm Python (@dsl.component,@dsl.pipeline) thành đặc tả trung gianIntermediate Representation(IR YAML,schemaVersion: 2.1.0) tách rờicomponents(hợp đồng kiểusystem.Dataset,system.Model,system.Metrics,system.ClassificationMetrics,system.HTML),deploymentSpec.executors(container image, CPU/RAM/GPU, biến môi trường) và đồ thịroot.dag.tasks. - Mọi tạo tác đầu ra được lưu trên kho đối tượng (
S3/MinIO/GCS) theo đường dẫn tham số hóa (s3://ml-artifacts-prod/.../{{$.pipeline_job_uuid}}/...), đồng thời siêu dữ liệu và chữ ký băm SHA-256 ghi vào ML Metadata (MLMD). - Execution Caching: Khi chạy lại đường ống với cùng đầu vào và chữ ký thành phần, bộ thực thi tra khóa băm cache và bỏ qua ngay toàn bộ bước không đổi (
0/4cache hit lần đầu \(\to\)4/4cache hit lần sau trongLab 14).
- Khác với
-
Toán tử Huấn luyện (
PyTorchJob v1vsKubeflow Trainer v2) & Tối ưu Siêu tham sốKatib:PyTorchJob(kubeflow.org/v1): Khai báopytorchReplicaSpecs.Master(replicas: 1) vàWorker(replicas: W-1), gắn cờ--rdzv_idtường minh,serviceAccountNameriêng vớiautomountServiceAccountToken: false. Operator tự động tiêmMASTER_ADDR,MASTER_PORT,WORLD_SIZE,RANKvà khởi tạo mạng rendezvousc10dchotorchrun.Kubeflow Trainer v2(TrainJob+ClusterTrainingRuntime+PodGroup): Chuẩn thế hệ mới tách cấu hình hạ tầng cụm (ClusterTrainingRuntimegồm/dev/shm, driverRDMA/NCCL, sidecar log do Platform Ops quản lý) khỏi mã huấn luyện gọn nhẹ (TrainJobdo ML Engineer gửi), dùng cơ chếPodGrouplập lịch đồng bộ liên pod chống deadlock giữa các Pod nạp dữ liệu (dataset initializer) và các GPU worker, hỗ trợ tự nhiênTorchElastic(co giãn/chịu lỗi khi rơi nút GPU) và tích hợp sẵn cờsuspend: truechoKueue.Katib: Điều phối cácTrialsong song để tìm siêu tham số tối ưu thông qua Random Search, Bayesian Optimization (TPE), Hyperband hoặc ASHA (Asynchronous Successive Halving, tự động kết thúc sớm các trial hội tụ kém nhằm tiết kiệm GPU).
1.2 Song song Dữ liệu (Data Parallelism): Parameter Server Cổ chai vs DDP Ring All-Reduce & Tree All-Reduce (R45 + AIDE 3)#
Khi toàn bộ trọng số mô hình vừa gọn trong VRAM của một GPU, chiến lược tăng tốc chuẩn là Song song Dữ liệu (Data Parallelism): chia lô toàn cục kích thước \(B\) thành \(W\) lô con \(B/W\) cho \(W\) worker, tính gradient cục bộ \(\mathbf{g}_{w,t}\) rồi cộng trung bình đồng bộ trước khi cập nhật trọng số:
1. Chứng minh Tương đương Toán học Trước Khi Bàn Về Tốc độ#
Một sai lầm phổ biến là nghĩ Parameter Server và Ring All-Reduce DDP cho ra mô hình khác nhau. Trong Lab 14 (Experiment 1), khi huấn luyện đồng bộ cùng tập dữ liệu trên mạng IntrusionBlockNet (4,866 tham số, \(W=4\), \(B=64\), \(12\) bước) với cùng điểm khởi tạo:
SingleWorkerBaseline: loss giảm0.772477 -> 0.460285.SyncParameterServerTrainer: sai lệch trọng số cực đại so với đơn máy chỉ2.98e-08(< 1e-5).RingAllReduceDDPTrainer(5bucket): sai lệch so với đơn máy2.98e-08, sai lệch giữa các rank DDP bằng0.0, sai lệch loss cực đại4.47e-08.- Thực thi Đa tiến trình
torch.distributed(backend="gloo",dist.FileStore,DDP):Lab 14còn sinh tiến trình hệ điều hành độc lập quamp.spawn(world_size = 2), chứng minh sai lệch giữa các rank0.0và sai lệch so với huấn luyện đơn tiến trình1.49e-08(< 1e-5).
Sự khác biệt chí tử giữa hai kiến trúc không nằm ở toán học, mà nằm ở nút thắt cổ chai mạng (\(O(W)\) vs \(O(1)\))!
2. Bẫy Cổ chai Parameter Server (PS) vs Tính Tối ưu Băng thông của Ring All-Reduce#
-
Kiến trúc
Parameter ServerĐồng bộ: \(W\) worker gửi gradient dung lượng \(\Psi_{\text{bytes}}\) về một PS trung tâm và kéo lại tham số mới. Tổng lượng dữ liệu đi qua thẻ mạng (NIC) của nút PS trong mỗi bước là:\[V_{\text{PS, Master}} = 2 \cdot W \cdot \Psi_{\text{bytes}} \quad \implies \quad O(W \cdot \Psi)\]Khi tăng \(W\) từ
2lên32, lưu lượng dồn vào một NIC trung tâm tăng gấp16x! Trên mô hình350M fp16(700.0 MB) qua mạng10 Gbps Ethernet(Lab 14), PS Master phải gánh44,800.0 MB/bước (35,925.03 ms/bước), kéo hiệu suất mở rộng mỗi GPU sụp xuống còn0.24%(tăng32GPU mà tốc độ tổng chỉ đạt0.08x!). Chế độ bất đồng bộ (Async PS) tránh rào đồng bộ nhưng gây gradient cũ (stale gradients) làm nhiễu quỹ đạo hội tụ. -
Giao thức
Ring All-Reduce: Sắp xếp \(W\) GPU thành một vòng khép kín (rank \(r\) chỉ gửi cho \(r+1 \bmod W\) và nhận từ \(r-1 \bmod W\)), chia vector gradient \(\Psi\) thành \(W\) lát đều kích thước \(\Psi/W\):- Pha
Reduce-Scatter(\(W - 1\) bước vòng): Sau \(W - 1\) lượt truyền lát, mỗi GPU giữ tổng chính xác của đúng1/Wphần gradient. - Pha
All-Gather(\(W - 1\) bước vòng): Truyền tiếp \(W - 1\) lượt để phát tán toàn bộ các lát đã cộng hoàn chỉnh tới mọi GPU.
Tổng dữ liệu mỗi GPU gửi/nhận chỉ là:
\[V_{\text{Ring, Rank}} = 2 \cdot \frac{W - 1}{W} \cdot \Psi_{\text{bytes}} < 2 \Psi_{\text{bytes}} \quad (\forall W \ge 2)\]Lưu lượng mỗi liên kết tiến tới hằng số \(2\Psi_{\text{bytes}}\) (\(O(1)\) theo \(W\))! Nhờ đó tại \(W = 32\), mỗi GPU chỉ truyền
1,356.25 MB(hệ số1.9375 < 2.0), giúpRing All-Reduce DDPnhanh hơn32.2xso với PS trên10G Ethernet(1,115.68 msvs35,925.03 ms) và đạt96.04%hiệu suất mở rộng (30.73xtăng tốc) trên400 Gbps InfiniBand! - Pha
3. Gradient Bucketing Overlap, Tree All-Reduce & Kiểm soát Nghẽn RoCEv2 (ECN + DCQCN)#
- Gradient Bucketing & Compute–Communication Overlap (
PyTorch DDP): Thay vì đợi tính xong đạo hàm toàn bộ mạng mới truyền thông,DDPgom các tensor theo thứ tự ngược từ lớp cuối về lớp đầu vào các xô (bucket, mặc định25 MB). Ngay khi một xô đầy trong lúc lan truyền ngược (backward pass),NCCLlập tức phóngAll-Reducetrên CUDA Stream truyền thông song song trong khi GPU vẫn tính backward cho các lớp phía trước! - Giới hạn Độ trễ Của Ring &
Double-Binary Tree All-Reduce:Ring All-Reducecần \(2(W - 1)\) chặng nhảy (hops — tới62hops ở \(W = 32\)). Khi truyền các thông điệp kích thước nhỏ hoặc ở cụm hàng trăm–nghìn GPU, độ trễ khởi phát mạng \(\alpha\) thống trị thời gian bước. Vì vậyNCCLtự động chuyển sang Cây Nhị phân Kép (Double-Binary Tree) với độ trễ chỉ \(2\lceil\log_2 W\rceil\) hops (10hops ở \(W = 32\), giảm6.2xđộ trễ nhảy!) mà vẫn giữ thông lượng gần \(2\Psi\). - Kỹ thuật Chống Chết Tắc
RoCEv2(ECN+DCQCNvsPFC Deadlock): Trên cụm RDMA qua Ethernet (RoCEv2), nếu chỉ bậtPFC(Priority Flow Control) thuần túy khi switch nghẽn incast trongAll-Reduce, khung tạm dừng (PAUSE frame) lan truyền ngược có thể gây tắc nghẽn đầu hàng (head-of-line blocking) hoặcPFC deadlocklàm sập toàn bộ cụm huấn luyện. Chuẩn SOTA 2026 yêu cầu kích hoạtECN(Explicit Congestion Notification) trên switch để đánh dấu sớm trước khi tràn đệm, kết hợp thuật toánDCQCNtrên NIC tự động giảm tốc độ phát ở nguồn phát sinh nghẽn mà không cần đóng băng toàn liên kết.
1.3 Song song Mô hình Đa chiều (TP, PP GPipe vs 1F1B, CP, EP) & Phân mảnh Bộ nhớ ZeRO/FSDP2 (R45 + SOTA)#
Khi mô hình vượt ngưỡng VRAM của một GPU (ví dụ LLM 7B với huấn luyện hỗn hợp bf16 + AdamW fp32 tiêu tốn 16Ψ = 112.0 GB chỉ riêng cho tham số, gradient và optimizer!), ta bắt buộc phải phân mảnh trạng thái (ZeRO / FSDP2) hoặc chia cắt chính kiến trúc mô hình (3D/5D Parallelism).
1. DeepSpeed ZeRO-1/2/3 & PyTorch FSDP2 (DTensor dim-0 + DCP)#
Xét 16Ψ byte/tham số của AdamW hỗn hợp (2Ψ trọng số fp16 + 2Ψ gradient fp16 + 4Ψ master fp32 + 4Ψ momentum + 4Ψ variance):
| Chiến lược Phân mảnh | Đối tượng Chia qua \(W\) GPU | Bộ nhớ Tĩnh Mỗi GPU | 7B LLM (W = 8) |
Lưu lượng Mạng / Bước |
|---|---|---|---|---|
| DDP Baseline | Không chia (nhân bản \(100\%\)) | \(16 \Psi\) | 112.0 GB (1.0x) |
\(2\frac{W-1}{W}\Psi\) (1.75Ψ) |
ZeRO-1 |
Trạng thái Optimizer (\(P_{\text{os}}\)) | \(4\Psi + \frac{12\Psi}{W}\) | 38.5 GB (2.91x) |
1.75Ψ |
ZeRO-2 |
Optimizer + Gradient (\(P_{\text{os}+g}\)) | \(2\Psi + \frac{14\Psi}{W}\) | 26.25 GB (4.27x) |
1.75Ψ (Reduce-Scatter + All-Gather) |
ZeRO-3 / PyTorch FSDP2 |
Optimizer + Gradient + Tham số (\(P_{\text{os}+g+p}\)) | \(\frac{16\Psi}{W}\) (+ đệm 1 lớp) | 14.0 GB (8.0x tĩnh) |
2.62Ψ (1.5x DDP do All-Gather khi Forward) |
- Bước nhảy Kiến trúc Của
PyTorch FSDP2(fully_shard+DTensor dim-0+DCP):FSDP1cũ ghép nhiều tensor thành mộtFlatParameter1D khổng lồ và phụ thuộc chặt vàorecord_stream(), khiến bộ cấp phát CUDA dễ bị phân mảnh, giữ bộ nhớ giải phóng muộn và khó ghép với Tensor Parallelism.FSDP2(chuẩn Composable APIfully_shard) phân mảnh từng tensor tham số dọc theo chiều 0 (DTensor dim-0), loại bỏ hoàn toànFlatParametervà lỗi quản lý bộ nhớrecord_stream, hỗ trợAll-Gather prefetchlớp \(l+1\) trong khi GPU đang tính lớp \(l\), đồng thời mở đường lưu/nạp checkpoint song songPyTorch Distributed Checkpoint (DCP)không cần tập hợp lại toàn bộ mô hình lên rank 0 (zero-communication checkpointing). TrongLab 14(Experiment 3), khi phân mảnh thực tế mô hình PyTorch134,288phần tử qua8rank (16,786phần tử/rank, bảo toàn100%tổng phần tử), bộ nhớ đỉnh thực đo kèm bộ đệm prefetch vẫn giảm4.05x(2,148,608 B -> 530,720 B).
2. Bốn Trục Song song Mô hình Bổ sung (TP, PP, CP, EP)#
Tensor Parallelism(TP— Megatron-LM): Chia ma trận trọng số của từng lớp MLP/Attention theo chiều cột rồi theo chiều hàng (ColumnParallelLinear\(\to\)RowParallelLinear), chỉ cần2phépAll-Reducetrên mỗi tầng Transformer trong Forward + Backward. Vì truyền thông nằm ngay giữa các lớp,TPbắt buộc chạy quaNVLink/NVSwitchnội bộ Node (\(TP \le 8\)).Pipeline Parallelism(PP—GPipevs1F1BvsInterleaved 1F1B): Cắt mô hình theo chiều sâu thành \(p\) stage qua nhiều Node và chia lô lớn thành \(m\) microbatch:- Tỷ lệ Bong bóng Đường ống (
Pipeline Bubble): CảGPipevà1F1Bđồng bộ đều chịu thời gian làm đầy/xả đường ống tạo tỷ lệ nhàn rỗi \(R_{\text{bubble}}^{\text{GPipe / 1F1B}} = \frac{p - 1}{m + p - 1}\) (ở \(p=4\): nếu \(m=4\) bong bóng lên tới42.86%; nâng \(m=16\) giảm còn15.79%; \(m=32\) còn8.57%). - Sống còn Bộ nhớ Kích hoạt Với
1F1B:GPipechạy hết \(m\) bước Forward mới chạy Backward nên phải giữ kích hoạt của cả \(m\) microbatch trong VRAM (\(O(m)\)).1F1B(One-Forward-One-Backward) xen kẽ chạy Backward ngay khi microbatch đầu ra tới cuối đường ống, giữ số kích hoạt tối đa trên mỗi GPU ở mức \(O(p)\) — tiết kiệm4.0xVRAM kích hoạt ởm=16và8.0xởm=32! Interleaved 1F1B(\(v\) khối ảo trên mỗi GPU): Giao mỗi GPU giữ \(v \ge 2\) đoạn tầng, thu nhỏ bong bóng xuống \(\frac{p - 1}{v \cdot m + p - 1}\) — giảm xuống chỉ còn8.57%(m=16) và4.48%(m=32) ở \(v=2\)!
- Tỷ lệ Bong bóng Đường ống (
Context Parallelism(CP—Ring Attention): Chia chuỗi ngữ cảnh dài (128k–1Mtoken) theo chiều token qua \(CP\) GPU; mỗi GPU tính FlashAttention trên khối cục bộ và truyền vòng các khốiK, Vẩn sau thời gian tính ma trận.Expert Parallelism(EP—Mixture-of-Experts): Đặt các chuyên gia MLP (Experts) trên các GPU khác nhau; bộ định tuyến (Router) sử dụng giao tiếpAll-to-All(Dispatch\(\to\)Expert Compute\(\to\)Combine) để chỉ tính toán trên các token được gán.
1.4 Lưu trữ Phân tán ML (Lustre / GCS Fuse / GPUDirect Storage) & Lập lịch Bầy đàn GPU Kueue (TAS + WaitForPodsReady) (R45 + SOTA)#
1. Khử Đói Dữ liệu (DataLoader Starvation) & Checkpoint Không Chặn Với GPUDirect Storage#
Khi cụm 8× H100 tiêu thụ hàng GB dữ liệu/giây, việc đọc ngẫu nhiên hàng triệu tệp ảnh/bản ghi rời rạc qua HTTP (S3/GCS) hoặc NFS đơn luồng khiến GPU rỗi chờ I/O (GPU Util < 20%). Hệ thống sản xuất giải quyết bằng 4 lớp:
- Hệ thống Tệp Song song (
Lustre/GPFS): Phân dải tệp (file striping) qua nhiều máy chủ đối tượng (OST), đạt băng thông đọcPOSIXsong song> 100 GB/s. NVIDIA GPUDirect Storage (GDS): Thiết lập đường truyềnDMAtrực tiếp giữa ổNVMe/NVMe-oF(hoặcLustreRDMA) với GPU VRAM, bỏ qua hoàn toàn CPU bounce buffer trong RAM hệ thống — đặc biệt sống còn khi ghi/nạp checkpointFSDP2 + DCPdung lượng hàng trăm GB để rút ngắn thời gian phục hồi nút lỗi.- Đóng gói Shard Tuần tự + Đệm
NVMe(GCS Fuse File Cache/S3Prefetch): Gộp hàng triệu mẫu nhỏ thành các shard lớn100–500 MB(WebDataset TAR/Parquet/Mosaic MDS) để biến đọc ngẫu nhiên thành luồng tuần tự, và bật bộ đệm trên ổNVMecục bộ của Node (GCS Fusecache) tránh tải lại từ xa qua nhiều epoch. - Tối ưu
PyTorch DataLoader: Khai báoDistributedSampler(chia đều không trùng giữa \(W\) rank),num_workers >= 4,pin_memory=True(khóa trang RAM truyền DMA lên GPU),persistent_workers=Truevàprefetch_factor >= 2.
2. Loại bỏ Deadlock Cụm GPU Bằng Kueue Gang Scheduling (ClusterQueue + Kueue TAS + Global WaitForPodsReady)#
Bộ lập lịch mặc định kube-scheduler cấp phát từng Pod một. Khi 2 hoặc 3 PyTorchJob cùng nộp lên cụm 8 GPU (ví dụ hai job đều đòi 5 GPU cho 1 Master + 4 Workers), việc cấp xen kẽ từng Pod dẫn tới Job A giữ 4/5 GPU và Job B giữ 4/5 GPU. Không job nào đủ 5 GPU để vượt qua NCCL Rendezvous, khiến cả 8/8 GPU kẹt cứng mãi mãi (2 deadlocked jobs, 0.0% goodput trong Lab 14)!
Kueue giải quyết triệt để ngay trên API Kubernetes chuẩn bằng ba tài nguyên cốt lõi và cấu hình điều phối hiện đại:
ResourceFlavor: Mô tả loại phần cứng (accelerator: nvidia-h100) vàtolerations.ClusterQueue: Quản lý hạn mức GPU toàn cụm (resourceGroupsvớinominalQuota: "8",borrowingLimit,cohortvà chính sáchpreemption). (Lưu ý chuẩn schemaKueue v1beta1: trườngwaitForPodsReadylà cấu hình toàn cục ở cấp Kueue controllerConfiguration(config.kueue.x-k8s.io/v1beta1) nhằm thu hồi toàn nhóm khi Pod treo khởi tạo quá hạn, không đặt sai vị trí vào trongClusterQueue.spec— kiểm toánLab 14bắt buộc bất biến này!)LocalQueue&Kueue TAS(Topology-Aware Scheduling):LocalQueuemở cổng tiếp nhận theo namespace (ml-team-gpu-queue) vớiPyTorchJobkhởi tạo ởsuspend: true(Kueuechỉ mở khóa All-or-Nothing khi đủ5/5GPU trống, đạt0deadlock,6/6job xong,77.5%goodput). Trên cụm đa node/rack,Kueue TASđọc sơ đồ phân cấpTopologyCRD để ép toàn bộ gangPyTorchJob/TrainJobnằm gọn trong một miềnNVLink(NVL72rack / cùng switch Leaf) thay vì rải mảnh qua các liên kết lõi chậm. (Khác vớiVolcanovốn thay thế toàn bộkube-scheduler,Kueuenhẹ và giữ nguyên tương thích mọi plugin của Kubernetes gốc).
Trụ cột 2 — Kiến trúc Hệ thống & Cẩm nang Quyết định Sản xuất (Production Decision Playbook)#
| Bài toán Huấn luyện Phân tán | Lựa chọn Ngây thơ (Gây sự cố) | Giải pháp Chuẩn SOTA 2026 (Ch 16 + Lab 14) |
Bối cảnh Mở rộng Hệ thống |
|---|---|---|---|
| Điều phối Quy trình ML | Script bash đơn lẻ, không cache, image :latest, hardcode S3 secret |
KFP v2 DSL \(\to\) IR YAML, DAG caching (4/4 warm hits), SHA-256 lineage, không :latest, 0 secrets |
Mở rộng với MLMD & CI/CD kiểm toán YAML trước apply |
| Đồng bộ Data Parallel | Parameter Server tập trung (\(O(W\Psi)\) \(\implies\) 35,925 ms, 0.24% eff ở W=32) |
PyTorch DDP Ring All-Reduce (< 2Ψ, 32.2x nhanh hơn 10G / 96.04% eff 400G) + Bucketing Overlap + Tree ở \(W\) lớn |
Đảm bảo tương đương toán học max_diff < 1e-5 qua bài kiểm thử CI |
| Mô hình Vượt VRAM 1 GPU | DDP nhân bản 16Ψ (112 GB cho 7B \(\implies\) CUDA OOM) |
PyTorch FSDP2 (DTensor / ZeRO-3) (14 GB/GPU, 8.0x tĩnh) + All-Gather prefetch |
Kết hợp HSDP (sharding nội bộ Node, DDP liên Node) ở cụm đa trăm GPU |
Cân bằng TP, PP, CP, EP |
GPipe thuần (O(m) VRAM kích hoạt, bong bóng 42.86% ở m=4) |
TP trên NVLink (\(TP \le 8\)) + 1F1B / Interleaved 1F1B (8.0x act saved, 4.48% bubble) + CP/EP |
Áp dụng thẳng công thức bong bóng chọn \(m \ge 4p\) |
| Lưu trữ & Lập lịch Cụm GPU | Đọc triệu file rời NFS + FIFO cấp từng Pod (2 deadlocks, 0.0% goodput) |
Shard tuần tự + NVMe cache (Lustre/GCS Fuse) + Kueue Gang (0 deadlocks, 77.5% goodput) |
Kết hợp Topology-Aware Scheduling (TAS) gom Pod cùng Leaf/NVLink |
Trụ cột 3 — Công nghệ 2026 & Mã nguồn Python/PyTorch Độc lập (100% Khả thi Trong .venv)#
Đoạn mã PyTorch/Python dưới đây chạy độc lập hoàn toàn trong .venv (không phụ thuộc cụm Kubernetes), chứng minh trực tiếp bốn trụ cột thực nghiệm của Chương 16:
- Tương đương Toán học (
Parity < 1e-5): Huấn luyện cùng tập dữ liệu trênSingleWorker,SyncParameterServer, vàRingAllReduceDDP(Reduce-Scatter+All-Gatherqua gradient buckets). - Định luật Mở rộng Băng thông (
W = 32,10 Gbps): So sánh lưu lượng Master PS vs Ring All-Reduce (\(< 2\Psi\)). - Phân mảnh Thực tế
FSDP2(DTensorSplit) &1F1BPipeline: Chia thực tế tensor PyTorch qua8rank bảo toàn tổng phần tử và kiểm tra tỷ lệ bong bóngGPipevsInterleaved 1F1B. - Lập lịch
KueueAll-or-Nothing vsFIFODeadlock: Mô phỏng hai job5-GPU trên cụm8GPU chứng minhKueuehoàn thành100%không deadlock.
from __future__ import annotations
import copy
import math
import torch
import torch.nn as nn
class TinyBlock(nn.Module):
def __init__(self, d_in: int = 12, d_hid: int = 24) -> None:
super().__init__()
self.net = nn.Sequential(
nn.Linear(d_in, d_hid),
nn.GELU(),
nn.Linear(d_hid, 2),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x)
def ring_allreduce_mean(tensors: list[torch.Tensor]) -> list[torch.Tensor]:
w = len(tensors)
flat_len = tensors[0].numel()
chunk = math.ceil(flat_len / w)
bufs = []
for t in tensors:
b = torch.zeros(chunk * w, dtype=torch.float64)
b[:flat_len] = t.detach().reshape(-1).to(torch.float64)
bufs.append(b)
# Phase 1: Reduce-Scatter (W - 1 ring steps)
for step in range(w - 1):
sends = [bufs[r][((r - step) % w) * chunk : ((r - step) % w + 1) * chunk].clone() for r in range(w)]
for r in range(w):
src = (r - 1) % w
c = (src - step) % w
bufs[r][c * chunk : (c + 1) * chunk] += sends[src]
# Phase 2: All-Gather (W - 1 ring steps)
for step in range(w - 1):
sends = [bufs[r][((r + 1 - step) % w) * chunk : ((r + 1 - step) % w + 1) * chunk].clone() for r in range(w)]
for r in range(w):
src = (r - 1) % w
c = (src + 1 - step) % w
bufs[r][c * chunk : (c + 1) * chunk] = sends[src]
shape = tensors[0].shape
return [(bufs[r][:flat_len] / float(w)).reshape(shape).to(torch.float32) for r in range(w)]
def verify_distributed_parity_and_fsdp2() -> None:
torch.manual_seed(42)
x = torch.randn(128, 12)
y = (x[:, 0] + 0.5 * x[:, 1] > 0).to(torch.long)
w_workers = 4
base = TinyBlock()
init_sd = copy.deepcopy(base.state_dict())
m_single = TinyBlock()
m_single.load_state_dict(copy.deepcopy(init_sd))
opt_s = torch.optim.SGD(m_single.parameters(), lr=0.1)
m_ring = [TinyBlock() for _ in range(w_workers)]
for m in m_ring:
m.load_state_dict(copy.deepcopy(init_sd))
opt_r = [torch.optim.SGD(m.parameters(), lr=0.1) for m in m_ring]
crit = nn.CrossEntropyLoss()
for step in range(4):
xb, yb = x[step * 32 : (step + 1) * 32], y[step * 32 : (step + 1) * 32]
opt_s.zero_grad()
crit(m_single(xb), yb).backward()
opt_s.step()
grads = []
for r in range(w_workers):
opt_r[r].zero_grad()
crit(m_ring[r](xb[r * 8 : (r + 1) * 8]), yb[r * 8 : (r + 1) * 8]).backward()
grads.append([p.grad.detach().clone() for p in m_ring[r].parameters() if p.grad is not None])
for pid in range(len(grads[0])):
synced = ring_allreduce_mean([grads[r][pid] for r in range(w_workers)])
for r in range(w_workers):
list(m_ring[r].parameters())[pid].grad = synced[r]
for o in opt_r:
o.step()
max_diff = max(
float((a - b).abs().max().item())
for a, b in zip(m_single.state_dict().values(), m_ring[0].state_dict().values(), strict=True)
)
assert max_diff < 1e-5
# FSDP2 real per-parameter sharding conservation across 8 ranks
sharded_counts = [0] * 8
for p in m_single.parameters():
for r, chunk in enumerate(torch.tensor_split(p.detach().reshape(-1), 8)):
sharded_counts[r] += chunk.numel()
assert sum(sharded_counts) == sum(p.numel() for p in m_single.parameters())
# 1F1B & Kueue checks
gpipe_b = (4 - 1) / (16 + 4 - 1)
int_1f1b_b = (4 - 1) / (2 * 16 + 4 - 1)
assert int_1f1b_b < gpipe_b
print(f"[Ch16 Pillar 3] Parity max_diff={max_diff:.2e} (<1e-5) | FSDP2 elems={sum(sharded_counts)} | Interleaved_1F1B={int_1f1b_b:.4f}")
if __name__ == "__main__":
verify_distributed_parity_and_fsdp2()
Trụ cột 4 — Thực hành Công nghiệp (Lab 14: kubeflow_distributed_lab) & Kết quả Thực nghiệm#
4.1 Kiến trúc Hai Tầng Lab 14 (labs/lab-14-kubeflow-4stage-distributed-training/)#
-
Tầng 1 — Tài nguyên Khai báo Đường ống & Hạ tầng Kubernetes (
pipelines/&manifests/):pipelines/kfp_4stage_training_pipeline.py&pipelines/kfp_4stage_pipeline_ir.yaml: Định nghĩa đường ống KFP v2 4 giai đoạn (data-prep\(\to\)distributed-train\(\to\)evaluate-model\(\to\)visualize-metrics) gọi mô-đunkubeflow_distributed_lab.distributed_training_bench, truyền tạo tác qua cổng chuẩn{{$.inputs.artifacts[...].uri}}, ghimepochs: 12khớp Python, ghim image phiên bản cụ thể (0tag:latest), bậtcachingOptions.enableCache: true, cấu hình GPUNVIDIA_H100: 4và giữ đúng lược đồContainerSpecprotobuf (không nhétsecurityContextcủa Kubernetes PodSpec vào cấpContainerSpectrong IR).manifests/pytorchjob_ddp.yaml: Khai báo CRDkubeflow.org/v1PyTorchJob(1 Master + 3 Workers = 4 GPUs), gắn nhãnkueue.x-k8s.io/queue-name: ml-team-gpu-queue, bậtsuspend: true, đặt--rdzv_id=intrusion-ddp-4gpu-job,serviceAccountName: kfp-distributed-trainer-sa,automountServiceAccountToken: false, cấu hìnhNCCL_IB_DISABLE, bộ nhớ chia sẻ/dev/shm8Gi,runAsNonRoot: true,allowPrivilegeEscalation: falsevà đọc bí mật S3 quasecretKeyRef(0mật khẩu tĩnh).manifests/kueue_clusterqueue.yaml: Khai báoResourceFlavor,ClusterQueue(8GPU quotanominalQuota,borrowingLimit,preemption, annotationkueue.x-k8s.io/wait-for-pods-ready-timeout: "300s"và tách cấu hìnhwaitForPodsReadyra controller toàn cục đúng chuẩn Kueuev1beta1) vàLocalQueue.
-
Tầng 2 — Bộ Thực nghiệm & Kiểm toán Python (
src/kubeflow_distributed_lab/):distributed_training_bench.py: Chạy đối chứngSingleWorkervsSyncParameterServervsRingAllReduceDDPlẫn đa tiến trìnhtorch.distributed(backend="gloo",dist.FileStore,DDP), mô phỏng định luật mở rộngPSvsRingqua10G / 100G / 400G, phân mảnh thực tếZeRO-1/2/FSDP2trên PyTorch và tính toán bong bóngGPipe/1F1B.kfp_pipeline_and_kueue.py: Kiểm toán bảo mật, lược đồ IR protobuf / Kueuev1beta1& DAG không chu trình bằngPyYAML, chạy cục bộ toàn bộ đường ống 4 bước kèm SHA-256 DAG caching, mô phỏngFIFODeadlock vsKueueAll-or-Nothing và xuất11OpenTelemetry spans quaBoundedInMemorySpanExporter(maxlen=256).
4.2 Bảng Kết quả Đo đạc Thực nghiệm (artifacts/t2_ch16_lab14_results.json, seed=42)#
Thực nghiệm (kubeflow_distributed_lab) |
Thông số Đo được (seed = 42) |
Bất biến Kỹ thuật Được Chứng minh |
|---|---|---|
1. Tương đương Gradient (Single/PS/Ring + gloo) |
4,866 params, 5 buckets (2.98e-08); gloo (ws=2) vs_single = 1.49e-08, inter_rank = 0.0, loss_end = 0.460285 |
Phân tán đồng bộ & đa tiến trình torch.distributed bảo toàn quỹ đạo |
2. Mở rộng PS vs Ring All-Reduce (350M fp16, W = 32) |
10G Eth: PS 35,925.03 ms (0.24% eff) vs Ring 1,115.68 ms (32.2x); 400G IB: 96.04% eff (30.73x) |
Ring All-Reduce (< 2Ψ) loại bỏ nút thắt cổ chai \(O(W)\) của Master PS |
3. Phân mảnh ZeRO-1/2/FSDP2 (W = 8) & 1F1B (p = 4) |
7B LLM: 112.0 GB -> 14.0 GB/GPU (8.0x tĩnh / 4.05x đỉnh); 1F1B 8.0x act mem, 4.48% bubble (m=32) |
Phân mảnh DTensor dim-0 & xen kẽ 1F1B mở khóa mô hình lớn không OOM |
4a. Kiểm toán YAML/CRD (KFP IR + PyTorchJob + Kueue) |
Quét 4 tệp (0 secrets, 0 :latest, 6 pinned images), 4 bước DAG acyclic, bắt sạch lỗi khi giả mạo (Tests 05, 23) |
Cổng kiểm toán tự động ngăn sai phạm bảo mật & lược đồ CRD trước apply |
4b. Đường ống KFP v2 4 Giai đoạn (Intrusion Detection) |
ROC-AUC = 0.9916, F1 = 0.9496, Acc = 0.9453; Run 1 cache 0/4 \(\to\) Run 2 cache 4/4; 11 OTel spans |
Pipeline tái lập, tiết kiệm tài nguyên bằng SHA-256 cache & truy vết đầy đủ |
4c. Lập lịch Bầy đàn Kueue vs FIFO (8 GPU, 6 Jobs) |
FIFO: 2 deadlocks (0/6 xong, 0.0% goodput) vs Kueue: 0 deadlocks (6/6 xong, 77.5% goodput) |
Cấp phát All-or-Nothing chấm dứt treo chéo đa GPU |
4.3 Quy trình Kiểm định Tự động (24/24 Test Cases Pass, 0 Skipped, 0 # type: ignore)#
cd 03-track-2-data-and-ai-engineering/part-03-distributed-k8s-cloud-and-gateway/labs/lab-14-kubeflow-4stage-distributed-training
python pipelines/kfp_4stage_training_pipeline.py
PYTHONPATH=src python scripts/run_lab_demo.py --seed 42 --output artifacts/t2_ch16_lab14_results.json
ruff check src scripts tests pipelines
mypy --strict src tests
pytest -p no:cacheprovider -v
uv lock --check
Trụ cột 5 — Danh mục Tài liệu SOTA (7 Tài liệu) & Bài tập Chuyên sâu#
5.1 Tài liệu Đọc Kinh điển & Frontier 2024–2026#
- Kubeflow Community & CNCF (2024–2026). Kubeflow Pipelines v2 IR Specification, ML Metadata (MLMD), Training Operator (
PyTorchJob) & Kubeflow Trainer v2 (TrainJob/ClusterTrainingRuntime/PodGroup). — Chuẩn hóa vòng đời đường ống ML đa bước và lập lịch gang giữa Pod nạp dữ liệu với GPU worker. - Li, S. et al. — Meta PyTorch Team (2020–2026). PyTorch Distributed: Experiences on Accelerating Data Parallel Training (VLDB 2020),
FSDP2(fully_shardDTensor dim-0), & Distributed Checkpoint (DCP). — Loại bỏFlatParameter/record_streamvà hỗ trợ checkpoint không tốn truyền thông lại. - Patarasuk, P. & Yuan, X. / NVIDIA NCCL & RoCEv2 Networking Team (2009–2026). Bandwidth Optimal All-Reduce (
Ring&Double-Binary Tree) &RoCEv2 ECN + DCQCNvsPFCDeadlock. — Chứng minh cận dưới lưu lượng \(2\frac{W-1}{W}\Psi\), độ trễ \(O(\log W)\) và kiểm soát nghẽn RDMA tránh treo PAUSE frame. - Rajbhandari, S. et al. — Microsoft DeepSpeed (2020–2025). ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (SC20) & ZeRO-Infinity. — Phân rã toán học
16Ψvà các cấp độ shardingZeRO-1/2/3. - Shoeybi, M., Narayanan, D. et al. — NVIDIA Megatron-LM (2019–2026). Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM (
TP,1F1B,Interleaved 1F1B,CPRing Attention,EP). — Nền tảng toán học song song5Dcho LLM/MoE quy mô nghìn GPU. - CNCF
KueueWorking Group (2024–2026). Kueue Multi-Tenant Job Queueing:ResourceFlavor,ClusterQueue(v1beta1),LocalQueue, GlobalWaitForPodsReady&Topology-Aware Scheduling (TAS)(NVL72). — Giải pháp lập lịch bầy đàn chuẩn Kubernetes gom gang vào chung một miền NVLink và chấm dứt deadlock GPU. - Google Cloud & NVIDIA Storage Engineering (2024–2026). High-Throughput Distributed Storage for ML (
Lustre,GCS Fuse File Cache,NVIDIA GPUDirect Storage (GDS),WebDataset&PyTorch DataLoader). — Khử nghẽn I/O và truyền DMA trực tiếpNVMe <-> GPU VRAMbỏ qua CPU bounce buffer.
5.2 Sáu Bài tập Tự luận & Thực hành (ex1 – ex6) Kèm Thang điểm (Grading Rubric)#
-
Bài tập 1 (
ex1, 15%) — Tương đương Gradient (SinglevsPSvsRing All-Reduce+glooĐa tiến trình): Chứng minh vì saoSingleWorkerBaseline,SyncParameterServerTrainer,RingAllReduceDDPTrainer(2.98e-08) vàrun_real_torch_distributed_gloo_parity(1.49e-08,ws=2) hội tụ cùng quỹ đạo (< 1e-5), đồng thời giải thích thuật toán2phaReduce-Scatter + All-Gathervà gom bucket theo thứ tự ngược (Tests 06–07, 22, 24).Thang điểm: Đúng cơ chế 2 pha Ring (
5%), giải thích Bucketing Overlap (5%), passTests 06–07, 22, 24(5%). -
Bài tập 2 (
ex2, 20%) — Định luật Mở rộngParameter ServervsRing/Tree All-Reduce&RoCEv2 ECN+DCQCN: Dẫn xuất lưu lượng Master PS \(2W\Psi\) (44,800 MBtạiW=32) so với Ring \(2\frac{W-1}{W}\Psi\) (1,356.25 MB), phân tích nguyên nhân PS sụp đổ xuống0.24%hiệu suất (35,925.03 ms) trên10GEthernet trong khi Ring nhanh hơn32.2x, và giải thích khi nàoNCCLchuyển sangDouble-Binary Tree(10vs62hops) cũng như vai tròECN + DCQCNtránhPFChead-of-line blocking (Tests 08–09).Thang điểm: Đúng dẫn xuất băng thông & bất biến Hypothesis (
8%), phân tích Ring/Tree &ECN+DCQCN(6%), passTests 08–09(6%). -
Bài tập 3 (
ex3, 20%) — Phân mảnh Bộ nhớZeRO-1/2/FSDP2& Đường ống1F1B: Tính toán phân rã bộ nhớ hỗn hợp16Ψ(112.0 GBcho LLM7B), đối chiếu kết quả phân mảnh thực tế PyTorch (134,288phần tử \(\to\)FSDP2 DTensor dim-0giảm8.0xtĩnh /4.05xđỉnh và lợi íchDCP), và giải thích vì sao1F1Bgiảm8.0xbộ nhớ kích hoạt (m=32, p=4) cònInterleaved 1F1Bhạ bong bóng xuống4.48%(Tests 10–12).Thang điểm: Đúng phép tính
ZeRO-1/2/3&DTensor/DCP(7%), chứng minh bất biến bong bóng1F1B(7%), passTests 10–12(6%). -
Bài tập 4 (
ex4, 15%) — Đường ốngKFP v24 Giai đoạn (IR YAML, SHA-256 Cache &MLMD): Phân tích đồ thịdata-prep -> distributed-train -> evaluate-model -> visualize-metricstrongkfp_4stage_pipeline_ir.yaml(cổng{{$.inputs.artifacts[...].uri}},ContainerSpecprotobuf hợp lệ) vàkfp_4stage_training_pipeline.py, giải thích cơ chế chống rò rỉ train/eval và vì sao lần chạy thứ hai đạt4/4cache hits vớiROC-AUC = 0.9916(Tests 13–14, 23).Thang điểm: Đúng cấu trúc
IR YAML& chống rò rỉ split (6%), giải thích SHA-256 DAG caching (5%), passTests 13–14, 23(4%). -
Bài tập 5 (
ex5, 15%) — Lập lịch Bầy đànKueue(TAS) Loại bỏ Deadlock GPU &GPUDirect Storage: Phân tích kịch bản6PyTorchJobtrên cụm8GPU nơiFIFOtừng Pod khóa cứng2job5-GPU (0.0%goodput), giải thích cơ chếsuspend: true+ClusterQueue(v1beta1) + globalWaitForPodsReady+Kueue TAS(NVL72) giúpKueueđạt0deadlocks (77.5%goodput), kèm kiến trúcLustre/GCS Fuse/GDSchống đóiDataLoader(Tests 15–17, 23).Thang điểm: Phân tích chính xác điều kiện deadlock,
ClusterQueueschema &TAS(6%), đề xuất lưu trữGDS/cache chống đói GPU (5%), passTests 15–17, 23(4%). -
Bài tập 6 (
ex6, 15%) — Kiểm toán Bảo mậtPyTorchJob/KFP&Bounded OpenTelemetry: Chứng minh bộ kiểm toán YAML/CRD bắt chính xác các hành vi giả mạo (:latest, plaintext password,suspend: false, chu trình DAG,ClusterQueue.spec.waitForPodsReadyhoặcContainerSpec.securityContexttrongTests 05, 23), kết hợp thu11OTel spans trongBoundedInMemorySpanExporter,0# type: ignore, pass24/24pytest +ruff+mypy --strict+uv lock --check(Tests 01–05, 18–21, 23).Thang điểm: Đúng chính sách bảo mật, lược đồ CRD & kiểm thử giả mạo (
6%), sạch AST/OTel/uv.lock(5%), passTests 01–05, 18–21, 23(4%).
5.3 Tám Câu hỏi Trắc nghiệm Khái niệm (q1 – q8, Đồng bộ quiz_and_hints.json)#
- (
q1— Kiến trúcKFP v2&PyTorchJobvsKubeflow Trainer v2): Sự khác biệt cốt lõi giữaKFP v2 IR YAMLso vớiv1, và vai trò củaPyTorchJob/Kubeflow Trainer v2 (TrainJob + PodGroup)cùngKatiblà gì? - (
q2— Tương đương Toán học & Bản chấtRing All-Reduce): TrongLab 14(Tests 06–07, 24), vì saoSingleWorker,SyncPS,Ring All-Reduce DDPvàgloođa tiến trình đạt độ lệch trọng số< 1e-5và 2 phaReduce-Scatter + All-Gathervận hành thế nào? - (
q3— Cổ chaiParameter ServervsRing/Tree All-Reduce&ECN+DCQCN): Khi mở rộng lênW = 32worker trên10 GbpsEthernet (Test 08), vì saoPStụt xuống0.24%hiệu suất (35,925.03 ms) trong khiRing All-Reducenhanh hơn32.2x, khi nàoNCCLdùngDouble-Binary Treevà vì saoRoCEv2ưu tiênECN + DCQCN? - (
q4—ZeRO-1/2/3&PyTorch FSDP2DTensor dim-0): Trên mô hình7Bhỗn hợpAdamW(112.0 GBbaseline16Ψ) chia qua8GPU (Test 10),ZeRO-1,ZeRO-2vàPyTorch FSDP2 (DTensor dim-0 + DCP)giảm bộ nhớ tĩnh và loại bỏFlatParameter/record_streamra sao? - (
q5—5D Parallelism:TP,PP(GPipevs1F1B),CP&EP): Lợi thế sống còn của1F1BvàInterleaved 1F1B(Tests 11–12) so vớiGPipeởp = 4, m = 32là gì, và các trụcTP,CP,EPánh xạ vào phần cứngNVLink/RDMAthế nào? - (
q6— Lưu trữ Phân tán ML,GDS& Chống ĐóiDataLoader): Tại sao đọc ngẫu nhiên triệu tệp nhỏ trênNFS/S3làm GPU rỗi chờ I/O, và sự kết hợp giữa shard tuần tự (WebDataset/Parquet),Lustre/GCS FuseNVMe cache,GPUDirect Storage (GDS)cùngDataLoadergiải quyết thế nào? - (
q7—KueueGang Scheduling vs DeadlockFIFO): Trên cụm8GPU nhận haiPyTorchJob5-GPU đồng thời (Tests 15, 23), vì saoFIFOtừng Pod chết cứng ở0.0%goodput (2deadlocks) vàKueue(suspend: true,ClusterQueuev1beta1, globalWaitForPodsReady,Kueue TASNVL72) khắc phục ra sao? - (
q8— Kiểm toán Bảo mậtPyTorchJob/KFP, SHA-256 Caching &Bounded OTel): Những chốt kiểm soát nào trongLab 14(Tests 01–05, 13, 19, 23) ngăn chặn rò rỉ mật khẩu, ảnh:latest, sai lược đồContainerSpec/ClusterQueue, chạy lặp pipeline vô ích và mất dấu telemetry?
W=32 Distributed Step Time (ms) on 10 Gbps Ethernet (350M fp16)
7B Mixed-Precision AdamW Static Memory per GPU (GB, W=8 Workers)
Pipeline Parallelism (p=4 Stages) Idle Bubble Ratio (%)
8-GPU Multi-Job Cluster Goodput (%): Naive FIFO vs Kueue Gang
Gradient Parity Verification & 4-Stage KFP v2 Pipeline Lineage
| stage_or_trainer | metric_or_sha | cache_or_parity | status |
|---|---|---|---|
| SingleWorker vs SyncPS | loss_end=0.460285 | max_diff=2.98e-08 | PASS (<1e-5) |
| SingleWorker vs RingDDP | loss_end=0.460285 (5 buckets) | max_diff=2.98e-08 | PASS (<1e-5) |
| KFP Stage: data-prep | sha256:d4489bb3ae52 | run1=False | run2=True | CACHED_OK |
| KFP Stage: distributed-train | sha256:15a642d79013 | run1=False | run2=True | CACHED_OK |
| KFP Stage: evaluate-model | sha256:a98f9e53a731 | run1=False | run2=True | CACHED_OK |
| KFP Stage: visualize-metrics | sha256:b473430871d8 | run1=False | run2=True | CACHED_OK |
Parameter Server vs Ring All-Reduce Scaling Law (10 Gbps vs 400 Gbps)
| workers_and_link | ps_master_vs_ring_mb | step_time_ms | scaling_eff |
|---|---|---|---|
| W=2 (10G Eth) | PS 2800.0 vs Ring 700.0 MB | PS 2325.03 vs Ring 589.78 | PS 3.66% vs Ring 14.41% |
| W=4 (10G Eth) | PS 5600.0 vs Ring 1050.0 MB | PS 4565.03 vs Ring 869.84 | PS 1.86% vs Ring 9.77% |
| W=8 (10G Eth) | PS 11200.0 vs Ring 1225.0 MB | PS 9045.03 vs Ring 1009.96 | PS 0.94% vs Ring 8.42% |
| W=16 (10G Eth) | PS 22400.0 vs Ring 1312.5 MB | PS 18005.03 vs Ring 1080.2 | PS 0.47% vs Ring 7.87% |
| W=32 (10G Eth) | PS 44800.0 vs Ring 1356.25 MB | PS 35925.03 vs Ring 1115.68 | PS 0.24% vs Ring 7.62% |
| W=32 (400G IB) | PS 44800.0 vs Ring 1356.25 MB | PS 981.03 vs Ring 88.51 | PS 8.66% vs Ring 96.04% |
ZeRO-1/2/FSDP2 Memory Sharding (W=8) & Pipeline 1F1B Bubble Sweep
| strategy_or_pp | memory_or_microbatch | savings_or_bubble | comm_or_act_mem |
|---|---|---|---|
| DDP Baseline (16 Psi) | 112.0 GB/GPU (7B) | 1.0x static | 1.75x Psi comm |
| ZeRO-1 (Optimizer Sharded) | 38.5 GB/GPU (7B) | 2.91x static | 1.75x Psi comm |
| ZeRO-2 (Opt + Grad Sharded) | 26.25 GB/GPU (7B) | 4.27x static | 1.75x Psi comm |
| PyTorch FSDP2 / ZeRO-3 (DTensor) | 14.0 GB/GPU (7B) | 8.0x static | 2.62x Psi comm |
| PP p=4, m=4 | GPipe 42.86% | Interleaved 27.27% | 1F1B act 1.0x saved |
| PP p=4, m=8 | GPipe 27.27% | Interleaved 15.79% | 1F1B act 2.0x saved |
| PP p=4, m=16 | GPipe 15.79% | Interleaved 8.57% | 1F1B act 4.0x saved |
| PP p=4, m=32 | GPipe 8.57% | Interleaved 4.48% | 1F1B act 8.0x saved |
Kueue Gang Scheduling vs FIFO Deadlock & YAML/CRD Policy Audit
| target | completed_or_files | deadlocks_or_rules | verdict |
|---|---|---|---|
| Naive FIFO Pod-by-Pod (8 GPUs) | 0/6 jobs | 2 deadlocked (0.0%) | DEADLOCKED |
| Kueue Gang + WaitForPodsReady | 6/6 jobs | 0 deadlocks (77.5%) | PASS |
| KFP IR + PyTorchJob + Kueue YAML | 4 files scanned | 0 secrets, 0 :latest, 4 GPUs, non-root | PASS |
03-track-2-data-and-ai-engineering/part-03-distributed-k8s-cloud-and-gateway/labs/lab-14-kubeflow-4stage-distributed-training
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "kubeflow-distributed-lab"
version = "0.1.0"
description = "FSDS-SOTA-2026 Track 2 Lab 14: Kubeflow Pipelines v2 (4-Stage IR), PyTorchJob DDP Ring All-Reduce vs Parameter Server, FSDP2/ZeRO-3, 1F1B Pipeline & Kueue GPU Gang Scheduling"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"opentelemetry-sdk>=1.28",
"pydantic>=2.0",
"pyyaml>=6.0",
"torch>=2.5",
]
[project.optional-dependencies]
dev = [
"hypothesis>=6.100",
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[project.scripts]
fsds-kubeflow-distributed-lab = "kubeflow_distributed_lab.kfp_pipeline_and_kueue:main"
[[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]
testpaths = ["tests"]
pythonpath = ["src", "."]
addopts = "-v"
[tool.ruff]
target-version = "py312"
line-length = 105
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "RUF"]
[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
[[tool.mypy.overrides]]
module = [
"yaml",
]
ignore_missing_imports = true
"""Cleanly typed KFP v2 style 4-stage Kubeflow pipeline aligned with kfp_4stage_pipeline_ir.yaml."""
from __future__ import annotations
import hashlib
import html
import json
from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, TypeVar, cast
import numpy as np
import torch
import torch.nn as nn
import yaml
F = TypeVar("F", bound=Callable[..., Any])
@dataclass(frozen=True, slots=True)
class ComponentSpec:
"""Lightweight KFP v2 component descriptor matching compiled IR definitions."""
name: str
image: str
inputs: tuple[str, ...]
outputs: tuple[str, ...]
fn: Callable[..., Any]
def __call__(self, *args: Any, **kwargs: Any) -> Any:
return self.fn(*args, **kwargs)
@dataclass(frozen=True, slots=True)
class PipelineStageResult:
"""Deterministic output record for a single KFP stage execution."""
stage_name: str
cache_hit: bool
cache_key: str
artifact_uri: str
payload: dict[str, Any]
@dataclass(frozen=True, slots=True)
class PipelineExecutionReport:
"""Structured summary emitted by running the 4-stage pipeline locally."""
pipeline_name: str
run_id: str
stages: tuple[PipelineStageResult, ...]
cache_hits: int
total_stages: int
roc_auc: float
f1_score: float
eval_accuracy: float
train_loss_end: float
throughput_samples_per_sec: float
html_visualization_summary: str
ir_dag_tasks: tuple[str, ...] = field(default_factory=tuple)
def kfp_component(
*,
name: str,
image: str,
inputs: tuple[str, ...],
outputs: tuple[str, ...],
) -> Callable[[F], ComponentSpec]:
"""Decorator marking a typed function as a KFP v2 style pipeline component."""
def _decorator(fn: F) -> ComponentSpec:
return ComponentSpec(
name=name,
image=image,
inputs=inputs,
outputs=outputs,
fn=fn,
)
return _decorator
def _sha256_json(obj: Any) -> str:
raw = json.dumps(obj, sort_keys=True, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(raw).hexdigest()
def _roc_auc_score_binary(y_true: np.ndarray, y_prob: np.ndarray) -> float:
"""Compute exact trapezoidal ROC-AUC without external sklearn dependency."""
pos = y_true == 1
neg = y_true == 0
n_pos = int(np.sum(pos))
n_neg = int(np.sum(neg))
if n_pos == 0 or n_neg == 0:
return 0.5
order = np.argsort(-y_prob, kind="mergesort")
y_sorted = y_true[order]
tps = np.cumsum(y_sorted == 1, dtype=np.float64)
fps = np.cumsum(y_sorted == 0, dtype=np.float64)
tpr = np.concatenate(([0.0], tps / n_pos))
fpr = np.concatenate(([0.0], fps / n_neg))
return float(np.trapezoid(tpr, fpr))
class IntrusionClassifierNet(nn.Module):
"""Compact residual-MLP network for deterministic network intrusion classification."""
def __init__(self, in_dim: int = 12, hidden_dim: int = 32, num_classes: int = 2) -> None:
super().__init__()
self.net = nn.Sequential(
nn.Linear(in_dim, hidden_dim),
nn.GELU(),
nn.Linear(hidden_dim, hidden_dim),
nn.GELU(),
nn.Linear(hidden_dim, num_classes),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return cast(torch.Tensor, self.net(x))
@kfp_component(
name="data-prep",
image="ghcr.io/fsds-sota/kubeflow-data-prep:2026.2.0",
inputs=("dataset_uri", "seed", "test_ratio"),
outputs=("prepared_dataset", "dataset_sha256"),
)
def data_prep_component(
*,
dataset_uri: str = "s3://ml-datasets-prod/intrusion-v2/packets.parquet",
seed: int = 42,
test_ratio: float = 0.25,
n_samples: int = 512,
n_features: int = 12,
) -> dict[str, Any]:
"""Stage 1: Generate deterministic intrusion-detection dataset with zero train/eval leakage."""
rng = np.random.default_rng(seed)
x_raw = rng.normal(0.0, 1.0, size=(n_samples, n_features)).astype(np.float32)
true_w = rng.normal(0.0, 0.85, size=(n_features,)).astype(np.float32)
nonlinear = 0.75 * np.tanh(x_raw[:, 0] * x_raw[:, 1]) - 0.55 * (x_raw[:, 2] ** 2 - 1.0)
logits = x_raw @ true_w + nonlinear + rng.normal(0.0, 0.35, size=(n_samples,)).astype(np.float32)
y_all = (logits > 0.0).astype(np.int64)
n_eval = max(32, round(n_samples * test_ratio))
n_train = n_samples - n_eval
x_train_raw, x_eval_raw = x_raw[:n_train], x_raw[n_train:]
y_train, y_eval = y_all[:n_train], y_all[n_train:]
# Fit standardizer strictly on train split only (prevent leakage)
mean = x_train_raw.mean(axis=0, keepdims=True)
std = np.maximum(x_train_raw.std(axis=0, keepdims=True), 1e-5)
x_train = ((x_train_raw - mean) / std).astype(np.float32)
x_eval = ((x_eval_raw - mean) / std).astype(np.float32)
digest = hashlib.sha256(x_train.tobytes() + y_train.tobytes() + x_eval.tobytes()).hexdigest()
return {
"dataset_uri": dataset_uri,
"dataset_sha256": digest,
"n_features": n_features,
"num_train_samples": int(n_train),
"num_eval_samples": int(n_eval),
"train_positive_rate": round(float(y_train.mean()), 4),
"eval_positive_rate": round(float(y_eval.mean()), 4),
"x_train": x_train.tolist(),
"y_train": y_train.tolist(),
"x_eval": x_eval.tolist(),
"y_eval": y_eval.tolist(),
}
@kfp_component(
name="distributed-train",
image="ghcr.io/fsds-sota/kubeflow-pytorch-ddp:2026.2.0-cuda12.4",
inputs=("prepared_dataset", "num_workers", "epochs", "batch_size", "learning_rate", "seed"),
outputs=("trained_model", "train_metrics", "checkpoint_sha256"),
)
def distributed_train_component(
*,
prepared_dataset: dict[str, Any],
num_workers: int = 4,
epochs: int = 12,
batch_size: int = 64,
learning_rate: float = 0.05,
strategy: str = "ring_allreduce_ddp",
seed: int = 42,
) -> dict[str, Any]:
"""Stage 2: Train IntrusionClassifierNet using synchronous Ring All-Reduce DDP gradient averaging."""
torch.manual_seed(seed)
x_train = torch.tensor(prepared_dataset["x_train"], dtype=torch.float32)
y_train = torch.tensor(prepared_dataset["y_train"], dtype=torch.long)
n_features = int(prepared_dataset["n_features"])
model = IntrusionClassifierNet(in_dim=n_features, hidden_dim=32, num_classes=2)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9)
loss_curve: list[float] = []
n_samples = x_train.shape[0]
steps_per_epoch = max(1, n_samples // batch_size)
local_bs = max(1, batch_size // num_workers)
for _epoch in range(epochs):
epoch_loss = 0.0
for step_idx in range(steps_per_epoch):
start = step_idx * batch_size
xb = x_train[start : start + batch_size]
yb = y_train[start : start + batch_size]
if xb.shape[0] < num_workers:
continue
# Simulate exact Ring All-Reduce gradient averaging over W worker shards
shard_grads: list[list[torch.Tensor]] = []
step_loss = 0.0
for rank in range(num_workers):
s0 = rank * local_bs
s1 = s0 + local_bs if rank < num_workers - 1 else xb.shape[0]
optimizer.zero_grad()
logits = model(xb[s0:s1])
loss = criterion(logits, yb[s0:s1])
loss.backward()
step_loss += float(loss.item()) * (s1 - s0) / float(xb.shape[0])
shard_grads.append(
[p.grad.detach().clone() for p in model.parameters() if p.grad is not None]
)
# Ring Reduce-Scatter + All-Gather exact mean across shards
optimizer.zero_grad()
tail_bs = xb.shape[0] - local_bs * (num_workers - 1)
for p_idx, p in enumerate(model.parameters()):
weighted = [
shard_grads[r][p_idx]
* (float(local_bs if r < num_workers - 1 else tail_bs) / float(xb.shape[0]))
for r in range(num_workers)
]
p.grad = torch.stack(weighted, dim=0).sum(dim=0)
optimizer.step()
epoch_loss += step_loss / steps_per_epoch
loss_curve.append(round(epoch_loss, 6))
state_dict_lists = {k: v.detach().cpu().tolist() for k, v in model.state_dict().items()}
ckpt_sha256 = _sha256_json(state_dict_lists)
# Deterministic modeled throughput accounting for DDP scaling efficiency on 100 Gbps RoCEv2
throughput_samples_sec = round(420.0 * num_workers * 0.94, 2)
return {
"strategy": strategy,
"num_workers": num_workers,
"epochs": epochs,
"loss_curve": loss_curve,
"train_loss_start": loss_curve[0],
"train_loss_end": loss_curve[-1],
"throughput_samples_per_sec": throughput_samples_sec,
"checkpoint_sha256": ckpt_sha256,
"state_dict": state_dict_lists,
"n_features": n_features,
}
@kfp_component(
name="evaluate-model",
image="ghcr.io/fsds-sota/kubeflow-eval-viz:2026.2.0",
inputs=("prepared_dataset", "trained_model"),
outputs=("eval_metrics", "confusion_metrics", "roc_auc", "f1_score"),
)
def evaluate_model_component(
*,
prepared_dataset: dict[str, Any],
trained_model: dict[str, Any],
) -> dict[str, Any]:
"""Stage 3: Compute holdout accuracy, precision, recall, F1, ROC-AUC, and confusion matrix."""
n_features = int(trained_model["n_features"])
model = IntrusionClassifierNet(in_dim=n_features, hidden_dim=32, num_classes=2)
loaded_sd = {k: torch.tensor(v, dtype=torch.float32) for k, v in trained_model["state_dict"].items()}
model.load_state_dict(loaded_sd)
model.eval()
x_eval = torch.tensor(prepared_dataset["x_eval"], dtype=torch.float32)
y_eval = np.array(prepared_dataset["y_eval"], dtype=np.int64)
with torch.no_grad():
logits = model(x_eval)
probs = torch.softmax(logits, dim=-1)[:, 1].cpu().numpy()
preds = (probs >= 0.5).astype(np.int64)
tp = int(np.sum((preds == 1) & (y_eval == 1)))
fp = int(np.sum((preds == 1) & (y_eval == 0)))
tn = int(np.sum((preds == 0) & (y_eval == 0)))
fn = int(np.sum((preds == 0) & (y_eval == 1)))
acc = float((tp + tn) / max(1, len(y_eval)))
prec = float(tp / max(1, tp + fp))
rec = float(tp / max(1, tp + fn))
f1 = float(2 * prec * rec / max(1e-9, prec + rec))
roc_auc = _roc_auc_score_binary(y_eval, probs)
return {
"eval_accuracy": round(acc, 4),
"precision": round(prec, 4),
"recall": round(rec, 4),
"f1_score": round(f1, 4),
"roc_auc": round(roc_auc, 4),
"confusion_matrix": {"tp": tp, "fp": fp, "tn": tn, "fn": fn},
"num_eval_samples": len(y_eval),
}
@kfp_component(
name="visualize-metrics",
image="ghcr.io/fsds-sota/kubeflow-eval-viz:2026.2.0",
inputs=("train_metrics", "eval_metrics", "confusion_metrics"),
outputs=("metrics_report_html", "summary_report_uri"),
)
def visualize_metrics_component(
*,
train_metrics: dict[str, Any],
eval_metrics: dict[str, Any],
) -> dict[str, Any]:
"""Stage 4: Render structured ROC/loss/throughput report + HTML visualization summary artifact."""
cm = eval_metrics["confusion_matrix"]
loss_curve: list[float] = train_metrics["loss_curve"]
bars = " ".join(
f"<span style='display:inline-block;width:14px;height:{max(8, round(lv * 60))}px;"
f"background:#0284c7;margin-right:3px;' title='Epoch {idx + 1}: {lv:.4f}'></span>"
for idx, lv in enumerate(loss_curve)
)
html_summary = (
"<section class='kfp-viz-report'>"
"<h3>KFP v2 Intrusion Detection Report</h3>"
f"<p>Strategy: <code>{html.escape(str(train_metrics['strategy']))}</code> | "
f"Workers: <strong>{int(train_metrics['num_workers'])}</strong> | "
f"Throughput: <strong>{train_metrics['throughput_samples_per_sec']} samples/s</strong></p>"
f"<p>ROC-AUC: <strong>{eval_metrics['roc_auc']:.4f}</strong> | "
f"F1: <strong>{eval_metrics['f1_score']:.4f}</strong> | "
f"Accuracy: <strong>{eval_metrics['eval_accuracy']:.4f}</strong></p>"
f"<p>Confusion Matrix: TP={cm['tp']}, FP={cm['fp']}, TN={cm['tn']}, FN={cm['fn']}</p>"
f"<div>{bars}</div>"
"</section>"
)
return {
"metrics_summary": {
"roc_auc": eval_metrics["roc_auc"],
"f1_score": eval_metrics["f1_score"],
"eval_accuracy": eval_metrics["eval_accuracy"],
"train_loss_start": train_metrics["train_loss_start"],
"train_loss_end": train_metrics["train_loss_end"],
"throughput_samples_per_sec": train_metrics["throughput_samples_per_sec"],
"confusion_matrix": cm,
},
"html_visualization_summary": html_summary,
}
def load_pipeline_ir_spec(ir_path: Path | None = None) -> dict[str, Any]:
"""Load the declarative KFP v2 IR YAML specification adjacent to this pipeline file."""
target = ir_path or (Path(__file__).resolve().parent / "kfp_4stage_pipeline_ir.yaml")
loaded = yaml.safe_load(target.read_text(encoding="utf-8"))
if not isinstance(loaded, dict):
raise ValueError(f"Expected mapping in KFP IR YAML at {target}")
return loaded
def run_local_4stage_pipeline(
*,
dataset_uri: str = "s3://ml-datasets-prod/intrusion-v2/packets.parquet",
num_workers: int = 4,
epochs: int = 12,
batch_size: int = 64,
learning_rate: float = 0.05,
seed: int = 42,
cache_store: dict[str, dict[str, Any]] | None = None,
) -> PipelineExecutionReport:
"""Execute all 4 KFP v2 stages locally with SHA-256 DAG caching and lineage."""
ir_spec = load_pipeline_ir_spec()
dag_tasks = tuple(ir_spec["root"]["dag"]["tasks"].keys())
cache = cache_store if cache_store is not None else {}
run_id = f"kfp-run-seed{seed}-w{num_workers}"
stage_results: list[PipelineStageResult] = []
cache_hits = 0
def _run_cached(
stage: str,
key_inputs: dict[str, Any],
fn: Callable[[], dict[str, Any]],
) -> dict[str, Any]:
nonlocal cache_hits
ckey = _sha256_json({"stage": stage, "inputs": key_inputs})
uri = f"s3://ml-artifacts-prod/kfp-runs/{run_id}/{stage}/{ckey[:12]}"
if ckey in cache:
cache_hits += 1
payload = cache[ckey]
stage_results.append(
PipelineStageResult(
stage_name=stage,
cache_hit=True,
cache_key=ckey,
artifact_uri=uri,
payload=payload,
)
)
return payload
payload = fn()
cache[ckey] = payload
stage_results.append(
PipelineStageResult(
stage_name=stage,
cache_hit=False,
cache_key=ckey,
artifact_uri=uri,
payload=payload,
)
)
return payload
prep_out = _run_cached(
"data-prep",
{"dataset_uri": dataset_uri, "seed": seed, "test_ratio": 0.25},
lambda: data_prep_component(dataset_uri=dataset_uri, seed=seed, test_ratio=0.25),
)
train_out = _run_cached(
"distributed-train",
{
"dataset_sha256": prep_out["dataset_sha256"],
"num_workers": num_workers,
"epochs": epochs,
"batch_size": batch_size,
"learning_rate": learning_rate,
"seed": seed,
},
lambda: distributed_train_component(
prepared_dataset=prep_out,
num_workers=num_workers,
epochs=epochs,
batch_size=batch_size,
learning_rate=learning_rate,
seed=seed,
),
)
eval_out = _run_cached(
"evaluate-model",
{
"dataset_sha256": prep_out["dataset_sha256"],
"checkpoint_sha256": train_out["checkpoint_sha256"],
},
lambda: evaluate_model_component(prepared_dataset=prep_out, trained_model=train_out),
)
viz_out = _run_cached(
"visualize-metrics",
{
"checkpoint_sha256": train_out["checkpoint_sha256"],
"eval_metrics": eval_out,
},
lambda: visualize_metrics_component(train_metrics=train_out, eval_metrics=eval_out),
)
return PipelineExecutionReport(
pipeline_name=str(ir_spec["pipelineInfo"]["name"]),
run_id=run_id,
stages=tuple(stage_results),
cache_hits=cache_hits,
total_stages=len(stage_results),
roc_auc=float(eval_out["roc_auc"]),
f1_score=float(eval_out["f1_score"]),
eval_accuracy=float(eval_out["eval_accuracy"]),
train_loss_end=float(train_out["train_loss_end"]),
throughput_samples_per_sec=float(train_out["throughput_samples_per_sec"]),
html_visualization_summary=str(viz_out["html_visualization_summary"]),
ir_dag_tasks=dag_tasks,
)
if __name__ == "__main__":
shared_cache: dict[str, dict[str, Any]] = {}
first = run_local_4stage_pipeline(seed=42, cache_store=shared_cache)
second = run_local_4stage_pipeline(seed=42, cache_store=shared_cache)
print(
json.dumps(
{
"pipeline_name": first.pipeline_name,
"ir_dag_tasks": list(first.ir_dag_tasks),
"run1_cache_hits": first.cache_hits,
"run2_cache_hits": second.cache_hits,
"roc_auc": first.roc_auc,
"f1_score": first.f1_score,
"eval_accuracy": first.eval_accuracy,
"train_loss_end": first.train_loss_end,
},
indent=2,
)
)
schemaVersion: 2.1.0
sdkVersion: kfp-2.10.1
pipelineInfo:
name: intrusion-detection-distributed-training-pipeline
description: >-
Production 4-stage Kubeflow Pipelines v2 DAG: data_prep -> distributed_train
(PyTorch DDP Ring All-Reduce / FSDP2) -> evaluate_model -> visualize_metrics.
defaultPipelineRoot: s3://ml-artifacts-prod/kfp-runs
components:
comp-data-prep:
executorLabel: exec-data-prep
inputDefinitions:
parameters:
dataset_uri:
parameterType: STRING
seed:
parameterType: NUMBER_INTEGER
test_ratio:
parameterType: NUMBER_DOUBLE
outputDefinitions:
artifacts:
prepared_dataset:
artifactType:
schemaTitle: system.Dataset
schemaVersion: 0.0.1
parameters:
dataset_sha256:
parameterType: STRING
num_train_samples:
parameterType: NUMBER_INTEGER
num_eval_samples:
parameterType: NUMBER_INTEGER
comp-distributed-train:
executorLabel: exec-distributed-train
inputDefinitions:
artifacts:
prepared_dataset:
artifactType:
schemaTitle: system.Dataset
schemaVersion: 0.0.1
parameters:
num_workers:
parameterType: NUMBER_INTEGER
epochs:
parameterType: NUMBER_INTEGER
batch_size:
parameterType: NUMBER_INTEGER
learning_rate:
parameterType: NUMBER_DOUBLE
strategy:
parameterType: STRING
seed:
parameterType: NUMBER_INTEGER
outputDefinitions:
artifacts:
trained_model:
artifactType:
schemaTitle: system.Model
schemaVersion: 0.0.1
train_metrics:
artifactType:
schemaTitle: system.Metrics
schemaVersion: 0.0.1
parameters:
checkpoint_sha256:
parameterType: STRING
comp-evaluate-model:
executorLabel: exec-evaluate-model
inputDefinitions:
artifacts:
prepared_dataset:
artifactType:
schemaTitle: system.Dataset
schemaVersion: 0.0.1
trained_model:
artifactType:
schemaTitle: system.Model
schemaVersion: 0.0.1
outputDefinitions:
artifacts:
eval_metrics:
artifactType:
schemaTitle: system.Metrics
schemaVersion: 0.0.1
confusion_metrics:
artifactType:
schemaTitle: system.ClassificationMetrics
schemaVersion: 0.0.1
parameters:
roc_auc:
parameterType: NUMBER_DOUBLE
f1_score:
parameterType: NUMBER_DOUBLE
comp-visualize-metrics:
executorLabel: exec-visualize-metrics
inputDefinitions:
artifacts:
train_metrics:
artifactType:
schemaTitle: system.Metrics
schemaVersion: 0.0.1
eval_metrics:
artifactType:
schemaTitle: system.Metrics
schemaVersion: 0.0.1
confusion_metrics:
artifactType:
schemaTitle: system.ClassificationMetrics
schemaVersion: 0.0.1
outputDefinitions:
artifacts:
metrics_report_html:
artifactType:
schemaTitle: system.HTML
schemaVersion: 0.0.1
summary_report_uri:
artifactType:
schemaTitle: system.Artifact
schemaVersion: 0.0.1
deploymentSpec:
executors:
exec-data-prep:
container:
image: ghcr.io/fsds-sota/kubeflow-data-prep:2026.2.0
command:
- python3
- -m
- kubeflow_distributed_lab.distributed_training_bench
args:
- --stage
- data-prep
- --dataset-uri
- "{{$.inputs.parameters['dataset_uri']}}"
- --output-uri
- "{{$.outputs.artifacts['prepared_dataset'].uri}}"
env:
- name: ARTIFACT_BUCKET_URI
value: s3://ml-artifacts-prod/kfp-runs
- name: DATA_CACHE_DIR
value: /mnt/nvme-cache/datasets
resources:
cpuRequest: 2.0
cpuLimit: 2.0
memoryRequest: 4.0
memoryLimit: 4.0
exec-distributed-train:
container:
image: ghcr.io/fsds-sota/kubeflow-pytorch-ddp:2026.2.0-cuda12.4
command:
- torchrun
- --nnodes=1
- --nproc_per_node=4
- --rdzv_id=kfp-intrusion-train
- -m
- kubeflow_distributed_lab.distributed_training_bench
args:
- --stage
- distributed-train
- --input-dataset
- "{{$.inputs.artifacts['prepared_dataset'].uri}}"
- --output-model
- "{{$.outputs.artifacts['trained_model'].uri}}"
- --output-metrics
- "{{$.outputs.artifacts['train_metrics'].uri}}"
env:
- name: NCCL_IB_DISABLE
value: "0"
- name: TORCH_NCCL_BLOCKING_WAIT
value: "1"
- name: KUEUE_QUEUE_NAME
value: ml-team-gpu-queue
resources:
cpuRequest: 16.0
cpuLimit: 16.0
memoryRequest: 64.0
memoryLimit: 64.0
accelerator:
type: NVIDIA_H100
count: "4"
exec-evaluate-model:
container:
image: ghcr.io/fsds-sota/kubeflow-eval-viz:2026.2.0
command:
- python3
- -m
- kubeflow_distributed_lab.distributed_training_bench
args:
- --stage
- evaluate-model
- --dataset-uri
- "{{$.inputs.artifacts['prepared_dataset'].uri}}"
- --model-uri
- "{{$.inputs.artifacts['trained_model'].uri}}"
- --metrics-uri
- "{{$.outputs.artifacts['eval_metrics'].uri}}"
- --confusion-uri
- "{{$.outputs.artifacts['confusion_metrics'].uri}}"
resources:
cpuRequest: 4.0
cpuLimit: 4.0
memoryRequest: 8.0
memoryLimit: 8.0
exec-visualize-metrics:
container:
image: ghcr.io/fsds-sota/kubeflow-eval-viz:2026.2.0
command:
- python3
- -m
- kubeflow_distributed_lab.distributed_training_bench
args:
- --stage
- visualize-metrics
- --train-metrics-uri
- "{{$.inputs.artifacts['train_metrics'].uri}}"
- --eval-metrics-uri
- "{{$.inputs.artifacts['eval_metrics'].uri}}"
- --confusion-uri
- "{{$.inputs.artifacts['confusion_metrics'].uri}}"
- --output-html
- "{{$.outputs.artifacts['metrics_report_html'].uri}}"
resources:
cpuRequest: 2.0
cpuLimit: 2.0
memoryRequest: 4.0
memoryLimit: 4.0
root:
inputDefinitions:
parameters:
dataset_uri:
defaultValue: s3://ml-datasets-prod/intrusion-v2/packets.parquet
parameterType: STRING
num_workers:
defaultValue: 4
parameterType: NUMBER_INTEGER
epochs:
defaultValue: 12
parameterType: NUMBER_INTEGER
batch_size:
defaultValue: 64
parameterType: NUMBER_INTEGER
learning_rate:
defaultValue: 0.05
parameterType: NUMBER_DOUBLE
strategy:
defaultValue: ring_allreduce_ddp
parameterType: STRING
seed:
defaultValue: 42
parameterType: NUMBER_INTEGER
test_ratio:
defaultValue: 0.25
parameterType: NUMBER_DOUBLE
dag:
tasks:
data-prep:
cachingOptions:
enableCache: true
componentRef:
name: comp-data-prep
inputs:
parameters:
dataset_uri:
componentInputParameter: dataset_uri
seed:
componentInputParameter: seed
test_ratio:
componentInputParameter: test_ratio
taskInfo:
name: data-prep
distributed-train:
cachingOptions:
enableCache: true
componentRef:
name: comp-distributed-train
dependentTasks:
- data-prep
inputs:
artifacts:
prepared_dataset:
taskOutputArtifact:
outputArtifactKey: prepared_dataset
producerTask: data-prep
parameters:
batch_size:
componentInputParameter: batch_size
epochs:
componentInputParameter: epochs
learning_rate:
componentInputParameter: learning_rate
num_workers:
componentInputParameter: num_workers
seed:
componentInputParameter: seed
strategy:
componentInputParameter: strategy
taskInfo:
name: distributed-train
evaluate-model:
cachingOptions:
enableCache: true
componentRef:
name: comp-evaluate-model
dependentTasks:
- data-prep
- distributed-train
inputs:
artifacts:
prepared_dataset:
taskOutputArtifact:
outputArtifactKey: prepared_dataset
producerTask: data-prep
trained_model:
taskOutputArtifact:
outputArtifactKey: trained_model
producerTask: distributed-train
taskInfo:
name: evaluate-model
visualize-metrics:
cachingOptions:
enableCache: true
componentRef:
name: comp-visualize-metrics
dependentTasks:
- evaluate-model
- distributed-train
inputs:
artifacts:
confusion_metrics:
taskOutputArtifact:
outputArtifactKey: confusion_metrics
producerTask: evaluate-model
eval_metrics:
taskOutputArtifact:
outputArtifactKey: eval_metrics
producerTask: evaluate-model
train_metrics:
taskOutputArtifact:
outputArtifactKey: train_metrics
producerTask: distributed-train
taskInfo:
name: visualize-metrics
apiVersion: kubeflow.org/v1
kind: PyTorchJob
metadata:
name: intrusion-ddp-4gpu-job
namespace: ml-training
labels:
app.kubernetes.io/name: intrusion-ddp-4gpu-job
app.kubernetes.io/part-of: kubeflow-distributed-lab
kueue.x-k8s.io/queue-name: ml-team-gpu-queue
spec:
runPolicy:
suspend: true
cleanPodPolicy: Running
ttlSecondsAfterFinished: 3600
backoffLimit: 2
pytorchReplicaSpecs:
Master:
replicas: 1
restartPolicy: OnFailure
template:
metadata:
labels:
role: master
kueue.x-k8s.io/queue-name: ml-team-gpu-queue
spec:
serviceAccountName: kfp-distributed-trainer-sa
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001
seccompProfile:
type: RuntimeDefault
containers:
- name: pytorch
image: ghcr.io/fsds-sota/kubeflow-pytorch-ddp:2026.2.0-cuda12.4
imagePullPolicy: IfNotPresent
command:
- torchrun
- --nnodes=4
- --nproc_per_node=1
- --rdzv_id=intrusion-ddp-4gpu-job
- --rdzv_backend=c10d
- --rdzv_endpoint=$(MASTER_ADDR):$(MASTER_PORT)
- -m
- kubeflow_distributed_lab.distributed_training_bench
- --stage
- distributed-train
env:
- name: NCCL_IB_DISABLE
value: "0"
- name: NCCL_SOCKET_IFNAME
value: eth0
- name: TORCH_NCCL_BLOCKING_WAIT
value: "1"
- name: ARTIFACT_BUCKET_URI
value: s3://ml-artifacts-prod/ddp-runs
- name: S3_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: ml-artifacts-vault-runtime-secret
key: s3_access_key_id
- name: S3_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: ml-artifacts-vault-runtime-secret
key: s3_secret_access_key
resources:
requests:
cpu: "8"
memory: 32Gi
nvidia.com/gpu: "1"
limits:
cpu: "8"
memory: 32Gi
nvidia.com/gpu: "1"
securityContext:
runAsNonRoot: true
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
volumeMounts:
- name: dshm
mountPath: /dev/shm
- name: tmp-scratch
mountPath: /tmp
- name: nvme-data-cache
mountPath: /mnt/nvme-cache
volumes:
- name: dshm
emptyDir:
medium: Memory
sizeLimit: 8Gi
- name: tmp-scratch
emptyDir:
sizeLimit: 2Gi
- name: nvme-data-cache
emptyDir:
sizeLimit: 32Gi
Worker:
replicas: 3
restartPolicy: OnFailure
template:
metadata:
labels:
role: worker
kueue.x-k8s.io/queue-name: ml-team-gpu-queue
spec:
serviceAccountName: kfp-distributed-trainer-sa
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001
seccompProfile:
type: RuntimeDefault
containers:
- name: pytorch
image: ghcr.io/fsds-sota/kubeflow-pytorch-ddp:2026.2.0-cuda12.4
imagePullPolicy: IfNotPresent
command:
- torchrun
- --nnodes=4
- --nproc_per_node=1
- --rdzv_id=intrusion-ddp-4gpu-job
- --rdzv_backend=c10d
- --rdzv_endpoint=$(MASTER_ADDR):$(MASTER_PORT)
- -m
- kubeflow_distributed_lab.distributed_training_bench
- --stage
- distributed-train
env:
- name: NCCL_IB_DISABLE
value: "0"
- name: NCCL_SOCKET_IFNAME
value: eth0
- name: TORCH_NCCL_BLOCKING_WAIT
value: "1"
- name: ARTIFACT_BUCKET_URI
value: s3://ml-artifacts-prod/ddp-runs
- name: S3_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: ml-artifacts-vault-runtime-secret
key: s3_access_key_id
- name: S3_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: ml-artifacts-vault-runtime-secret
key: s3_secret_access_key
resources:
requests:
cpu: "8"
memory: 32Gi
nvidia.com/gpu: "1"
limits:
cpu: "8"
memory: 32Gi
nvidia.com/gpu: "1"
securityContext:
runAsNonRoot: true
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
volumeMounts:
- name: dshm
mountPath: /dev/shm
- name: tmp-scratch
mountPath: /tmp
- name: nvme-data-cache
mountPath: /mnt/nvme-cache
volumes:
- name: dshm
emptyDir:
medium: Memory
sizeLimit: 8Gi
- name: tmp-scratch
emptyDir:
sizeLimit: 2Gi
- name: nvme-data-cache
emptyDir:
sizeLimit: 32Gi
apiVersion: kueue.x-k8s.io/v1beta1
kind: ResourceFlavor
metadata:
name: nvidia-h100-flavor
spec:
nodeLabels:
accelerator: nvidia-h100
tolerations:
- key: nvidia.com/gpu
operator: Exists
effect: NoSchedule
---
apiVersion: kueue.x-k8s.io/v1beta1
kind: ClusterQueue
metadata:
name: ml-cluster-gpu-queue
annotations:
kueue.x-k8s.io/wait-for-pods-ready-timeout: "300s"
spec:
namespaceSelector: {}
cohort: ml-engineering-cohort
queueingStrategy: BestEffortFIFO
preemption:
reclaimWithinCohort: Any
withinClusterQueue: LowerPriority
# Note: waitForPodsReady (e.g., timeout: 5m, recoveryTimeout: 1m) is configured globally
# on Kueue controller Configuration (config.kueue.x-k8s.io/v1beta1), NOT on ClusterQueue.spec.
resourceGroups:
- coveredResources:
- cpu
- memory
- nvidia.com/gpu
flavors:
- name: nvidia-h100-flavor
resources:
- name: cpu
nominalQuota: "64"
borrowingLimit: "16"
- name: memory
nominalQuota: 256Gi
borrowingLimit: 64Gi
- name: nvidia.com/gpu
nominalQuota: "8"
borrowingLimit: "0"
---
apiVersion: kueue.x-k8s.io/v1beta1
kind: LocalQueue
metadata:
name: ml-team-gpu-queue
namespace: ml-training
spec:
clusterQueue: ml-cluster-gpu-queue
"""Lab 14: Kubeflow Pipelines v2, PyTorch DDP vs Parameter Server, FSDP2/ZeRO-3 & Kueue Gang."""
from kubeflow_distributed_lab.distributed_training_bench import (
IntrusionBlockNet,
benchmark_ps_vs_ring_scaling,
evaluate_zero_fsdp2_and_pipeline_parallelism,
run_gradient_parity_experiment,
)
from kubeflow_distributed_lab.kfp_pipeline_and_kueue import (
BoundedInMemorySpanExporter,
audit_kfp_and_kueue_manifests,
create_in_memory_telemetry,
run_kfp_pipeline_experiment,
simulate_gang_scheduling_vs_fifo,
summarize_finished_spans,
)
__all__ = [
"BoundedInMemorySpanExporter",
"IntrusionBlockNet",
"audit_kfp_and_kueue_manifests",
"benchmark_ps_vs_ring_scaling",
"create_in_memory_telemetry",
"evaluate_zero_fsdp2_and_pipeline_parallelism",
"run_gradient_parity_experiment",
"run_kfp_pipeline_experiment",
"simulate_gang_scheduling_vs_fifo",
"summarize_finished_spans",
]
"""Distributed ML Training Benchmarks: Parity (Single vs PS vs Ring DDP), Scaling & FSDP2/1F1B."""
from __future__ import annotations
import argparse
import copy
import datetime
import json
import math
import tempfile
from pathlib import Path
from typing import Any, cast
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel as DDP
class IntrusionBlockNet(nn.Module):
"""Residual Transformer-MLP block used to verify exact distributed gradient parity."""
def __init__(self, in_dim: int = 16, hidden_dim: int = 32, num_classes: int = 2) -> None:
super().__init__()
self.proj_in = nn.Linear(in_dim, hidden_dim)
self.norm1 = nn.LayerNorm(hidden_dim)
self.ffn1 = nn.Linear(hidden_dim, hidden_dim * 2)
self.act = nn.GELU()
self.ffn2 = nn.Linear(hidden_dim * 2, hidden_dim)
self.head = nn.Linear(hidden_dim, num_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor:
h = self.act(self.proj_in(x))
h = h + self.ffn2(self.act(self.ffn1(self.norm1(h))))
return cast(torch.Tensor, self.head(h))
def _ring_allreduce_mean_buckets(
worker_grads: list[list[torch.Tensor]],
bucket_size_elems: int = 1024,
) -> tuple[list[list[torch.Tensor]], dict[str, int]]:
"""Execute deterministic Reduce-Scatter + All-Gather Ring All-Reduce over gradient buckets."""
num_workers = len(worker_grads)
num_params = len(worker_grads[0])
# Pack parameters in reverse order (matching PyTorch DDP backward bucket registration)
rev_indices = list(range(num_params - 1, -1, -1))
buckets: list[list[int]] = []
cur_bucket: list[int] = []
cur_elems = 0
for pid in rev_indices:
pelems = worker_grads[0][pid].numel()
if cur_bucket and cur_elems + pelems > bucket_size_elems:
buckets.append(cur_bucket)
cur_bucket = []
cur_elems = 0
cur_bucket.append(pid)
cur_elems += pelems
if cur_bucket:
buckets.append(cur_bucket)
out_grads: list[list[torch.Tensor]] = [
[torch.empty_like(g) for g in worker_grads[r]] for r in range(num_workers)
]
ring_hops = 0
total_elems_transferred_per_rank = 0
for b_pids in buckets:
flat_len = sum(worker_grads[0][pid].numel() for pid in b_pids)
chunk_len = math.ceil(flat_len / num_workers)
padded_len = chunk_len * num_workers
# Each worker owns a padded flat buffer in float64 to preserve exact arithmetic associativity
ring_bufs: list[torch.Tensor] = []
for r in range(num_workers):
buf = torch.zeros(padded_len, dtype=torch.float64)
offset = 0
for pid in b_pids:
t = worker_grads[r][pid].detach().reshape(-1).to(torch.float64)
buf[offset : offset + t.numel()] = t
offset += t.numel()
ring_bufs.append(buf)
# Phase 1: Reduce-Scatter (W - 1 ring steps)
for step in range(num_workers - 1):
send_slices: list[torch.Tensor] = []
for r in range(num_workers):
c_idx = (r - step) % num_workers
s0 = c_idx * chunk_len
send_slices.append(ring_bufs[r][s0 : s0 + chunk_len].clone())
for r in range(num_workers):
src = (r - 1) % num_workers
c_idx = (src - step) % num_workers
s0 = c_idx * chunk_len
ring_bufs[r][s0 : s0 + chunk_len] += send_slices[src]
ring_hops += 1
total_elems_transferred_per_rank += chunk_len
# Phase 2: All-Gather (W - 1 ring steps)
for step in range(num_workers - 1):
send_slices = []
for r in range(num_workers):
c_idx = (r + 1 - step) % num_workers
s0 = c_idx * chunk_len
send_slices.append(ring_bufs[r][s0 : s0 + chunk_len].clone())
for r in range(num_workers):
src = (r - 1) % num_workers
c_idx = (src + 1 - step) % num_workers
s0 = c_idx * chunk_len
ring_bufs[r][s0 : s0 + chunk_len] = send_slices[src]
ring_hops += 1
total_elems_transferred_per_rank += chunk_len
# Scale by 1 / W and scatter back to each worker's parameter gradients
for r in range(num_workers):
avg_buf = ring_bufs[r] / float(num_workers)
offset = 0
for pid in b_pids:
shape = worker_grads[r][pid].shape
numel = worker_grads[r][pid].numel()
out_grads[r][pid] = avg_buf[offset : offset + numel].reshape(shape).to(torch.float32)
offset += numel
return out_grads, {
"bucket_count": len(buckets),
"ring_steps_total": ring_hops,
"elems_transferred_per_rank": total_elems_transferred_per_rank,
}
def _max_abs_state_diff(
state_a: dict[str, torch.Tensor],
state_b: dict[str, torch.Tensor],
) -> float:
max_diff = 0.0
for key, tensor_a in state_a.items():
diff = float((tensor_a.detach() - state_b[key].detach()).abs().max().item())
if diff > max_diff:
max_diff = diff
return max_diff
def run_gradient_parity_experiment(
*,
seed: int = 42,
num_workers: int = 4,
steps: int = 12,
batch_size: int = 64,
learning_rate: float = 0.05,
bucket_size_elems: int = 1024,
) -> dict[str, Any]:
"""Verify numerical parity across Single-Worker, Sync Parameter Server & Ring All-Reduce DDP."""
if batch_size % num_workers != 0:
raise ValueError("batch_size must be evenly divisible by num_workers for exact shard parity")
gen = torch.Generator().manual_seed(seed)
n_samples = steps * batch_size
in_dim = 16
x_all = torch.randn((n_samples, in_dim), generator=gen, dtype=torch.float32)
true_w = torch.randn((in_dim,), generator=gen, dtype=torch.float32)
logits_true = x_all @ true_w + 0.5 * torch.tanh(x_all[:, 0] * x_all[:, 1])
y_all = (logits_true > 0.0).to(torch.long)
torch.manual_seed(seed)
base_model = IntrusionBlockNet(in_dim=in_dim, hidden_dim=32, num_classes=2)
init_state = copy.deepcopy(base_model.state_dict())
criterion = nn.CrossEntropyLoss()
# 1. Single-Worker Baseline (full global batch B)
single_model = IntrusionBlockNet(in_dim=in_dim, hidden_dim=32, num_classes=2)
single_model.load_state_dict(copy.deepcopy(init_state))
single_opt = torch.optim.SGD(single_model.parameters(), lr=learning_rate, momentum=0.9)
single_losses: list[float] = []
# 2. Synchronous Parameter Server (W workers push grads, PS averages & steps)
ps_model = IntrusionBlockNet(in_dim=in_dim, hidden_dim=32, num_classes=2)
ps_model.load_state_dict(copy.deepcopy(init_state))
ps_opt = torch.optim.SGD(ps_model.parameters(), lr=learning_rate, momentum=0.9)
ps_worker_models = [
IntrusionBlockNet(in_dim=in_dim, hidden_dim=32, num_classes=2) for _ in range(num_workers)
]
ps_losses: list[float] = []
# 3. Ring All-Reduce DDP (W independent workers + gradient bucketing Ring All-Reduce)
ddp_models = [
IntrusionBlockNet(in_dim=in_dim, hidden_dim=32, num_classes=2) for _ in range(num_workers)
]
for m in ddp_models:
m.load_state_dict(copy.deepcopy(init_state))
ddp_opts = [torch.optim.SGD(m.parameters(), lr=learning_rate, momentum=0.9) for m in ddp_models]
ddp_losses: list[float] = []
local_bs = batch_size // num_workers
last_ring_stats: dict[str, int] = {"bucket_count": 0, "ring_steps_total": 0}
for step in range(steps):
s0 = step * batch_size
xb = x_all[s0 : s0 + batch_size]
yb = y_all[s0 : s0 + batch_size]
# Single-Worker step
single_opt.zero_grad()
loss_s = criterion(single_model(xb), yb)
loss_s.backward()
single_opt.step()
single_losses.append(float(loss_s.item()))
# Sync Parameter Server step
ps_snapshot = copy.deepcopy(ps_model.state_dict())
ps_grads_by_worker: list[list[torch.Tensor]] = []
ps_step_loss = 0.0
for r in range(num_workers):
wm = ps_worker_models[r]
wm.load_state_dict(ps_snapshot)
wm.zero_grad()
xw = xb[r * local_bs : (r + 1) * local_bs]
yw = yb[r * local_bs : (r + 1) * local_bs]
w_loss = criterion(wm(xw), yw)
w_loss.backward()
ps_step_loss += float(w_loss.item()) / float(num_workers)
ps_grads_by_worker.append(
[p.grad.detach().clone() for p in wm.parameters() if p.grad is not None]
)
ps_opt.zero_grad()
for pid, param in enumerate(ps_model.parameters()):
stacked_ps = [
ps_grads_by_worker[r][pid].to(torch.float64) for r in range(num_workers)
]
acc = torch.stack(stacked_ps, dim=0)
param.grad = acc.mean(dim=0).to(torch.float32)
ps_opt.step()
ps_losses.append(ps_step_loss)
# Ring All-Reduce DDP step
ddp_grads_by_worker: list[list[torch.Tensor]] = []
ddp_step_loss = 0.0
for r in range(num_workers):
ddp_opts[r].zero_grad()
d_loss = criterion(
ddp_models[r](xb[r * local_bs : (r + 1) * local_bs]),
yb[r * local_bs : (r + 1) * local_bs],
)
d_loss.backward()
ddp_step_loss += float(d_loss.item()) / float(num_workers)
ddp_grads_by_worker.append(
[p.grad.detach().clone() for p in ddp_models[r].parameters() if p.grad is not None]
)
synced_grads, last_ring_stats = _ring_allreduce_mean_buckets(
ddp_grads_by_worker,
bucket_size_elems=bucket_size_elems,
)
for r in range(num_workers):
for pid, param in enumerate(ddp_models[r].parameters()):
param.grad = synced_grads[r][pid]
ddp_opts[r].step()
ddp_losses.append(ddp_step_loss)
ps_vs_single = _max_abs_state_diff(ps_model.state_dict(), single_model.state_dict())
ring_vs_single = _max_abs_state_diff(ddp_models[0].state_dict(), single_model.state_dict())
ring_inter_rank = max(
_max_abs_state_diff(ddp_models[0].state_dict(), ddp_models[r].state_dict())
for r in range(1, num_workers)
)
max_loss_diff = max(abs(a - b) for a, b in zip(single_losses, ddp_losses, strict=True))
total_params = sum(p.numel() for p in single_model.parameters())
return {
"seed": seed,
"num_workers": num_workers,
"steps": steps,
"global_batch_size": batch_size,
"total_parameters": int(total_params),
"bucket_count": int(last_ring_stats["bucket_count"]),
"single_worker_loss_start": round(single_losses[0], 6),
"single_worker_loss_end": round(single_losses[-1], 6),
"ps_loss_end": round(ps_losses[-1], 6),
"ring_ddp_loss_end": round(ddp_losses[-1], 6),
"max_abs_weight_diff_ps_vs_single": ps_vs_single,
"max_abs_weight_diff_ring_vs_single": ring_vs_single,
"max_abs_weight_diff_ring_inter_rank": ring_inter_rank,
"max_abs_loss_diff": max_loss_diff,
"parity_verified": bool(
ps_vs_single < 1e-5 and ring_vs_single < 1e-5 and ring_inter_rank < 1e-6
),
}
def compute_ring_allreduce_factor(num_workers: int) -> float:
"""Return Ring All-Reduce per-rank traffic factor 2*(W-1)/W relative to model payload."""
if num_workers < 2:
return 0.0
return 2.0 * float(num_workers - 1) / float(num_workers)
def benchmark_ps_vs_ring_scaling(
*,
worker_counts: tuple[int, ...] = (2, 4, 8, 16, 32),
model_params_millions: float = 350.0,
bytes_per_param: int = 2,
link_gbps_profiles: tuple[float, ...] = (10.0, 100.0, 400.0),
compute_step_ms: float = 85.0,
hop_latency_ms: float = 0.015,
bucket_overlap_fraction: float = 0.65,
num_buckets: int = 8,
) -> dict[str, Any]:
"""Compare Parameter Server O(W*Psi) NIC saturation vs Ring All-Reduce & Tree All-Reduce."""
psi_mb = model_params_millions * float(bytes_per_param) # 1e6 params * B bytes = MB (decimal)
profiles: list[dict[str, Any]] = []
for link_gbps in link_gbps_profiles:
link_mb_per_ms = (link_gbps * 1000.0) / 8.0 / 1000.0 # Gbps -> MB/ms
rows: list[dict[str, Any]] = []
for w in worker_counts:
# Parameter Server: master NIC receives W*Psi and sends W*Psi -> 2*W*Psi total bottleneck
ps_master_mb = 2.0 * float(w) * psi_mb
ps_comm_ms = (ps_master_mb / link_mb_per_ms) + 2.0 * hop_latency_ms
ps_step_ms = compute_step_ms + ps_comm_ms
ps_scaling_eff_pct = 100.0 * compute_step_ms / ps_step_ms
ps_speedup = float(w) * compute_step_ms / ps_step_ms
# Ring All-Reduce: 2*(W-1)/W * Psi per rank (< 2*Psi), overlapped across DDP buckets
ring_factor = compute_ring_allreduce_factor(w)
ring_rank_mb = ring_factor * psi_mb
ring_bw_ms = ring_rank_mb / link_mb_per_ms
ring_lat_ms = 2.0 * float(w - 1) * hop_latency_ms
ring_raw_comm_ms = ring_bw_ms + ring_lat_ms
ring_exposed_comm_ms = max(
ring_raw_comm_ms / float(num_buckets),
ring_raw_comm_ms - bucket_overlap_fraction * compute_step_ms,
)
ring_step_ms = compute_step_ms + ring_exposed_comm_ms
ring_scaling_eff_pct = 100.0 * compute_step_ms / ring_step_ms
ring_speedup = float(w) * compute_step_ms / ring_step_ms
# Double-Binary Tree All-Reduce: O(log2 W) latency hops
tree_hops = 2.0 * math.ceil(math.log2(max(2, w)))
tree_lat_ms = tree_hops * hop_latency_ms
rows.append(
{
"workers": w,
"ps_master_traffic_mb": round(ps_master_mb, 2),
"ring_per_rank_traffic_mb": round(ring_rank_mb, 2),
"ring_traffic_factor": round(ring_factor, 4),
"ps_comm_ms": round(ps_comm_ms, 2),
"ring_raw_comm_ms": round(ring_raw_comm_ms, 2),
"ring_exposed_comm_ms": round(ring_exposed_comm_ms, 2),
"ps_step_ms": round(ps_step_ms, 2),
"ring_step_ms": round(ring_step_ms, 2),
"ps_scaling_efficiency_pct": round(ps_scaling_eff_pct, 2),
"ring_scaling_efficiency_pct": round(ring_scaling_eff_pct, 2),
"ps_throughput_speedup_x": round(ps_speedup, 2),
"ring_throughput_speedup_x": round(ring_speedup, 2),
"ring_vs_ps_step_speedup_x": round(ps_step_ms / ring_step_ms, 2),
"ring_hops": 2 * (w - 1),
"tree_hops": int(tree_hops),
"ring_latency_ms": round(ring_lat_ms, 3),
"tree_latency_ms": round(tree_lat_ms, 3),
}
)
profiles.append(
{
"link_gbps": link_gbps,
"network_label": (
"10 Gbps Ethernet"
if link_gbps == 10.0
else (
"100 Gbps RoCEv2"
if link_gbps == 100.0
else f"{int(link_gbps)} Gbps InfiniBand"
)
),
"rows": rows,
}
)
return {
"model_type": "analytical_cluster_bandwidth_latency_model",
"model_params_millions": model_params_millions,
"payload_mb": round(psi_mb, 2),
"compute_step_ms": compute_step_ms,
"profiles": profiles,
}
def compute_pipeline_bubble_ratios(
*,
stages: int,
microbatches: int,
interleaved_chunks: int = 2,
) -> dict[str, float]:
"""Compute GPipe, 1F1B (same bubble, O(p) activation mem), and Interleaved 1F1B bubble ratios."""
if stages < 1 or microbatches < 1 or interleaved_chunks < 1:
raise ValueError("stages, microbatches, and interleaved_chunks must be positive integers")
gpipe_bubble = float(stages - 1) / float(microbatches + stages - 1)
one_f_one_b_bubble = gpipe_bubble
interleaved_bubble = float(stages - 1) / float(interleaved_chunks * microbatches + stages - 1)
activation_mem_saving_x = float(microbatches) / float(min(microbatches, stages))
return {
"gpipe_bubble_ratio": round(gpipe_bubble, 6),
"one_f_one_b_bubble_ratio": round(one_f_one_b_bubble, 6),
"interleaved_1f1b_bubble_ratio": round(interleaved_bubble, 6),
"gpipe_activation_slots": float(microbatches),
"one_f_one_b_activation_slots": float(min(microbatches, stages)),
"activation_memory_saving_x": round(activation_mem_saving_x, 2),
}
def evaluate_zero_fsdp2_and_pipeline_parallelism(
*,
num_workers: int = 8,
llm_params_billions: float = 7.0,
pipeline_stages: int = 4,
microbatch_grid: tuple[int, ...] = (4, 8, 16, 32),
) -> dict[str, Any]:
"""Partition real PyTorch tensors across ZeRO-1/2/FSDP2 ranks and evaluate 1F1B bubble ratios."""
# Real PyTorch module sharding verification (per-parameter DTensor-style partitioning)
torch.manual_seed(42)
real_model = nn.Sequential(
nn.Linear(128, 256),
nn.GELU(),
nn.Linear(256, 256),
nn.LayerNorm(256),
nn.Linear(256, 128),
nn.GELU(),
nn.Linear(128, 16),
)
params = list(real_model.parameters())
total_elems = sum(p.numel() for p in params)
# Measured byte footprint per rank in mixed-precision AdamW:
# fp16 weight (2B) + fp16 grad (2B) + fp32 master (4B) + fp32 m (4B) + fp32 v (4B) = 16B/param
shard_elem_counts_by_rank = [0 for _ in range(num_workers)]
largest_layer_elems = max(p.numel() for p in params)
for p in params:
chunks = torch.tensor_split(p.detach().reshape(-1), num_workers)
for r, chunk in enumerate(chunks):
shard_elem_counts_by_rank[r] += int(chunk.numel())
assert sum(shard_elem_counts_by_rank) == total_elems
max_rank_elems = max(shard_elem_counts_by_rank)
# Measured real-tensor bytes per rank across stages
measured_baseline_bytes = total_elems * 16
measured_zero1_bytes = total_elems * 4 + max_rank_elems * 12
measured_zero2_bytes = total_elems * 2 + max_rank_elems * 14
measured_fsdp2_static_bytes = max_rank_elems * 16
# FSDP2 unshards 1 layer at a time (+ prefetch buffer = 2x largest layer fp16 weights)
measured_fsdp2_peak_bytes = measured_fsdp2_static_bytes + largest_layer_elems * 2 * 2
# Analytical 7B LLM scaling (1B params -> 16 GB baseline)
baseline_gb = 16.0 * llm_params_billions
zero_profiles = [
{
"strategy": "ddp_baseline",
"label": "DDP Baseline (16 Psi)",
"bytes_per_param_effective": 16.0,
"llm_static_gb_per_gpu": round(baseline_gb, 2),
"memory_reduction_x": 1.0,
"comm_volume_psi": round(compute_ring_allreduce_factor(num_workers), 2),
"measured_rank_bytes": measured_baseline_bytes,
"total_sharded_elems_conserved": total_elems,
},
{
"strategy": "zero_1_os",
"label": "ZeRO-1 (Optimizer Sharded)",
"bytes_per_param_effective": round(4.0 + 12.0 / num_workers, 2),
"llm_static_gb_per_gpu": round((4.0 + 12.0 / num_workers) * llm_params_billions, 2),
"memory_reduction_x": round(16.0 / (4.0 + 12.0 / num_workers), 2),
"comm_volume_psi": round(compute_ring_allreduce_factor(num_workers), 2),
"measured_rank_bytes": measured_zero1_bytes,
"total_sharded_elems_conserved": total_elems,
},
{
"strategy": "zero_2_os_grad",
"label": "ZeRO-2 (Opt + Grad Sharded)",
"bytes_per_param_effective": round(2.0 + 14.0 / num_workers, 2),
"llm_static_gb_per_gpu": round((2.0 + 14.0 / num_workers) * llm_params_billions, 2),
"memory_reduction_x": round(16.0 / (2.0 + 14.0 / num_workers), 2),
"comm_volume_psi": round(compute_ring_allreduce_factor(num_workers), 2),
"measured_rank_bytes": measured_zero2_bytes,
"total_sharded_elems_conserved": total_elems,
},
{
"strategy": "fsdp2_zero3_dtensor",
"label": "PyTorch FSDP2 / ZeRO-3 (DTensor)",
"bytes_per_param_effective": round(16.0 / num_workers, 2),
"llm_static_gb_per_gpu": round((16.0 / num_workers) * llm_params_billions, 2),
"memory_reduction_x": round(float(num_workers), 2),
"comm_volume_psi": round(1.5 * compute_ring_allreduce_factor(num_workers), 2),
"measured_rank_bytes": measured_fsdp2_static_bytes,
"measured_peak_with_prefetch_bytes": measured_fsdp2_peak_bytes,
"measured_peak_reduction_x": round(measured_baseline_bytes / measured_fsdp2_peak_bytes, 2),
"total_sharded_elems_conserved": total_elems,
},
]
pipeline_sweeps: list[dict[str, Any]] = []
for m in microbatch_grid:
stats = compute_pipeline_bubble_ratios(
stages=pipeline_stages,
microbatches=m,
interleaved_chunks=2,
)
pipeline_sweeps.append(
{
"pipeline_stages": pipeline_stages,
"microbatches": m,
"interleaved_chunks": 2,
**stats,
}
)
return {
"num_workers": num_workers,
"llm_params_billions": llm_params_billions,
"real_module_total_elems": total_elems,
"shard_elem_counts_by_rank": shard_elem_counts_by_rank,
"zero_fsdp2_profiles": zero_profiles,
"pipeline_stages": pipeline_stages,
"pipeline_sweeps": pipeline_sweeps,
}
def _gloo_ddp_worker(
rank: int,
world_size: int,
store_path: str,
tmp_dir: str,
seed: int,
steps: int,
global_batch_size: int,
) -> None:
dist_mod: Any = dist
store = dist_mod.FileStore(store_path, world_size)
dist.init_process_group(
backend="gloo",
store=store,
rank=rank,
world_size=world_size,
timeout=datetime.timedelta(seconds=30),
)
try:
torch.manual_seed(seed)
x_all = torch.randn(steps * global_batch_size, 16)
y_all = (x_all[:, 0] + 0.5 * x_all[:, 1] > 0.0).to(torch.long)
torch.manual_seed(seed + 100)
base_model = IntrusionBlockNet(in_dim=16, hidden_dim=32, num_classes=2)
ddp_model = DDP(base_model)
criterion = nn.CrossEntropyLoss()
opt = torch.optim.SGD(ddp_model.parameters(), lr=0.05, momentum=0.9)
local_bs = global_batch_size // world_size
losses: list[float] = []
for s in range(steps):
xb = x_all[s * global_batch_size : (s + 1) * global_batch_size]
yb = y_all[s * global_batch_size : (s + 1) * global_batch_size]
xw = xb[rank * local_bs : (rank + 1) * local_bs]
yw = yb[rank * local_bs : (rank + 1) * local_bs]
opt.zero_grad()
loss = criterion(ddp_model(xw), yw)
loss.backward()
opt.step()
losses.append(float(loss.item()))
state_lists = {
k: v.detach().cpu().tolist() for k, v in base_model.state_dict().items()
}
out_path = Path(tmp_dir) / f"rank_{rank}.json"
out_path.write_text(
json.dumps(
{
"rank": rank,
"state_lists": state_lists,
"loss_end": round(losses[-1], 6),
}
),
encoding="utf-8",
)
finally:
dist.destroy_process_group()
def run_real_torch_distributed_gloo_parity(
*,
seed: int = 42,
world_size: int = 2,
steps: int = 4,
global_batch_size: int = 32,
) -> dict[str, Any]:
"""Spawn real OS worker processes running PyTorch DDP over the `gloo` CPU backend."""
rank_states: dict[int, dict[str, Any]] = {}
rank_losses: dict[int, float] = {}
mp_mod: Any = mp
with tempfile.TemporaryDirectory() as tmp_dir:
store_path = str(Path(tmp_dir) / "gloo_rendezvous_store")
mp_mod.spawn(
_gloo_ddp_worker,
args=(world_size, store_path, tmp_dir, seed, steps, global_batch_size),
nprocs=world_size,
join=True,
)
for r in range(world_size):
payload = json.loads(
(Path(tmp_dir) / f"rank_{r}.json").read_text(encoding="utf-8")
)
rank_id = int(payload["rank"])
rank_states[rank_id] = {
k: torch.tensor(v, dtype=torch.float32)
for k, v in payload["state_lists"].items()
}
rank_losses[rank_id] = float(payload["loss_end"])
inter_rank_diff = max(
_max_abs_state_diff(rank_states[0], rank_states[r]) for r in range(1, world_size)
)
# Compare against SingleWorker reference trained on identical global batches
torch.manual_seed(seed)
x_all = torch.randn(steps * global_batch_size, 16)
y_all = (x_all[:, 0] + 0.5 * x_all[:, 1] > 0.0).to(torch.long)
torch.manual_seed(seed + 100)
ref_model = IntrusionBlockNet(in_dim=16, hidden_dim=32, num_classes=2)
criterion = nn.CrossEntropyLoss()
ref_opt = torch.optim.SGD(ref_model.parameters(), lr=0.05, momentum=0.9)
for s in range(steps):
xb = x_all[s * global_batch_size : (s + 1) * global_batch_size]
yb = y_all[s * global_batch_size : (s + 1) * global_batch_size]
ref_opt.zero_grad()
loss = criterion(ref_model(xb), yb)
loss.backward()
ref_opt.step()
vs_single_diff = _max_abs_state_diff(rank_states[0], ref_model.state_dict())
return {
"execution_mode": "real_multiprocess_torch_distributed",
"backend": "gloo",
"world_size": world_size,
"steps": steps,
"inter_rank_weight_diff": inter_rank_diff,
"vs_single_max_diff": vs_single_diff,
"gloo_rank0_loss_end": rank_losses[0],
"parity_verified": bool(inter_rank_diff < 1e-6 and vs_single_diff < 1e-5),
}
def main(argv: list[str] | None = None) -> int:
"""CLI entrypoint referenced by PyTorchJob & KFP v2 executor YAML manifests."""
parser = argparse.ArgumentParser(
description="Kubeflow Distributed Training Bench & Stage Runner"
)
parser.add_argument(
"--stage",
default="parity",
choices=[
"parity",
"gloo",
"scaling",
"fsdp2",
"data-prep",
"distributed-train",
"evaluate-model",
"visualize-metrics",
],
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--epochs", type=int, default=12)
parser.add_argument("--num-workers", type=int, default=4)
parser.add_argument("--rdzv-id", "--rdzv_id", dest="rdzv_id", default="local-ddp-run")
args, _unknown = parser.parse_known_args(argv)
if args.stage in ("parity", "distributed-train"):
payload: dict[str, Any] = {
"stage": args.stage,
"rdzv_id": args.rdzv_id,
**run_gradient_parity_experiment(seed=args.seed, num_workers=args.num_workers),
}
elif args.stage == "gloo":
payload = run_real_torch_distributed_gloo_parity(seed=args.seed)
elif args.stage == "scaling":
payload = benchmark_ps_vs_ring_scaling()
elif args.stage == "fsdp2":
payload = evaluate_zero_fsdp2_and_pipeline_parallelism()
else:
payload = {
"stage": args.stage,
"seed": args.seed,
"epochs": args.epochs,
"status": "READY",
}
print(json.dumps(payload))
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""KFP v2 4-Stage Pipeline Executor, YAML/CRD Auditor, Kueue Gang Scheduler & Bounded OTel."""
from __future__ import annotations
import re
import threading
from collections import deque
from collections.abc import Sequence
from pathlib import Path
from typing import Any
import yaml
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult
from pydantic import BaseModel, ConfigDict, Field
class BoundedInMemorySpanExporter(SpanExporter):
"""Thread-safe bounded FIFO OpenTelemetry span exporter backed by deque(maxlen=256)."""
def __init__(self, maxlen: int = 256) -> None:
self._spans: deque[ReadableSpan] = deque(maxlen=maxlen)
self._lock = threading.Lock()
self._stopped = False
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
if self._stopped:
return SpanExportResult.FAILURE
with self._lock:
self._spans.extend(spans)
return SpanExportResult.SUCCESS
def shutdown(self) -> None:
self._stopped = True
def force_flush(self, timeout_millis: int = 30000) -> bool:
return True
def get_finished_spans(self) -> tuple[ReadableSpan, ...]:
with self._lock:
return tuple(self._spans)
def clear(self) -> None:
with self._lock:
self._spans.clear()
def create_in_memory_telemetry(
service_name: str = "fsds-lab14-kubeflow-distributed-training",
) -> tuple[TracerProvider, BoundedInMemorySpanExporter, trace.Tracer]:
"""Create an OpenTelemetry TracerProvider backed by BoundedInMemorySpanExporter."""
exporter = BoundedInMemorySpanExporter(maxlen=256)
provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer("kubeflow_distributed_lab")
return provider, exporter, tracer
def summarize_finished_spans(exporter: BoundedInMemorySpanExporter) -> dict[str, Any]:
"""Serialize captured OpenTelemetry spans into JSON-safe artifact records."""
spans = exporter.get_finished_spans()
return {
"span_count": len(spans),
"span_names": [span.name for span in spans],
"spans": [
{
"name": span.name,
"status": span.status.status_code.name,
"attributes": dict(span.attributes or {}),
}
for span in spans
],
}
_SECRET_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
("aws_access_key", re.compile(r"AKIA[0-9A-Z]{16}")),
("vault_token", re.compile(r"hvs\.[A-Za-z0-9_-]{8,}")),
("private_key_pem", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")),
(
"plaintext_secret_kv",
re.compile(
r"(?im)^\s*(?:password|secret_key|aws_secret_access_key|api_key|token)\s*:\s*['\"]?"
r"(?!\$\{)(?!\{\{)[A-Za-z0-9_@#$%^&*+=!-]{6,}['\"]?\s*$"
),
),
)
def scan_manifest_secret_hygiene(lab_root: Path) -> dict[str, Any]:
"""Scan all YAML manifests and pipeline specs for hardcoded credentials or tokens."""
targets = sorted(
[
*(lab_root / "pipelines").glob("*.yaml"),
*(lab_root / "pipelines").glob("*.py"),
*(lab_root / "manifests").glob("*.yaml"),
]
)
findings: list[dict[str, str]] = []
for path in targets:
text = path.read_text(encoding="utf-8")
for label, pattern in _SECRET_PATTERNS:
if pattern.search(text):
findings.append({"file": str(path.relative_to(lab_root)), "rule": label})
return {
"passed": len(findings) == 0 and len(targets) >= 4,
"scanned_files_count": len(targets),
"scanned_files": [str(p.relative_to(lab_root)).replace("\\", "/") for p in targets],
"findings": findings,
}
def _topological_sort_kfp_dag(tasks: dict[str, Any]) -> list[str]:
"""Compute topological order of KFP v2 DAG tasks using Kahn's algorithm."""
indegree: dict[str, int] = {name: 0 for name in tasks}
adj: dict[str, list[str]] = {name: [] for name in tasks}
for name, spec in tasks.items():
deps = spec.get("dependentTasks", []) or []
for dep in deps:
if dep not in tasks:
raise ValueError(f"Unknown KFP DAG dependency {dep!r} referenced by {name!r}")
adj[dep].append(name)
indegree[name] += 1
queue: deque[str] = deque(sorted(n for n, deg in indegree.items() if deg == 0))
order: list[str] = []
while queue:
node = queue.popleft()
order.append(node)
for nxt in sorted(adj[node]):
indegree[nxt] -= 1
if indegree[nxt] == 0:
queue.append(nxt)
if len(order) != len(tasks):
raise ValueError("Cycle detected in KFP v2 IR DAG tasks")
return order
def audit_kfp_and_kueue_manifests(lab_root: Path | None = None) -> dict[str, Any]:
"""Audit KFP v2 IR YAML, PyTorchJob CRD, and Kueue ClusterQueue manifests via PyYAML."""
root = lab_root or Path(__file__).resolve().parents[2]
violations: list[str] = []
hygiene = scan_manifest_secret_hygiene(root)
if not hygiene["passed"]:
violations.append(f"Secret hygiene violation: {hygiene['findings']}")
# 1. Audit KFP v2 IR YAML
ir_path = root / "pipelines" / "kfp_4stage_pipeline_ir.yaml"
ir_doc = yaml.safe_load(ir_path.read_text(encoding="utf-8"))
if ir_doc.get("schemaVersion") != "2.1.0":
violations.append("KFP IR schemaVersion must equal 2.1.0")
tasks = ir_doc.get("root", {}).get("dag", {}).get("tasks", {})
expected_tasks = {"data-prep", "distributed-train", "evaluate-model", "visualize-metrics"}
if set(tasks.keys()) != expected_tasks:
violations.append(f"Expected 4 KFP stages {expected_tasks}, got {set(tasks.keys())}")
try:
dag_order = _topological_sort_kfp_dag(tasks)
except ValueError as exc:
dag_order = []
violations.append(str(exc))
executors = ir_doc.get("deploymentSpec", {}).get("executors", {})
pinned_images: list[str] = []
for ex_name, ex_spec in executors.items():
c = ex_spec.get("container", {})
img = str(c.get("image", ""))
pinned_images.append(img)
if not img or img.endswith(":latest") or ":latest" in img:
violations.append(f"Executor {ex_name} uses forbidden :latest or empty image tag: {img!r}")
if "securityContext" in c:
violations.append(
f"Executor {ex_name} invalid K8s securityContext in KFP v2 ContainerSpec protobuf"
)
cmd_tokens = [str(x) for x in (c.get("command") or [])]
if "kubeflow_distributed_lab.distributed_training_bench" not in cmd_tokens:
violations.append(
f"Executor {ex_name} must invoke kubeflow_distributed_lab.distributed_training_bench"
)
args_str = " ".join(str(x) for x in (c.get("args") or []))
if "{{$.pipeline_job_uuid}}" in args_str:
violations.append(
f"Executor {ex_name} hardcodes pipeline_job_uuid instead of inputs/outputs artifacts URI"
)
if not any(tok in args_str for tok in ("{{$.inputs.artifacts[", "{{$.outputs.artifacts[")):
violations.append(
f"Executor {ex_name} missing KFP v2 inputs/outputs artifact URI placeholder"
)
res = c.get("resources", {})
if float(res.get("cpuLimit", 0)) <= 0 or float(res.get("memoryLimit", 0)) <= 0:
violations.append(f"Executor {ex_name} missing positive cpuLimit/memoryLimit")
epochs_default = (
ir_doc.get("root", {})
.get("inputDefinitions", {})
.get("parameters", {})
.get("epochs", {})
.get("defaultValue")
)
if epochs_default != 12:
violations.append(f"KFP IR default epochs must equal 12, got {epochs_default!r}")
# 2. Audit Kubeflow PyTorchJob CRD
pt_path = root / "manifests" / "pytorchjob_ddp.yaml"
pt_doc = yaml.safe_load(pt_path.read_text(encoding="utf-8"))
if pt_doc.get("kind") != "PyTorchJob" or pt_doc.get("apiVersion") != "kubeflow.org/v1":
violations.append("pytorchjob_ddp.yaml must define kubeflow.org/v1 PyTorchJob")
labels = pt_doc.get("metadata", {}).get("labels", {})
queue_name = labels.get("kueue.x-k8s.io/queue-name")
if not queue_name:
violations.append("PyTorchJob missing kueue.x-k8s.io/queue-name label")
if pt_doc.get("spec", {}).get("runPolicy", {}).get("suspend") is not True:
violations.append("PyTorchJob spec.runPolicy.suspend must be true for Kueue gang admission")
replica_specs = pt_doc.get("spec", {}).get("pytorchReplicaSpecs", {})
total_gpus = 0
for role in ("Master", "Worker"):
if role not in replica_specs:
violations.append(f"PyTorchJob missing {role} replicaSpec")
continue
rspec = replica_specs[role]
reps = int(rspec.get("replicas", 0))
pod_spec = rspec.get("template", {}).get("spec", {})
if pod_spec.get("securityContext", {}).get("runAsNonRoot") is not True:
violations.append(f"PyTorchJob {role} pod securityContext.runAsNonRoot must be true")
c = pod_spec.get("containers", [{}])[0]
cmd_str = " ".join(str(x) for x in (c.get("command") or []))
if "--rdzv_id" not in cmd_str and "--rdzv-id" not in cmd_str:
violations.append(f"PyTorchJob {role} torchrun command missing explicit --rdzv_id")
c_img = str(c.get("image", ""))
pinned_images.append(c_img)
if not c_img or c_img.endswith(":latest"):
violations.append(f"PyTorchJob {role} image must be pinned (no :latest): {c_img!r}")
c_sc = c.get("securityContext", {})
if c_sc.get("allowPrivilegeEscalation") is not False or c_sc.get("runAsNonRoot") is not True:
violations.append(f"PyTorchJob {role} container violates non-root/no-escalation policy")
env_names = {e.get("name") for e in c.get("env", [])}
if "NCCL_IB_DISABLE" not in env_names:
violations.append(f"PyTorchJob {role} missing NCCL_IB_DISABLE env setting")
res = c.get("resources", {})
if res.get("requests") != res.get("limits"):
violations.append(f"PyTorchJob {role} requests must equal limits for Guaranteed QoS")
gpus = int(res.get("limits", {}).get("nvidia.com/gpu", 0))
if gpus < 1:
violations.append(f"PyTorchJob {role} must request >= 1 nvidia.com/gpu")
total_gpus += reps * gpus
# 3. Audit Kueue ClusterQueue / LocalQueue / ResourceFlavor
kq_path = root / "manifests" / "kueue_clusterqueue.yaml"
kq_docs = [d for d in yaml.safe_load_all(kq_path.read_text(encoding="utf-8")) if isinstance(d, dict)]
by_kind = {d.get("kind"): d for d in kq_docs}
for req_kind in ("ResourceFlavor", "ClusterQueue", "LocalQueue"):
if req_kind not in by_kind:
violations.append(f"kueue_clusterqueue.yaml missing {req_kind}")
cq = by_kind.get("ClusterQueue", {})
lq = by_kind.get("LocalQueue", {})
if lq.get("spec", {}).get("clusterQueue") != cq.get("metadata", {}).get("name"):
violations.append("LocalQueue.spec.clusterQueue does not match ClusterQueue metadata.name")
if lq.get("metadata", {}).get("name") != queue_name:
violations.append("LocalQueue name does not match PyTorchJob kueue.x-k8s.io/queue-name label")
if "waitForPodsReady" in cq.get("spec", {}):
violations.append("ClusterQueue.spec must NOT set invalid waitForPodsReady field")
return {
"all_passed": len(violations) == 0,
"violations": violations,
"secret_hygiene": hygiene,
"kfp_ir_dag_order": dag_order,
"kfp_executor_count": len(executors),
"pytorchjob_total_gpus": total_gpus,
"kueue_resource_kinds": sorted(k for k in by_kind if k is not None),
"pinned_images_count": len(pinned_images),
}
def run_kfp_pipeline_experiment(
*,
seed: int = 42,
num_workers: int = 4,
epochs: int = 12,
lab_root: Path | None = None,
) -> dict[str, Any]:
"""Run the 4-stage KFP v2 pipeline twice (cold + cached) and return lineage + evaluation metrics."""
import importlib.util
root = lab_root or Path(__file__).resolve().parents[2]
pipe_file = root / "pipelines" / "kfp_4stage_training_pipeline.py"
spec = importlib.util.spec_from_file_location("kfp_4stage_training_pipeline", pipe_file)
if spec is None or spec.loader is None:
raise RuntimeError(f"Unable to load pipeline module from {pipe_file}")
module = importlib.util.module_from_spec(spec)
import sys
sys.modules[spec.name] = module
spec.loader.exec_module(module)
cache_store: dict[str, dict[str, Any]] = {}
run_1 = module.run_local_4stage_pipeline(
seed=seed,
num_workers=num_workers,
epochs=epochs,
cache_store=cache_store,
)
run_2 = module.run_local_4stage_pipeline(
seed=seed,
num_workers=num_workers,
epochs=epochs,
cache_store=cache_store,
)
return {
"pipeline_name": run_1.pipeline_name,
"ir_dag_tasks": list(run_1.ir_dag_tasks),
"total_stages": run_1.total_stages,
"run1_cache_hits": run_1.cache_hits,
"run2_cache_hits": run_2.cache_hits,
"roc_auc": run_1.roc_auc,
"f1_score": run_1.f1_score,
"eval_accuracy": run_1.eval_accuracy,
"train_loss_end": run_1.train_loss_end,
"throughput_samples_per_sec": run_1.throughput_samples_per_sec,
"stage_lineage": [
{
"stage_name": st.stage_name,
"cache_key": st.cache_key,
"artifact_uri": st.artifact_uri,
"run1_cache_hit": st.cache_hit,
"run2_cache_hit": run_2.stages[idx].cache_hit,
}
for idx, st in enumerate(run_1.stages)
],
"html_visualization_summary": run_1.html_visualization_summary,
}
class GangJobSpec(BaseModel):
model_config = ConfigDict(extra="forbid")
job_id: str
arrival_tick: int = Field(ge=0)
gpus_required: int = Field(ge=1)
duration_ticks: int = Field(ge=1)
def default_gang_workload() -> list[GangJobSpec]:
"""Deterministic 6-job trace where concurrent 5-GPU jobs deadlock under FIFO Pod scheduling."""
return [
GangJobSpec(job_id="ptjob-01-5gpu", arrival_tick=0, gpus_required=5, duration_ticks=4),
GangJobSpec(job_id="ptjob-02-5gpu", arrival_tick=0, gpus_required=5, duration_ticks=4),
GangJobSpec(job_id="ptjob-03-4gpu", arrival_tick=2, gpus_required=4, duration_ticks=3),
GangJobSpec(job_id="ptjob-04-4gpu", arrival_tick=2, gpus_required=4, duration_ticks=3),
GangJobSpec(job_id="ptjob-05-3gpu", arrival_tick=4, gpus_required=3, duration_ticks=3),
GangJobSpec(job_id="ptjob-06-5gpu", arrival_tick=4, gpus_required=5, duration_ticks=4),
]
def simulate_gang_scheduling_vs_fifo(
*,
cluster_gpus: int = 8,
jobs: Sequence[GangJobSpec] | None = None,
max_ticks: int = 60,
) -> dict[str, Any]:
"""Simulate naive FIFO Pod-by-Pod deadlock vs Kueue All-or-Nothing Gang Scheduling."""
workload = list(jobs) if jobs is not None else default_gang_workload()
def _run_mode(use_kueue_gang: bool) -> dict[str, Any]:
held_gpus: dict[str, int] = {j.job_id: 0 for j in workload}
remaining: dict[str, int] = {j.job_id: j.duration_ticks for j in workload}
status_map: dict[str, str] = {j.job_id: "PENDING" for j in workload}
wait_ticks: dict[str, int] = {j.job_id: 0 for j in workload}
free_gpus = cluster_gpus
useful_gpu_ticks = 0
wasted_held_gpu_ticks = 0
total_ticks_run = 0
deadlock_detected = False
for tick in range(max_ticks):
arrived = [j for j in workload if j.arrival_tick <= tick and status_map[j.job_id] != "DONE"]
if not arrived and all(status_map[j.job_id] == "DONE" for j in workload):
total_ticks_run = tick
break
if use_kueue_gang:
# Kueue ClusterQueue: admit entire PodSet atomically iff free_gpus >= gpus_required
for j in arrived:
if status_map[j.job_id] == "PENDING" and free_gpus >= j.gpus_required:
free_gpus -= j.gpus_required
held_gpus[j.job_id] = j.gpus_required
status_map[j.job_id] = "RUNNING"
else:
# Naive Pod-by-Pod kube-scheduler: round-robin / interleaved partial allocation
pending_or_partial = [
j for j in arrived if held_gpus[j.job_id] < j.gpus_required
]
while free_gpus > 0 and pending_or_partial:
progressed = False
for j in pending_or_partial:
if free_gpus == 0:
break
if held_gpus[j.job_id] < j.gpus_required:
held_gpus[j.job_id] += 1
free_gpus -= 1
progressed = True
if held_gpus[j.job_id] == j.gpus_required:
status_map[j.job_id] = "RUNNING"
if not progressed:
break
pending_or_partial = [
j for j in arrived if held_gpus[j.job_id] < j.gpus_required
]
# Step running vs partially stalled jobs
for j in arrived:
if status_map[j.job_id] == "RUNNING":
useful_gpu_ticks += j.gpus_required
remaining[j.job_id] -= 1
if remaining[j.job_id] == 0:
status_map[j.job_id] = "DONE"
free_gpus += held_gpus[j.job_id]
held_gpus[j.job_id] = 0
else:
wait_ticks[j.job_id] += 1
wasted_held_gpu_ticks += held_gpus[j.job_id]
# Detect circular partial-allocation deadlock
if (
not use_kueue_gang
and free_gpus == 0
and all(status_map[j.job_id] != "RUNNING" for j in arrived)
and any(held_gpus[j.job_id] > 0 for j in arrived)
):
deadlock_detected = True
total_ticks_run = tick + 1
completed = sum(1 for v in status_map.values() if v == "DONE")
deadlocked = sum(
1 for j in workload if status_map[j.job_id] != "DONE" and held_gpus[j.job_id] > 0
)
capacity_gpu_ticks = max(1, total_ticks_run * cluster_gpus)
goodput_pct = 100.0 * float(useful_gpu_ticks) / float(capacity_gpu_ticks)
avg_wait = sum(wait_ticks.values()) / float(max(1, len(workload)))
return {
"scheduler": "kueue_gang_wait_for_pods_ready" if use_kueue_gang else "naive_fifo_pod_by_pod",
"total_jobs": len(workload),
"completed_jobs": completed,
"deadlocked_jobs": deadlocked,
"deadlock_detected": deadlock_detected,
"makespan_ticks": total_ticks_run,
"useful_gpu_ticks": useful_gpu_ticks,
"wasted_held_gpu_ticks": wasted_held_gpu_ticks,
"gpu_goodput_pct": round(goodput_pct, 2),
"avg_queue_wait_ticks": round(avg_wait, 2),
"final_held_gpus": held_gpus,
}
fifo_res = _run_mode(use_kueue_gang=False)
kueue_res = _run_mode(use_kueue_gang=True)
return {
"cluster_gpus": cluster_gpus,
"fifo_pod_by_pod": fifo_res,
"kueue_gang": kueue_res,
}
def main() -> None:
"""CLI entrypoint verifying audit, pipeline execution, and Kueue gang scheduling."""
audit = audit_kfp_and_kueue_manifests()
pipe = run_kfp_pipeline_experiment(seed=42)
kueue = simulate_gang_scheduling_vs_fifo()
print(
f"Audit passed={audit['all_passed']} | "
f"KFP run2 cache={pipe['run2_cache_hits']}/{pipe['total_stages']} | "
f"ROC-AUC={pipe['roc_auc']} | "
f"FIFO deadlocks={kueue['fifo_pod_by_pod']['deadlocked_jobs']} vs "
f"Kueue deadlocks={kueue['kueue_gang']['deadlocked_jobs']}"
)
"""Deterministic CLI runner generating artifacts/t2_ch16_lab14_results.json."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from typing import Any
from kubeflow_distributed_lab.distributed_training_bench import (
benchmark_ps_vs_ring_scaling,
evaluate_zero_fsdp2_and_pipeline_parallelism,
run_gradient_parity_experiment,
run_real_torch_distributed_gloo_parity,
)
from kubeflow_distributed_lab.kfp_pipeline_and_kueue import (
audit_kfp_and_kueue_manifests,
create_in_memory_telemetry,
run_kfp_pipeline_experiment,
simulate_gang_scheduling_vs_fifo,
summarize_finished_spans,
)
def run_full_benchmark_suite(seed: int = 42, lab_root: Path | None = None) -> dict[str, Any]:
"""Execute all 4 Lab 14 experiments with OpenTelemetry spans and build workbench panels."""
root = lab_root or Path(__file__).resolve().parents[1]
_provider, exporter, tracer = create_in_memory_telemetry()
with tracer.start_as_current_span("lab14.benchmark.suite") as root_span:
root_span.set_attribute("lab.seed", seed)
with tracer.start_as_current_span("lab14.exp1_gradient_parity") as sp:
parity_eval = run_gradient_parity_experiment(seed=seed)
gloo_eval = run_real_torch_distributed_gloo_parity(seed=seed, world_size=2, steps=4)
parity_eval = {**parity_eval, "real_gloo_ddp": gloo_eval}
sp.set_attribute("parity.verified", parity_eval["parity_verified"])
sp.set_attribute("parity.gloo_verified", gloo_eval["parity_verified"])
sp.set_attribute(
"parity.ring_vs_single_diff",
parity_eval["max_abs_weight_diff_ring_vs_single"],
)
with tracer.start_as_current_span("lab14.exp2_ps_vs_ring_scaling") as sp:
scaling_eval = benchmark_ps_vs_ring_scaling()
eth10_w32 = scaling_eval["profiles"][0]["rows"][-1]
sp.set_attribute(
"scaling.eth10_w32_speedup_x",
eth10_w32["ring_vs_ps_step_speedup_x"],
)
with tracer.start_as_current_span("lab14.exp3_zero_fsdp2_and_1f1b") as sp:
zero_pp_eval = evaluate_zero_fsdp2_and_pipeline_parallelism()
fsdp2_prof = zero_pp_eval["zero_fsdp2_profiles"][3]
sp.set_attribute("fsdp2.static_reduction_x", fsdp2_prof["memory_reduction_x"])
sp.set_attribute(
"fsdp2.measured_peak_reduction_x",
fsdp2_prof["measured_peak_reduction_x"],
)
with tracer.start_as_current_span("lab14.exp4a_manifest_policy_audit") as sp:
manifest_audit = audit_kfp_and_kueue_manifests(lab_root=root)
sp.set_attribute("audit.all_passed", manifest_audit["all_passed"])
sp.set_attribute(
"audit.scanned_files_count",
manifest_audit["secret_hygiene"]["scanned_files_count"],
)
with tracer.start_as_current_span("lab14.exp4b_kfp_4stage_pipeline") as sp:
kfp_eval = run_kfp_pipeline_experiment(seed=seed, lab_root=root)
for st in kfp_eval["stage_lineage"]:
with tracer.start_as_current_span(
f"lab14.kfp.stage.{st['stage_name']}"
) as stage_sp:
stage_sp.set_attribute("kfp.stage", st["stage_name"])
stage_sp.set_attribute("kfp.cache_key_prefix", st["cache_key"][:12])
stage_sp.set_attribute("kfp.run2_cache_hit", st["run2_cache_hit"])
sp.set_attribute("kfp.roc_auc", kfp_eval["roc_auc"])
sp.set_attribute("kfp.run2_cache_hits", kfp_eval["run2_cache_hits"])
with tracer.start_as_current_span("lab14.exp4c_kueue_gang_scheduler") as sp:
kueue_eval = simulate_gang_scheduling_vs_fifo()
sp.set_attribute(
"kueue.fifo_deadlocks",
kueue_eval["fifo_pod_by_pod"]["deadlocked_jobs"],
)
sp.set_attribute("kueue.gang_deadlocks", kueue_eval["kueue_gang"]["deadlocked_jobs"])
sp.set_attribute("kueue.gang_goodput_pct", kueue_eval["kueue_gang"]["gpu_goodput_pct"])
otel_summary = summarize_finished_spans(exporter)
eth10_rows = scaling_eval["profiles"][0]["rows"]
ib400_rows = scaling_eval["profiles"][2]["rows"]
eth10_w32 = eth10_rows[-1]
ib400_w32 = ib400_rows[-1]
ddp_prof, z1_prof, z2_prof, fsdp2_prof = zero_pp_eval["zero_fsdp2_profiles"]
pp_m4, _pp_m8, pp_m16, pp_m32 = zero_pp_eval["pipeline_sweeps"]
fifo_res = kueue_eval["fifo_pod_by_pod"]
kueue_res = kueue_eval["kueue_gang"]
max_diff_sci = f"{parity_eval['max_abs_weight_diff_ring_vs_single']:.2e}"
gpipe_m4_pct = round(pp_m4["gpipe_bubble_ratio"] * 100.0, 2)
gpipe_m16_pct = round(pp_m16["gpipe_bubble_ratio"] * 100.0, 2)
int_m16_pct = round(pp_m16["interleaved_1f1b_bubble_ratio"] * 100.0, 2)
int_m32_pct = round(pp_m32["interleaved_1f1b_bubble_ratio"] * 100.0, 2)
scanned_cnt = manifest_audit["secret_hygiene"]["scanned_files_count"]
total_sharded = fsdp2_prof["total_sharded_elems_conserved"]
ddp_gb = ddp_prof["llm_static_gb_per_gpu"]
fsdp_gb = fsdp2_prof["llm_static_gb_per_gpu"]
workbench_panels = {
"kpis": [
{
"id": "kpi_gradient_parity",
"label": "Single vs PS vs Ring DDP Weight Parity",
"value": f"PASS (diff {max_diff_sci})",
"unit": f"(W={parity_eval['num_workers']}, {parity_eval['total_parameters']} params)",
"status": "ok",
"detail": (
"Deterministic PyTorch CPU training proves Single-Worker, Sync Parameter "
"Server, and Ring All-Reduce DDP converge identically (diff < 1e-5)."
),
},
{
"id": "kpi_ps_vs_ring_scaling",
"label": "PS vs Ring All-Reduce Step Speedup (W=32)",
"value": f"{eth10_w32['ring_vs_ps_step_speedup_x']}x faster",
"unit": f"(10G Eth; IB400G {ib400_w32['ring_scaling_efficiency_pct']}% eff)",
"status": "ok",
"detail": (
f"At W=32 on 10 Gbps Ethernet, PS master saturates at "
f"{eth10_w32['ps_step_ms']} ms vs Ring DDP {eth10_w32['ring_step_ms']} ms; "
f"400G IB holds {ib400_w32['ring_scaling_efficiency_pct']}% scaling."
),
},
{
"id": "kpi_fsdp2_memory_savings",
"label": "FSDP2 / ZeRO-3 Memory Reduction (W=8)",
"value": (
f"{fsdp2_prof['memory_reduction_x']}x static "
f"({fsdp2_prof['measured_peak_reduction_x']}x peak)"
),
"unit": f"({fsdp_gb} vs {ddp_gb} GB)",
"status": "ok",
"detail": (
f"Real PyTorch DTensor partitioning conserves {total_sharded} elems "
f"while shrinking 7B AdamW fp32 footprint from {ddp_gb} GB to {fsdp_gb} GB."
),
},
{
"id": "kpi_pipeline_1f1b_bubble",
"label": "1F1B & Interleaved Pipeline Efficiency (p=4)",
"value": f"{int_m32_pct}% bubble",
"unit": f"(m=32, {pp_m32['activation_memory_saving_x']}x act mem saved)",
"status": "ok",
"detail": (
f"1F1B caps activation VRAM to O(p) ({pp_m32['activation_memory_saving_x']}x "
f"less than GPipe at m=32) and cuts bubble from {gpipe_m4_pct}% to {int_m32_pct}%."
),
},
{
"id": "kpi_kfp_4stage_and_audit",
"label": "KFP v2 4-Stage Pipeline & YAML Audit",
"value": f"ROC-AUC {kfp_eval['roc_auc']}",
"unit": f"({kfp_eval['run2_cache_hits']}/4 warm cache hits)",
"status": "ok",
"detail": (
f"All {scanned_cnt} YAML/pipeline specs pass with 0 secrets and "
"0 :latest tags; KFP v2 rerun hits 4/4 SHA-256 cached stages."
),
},
{
"id": "kpi_kueue_gang_and_otel",
"label": "Kueue Gang Scheduling & OTel Traceability",
"value": f"{kueue_res['deadlocked_jobs']} vs {fifo_res['deadlocked_jobs']} deadlocks",
"unit": f"({kueue_res['gpu_goodput_pct']}% goodput, {otel_summary['span_count']} spans)",
"status": "ok",
"detail": (
f"Naive FIFO deadlocks {fifo_res['deadlocked_jobs']} concurrent 5-GPU jobs "
f"at {fifo_res['gpu_goodput_pct']}% goodput; Kueue finishes "
f"{kueue_res['completed_jobs']}/{kueue_res['total_jobs']} jobs with 0 deadlocks."
),
},
],
"bars": [
{
"id": "bar_ps_vs_ring_step_time_10g",
"title": "W=32 Distributed Step Time (ms) on 10 Gbps Ethernet (350M fp16)",
"metric_label": "Step Time (ms)",
"items": [
{
"label": "parameter_server_w32_10g",
"value": eth10_w32["ps_step_ms"],
"display": (
f"{eth10_w32['ps_step_ms']} ms "
f"({eth10_w32['ps_scaling_efficiency_pct']}% scaling eff)"
),
"css_class": "is-slow",
},
{
"label": "ring_allreduce_ddp_w32_10g",
"value": eth10_w32["ring_step_ms"],
"display": (
f"{eth10_w32['ring_step_ms']} ms "
f"({eth10_w32['ring_vs_ps_step_speedup_x']}x faster than PS)"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_zero_fsdp2_memory_gb",
"title": "7B Mixed-Precision AdamW Static Memory per GPU (GB, W=8 Workers)",
"metric_label": "Static Memory per GPU (GB)",
"items": [
{
"label": "ddp_baseline_16psi",
"value": ddp_gb,
"display": f"{ddp_gb} GB (1.0x, 16.0 Psi)",
"css_class": "is-slow",
},
{
"label": "zero_1_optimizer_sharded",
"value": z1_prof["llm_static_gb_per_gpu"],
"display": (
f"{z1_prof['llm_static_gb_per_gpu']} GB "
f"({z1_prof['memory_reduction_x']}x)"
),
"css_class": "is-mid",
},
{
"label": "zero_2_opt_grad_sharded",
"value": z2_prof["llm_static_gb_per_gpu"],
"display": (
f"{z2_prof['llm_static_gb_per_gpu']} GB "
f"({z2_prof['memory_reduction_x']}x)"
),
"css_class": "is-mid",
},
{
"label": "fsdp2_zero3_dtensor",
"value": fsdp_gb,
"display": f"{fsdp_gb} GB ({fsdp2_prof['memory_reduction_x']}x static)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_pipeline_bubble_pct",
"title": "Pipeline Parallelism (p=4 Stages) Idle Bubble Ratio (%)",
"metric_label": "Idle Bubble (%)",
"items": [
{
"label": "gpipe_m4",
"value": gpipe_m4_pct,
"display": f"{gpipe_m4_pct}% (m=4, O(m) act)",
"css_class": "is-slow",
},
{
"label": "gpipe_or_1f1b_m16",
"value": gpipe_m16_pct,
"display": f"{gpipe_m16_pct}% (m=16, 1F1B 4.0x act saved)",
"css_class": "is-mid",
},
{
"label": "interleaved_1f1b_m16",
"value": int_m16_pct,
"display": f"{int_m16_pct}% (v=2, m=16)",
"css_class": "is-fast",
},
{
"label": "interleaved_1f1b_m32",
"value": int_m32_pct,
"display": f"{int_m32_pct}% (v=2, m=32)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_kueue_vs_fifo_goodput",
"title": "8-GPU Multi-Job Cluster Goodput (%): Naive FIFO vs Kueue Gang",
"metric_label": "Useful GPU Goodput (%)",
"items": [
{
"label": "naive_fifo_pod_by_pod",
"value": fifo_res["gpu_goodput_pct"],
"display": (
f"{fifo_res['gpu_goodput_pct']}% "
f"({fifo_res['deadlocked_jobs']} deadlocked jobs)"
),
"css_class": "is-slow",
},
{
"label": "kueue_gang_wait_for_pods_ready",
"value": kueue_res["gpu_goodput_pct"],
"display": (
f"{kueue_res['gpu_goodput_pct']}% "
f"({kueue_res['completed_jobs']}/{kueue_res['total_jobs']} done, "
"0 deadlocks)"
),
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "table_gradient_parity_and_kfp_stages",
"title": "Gradient Parity Verification & 4-Stage KFP v2 Pipeline Lineage",
"columns": ["stage_or_trainer", "metric_or_sha", "cache_or_parity", "status"],
"rows": [
[
"SingleWorker vs SyncPS",
f"loss_end={parity_eval['ps_loss_end']}",
f"max_diff={parity_eval['max_abs_weight_diff_ps_vs_single']:.2e}",
"PASS (<1e-5)",
],
[
"SingleWorker vs RingDDP",
(
f"loss_end={parity_eval['ring_ddp_loss_end']} "
f"({parity_eval['bucket_count']} buckets)"
),
f"max_diff={parity_eval['max_abs_weight_diff_ring_vs_single']:.2e}",
"PASS (<1e-5)",
],
*[
[
f"KFP Stage: {st['stage_name']}",
f"sha256:{st['cache_key'][:12]}",
f"run1={st['run1_cache_hit']} | run2={st['run2_cache_hit']}",
"CACHED_OK",
]
for st in kfp_eval["stage_lineage"]
],
],
},
{
"id": "table_ps_vs_ring_scaling_law",
"title": "Parameter Server vs Ring All-Reduce Scaling Law (10 Gbps vs 400 Gbps)",
"columns": ["workers_and_link", "ps_master_vs_ring_mb", "step_time_ms", "scaling_eff"],
"rows": [
[
f"W={r10['workers']} (10G Eth)",
(
f"PS {r10['ps_master_traffic_mb']} vs "
f"Ring {r10['ring_per_rank_traffic_mb']} MB"
),
f"PS {r10['ps_step_ms']} vs Ring {r10['ring_step_ms']}",
(
f"PS {r10['ps_scaling_efficiency_pct']}% vs "
f"Ring {r10['ring_scaling_efficiency_pct']}%"
),
]
for r10 in eth10_rows
]
+ [
[
f"W={ib400_w32['workers']} (400G IB)",
(
f"PS {ib400_w32['ps_master_traffic_mb']} vs "
f"Ring {ib400_w32['ring_per_rank_traffic_mb']} MB"
),
f"PS {ib400_w32['ps_step_ms']} vs Ring {ib400_w32['ring_step_ms']}",
(
f"PS {ib400_w32['ps_scaling_efficiency_pct']}% vs "
f"Ring {ib400_w32['ring_scaling_efficiency_pct']}%"
),
]
],
},
{
"id": "table_zero_fsdp2_and_pipeline",
"title": "ZeRO-1/2/FSDP2 Memory Sharding (W=8) & Pipeline 1F1B Bubble Sweep",
"columns": [
"strategy_or_pp",
"memory_or_microbatch",
"savings_or_bubble",
"comm_or_act_mem",
],
"rows": [
[
p["label"],
f"{p['llm_static_gb_per_gpu']} GB/GPU (7B)",
f"{p['memory_reduction_x']}x static",
f"{p['comm_volume_psi']}x Psi comm",
]
for p in zero_pp_eval["zero_fsdp2_profiles"]
]
+ [
[
f"PP p=4, m={sw['microbatches']}",
f"GPipe {round(sw['gpipe_bubble_ratio'] * 100, 2)}%",
f"Interleaved {round(sw['interleaved_1f1b_bubble_ratio'] * 100, 2)}%",
f"1F1B act {sw['activation_memory_saving_x']}x saved",
]
for sw in zero_pp_eval["pipeline_sweeps"]
],
},
{
"id": "table_kueue_and_manifest_audit",
"title": "Kueue Gang Scheduling vs FIFO Deadlock & YAML/CRD Policy Audit",
"columns": ["target", "completed_or_files", "deadlocks_or_rules", "verdict"],
"rows": [
[
"Naive FIFO Pod-by-Pod (8 GPUs)",
f"{fifo_res['completed_jobs']}/{fifo_res['total_jobs']} jobs",
f"{fifo_res['deadlocked_jobs']} deadlocked ({fifo_res['gpu_goodput_pct']}%)",
"DEADLOCKED",
],
[
"Kueue Gang + WaitForPodsReady",
f"{kueue_res['completed_jobs']}/{kueue_res['total_jobs']} jobs",
f"{kueue_res['deadlocked_jobs']} deadlocks ({kueue_res['gpu_goodput_pct']}%)",
"PASS",
],
[
"KFP IR + PyTorchJob + Kueue YAML",
f"{scanned_cnt} files scanned",
(
f"0 secrets, 0 :latest, "
f"{manifest_audit['pytorchjob_total_gpus']} GPUs, non-root"
),
"PASS" if manifest_audit["all_passed"] else "FAIL",
],
],
},
],
}
return {
"unit_id": "T2-P3-U04",
"lab_id": "lab-14-kubeflow-4stage-distributed-training",
"seed": seed,
"experiment_1_gradient_parity": parity_eval,
"experiment_2_ps_vs_ring_scaling": scaling_eval,
"experiment_3_zero_fsdp2_and_pipeline": zero_pp_eval,
"experiment_4_manifest_audit": manifest_audit,
"experiment_4_kfp_4stage_pipeline": kfp_eval,
"experiment_4_kueue_gang_vs_fifo": kueue_eval,
"otel_telemetry": otel_summary,
"workbench_panels": workbench_panels,
}
def main() -> None:
parser = argparse.ArgumentParser(
description="Run Lab 14 Kubeflow & Distributed ML Training suite."
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument(
"--output",
type=Path,
default=Path("artifacts/t2_ch16_lab14_results.json"),
)
args = parser.parse_args()
lab_root = Path(__file__).resolve().parents[1]
out_path = args.output if args.output.is_absolute() else (lab_root / args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
results = run_full_benchmark_suite(seed=args.seed, lab_root=lab_root)
out_path.write_text(json.dumps(results, indent=2), encoding="utf-8")
print(f"Wrote deterministic Lab 14 results to {out_path}")
if __name__ == "__main__":
main()
"""Automated verification suite (24 tests, 0 skips) for Lab 14 Kubeflow & Distributed ML."""
from __future__ import annotations
import ast
import io
import json
import shutil
import subprocess
import sys
import tokenize
from pathlib import Path
import pytest
import torch
import yaml
from hypothesis import given, settings
from hypothesis import strategies as st
from pydantic import ValidationError
from kubeflow_distributed_lab.distributed_training_bench import (
_ring_allreduce_mean_buckets,
benchmark_ps_vs_ring_scaling,
compute_pipeline_bubble_ratios,
compute_ring_allreduce_factor,
evaluate_zero_fsdp2_and_pipeline_parallelism,
run_gradient_parity_experiment,
run_real_torch_distributed_gloo_parity,
)
from kubeflow_distributed_lab.kfp_pipeline_and_kueue import (
BoundedInMemorySpanExporter,
GangJobSpec,
audit_kfp_and_kueue_manifests,
create_in_memory_telemetry,
run_kfp_pipeline_experiment,
scan_manifest_secret_hygiene,
simulate_gang_scheduling_vs_fifo,
summarize_finished_spans,
)
from scripts.run_lab_demo import run_full_benchmark_suite
LAB_ROOT = Path(__file__).resolve().parents[1]
def test_01_ast_safety_no_pickle_eval_exec_or_type_ignore() -> None:
forbidden_modules = {"pickle", "cPickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
forbidden_calls = {"eval", "exec"}
py_files = [
*sorted((LAB_ROOT / "src").rglob("*.py")),
*sorted((LAB_ROOT / "scripts").rglob("*.py")),
*sorted((LAB_ROOT / "tests").rglob("*.py")),
*sorted((LAB_ROOT / "pipelines").rglob("*.py")),
]
assert len(py_files) >= 5
forbidden_comment = "type:" + " ignore"
for py_file in py_files:
source = py_file.read_text(encoding="utf-8")
with io.StringIO(source) as buf:
for tok in tokenize.generate_tokens(buf.readline):
if tok.type == tokenize.COMMENT and forbidden_comment in tok.string:
raise AssertionError(f"Forbidden type-ignore comment found in {py_file}")
tree = ast.parse(source, filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
assert alias.name.split(".")[0] not in forbidden_modules
elif isinstance(node, ast.ImportFrom) and node.module:
assert node.module.split(".")[0] not in forbidden_modules
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
assert node.func.id not in forbidden_calls
for ext in ("*.png", "*.parquet", "*.duckdb*"):
assert not list(LAB_ROOT.rglob(ext))
def test_02_manifest_audit_kfp_ir_pytorchjob_and_kueue() -> None:
audit = audit_kfp_and_kueue_manifests(LAB_ROOT)
assert audit["all_passed"] is True
assert audit["violations"] == []
assert audit["kfp_ir_dag_order"] == [
"data-prep",
"distributed-train",
"evaluate-model",
"visualize-metrics",
]
assert audit["kfp_executor_count"] == 4
assert audit["pytorchjob_total_gpus"] == 4
assert audit["pinned_images_count"] == 6
assert set(audit["kueue_resource_kinds"]) == {"ClusterQueue", "LocalQueue", "ResourceFlavor"}
def test_03_secret_hygiene_zero_plaintext_credentials() -> None:
hygiene = scan_manifest_secret_hygiene(LAB_ROOT)
assert hygiene["passed"] is True
assert hygiene["scanned_files_count"] == 4
assert hygiene["findings"] == []
def test_04_pytorchjob_crd_security_kueue_and_nccl_env() -> None:
pt_doc = yaml.safe_load(
(LAB_ROOT / "manifests" / "pytorchjob_ddp.yaml").read_text(encoding="utf-8")
)
assert pt_doc["metadata"]["labels"]["kueue.x-k8s.io/queue-name"] == "ml-team-gpu-queue"
assert pt_doc["spec"]["runPolicy"]["suspend"] is True
for role, expected_reps in (("Master", 1), ("Worker", 3)):
rspec = pt_doc["spec"]["pytorchReplicaSpecs"][role]
assert rspec["replicas"] == expected_reps
pod_spec = rspec["template"]["spec"]
assert pod_spec["securityContext"]["runAsNonRoot"] is True
c = pod_spec["containers"][0]
assert ":latest" not in c["image"]
assert c["securityContext"]["allowPrivilegeEscalation"] is False
assert "ALL" in c["securityContext"]["capabilities"]["drop"]
assert c["resources"]["requests"] == c["resources"]["limits"]
def test_05_tampered_manifests_rejected_by_policy_auditor(tmp_path: Path) -> None:
for folder in ("pipelines", "manifests"):
shutil.copytree(LAB_ROOT / folder, tmp_path / folder)
# Inject :latest tag, plaintext password, suspend=false, and KFP DAG cycle
pt_file = tmp_path / "manifests" / "pytorchjob_ddp.yaml"
pt_txt = pt_file.read_text(encoding="utf-8")
pt_txt = pt_txt.replace("suspend: true", "suspend: false").replace(
"2026.2.0-cuda12.4", "latest"
)
pt_file.write_text(pt_txt + "\npassword: supersecret123\n", encoding="utf-8")
ir_file = tmp_path / "pipelines" / "kfp_4stage_pipeline_ir.yaml"
ir_doc = yaml.safe_load(ir_file.read_text(encoding="utf-8"))
ir_doc["root"]["dag"]["tasks"]["data-prep"]["dependentTasks"] = ["visualize-metrics"]
ir_file.write_text(yaml.safe_dump(ir_doc), encoding="utf-8")
tampered = audit_kfp_and_kueue_manifests(tmp_path)
assert tampered["all_passed"] is False
joined = " | ".join(tampered["violations"])
assert "Secret hygiene" in joined
assert "Cycle detected" in joined
assert "suspend must be true" in joined
assert ":latest" in joined
def test_06_gradient_parity_single_vs_ps_vs_ring_allreduce() -> None:
res = run_gradient_parity_experiment(seed=42, num_workers=4, steps=12, batch_size=64)
assert res["parity_verified"] is True
assert res["max_abs_weight_diff_ps_vs_single"] < 1e-5
assert res["max_abs_weight_diff_ring_vs_single"] < 1e-5
assert res["max_abs_weight_diff_ring_inter_rank"] < 1e-6
assert res["max_abs_loss_diff"] < 1e-5
assert res["single_worker_loss_end"] < res["single_worker_loss_start"]
assert res["bucket_count"] >= 2
def test_07_ring_allreduce_bucket_kernel_matches_exact_mean() -> None:
torch.manual_seed(99)
workers = 5
worker_grads = [
[torch.randn(17, 13), torch.randn(31), torch.randn(9, 7)] for _ in range(workers)
]
synced, stats = _ring_allreduce_mean_buckets(worker_grads, bucket_size_elems=100)
assert stats["ring_steps_total"] == stats["bucket_count"] * 2 * (workers - 1)
for pid in range(3):
expected = torch.stack([worker_grads[r][pid] for r in range(workers)], dim=0).mean(dim=0)
for r in range(workers):
assert float((synced[r][pid] - expected).abs().max().item()) < 1e-6
def test_08_ps_saturation_vs_ring_allreduce_scaling_monotonicity() -> None:
scaling = benchmark_ps_vs_ring_scaling()
eth10_rows = scaling["profiles"][0]["rows"]
ib400_rows = scaling["profiles"][2]["rows"]
payload = scaling["payload_mb"]
# PS master traffic grows linearly O(W), Ring per-rank traffic stays < 2*Psi
ps_traffic = [r["ps_master_traffic_mb"] for r in eth10_rows]
ring_traffic = [r["ring_per_rank_traffic_mb"] for r in eth10_rows]
assert ps_traffic == sorted(ps_traffic)
assert ps_traffic[-1] > 10.0 * ps_traffic[0]
assert all(rt < 2.0 * payload for rt in ring_traffic)
# Ring outperforms PS at W=32 across all networks, and 400G IB > 85% scaling efficiency
assert eth10_rows[-1]["ring_vs_ps_step_speedup_x"] > 20.0
assert ib400_rows[-1]["ring_scaling_efficiency_pct"] > 90.0
# Tree hops strictly smaller than Ring hops for W >= 8
for r in eth10_rows:
if r["workers"] >= 8:
assert r["tree_hops"] < r["ring_hops"]
@settings(max_examples=40, deadline=None)
@given(w=st.integers(min_value=2, max_value=1024))
def test_09_hypothesis_ring_allreduce_factor_strictly_bounded(w: int) -> None:
factor = compute_ring_allreduce_factor(w)
assert 1.0 <= factor < 2.0
assert compute_ring_allreduce_factor(w + 1) > factor
def test_10_zero_fsdp2_real_tensor_sharding_conservation_and_savings() -> None:
res = evaluate_zero_fsdp2_and_pipeline_parallelism(num_workers=8, llm_params_billions=7.0)
total_elems = res["real_module_total_elems"]
assert sum(res["shard_elem_counts_by_rank"]) == total_elems
profs = {p["strategy"]: p for p in res["zero_fsdp2_profiles"]}
assert profs["ddp_baseline"]["llm_static_gb_per_gpu"] == 112.0
assert profs["zero_1_os"]["llm_static_gb_per_gpu"] == 38.5
assert profs["zero_2_os_grad"]["llm_static_gb_per_gpu"] == 26.25
assert profs["fsdp2_zero3_dtensor"]["llm_static_gb_per_gpu"] == 14.0
assert profs["fsdp2_zero3_dtensor"]["memory_reduction_x"] == 8.0
assert profs["fsdp2_zero3_dtensor"]["measured_peak_reduction_x"] >= 4.0
def test_11_pipeline_1f1b_bubble_and_activation_memory_sweep() -> None:
res = evaluate_zero_fsdp2_and_pipeline_parallelism(pipeline_stages=4, microbatch_grid=(4, 8, 16, 32))
sweeps = res["pipeline_sweeps"]
gpipe_bubbles = [s["gpipe_bubble_ratio"] for s in sweeps]
interleaved_bubbles = [s["interleaved_1f1b_bubble_ratio"] for s in sweeps]
assert gpipe_bubbles == sorted(gpipe_bubbles, reverse=True)
assert interleaved_bubbles == sorted(interleaved_bubbles, reverse=True)
for sw in sweeps:
assert sw["interleaved_1f1b_bubble_ratio"] < sw["gpipe_bubble_ratio"]
assert sweeps[-1]["activation_memory_saving_x"] == 8.0
@settings(max_examples=50, deadline=None)
@given(
stages=st.integers(min_value=2, max_value=16),
microbatches=st.integers(min_value=1, max_value=128),
chunks=st.integers(min_value=2, max_value=6),
)
def test_12_hypothesis_pipeline_bubble_invariants(
stages: int,
microbatches: int,
chunks: int,
) -> None:
cur = compute_pipeline_bubble_ratios(
stages=stages,
microbatches=microbatches,
interleaved_chunks=chunks,
)
nxt = compute_pipeline_bubble_ratios(
stages=stages,
microbatches=microbatches + 1,
interleaved_chunks=chunks,
)
assert 0.0 < cur["interleaved_1f1b_bubble_ratio"] < cur["gpipe_bubble_ratio"] < 1.0
assert nxt["gpipe_bubble_ratio"] < cur["gpipe_bubble_ratio"]
assert nxt["interleaved_1f1b_bubble_ratio"] < cur["interleaved_1f1b_bubble_ratio"]
def test_13_kfp_4stage_pipeline_execution_cache_hit_and_lineage() -> None:
kfp = run_kfp_pipeline_experiment(seed=42, num_workers=4, epochs=12, lab_root=LAB_ROOT)
assert kfp["total_stages"] == 4
assert kfp["run1_cache_hits"] == 0
assert kfp["run2_cache_hits"] == 4
assert kfp["roc_auc"] > 0.95
assert kfp["f1_score"] > 0.90
assert kfp["eval_accuracy"] > 0.90
assert "Confusion Matrix:" in kfp["html_visualization_summary"]
assert len({st["cache_key"] for st in kfp["stage_lineage"]}) == 4
def test_14_kfp_pipeline_script_runs_standalone() -> None:
proc = subprocess.run(
[sys.executable, str(LAB_ROOT / "pipelines" / "kfp_4stage_training_pipeline.py")],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=True,
)
payload = json.loads(proc.stdout)
assert payload["run1_cache_hits"] == 0
assert payload["run2_cache_hits"] == 4
assert payload["roc_auc"] > 0.95
def test_15_kueue_gang_scheduling_eliminates_fifo_deadlock() -> None:
res = simulate_gang_scheduling_vs_fifo(cluster_gpus=8)
fifo = res["fifo_pod_by_pod"]
kueue = res["kueue_gang"]
assert fifo["deadlock_detected"] is True
assert fifo["deadlocked_jobs"] >= 2
assert fifo["completed_jobs"] == 0
assert fifo["gpu_goodput_pct"] == 0.0
assert kueue["deadlock_detected"] is False
assert kueue["deadlocked_jobs"] == 0
assert kueue["completed_jobs"] == kueue["total_jobs"] == 6
assert kueue["gpu_goodput_pct"] >= 70.0
def test_16_kueue_gang_job_spec_pydantic_extra_forbid() -> None:
valid = GangJobSpec(job_id="pt-1", arrival_tick=0, gpus_required=4, duration_ticks=3)
assert valid.gpus_required == 4
with pytest.raises(ValidationError):
GangJobSpec.model_validate(
{
"job_id": "pt-bad",
"arrival_tick": 0,
"gpus_required": 4,
"duration_ticks": 3,
"unknown_field": True,
}
)
def test_17_kueue_single_job_fits_without_deadlock_even_in_fifo() -> None:
jobs = [GangJobSpec(job_id="solo", arrival_tick=0, gpus_required=4, duration_ticks=2)]
res = simulate_gang_scheduling_vs_fifo(cluster_gpus=8, jobs=jobs, max_ticks=10)
assert res["fifo_pod_by_pod"]["completed_jobs"] == 1
assert res["kueue_gang"]["completed_jobs"] == 1
assert res["kueue_gang"]["deadlocked_jobs"] == 0
def test_18_bounded_otel_exporter_enforces_maxlen() -> None:
_prov, exporter, tracer = create_in_memory_telemetry()
assert isinstance(exporter, BoundedInMemorySpanExporter)
for i in range(300):
with tracer.start_as_current_span("lab14.stress_span") as sp:
sp.set_attribute("idx", i)
summary = summarize_finished_spans(exporter)
assert summary["span_count"] == 256
def test_19_full_suite_otel_spans_and_zero_secrets() -> None:
suite = run_full_benchmark_suite(seed=42, lab_root=LAB_ROOT)
otel = suite["otel_telemetry"]
assert otel["span_count"] >= 6
assert otel["span_count"] == 11
for stage in ("data-prep", "distributed-train", "evaluate-model", "visualize-metrics"):
assert f"lab14.kfp.stage.{stage}" in otel["span_names"]
serialized = json.dumps(otel)
for bad in ("AKIA", "hvs.", "supersecret", "PRIVATE KEY"):
assert bad not in serialized
def test_20_workbench_panels_exact_counts_and_determinism() -> None:
run_a = run_full_benchmark_suite(seed=42, lab_root=LAB_ROOT)
run_b = run_full_benchmark_suite(seed=42, lab_root=LAB_ROOT)
assert run_a == run_b
panels = run_a["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
def test_21_saved_artifact_matches_suite_output() -> None:
artifact_path = LAB_ROOT / "artifacts" / "t2_ch16_lab14_results.json"
assert artifact_path.is_file()
saved = json.loads(artifact_path.read_text(encoding="utf-8"))
fresh = run_full_benchmark_suite(seed=42, lab_root=LAB_ROOT)
assert saved == fresh
def test_22_zero_nonzero_parity_tolerance_with_custom_batch() -> None:
res = run_gradient_parity_experiment(seed=7, num_workers=2, steps=6, batch_size=32)
assert res["parity_verified"] is True
assert res["max_abs_weight_diff_ring_vs_single"] < 1e-5
def test_23_h7_kfp_ir_kueue_clusterqueue_and_pytorchjob_rdzv_cli(tmp_path: Path) -> None:
ir_doc = yaml.safe_load(
(LAB_ROOT / "pipelines" / "kfp_4stage_pipeline_ir.yaml").read_text(encoding="utf-8")
)
assert ir_doc["root"]["inputDefinitions"]["parameters"]["epochs"]["defaultValue"] == 12
for ex_spec in ir_doc["deploymentSpec"]["executors"].values():
c = ex_spec["container"]
assert "securityContext" not in c
assert "kubeflow_distributed_lab.distributed_training_bench" in c["command"]
assert "{{$.pipeline_job_uuid}}" not in " ".join(c["args"])
cq_docs = list(
yaml.safe_load_all(
(LAB_ROOT / "manifests" / "kueue_clusterqueue.yaml").read_text(encoding="utf-8")
)
)
cq = next(d for d in cq_docs if d.get("kind") == "ClusterQueue")
assert "waitForPodsReady" not in cq["spec"]
# Tamper copy: re-introducing securityContext in KFP ContainerSpec or waitForPodsReady
# in ClusterQueue must fail
for folder in ("pipelines", "manifests"):
shutil.copytree(LAB_ROOT / folder, tmp_path / folder)
bad_ir_path = tmp_path / "pipelines" / "kfp_4stage_pipeline_ir.yaml"
bad_ir = yaml.safe_load(bad_ir_path.read_text(encoding="utf-8"))
bad_ir["deploymentSpec"]["executors"]["exec-data-prep"]["container"]["securityContext"] = {
"runAsNonRoot": True
}
bad_ir_path.write_text(yaml.safe_dump(bad_ir), encoding="utf-8")
bad_cq_path = tmp_path / "manifests" / "kueue_clusterqueue.yaml"
bad_cq_docs = list(yaml.safe_load_all(bad_cq_path.read_text(encoding="utf-8")))
bad_cq_docs[1]["spec"]["waitForPodsReady"] = {"timeout": "5m"}
bad_cq_path.write_text(yaml.safe_dump_all(bad_cq_docs), encoding="utf-8")
res_bad = audit_kfp_and_kueue_manifests(tmp_path)
assert res_bad["all_passed"] is False
joined = " | ".join(res_bad["violations"])
assert "ContainerSpec protobuf" in joined
assert "waitForPodsReady" in joined
# Verify distributed_training_bench real __main__ CLI entrypoint runs cleanly
proc = subprocess.run(
[
sys.executable,
"-m",
"kubeflow_distributed_lab.distributed_training_bench",
"--stage",
"parity",
"--rdzv-id",
"intrusion-ddp-4gpu-job",
],
cwd=str(LAB_ROOT),
env={**dict(__import__("os").environ), "PYTHONPATH": str(LAB_ROOT / "src")},
capture_output=True,
text=True,
check=True,
)
out = json.loads(proc.stdout)
assert out["rdzv_id"] == "intrusion-ddp-4gpu-job"
assert out["parity_verified"] is True
def test_24_real_multiprocess_torch_distributed_gloo_ddp_and_model_type() -> None:
gloo_res = run_real_torch_distributed_gloo_parity(seed=42, world_size=2, steps=4)
assert gloo_res["execution_mode"] == "real_multiprocess_torch_distributed"
assert gloo_res["backend"] == "gloo"
assert gloo_res["world_size"] == 2
assert gloo_res["inter_rank_weight_diff"] < 1e-6
assert gloo_res["vs_single_max_diff"] < 1e-5
assert gloo_res["parity_verified"] is True
scaling = benchmark_ps_vs_ring_scaling()
assert scaling["model_type"] == "analytical_cluster_bandwidth_latency_model"
Kubeflow chuẩn sản xuất của Lab 14 (Tests 02, 13), điểm nâng cấp cốt lõi của KFP v2 IR YAML, PyTorchJob và Kubeflow Trainer v2 (TrainJob) là gì?Tests 02, 13: KFP v2 tách biệt đặc tả IR YAML (schemaVersion: 2.1.0) với các kiểu tạo tác chuẩn (Dataset, Model, Metrics, HTML), theo dõi dòng dõi MLMD và SHA-256 DAG caching (0/4 -> 4/4 hits); Kubeflow Trainer v2 tách ClusterTrainingRuntime của Platform Ops khỏi TrainJob kèm PodGroup gang scheduling và TorchElastic.
Lab 14 (Tests 06–07, 22) so sánh SingleWorkerBaseline, SyncParameterServerTrainer, RingAllReduceDDPTrainer và chạy đa tiến trình torch.distributed (gloo), cơ chế nào bảo đảm độ lệch trọng số chỉ 2.98e-08 (và 1.49e-08 đa tiến trình)?Tests 06–07, 22: đồng bộ trung bình 1/W sum(g_w) bằng SyncPS hoặc 2 pha Reduce-Scatter + All-Gather của Ring All-Reduce (5 buckets) cho cùng quỹ đạo SGD với chạy đơn máy (max_diff = 2.98e-08), và được kiểm chứng thêm bằng torch.distributed đa tiến trình thật (backend="gloo", dist.FileStore, world_size=2, vs_single_max_diff = 1.49e-08, inter-rank 0.0).
350M fp16 (700.0 MB) lên W = 32 worker trên mạng 10 Gbps Ethernet (Tests 08–09), vì sao Parameter Server sụp xuống 0.24% hiệu suất còn Ring All-Reduce nhanh hơn 32.2x (cùng Tree & RoCEv2 ECN/DCQCN)?Tests 08–09: PS đẩy 2*W*Psi = 44,800 MB qua 1 Master NIC (35,925.03 ms, 0.24% eff), còn Ring All-Reduce giữ mỗi rank ở 2(W-1)/W * Psi = 1,356.25 MB (1,115.68 ms, nhanh hơn 32.2x trên 10G và 96.04% eff trên 400G IB). Khi W lớn, NCCL dùng Double-Binary Tree giảm từ 62 xuống 10 hops; trên Ethernet không tổn thất dùng RoCEv2 ECN + DCQCN để tránh deadlock/head-of-line blocking từ PFC.
7B huấn luyện hỗn hợp AdamW fp32 (112.0 GB baseline 16*Psi) chia qua W = 8 GPU (Test 10), ZeRO-1, ZeRO-2, PyTorch FSDP2 (DTensor) và DCP tối ưu VRAM và checkpointing như thế nào?Test 10: ZeRO-1 chia optimizer (38.5 GB), ZeRO-2 chia thêm gradient (26.25 GB), và FSDP2 / ZeRO-3 chia cả 3 (14.0 GB/GPU, 8.0x tĩnh). Khác FSDP1 FlatParameter gây record_stream, FSDP2 dùng fully_shard với DTensor dim-0 theo từng tham số (4.05x đỉnh đo được có prefetch) và dùng DCP (Distributed Checkpoint) lưu song song không gom RAM lên rank 0.
Tests 11–12), đặc điểm cốt lõi nào phân biệt 1F1B / Interleaved 1F1B với GPipe (p = 4, m = 32) và cách ánh xạ TP, CP, EP lên phần cứng?Tests 11–12: 1F1B chạy Backward sớm giúp giữ chỉ O(p) kích hoạt (tiết kiệm 8.0x VRAM ở m=32, p=4), và Interleaved 1F1B (v=2) hạ bong bóng xuống (p-1)/(2m+p-1) = 4.48% (so với 8.57% của GPipe tại m=32, hay 42.86% tại m=4). TP cần băng thông cao NVLink, CP dùng Ring Attention, còn EP dùng All-to-All.
GPU Util < 20% do đọc hàng triệu tệp mẫu nhỏ từ kho mạng từ xa, kiến trúc lưu trữ, GPUDirect Storage (GDS) và nạp dữ liệu chuẩn SOTA giải quyết thế nào?100–500 MB WebDataset/Parquet), đọc qua Lustre hoặc GCS Fuse/S3 có đệm NVMe, kết hợp NVIDIA GPUDirect Storage (GDS) chuyển dữ liệu RDMA/DMA trực tiếp từ NVMe/Lustre vào GPU VRAM (tránh CPU bounce buffer), cùng DistributedSampler, num_workers > 0, pin_memory=True và prefetch_factor >= 2.
8 GPU nhận 6 PyTorchJob (mở đầu bởi hai job 5-GPU đến đồng thời tại t = 0) trong Lab 14 (Test 15), kết quả giữa FIFO từng Pod với Kueue (cấu hình controller waitForPodsReady + Kueue TAS) khác nhau ra sao?Test 15: FIFO xen kẽ cấp 4 GPU cho Job 1 và 4 GPU cho Job 2 khiến cả hai thiếu 1 GPU mở NCCL Rendezvous (2 deadlocks, 0.0% goodput). Kueue giữ job mới ở suspend: true, đọc waitForPodsReady ở cấu hình controller toàn cục (tuyệt đối KHÔNG đặt vào ClusterQueue.spec), kết hợp Kueue TAS (Topology-Aware Scheduling) gom gang trong cùng miền NVLink/NVL72/leaf, hoàn tất 6/6 job (0 deadlock, 77.5% goodput).
Lab 14 (Tests 01–05, 13, 19, 23), chốt bảo vệ nào đảm bảo tính tái lập đường ống và phát hiện sai lược đồ KFP/Kueue trước khi nộp lên Kubernetes?Tests 01–05, 13, 19, 23: trình kiểm toán PyYAML phát hiện :latest, bí mật tĩnh, suspend: false, chu trình DAG (Test 05) cũng như lược đồ sai (ContainerSpec.securityContext trong KFP v2 và waitForPodsReady trong ClusterQueue.spec, Test 23); đường ống đạt 4/4 cache hits (ROC-AUC = 0.9916), 0 pickle, 0 # type: ignore và xuất 11 span OpenTelemetry sạch.
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 Tương đương Gradient Single vs PS vs Ring All-Reduce và Multi-Process Gloo 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Theo dõi _ring_allreduce_mean_buckets (Reduce-Scatter + All-Gather) và thí nghiệm đa tiến trình thật torch.distributed (backend="gloo", dist.FileStore, world_size=2) trong distributed_training_bench.py.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_06 or test_07 or test_22" -v và kiểm tra experiment_1_gradient_parity cùng real_torch_distributed_gloo trong artifacts/t2_ch16_lab14_results.json.
Tiêu chí Đáp án & Số đối chứng
Cả SyncParameterServerTrainer lẫn RingAllReduceDDPTrainer (5 buckets) đạt sai lệch cực đại 2.98e-08 < 1e-5, và bài chạy đa tiến trình torch.distributed thật (backend="gloo", world_size=2) đạt vs_single_max_diff = 1.49e-08 (inter-rank 0.0), loss giảm đồng nhất 0.772477 -> 0.460285.
Bài tập 2 — Định luật Mở rộng Parameter Server vs Ring/Tree All-Reduce và RoCEv2 ECN/DCQCN 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
So sánh cổ chai Master PS 2 * W * Psi với lưu lượng Ring 2 * ((W - 1) / W) * Psi < 2 * Psi, hiệu ứng bucket overlap 65%, độ trễ nhảy Tree 2 * ceil(log2(W)) và vai trò RoCEv2 ECN + DCQCN tránh nghẽn PFC.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_08 or test_09" -v và đối chiếu bảng table_ps_vs_ring_scaling_law trong artifacts/t2_ch16_lab14_results.json.
Tiêu chí Đáp án & Số đối chứng
Tại W = 32 trên 10 Gbps Ethernet (350M fp16 = 700.0 MB), PS dồn 44,800.0 MB lên Master NIC (35,925.03 ms, 0.24% eff), trong khi Ring chỉ truyền 1,356.25 MB/rank (1,115.68 ms, nhanh hơn 32.2x) và đạt 96.04% eff trên 400 Gbps IB; Tree giảm từ 62 xuống 10 hops, còn RoCEv2 ECN + DCQCN ngăn chặn head-of-line blocking do PFC.
Bài tập 3 — Phân mảnh Bộ nhớ ZeRO-1/2/FSDP2 DTensor, DCP và Bong bóng Pipeline 1F1B 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân rã 16 * Psi byte hỗn hợp AdamW qua W = 8 rank; so sánh FSDP2 (fully_shard DTensor dim-0 tránh FlatParameter/record_stream) + DCP với FSDP1, và công thức (p - 1)/(v*m + p - 1).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_10 or test_11 or test_12" -v và kiểm tra experiment_3_zero_fsdp2_and_pipeline.
Tiêu chí Đáp án & Số đối chứng
Phân mảnh thực tế bảo toàn 134,288 phần tử qua 8 rank (16,786/rank). Trên LLM 7B, FSDP2 / ZeRO-3 (DTensor dim-0) giảm VRAM tĩnh từ 112.0 GB xuống 14.0 GB/GPU (8.0x tĩnh, 4.05x đỉnh đo được có prefetch) kèm lưu DCP không gom rank 0. Tại p = 4, m = 32, 1F1B tiết kiệm 8.0x bộ nhớ kích hoạt và Interleaved 1F1B giảm bong bóng còn 4.48%.
Bài tập 4 — Đường ống Kubeflow Pipelines v2 Bốn Giai đoạn và SHA-256 Caching 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Khảo sát đồ thị phụ thuộc data-prep -> distributed-train -> evaluate-model -> visualize-metrics trong kfp_4stage_pipeline_ir.yaml (không đặt securityContext trong ContainerSpec) và cơ chế SHA-256 cache trong kfp_4stage_training_pipeline.py.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy python pipelines/kfp_4stage_training_pipeline.py và pytest -k "test_13 or test_14" -v.
Tiêu chí Đáp án & Số đối chứng
Đường ống chuẩn hóa tập dữ liệu không rò rỉ train/eval, huấn luyện DDP đạt ROC-AUC = 0.9916, F1 = 0.9496, Accuracy = 0.9453, sinh báo cáo HTML/Confusion Matrix, và đạt 0/4 cache hits ở lần chạy 1 sang 4/4 cache hits ở lần chạy 2.
Bài tập 5 — Lập lịch Bầy đàn Kueue (Controller waitForPodsReady + TAS), GPUDirect Storage và WebDataset 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân tích vì sao hai job 5-GPU trên cụm 8 GPU bị khóa 4 + 4 dưới FIFO, cách suspend: true + ClusterQueue + cài đặt waitForPodsReady ở controller toàn cục (KHÔNG nằm trong ClusterQueue.spec) + Kueue TAS ngăn deadlock, và vai trò GPUDirect Storage (GDS).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_15 or test_16 or test_17 or test_23" -v và kiểm tra mục experiment_4_kueue_gang_vs_fifo.
Tiêu chí Đáp án & Số đối chứng
FIFO từng Pod khóa cứng 2 job 5-GPU (0/6, 0.0% goodput), còn Kueue (waitForPodsReady ở controller toàn cục + TAS) hoàn tất 6/6 job trong 15 tick với 0 deadlock và 77.5% goodput; kết hợp shard tuần tự + NVMe cache + GPUDirect Storage DMA thẳng vào VRAM tránh bỏ đói GPU.
Bài tập 6 — Kiểm toán Bảo mật Lược đồ KFP/Kueue và Quan sát Bounded OpenTelemetry 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Xem cách audit_kfp_and_kueue_manifests kiểm tra chu trình Kahn, ghim tag image, runAsNonRoot, suspend: true, và cách Tests 05, 23 bắt lỗi ContainerSpec.securityContext lẫn ClusterQueue.spec.waitForPodsReady.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy trọn bộ run_lab_demo.py, ruff check src scripts tests pipelines, mypy src tests, pytest -p no:cacheprovider -v, và uv lock --check.
Tiêu chí Đáp án & Số đối chứng
Kiểm toán quét sạch 4/4 tệp khai báo (0 secrets, 0 :latest, 6 image ghim phiên bản), từ chối chính xác mọi hành vi giả mạo & sai lược đồ (Tests 05, 23), thu 11 OTel spans sạch bí mật trong BoundedInMemorySpanExporter, 0 # type: ignore, 24/24 pytest pass và uv lock --check hợp lệ.