File size: 15,215 Bytes
53aa26f f8909cf 53aa26f f8909cf 53aa26f f8909cf 53aa26f f8909cf 53aa26f f8909cf 53aa26f f8909cf 53aa26f | 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 337 338 339 340 341 342 343 344 | # /// script
# requires-python = ">=3.11"
# dependencies = [
# "torch>=2.6",
# "transformers>=5.0.0",
# "huggingface-hub>=1.0",
# "safetensors>=0.5",
# "psutil>=6",
# "nvidia-ml-py>=12; platform_system == 'Linux'",
# ]
# ///
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))
# Some hybrid architectures keep additional lists not known in advance.
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)
# Re-run generic validators before publishing instead of discovering errors at load time.
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()
|