Download scripts/hardware.py from coderofpears/pear15-stage3-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/datasets/coderofpears/pear15-stage3-checkpoints/resolve/main/scripts/hardware.py
- Command line
-
hf download hf://datasets/coderofpears/pear15-stage3-checkpoints/scripts/hardware.py
-
curl -L -o hardware.py https://huggingface.co/datasets/coderofpears/pear15-stage3-checkpoints/resolve/main/scripts/hardware.py
10.4 kB
| """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" | |
| 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)) |