patdev commited on
Commit
53aa26f
·
verified ·
1 Parent(s): 645277b

Add compact child creation Job

Browse files
Files changed (1) hide show
  1. create_child_job.py +301 -0
create_child_job.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "torch>=2.6",
5
+ # "transformers>=5.0.0",
6
+ # "huggingface-hub>=1.0",
7
+ # "safetensors>=0.5",
8
+ # "psutil>=6",
9
+ # "nvidia-ml-py>=12; platform_system == 'Linux'",
10
+ # ]
11
+ # ///
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import copy
16
+ import json
17
+ import math
18
+ import os
19
+ import threading
20
+ import time
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ import psutil
25
+ import torch
26
+ from huggingface_hub import HfApi, hf_hub_download
27
+ from transformers import AutoConfig, AutoProcessor, AutoTokenizer
28
+
29
+
30
+ class Telemetry:
31
+ def __init__(self, interval: float = 2.0):
32
+ self.interval = interval
33
+ self.stop_event = threading.Event()
34
+ self.thread = threading.Thread(target=self.run, daemon=True)
35
+
36
+ def start(self):
37
+ self.thread.start()
38
+ return self
39
+
40
+ def stop(self):
41
+ self.stop_event.set()
42
+ self.thread.join(timeout=3)
43
+
44
+ def run(self):
45
+ psutil.cpu_percent(interval=None)
46
+ while not self.stop_event.wait(self.interval):
47
+ memory = psutil.virtual_memory()
48
+ payload: dict[str, Any] = {
49
+ "event": "telemetry",
50
+ "timestamp": time.time(),
51
+ "cpu_percent": psutil.cpu_percent(interval=None),
52
+ "ram_used_gb": round((memory.total - memory.available) / 1024**3, 3),
53
+ "ram_total_gb": round(memory.total / 1024**3, 3),
54
+ "ram_percent": memory.percent,
55
+ "gpu_count": 0,
56
+ "gpu_name": None,
57
+ "gpu_util_percent": None,
58
+ "vram_used_gb": None,
59
+ "vram_total_gb": None,
60
+ "vram_percent": None,
61
+ "gpu_temperature_c": None,
62
+ }
63
+ try:
64
+ import pynvml
65
+ pynvml.nvmlInit()
66
+ count = pynvml.nvmlDeviceGetCount()
67
+ utils, used, total, temps, names = [], 0, 0, [], []
68
+ for index in range(count):
69
+ handle = pynvml.nvmlDeviceGetHandleByIndex(index)
70
+ util = pynvml.nvmlDeviceGetUtilizationRates(handle)
71
+ mem = pynvml.nvmlDeviceGetMemoryInfo(handle)
72
+ name = pynvml.nvmlDeviceGetName(handle)
73
+ names.append(name.decode() if isinstance(name, bytes) else str(name))
74
+ utils.append(float(util.gpu)); used += int(mem.used); total += int(mem.total)
75
+ try: temps.append(float(pynvml.nvmlDeviceGetTemperature(handle, pynvml.NVML_TEMPERATURE_GPU)))
76
+ except Exception: pass
77
+ payload.update({
78
+ "gpu_count": count,
79
+ "gpu_name": " + ".join(names) if names else None,
80
+ "gpu_util_percent": round(sum(utils) / len(utils), 1) if utils else None,
81
+ "vram_used_gb": round(used / 1024**3, 3) if total else None,
82
+ "vram_total_gb": round(total / 1024**3, 3) if total else None,
83
+ "vram_percent": round(100 * used / total, 1) if total else None,
84
+ "gpu_temperature_c": round(sum(temps) / len(temps), 1) if temps else None,
85
+ })
86
+ pynvml.nvmlShutdown()
87
+ except Exception:
88
+ pass
89
+ print(json.dumps(payload), flush=True)
90
+
91
+
92
+ def progress(percent: int, stage: str, message: str = "") -> None:
93
+ print(json.dumps({"event": "progress", "percent": percent, "stage": stage, "message": message}), flush=True)
94
+ print(f"{percent}% · {stage} · {message}", flush=True)
95
+
96
+
97
+ def round_multiple(value: float, multiple: int, minimum: int) -> int:
98
+ return max(minimum, int(round(value / multiple) * multiple))
99
+
100
+
101
+ def divisors(value: int) -> list[int]:
102
+ result = []
103
+ for item in range(1, int(math.sqrt(value)) + 1):
104
+ if value % item == 0:
105
+ result.extend([item, value // item])
106
+ return sorted(set(result))
107
+
108
+
109
+ def best_head_count(hidden_size: int, original: int) -> int:
110
+ choices = [value for value in divisors(hidden_size) if value <= max(1, original)]
111
+ target = min(max(1, original), max(1, hidden_size // 64))
112
+ return min(choices or [1], key=lambda value: abs(value - target))
113
+
114
+
115
+ def scale_config_object(config: Any, ratio: float, overrides: dict[str, Any] | None = None) -> dict[str, Any]:
116
+ """Scale common Transformer dimensions in-place while preserving tokenizer/task heads."""
117
+ overrides = overrides or {}
118
+ layer_scale = max(0.18, min(1.0, ratio ** 0.40))
119
+ hidden_scale = max(0.22, min(1.0, ratio ** 0.30))
120
+
121
+ layer_keys = ["num_hidden_layers", "n_layer", "num_layers", "encoder_layers", "decoder_layers", "num_decoder_layers"]
122
+ hidden_keys = ["hidden_size", "d_model", "n_embd", "model_dim"]
123
+ ff_keys = ["intermediate_size", "d_ff", "ffn_dim", "encoder_ffn_dim", "decoder_ffn_dim"]
124
+ head_keys = ["num_attention_heads", "n_head", "encoder_attention_heads", "decoder_attention_heads"]
125
+
126
+ original_heads: dict[str, int] = {}
127
+ for key in head_keys:
128
+ value = getattr(config, key, None)
129
+ if isinstance(value, int) and value > 0:
130
+ original_heads[key] = value
131
+
132
+ for key in layer_keys:
133
+ value = getattr(config, key, None)
134
+ if isinstance(value, int) and value > 1:
135
+ setattr(config, key, max(2, int(round(value * layer_scale))))
136
+
137
+ hidden_value = None
138
+ for key in hidden_keys:
139
+ value = getattr(config, key, None)
140
+ if isinstance(value, int) and value >= 64:
141
+ scaled = round_multiple(value * hidden_scale, 64, 128)
142
+ setattr(config, key, scaled)
143
+ hidden_value = scaled
144
+
145
+ for key in ff_keys:
146
+ value = getattr(config, key, None)
147
+ if isinstance(value, int) and value >= 128:
148
+ setattr(config, key, round_multiple(value * hidden_scale, 128, 256))
149
+
150
+ if hidden_value:
151
+ for key, original in original_heads.items():
152
+ setattr(config, key, best_head_count(hidden_value, original))
153
+ kv = getattr(config, "num_key_value_heads", None)
154
+ heads = getattr(config, "num_attention_heads", None)
155
+ if isinstance(kv, int) and isinstance(heads, int):
156
+ valid = [value for value in divisors(heads) if value <= kv]
157
+ setattr(config, "num_key_value_heads", max(valid or [1]))
158
+ head_dim = getattr(config, "head_dim", None)
159
+ heads = getattr(config, "num_attention_heads", None)
160
+ if isinstance(head_dim, int) and isinstance(heads, int) and heads:
161
+ setattr(config, "head_dim", hidden_value // heads)
162
+
163
+ for nested_name in ("text_config", "vision_config", "audio_config", "encoder", "decoder"):
164
+ nested = getattr(config, nested_name, None)
165
+ if nested is not None and hasattr(nested, "to_dict"):
166
+ scale_config_object(nested, ratio, {})
167
+
168
+ for key, value in overrides.items():
169
+ if hasattr(config, key):
170
+ setattr(config, key, value)
171
+
172
+ return config.to_dict() if hasattr(config, "to_dict") else {}
173
+
174
+
175
+ def choose_loader(config: Any, tags: list[str]):
176
+ import transformers
177
+
178
+ if bool(getattr(config, "is_encoder_decoder", False)):
179
+ return getattr(transformers, "AutoModelForSeq2SeqLM")
180
+ tag_text = " ".join(tags).lower()
181
+ if any(tag in tag_text for tag in ("image-text-to-text", "any-to-any", "vision-language")):
182
+ for name in ("AutoModelForMultimodalLM", "AutoModelForImageTextToText", "AutoModelForVision2Seq"):
183
+ loader = getattr(transformers, name, None)
184
+ if loader is not None:
185
+ return loader
186
+ return getattr(transformers, "AutoModelForCausalLM")
187
+
188
+
189
+ def copy_processor(source_model: str, output_dir: Path, token: str) -> str | None:
190
+ for loader in (AutoProcessor, AutoTokenizer):
191
+ try:
192
+ processor = loader.from_pretrained(source_model, token=token, trust_remote_code=True)
193
+ processor.save_pretrained(output_dir)
194
+ return loader.__name__
195
+ except Exception:
196
+ continue
197
+ return None
198
+
199
+
200
+ def parse_args() -> argparse.Namespace:
201
+ parser = argparse.ArgumentParser(description="Create a compact initialized child model from a source config")
202
+ parser.add_argument("--source-model", required=True)
203
+ parser.add_argument("--output-repo", required=True)
204
+ parser.add_argument("--target-parameters", type=int, required=True)
205
+ parser.add_argument("--plan-path", default="training_adapter.json")
206
+ parser.add_argument("--initialize-weights", action="store_true")
207
+ parser.add_argument("--private", action="store_true")
208
+ parser.add_argument("--dry-run", action="store_true")
209
+ return parser.parse_args()
210
+
211
+
212
+ def main() -> None:
213
+ args = parse_args()
214
+ token = os.environ["HF_TOKEN"]
215
+ api = HfApi(token=token)
216
+ telemetry = Telemetry().start()
217
+ try:
218
+ progress(3, "inventory", "Reading source and AI blueprint")
219
+ info = api.model_info(args.source_model, token=token)
220
+ source_params = None
221
+ safetensors = getattr(info, "safetensors", None)
222
+ if safetensors and isinstance(getattr(safetensors, "total", None), (int, float)):
223
+ source_params = int(safetensors.total)
224
+ try:
225
+ plan_path = hf_hub_download(args.output_repo, args.plan_path, token=token)
226
+ plan = json.loads(Path(plan_path).read_text(encoding="utf-8"))
227
+ except Exception:
228
+ plan = {}
229
+ tags = list(info.tags or [])
230
+ ratio = min(1.0, args.target_parameters / source_params) if source_params else 0.25
231
+ progress(15, "configuration", f"Target ratio {ratio:.3f}")
232
+
233
+ api.create_repo(args.output_repo, repo_type="model", private=args.private, exist_ok=True, token=token)
234
+ with __import__("tempfile").TemporaryDirectory() as tmp:
235
+ output_dir = Path(tmp) / "child"
236
+ output_dir.mkdir(parents=True)
237
+ build: dict[str, Any] = {
238
+ "source_model": args.source_model,
239
+ "source_parameters": source_params,
240
+ "target_parameters": args.target_parameters,
241
+ "ratio": ratio,
242
+ "initialized": False,
243
+ "processor": None,
244
+ "loader": None,
245
+ "status": "scaffold",
246
+ "errors": [],
247
+ }
248
+ config = None
249
+ try:
250
+ config = AutoConfig.from_pretrained(args.source_model, token=token, trust_remote_code=True)
251
+ overrides = ((plan.get("child") or {}).get("config_overrides") or {}) if isinstance(plan, dict) else {}
252
+ scaled = scale_config_object(config, ratio, overrides)
253
+ config.save_pretrained(output_dir)
254
+ (output_dir / "scaled_config.json").write_text(json.dumps(scaled, indent=2), encoding="utf-8")
255
+ build["status"] = "configured"
256
+ except Exception as exc:
257
+ build["errors"].append(f"config: {exc}")
258
+ (output_dir / "child_blueprint.json").write_text(json.dumps({
259
+ "source_model": args.source_model,
260
+ "target_parameters": args.target_parameters,
261
+ "plan": plan,
262
+ "note": "Source does not expose a standard Transformers config. Use the generated TrainingAdapter/custom entrypoint.",
263
+ }, indent=2), encoding="utf-8")
264
+
265
+ progress(35, "processor", "Copying tokenizer/processor")
266
+ build["processor"] = copy_processor(args.source_model, output_dir, token)
267
+
268
+ if args.dry_run:
269
+ progress(80, "dry-run", "Architecture validation complete")
270
+ elif args.initialize_weights and config is not None:
271
+ progress(45, "initialization", "Creating compact random-initialized weights")
272
+ try:
273
+ loader = choose_loader(config, tags)
274
+ build["loader"] = loader.__name__
275
+ model = loader.from_config(config, trust_remote_code=True)
276
+ model.save_pretrained(output_dir, safe_serialization=True, max_shard_size="3GB")
277
+ build["initialized"] = True
278
+ build["status"] = "initialized"
279
+ del model
280
+ if torch.cuda.is_available():
281
+ torch.cuda.empty_cache()
282
+ except Exception as exc:
283
+ build["errors"].append(f"weights: {exc}")
284
+ build["status"] = "configured"
285
+
286
+ (output_dir / "child_build.json").write_text(json.dumps(build, indent=2), encoding="utf-8")
287
+ progress(88, "publish", "Uploading child architecture")
288
+ api.upload_folder(
289
+ folder_path=output_dir,
290
+ repo_id=args.output_repo,
291
+ repo_type="model",
292
+ token=token,
293
+ commit_message="Create distilled child architecture",
294
+ )
295
+ progress(100, "completed", f"Child repository ready: {args.output_repo}")
296
+ finally:
297
+ telemetry.stop()
298
+
299
+
300
+ if __name__ == "__main__":
301
+ main()