Develop a resilient distributed scheduler for GPUs and TPUs across regions: placement heuristics, failure domains, utilization reporting, and fairness controls.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The user wants a resilient distributed scheduler for GPUs and TPUs across multiple regions.
Key requirements:
Resilience: Handle failures gracefully.
Distributed: Work across regions (latency, topology awareness).
Hardware support: GPUs (usually NVIDIA) and TPUs (Google).
Placement heuristics: How to decide where a job runs (bin packing, spread, topology).
Failure domains: Avoid single points of failure.
Utilization reporting: Metrics, monitoring.
Fairness controls: Quotas, sharing, preemption.
System Architecture:
Global State Store: Needs to be strongly consistent or use a leasing mechanism (etcd, Zookeeper, or a custom Raft implementation). Let's assume a Control Plane + Data Plane architecture.
Topology Awareness: TPUs need pods/slices. GPUs need NVLink/Infiniband. You can't split a TPU pod across regions.
Latency: Minimize cross-region traffic.
Strategies:
Bin Packing: Fill up a rack before moving to the next (good for power/cooling efficiency).
Spread: Distribute replicas across failure domains (racks/regions) for HA.
Affinity/Anti-affinity: Co-locate parameters with gradients, or separate masters.
Resilience & Failure Domains:
Heartbeats: Agents ping the control plane.
Leader Election: For the scheduler itself.
Handling Worker Failure: If a TPU in a slice dies, the whole slice is dead. Restart mechanism (Checkpointing).
Handling Control Plane Failure: Active-Active or Active-Passive regions.
Fairness Controls:
Dominant Resource Fairness (DRF): Standard for mixed resource types.
Quotas: Per team/project.
Preemption: Kill low-priority jobs to run high-priority ones.
Reclamation: Use idle resources for preemptible jobs.
Utilization Reporting:
Time-series database (Prometheus/ClickHouse).
Metrics: SM utilization, memory bandwidth, power draw (DCGM for GPUs).
Implementation Strategy (Python Prototype):
I need to provide a conceptual framework and a code skeleton. I shouldn't try to write a production-grade C++ scheduler in a single response. Python using asyncio is good for simulating the logic.
Class ResourceTopology: Manages the hierarchy (Region -> Cluster -> Node).
Class Job: User request.
Class Scheduler: The logic engine.
Heuristics Engine: Separate class for scoring nodes.
Refining the TPU/GPU specific logic:
TPUs are strictly topology-bound (Slices). You request a v4-256, you need a contiguous block of 256 connected chips.
GPUs are often requested as "8x A100" (a single node) or a distributed training setup. The scheduler needs to verify topology (e.g., "Do these 4 nodes have the same Infiniband switch?").
Drafting the Solution Structure:
Architecture Overview: Diagram description.
Core Data Structures: Classes for Nodes, Jobs, Topology.
Placement Engine: The algorithm (Filter -> Score -> Bind).
Implementation: Python code demonstrating the core loop.
Self-Correction/Review during drafting:
Initial thought: Just use Kubernetes.
Correction: The prompt asks to develop one, implying custom logic is needed for specific TPU/GPU constraints (like TPU topology slicing) that standard K8s schedulers struggle with without heavy customization (like Volcano or YuniKorn). I will implement a custom logic layer.
Fairness: Keep it simple. DRF is the gold standard, I'll mock the logic.
TPU Specifics: Emphasize "Slices". A TPU job isn't just N chips; it's N chips connected in a specific torus/mesh.
Let's write the code. I will create a modular Python system.
TopologyManager: Manages the physical world.
JobQueue: Priority queue.
Scheduler: Runs the loop.
DRFAllocator: Fairness logic.
I will include comments explaining the heuristics (e.g., "TopologyAwareScoring").
Detailed Logic for Placement Heuristics:
Hard Constraints: Does the region have the specific accelerator? (e.g., TPU v5).
If Job.RequiresHA, enforce strictly one replica per Rack ID.
Let's assemble the final output. I will structure it as a design document + reference implementation.
This design outlines a production-grade architecture for a multi-region, multi-architecture scheduler. This system is built to handle the rigorous demands of Large Language Model (LLM) training (TPU/GPU mesh requirements) and high-throughput inference.
We will use a Global Orchestrator pattern with Regional Controllers, utilizing Dominant Resource Fairness (DRF) for allocation.
1. System Architecture
Global Scheduler (Stateless + Cache): Receives jobs, maintains the global "Truth" of cluster capacity (eventually consistent), and runs the placement heuristic loop.
Region Controllers: Act as the source of truth for local utilization and manage the "Heartbeat" of the global scheduler.
Node Agents: Run on every physical host/tower, reporting GPU/TPU health and power metrics.
2. Core Data Structures
python
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Dict, Optional
import hashlib
class AcceleratorType(Enum):
NVIDIA_A100 = "A100"
NVIDIA_H100 = "H100"
GOOGLE_TPU_V4 = "TPU-v4"
GOOGLE_TPU_V5 = "TPU-v5"
class TopologyScope(Enum):
# TPU specific: Requires physical proximity for low latency
POD = "POD"
# GPU specific: Within same rack/switch
RACK = "RACK"
# Multi-region training (rare, high latency)
GLOBAL = "GLOBAL"
@dataclass
class NodeSpec:
id: str
region: str
rack_id: str
accel_type: AcceleratorType
capacity: int # e.g., 8 chips per node
# Topology hints: maps of connectivity bandwidth
links: Dict[str, int] = field(default_factory=dict)
@dataclass
class JobSpec:
id: str
user_id: str
priority: int # 0-100
accelerator: AcceleratorType
count: int
topology_scope: TopologyScope
preemptible: bool = False
# Constraints
require_spot: bool = False
min_bw_gbps: int = 0
3. The Scheduler Logic (Python Implementation)
This class implements the placement heuristics, failure domain awareness, and fairness controls.
python
4. Component Deep Dive
A. Placement Heuristics & Topology
GPUs and TPUs have strict topology requirements.
TPU Slices: A TPU v4 pod has 4096 chips. The scheduler must understand that a request for 4096 chips must map to a single physical Pod slice, not 4000 chips in Region A and 96 in Region B.
GPU Clusters: For NVIDIA DGX systems, we prioritize NVLink domains first, then NVSwitch domains, then InfiniBand.
Algorithm: The find_placement function implements a "Best Fit" strategy. It tries to pack jobs into the smallest number of switches/racks possible to minimize network hops and preserve larger contiguous blocks of resources for future massive jobs.
B. Resilience & Failure Domains
A "Failure Domain" is defined as a Rack Power Circuit or a ToR (Top of Rack) Switch.
Detection: The Node Agent utilizes a "dead man's switch" (gRPC bidirectional stream). If the stream breaks for > 5s, the node is marked UNHEALTHY.
Containment:
Training Jobs: The scheduler supports "Elastic Training." If 1 out of 64 nodes fails, the scheduler can resubmit the job with 63 nodes (if supported by the framework) or pause the job until the node is replaced.
Stateless Jobs: The endpoint (Load Balancer) is updated via service discovery to drain traffic from the failed IP.
C. Utilization Reporting
Scheduling decisions rely on accurate metrics. The Node Agent exposes a /metrics endpoint (Prometheus format) with custom tags:
The Global Scheduler caches this data to make rapid bin-packing decisions without querying every node for every job.
D. Fairness Controls (DRF + Quotas)
To prevent a single user from hogging all TPUs:
Quotas: Hard limits per project (e.g., Project A: max 100 TPUs).
Dominant Resource Fairness (DRF): If the cluster has 50% GPUs and 50% TPUs, and User A has been using 90% of GPUs, User B gets priority on TPUs, or User A's GPU priority drops.
Preemption: If a high-priority "On-Demand" job arrives and the cluster is full of "Spot/Preemptible" jobs, the scheduler selects the "Spot" job that has run the longest (to minimize waste) or is smallest (to fit the new job) and kills it.
5. Execution Scenario
python
# Setup
scheduler = GlobalScheduler()
# Infrastructure Setup
# Region A, Rack 1
scheduler.add_node(NodeSpec("node-a1", "us-east", "rack-1", AcceleratorType.NVIDIA_H100, 8))
scheduler.add_node(NodeSpec("node-a2", "us-east", "rack-1", AcceleratorType.NVIDIA_H100, 8))
# Region A, Rack 2
scheduler.add_node(NodeSpec("node-b1", "us-east", "rack-2", AcceleratorType.NVIDIA_H100, 8))
# Job 1: Massive Training Run (Needs tight topology)
job1 = JobSpec("train-llm", "alice", priority=90,
accelerator=AcceleratorType.NVIDIA_H100,
count=16, topology_scope=TopologyScope.RACK)
# Job 2: Small Inference (Can be anywhere)
job2 = JobSpec("inference-api", "bob", priority=50,
accelerator=AcceleratorType.NVIDIA_H100,
count=2, topology_scope=TopologyScope.GLOBAL)
scheduler.submit_job(job1)
scheduler.submit_job(job2)
scheduler.reconcile()
# Simulate Failure
scheduler.handle_node_failure("node-a1")
import random
import math
class GlobalScheduler:
def __init__(self):
# Indexed storage for fast lookup
self.nodes: Dict[str, NodeSpec] = {}
self.jobs_queue: List[JobSpec] = []
self.allocations: Dict[str, List[str]] = {} # JobID -> [NodeIDs]
# Fairness State: Track historical usage for DRF
# user_id -> { 'gpu': float, 'tpu': float }
self.user_consumption: Dict[str, Dict[str, float]] = {}
def add_node(self, node: NodeSpec):
self.nodes[node.id] = node
def submit_job(self, job: JobSpec):
self.jobs_queue.append(job)
def _calculate_dominant_share(self, user_id: str, resource_type: str) -> float:
"""Calculates the user's share of the dominant resource."""
# Simplified: Return raw usage. Real implementation normalizes against total cluster capacity.
return self.user_consumption.get(user_id, {}).get(resource_type, 0.0)
def _sort_queue_by_fairness(self):
"""
Sorts pending queue based on Dominant Resource Fairness (DRF).
Users with lower dominant share get higher priority.
"""
def sorter(job: JobSpec):
usage = self._calculate_dominant_share(job.user_id, job.accelerator.value)
# Secondary sort by priority, then submission time (implied by list order)
return (usage, -job.priority)
self.jobs_queue.sort(key=sorter)
def _score_placement(self, job: JobSpec, candidate_nodes: List[NodeSpec]) -> float:
"""
Heuristic scoring function.
Returns a score (lower is better) for a specific set of candidate nodes.
"""
score = 0.0
# 1. Topology / Compactness
# We prefer nodes that are physically close (same rack/pod)
unique_racks = set(n.rack_id for n in candidate_nodes)
if job.topology_scope == TopologyScope.RACK and len(unique_racks) > 1:
score += 1000 * len(unique_racks) # Heavy penalty for cross-rack traffic
# 2. Utilization Efficiency (Bin Packing)
# Prefer filling up nearly full nodes/racks over spreading out
# This preserves "empty blocks" for large jobs
avg_free = sum(n.capacity for n in candidate_nodes) / len(candidate_nodes)
score += avg_free * 10 # Slight preference for nodes with less free space (fragmentation reduction)
# 3. Failure Domain Spreading (For Distributed Inference/FT)
# If job is stateless inference, we WANT to spread across racks
# (This is a placeholder logic, assume job spec defines spreading)
return score
def find_placement(self, job: JobSpec) -> Optional[List[str]]:
"""
Core Placement Engine.
"""
# 1. Filtering: Find candidates with correct HW and capacity
candidates = [n for n in self.nodes.values()
if n.accel_type == job.accelerator and n.capacity > 0]
if len(candidates) < job.count:
return None
# 2. Topology Grouping
# Try to fit the job within the tightest failure domain first
# Strategy: Try Pod -> Try Rack -> Try Region
# Group candidates by Rack
racks: Dict[str, List[NodeSpec]] = {}
for n in candidates:
if n.rack_id not in racks: racks[n.rack_id] = []
racks[n.rack_id].append(n)
best_fit = None
best_score = float('inf')
# Heuristic: Look for a single rack that can fit everything (Optimal for Training)
for rack_id, nodes in racks.items():
available_in_rack = sum(n.capacity for n in nodes)
if available_in_rack >= job.count:
# Basic selection: take first N chips
selected = []
remaining = job.count
for n in nodes:
take = min(n.capacity, remaining)
selected.append(n) # Simplification: selecting whole nodes
remaining -= take
if remaining == 0: break
s = self._score_placement(job, selected)
if s < best_score:
best_score = s
best_fit = [n.id for n in selected]
# 3. Fallback: Spread across racks if single rack fit not found (Fragmentation)
if not best_fit:
# Sort candidates by capacity (bin packing)
candidates.sort(key=lambda x: x.capacity, reverse=True)
selected = []
remaining = job.count
# Ensure Failure Domain spread if required (skip same rack if possible for HA)
# ... logic for spreading ...
# Simple fallback
for n in candidates:
selected.append(n.id)
remaining -= n.capacity # Assuming we take whole node for simplicity
if remaining <= 0:
best_fit = selected
break
return best_fit
def reconcile(self):
"""
Main loop: Handles scheduling and failure recovery.
"""
print("--- Reconciliation Loop ---")
# 1. Fairness Reordering
self._sort_queue_by_fairness()
# 2. Process Queue
scheduled_jobs = []
for job in self.jobs_queue:
placement = self.find_placement(job)
if placement:
print(f"SCHEDULED: Job {job.id} -> Nodes {placement}")
# Update State
self.allocations[job.id] = placement
for node_id in placement:
# Decrement capacity (simplified)
pass
# Update Fairness Counters
u_type = job.accelerator.value
if job.user_id not in self.user_consumption:
self.user_consumption[job.user_id] = {}
self.user_consumption[job.user_id][u_type] = \
self.user_consumption[job.user_id].get(u_type, 0) + job.count
scheduled_jobs.append(job)
# Remove scheduled jobs from queue
for j in scheduled_jobs:
self.jobs_queue.remove(j)
def handle_node_failure(self, node_id: str):
"""
Resilience Logic.
"""
print(f"!!! FAILURE DETECTED: Node {node_id}")
# Find affected jobs
affected_jobs = [jid for jid, nodes in self.allocations.items() if node_id in nodes]
for jid in affected_jobs:
print(f"IMPACTED: Job {jid} requires rescheduling")
# Logic:
# 1. If Job is preemptible: Kill it.
# 2. If Job is checkpointed training: Trigger rollback and reschedule.
# 3. If Job is stateless inference: Remove from alloc, traffic will reroute.