File size: 33,838 Bytes
37c6b3b 645277b 37c6b3b 5239f72 37c6b3b 645277b 37c6b3b 5239f72 37c6b3b 5239f72 37c6b3b 645277b 1fa286b 645277b 1fa286b 645277b 1fa286b 645277b 1fa286b 645277b 1fa286b 645277b 1fa286b 645277b 37c6b3b 9df2674 37c6b3b 9df2674 1fa286b 9df2674 1fa286b 37c6b3b 1fa286b 37c6b3b 9df2674 1fa286b 37c6b3b 1fa286b 37c6b3b 9df2674 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 9df2674 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 9df2674 1fa286b 37c6b3b 1fa286b 37c6b3b 9df2674 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 9df2674 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 9df2674 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 9df2674 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 9df2674 1fa286b 6ae8476 1fa286b 6ae8476 1fa286b 9df2674 1fa286b 6ae8476 1fa286b 6ae8476 1fa286b 6ae8476 1fa286b 6ae8476 1fa286b 6ae8476 9df2674 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 9df2674 1fa286b 37c6b3b 9df2674 37c6b3b 1fa286b 9df2674 1fa286b 9df2674 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 9df2674 1fa286b 37c6b3b 5239f72 1fa286b 5239f72 1fa286b 5239f72 1fa286b 5239f72 1fa286b 5239f72 9df2674 5239f72 1fa286b 5239f72 1fa286b 9df2674 1fa286b 5239f72 1fa286b 5239f72 1fa286b 9df2674 1fa286b 5239f72 37c6b3b 1fa286b 9df2674 1fa286b 37c6b3b 1fa286b 9df2674 5239f72 1fa286b 9df2674 1fa286b 9df2674 1fa286b 9df2674 1fa286b 37c6b3b 1fa286b 37c6b3b 1fa286b 9df2674 1fa286b | 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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 | # /// script
# requires-python = ">=3.11"
# dependencies = [
# "torch>=2.6",
# "transformers>=5.0.0",
# "datasets>=4.0",
# "accelerate>=1.10",
# "peft>=0.17",
# "bitsandbytes>=0.46; platform_system == 'Linux'",
# "pillow>=11",
# "huggingface-hub>=1.0",
# "psutil>=6.0",
# "nvidia-ml-py>=12.560",
# "safetensors>=0.5",
# "pyyaml>=6",
# "timm>=1.0",
# ]
# ///
from __future__ import annotations
import argparse
import atexit
import threading
import time
import psutil
import inspect
import json
import os
import re
import subprocess
import tempfile
from abc import ABC, abstractmethod
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
import torch
from datasets import Dataset, load_dataset
from huggingface_hub import HfApi, snapshot_download
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from transformers import (
AutoConfig,
AutoModelForCausalLM,
AutoModelForSeq2SeqLM,
AutoProcessor,
AutoTokenizer,
BitsAndBytesConfig,
DataCollatorForLanguageModeling,
DataCollatorForSeq2Seq,
Trainer,
TrainingArguments,
)
class TelemetryReporter:
"""Emit machine-readable host and accelerator utilization for the Gradio monitor."""
def __init__(self, interval: float = 2.0):
self.interval = interval
self.stop_event = threading.Event()
self.thread = threading.Thread(target=self._run, name="generic-trainer-telemetry", daemon=True)
self.nvml = None
try:
import pynvml
pynvml.nvmlInit()
self.nvml = pynvml
except Exception:
self.nvml = None
def start(self) -> None:
psutil.cpu_percent(interval=None)
self.thread.start()
atexit.register(self.stop)
def stop(self) -> None:
self.stop_event.set()
if self.thread.is_alive() and threading.current_thread() is not self.thread:
self.thread.join(timeout=1.0)
if self.nvml is not None:
try:
self.nvml.nvmlShutdown()
except Exception:
pass
def _gpu_sample(self) -> dict[str, object]:
if self.nvml is not None:
count = self.nvml.nvmlDeviceGetCount()
names, utils, used, total, temperatures = [], [], 0, 0, []
for index in range(count):
handle = self.nvml.nvmlDeviceGetHandleByIndex(index)
name = self.nvml.nvmlDeviceGetName(handle)
names.append(name.decode() if isinstance(name, bytes) else str(name))
memory = self.nvml.nvmlDeviceGetMemoryInfo(handle)
used += int(memory.used); total += int(memory.total)
try:
utils.append(float(self.nvml.nvmlDeviceGetUtilizationRates(handle).gpu))
except Exception:
pass
try:
temperatures.append(float(self.nvml.nvmlDeviceGetTemperature(handle, self.nvml.NVML_TEMPERATURE_GPU)))
except Exception:
pass
return {
"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(used * 100 / total, 1) if total else None,
"gpu_temperature_c": round(max(temperatures), 1) if temperatures else None,
}
if torch.cuda.is_available():
free, total = torch.cuda.mem_get_info()
used = total - free
return {
"gpu_count": torch.cuda.device_count(),
"gpu_name": " · ".join(torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())),
"gpu_util_percent": None,
"vram_used_gb": round(used / 1024**3, 3),
"vram_total_gb": round(total / 1024**3, 3),
"vram_percent": round(used * 100 / total, 1) if total else None,
"gpu_temperature_c": None,
}
return {"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}
def sample(self) -> dict[str, object]:
memory = psutil.virtual_memory()
payload: dict[str, object] = {
"event": "telemetry",
"timestamp": time.time(),
"cpu_percent": round(psutil.cpu_percent(interval=None), 1),
"ram_used_gb": round((memory.total - memory.available) / 1024**3, 3),
"ram_total_gb": round(memory.total / 1024**3, 3),
"ram_percent": round(float(memory.percent), 1),
}
payload.update(self._gpu_sample())
return payload
def _run(self) -> None:
while not self.stop_event.is_set():
try:
print(json.dumps(self.sample(), ensure_ascii=False), flush=True)
except Exception as exc:
print(json.dumps({"event": "telemetry_error", "message": str(exc)}), flush=True)
self.stop_event.wait(self.interval)
def start_telemetry() -> TelemetryReporter:
reporter = TelemetryReporter()
reporter.start()
return reporter
@dataclass(slots=True)
class RuntimePlan:
runtime_id: str
modality: str
model_loader: str
processor_loader: str
default_method: str
notes: list[str]
class ModelRuntime(ABC):
"""Runtime adapter contract used by every training family."""
runtime_id: str
@classmethod
@abstractmethod
def score(cls, model_id: str, config: Any, tags: list[str]) -> int: ...
@classmethod
@abstractmethod
def plan(cls, model_id: str, config: Any) -> RuntimePlan: ...
@abstractmethod
def load(self, args: argparse.Namespace, quantization_config: BitsAndBytesConfig | None): ...
@abstractmethod
def build_trainer(self, args: argparse.Namespace, model: Any, processor: Any, train: Dataset, validation: Dataset | None, output_dir: Path) -> Trainer: ...
class TextRuntimeBase(ModelRuntime):
seq2seq = False
def _render(self, row: dict[str, Any], tokenizer: Any, args: argparse.Namespace) -> str:
messages = row.get(args.messages_column) if args.messages_column else None
if isinstance(messages, list) and hasattr(tokenizer, "apply_chat_template"):
return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
text = row.get(args.text_column) if args.text_column else None
if text not in (None, ""):
return str(text)
prompt = str(row.get(args.prompt_column, "")) if args.prompt_column else ""
response = str(row.get(args.response_column, "")) if args.response_column else ""
if response:
return f"{prompt}\n{response}".strip()
return prompt
def build_trainer(self, args, model, tokenizer, train, validation, output_dir):
max_length = int(args.max_length)
if self.seq2seq:
def tokenize_batch(batch):
prompts = [str(value or "") for value in batch[args.prompt_column]]
targets = [str(value or "") for value in batch[args.response_column]]
encoded = tokenizer(prompts, max_length=max_length, truncation=True)
encoded["labels"] = tokenizer(text_target=targets, max_length=max_length, truncation=True)["input_ids"]
return encoded
else:
def tokenize_batch(batch):
rows = [{key: batch[key][i] for key in batch} for i in range(len(next(iter(batch.values()))))]
texts = [self._render(row, tokenizer, args) for row in rows]
encoded = tokenizer(texts, max_length=max_length, truncation=True, padding=False)
encoded["labels"] = [list(ids) for ids in encoded["input_ids"]]
return encoded
remove_columns = train.column_names
tokenized_train = train.map(tokenize_batch, batched=True, remove_columns=remove_columns, desc="Tokenizing train split")
tokenized_validation = None
if validation is not None:
tokenized_validation = validation.map(tokenize_batch, batched=True, remove_columns=validation.column_names, desc="Tokenizing validation split")
collator = DataCollatorForSeq2Seq(tokenizer, model=model) if self.seq2seq else DataCollatorForLanguageModeling(tokenizer, mlm=False)
return Trainer(
model=model,
args=training_arguments(args, output_dir, tokenized_validation is not None),
train_dataset=tokenized_train,
eval_dataset=tokenized_validation,
data_collator=collator,
)
class CausalLMRuntime(TextRuntimeBase):
runtime_id = "causal-lm"
@classmethod
def score(cls, model_id, config, tags):
architectures = " ".join(getattr(config, "architectures", []) or []).lower()
return 35 if "causallm" in architectures or "text-generation" in " ".join(tags).lower() else 10
@classmethod
def plan(cls, model_id, config):
return RuntimePlan(cls.runtime_id, "text/chat", "AutoModelForCausalLM", "AutoTokenizer", "lora", [])
def load(self, args, quantization_config):
tokenizer = AutoTokenizer.from_pretrained(args.model_id, token=os.environ["HF_TOKEN"], trust_remote_code=args.trust_remote_code)
if tokenizer.pad_token_id is None:
tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained(
args.model_id,
token=os.environ["HF_TOKEN"],
trust_remote_code=args.trust_remote_code,
torch_dtype="auto",
device_map="auto" if torch.cuda.is_available() else None,
quantization_config=quantization_config,
)
return model, tokenizer
class Seq2SeqRuntime(TextRuntimeBase):
runtime_id = "seq2seq"
seq2seq = True
@classmethod
def score(cls, model_id, config, tags):
return 50 if bool(getattr(config, "is_encoder_decoder", False)) else 0
@classmethod
def plan(cls, model_id, config):
return RuntimePlan(cls.runtime_id, "text-to-text", "AutoModelForSeq2SeqLM", "AutoTokenizer", "lora", [])
def load(self, args, quantization_config):
tokenizer = AutoTokenizer.from_pretrained(args.model_id, token=os.environ["HF_TOKEN"], trust_remote_code=args.trust_remote_code)
model = AutoModelForSeq2SeqLM.from_pretrained(
args.model_id,
token=os.environ["HF_TOKEN"],
trust_remote_code=args.trust_remote_code,
torch_dtype="auto",
device_map="auto" if torch.cuda.is_available() else None,
quantization_config=quantization_config,
)
return model, tokenizer
class MultimodalCollator:
def __init__(self, processor: Any, args: argparse.Namespace):
self.processor = processor
self.args = args
def _text(self, row: dict[str, Any]) -> str:
messages = row.get(self.args.messages_column) if self.args.messages_column else None
if isinstance(messages, list) and hasattr(self.processor, "apply_chat_template"):
return self.processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
prompt = str(row.get(self.args.prompt_column, "")) if self.args.prompt_column else ""
response = str(row.get(self.args.response_column, "")) if self.args.response_column else ""
text = str(row.get(self.args.text_column, "")) if self.args.text_column else ""
return text or (f"{prompt}\n{response}".strip())
def __call__(self, rows: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
texts = [self._text(row) for row in rows]
images = None
if self.args.image_column and self.args.image_column in rows[0]:
images = [row.get(self.args.image_column) for row in rows]
kwargs: dict[str, Any] = {"text": texts, "padding": True, "truncation": True, "max_length": self.args.max_length, "return_tensors": "pt"}
if images is not None and any(image is not None for image in images):
kwargs["images"] = images
batch = self.processor(**kwargs)
if "input_ids" in batch:
labels = batch["input_ids"].clone()
pad_id = getattr(getattr(self.processor, "tokenizer", None), "pad_token_id", None)
if pad_id is not None:
labels[labels == pad_id] = -100
batch["labels"] = labels
return batch
class VisionLanguageRuntime(ModelRuntime):
runtime_id = "vision-language"
@classmethod
def score(cls, model_id, config, tags):
haystack = " ".join([model_id, getattr(config, "model_type", ""), *(getattr(config, "architectures", []) or []), *tags]).lower()
return 70 if any(term in haystack for term in ("image-text-to-text", "vision", "multimodal", "any-to-any")) else 0
@classmethod
def plan(cls, model_id, config):
return RuntimePlan(cls.runtime_id, "text+image", "Auto multimodal model", "AutoProcessor", "lora", [])
def _model_class(self):
import transformers
for name in ("AutoModelForMultimodalLM", "AutoModelForImageTextToText", "AutoModelForVision2Seq"):
candidate = getattr(transformers, name, None)
if candidate is not None:
return candidate
raise RuntimeError("This Transformers version has no multimodal auto-model class.")
def load(self, args, quantization_config):
processor = AutoProcessor.from_pretrained(args.model_id, token=os.environ["HF_TOKEN"], trust_remote_code=args.trust_remote_code)
model = self._model_class().from_pretrained(
args.model_id,
token=os.environ["HF_TOKEN"],
trust_remote_code=args.trust_remote_code,
torch_dtype="auto",
device_map="auto" if torch.cuda.is_available() else None,
quantization_config=quantization_config,
)
return model, processor
def build_trainer(self, args, model, processor, train, validation, output_dir):
return Trainer(
model=model,
args=training_arguments(args, output_dir, validation is not None),
train_dataset=train,
eval_dataset=validation,
data_collator=MultimodalCollator(processor, args),
)
class UnlimitedOCRNanoRuntime(VisionLanguageRuntime):
runtime_id = "unlimited-ocr-nano"
@classmethod
def score(cls, model_id, config, tags):
haystack = " ".join([model_id, getattr(config, "model_type", ""), *(getattr(config, "architectures", []) or []), *tags]).lower()
return 95 if "unlimited-ocr-nano" in haystack else 0
@classmethod
def plan(cls, model_id, config):
return RuntimePlan(
cls.runtime_id,
"document image → structured text",
"AutoModel / custom trust_remote_code architecture",
"AutoProcessor",
"projector",
[
"Uses the model repository's custom processor and model code.",
"Projector mode trains the multimodal projector while keeping backbone weights frozen when supported.",
"Expected dataset columns are image plus text/target or prompt/response.",
],
)
def _model_class(self):
from transformers import AutoModel
return AutoModel
def load(self, args, quantization_config):
processor = AutoProcessor.from_pretrained(args.model_id, token=os.environ["HF_TOKEN"], trust_remote_code=True)
model = self._model_class().from_pretrained(
args.model_id,
token=os.environ["HF_TOKEN"],
trust_remote_code=True,
torch_dtype="auto",
device_map="auto" if torch.cuda.is_available() else None,
quantization_config=quantization_config,
)
if args.method == "projector":
if hasattr(model, "freeze_language_model"):
model.freeze_language_model()
if hasattr(model, "freeze_vision_encoder"):
model.freeze_vision_encoder()
if hasattr(model, "unfreeze_projector"):
model.unfreeze_projector()
else:
for name, parameter in model.named_parameters():
parameter.requires_grad = any(key in name.lower() for key in ("projector", "multimodal_projector", "vision_projector"))
return model, processor
class Gemma4Runtime(VisionLanguageRuntime):
runtime_id = "gemma4"
@classmethod
def score(cls, model_id, config, tags):
haystack = " ".join([model_id, getattr(config, "model_type", ""), *(getattr(config, "architectures", []) or []), *tags]).lower()
return 100 if "gemma4" in haystack or "gemma-4" in haystack else 0
@classmethod
def plan(cls, model_id, config):
return RuntimePlan(
cls.runtime_id,
"Gemma 4 any-to-any / image-text",
"AutoModelForMultimodalLM",
"AutoProcessor",
"qlora",
["Text and image-conditioned SFT are enabled.", "Accept Gemma model terms before launching."],
)
RUNTIMES: list[type[ModelRuntime]] = [Gemma4Runtime, UnlimitedOCRNanoRuntime, Seq2SeqRuntime, VisionLanguageRuntime, CausalLMRuntime]
def choose_runtime(runtime_id: str, model_id: str, config: Any, tags: list[str]) -> ModelRuntime:
if runtime_id != "auto":
for adapter in RUNTIMES:
if adapter.runtime_id == runtime_id:
return adapter()
raise ValueError(f"Unknown adapter {runtime_id}")
selected = max(RUNTIMES, key=lambda adapter: adapter.score(model_id, config, tags))
return selected()
def training_arguments(args: argparse.Namespace, output_dir: Path, has_eval: bool) -> TrainingArguments:
kwargs = dict(
output_dir=str(output_dir),
per_device_train_batch_size=args.batch_size,
per_device_eval_batch_size=max(1, args.batch_size),
gradient_accumulation_steps=args.gradient_accumulation,
learning_rate=args.learning_rate,
num_train_epochs=args.epochs,
max_steps=args.max_steps,
warmup_ratio=args.warmup_ratio,
weight_decay=args.weight_decay,
logging_steps=args.logging_steps,
save_steps=args.save_steps,
save_total_limit=2,
fp16=args.precision == "fp16",
bf16=args.precision == "bf16",
gradient_checkpointing=args.gradient_checkpointing,
remove_unused_columns=False,
report_to=[],
prediction_loss_only=True,
seed=args.seed,
)
signature = inspect.signature(TrainingArguments)
if "eval_strategy" in signature.parameters:
kwargs["eval_strategy"] = "steps" if has_eval else "no"
elif "evaluation_strategy" in signature.parameters:
kwargs["evaluation_strategy"] = "steps" if has_eval else "no"
if has_eval:
kwargs["eval_steps"] = args.eval_steps
return TrainingArguments(**kwargs)
def quantization(method: str) -> BitsAndBytesConfig | None:
if method != "qlora":
return None
if not torch.cuda.is_available():
raise RuntimeError("QLoRA requires a CUDA GPU.")
compute_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
return BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=compute_dtype)
def apply_peft(model: Any, args: argparse.Namespace) -> Any:
if args.method not in {"lora", "qlora"}:
return model
if args.method == "qlora":
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=args.gradient_checkpointing)
config = LoraConfig(
r=args.lora_rank,
lora_alpha=args.lora_alpha,
lora_dropout=args.lora_dropout,
bias="none",
target_modules="all-linear",
task_type="SEQ_2_SEQ_LM" if args.runtime_family == "seq2seq" else "CAUSAL_LM",
)
return get_peft_model(model, config)
def _pick_ocr_file(files: list[str], explicit: str, candidates: list[str]) -> str:
if explicit:
if explicit not in files:
raise FileNotFoundError(f"Dataset file not found: {explicit}")
return explicit
for candidate in candidates:
if candidate in files:
return candidate
raise FileNotFoundError(f"No compatible OCR JSONL found. Tried: {candidates}")
def _subset_jsonl(source: Path, limit: int) -> Path:
if limit <= 0:
return source
destination = source.with_name(f"{source.stem}.subset-{limit}{source.suffix}")
lines = []
with source.open("r", encoding="utf-8", errors="replace") as handle:
for index, line in enumerate(handle):
if index >= limit:
break
lines.append(line)
destination.write_text("".join(lines), encoding="utf-8")
return destination
def run_unlimited_ocr_nano(args: argparse.Namespace, token: str, plan: RuntimePlan) -> None:
import yaml
api = HfApi(token=token)
files = api.list_repo_files(args.dataset_id, repo_type="dataset", token=token)
train_file = _pick_ocr_file(
files,
args.train_file,
["teacher/train.jsonl", f"{args.train_split}.jsonl", "train.jsonl"],
)
validation_file = ""
if args.validation_file:
validation_file = _pick_ocr_file(files, args.validation_file, [])
else:
for candidate in ["teacher/validation.jsonl", "validation.jsonl"]:
if candidate in files:
validation_file = candidate
break
print(json.dumps({
"event": "runtime",
**asdict(plan),
"train_file": train_file,
"validation_file": validation_file or None,
}, ensure_ascii=False), flush=True)
if args.dry_run:
print("100% · Unlimited OCR Nano dry-run validation completed", flush=True)
return
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
project = Path(snapshot_download(
args.model_id,
repo_type="model",
token=token,
local_dir=root / "project",
allow_patterns=["src/**", "scripts/train.py", "configs/**", "pyproject.toml", "README.md"],
))
patterns = [train_file, "pages/**"]
if validation_file:
patterns.append(validation_file)
dataset = Path(snapshot_download(
args.dataset_id,
repo_type="dataset",
token=token,
local_dir=root / "dataset",
allow_patterns=patterns,
max_workers=64,
))
train_path = _subset_jsonl(dataset / train_file, args.max_samples)
validation_path = dataset / validation_file if validation_file else None
base_name = "nano-600m-alignment.yaml" if args.method == "projector" else "nano-600m-distill.yaml"
base_path = project / "configs" / base_name
if not base_path.exists():
available = sorted(path.name for path in (project / "configs").glob("*.yaml"))
raise FileNotFoundError(f"Missing {base_name}; available configs: {available}")
config = yaml.safe_load(base_path.read_text(encoding="utf-8"))
training = config.setdefault("training", {})
training.update({
"max_length": int(args.max_length),
"batch_size": int(args.batch_size),
"gradient_accumulation_steps": int(args.gradient_accumulation),
"learning_rate": float(args.learning_rate),
"epochs": float(args.epochs),
"max_steps": int(args.max_steps),
"warmup_ratio": float(args.warmup_ratio),
"weight_decay": float(args.weight_decay),
"logging_steps": int(args.logging_steps),
"save_steps": int(args.save_steps),
"eval_steps": int(args.eval_steps),
"fp16": args.precision == "fp16",
"bf16": args.precision == "bf16",
"gradient_checkpointing": bool(args.gradient_checkpointing),
"seed": int(args.seed),
})
if args.method == "projector":
training.update({"stage": "alignment", "freeze_language_model": True, "freeze_vision_encoder": True, "use_lora": False})
elif args.method == "lora":
training.update({"stage": "distill", "freeze_language_model": False, "use_lora": True})
lora = training.setdefault("lora", {})
lora.update({"rank": int(args.lora_rank), "alpha": int(args.lora_alpha), "dropout": float(args.lora_dropout)})
elif args.method == "full":
training.update({"stage": "full", "freeze_language_model": False, "freeze_vision_encoder": False, "use_lora": False})
else:
raise ValueError("Unlimited OCR Nano supports projector, lora or full methods.")
generated_config = root / "ocr-nano-generated.yaml"
generated_config.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8")
output_dir = root / "output"
command = [
os.environ.get("PYTHON", "python"),
str(project / "scripts" / "train.py"),
"--config", str(generated_config),
"--train-file", str(train_path),
"--output-dir", str(output_dir),
]
if validation_path and validation_path.exists():
command += ["--validation-file", str(validation_path)]
if args.resume_checkpoint:
resume_root = Path(args.resume_checkpoint)
trainer_states = sorted(resume_root.rglob("trainer_state.json"), key=lambda item: item.stat().st_mtime if item.exists() else 0) if resume_root.exists() else []
if trainer_states:
command += ["--resume-training-from", str(trainer_states[-1].parent)]
else:
model_roots = [resume_root] + [item.parent for item in resume_root.rglob("config.json")] if resume_root.exists() else []
model_root = next((item for item in model_roots if (item / "config.json").exists() and (list(item.glob("*.safetensors")) or list(item.glob("*.bin")))), None)
if model_root is not None:
command += ["--resume-from", str(model_root)]
else:
print(json.dumps({"event":"warning","message":f"No resumable OCR checkpoint found below {resume_root}"}), flush=True)
environment = dict(os.environ)
environment["PYTHONPATH"] = str(project / "src")
subprocess.run(command, check=True, env=environment)
manifest = {
"model_id": args.model_id,
"dataset_id": args.dataset_id,
"runtime_family": plan.runtime_id,
"method": args.method,
"train_file": train_file,
"validation_file": validation_file or None,
"arguments": vars(args),
}
(output_dir / "generic_trainer_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
api.create_repo(args.output_repo, repo_type="model", private=True, exist_ok=True, token=token)
api.upload_folder(
folder_path=output_dir,
repo_id=args.output_repo,
repo_type="model",
token=token,
commit_message=f"Generic Trainer OCR Nano: {args.method}",
)
print(f"100% · uploaded OCR Nano checkpoint to {args.output_repo}", flush=True)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Generic Transformers training job")
parser.add_argument("--model-id", required=True)
parser.add_argument("--dataset-id", required=True)
parser.add_argument("--dataset-config", default="")
parser.add_argument("--train-split", default="train")
parser.add_argument("--train-file", default="")
parser.add_argument("--validation-file", default="")
parser.add_argument("--validation-split", default="")
parser.add_argument("--output-repo", required=True)
parser.add_argument("--runtime-family", default="auto", choices=["auto", "gemma4", "unlimited-ocr-nano", "vision-language", "seq2seq", "causal-lm"])
parser.add_argument("--method", default="lora", choices=["projector", "lora", "qlora", "full"])
parser.add_argument("--text-column", default="text")
parser.add_argument("--prompt-column", default="prompt")
parser.add_argument("--response-column", default="response")
parser.add_argument("--messages-column", default="messages")
parser.add_argument("--image-column", default="image")
parser.add_argument("--max-samples", type=int, default=0)
parser.add_argument("--max-length", type=int, default=2048)
parser.add_argument("--batch-size", type=int, default=1)
parser.add_argument("--gradient-accumulation", type=int, default=8)
parser.add_argument("--learning-rate", type=float, default=2e-4)
parser.add_argument("--epochs", type=float, default=1.0)
parser.add_argument("--max-steps", type=int, default=-1)
parser.add_argument("--warmup-ratio", type=float, default=0.03)
parser.add_argument("--weight-decay", type=float, default=0.0)
parser.add_argument("--logging-steps", type=int, default=1)
parser.add_argument("--save-steps", type=int, default=50)
parser.add_argument("--eval-steps", type=int, default=50)
parser.add_argument("--precision", choices=["fp32", "fp16", "bf16"], default="bf16")
parser.add_argument("--gradient-checkpointing", action="store_true")
parser.add_argument("--lora-rank", type=int, default=16)
parser.add_argument("--lora-alpha", type=int, default=32)
parser.add_argument("--lora-dropout", type=float, default=0.05)
parser.add_argument("--trust-remote-code", action="store_true")
parser.add_argument("--resume-checkpoint", default="")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--dry-run", action="store_true")
return parser.parse_args()
def main() -> None:
telemetry = start_telemetry()
args = parse_args()
token = os.environ["HF_TOKEN"]
api = HfApi(token=token)
info = api.model_info(args.model_id, token=token)
is_ocr_nano = args.runtime_family == "unlimited-ocr-nano" or "unlimited-ocr-nano" in args.model_id.lower()
if is_ocr_nano:
class OCRConfig:
model_type = "unlimited_ocr_nano"
architectures = ["UnlimitedOCRNanoForConditionalGeneration"]
is_encoder_decoder = False
config = OCRConfig()
else:
config = AutoConfig.from_pretrained(args.model_id, token=token, trust_remote_code=args.trust_remote_code)
adapter = choose_runtime(args.runtime_family, args.model_id, config, list(info.tags or []))
plan = adapter.plan(args.model_id, config)
args.runtime_family = plan.runtime_id
if plan.runtime_id == "unlimited-ocr-nano":
run_unlimited_ocr_nano(args, token, plan)
return
print(json.dumps({"event": "runtime", **asdict(plan)}, ensure_ascii=False), flush=True)
dataset_kwargs: dict[str, Any] = {"path": args.dataset_id, "split": args.train_split, "token": token}
if args.dataset_config:
dataset_kwargs["name"] = args.dataset_config
train = load_dataset(**dataset_kwargs)
if args.max_samples > 0:
train = train.select(range(min(args.max_samples, len(train))))
validation = None
if args.validation_split:
validation_kwargs = dict(dataset_kwargs)
validation_kwargs["split"] = args.validation_split
validation = load_dataset(**validation_kwargs)
if args.max_samples > 0:
validation = validation.select(range(min(max(1, args.max_samples // 10), len(validation))))
print(json.dumps({"event": "dataset", "train_rows": len(train), "validation_rows": len(validation) if validation is not None else 0, "columns": train.column_names}), flush=True)
if args.dry_run:
print("100% · dry-run validation completed", flush=True)
return
with tempfile.TemporaryDirectory() as tmp:
output_dir = Path(tmp) / "output"
output_dir.mkdir(parents=True)
model, processor = adapter.load(args, quantization(args.method))
model = apply_peft(model, args)
if hasattr(model, "config") and args.gradient_checkpointing:
model.config.use_cache = False
if hasattr(model, "print_trainable_parameters"):
model.print_trainable_parameters()
trainer = adapter.build_trainer(args, model, processor, train, validation, output_dir)
trainer.train(resume_from_checkpoint=(args.resume_checkpoint or None))
trainer.save_model(output_dir)
if hasattr(processor, "save_pretrained"):
processor.save_pretrained(output_dir)
manifest = {"model_id": args.model_id, "dataset_id": args.dataset_id, "runtime_family": plan.runtime_id, "method": args.method, "arguments": vars(args)}
(output_dir / "training_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
api.create_repo(args.output_repo, repo_type="model", private=True, exist_ok=True, token=token)
api.upload_folder(folder_path=output_dir, repo_id=args.output_repo, repo_type="model", token=token, commit_message=f"Generic Trainer: {args.method} on {args.dataset_id}")
print(f"100% · uploaded model to {args.output_repo}", flush=True)
if __name__ == "__main__":
main()
|