Add TrainingJob checkpoint resume support
Browse files- generic_train_job.py +494 -124
generic_train_job.py
CHANGED
|
@@ -54,6 +54,8 @@ from transformers import (
|
|
| 54 |
|
| 55 |
|
| 56 |
class TelemetryReporter:
|
|
|
|
|
|
|
| 57 |
def __init__(self, interval: float = 2.0):
|
| 58 |
self.interval = interval
|
| 59 |
self.stop_event = threading.Event()
|
|
@@ -91,30 +93,63 @@ class TelemetryReporter:
|
|
| 91 |
names.append(name.decode() if isinstance(name, bytes) else str(name))
|
| 92 |
memory = self.nvml.nvmlDeviceGetMemoryInfo(handle)
|
| 93 |
used += int(memory.used); total += int(memory.total)
|
| 94 |
-
try:
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
if torch.cuda.is_available():
|
| 100 |
-
free, total = torch.cuda.mem_get_info()
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
def sample(self) -> dict[str, object]:
|
| 105 |
memory = psutil.virtual_memory()
|
| 106 |
-
payload: dict[str, object] = {
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
def _run(self) -> None:
|
| 110 |
while not self.stop_event.is_set():
|
| 111 |
-
try:
|
| 112 |
-
|
|
|
|
|
|
|
| 113 |
self.stop_event.wait(self.interval)
|
| 114 |
|
| 115 |
|
| 116 |
def start_telemetry() -> TelemetryReporter:
|
| 117 |
-
reporter = TelemetryReporter()
|
|
|
|
|
|
|
| 118 |
|
| 119 |
|
| 120 |
@dataclass(slots=True)
|
|
@@ -128,29 +163,40 @@ class AdapterPlan:
|
|
| 128 |
|
| 129 |
|
| 130 |
class TrainingAdapter(ABC):
|
|
|
|
|
|
|
| 131 |
adapter_id: str
|
|
|
|
| 132 |
@classmethod
|
| 133 |
@abstractmethod
|
| 134 |
def score(cls, model_id: str, config: Any, tags: list[str]) -> int: ...
|
|
|
|
| 135 |
@classmethod
|
| 136 |
@abstractmethod
|
| 137 |
def plan(cls, model_id: str, config: Any) -> AdapterPlan: ...
|
|
|
|
| 138 |
@abstractmethod
|
| 139 |
def load(self, args: argparse.Namespace, quantization_config: BitsAndBytesConfig | None): ...
|
|
|
|
| 140 |
@abstractmethod
|
| 141 |
def build_trainer(self, args: argparse.Namespace, model: Any, processor: Any, train: Dataset, validation: Dataset | None, output_dir: Path) -> Trainer: ...
|
| 142 |
|
| 143 |
|
| 144 |
class TextAdapterBase(TrainingAdapter):
|
| 145 |
seq2seq = False
|
|
|
|
| 146 |
def _render(self, row: dict[str, Any], tokenizer: Any, args: argparse.Namespace) -> str:
|
| 147 |
messages = row.get(args.messages_column) if args.messages_column else None
|
| 148 |
-
if isinstance(messages, list) and hasattr(tokenizer, "apply_chat_template"):
|
|
|
|
| 149 |
text = row.get(args.text_column) if args.text_column else None
|
| 150 |
-
if text not in (None, ""):
|
|
|
|
| 151 |
prompt = str(row.get(args.prompt_column, "")) if args.prompt_column else ""
|
| 152 |
response = str(row.get(args.response_column, "")) if args.response_column else ""
|
| 153 |
-
|
|
|
|
|
|
|
| 154 |
|
| 155 |
def build_trainer(self, args, model, tokenizer, train, validation, output_dir):
|
| 156 |
max_length = int(args.max_length)
|
|
@@ -168,227 +214,551 @@ class TextAdapterBase(TrainingAdapter):
|
|
| 168 |
encoded = tokenizer(texts, max_length=max_length, truncation=True, padding=False)
|
| 169 |
encoded["labels"] = [list(ids) for ids in encoded["input_ids"]]
|
| 170 |
return encoded
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
collator = DataCollatorForSeq2Seq(tokenizer, model=model) if self.seq2seq else DataCollatorForLanguageModeling(tokenizer, mlm=False)
|
| 174 |
-
return Trainer(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
|
| 176 |
|
| 177 |
class CausalLMAdapter(TextAdapterBase):
|
| 178 |
adapter_id = "causal-lm"
|
|
|
|
| 179 |
@classmethod
|
| 180 |
def score(cls, model_id, config, tags):
|
| 181 |
-
architectures = " ".join(getattr(config, "architectures", []) or []).lower()
|
|
|
|
|
|
|
| 182 |
@classmethod
|
| 183 |
-
def plan(cls, model_id, config):
|
|
|
|
|
|
|
| 184 |
def load(self, args, quantization_config):
|
| 185 |
tokenizer = AutoTokenizer.from_pretrained(args.model_id, token=os.environ["HF_TOKEN"], trust_remote_code=args.trust_remote_code)
|
| 186 |
-
if tokenizer.pad_token_id is None:
|
| 187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
return model, tokenizer
|
| 189 |
|
| 190 |
|
| 191 |
class Seq2SeqAdapter(TextAdapterBase):
|
| 192 |
-
adapter_id = "seq2seq"
|
|
|
|
|
|
|
| 193 |
@classmethod
|
| 194 |
-
def score(cls, model_id, config, tags):
|
|
|
|
|
|
|
| 195 |
@classmethod
|
| 196 |
-
def plan(cls, model_id, config):
|
|
|
|
|
|
|
| 197 |
def load(self, args, quantization_config):
|
| 198 |
tokenizer = AutoTokenizer.from_pretrained(args.model_id, token=os.environ["HF_TOKEN"], trust_remote_code=args.trust_remote_code)
|
| 199 |
-
model = AutoModelForSeq2SeqLM.from_pretrained(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
return model, tokenizer
|
| 201 |
|
| 202 |
|
| 203 |
class MultimodalCollator:
|
| 204 |
-
def __init__(self, processor: Any, args: argparse.Namespace):
|
|
|
|
|
|
|
|
|
|
| 205 |
def _text(self, row: dict[str, Any]) -> str:
|
| 206 |
messages = row.get(self.args.messages_column) if self.args.messages_column else None
|
| 207 |
-
if isinstance(messages, list) and hasattr(self.processor, "apply_chat_template"):
|
| 208 |
-
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
def __call__(self, rows: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
|
| 211 |
-
texts = [self._text(row) for row in rows]
|
| 212 |
-
|
| 213 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
batch = self.processor(**kwargs)
|
| 215 |
if "input_ids" in batch:
|
| 216 |
-
labels = batch["input_ids"].clone()
|
| 217 |
-
|
|
|
|
|
|
|
| 218 |
batch["labels"] = labels
|
| 219 |
return batch
|
| 220 |
|
| 221 |
|
| 222 |
class VisionLanguageAdapter(TrainingAdapter):
|
| 223 |
adapter_id = "vision-language"
|
|
|
|
| 224 |
@classmethod
|
| 225 |
def score(cls, model_id, config, tags):
|
| 226 |
-
haystack = " ".join([model_id, getattr(config, "model_type", ""), *(getattr(config, "architectures", []) or []), *tags]).lower()
|
|
|
|
|
|
|
| 227 |
@classmethod
|
| 228 |
-
def plan(cls, model_id, config):
|
|
|
|
|
|
|
| 229 |
def _model_class(self):
|
| 230 |
import transformers
|
| 231 |
for name in ("AutoModelForMultimodalLM", "AutoModelForImageTextToText", "AutoModelForVision2Seq"):
|
| 232 |
candidate = getattr(transformers, name, None)
|
| 233 |
-
if candidate is not None:
|
|
|
|
| 234 |
raise RuntimeError("This Transformers version has no multimodal auto-model class.")
|
|
|
|
| 235 |
def load(self, args, quantization_config):
|
| 236 |
processor = AutoProcessor.from_pretrained(args.model_id, token=os.environ["HF_TOKEN"], trust_remote_code=args.trust_remote_code)
|
| 237 |
-
model = self._model_class().from_pretrained(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
return model, processor
|
|
|
|
| 239 |
def build_trainer(self, args, model, processor, train, validation, output_dir):
|
| 240 |
-
return Trainer(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
|
| 243 |
class UnlimitedOCRNanoAdapter(VisionLanguageAdapter):
|
| 244 |
adapter_id = "unlimited-ocr-nano"
|
|
|
|
| 245 |
@classmethod
|
| 246 |
def score(cls, model_id, config, tags):
|
| 247 |
-
haystack = " ".join([model_id, getattr(config, "model_type", ""), *(getattr(config, "architectures", []) or []), *tags]).lower()
|
|
|
|
|
|
|
| 248 |
@classmethod
|
| 249 |
-
def plan(cls, model_id, config):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
def _model_class(self):
|
| 251 |
from transformers import AutoModel
|
| 252 |
return AutoModel
|
|
|
|
| 253 |
def load(self, args, quantization_config):
|
| 254 |
processor = AutoProcessor.from_pretrained(args.model_id, token=os.environ["HF_TOKEN"], trust_remote_code=True)
|
| 255 |
-
model = self._model_class().from_pretrained(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
if args.method == "projector":
|
| 257 |
-
if hasattr(model, "freeze_language_model"):
|
| 258 |
-
|
| 259 |
-
if hasattr(model, "
|
|
|
|
|
|
|
|
|
|
| 260 |
else:
|
| 261 |
-
for name, parameter in model.named_parameters():
|
|
|
|
| 262 |
return model, processor
|
| 263 |
|
| 264 |
|
| 265 |
class Gemma4Adapter(VisionLanguageAdapter):
|
| 266 |
adapter_id = "gemma4"
|
|
|
|
| 267 |
@classmethod
|
| 268 |
def score(cls, model_id, config, tags):
|
| 269 |
-
haystack = " ".join([model_id, getattr(config, "model_type", ""), *(getattr(config, "architectures", []) or []), *tags]).lower()
|
|
|
|
|
|
|
| 270 |
@classmethod
|
| 271 |
-
def plan(cls, model_id, config):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
|
| 273 |
|
| 274 |
ADAPTERS: list[type[TrainingAdapter]] = [Gemma4Adapter, UnlimitedOCRNanoAdapter, Seq2SeqAdapter, VisionLanguageAdapter, CausalLMAdapter]
|
| 275 |
|
|
|
|
| 276 |
def choose_adapter(adapter_id: str, model_id: str, config: Any, tags: list[str]) -> TrainingAdapter:
|
| 277 |
if adapter_id != "auto":
|
| 278 |
for adapter in ADAPTERS:
|
| 279 |
-
if adapter.adapter_id == adapter_id:
|
|
|
|
| 280 |
raise ValueError(f"Unknown adapter {adapter_id}")
|
| 281 |
-
|
|
|
|
| 282 |
|
| 283 |
|
| 284 |
def training_arguments(args: argparse.Namespace, output_dir: Path, has_eval: bool) -> TrainingArguments:
|
| 285 |
-
kwargs = dict(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
signature = inspect.signature(TrainingArguments)
|
| 287 |
-
if "eval_strategy" in signature.parameters:
|
| 288 |
-
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
| 290 |
return TrainingArguments(**kwargs)
|
| 291 |
|
| 292 |
|
| 293 |
def quantization(method: str) -> BitsAndBytesConfig | None:
|
| 294 |
-
if method != "qlora":
|
| 295 |
-
|
|
|
|
|
|
|
| 296 |
compute_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
|
| 297 |
-
return BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type="nf4",bnb_4bit_use_double_quant=True,bnb_4bit_compute_dtype=compute_dtype)
|
| 298 |
|
| 299 |
|
| 300 |
def apply_peft(model: Any, args: argparse.Namespace) -> Any:
|
| 301 |
-
if args.method not in {"lora", "qlora"}:
|
| 302 |
-
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
return get_peft_model(model, config)
|
| 305 |
|
| 306 |
|
| 307 |
def _pick_ocr_file(files: list[str], explicit: str, candidates: list[str]) -> str:
|
| 308 |
if explicit:
|
| 309 |
-
if explicit not in files:
|
|
|
|
| 310 |
return explicit
|
| 311 |
for candidate in candidates:
|
| 312 |
-
if candidate in files:
|
|
|
|
| 313 |
raise FileNotFoundError(f"No compatible OCR JSONL found. Tried: {candidates}")
|
| 314 |
|
| 315 |
|
| 316 |
def _subset_jsonl(source: Path, limit: int) -> Path:
|
| 317 |
-
if limit <= 0:
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
|
|
|
|
|
|
|
|
|
| 322 |
lines.append(line)
|
| 323 |
-
destination.write_text("".join(lines),encoding="utf-8")
|
|
|
|
| 324 |
|
| 325 |
|
| 326 |
def run_unlimited_ocr_nano(args: argparse.Namespace, token: str, plan: AdapterPlan) -> None:
|
| 327 |
import yaml
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
else:
|
| 333 |
-
for candidate in ["teacher/validation.jsonl","validation.jsonl"]:
|
| 334 |
-
if candidate in files:
|
| 335 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
if args.dry_run:
|
| 337 |
-
print("100% · Unlimited OCR Nano dry-run validation completed",flush=True)
|
|
|
|
|
|
|
| 338 |
with tempfile.TemporaryDirectory() as tmp:
|
| 339 |
-
root=Path(tmp)
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
|
| 359 |
|
| 360 |
def parse_args() -> argparse.Namespace:
|
| 361 |
-
parser=argparse.ArgumentParser(description="Generic Transformers training job")
|
| 362 |
-
parser.add_argument("--model-id",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
return parser.parse_args()
|
| 364 |
|
| 365 |
|
| 366 |
def main() -> None:
|
| 367 |
-
telemetry
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
if is_ocr_nano:
|
| 369 |
-
class OCRConfig:
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
if args.validation_split:
|
| 381 |
-
validation_kwargs=dict(dataset_kwargs)
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
with tempfile.TemporaryDirectory() as tmp:
|
| 386 |
-
output_dir=Path(tmp)/"output"
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
if hasattr(
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
|
| 56 |
class TelemetryReporter:
|
| 57 |
+
"""Emit machine-readable host and accelerator utilization for the Gradio monitor."""
|
| 58 |
+
|
| 59 |
def __init__(self, interval: float = 2.0):
|
| 60 |
self.interval = interval
|
| 61 |
self.stop_event = threading.Event()
|
|
|
|
| 93 |
names.append(name.decode() if isinstance(name, bytes) else str(name))
|
| 94 |
memory = self.nvml.nvmlDeviceGetMemoryInfo(handle)
|
| 95 |
used += int(memory.used); total += int(memory.total)
|
| 96 |
+
try:
|
| 97 |
+
utils.append(float(self.nvml.nvmlDeviceGetUtilizationRates(handle).gpu))
|
| 98 |
+
except Exception:
|
| 99 |
+
pass
|
| 100 |
+
try:
|
| 101 |
+
temperatures.append(float(self.nvml.nvmlDeviceGetTemperature(handle, self.nvml.NVML_TEMPERATURE_GPU)))
|
| 102 |
+
except Exception:
|
| 103 |
+
pass
|
| 104 |
+
return {
|
| 105 |
+
"gpu_count": count,
|
| 106 |
+
"gpu_name": " · ".join(names) if names else None,
|
| 107 |
+
"gpu_util_percent": round(sum(utils) / len(utils), 1) if utils else None,
|
| 108 |
+
"vram_used_gb": round(used / 1024**3, 3) if total else None,
|
| 109 |
+
"vram_total_gb": round(total / 1024**3, 3) if total else None,
|
| 110 |
+
"vram_percent": round(used * 100 / total, 1) if total else None,
|
| 111 |
+
"gpu_temperature_c": round(max(temperatures), 1) if temperatures else None,
|
| 112 |
+
}
|
| 113 |
if torch.cuda.is_available():
|
| 114 |
+
free, total = torch.cuda.mem_get_info()
|
| 115 |
+
used = total - free
|
| 116 |
+
return {
|
| 117 |
+
"gpu_count": torch.cuda.device_count(),
|
| 118 |
+
"gpu_name": " · ".join(torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())),
|
| 119 |
+
"gpu_util_percent": None,
|
| 120 |
+
"vram_used_gb": round(used / 1024**3, 3),
|
| 121 |
+
"vram_total_gb": round(total / 1024**3, 3),
|
| 122 |
+
"vram_percent": round(used * 100 / total, 1) if total else None,
|
| 123 |
+
"gpu_temperature_c": None,
|
| 124 |
+
}
|
| 125 |
+
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}
|
| 126 |
|
| 127 |
def sample(self) -> dict[str, object]:
|
| 128 |
memory = psutil.virtual_memory()
|
| 129 |
+
payload: dict[str, object] = {
|
| 130 |
+
"event": "telemetry",
|
| 131 |
+
"timestamp": time.time(),
|
| 132 |
+
"cpu_percent": round(psutil.cpu_percent(interval=None), 1),
|
| 133 |
+
"ram_used_gb": round((memory.total - memory.available) / 1024**3, 3),
|
| 134 |
+
"ram_total_gb": round(memory.total / 1024**3, 3),
|
| 135 |
+
"ram_percent": round(float(memory.percent), 1),
|
| 136 |
+
}
|
| 137 |
+
payload.update(self._gpu_sample())
|
| 138 |
+
return payload
|
| 139 |
|
| 140 |
def _run(self) -> None:
|
| 141 |
while not self.stop_event.is_set():
|
| 142 |
+
try:
|
| 143 |
+
print(json.dumps(self.sample(), ensure_ascii=False), flush=True)
|
| 144 |
+
except Exception as exc:
|
| 145 |
+
print(json.dumps({"event": "telemetry_error", "message": str(exc)}), flush=True)
|
| 146 |
self.stop_event.wait(self.interval)
|
| 147 |
|
| 148 |
|
| 149 |
def start_telemetry() -> TelemetryReporter:
|
| 150 |
+
reporter = TelemetryReporter()
|
| 151 |
+
reporter.start()
|
| 152 |
+
return reporter
|
| 153 |
|
| 154 |
|
| 155 |
@dataclass(slots=True)
|
|
|
|
| 163 |
|
| 164 |
|
| 165 |
class TrainingAdapter(ABC):
|
| 166 |
+
"""Runtime adapter contract used by every training family."""
|
| 167 |
+
|
| 168 |
adapter_id: str
|
| 169 |
+
|
| 170 |
@classmethod
|
| 171 |
@abstractmethod
|
| 172 |
def score(cls, model_id: str, config: Any, tags: list[str]) -> int: ...
|
| 173 |
+
|
| 174 |
@classmethod
|
| 175 |
@abstractmethod
|
| 176 |
def plan(cls, model_id: str, config: Any) -> AdapterPlan: ...
|
| 177 |
+
|
| 178 |
@abstractmethod
|
| 179 |
def load(self, args: argparse.Namespace, quantization_config: BitsAndBytesConfig | None): ...
|
| 180 |
+
|
| 181 |
@abstractmethod
|
| 182 |
def build_trainer(self, args: argparse.Namespace, model: Any, processor: Any, train: Dataset, validation: Dataset | None, output_dir: Path) -> Trainer: ...
|
| 183 |
|
| 184 |
|
| 185 |
class TextAdapterBase(TrainingAdapter):
|
| 186 |
seq2seq = False
|
| 187 |
+
|
| 188 |
def _render(self, row: dict[str, Any], tokenizer: Any, args: argparse.Namespace) -> str:
|
| 189 |
messages = row.get(args.messages_column) if args.messages_column else None
|
| 190 |
+
if isinstance(messages, list) and hasattr(tokenizer, "apply_chat_template"):
|
| 191 |
+
return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
|
| 192 |
text = row.get(args.text_column) if args.text_column else None
|
| 193 |
+
if text not in (None, ""):
|
| 194 |
+
return str(text)
|
| 195 |
prompt = str(row.get(args.prompt_column, "")) if args.prompt_column else ""
|
| 196 |
response = str(row.get(args.response_column, "")) if args.response_column else ""
|
| 197 |
+
if response:
|
| 198 |
+
return f"{prompt}\n{response}".strip()
|
| 199 |
+
return prompt
|
| 200 |
|
| 201 |
def build_trainer(self, args, model, tokenizer, train, validation, output_dir):
|
| 202 |
max_length = int(args.max_length)
|
|
|
|
| 214 |
encoded = tokenizer(texts, max_length=max_length, truncation=True, padding=False)
|
| 215 |
encoded["labels"] = [list(ids) for ids in encoded["input_ids"]]
|
| 216 |
return encoded
|
| 217 |
+
|
| 218 |
+
remove_columns = train.column_names
|
| 219 |
+
tokenized_train = train.map(tokenize_batch, batched=True, remove_columns=remove_columns, desc="Tokenizing train split")
|
| 220 |
+
tokenized_validation = None
|
| 221 |
+
if validation is not None:
|
| 222 |
+
tokenized_validation = validation.map(tokenize_batch, batched=True, remove_columns=validation.column_names, desc="Tokenizing validation split")
|
| 223 |
collator = DataCollatorForSeq2Seq(tokenizer, model=model) if self.seq2seq else DataCollatorForLanguageModeling(tokenizer, mlm=False)
|
| 224 |
+
return Trainer(
|
| 225 |
+
model=model,
|
| 226 |
+
args=training_arguments(args, output_dir, tokenized_validation is not None),
|
| 227 |
+
train_dataset=tokenized_train,
|
| 228 |
+
eval_dataset=tokenized_validation,
|
| 229 |
+
data_collator=collator,
|
| 230 |
+
)
|
| 231 |
|
| 232 |
|
| 233 |
class CausalLMAdapter(TextAdapterBase):
|
| 234 |
adapter_id = "causal-lm"
|
| 235 |
+
|
| 236 |
@classmethod
|
| 237 |
def score(cls, model_id, config, tags):
|
| 238 |
+
architectures = " ".join(getattr(config, "architectures", []) or []).lower()
|
| 239 |
+
return 35 if "causallm" in architectures or "text-generation" in " ".join(tags).lower() else 10
|
| 240 |
+
|
| 241 |
@classmethod
|
| 242 |
+
def plan(cls, model_id, config):
|
| 243 |
+
return AdapterPlan(cls.adapter_id, "text/chat", "AutoModelForCausalLM", "AutoTokenizer", "lora", [])
|
| 244 |
+
|
| 245 |
def load(self, args, quantization_config):
|
| 246 |
tokenizer = AutoTokenizer.from_pretrained(args.model_id, token=os.environ["HF_TOKEN"], trust_remote_code=args.trust_remote_code)
|
| 247 |
+
if tokenizer.pad_token_id is None:
|
| 248 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 249 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 250 |
+
args.model_id,
|
| 251 |
+
token=os.environ["HF_TOKEN"],
|
| 252 |
+
trust_remote_code=args.trust_remote_code,
|
| 253 |
+
torch_dtype="auto",
|
| 254 |
+
device_map="auto" if torch.cuda.is_available() else None,
|
| 255 |
+
quantization_config=quantization_config,
|
| 256 |
+
)
|
| 257 |
return model, tokenizer
|
| 258 |
|
| 259 |
|
| 260 |
class Seq2SeqAdapter(TextAdapterBase):
|
| 261 |
+
adapter_id = "seq2seq"
|
| 262 |
+
seq2seq = True
|
| 263 |
+
|
| 264 |
@classmethod
|
| 265 |
+
def score(cls, model_id, config, tags):
|
| 266 |
+
return 50 if bool(getattr(config, "is_encoder_decoder", False)) else 0
|
| 267 |
+
|
| 268 |
@classmethod
|
| 269 |
+
def plan(cls, model_id, config):
|
| 270 |
+
return AdapterPlan(cls.adapter_id, "text-to-text", "AutoModelForSeq2SeqLM", "AutoTokenizer", "lora", [])
|
| 271 |
+
|
| 272 |
def load(self, args, quantization_config):
|
| 273 |
tokenizer = AutoTokenizer.from_pretrained(args.model_id, token=os.environ["HF_TOKEN"], trust_remote_code=args.trust_remote_code)
|
| 274 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 275 |
+
args.model_id,
|
| 276 |
+
token=os.environ["HF_TOKEN"],
|
| 277 |
+
trust_remote_code=args.trust_remote_code,
|
| 278 |
+
torch_dtype="auto",
|
| 279 |
+
device_map="auto" if torch.cuda.is_available() else None,
|
| 280 |
+
quantization_config=quantization_config,
|
| 281 |
+
)
|
| 282 |
return model, tokenizer
|
| 283 |
|
| 284 |
|
| 285 |
class MultimodalCollator:
|
| 286 |
+
def __init__(self, processor: Any, args: argparse.Namespace):
|
| 287 |
+
self.processor = processor
|
| 288 |
+
self.args = args
|
| 289 |
+
|
| 290 |
def _text(self, row: dict[str, Any]) -> str:
|
| 291 |
messages = row.get(self.args.messages_column) if self.args.messages_column else None
|
| 292 |
+
if isinstance(messages, list) and hasattr(self.processor, "apply_chat_template"):
|
| 293 |
+
return self.processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
|
| 294 |
+
prompt = str(row.get(self.args.prompt_column, "")) if self.args.prompt_column else ""
|
| 295 |
+
response = str(row.get(self.args.response_column, "")) if self.args.response_column else ""
|
| 296 |
+
text = str(row.get(self.args.text_column, "")) if self.args.text_column else ""
|
| 297 |
+
return text or (f"{prompt}\n{response}".strip())
|
| 298 |
+
|
| 299 |
def __call__(self, rows: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
|
| 300 |
+
texts = [self._text(row) for row in rows]
|
| 301 |
+
images = None
|
| 302 |
+
if self.args.image_column and self.args.image_column in rows[0]:
|
| 303 |
+
images = [row.get(self.args.image_column) for row in rows]
|
| 304 |
+
kwargs: dict[str, Any] = {"text": texts, "padding": True, "truncation": True, "max_length": self.args.max_length, "return_tensors": "pt"}
|
| 305 |
+
if images is not None and any(image is not None for image in images):
|
| 306 |
+
kwargs["images"] = images
|
| 307 |
batch = self.processor(**kwargs)
|
| 308 |
if "input_ids" in batch:
|
| 309 |
+
labels = batch["input_ids"].clone()
|
| 310 |
+
pad_id = getattr(getattr(self.processor, "tokenizer", None), "pad_token_id", None)
|
| 311 |
+
if pad_id is not None:
|
| 312 |
+
labels[labels == pad_id] = -100
|
| 313 |
batch["labels"] = labels
|
| 314 |
return batch
|
| 315 |
|
| 316 |
|
| 317 |
class VisionLanguageAdapter(TrainingAdapter):
|
| 318 |
adapter_id = "vision-language"
|
| 319 |
+
|
| 320 |
@classmethod
|
| 321 |
def score(cls, model_id, config, tags):
|
| 322 |
+
haystack = " ".join([model_id, getattr(config, "model_type", ""), *(getattr(config, "architectures", []) or []), *tags]).lower()
|
| 323 |
+
return 70 if any(term in haystack for term in ("image-text-to-text", "vision", "multimodal", "any-to-any")) else 0
|
| 324 |
+
|
| 325 |
@classmethod
|
| 326 |
+
def plan(cls, model_id, config):
|
| 327 |
+
return AdapterPlan(cls.adapter_id, "text+image", "Auto multimodal model", "AutoProcessor", "lora", [])
|
| 328 |
+
|
| 329 |
def _model_class(self):
|
| 330 |
import transformers
|
| 331 |
for name in ("AutoModelForMultimodalLM", "AutoModelForImageTextToText", "AutoModelForVision2Seq"):
|
| 332 |
candidate = getattr(transformers, name, None)
|
| 333 |
+
if candidate is not None:
|
| 334 |
+
return candidate
|
| 335 |
raise RuntimeError("This Transformers version has no multimodal auto-model class.")
|
| 336 |
+
|
| 337 |
def load(self, args, quantization_config):
|
| 338 |
processor = AutoProcessor.from_pretrained(args.model_id, token=os.environ["HF_TOKEN"], trust_remote_code=args.trust_remote_code)
|
| 339 |
+
model = self._model_class().from_pretrained(
|
| 340 |
+
args.model_id,
|
| 341 |
+
token=os.environ["HF_TOKEN"],
|
| 342 |
+
trust_remote_code=args.trust_remote_code,
|
| 343 |
+
torch_dtype="auto",
|
| 344 |
+
device_map="auto" if torch.cuda.is_available() else None,
|
| 345 |
+
quantization_config=quantization_config,
|
| 346 |
+
)
|
| 347 |
return model, processor
|
| 348 |
+
|
| 349 |
def build_trainer(self, args, model, processor, train, validation, output_dir):
|
| 350 |
+
return Trainer(
|
| 351 |
+
model=model,
|
| 352 |
+
args=training_arguments(args, output_dir, validation is not None),
|
| 353 |
+
train_dataset=train,
|
| 354 |
+
eval_dataset=validation,
|
| 355 |
+
data_collator=MultimodalCollator(processor, args),
|
| 356 |
+
)
|
| 357 |
|
| 358 |
|
| 359 |
class UnlimitedOCRNanoAdapter(VisionLanguageAdapter):
|
| 360 |
adapter_id = "unlimited-ocr-nano"
|
| 361 |
+
|
| 362 |
@classmethod
|
| 363 |
def score(cls, model_id, config, tags):
|
| 364 |
+
haystack = " ".join([model_id, getattr(config, "model_type", ""), *(getattr(config, "architectures", []) or []), *tags]).lower()
|
| 365 |
+
return 95 if "unlimited-ocr-nano" in haystack else 0
|
| 366 |
+
|
| 367 |
@classmethod
|
| 368 |
+
def plan(cls, model_id, config):
|
| 369 |
+
return AdapterPlan(
|
| 370 |
+
cls.adapter_id,
|
| 371 |
+
"document image → structured text",
|
| 372 |
+
"AutoModel / custom trust_remote_code architecture",
|
| 373 |
+
"AutoProcessor",
|
| 374 |
+
"projector",
|
| 375 |
+
[
|
| 376 |
+
"Uses the model repository's custom processor and model code.",
|
| 377 |
+
"Projector mode trains the multimodal projector while keeping backbone weights frozen when supported.",
|
| 378 |
+
"Expected dataset columns are image plus text/target or prompt/response.",
|
| 379 |
+
],
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
def _model_class(self):
|
| 383 |
from transformers import AutoModel
|
| 384 |
return AutoModel
|
| 385 |
+
|
| 386 |
def load(self, args, quantization_config):
|
| 387 |
processor = AutoProcessor.from_pretrained(args.model_id, token=os.environ["HF_TOKEN"], trust_remote_code=True)
|
| 388 |
+
model = self._model_class().from_pretrained(
|
| 389 |
+
args.model_id,
|
| 390 |
+
token=os.environ["HF_TOKEN"],
|
| 391 |
+
trust_remote_code=True,
|
| 392 |
+
torch_dtype="auto",
|
| 393 |
+
device_map="auto" if torch.cuda.is_available() else None,
|
| 394 |
+
quantization_config=quantization_config,
|
| 395 |
+
)
|
| 396 |
if args.method == "projector":
|
| 397 |
+
if hasattr(model, "freeze_language_model"):
|
| 398 |
+
model.freeze_language_model()
|
| 399 |
+
if hasattr(model, "freeze_vision_encoder"):
|
| 400 |
+
model.freeze_vision_encoder()
|
| 401 |
+
if hasattr(model, "unfreeze_projector"):
|
| 402 |
+
model.unfreeze_projector()
|
| 403 |
else:
|
| 404 |
+
for name, parameter in model.named_parameters():
|
| 405 |
+
parameter.requires_grad = any(key in name.lower() for key in ("projector", "multimodal_projector", "vision_projector"))
|
| 406 |
return model, processor
|
| 407 |
|
| 408 |
|
| 409 |
class Gemma4Adapter(VisionLanguageAdapter):
|
| 410 |
adapter_id = "gemma4"
|
| 411 |
+
|
| 412 |
@classmethod
|
| 413 |
def score(cls, model_id, config, tags):
|
| 414 |
+
haystack = " ".join([model_id, getattr(config, "model_type", ""), *(getattr(config, "architectures", []) or []), *tags]).lower()
|
| 415 |
+
return 100 if "gemma4" in haystack or "gemma-4" in haystack else 0
|
| 416 |
+
|
| 417 |
@classmethod
|
| 418 |
+
def plan(cls, model_id, config):
|
| 419 |
+
return AdapterPlan(
|
| 420 |
+
cls.adapter_id,
|
| 421 |
+
"Gemma 4 any-to-any / image-text",
|
| 422 |
+
"AutoModelForMultimodalLM",
|
| 423 |
+
"AutoProcessor",
|
| 424 |
+
"qlora",
|
| 425 |
+
["Text and image-conditioned SFT are enabled.", "Accept Gemma model terms before launching."],
|
| 426 |
+
)
|
| 427 |
|
| 428 |
|
| 429 |
ADAPTERS: list[type[TrainingAdapter]] = [Gemma4Adapter, UnlimitedOCRNanoAdapter, Seq2SeqAdapter, VisionLanguageAdapter, CausalLMAdapter]
|
| 430 |
|
| 431 |
+
|
| 432 |
def choose_adapter(adapter_id: str, model_id: str, config: Any, tags: list[str]) -> TrainingAdapter:
|
| 433 |
if adapter_id != "auto":
|
| 434 |
for adapter in ADAPTERS:
|
| 435 |
+
if adapter.adapter_id == adapter_id:
|
| 436 |
+
return adapter()
|
| 437 |
raise ValueError(f"Unknown adapter {adapter_id}")
|
| 438 |
+
selected = max(ADAPTERS, key=lambda adapter: adapter.score(model_id, config, tags))
|
| 439 |
+
return selected()
|
| 440 |
|
| 441 |
|
| 442 |
def training_arguments(args: argparse.Namespace, output_dir: Path, has_eval: bool) -> TrainingArguments:
|
| 443 |
+
kwargs = dict(
|
| 444 |
+
output_dir=str(output_dir),
|
| 445 |
+
per_device_train_batch_size=args.batch_size,
|
| 446 |
+
per_device_eval_batch_size=max(1, args.batch_size),
|
| 447 |
+
gradient_accumulation_steps=args.gradient_accumulation,
|
| 448 |
+
learning_rate=args.learning_rate,
|
| 449 |
+
num_train_epochs=args.epochs,
|
| 450 |
+
max_steps=args.max_steps,
|
| 451 |
+
warmup_ratio=args.warmup_ratio,
|
| 452 |
+
weight_decay=args.weight_decay,
|
| 453 |
+
logging_steps=args.logging_steps,
|
| 454 |
+
save_steps=args.save_steps,
|
| 455 |
+
save_total_limit=2,
|
| 456 |
+
fp16=args.precision == "fp16",
|
| 457 |
+
bf16=args.precision == "bf16",
|
| 458 |
+
gradient_checkpointing=args.gradient_checkpointing,
|
| 459 |
+
remove_unused_columns=False,
|
| 460 |
+
report_to=[],
|
| 461 |
+
prediction_loss_only=True,
|
| 462 |
+
seed=args.seed,
|
| 463 |
+
)
|
| 464 |
signature = inspect.signature(TrainingArguments)
|
| 465 |
+
if "eval_strategy" in signature.parameters:
|
| 466 |
+
kwargs["eval_strategy"] = "steps" if has_eval else "no"
|
| 467 |
+
elif "evaluation_strategy" in signature.parameters:
|
| 468 |
+
kwargs["evaluation_strategy"] = "steps" if has_eval else "no"
|
| 469 |
+
if has_eval:
|
| 470 |
+
kwargs["eval_steps"] = args.eval_steps
|
| 471 |
return TrainingArguments(**kwargs)
|
| 472 |
|
| 473 |
|
| 474 |
def quantization(method: str) -> BitsAndBytesConfig | None:
|
| 475 |
+
if method != "qlora":
|
| 476 |
+
return None
|
| 477 |
+
if not torch.cuda.is_available():
|
| 478 |
+
raise RuntimeError("QLoRA requires a CUDA GPU.")
|
| 479 |
compute_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
|
| 480 |
+
return BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=compute_dtype)
|
| 481 |
|
| 482 |
|
| 483 |
def apply_peft(model: Any, args: argparse.Namespace) -> Any:
|
| 484 |
+
if args.method not in {"lora", "qlora"}:
|
| 485 |
+
return model
|
| 486 |
+
if args.method == "qlora":
|
| 487 |
+
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=args.gradient_checkpointing)
|
| 488 |
+
config = LoraConfig(
|
| 489 |
+
r=args.lora_rank,
|
| 490 |
+
lora_alpha=args.lora_alpha,
|
| 491 |
+
lora_dropout=args.lora_dropout,
|
| 492 |
+
bias="none",
|
| 493 |
+
target_modules="all-linear",
|
| 494 |
+
task_type="SEQ_2_SEQ_LM" if args.adapter == "seq2seq" else "CAUSAL_LM",
|
| 495 |
+
)
|
| 496 |
return get_peft_model(model, config)
|
| 497 |
|
| 498 |
|
| 499 |
def _pick_ocr_file(files: list[str], explicit: str, candidates: list[str]) -> str:
|
| 500 |
if explicit:
|
| 501 |
+
if explicit not in files:
|
| 502 |
+
raise FileNotFoundError(f"Dataset file not found: {explicit}")
|
| 503 |
return explicit
|
| 504 |
for candidate in candidates:
|
| 505 |
+
if candidate in files:
|
| 506 |
+
return candidate
|
| 507 |
raise FileNotFoundError(f"No compatible OCR JSONL found. Tried: {candidates}")
|
| 508 |
|
| 509 |
|
| 510 |
def _subset_jsonl(source: Path, limit: int) -> Path:
|
| 511 |
+
if limit <= 0:
|
| 512 |
+
return source
|
| 513 |
+
destination = source.with_name(f"{source.stem}.subset-{limit}{source.suffix}")
|
| 514 |
+
lines = []
|
| 515 |
+
with source.open("r", encoding="utf-8", errors="replace") as handle:
|
| 516 |
+
for index, line in enumerate(handle):
|
| 517 |
+
if index >= limit:
|
| 518 |
+
break
|
| 519 |
lines.append(line)
|
| 520 |
+
destination.write_text("".join(lines), encoding="utf-8")
|
| 521 |
+
return destination
|
| 522 |
|
| 523 |
|
| 524 |
def run_unlimited_ocr_nano(args: argparse.Namespace, token: str, plan: AdapterPlan) -> None:
|
| 525 |
import yaml
|
| 526 |
+
|
| 527 |
+
api = HfApi(token=token)
|
| 528 |
+
files = api.list_repo_files(args.dataset_id, repo_type="dataset", token=token)
|
| 529 |
+
train_file = _pick_ocr_file(
|
| 530 |
+
files,
|
| 531 |
+
args.train_file,
|
| 532 |
+
["teacher/train.jsonl", f"{args.train_split}.jsonl", "train.jsonl"],
|
| 533 |
+
)
|
| 534 |
+
validation_file = ""
|
| 535 |
+
if args.validation_file:
|
| 536 |
+
validation_file = _pick_ocr_file(files, args.validation_file, [])
|
| 537 |
else:
|
| 538 |
+
for candidate in ["teacher/validation.jsonl", "validation.jsonl"]:
|
| 539 |
+
if candidate in files:
|
| 540 |
+
validation_file = candidate
|
| 541 |
+
break
|
| 542 |
+
|
| 543 |
+
print(json.dumps({
|
| 544 |
+
"event": "adapter",
|
| 545 |
+
**asdict(plan),
|
| 546 |
+
"train_file": train_file,
|
| 547 |
+
"validation_file": validation_file or None,
|
| 548 |
+
}, ensure_ascii=False), flush=True)
|
| 549 |
if args.dry_run:
|
| 550 |
+
print("100% · Unlimited OCR Nano dry-run validation completed", flush=True)
|
| 551 |
+
return
|
| 552 |
+
|
| 553 |
with tempfile.TemporaryDirectory() as tmp:
|
| 554 |
+
root = Path(tmp)
|
| 555 |
+
project = Path(snapshot_download(
|
| 556 |
+
args.model_id,
|
| 557 |
+
repo_type="model",
|
| 558 |
+
token=token,
|
| 559 |
+
local_dir=root / "project",
|
| 560 |
+
allow_patterns=["src/**", "scripts/train.py", "configs/**", "pyproject.toml", "README.md"],
|
| 561 |
+
))
|
| 562 |
+
patterns = [train_file, "pages/**"]
|
| 563 |
+
if validation_file:
|
| 564 |
+
patterns.append(validation_file)
|
| 565 |
+
dataset = Path(snapshot_download(
|
| 566 |
+
args.dataset_id,
|
| 567 |
+
repo_type="dataset",
|
| 568 |
+
token=token,
|
| 569 |
+
local_dir=root / "dataset",
|
| 570 |
+
allow_patterns=patterns,
|
| 571 |
+
max_workers=64,
|
| 572 |
+
))
|
| 573 |
+
train_path = _subset_jsonl(dataset / train_file, args.max_samples)
|
| 574 |
+
validation_path = dataset / validation_file if validation_file else None
|
| 575 |
+
|
| 576 |
+
base_name = "nano-600m-alignment.yaml" if args.method == "projector" else "nano-600m-distill.yaml"
|
| 577 |
+
base_path = project / "configs" / base_name
|
| 578 |
+
if not base_path.exists():
|
| 579 |
+
available = sorted(path.name for path in (project / "configs").glob("*.yaml"))
|
| 580 |
+
raise FileNotFoundError(f"Missing {base_name}; available configs: {available}")
|
| 581 |
+
config = yaml.safe_load(base_path.read_text(encoding="utf-8"))
|
| 582 |
+
training = config.setdefault("training", {})
|
| 583 |
+
training.update({
|
| 584 |
+
"max_length": int(args.max_length),
|
| 585 |
+
"batch_size": int(args.batch_size),
|
| 586 |
+
"gradient_accumulation_steps": int(args.gradient_accumulation),
|
| 587 |
+
"learning_rate": float(args.learning_rate),
|
| 588 |
+
"epochs": float(args.epochs),
|
| 589 |
+
"max_steps": int(args.max_steps),
|
| 590 |
+
"warmup_ratio": float(args.warmup_ratio),
|
| 591 |
+
"weight_decay": float(args.weight_decay),
|
| 592 |
+
"logging_steps": int(args.logging_steps),
|
| 593 |
+
"save_steps": int(args.save_steps),
|
| 594 |
+
"eval_steps": int(args.eval_steps),
|
| 595 |
+
"fp16": args.precision == "fp16",
|
| 596 |
+
"bf16": args.precision == "bf16",
|
| 597 |
+
"gradient_checkpointing": bool(args.gradient_checkpointing),
|
| 598 |
+
"seed": int(args.seed),
|
| 599 |
+
})
|
| 600 |
+
if args.method == "projector":
|
| 601 |
+
training.update({"stage": "alignment", "freeze_language_model": True, "freeze_vision_encoder": True, "use_lora": False})
|
| 602 |
+
elif args.method == "lora":
|
| 603 |
+
training.update({"stage": "distill", "freeze_language_model": False, "use_lora": True})
|
| 604 |
+
lora = training.setdefault("lora", {})
|
| 605 |
+
lora.update({"rank": int(args.lora_rank), "alpha": int(args.lora_alpha), "dropout": float(args.lora_dropout)})
|
| 606 |
+
elif args.method == "full":
|
| 607 |
+
training.update({"stage": "full", "freeze_language_model": False, "freeze_vision_encoder": False, "use_lora": False})
|
| 608 |
+
else:
|
| 609 |
+
raise ValueError("Unlimited OCR Nano supports projector, lora or full methods.")
|
| 610 |
+
|
| 611 |
+
generated_config = root / "ocr-nano-generated.yaml"
|
| 612 |
+
generated_config.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8")
|
| 613 |
+
output_dir = root / "output"
|
| 614 |
+
command = [
|
| 615 |
+
os.environ.get("PYTHON", "python"),
|
| 616 |
+
str(project / "scripts" / "train.py"),
|
| 617 |
+
"--config", str(generated_config),
|
| 618 |
+
"--train-file", str(train_path),
|
| 619 |
+
"--output-dir", str(output_dir),
|
| 620 |
+
]
|
| 621 |
+
if validation_path and validation_path.exists():
|
| 622 |
+
command += ["--validation-file", str(validation_path)]
|
| 623 |
+
if args.resume_checkpoint:
|
| 624 |
+
resume_root = Path(args.resume_checkpoint)
|
| 625 |
+
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 []
|
| 626 |
+
if trainer_states:
|
| 627 |
+
command += ["--resume-training-from", str(trainer_states[-1].parent)]
|
| 628 |
+
else:
|
| 629 |
+
model_roots = [resume_root] + [item.parent for item in resume_root.rglob("config.json")] if resume_root.exists() else []
|
| 630 |
+
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)
|
| 631 |
+
if model_root is not None:
|
| 632 |
+
command += ["--resume-from", str(model_root)]
|
| 633 |
+
else:
|
| 634 |
+
print(json.dumps({"event":"warning","message":f"No resumable OCR checkpoint found below {resume_root}"}), flush=True)
|
| 635 |
+
environment = dict(os.environ)
|
| 636 |
+
environment["PYTHONPATH"] = str(project / "src")
|
| 637 |
+
subprocess.run(command, check=True, env=environment)
|
| 638 |
+
manifest = {
|
| 639 |
+
"model_id": args.model_id,
|
| 640 |
+
"dataset_id": args.dataset_id,
|
| 641 |
+
"adapter": plan.adapter_id,
|
| 642 |
+
"method": args.method,
|
| 643 |
+
"train_file": train_file,
|
| 644 |
+
"validation_file": validation_file or None,
|
| 645 |
+
"arguments": vars(args),
|
| 646 |
+
}
|
| 647 |
+
(output_dir / "generic_trainer_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
| 648 |
+
api.create_repo(args.output_repo, repo_type="model", private=True, exist_ok=True, token=token)
|
| 649 |
+
api.upload_folder(
|
| 650 |
+
folder_path=output_dir,
|
| 651 |
+
repo_id=args.output_repo,
|
| 652 |
+
repo_type="model",
|
| 653 |
+
token=token,
|
| 654 |
+
commit_message=f"Generic Trainer OCR Nano: {args.method}",
|
| 655 |
+
)
|
| 656 |
+
print(f"100% · uploaded OCR Nano checkpoint to {args.output_repo}", flush=True)
|
| 657 |
|
| 658 |
|
| 659 |
def parse_args() -> argparse.Namespace:
|
| 660 |
+
parser = argparse.ArgumentParser(description="Generic Transformers training job")
|
| 661 |
+
parser.add_argument("--model-id", required=True)
|
| 662 |
+
parser.add_argument("--dataset-id", required=True)
|
| 663 |
+
parser.add_argument("--dataset-config", default="")
|
| 664 |
+
parser.add_argument("--train-split", default="train")
|
| 665 |
+
parser.add_argument("--train-file", default="")
|
| 666 |
+
parser.add_argument("--validation-file", default="")
|
| 667 |
+
parser.add_argument("--validation-split", default="")
|
| 668 |
+
parser.add_argument("--output-repo", required=True)
|
| 669 |
+
parser.add_argument("--adapter", default="auto", choices=["auto", "gemma4", "unlimited-ocr-nano", "vision-language", "seq2seq", "causal-lm"])
|
| 670 |
+
parser.add_argument("--method", default="lora", choices=["projector", "lora", "qlora", "full"])
|
| 671 |
+
parser.add_argument("--text-column", default="text")
|
| 672 |
+
parser.add_argument("--prompt-column", default="prompt")
|
| 673 |
+
parser.add_argument("--response-column", default="response")
|
| 674 |
+
parser.add_argument("--messages-column", default="messages")
|
| 675 |
+
parser.add_argument("--image-column", default="image")
|
| 676 |
+
parser.add_argument("--max-samples", type=int, default=0)
|
| 677 |
+
parser.add_argument("--max-length", type=int, default=2048)
|
| 678 |
+
parser.add_argument("--batch-size", type=int, default=1)
|
| 679 |
+
parser.add_argument("--gradient-accumulation", type=int, default=8)
|
| 680 |
+
parser.add_argument("--learning-rate", type=float, default=2e-4)
|
| 681 |
+
parser.add_argument("--epochs", type=float, default=1.0)
|
| 682 |
+
parser.add_argument("--max-steps", type=int, default=-1)
|
| 683 |
+
parser.add_argument("--warmup-ratio", type=float, default=0.03)
|
| 684 |
+
parser.add_argument("--weight-decay", type=float, default=0.0)
|
| 685 |
+
parser.add_argument("--logging-steps", type=int, default=1)
|
| 686 |
+
parser.add_argument("--save-steps", type=int, default=50)
|
| 687 |
+
parser.add_argument("--eval-steps", type=int, default=50)
|
| 688 |
+
parser.add_argument("--precision", choices=["fp32", "fp16", "bf16"], default="bf16")
|
| 689 |
+
parser.add_argument("--gradient-checkpointing", action="store_true")
|
| 690 |
+
parser.add_argument("--lora-rank", type=int, default=16)
|
| 691 |
+
parser.add_argument("--lora-alpha", type=int, default=32)
|
| 692 |
+
parser.add_argument("--lora-dropout", type=float, default=0.05)
|
| 693 |
+
parser.add_argument("--trust-remote-code", action="store_true")
|
| 694 |
+
parser.add_argument("--resume-checkpoint", default="")
|
| 695 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 696 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 697 |
return parser.parse_args()
|
| 698 |
|
| 699 |
|
| 700 |
def main() -> None:
|
| 701 |
+
telemetry = start_telemetry()
|
| 702 |
+
args = parse_args()
|
| 703 |
+
token = os.environ["HF_TOKEN"]
|
| 704 |
+
api = HfApi(token=token)
|
| 705 |
+
info = api.model_info(args.model_id, token=token)
|
| 706 |
+
is_ocr_nano = args.adapter == "unlimited-ocr-nano" or "unlimited-ocr-nano" in args.model_id.lower()
|
| 707 |
if is_ocr_nano:
|
| 708 |
+
class OCRConfig:
|
| 709 |
+
model_type = "unlimited_ocr_nano"
|
| 710 |
+
architectures = ["UnlimitedOCRNanoForConditionalGeneration"]
|
| 711 |
+
is_encoder_decoder = False
|
| 712 |
+
config = OCRConfig()
|
| 713 |
+
else:
|
| 714 |
+
config = AutoConfig.from_pretrained(args.model_id, token=token, trust_remote_code=args.trust_remote_code)
|
| 715 |
+
adapter = choose_adapter(args.adapter, args.model_id, config, list(info.tags or []))
|
| 716 |
+
plan = adapter.plan(args.model_id, config)
|
| 717 |
+
args.adapter = plan.adapter_id
|
| 718 |
+
if plan.adapter_id == "unlimited-ocr-nano":
|
| 719 |
+
run_unlimited_ocr_nano(args, token, plan)
|
| 720 |
+
return
|
| 721 |
+
print(json.dumps({"event": "adapter", **asdict(plan)}, ensure_ascii=False), flush=True)
|
| 722 |
+
|
| 723 |
+
dataset_kwargs: dict[str, Any] = {"path": args.dataset_id, "split": args.train_split, "token": token}
|
| 724 |
+
if args.dataset_config:
|
| 725 |
+
dataset_kwargs["name"] = args.dataset_config
|
| 726 |
+
train = load_dataset(**dataset_kwargs)
|
| 727 |
+
if args.max_samples > 0:
|
| 728 |
+
train = train.select(range(min(args.max_samples, len(train))))
|
| 729 |
+
validation = None
|
| 730 |
if args.validation_split:
|
| 731 |
+
validation_kwargs = dict(dataset_kwargs)
|
| 732 |
+
validation_kwargs["split"] = args.validation_split
|
| 733 |
+
validation = load_dataset(**validation_kwargs)
|
| 734 |
+
if args.max_samples > 0:
|
| 735 |
+
validation = validation.select(range(min(max(1, args.max_samples // 10), len(validation))))
|
| 736 |
+
|
| 737 |
+
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)
|
| 738 |
+
if args.dry_run:
|
| 739 |
+
print("100% · dry-run validation completed", flush=True)
|
| 740 |
+
return
|
| 741 |
+
|
| 742 |
with tempfile.TemporaryDirectory() as tmp:
|
| 743 |
+
output_dir = Path(tmp) / "output"
|
| 744 |
+
output_dir.mkdir(parents=True)
|
| 745 |
+
model, processor = adapter.load(args, quantization(args.method))
|
| 746 |
+
model = apply_peft(model, args)
|
| 747 |
+
if hasattr(model, "config") and args.gradient_checkpointing:
|
| 748 |
+
model.config.use_cache = False
|
| 749 |
+
if hasattr(model, "print_trainable_parameters"):
|
| 750 |
+
model.print_trainable_parameters()
|
| 751 |
+
trainer = adapter.build_trainer(args, model, processor, train, validation, output_dir)
|
| 752 |
+
trainer.train(resume_from_checkpoint=(args.resume_checkpoint or None))
|
| 753 |
+
trainer.save_model(output_dir)
|
| 754 |
+
if hasattr(processor, "save_pretrained"):
|
| 755 |
+
processor.save_pretrained(output_dir)
|
| 756 |
+
manifest = {"model_id": args.model_id, "dataset_id": args.dataset_id, "adapter": plan.adapter_id, "method": args.method, "arguments": vars(args)}
|
| 757 |
+
(output_dir / "training_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
| 758 |
+
api.create_repo(args.output_repo, repo_type="model", private=True, exist_ok=True, token=token)
|
| 759 |
+
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}")
|
| 760 |
+
print(f"100% · uploaded model to {args.output_repo}", flush=True)
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
if __name__ == "__main__":
|
| 764 |
+
main()
|