File size: 10,429 Bytes
95e202c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | """Hardware detection and optimal configuration for Pear1.5 training.
Auto-detects: CUDA GPU (type, VRAM), TPU (type, cores), CPU.
Returns optimal training config for the detected hardware.
"""
import os
import json
import torch
from dataclasses import dataclass, asdict
from typing import Optional, Dict, Any
from enum import Enum
class DeviceType(Enum):
CUDA = "cuda"
TPU = "tpu"
CPU = "cpu"
class GPUVariant(Enum):
A100_40GB = "A100-40GB"
A100_80GB = "A100-80GB"
H100_80GB = "H100-80GB"
V100_32GB = "V100-32GB"
V100_16GB = "V100-16GB"
T4_16GB = "T4-16GB"
P100_16GB = "P100-16GB"
RTX_5060_TI_16GB = "RTX-5060-TI-16GB"
RTX_4090_24GB = "RTX-4090-24GB"
RTX_3090_24GB = "RTX-3090-24GB"
UNKNOWN = "UNKNOWN"
class TPUVariant(Enum):
V3_8 = "v3-8"
V3_32 = "v3-32"
V4_8 = "v4-8"
V4_16 = "v4-16"
V5E_8 = "v5e-8"
V5E_16 = "v5e-16"
V5E_32 = "v5e-32"
V5P_8 = "v5p-8"
UNKNOWN = "UNKNOWN"
@dataclass
class HardwareInfo:
device_type: DeviceType
variant: str
num_devices: int
vram_per_device_gb: int
total_vram_gb: int
supports_bf16: bool
supports_fp8: bool
max_batch_per_device: int # at seq_len=1024, model=134M
recommended_grad_accum: int
effective_batch: int
notes: str
# Model constants
MODEL_PARAMS = 134_500_000 # 134.5M
SEQ_LEN = 1024
HIDDEN = 576
LAYERS = 30
HEADS = 9
KV_HEADS = 3
VOCAB = 49152
# Rough VRAM per param (bf16): 2 bytes + optimizer states (8 bytes AdamW) = ~10 bytes/param
# + activations ~ batch * seq * hidden * layers * 2 bytes
# For batch=1: ~1.3GB model+optim, ~0.3GB activations = ~1.6GB base
def detect_cuda() -> Optional[HardwareInfo]:
"""Detect NVIDIA GPU and return optimal config."""
if not torch.cuda.is_available():
return None
name = torch.cuda.get_device_name(0).upper()
props = torch.cuda.get_device_properties(0)
vram_gb = props.total_memory // (1024**3)
num_gpus = torch.cuda.device_count()
# Identify variant
variant = GPUVariant.UNKNOWN
if "A100" in name and "80" in name:
variant = GPUVariant.A100_80GB
elif "A100" in name:
variant = GPUVariant.A100_40GB
elif "H100" in name:
variant = GPUVariant.H100_80GB
elif "V100" in name and "32" in name:
variant = GPUVariant.V100_32GB
elif "V100" in name:
variant = GPUVariant.V100_16GB
elif "T4" in name:
variant = GPUVariant.T4_16GB
elif "P100" in name:
variant = GPUVariant.P100_16GB
elif "RTX 5060 TI" in name or "5060 TI" in name:
variant = GPUVariant.RTX_5060_TI_16GB
elif "RTX 4090" in name:
variant = GPUVariant.RTX_4090_24GB
elif "RTX 3090" in name:
variant = GPUVariant.RTX_3090_24GB
# Optimal batch sizes per device (seq=1024, bf16, gradient_checkpointing=True)
batch_map = {
GPUVariant.A100_80GB: 64,
GPUVariant.A100_40GB: 32,
GPUVariant.H100_80GB: 64,
GPUVariant.V100_32GB: 16,
GPUVariant.V100_16GB: 8,
GPUVariant.T4_16GB: 4,
GPUVariant.P100_16GB: 4,
GPUVariant.RTX_5060_TI_16GB: 4,
GPUVariant.RTX_4090_24GB: 8,
GPUVariant.RTX_3090_24GB: 8,
GPUVariant.UNKNOWN: 2,
}
max_batch = batch_map.get(variant, 2)
# Target effective batch = 16 (matches original A100 run)
target_effective = 16
grad_accum = max(1, target_effective // (max_batch * num_gpus))
effective = max_batch * num_gpus * grad_accum
return HardwareInfo(
device_type=DeviceType.CUDA,
variant=variant.value,
num_devices=num_gpus,
vram_per_device_gb=vram_gb,
total_vram_gb=vram_gb * num_gpus,
supports_bf16=props.major >= 8, # Ampere+
supports_fp8="H100" in name,
max_batch_per_device=max_batch,
recommended_grad_accum=grad_accum,
effective_batch=effective,
notes=f"Detected {num_gpus}x {variant.value} ({vram_gb}GB each). Target effective batch: {target_effective}"
)
def detect_tpu() -> Optional[HardwareInfo]:
"""Detect TPU and return optimal config."""
# Check for TPU via environment (Kaggle, Colab, GCP)
tpu_name = os.environ.get("TPU_NAME", "").lower()
if not tpu_name:
# Try XLA
try:
import torch_xla.core.xla_model as xm
devices = xm.get_xla_supported_devices()
if devices:
tpu_name = str(devices[0]).lower()
except Exception:
pass
if not tpu_name:
# Check Kaggle/Colab TPU env vars
if os.environ.get("COLAB_TPU_ADDR") or os.environ.get("TPU_ADDR"):
tpu_name = "v5e-8" # Default assumption for Kaggle/Colab
if not tpu_name:
return None
# Identify variant
variant = TPUVariant.UNKNOWN
for v in TPUVariant:
if v.value in tpu_name:
variant = v
break
# TPU specs
tpu_specs = {
TPUVariant.V3_8: {"cores": 8, "hbm_per_core_gb": 16},
TPUVariant.V3_32: {"cores": 32, "hbm_per_core_gb": 16},
TPUVariant.V4_8: {"cores": 8, "hbm_per_core_gb": 32},
TPUVariant.V4_16: {"cores": 16, "hbm_per_core_gb": 32},
TPUVariant.V5E_8: {"cores": 8, "hbm_per_core_gb": 16},
TPUVariant.V5E_16: {"cores": 16, "hbm_per_core_gb": 16},
TPUVariant.V5E_32: {"cores": 32, "hbm_per_core_gb": 16},
TPUVariant.V5P_8: {"cores": 8, "hbm_per_core_gb": 96},
}
specs = tpu_specs.get(variant, {"cores": 8, "hbm_per_core_gb": 16})
num_cores = specs["cores"]
hbm_per_core = specs["hbm_per_core_gb"]
# Batch size per core (seq=1024, bf16, gradient_checkpointing)
batch_per_core_map = {
TPUVariant.V3_8: 2,
TPUVariant.V3_32: 2,
TPUVariant.V4_8: 4,
TPUVariant.V4_16: 4,
TPUVariant.V5E_8: 2,
TPUVariant.V5E_16: 2,
TPUVariant.V5E_32: 2,
TPUVariant.V5P_8: 8,
TPUVariant.UNKNOWN: 1,
}
max_batch = batch_per_core_map.get(variant, 1)
target_effective = 16
grad_accum = max(1, target_effective // (max_batch * num_cores))
effective = max_batch * num_cores * grad_accum
return HardwareInfo(
device_type=DeviceType.TPU,
variant=variant.value,
num_devices=num_cores,
vram_per_device_gb=hbm_per_core,
total_vram_gb=hbm_per_core * num_cores,
supports_bf16=True,
supports_fp8=False,
max_batch_per_device=max_batch,
recommended_grad_accum=grad_accum,
effective_batch=effective,
notes=f"Detected TPU {variant.value} ({num_cores} cores, {hbm_per_core}GB HBM/core)"
)
def detect_cpu() -> HardwareInfo:
"""Fallback CPU config."""
import multiprocessing
return HardwareInfo(
device_type=DeviceType.CPU,
variant="CPU",
num_devices=1,
vram_per_device_gb=0,
total_vram_gb=0,
supports_bf16=False,
supports_fp8=False,
max_batch_per_device=1,
recommended_grad_accum=16,
effective_batch=16,
notes=f"CPU fallback ({multiprocessing.cpu_count()} cores). Very slow."
)
def get_hardware_info() -> HardwareInfo:
"""Auto-detect best available hardware."""
# Priority: CUDA > TPU > CPU
for detector in [detect_cuda, detect_tpu]:
hw = detector()
if hw:
return hw
return detect_cpu()
def get_training_config(hw: HardwareInfo) -> Dict[str, Any]:
"""Generate complete training config for the detected hardware."""
base_config = {
# Model
"model_type": "llama",
"vocab_size": VOCAB,
"hidden_size": HIDDEN,
"num_hidden_layers": LAYERS,
"num_attention_heads": HEADS,
"num_key_value_heads": KV_HEADS,
"tie_word_embeddings": True,
"max_position_embeddings": 2048,
"rope_theta": 10000.0,
# Training
"sequence_length": SEQ_LEN,
"batch_size": hw.max_batch_per_device,
"gradient_accumulation_steps": hw.recommended_grad_accum,
"gradient_checkpointing": True,
"loss_chunk_tokens": 8192,
"precision": "bf16" if hw.supports_bf16 else "fp32",
"learning_rate": 3e-4,
"min_lr_ratio": 0.1,
"weight_decay": 0.1,
"adam_beta1": 0.9,
"adam_beta2": 0.95,
"adam_epsilon": 1e-8,
"max_grad_norm": 1.0,
"warmup_steps": 500,
"total_steps": 2_929_688, # (50B - 1.74B) / 16384
"checkpoint_interval_steps": 500,
"checkpoint_interval_seconds": 1800,
"log_interval_steps": 50,
"eval_interval_steps": 2000,
"eval_targets": 8192,
"seed": 0,
# Hardware-specific
"device_type": hw.device_type.value,
"num_devices": hw.num_devices,
"effective_batch": hw.effective_batch,
"hardware_variant": hw.variant,
}
# TPU-specific additions
if hw.device_type == DeviceType.TPU:
base_config.update({
"xla_device": "TPU",
"pjrt_device": "TPU",
"use_spmd": hw.num_devices > 8,
})
# CUDA-specific additions
if hw.device_type == DeviceType.CUDA:
base_config.update({
"cuda_device": "cuda",
"use_ddp": hw.num_devices > 1,
"nccl_backend": "nccl",
})
return base_config
def print_hardware_summary(hw: HardwareInfo, config: Dict):
"""Pretty print hardware detection and config."""
print("=" * 60)
print(f"HARDWARE DETECTED: {hw.device_type.value.upper()} - {hw.variant}")
print("=" * 60)
print(f"Devices: {hw.num_devices} x {hw.variant}")
print(f"VRAM/HBM per device: {hw.vram_per_device_gb} GB")
print(f"Total VRAM/HBM: {hw.total_vram_gb} GB")
print(f"BF16 support: {hw.supports_bf16}")
print(f"FP8 support: {hw.supports_fp8}")
print(f"Max batch/device: {hw.max_batch_per_device}")
print(f"Grad accum steps: {hw.recommended_grad_accum}")
print(f"Effective batch: {hw.effective_batch} (target: 16)")
print(f"Precision: {config['precision']}")
print(f"Notes: {hw.notes}")
print("=" * 60)
if __name__ == "__main__":
hw = get_hardware_info()
config = get_training_config(hw)
print_hardware_summary(hw, config)
print(json.dumps(config, indent=2)) |