Use repository-native Unlimited OCR Nano training backend
Browse files- generic_train_job.py +166 -2
generic_train_job.py
CHANGED
|
@@ -10,6 +10,8 @@
|
|
| 10 |
# "pillow>=11",
|
| 11 |
# "huggingface-hub>=1.0",
|
| 12 |
# "safetensors>=0.5",
|
|
|
|
|
|
|
| 13 |
# ]
|
| 14 |
# ///
|
| 15 |
from __future__ import annotations
|
|
@@ -19,6 +21,7 @@ import inspect
|
|
| 19 |
import json
|
| 20 |
import os
|
| 21 |
import re
|
|
|
|
| 22 |
import tempfile
|
| 23 |
from abc import ABC, abstractmethod
|
| 24 |
from dataclasses import asdict, dataclass
|
|
@@ -27,7 +30,7 @@ from typing import Any
|
|
| 27 |
|
| 28 |
import torch
|
| 29 |
from datasets import Dataset, load_dataset
|
| 30 |
-
from huggingface_hub import HfApi
|
| 31 |
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
|
| 32 |
from transformers import (
|
| 33 |
AutoConfig,
|
|
@@ -387,12 +390,162 @@ def apply_peft(model: Any, args: argparse.Namespace) -> Any:
|
|
| 387 |
return get_peft_model(model, config)
|
| 388 |
|
| 389 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
def parse_args() -> argparse.Namespace:
|
| 391 |
parser = argparse.ArgumentParser(description="Generic Transformers training job")
|
| 392 |
parser.add_argument("--model-id", required=True)
|
| 393 |
parser.add_argument("--dataset-id", required=True)
|
| 394 |
parser.add_argument("--dataset-config", default="")
|
| 395 |
parser.add_argument("--train-split", default="train")
|
|
|
|
|
|
|
| 396 |
parser.add_argument("--validation-split", default="")
|
| 397 |
parser.add_argument("--output-repo", required=True)
|
| 398 |
parser.add_argument("--adapter", default="auto", choices=["auto", "gemma4", "unlimited-ocr-nano", "vision-language", "seq2seq", "causal-lm"])
|
|
@@ -430,10 +583,21 @@ def main() -> None:
|
|
| 430 |
token = os.environ["HF_TOKEN"]
|
| 431 |
api = HfApi(token=token)
|
| 432 |
info = api.model_info(args.model_id, token=token)
|
| 433 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 434 |
adapter = choose_adapter(args.adapter, args.model_id, config, list(info.tags or []))
|
| 435 |
plan = adapter.plan(args.model_id, config)
|
| 436 |
args.adapter = plan.adapter_id
|
|
|
|
|
|
|
|
|
|
| 437 |
print(json.dumps({"event": "adapter", **asdict(plan)}, ensure_ascii=False), flush=True)
|
| 438 |
|
| 439 |
dataset_kwargs: dict[str, Any] = {"path": args.dataset_id, "split": args.train_split, "token": token}
|
|
|
|
| 10 |
# "pillow>=11",
|
| 11 |
# "huggingface-hub>=1.0",
|
| 12 |
# "safetensors>=0.5",
|
| 13 |
+
# "pyyaml>=6",
|
| 14 |
+
# "timm>=1.0",
|
| 15 |
# ]
|
| 16 |
# ///
|
| 17 |
from __future__ import annotations
|
|
|
|
| 21 |
import json
|
| 22 |
import os
|
| 23 |
import re
|
| 24 |
+
import subprocess
|
| 25 |
import tempfile
|
| 26 |
from abc import ABC, abstractmethod
|
| 27 |
from dataclasses import asdict, dataclass
|
|
|
|
| 30 |
|
| 31 |
import torch
|
| 32 |
from datasets import Dataset, load_dataset
|
| 33 |
+
from huggingface_hub import HfApi, snapshot_download
|
| 34 |
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
|
| 35 |
from transformers import (
|
| 36 |
AutoConfig,
|
|
|
|
| 390 |
return get_peft_model(model, config)
|
| 391 |
|
| 392 |
|
| 393 |
+
def _pick_ocr_file(files: list[str], explicit: str, candidates: list[str]) -> str:
|
| 394 |
+
if explicit:
|
| 395 |
+
if explicit not in files:
|
| 396 |
+
raise FileNotFoundError(f"Dataset file not found: {explicit}")
|
| 397 |
+
return explicit
|
| 398 |
+
for candidate in candidates:
|
| 399 |
+
if candidate in files:
|
| 400 |
+
return candidate
|
| 401 |
+
raise FileNotFoundError(f"No compatible OCR JSONL found. Tried: {candidates}")
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _subset_jsonl(source: Path, limit: int) -> Path:
|
| 405 |
+
if limit <= 0:
|
| 406 |
+
return source
|
| 407 |
+
destination = source.with_name(f"{source.stem}.subset-{limit}{source.suffix}")
|
| 408 |
+
lines = []
|
| 409 |
+
with source.open("r", encoding="utf-8", errors="replace") as handle:
|
| 410 |
+
for index, line in enumerate(handle):
|
| 411 |
+
if index >= limit:
|
| 412 |
+
break
|
| 413 |
+
lines.append(line)
|
| 414 |
+
destination.write_text("".join(lines), encoding="utf-8")
|
| 415 |
+
return destination
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def run_unlimited_ocr_nano(args: argparse.Namespace, token: str, plan: AdapterPlan) -> None:
|
| 419 |
+
import yaml
|
| 420 |
+
|
| 421 |
+
api = HfApi(token=token)
|
| 422 |
+
files = api.list_repo_files(args.dataset_id, repo_type="dataset", token=token)
|
| 423 |
+
train_file = _pick_ocr_file(
|
| 424 |
+
files,
|
| 425 |
+
args.train_file,
|
| 426 |
+
["teacher/train.jsonl", f"{args.train_split}.jsonl", "train.jsonl"],
|
| 427 |
+
)
|
| 428 |
+
validation_file = ""
|
| 429 |
+
if args.validation_file:
|
| 430 |
+
validation_file = _pick_ocr_file(files, args.validation_file, [])
|
| 431 |
+
else:
|
| 432 |
+
for candidate in ["teacher/validation.jsonl", "validation.jsonl"]:
|
| 433 |
+
if candidate in files:
|
| 434 |
+
validation_file = candidate
|
| 435 |
+
break
|
| 436 |
+
|
| 437 |
+
print(json.dumps({
|
| 438 |
+
"event": "adapter",
|
| 439 |
+
**asdict(plan),
|
| 440 |
+
"train_file": train_file,
|
| 441 |
+
"validation_file": validation_file or None,
|
| 442 |
+
}, ensure_ascii=False), flush=True)
|
| 443 |
+
if args.dry_run:
|
| 444 |
+
print("100% 路 Unlimited OCR Nano dry-run validation completed", flush=True)
|
| 445 |
+
return
|
| 446 |
+
|
| 447 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 448 |
+
root = Path(tmp)
|
| 449 |
+
project = Path(snapshot_download(
|
| 450 |
+
args.model_id,
|
| 451 |
+
repo_type="model",
|
| 452 |
+
token=token,
|
| 453 |
+
local_dir=root / "project",
|
| 454 |
+
allow_patterns=["src/**", "scripts/train.py", "configs/**", "pyproject.toml", "README.md"],
|
| 455 |
+
))
|
| 456 |
+
patterns = [train_file, "pages/**"]
|
| 457 |
+
if validation_file:
|
| 458 |
+
patterns.append(validation_file)
|
| 459 |
+
dataset = Path(snapshot_download(
|
| 460 |
+
args.dataset_id,
|
| 461 |
+
repo_type="dataset",
|
| 462 |
+
token=token,
|
| 463 |
+
local_dir=root / "dataset",
|
| 464 |
+
allow_patterns=patterns,
|
| 465 |
+
max_workers=64,
|
| 466 |
+
))
|
| 467 |
+
train_path = _subset_jsonl(dataset / train_file, args.max_samples)
|
| 468 |
+
validation_path = dataset / validation_file if validation_file else None
|
| 469 |
+
|
| 470 |
+
base_name = "nano-600m-alignment.yaml" if args.method == "projector" else "nano-600m-distill.yaml"
|
| 471 |
+
base_path = project / "configs" / base_name
|
| 472 |
+
if not base_path.exists():
|
| 473 |
+
available = sorted(path.name for path in (project / "configs").glob("*.yaml"))
|
| 474 |
+
raise FileNotFoundError(f"Missing {base_name}; available configs: {available}")
|
| 475 |
+
config = yaml.safe_load(base_path.read_text(encoding="utf-8"))
|
| 476 |
+
training = config.setdefault("training", {})
|
| 477 |
+
training.update({
|
| 478 |
+
"max_length": int(args.max_length),
|
| 479 |
+
"batch_size": int(args.batch_size),
|
| 480 |
+
"gradient_accumulation_steps": int(args.gradient_accumulation),
|
| 481 |
+
"learning_rate": float(args.learning_rate),
|
| 482 |
+
"epochs": float(args.epochs),
|
| 483 |
+
"max_steps": int(args.max_steps),
|
| 484 |
+
"warmup_ratio": float(args.warmup_ratio),
|
| 485 |
+
"weight_decay": float(args.weight_decay),
|
| 486 |
+
"logging_steps": int(args.logging_steps),
|
| 487 |
+
"save_steps": int(args.save_steps),
|
| 488 |
+
"eval_steps": int(args.eval_steps),
|
| 489 |
+
"fp16": args.precision == "fp16",
|
| 490 |
+
"bf16": args.precision == "bf16",
|
| 491 |
+
"gradient_checkpointing": bool(args.gradient_checkpointing),
|
| 492 |
+
"seed": int(args.seed),
|
| 493 |
+
})
|
| 494 |
+
if args.method == "projector":
|
| 495 |
+
training.update({"stage": "alignment", "freeze_language_model": True, "freeze_vision_encoder": True, "use_lora": False})
|
| 496 |
+
elif args.method == "lora":
|
| 497 |
+
training.update({"stage": "distill", "freeze_language_model": False, "use_lora": True})
|
| 498 |
+
lora = training.setdefault("lora", {})
|
| 499 |
+
lora.update({"rank": int(args.lora_rank), "alpha": int(args.lora_alpha), "dropout": float(args.lora_dropout)})
|
| 500 |
+
elif args.method == "full":
|
| 501 |
+
training.update({"stage": "full", "freeze_language_model": False, "freeze_vision_encoder": False, "use_lora": False})
|
| 502 |
+
else:
|
| 503 |
+
raise ValueError("Unlimited OCR Nano supports projector, lora or full methods.")
|
| 504 |
+
|
| 505 |
+
generated_config = root / "ocr-nano-generated.yaml"
|
| 506 |
+
generated_config.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8")
|
| 507 |
+
output_dir = root / "output"
|
| 508 |
+
command = [
|
| 509 |
+
os.environ.get("PYTHON", "python"),
|
| 510 |
+
str(project / "scripts" / "train.py"),
|
| 511 |
+
"--config", str(generated_config),
|
| 512 |
+
"--train-file", str(train_path),
|
| 513 |
+
"--output-dir", str(output_dir),
|
| 514 |
+
]
|
| 515 |
+
if validation_path and validation_path.exists():
|
| 516 |
+
command += ["--validation-file", str(validation_path)]
|
| 517 |
+
environment = dict(os.environ)
|
| 518 |
+
environment["PYTHONPATH"] = str(project / "src")
|
| 519 |
+
subprocess.run(command, check=True, env=environment)
|
| 520 |
+
manifest = {
|
| 521 |
+
"model_id": args.model_id,
|
| 522 |
+
"dataset_id": args.dataset_id,
|
| 523 |
+
"adapter": plan.adapter_id,
|
| 524 |
+
"method": args.method,
|
| 525 |
+
"train_file": train_file,
|
| 526 |
+
"validation_file": validation_file or None,
|
| 527 |
+
"arguments": vars(args),
|
| 528 |
+
}
|
| 529 |
+
(output_dir / "generic_trainer_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
| 530 |
+
api.create_repo(args.output_repo, repo_type="model", private=True, exist_ok=True, token=token)
|
| 531 |
+
api.upload_folder(
|
| 532 |
+
folder_path=output_dir,
|
| 533 |
+
repo_id=args.output_repo,
|
| 534 |
+
repo_type="model",
|
| 535 |
+
token=token,
|
| 536 |
+
commit_message=f"Generic Trainer OCR Nano: {args.method}",
|
| 537 |
+
)
|
| 538 |
+
print(f"100% 路 uploaded OCR Nano checkpoint to {args.output_repo}", flush=True)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
def parse_args() -> argparse.Namespace:
|
| 542 |
parser = argparse.ArgumentParser(description="Generic Transformers training job")
|
| 543 |
parser.add_argument("--model-id", required=True)
|
| 544 |
parser.add_argument("--dataset-id", required=True)
|
| 545 |
parser.add_argument("--dataset-config", default="")
|
| 546 |
parser.add_argument("--train-split", default="train")
|
| 547 |
+
parser.add_argument("--train-file", default="")
|
| 548 |
+
parser.add_argument("--validation-file", default="")
|
| 549 |
parser.add_argument("--validation-split", default="")
|
| 550 |
parser.add_argument("--output-repo", required=True)
|
| 551 |
parser.add_argument("--adapter", default="auto", choices=["auto", "gemma4", "unlimited-ocr-nano", "vision-language", "seq2seq", "causal-lm"])
|
|
|
|
| 583 |
token = os.environ["HF_TOKEN"]
|
| 584 |
api = HfApi(token=token)
|
| 585 |
info = api.model_info(args.model_id, token=token)
|
| 586 |
+
is_ocr_nano = args.adapter == "unlimited-ocr-nano" or "unlimited-ocr-nano" in args.model_id.lower()
|
| 587 |
+
if is_ocr_nano:
|
| 588 |
+
class OCRConfig:
|
| 589 |
+
model_type = "unlimited_ocr_nano"
|
| 590 |
+
architectures = ["UnlimitedOCRNanoForConditionalGeneration"]
|
| 591 |
+
is_encoder_decoder = False
|
| 592 |
+
config = OCRConfig()
|
| 593 |
+
else:
|
| 594 |
+
config = AutoConfig.from_pretrained(args.model_id, token=token, trust_remote_code=args.trust_remote_code)
|
| 595 |
adapter = choose_adapter(args.adapter, args.model_id, config, list(info.tags or []))
|
| 596 |
plan = adapter.plan(args.model_id, config)
|
| 597 |
args.adapter = plan.adapter_id
|
| 598 |
+
if plan.adapter_id == "unlimited-ocr-nano":
|
| 599 |
+
run_unlimited_ocr_nano(args, token, plan)
|
| 600 |
+
return
|
| 601 |
print(json.dumps({"event": "adapter", **asdict(plan)}, ensure_ascii=False), flush=True)
|
| 602 |
|
| 603 |
dataset_kwargs: dict[str, Any] = {"path": args.dataset_id, "split": args.train_split, "token": token}
|