Context: ML workloads are heavy, stateful (model parameters), and sensitive to interruptions (checkpoints).
Abstraction: The scheduling layer sits between the ML framework (PyTorch/TensorFlow) and the hardware (CUDA/ROCm) or acts as a cluster manager (like Kubernetes). Given "scheduling layer," it could be a userspace daemon or a kernel-level driver extension, but a userspace "orchestrator" managing distinct processes/containers is the most practical enterprise scenario. Let's assume a distributed cluster manager + a node-level agent.
2. Core Components
The Queue Manager: Holds pending jobs.
The Resource Tracker: Knows what GPUs are free/busy.
The Policy Engine: Decides who runs (Quotas/Priorities).
The Execution Agent: Handles preemption and life-cycle.
3. Addressing Quotas
What are they? GPU hours, memory fractions, or specific device IDs.
Mechanism:
Hard limits:cgroups (for generic GPU memory limits via drivers like NVIDIA) or virtualization (MIG).
Fair Share: Weighted fair queuing over time. If User A has 50% quota and User B has 50%, they should get equal GPU time over a week.
Implementation: Token buckets or accumulated "debt" tracking.
4. Addressing Priorities
Levels: High (Interactive/Production), Medium (Training), Low (Batch/Inference).
Starvation: Need an "aging" mechanism where low-priority jobs eventually get resources.
5. Addressing Preemption (The Hard Part)
Why is it hard in ML? You can't just context switch a GPU register state easily like a CPU. You have GBs of VRAM. Moving data to CPU RAM is slow (PCIe bottleneck).
Granularities:
Coarse-grained: Kill the job and restart from checkpoint. (Simple, but wastes progress).
Medium-grained: Pause the job, swap VRAM to Host RAM (Unified Memory or explicit swapping).
Fine-grained: Instruction-level preemption (Pascal architecture+ supports some of this, but hard to control from software layer). Actually, for a "design" prompt, we should stick to application-level preemption.
The "Graceful" approach: The scheduler sends a signal (SIGTERM or custom gRPC) to the training script. The script saves a checkpoint and exits. This is the most robust ML approach.
The "Forced" approach: If the job doesn't yield, kill the container (SIGKILL).
Space-sharing vs. Time-sharing: MIG (Multi-Instance GPU) allows space sharing. MPS (Multi-Process Service) allows spatial sharing but weak isolation.
Design Choice: Use "Save-checkpoint-and-exit" as the primary preemption strategy, supported by robust checkpointing libraries. For inference, just drain connections.
6. Structuring the Design
Architecture Diagram (Mental): Client -> API Server -> Scheduler -> Node Agents -> GPU.
Quotas: Usage should be tracked per user/group. Consumed = Duration * GPU_Count.
Priorities: A simple integer or tier system.
Preemption Strategies:
Checkpoint-based: Best for training. The scheduler asks the job to checkpoint and terminate.
Swap-based: (Advanced) Using libraries like vCUDA or rCUDA (virtualization layers) to intercept CUDA calls and swap memory. This is high overhead. Let's stick to the Checkpoint/Restore approach as the "standard" design, mentioning Swapping as an optimization.
MIG: Mention this for A100/H100 as a way to avoid preemption entirely by slicing hardware.
8. Drafting the Content
Introduction: Define the problem.
System Architecture: Control Plane (Centralized) vs Data Plane (Node-level).
Quota Management: Fair share, max limits.
Priority Logic: Queuing, aging.
Preemption Strategy: The 3 modes (Kill, Checkpoint, Swap).
API/Interface: How users interact.
Self-Correction during drafting:
Initial thought: Design a kernel driver. Correction: Too hard, not portable. Design a userspace orchestrator (like a custom Kubernetes operator or a Slurm-like system).
Focus on Preemption: Simply killing a training job after 3 days of work is bad. I must emphasize opportunistic preemption or auto-checkpointing. The scheduler needs to integrate with the ML framework (e.g., sending a signal to PyTorch to trigger torch.save).
Final Polish:
Use standard terminology (SLA, QoS, Gang Scheduling).
Add a section on "Gang Scheduling" because distributed training requires all GPUs at once or none.
Let's write this out.
Title: Design Doc: ML GPU Orchestrator
Section 1: Architecture: Global Scheduler vs Local Agent.
Section 5: Preemption (Crucial): The "Graceful Checkpoint" workflow.
Section 6: Tech Stack: K8s, CUDA, MPI.
(Self-Correction on Preemption): Is there a way to do transparent preemption? Yes, with "GPU Virtualization" middleware that intercepts CUDA calls. It creates a virtual address space. When preempted, it unmaps the physical GPU memory but keeps the virtual context alive on the CPU. This is complex but worth mentioning as the "Advanced" tier.
Let's stick to a practical, robust design: A centralized controller managing distributed agents, utilizing Kubernetes concepts (Pods, Resources), but adding custom logic for the specific "Preemption" and "Quota" interactions.
Key Design Trade-off:Latency vs. Overhead.
Swapping memory allows fast resume but high pause time. Checkpointing allows slow resume but frees up resources immediately.
Revised Preemption Logic:
Signal: SIGTERM (or gRPC Preempt).
Action (Application): ML Framework catches signal, saves weights, exits.
Action (Scheduler): Marks node as free, puts job back in queue with "restart" metadata.
Let's assemble.
Designing a GPU scheduling layer for Machine Learning (ML) workloads requires a shift from traditional CPU scheduling logic. ML workloads are typically throughput-oriented, stateful (holding massive VRAM state), and sensitive to interruption (killing a training job after 3 weeks wastes significant work).
Here is a design proposal for a comprehensive GPU scheduling layer.
1. High-Level Architecture
We will design a Global Scheduler (Control Plane) and a Node-Level Agent (Data Plane).
The Global Scheduler: Manages the logical queue, enforces quotas, and decides which job runs where.
The Node Agent: Runs on every physical GPU node. It handles the mechanics of starting, pausing, and checkpointing containers.
The Interceptor Layer (Optional): A library (like libcuda.so hook) that traps GPU calls to enforce fine-grained time-slicing or memory limits at the hardware level.
Quotas in ML are not just about "time"; they are about GPU Memory and Compute Availability.
A. The Quota Model
We implement a Hierarchical Token Bucket.
Organization / Team: Hard limit (e.g., Team A gets 100 GPU-hours/month).
Project / User: Soft limits within the team.
Resource Types:
Dedicated: Whole GPU (A100).
Shared: Fractional GPU (0.5 GPU).
B. Elastic Resource Allocation (Borrowing)
ML jobs often have a "goodput" range. A training job might run on 4 GPUs or 64 GPUs, just with different batch sizes.
Guaranteed Quota: The minimum resources a user has paid for/reserved.
Burst Quota: If the cluster is idle, a user can "borrow" unused capacity.
Mechanism: If User A is using 10% of their quota, User B can burst into the remaining 90%. However, these "Burst" pods are marked with a lower QoS class (BestEffort).
3. Priorities: Multi-Dimensional Ranking
We cannot rely solely on user-provided priorities (everyone sets their job to "High"). We need a dynamic score.
Priority Score Formula
Priority=(UserPri
User Priority:0-100 (Standard).
Urgency: Calculated based on deadlines (e.g., "Must finish before ACL conference submission").
Age: Standard fair-share logic. Jobs waiting longer get a boost.
Quota Deficit (The Anti-Affinity):
If User A has used 1000 hours and User B has used 0, User B gets a massive priority boost ("Guilt" scheduling). This ensures quota enforcement without hard walls, promoting fair-share usage.
4. Preemption: The Core Challenge
Preemption in ML is dangerous. Moving 80GB of VRAM to RAM and back is slow (PCIe bottleneck). We have three levels of preemption, chosen based on urgency.
Level 1: Checkpoint & Evict (Graceful)
Used when: High-priority job arrives, but cluster isn't critical.
Signal: Scheduler sends SIGTERM or a custom gRPC signal to the Node Agent.
Trap: The ML Framework (PyTorch/TensorFlow) has a registered signal handler.
Action: The job dumps model weights and optimizer state to disk (S3/GlusterFS).
Resume: The job is re-queued. When it restarts, it loads the checkpoint.
Design Requirement: Every ML job must support this via a standardized save_state(location) interface.
Level 2: Swap to Host Memory (Suspend)
Used when: The preemption is temporary (e.g., a 5-minute high-priority inference burst).
Mechanism: Utilize Unified Memory (CUDA Managed Memory) or a custom memory manager.
Action: Unmap GPU memory pages to Host RAM. The GPU context remains open but idle.
Cost: High latency to resume (seconds to minutes depending on model size).
Level 3: Hard Kill (Default)
Used when: The job is misbehaving, stuck, or the system is under extreme pressure.
Action:SIGKILL.
Consequence: All progress since last checkpoint is lost.
5. Detailed Scheduling Algorithm
The scheduler runs a loop every X seconds (e.g., 5s).
Step 1: Bin Packing vs. Load Spreading
Inference workloads: Pack tightly using MIG (Multi-Instance GPU) or MPS (Multi-Process Service). Put 7 small models on one A100.
Training workloads: Spread across nodes to avoid bandwidth contention (NCCL).
Step 2: Fragmentation Resolution
If a large job (requires 8 GPUs) is pending but the cluster has 40 free GPUs scattered across 20 nodes:
Identify "Low Priority" jobs occupying specific nodes needed to complete the "Chunk".
Preempt those specific jobs using Level 1 Preemption to defragment the cluster.
Step 3: Gang Scheduling
For distributed training, "All or Nothing" is required.
If a job requires 8 GPUs, acquire 8 "slots" simultaneously.
If one node fails/drains, the entire job enters the "Preemption/Restart" phase to maintain synchronization.
6. Implementation Stack
If building this today, do not start from scratch. Stack recommendation: