Download trainer_source/grom_runtime.py from GRIMIAI-VNAnhdev/GROMAIVN: direct link, hf CLI and curl.
- Browser
- Download file 17.4 kB
-
https://huggingface.co/datasets/GRIMIAI-VNAnhdev/GROMAIVN/resolve/main/trainer_source/grom_runtime.py
- Command line
-
hf download hf://datasets/GRIMIAI-VNAnhdev/GROMAIVN/trainer_source/grom_runtime.py
-
curl -L -o grom_runtime.py https://huggingface.co/datasets/GRIMIAI-VNAnhdev/GROMAIVN/resolve/main/trainer_source/grom_runtime.py
17.4 kB
| """Shared runtime contract for GROM Mini. | |
| All Python entrypoints import paths/config from here so the project has one source of truth. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import platform | |
| import shutil | |
| import subprocess | |
| import sys | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent | |
| CONFIG_PATH = ROOT / "config.json" | |
| _BOOT_CFG = {} | |
| try: | |
| _BOOT_CFG = json.loads(CONFIG_PATH.read_text(encoding="utf-8").replace("\ufeff", "")) | |
| except Exception: | |
| pass | |
| _DATA_ROOT_RAW = os.environ.get("GROM_DATA_ROOT") or _BOOT_CFG.get("dataset_root") or "data/data" | |
| DATA_ROOT = Path(_DATA_ROOT_RAW).expanduser() | |
| if not DATA_ROOT.is_absolute(): | |
| DATA_ROOT = ROOT / DATA_ROOT | |
| # Dataset storage is intentionally C:-local only. Any external drive path is rejected. | |
| if DATA_ROOT.drive.upper() != ROOT.drive.upper(): | |
| DATA_ROOT = ROOT / "data" / "data" | |
| _OUTPUT_ROOT_RAW = _BOOT_CFG.get("dataset_output_root") or str(ROOT / "data" / "dataset") | |
| DATASET_OUTPUT_ROOT = Path(_OUTPUT_ROOT_RAW).expanduser() | |
| if not DATASET_OUTPUT_ROOT.is_absolute(): | |
| DATASET_OUTPUT_ROOT = ROOT / DATASET_OUTPUT_ROOT | |
| if DATASET_OUTPUT_ROOT.drive.upper() != ROOT.drive.upper(): | |
| DATASET_OUTPUT_ROOT = ROOT / "data" / "dataset" | |
| SOURCES_DIR = DATA_ROOT / "sources" | |
| RAW_TEXT_DIR = DATA_ROOT / "raw_text" | |
| TRAIN_TXT = DATA_ROOT / "train.txt" | |
| TRAIN_SHARDS_DIR = DATASET_OUTPUT_ROOT / "train_shards" | |
| VAL_SHARDS_DIR = DATASET_OUTPUT_ROOT / "val_shards" | |
| DATASET_MANIFEST = TRAIN_SHARDS_DIR / "manifest.json" | |
| DATASET_REPORT = DATASET_OUTPUT_ROOT / "dataset_report.json" | |
| PICTURE_DIR = ROOT / "data" / "picture" | |
| MODEL_PATH = ROOT / "grom_mini.pt" | |
| CHECKPOINT_PATH = ROOT / "checkpoint.pt" | |
| TOKENIZER_PATH = ROOT / "tokenizer.json" | |
| TOKENIZER_META_PATH = ROOT / "tokenizer.meta.json" | |
| PROGRESS_PATH = ROOT / "parquet_progress.json" | |
| EXCLUDED_DATA_DIRS = { | |
| ".git", ".venv", "venv", "__pycache__", "node_modules", | |
| "train_shards", "_needs_review", "_unique_stage", "_dedup", | |
| "checkpoints", "models", "dist", "build", ".cache", "site-packages", | |
| } | |
| def load_config() -> dict: | |
| path = Path(os.environ.get("GROM_CONFIG", str(CONFIG_PATH))).expanduser() | |
| if not path.is_absolute(): | |
| path = ROOT / path | |
| if not path.exists(): | |
| return {} | |
| return json.loads(path.read_text(encoding="utf-8").replace("", "")) | |
| CFG = load_config() | |
| # Canonical product identity. Keep these values centralized so every | |
| # builder, tokenizer, trainer and inference entrypoint speaks the same name. | |
| AI_NAME = "GynixA.I" | |
| AI_FULL_NAME = "GynixA.I" | |
| DEVELOPER_NAME = "Mixtralrde Cineten Ktinde" | |
| RESPONSE_MARKER = AI_NAME + ":" | |
| def directory_size(path: Path) -> int: | |
| total = 0 | |
| if not path.exists(): | |
| return 0 | |
| for p in path.rglob("*"): | |
| try: | |
| if p.is_file(): | |
| total += p.stat().st_size | |
| except OSError: | |
| pass | |
| return total | |
| def available_ram_bytes() -> int: | |
| if os.name == "nt": | |
| try: | |
| import ctypes | |
| class MEMORYSTATUSEX(ctypes.Structure): | |
| _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), | |
| ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), | |
| ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), | |
| ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), | |
| ("sullAvailExtendedVirtual", ctypes.c_ulonglong)] | |
| m = MEMORYSTATUSEX() | |
| m.dwLength = ctypes.sizeof(m) | |
| if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)): | |
| return int(m.ullAvailPhys) | |
| except Exception: | |
| pass | |
| try: | |
| import psutil | |
| return int(psutil.virtual_memory().available) | |
| except Exception: | |
| return 0 | |
| def system_ram_bytes() -> int: | |
| if os.name == "nt": | |
| try: | |
| import ctypes | |
| class MEMORYSTATUSEX(ctypes.Structure): | |
| _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), | |
| ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), | |
| ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), | |
| ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), | |
| ("sullAvailExtendedVirtual", ctypes.c_ulonglong)] | |
| m = MEMORYSTATUSEX() | |
| m.dwLength = ctypes.sizeof(m) | |
| if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)): | |
| return int(m.ullTotalPhys) | |
| except Exception: | |
| pass | |
| try: | |
| import psutil | |
| return int(psutil.virtual_memory().total) | |
| except Exception: | |
| return 0 | |
| def gpu_memory_mib() -> int: | |
| """Return total VRAM in MiB on Windows or Linux; 0 means unknown.""" | |
| if not shutil.which("nvidia-smi"): | |
| return 0 | |
| try: | |
| out = subprocess.check_output( | |
| ["nvidia-smi", "--query-gpu=memory.total", "--format=csv,noheader,nounits"], | |
| text=True, stderr=subprocess.DEVNULL, timeout=3, | |
| ) | |
| values = [int(x.strip()) for x in out.splitlines() if x.strip().isdigit()] | |
| # Training uses device 0; do not use the largest GPU if multiple GPUs differ. | |
| return values[0] if values else 0 | |
| except Exception: | |
| return 0 | |
| def has_cuda() -> bool: | |
| """Return whether the active Python/PyTorch runtime can really execute CUDA.""" | |
| if str(CFG.get("force_cpu", "")).lower() in {"1", "true", "yes"}: | |
| return False | |
| try: | |
| import torch | |
| return bool(torch.cuda.is_available()) | |
| except Exception: | |
| return False | |
| def gpu_name() -> str: | |
| if not has_cuda(): | |
| return "" | |
| try: | |
| import torch | |
| return str(torch.cuda.get_device_name(0)) | |
| except Exception: | |
| return "" | |
| def h100_profile() -> bool: | |
| """True only when the active CUDA device is actually an H100/H200.""" | |
| name = gpu_name().lower() | |
| return bool(has_cuda() and ("h100" in name or "h200" in name)) | |
| def dataset_roots() -> list[Path]: | |
| """Raw/extra roots that feed the active dataset builder.""" | |
| roots: list[Path] = [] | |
| configured = str(CFG.get("dataset_root", "")).strip() | |
| if configured: | |
| p = Path(configured).expanduser() | |
| if not p.is_absolute(): | |
| p = ROOT / p | |
| if p.exists() and p.drive.upper() == ROOT.drive.upper(): | |
| roots.append(p) | |
| explicit = ROOT / "dataset" | |
| if explicit.exists(): | |
| roots.append(explicit) | |
| for raw in CFG.get("dataset_extra_roots", []) or []: | |
| p = Path(str(raw)).expanduser() | |
| if not p.is_absolute(): | |
| p = ROOT / p | |
| if p.exists() and p.drive.upper() == ROOT.drive.upper(): | |
| roots.append(p) | |
| if not roots: | |
| roots.append(DATA_ROOT) | |
| out = [] | |
| seen = set() | |
| for p in roots: | |
| key = str(p.resolve()).lower() | |
| if key not in seen: | |
| seen.add(key); out.append(p) | |
| return out | |
| def low_resource_profile() -> bool: | |
| """True only when both usable compute memory and host memory are constrained.""" | |
| ram = system_ram_bytes() | |
| vram_mib = gpu_memory_mib() if has_cuda() else 0 | |
| # A real CUDA GPU with >4 GiB VRAM should not be forced to CPU just because | |
| # the host has little RAM. If VRAM cannot be detected, fall back to RAM. | |
| if has_cuda() and vram_mib > 4096: | |
| return False | |
| ram_low = 0 < ram <= 8 * 1024**3 | |
| vram_low = bool(has_cuda() and 0 < vram_mib <= 4096) | |
| return ram_low or vram_low | |
| def gpu_profile() -> str: | |
| """Choose a conservative training profile from the active GPU's actual VRAM.""" | |
| if not has_cuda(): | |
| return "cpu" | |
| name = gpu_name().lower() | |
| vram = gpu_memory_mib() | |
| if "h100" in name or "h200" in name: | |
| return "h100" | |
| if vram >= 70000: | |
| return "gpu80" | |
| if vram >= 40000: | |
| return "gpu48" | |
| if vram >= 23000: | |
| return "gpu24" | |
| if vram >= 14000: | |
| return "gpu16" | |
| if vram >= 9000: | |
| return "gpu10" | |
| if vram > 0: | |
| return "gpu_small" | |
| return "gpu_unknown" | |
| def training_config(cfg: dict | None = None) -> dict: | |
| c = dict(CFG if cfg is None else cfg) | |
| profile = gpu_profile() | |
| c["active_gpu_profile"] = profile | |
| vram_mib = gpu_memory_mib() if has_cuda() else 0 | |
| if profile == "h100": | |
| c["force_cpu"] = False | |
| c["low_resource_auto"] = False | |
| c["full_corpus_gpu"] = True | |
| c["full_corpus_no_caps"] = True | |
| c["dataset_target_gib"] = 0 | |
| c["tokenizer_max_chars"] = 0 | |
| c["parquet_max_chars"] = 0 | |
| c["image_max_per_run"] = 0 | |
| c["image_max_seconds"] = 0 | |
| c["image_target_per_class"] = 0 | |
| c["training_steps_hard_max"] = 0 | |
| c["training_auto_scale"] = True | |
| c["training_epochs"] = max(1.0, float(c.get("training_epochs_h100", 1.0))) | |
| c["block_size"] = max(1024, int(c.get("block_size_h100", 16384))) | |
| c["batch_size"] = max(1, int(c.get("batch_size_h100", 2))) | |
| c["img_batch_size"] = max(1, int(c.get("img_batch_size_h100", 32))) | |
| c["img_every"] = max(1, int(c.get("img_every_h100", 1))) | |
| c["gradient_checkpointing"] = bool(c.get("gradient_checkpointing_h100", True)) | |
| return c | |
| if profile in {"gpu80", "gpu48", "gpu24", "gpu16", "gpu10", "gpu_small", "gpu_unknown"}: | |
| # Conservative defaults; actual peak VRAM depends on model, kernels and data. | |
| tiers = { | |
| "gpu80": (8192, 8, 32, 1), | |
| "gpu48": (4096, 4, 16, 1), | |
| "gpu24": (2048, 1, 8, 2), | |
| "gpu16": (1024, 1, 4, 2), | |
| "gpu10": (512, 1, 2, 4), | |
| "gpu_small": (256, 1, 1, 8), | |
| "gpu_unknown":(512, 1, 2, 4), | |
| } | |
| block, batch, img_batch, img_every = tiers[profile] | |
| c["force_cpu"] = False | |
| c["full_corpus_gpu"] = False | |
| c["full_corpus_no_caps"] = False | |
| # Hardware profile owns memory-sensitive values; don't let stale config | |
| # (for example batch=48/block=512 from another machine) override detection. | |
| c["block_size"] = block | |
| c["batch_size"] = batch | |
| c["img_batch_size"] = img_batch | |
| c["img_every"] = img_every | |
| c["gradient_checkpointing"] = True | |
| c["training_auto_scale"] = True | |
| # Do not let an old H100-only setting leak into non-H100 GPU runs. | |
| c["training_steps_hard_max"] = max(1, int(c.get("training_steps_hard_max", 8000) or 8000)) | |
| c["vision"] = bool(c.get("vision", True)) and profile not in {"gpu_small"} | |
| return c | |
| # CPU fallback: retain the existing low-resource guardrails. | |
| if not low_resource_profile() or bool(c.get("allow_large_cpu_model", False)): | |
| return c | |
| c["force_cpu"] = True | |
| c["vision"] = False | |
| c["image_auto_download"] = False | |
| c["block_size"] = min(int(c.get("block_size", 192)), 192) | |
| c["batch_size"] = min(int(c.get("batch_size", 8)), 1) | |
| c["n_embd"] = min(int(c.get("n_embd", 192)), 256) | |
| c["n_head"] = min(int(c.get("n_head", 6)), 4) | |
| c["n_layer"] = min(int(c.get("n_layer", 5)), 6) | |
| c["img_batch_size"] = 1 | |
| c["img_every"] = 0 | |
| c["tokenizer_max_chars"] = min(int(c.get("tokenizer_max_chars", 600_000_000)), 20_000_000) | |
| c["parquet_max_chars"] = min(int(c.get("parquet_max_chars", 20_000_000)), 4_000_000) | |
| c["training_steps_min"] = min(int(c.get("training_steps_min", 14000)), 2000) | |
| c["training_steps_upgrade"] = min(int(c.get("training_steps_upgrade", 50000)), 8000) | |
| c["training_auto_scale"] = True | |
| return c | |
| def validate_config(cfg: dict | None = None) -> list[str]: | |
| c = CFG if cfg is None else cfg | |
| errors = [] | |
| vocab = int(c.get("vocab_size", 8000)) | |
| block = int(c.get("block_size", 192)) | |
| embd = int(c.get("n_embd", 192)) | |
| heads = int(c.get("n_head", 6)) | |
| layers = int(c.get("n_layer", 5)) | |
| if vocab < 256: errors.append("vocab_size must be >= 256") | |
| if block < 32: errors.append("block_size must be >= 32") | |
| if embd < 32: errors.append("n_embd must be >= 32") | |
| if heads < 1 or embd % heads: errors.append("n_embd must be divisible by n_head") | |
| if layers < 1: errors.append("n_layer must be >= 1") | |
| if float(c.get("temperature", 0.45)) <= 0: errors.append("temperature must be > 0") | |
| if not 0 < float(c.get("top_p", 0.9)) <= 1: errors.append("top_p must be in (0,1]") | |
| return errors | |
| def manifest_paths() -> list[Path]: | |
| if not DATASET_MANIFEST.exists(): | |
| return [] | |
| try: | |
| m = json.loads(DATASET_MANIFEST.read_text(encoding="utf-8")) | |
| return [TRAIN_SHARDS_DIR / str(x) for x in m.get("train_shards", m.get("shards", []))] | |
| except Exception: | |
| return [] | |
| def dataset_fingerprint(manifest: dict | None = None) -> str: | |
| import hashlib | |
| m = manifest | |
| if m is None: | |
| if not DATASET_MANIFEST.exists(): | |
| return "" | |
| m = json.loads(DATASET_MANIFEST.read_text(encoding="utf-8")) | |
| h = hashlib.sha256() | |
| entries = m.get("source_manifest") or m.get("source_files") or [] | |
| for x in entries: | |
| h.update(str(x.get("path")).encode("utf-8")) | |
| h.update(b"\0") | |
| h.update(str(x.get("bytes")).encode("utf-8")) | |
| h.update(b"\0") | |
| h.update(str(x.get("sha256", x.get("mtime_ns", ""))).encode("utf-8")) | |
| h.update(b"\n") | |
| pipeline = str(m.get("pipeline", "grom_record_dedup")) | |
| quality = str(m.get("quality_profile", "response_and_code_v2")) | |
| segmentation = str(m.get("record_segmentation", "role_aware_v2")) | |
| safety = str(m.get("safety_filter", "strict_assistant_safe_v1")) | |
| h.update(f"pipeline={pipeline}\nquality={quality}\nsegmentation={segmentation}\nsafety={safety}\n".encode("utf-8")) | |
| identity_policy = str(m.get("identity_policy", "single_canonical_identity_v2")) | |
| if identity_policy != "single_canonical_identity_v2": | |
| h.update(f"identity={identity_policy}\n".encode("utf-8")) | |
| h.update(f"unique={m.get('unique_records', 0)}\n".encode("utf-8")) | |
| h.update(f"bytes={m.get('unique_bytes', 0)}\n".encode("utf-8")) | |
| h.update(f"duplicates={m.get('duplicate_records', 0)}\n".encode("utf-8")) | |
| h.update(f"rejected={m.get('rejected_records', 0)}".encode("utf-8")) | |
| return h.hexdigest() | |
| def verify_manifest(require_dedup: bool = False, require_validation: bool = False) -> dict: | |
| if not DATASET_MANIFEST.exists(): | |
| raise FileNotFoundError(f"Missing dataset manifest: {DATASET_MANIFEST}") | |
| m = json.loads(DATASET_MANIFEST.read_text(encoding="utf-8")) | |
| if require_dedup and m.get("dedup_mode") != "record_sha256": | |
| raise RuntimeError("Dataset manifest is not record-level deduplicated.") | |
| if require_validation and not m.get("val_shards"): | |
| raise RuntimeError("Dataset manifest has no validation split.") | |
| missing = [] | |
| actual = 0 | |
| for p in manifest_paths(): | |
| if not p.exists(): | |
| missing.append(p.name) | |
| else: | |
| actual += p.stat().st_size | |
| val_dir = DATASET_OUTPUT_ROOT / "val_shards" | |
| for name in m.get("val_shards", []): | |
| p = val_dir / str(name) | |
| if not p.exists(): | |
| missing.append(str(name)) | |
| else: | |
| actual += p.stat().st_size | |
| expected = int(m.get("actual_bytes", 0) or 0) | |
| if missing: | |
| raise RuntimeError("Missing shards: " + ", ".join(missing[:20])) | |
| if actual != expected: | |
| raise RuntimeError(f"Manifest byte mismatch: actual={actual} expected={expected}") | |
| return m | |
| def print_runtime_status(cfg: dict | None = None) -> None: | |
| c = training_config(cfg) | |
| ram = system_ram_bytes() | |
| free = available_ram_bytes() | |
| print(f"[runtime] root={ROOT}") | |
| print(f"[runtime] python={sys.executable}") | |
| print(f"[runtime] platform={platform.platform()}") | |
| print(f"[runtime] ram={ram / 1024**3:.2f} GiB available={free / 1024**3:.2f} GiB" if ram else "[runtime] ram=unknown") | |
| vram_mib = gpu_memory_mib() if has_cuda() else 0 | |
| print(f"[runtime] gpu={gpu_name() or 'none'} vram={vram_mib / 1024:.1f} GiB profile={gpu_profile()} cuda={has_cuda()} h100_profile={h100_profile()} low_resource={low_resource_profile()}") | |
| print(f"[runtime] raw_dataset={DATA_ROOT} roots={', '.join(str(x) for x in dataset_roots())}") | |
| print(f"[runtime] output_dataset={DATASET_OUTPUT_ROOT}") | |
| print(f"[runtime] shards={TRAIN_SHARDS_DIR}") | |
| print(f"[runtime] effective_model={c.get('n_embd')}d/{c.get('n_head')}h/{c.get('n_layer')}L block={c.get('block_size')} batch={c.get('batch_size')}") | |
| __all__ = [ | |
| "ROOT", "CONFIG_PATH", "DATA_ROOT", "DATASET_OUTPUT_ROOT", "SOURCES_DIR", "RAW_TEXT_DIR", "TRAIN_TXT", | |
| "TRAIN_SHARDS_DIR", "VAL_SHARDS_DIR", "DATASET_MANIFEST", "DATASET_REPORT", "PICTURE_DIR", | |
| "MODEL_PATH", "CHECKPOINT_PATH", "TOKENIZER_PATH", "TOKENIZER_META_PATH", "PROGRESS_PATH", | |
| "EXCLUDED_DATA_DIRS", "CFG", "AI_NAME", "AI_FULL_NAME", "DEVELOPER_NAME", "RESPONSE_MARKER", "load_config", "training_config", "validate_config", | |
| "verify_manifest", "manifest_paths", "dataset_fingerprint", "directory_size", "system_ram_bytes", | |
| "available_ram_bytes", "has_cuda", "gpu_name", "gpu_memory_mib", "gpu_profile", "h100_profile", "dataset_roots", | |
| "low_resource_profile", "print_runtime_status", | |
| ] |