| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| from __future__ import annotations |
|
|
| import argparse |
| import copy |
| import json |
| import math |
| import os |
| import threading |
| import time |
| from pathlib import Path |
| from typing import Any |
|
|
| import psutil |
| import torch |
| from huggingface_hub import HfApi, hf_hub_download |
| from transformers import AutoConfig, AutoProcessor, AutoTokenizer |
|
|
|
|
| class Telemetry: |
| def __init__(self, interval: float = 2.0): |
| self.interval = interval |
| self.stop_event = threading.Event() |
| self.thread = threading.Thread(target=self.run, daemon=True) |
|
|
| def start(self): |
| self.thread.start() |
| return self |
|
|
| def stop(self): |
| self.stop_event.set() |
| self.thread.join(timeout=3) |
|
|
| def run(self): |
| psutil.cpu_percent(interval=None) |
| while not self.stop_event.wait(self.interval): |
| memory = psutil.virtual_memory() |
| payload: dict[str, Any] = { |
| "event": "telemetry", |
| "timestamp": time.time(), |
| "cpu_percent": psutil.cpu_percent(interval=None), |
| "ram_used_gb": round((memory.total - memory.available) / 1024**3, 3), |
| "ram_total_gb": round(memory.total / 1024**3, 3), |
| "ram_percent": memory.percent, |
| "gpu_count": 0, |
| "gpu_name": None, |
| "gpu_util_percent": None, |
| "vram_used_gb": None, |
| "vram_total_gb": None, |
| "vram_percent": None, |
| "gpu_temperature_c": None, |
| } |
| try: |
| import pynvml |
| pynvml.nvmlInit() |
| count = pynvml.nvmlDeviceGetCount() |
| utils, used, total, temps, names = [], 0, 0, [], [] |
| for index in range(count): |
| handle = pynvml.nvmlDeviceGetHandleByIndex(index) |
| util = pynvml.nvmlDeviceGetUtilizationRates(handle) |
| mem = pynvml.nvmlDeviceGetMemoryInfo(handle) |
| name = pynvml.nvmlDeviceGetName(handle) |
| names.append(name.decode() if isinstance(name, bytes) else str(name)) |
| utils.append(float(util.gpu)); used += int(mem.used); total += int(mem.total) |
| try: temps.append(float(pynvml.nvmlDeviceGetTemperature(handle, pynvml.NVML_TEMPERATURE_GPU))) |
| except Exception: pass |
| payload.update({ |
| "gpu_count": count, |
| "gpu_name": " + ".join(names) if names else None, |
| "gpu_util_percent": round(sum(utils) / len(utils), 1) if utils else None, |
| "vram_used_gb": round(used / 1024**3, 3) if total else None, |
| "vram_total_gb": round(total / 1024**3, 3) if total else None, |
| "vram_percent": round(100 * used / total, 1) if total else None, |
| "gpu_temperature_c": round(sum(temps) / len(temps), 1) if temps else None, |
| }) |
| pynvml.nvmlShutdown() |
| except Exception: |
| pass |
| print(json.dumps(payload), flush=True) |
|
|
|
|
| def progress(percent: int, stage: str, message: str = "") -> None: |
| print(json.dumps({"event": "progress", "percent": percent, "stage": stage, "message": message}), flush=True) |
| print(f"{percent}% · {stage} · {message}", flush=True) |
|
|
|
|
| def round_multiple(value: float, multiple: int, minimum: int) -> int: |
| return max(minimum, int(round(value / multiple) * multiple)) |
|
|
|
|
| def divisors(value: int) -> list[int]: |
| result = [] |
| for item in range(1, int(math.sqrt(value)) + 1): |
| if value % item == 0: |
| result.extend([item, value // item]) |
| return sorted(set(result)) |
|
|
|
|
| def best_head_count(hidden_size: int, original: int) -> int: |
| choices = [value for value in divisors(hidden_size) if value <= max(1, original)] |
| target = min(max(1, original), max(1, hidden_size // 64)) |
| return min(choices or [1], key=lambda value: abs(value - target)) |
|
|
|
|
| def resize_layer_sequence(values: list[Any], new_length: int) -> list[Any]: |
| """Resize per-layer metadata while preserving its distribution and final layer.""" |
| if new_length <= 0 or not values: |
| return [] |
| if len(values) == new_length: |
| return list(values) |
| if new_length == 1: |
| return [values[-1]] |
| last = len(values) - 1 |
| indices = [round(index * last / (new_length - 1)) for index in range(new_length)] |
| return [values[index] for index in indices] |
|
|
|
|
| def scale_config_object(config: Any, ratio: float, overrides: dict[str, Any] | None = None) -> dict[str, Any]: |
| """Scale common Transformer dimensions and keep architecture-coupled fields valid.""" |
| overrides = overrides or {} |
| layer_scale = max(0.18, min(1.0, ratio ** 0.40)) |
| hidden_scale = max(0.22, min(1.0, ratio ** 0.30)) |
|
|
| layer_keys = ["num_hidden_layers", "n_layer", "num_layers", "encoder_layers", "decoder_layers", "num_decoder_layers"] |
| hidden_keys = ["hidden_size", "d_model", "n_embd", "model_dim"] |
| ff_keys = ["intermediate_size", "d_ff", "ffn_dim", "encoder_ffn_dim", "decoder_ffn_dim"] |
| head_keys = ["num_attention_heads", "n_head", "encoder_attention_heads", "decoder_attention_heads"] |
| per_layer_keys = ["layer_types", "mlp_layer_types", "block_types", "attention_types"] |
|
|
| original_layer_count = getattr(config, "num_hidden_layers", None) |
| per_layer_values = { |
| key: list(value) |
| for key in per_layer_keys |
| if isinstance((value := getattr(config, key, None)), (list, tuple)) |
| } |
| original_heads: dict[str, int] = {} |
| for key in head_keys: |
| value = getattr(config, key, None) |
| if isinstance(value, int) and value > 0: |
| original_heads[key] = value |
|
|
| scaled_layer_counts: dict[str, int] = {} |
| for key in layer_keys: |
| value = getattr(config, key, None) |
| if isinstance(value, int) and value > 1: |
| scaled_layer_counts[key] = max(2, int(round(value * layer_scale))) |
| for key, value in scaled_layer_counts.items(): |
| setattr(config, key, value) |
|
|
| new_layer_count = getattr(config, "num_hidden_layers", None) |
| if isinstance(new_layer_count, int) and new_layer_count > 0: |
| for key, values in per_layer_values.items(): |
| setattr(config, key, resize_layer_sequence(values, new_layer_count)) |
| max_window_layers = getattr(config, "max_window_layers", None) |
| if isinstance(max_window_layers, int): |
| setattr(config, "max_window_layers", min(max_window_layers, new_layer_count)) |
| |
| if isinstance(original_layer_count, int) and original_layer_count > 0: |
| for key, value in list(getattr(config, "__dict__", {}).items()): |
| if key in per_layer_keys: |
| continue |
| if isinstance(value, list) and len(value) == original_layer_count and ("layer" in key or "block" in key or "attention" in key): |
| setattr(config, key, resize_layer_sequence(value, new_layer_count)) |
|
|
| hidden_value = None |
| for key in hidden_keys: |
| value = getattr(config, key, None) |
| if isinstance(value, int) and value >= 64: |
| scaled = round_multiple(value * hidden_scale, 64, 128) |
| setattr(config, key, scaled) |
| hidden_value = scaled |
|
|
| for key in ff_keys: |
| value = getattr(config, key, None) |
| if isinstance(value, int) and value >= 128: |
| setattr(config, key, round_multiple(value * hidden_scale, 128, 256)) |
|
|
| if hidden_value: |
| for key, original in original_heads.items(): |
| setattr(config, key, best_head_count(hidden_value, original)) |
| kv = getattr(config, "num_key_value_heads", None) |
| heads = getattr(config, "num_attention_heads", None) |
| if isinstance(kv, int) and isinstance(heads, int): |
| valid = [value for value in divisors(heads) if value <= kv] |
| setattr(config, "num_key_value_heads", max(valid or [1])) |
| head_dim = getattr(config, "head_dim", None) |
| heads = getattr(config, "num_attention_heads", None) |
| if isinstance(head_dim, int) and isinstance(heads, int) and heads: |
| setattr(config, "head_dim", hidden_value // heads) |
|
|
| for nested_name in ("text_config", "vision_config", "audio_config", "encoder", "decoder"): |
| nested = getattr(config, nested_name, None) |
| if nested is not None and hasattr(nested, "to_dict"): |
| scale_config_object(nested, ratio, {}) |
|
|
| for key, value in overrides.items(): |
| if hasattr(config, key): |
| setattr(config, key, value) |
|
|
| |
| validator = getattr(config, "validate_layer_type", None) |
| if callable(validator): |
| validator() |
| return config.to_dict() if hasattr(config, "to_dict") else {} |
|
|
|
|
| def choose_loader(config: Any, tags: list[str]): |
| import transformers |
|
|
| if bool(getattr(config, "is_encoder_decoder", False)): |
| return getattr(transformers, "AutoModelForSeq2SeqLM") |
| tag_text = " ".join(tags).lower() |
| if any(tag in tag_text for tag in ("image-text-to-text", "any-to-any", "vision-language")): |
| for name in ("AutoModelForMultimodalLM", "AutoModelForImageTextToText", "AutoModelForVision2Seq"): |
| loader = getattr(transformers, name, None) |
| if loader is not None: |
| return loader |
| return getattr(transformers, "AutoModelForCausalLM") |
|
|
|
|
| def copy_processor(source_model: str, output_dir: Path, token: str) -> str | None: |
| for loader in (AutoProcessor, AutoTokenizer): |
| try: |
| processor = loader.from_pretrained(source_model, token=token, trust_remote_code=True) |
| processor.save_pretrained(output_dir) |
| return loader.__name__ |
| except Exception: |
| continue |
| return None |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description="Create a compact initialized child model from a source config") |
| parser.add_argument("--source-model", required=True) |
| parser.add_argument("--output-repo", required=True) |
| parser.add_argument("--target-parameters", type=int, required=True) |
| parser.add_argument("--plan-path", default="training_adapter.json") |
| parser.add_argument("--initialize-weights", action="store_true") |
| parser.add_argument("--private", action="store_true") |
| parser.add_argument("--dry-run", action="store_true") |
| return parser.parse_args() |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| token = os.environ["HF_TOKEN"] |
| api = HfApi(token=token) |
| telemetry = Telemetry().start() |
| try: |
| progress(3, "inventory", "Reading source and AI blueprint") |
| info = api.model_info(args.source_model, token=token) |
| source_params = None |
| safetensors = getattr(info, "safetensors", None) |
| if safetensors and isinstance(getattr(safetensors, "total", None), (int, float)): |
| source_params = int(safetensors.total) |
| try: |
| plan_path = hf_hub_download(args.output_repo, args.plan_path, token=token) |
| plan = json.loads(Path(plan_path).read_text(encoding="utf-8")) |
| except Exception: |
| plan = {} |
| tags = list(info.tags or []) |
| ratio = min(1.0, args.target_parameters / source_params) if source_params else 0.25 |
| progress(15, "configuration", f"Target ratio {ratio:.3f}") |
|
|
| api.create_repo(args.output_repo, repo_type="model", private=args.private, exist_ok=True, token=token) |
| with __import__("tempfile").TemporaryDirectory() as tmp: |
| output_dir = Path(tmp) / "child" |
| output_dir.mkdir(parents=True) |
| build: dict[str, Any] = { |
| "source_model": args.source_model, |
| "source_parameters": source_params, |
| "target_parameters": args.target_parameters, |
| "ratio": ratio, |
| "initialized": False, |
| "processor": None, |
| "loader": None, |
| "status": "scaffold", |
| "errors": [], |
| } |
| config = None |
| try: |
| config = AutoConfig.from_pretrained(args.source_model, token=token, trust_remote_code=True) |
| overrides = ((plan.get("child") or {}).get("config_overrides") or {}) if isinstance(plan, dict) else {} |
| scaled = scale_config_object(config, ratio, overrides) |
| config.save_pretrained(output_dir) |
| (output_dir / "scaled_config.json").write_text(json.dumps(scaled, indent=2), encoding="utf-8") |
| build["status"] = "configured" |
| except Exception as exc: |
| build["errors"].append(f"config: {exc}") |
| (output_dir / "child_blueprint.json").write_text(json.dumps({ |
| "source_model": args.source_model, |
| "target_parameters": args.target_parameters, |
| "plan": plan, |
| "note": "Source does not expose a standard Transformers config. Use the generated TrainingAdapter/custom entrypoint.", |
| }, indent=2), encoding="utf-8") |
|
|
| progress(35, "processor", "Copying tokenizer/processor") |
| build["processor"] = copy_processor(args.source_model, output_dir, token) |
|
|
| if args.dry_run: |
| progress(80, "dry-run", "Architecture validation complete") |
| elif args.initialize_weights and config is not None: |
| progress(45, "initialization", "Creating compact random-initialized weights") |
| try: |
| loader = choose_loader(config, tags) |
| build["loader"] = loader.__name__ |
| model = loader.from_config(config, trust_remote_code=True) |
| model.save_pretrained(output_dir, safe_serialization=True, max_shard_size="3GB") |
| build["initialized"] = True |
| build["status"] = "initialized" |
| del model |
| if torch.cuda.is_available(): |
| torch.cuda.empty_cache() |
| except Exception as exc: |
| build["errors"].append(f"weights: {exc}") |
| build["status"] = "configured" |
|
|
| (output_dir / "child_build.json").write_text(json.dumps(build, indent=2), encoding="utf-8") |
| progress(88, "publish", "Uploading child architecture") |
| api.upload_folder( |
| folder_path=output_dir, |
| repo_id=args.output_repo, |
| repo_type="model", |
| token=token, |
| commit_message="Create distilled child architecture", |
| ) |
| progress(100, "completed", f"Child repository ready: {args.output_repo}") |
| finally: |
| telemetry.stop() |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|