| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| 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() |
|
|