Coverage for collectra/tasks/ocr_huggingface.py: 22.38%

362 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1"""Image-to-text recognition with Transformers vision-language models. 

2 

3Any model that loads natively with ``AutoModelForImageTextToText`` and 

4``AutoProcessor`` is supported, without remote code: for example 

5DeepSeek-OCR-2, GLM-OCR, LightOnOCR, PaddleOCR-VL and Qianfan-OCR. 

6Models with a chat template receive the image and prompt as a user message; 

7others receive the prompt directly, with the image token prepended if absent. 

8""" 

9 

10from __future__ import annotations 

11 

12import json 

13import random 

14import shutil 

15import time 

16from typing import Annotated 

17from pydantic import BaseModel 

18 

19from collectra.commons import PositionalFields 

20from datetime import datetime 

21from pathlib import Path 

22 

23from cappa import Arg 

24from PIL import Image as PILImage 

25from rich.progress import track 

26 

27from collectra.cli import command 

28from collectra.tasks.text_output import TextOutputTask 

29from collectra.types.images import Image, open_oriented 

30from collectra.types.texts import Text 

31from collectra.utils import threading_locked 

32 

33__all__ = ["OCRHuggingFace", "character_error_rate"] 

34 

35DEFAULT_MODEL = "deepseek-community/DeepSeek-OCR-2" 

36DEFAULT_PROMPT = "Free OCR." 

37SPLITS = ("train", "validation") 

38 

39 

40def training_progress(message): 

41 """Keep progress visible in terminals and redirected cluster job logs.""" 

42 print(f"[OCR] {message}", flush=True) 

43 

44 

45def _edit_distance(prediction: str, reference: str) -> int: 

46 previous = list(range(len(reference) + 1)) 

47 for i, predicted in enumerate(prediction, 1): 

48 current = [i] 

49 for j, expected in enumerate(reference, 1): 

50 current.append( 

51 min( 

52 previous[j] + 1, 

53 current[j - 1] + 1, 

54 previous[j - 1] + (predicted != expected), 

55 ) 

56 ) 

57 previous = current 

58 return previous[-1] 

59 

60 

61def character_error_rate(predictions: list[str], references: list[str]) -> float: 

62 """Total character edits divided by total reference characters.""" 

63 edits = sum(map(_edit_distance, predictions, references)) 

64 return edits / max(1, sum(len(reference) for reference in references)) 

65 

66 

67def _rgb(image: PILImage.Image) -> PILImage.Image: 

68 """Flatten masked (transparent) regions onto white, as on a page.""" 

69 if image.mode in {"RGBA", "LA", "P"}: 

70 image = image.convert("RGBA") 

71 background = PILImage.new("RGBA", image.size, "white") 

72 return PILImage.alpha_composite(background, image).convert("RGB") 

73 return image.convert("RGB") 

74 

75 

76class OCRSample(PositionalFields, BaseModel): 

77 image: Image 

78 text: str 

79 partition: str = "" 

80 

81 

82class _ExportedLines: 

83 """Exported line images and transcriptions of one dataset split.""" 

84 

85 def __init__(self, directory: Path): 

86 self.directory = directory 

87 with open(directory / "labels.jsonl", encoding="utf-8") as stream: 

88 self.items = [json.loads(line) for line in stream if line.strip()] 

89 

90 def __len__(self): 

91 return len(self.items) 

92 

93 def __getitem__(self, index): 

94 item = self.items[index] 

95 return _rgb(open_oriented(self.directory / item["file"])), item["text"] 

96 

97 

98class OCRHuggingFace(TextOutputTask): 

99 """Transcribe images with a Transformers image-text-to-text model.""" 

100 

101 def __init__( 

102 self, 

103 name: str, 

104 model: str | Path = DEFAULT_MODEL, 

105 prompt: str = DEFAULT_PROMPT, 

106 max_new_tokens: int = 256, 

107 device: str = "", 

108 dtype: str = "auto", 

109 **kwargs, 

110 ): 

111 super().__init__(name, **kwargs) 

112 self.model, self.prompt = model, prompt 

113 self.max_new_tokens, self.device, self.dtype = max_new_tokens, device, dtype 

114 self._model = None 

115 self._processor = None 

116 

117 def attributes_to_ignore(self): 

118 return super().attributes_to_ignore() | {"_model", "_processor"} 

119 

120 def input_type(self) -> type: 

121 return Image 

122 

123 def output_type(self) -> type: 

124 return Text 

125 

126 @staticmethod 

127 def _select_device(device: str = "") -> str: 

128 import torch 

129 

130 if device: 

131 return device 

132 if torch.cuda.is_available(): 

133 return "cuda" 

134 if torch.backends.mps.is_available(): 

135 return "mps" 

136 return "cpu" 

137 

138 def _source(self, model: str | Path | None = None) -> str: 

139 """Resolve local directories relative to the pipeline, else a Hub model ID.""" 

140 model = str(model or self.model) 

141 path = Path(model).expanduser() 

142 if not path.is_absolute() and self.pipeline is not None: 

143 if (Path(self.pipeline.path) / path).is_dir(): 

144 path = Path(self.pipeline.path) / path 

145 if path.is_dir(): 

146 return str(path.resolve()) 

147 if model.startswith(("/", "./", "../", "~")): 

148 raise FileNotFoundError(f"Model directory does not exist: {path}") 

149 return model 

150 

151 def _load(self, model: str | Path | None = None) -> None: 

152 if self._model is not None and model is None: 

153 return 

154 import torch 

155 from transformers import AutoModelForImageTextToText, AutoProcessor 

156 

157 source = self._source(model) 

158 device = self._select_device(self.device) 

159 dtype = self.dtype if self.dtype == "auto" else getattr(torch, self.dtype) 

160 self._processor = AutoProcessor.from_pretrained( 

161 source, trust_remote_code=False 

162 ) 

163 self._model = AutoModelForImageTextToText.from_pretrained( 

164 source, dtype=dtype, trust_remote_code=False 

165 ).to(device) 

166 self._model.eval() 

167 

168 @property 

169 def _tokenizer(self): 

170 return self._processor.tokenizer 

171 

172 def _prompt_text(self) -> str: 

173 """The text preceding the transcription, for inference and training alike.""" 

174 processor = self._processor 

175 if getattr(processor, "chat_template", None): 

176 content = [{"type": "image"}] 

177 if self.prompt: 

178 content.append({"type": "text", "text": self.prompt}) 

179 return processor.apply_chat_template( 

180 [{"role": "user", "content": content}], 

181 add_generation_prompt=True, 

182 tokenize=False, 

183 ) 

184 image_token = getattr(processor, "image_token", None) or "<image>" 

185 if image_token in self.prompt: 

186 return self.prompt 

187 return f"{image_token}\n{self.prompt}" if self.prompt else image_token 

188 

189 def _encode_prompts(self, images: list[PILImage.Image]): 

190 """Left-padded prompts so every row ends where generation begins.""" 

191 tokenizer = self._tokenizer 

192 side, tokenizer.padding_side = tokenizer.padding_side, "left" 

193 try: 

194 return self._processor( 

195 images=images, 

196 text=[self._prompt_text()] * len(images), 

197 padding=True, 

198 return_tensors="pt", 

199 ) 

200 finally: 

201 tokenizer.padding_side = side 

202 

203 def _to_device(self, inputs: dict) -> dict: 

204 import torch 

205 

206 dtype = self._model.dtype 

207 return { 

208 name: ( 

209 value.to(self._model.device, dtype=dtype) 

210 if torch.is_floating_point(value) 

211 else value.to(self._model.device) 

212 ) 

213 for name, value in inputs.items() 

214 } 

215 

216 def _generate(self, images: list[PILImage.Image]) -> list[str]: 

217 import torch 

218 

219 inputs = self._encode_prompts(images) 

220 with torch.inference_mode(): 

221 generated = self._model.generate( 

222 **self._to_device(inputs), 

223 max_new_tokens=self.max_new_tokens, 

224 do_sample=False, 

225 ) 

226 texts = self._processor.batch_decode( 

227 generated[:, inputs["input_ids"].shape[1] :], skip_special_tokens=True 

228 ) 

229 return [text.strip() for text in texts] 

230 

231 def _training_batch(self, images: list[PILImage.Image], texts: list[str]): 

232 """Append each tokenized transcription to its prompt and mask the prompt. 

233 

234 Tokenizing transcriptions separately keeps the loss boundary exact: 

235 joint tokenization could merge the last prompt and first text tokens. 

236 """ 

237 import torch 

238 

239 tokenizer = self._tokenizer 

240 prompts = self._encode_prompts(images) 

241 input_ids, mask = prompts["input_ids"], prompts["attention_mask"].bool() 

242 # Sequence-aligned extras (e.g. token type ids) are extended with zeros. 

243 aligned = [ 

244 name 

245 for name, value in prompts.items() 

246 if name not in {"input_ids", "attention_mask"} 

247 and torch.is_tensor(value) 

248 and value.shape[:2] == input_ids.shape 

249 ] 

250 rows = [] 

251 for index, text in enumerate(texts): 

252 target = tokenizer(text, add_special_tokens=False).input_ids 

253 target = torch.tensor([*target, tokenizer.eos_token_id]) 

254 prompt = input_ids[index][mask[index]] 

255 rows.append((index, prompt, target)) 

256 length = max(len(prompt) + len(target) for _, prompt, target in rows) 

257 pad_id = ( 

258 tokenizer.pad_token_id 

259 if tokenizer.pad_token_id is not None 

260 else tokenizer.eos_token_id 

261 ) 

262 batch = { 

263 "input_ids": torch.full((len(rows), length), pad_id), 

264 "attention_mask": torch.zeros((len(rows), length), dtype=torch.long), 

265 "labels": torch.full((len(rows), length), -100), 

266 } 

267 for name in aligned: 

268 batch[name] = torch.zeros( 

269 (len(rows), length, *prompts[name].shape[2:]), 

270 dtype=prompts[name].dtype, 

271 ) 

272 for index, prompt, target in rows: 

273 size = len(prompt) + len(target) 

274 batch["input_ids"][index, :size] = torch.cat([prompt, target]) 

275 batch["attention_mask"][index, :size] = 1 

276 batch["labels"][index, len(prompt) : size] = target 

277 for name in aligned: 

278 batch[name][index, : len(prompt)] = prompts[name][index][mask[index]] 

279 for name, value in prompts.items(): 

280 if name not in batch and name != "attention_mask": 

281 batch[name] = value 

282 return batch 

283 

284 @threading_locked() 

285 def run(self, *images: Image) -> list[Text]: 

286 """Transcribe each image or crop and return one Text per input.""" 

287 if not images or any(not isinstance(image, Image) for image in images): 

288 raise TypeError("OCRHuggingFace requires one or more Image artefacts") 

289 self._load() 

290 texts = self._generate([_rgb(image.pil()) for image in images]) 

291 return [self.text_output(text) for text in texts] 

292 

293 def _samples( 

294 self, inputs: list[str], exclude: str = "", max_items: int | None = None 

295 ): 

296 """Pair each transcribed Text output with the image it was read from.""" 

297 from collectra.tasks.machine_learning.training import ( 

298 _prepare_data, 

299 _training_files, 

300 ) 

301 

302 if self.pipeline is None: 

303 raise RuntimeError( 

304 "Attach the task to a pipeline before preparing training data" 

305 ) 

306 self.pipeline._ensure_workflow_connected() 

307 node = self.pipeline.node_manager.resolve_node(self.name) 

308 children = self.pipeline.node_manager.get_children_artefact(node) 

309 ancestors = self.pipeline.node_manager.get_ancestor_artefacts(node) 

310 files = [] 

311 for value in inputs: 

312 path = Path(value).expanduser().resolve() 

313 if path.name == "results.yaml" and path.is_file(): 

314 path = path.parent 

315 if path.is_dir() and (path / "results.yaml").is_file(): 

316 files.append(path) 

317 else: 

318 files.extend(_training_files(self, [str(path)])) 

319 files = list(dict.fromkeys(files)) 

320 samples = [] 

321 for path in track(files, description="Loading transcriptions"): 

322 # Read each result independently: artefact ids may repeat across datasets. 

323 texts, _ = _prepare_data(self, [path], children) 

324 parents, _ = _prepare_data(self, [path], ancestors) 

325 images = {item.id: item for item in parents if isinstance(item, Image)} 

326 for text in texts: 

327 if not isinstance(text, Text) or not str(text.data).strip(): 

328 continue 

329 parent_ids = text.parents or [] 

330 parent_ids = [parent_ids] if isinstance(parent_ids, str) else parent_ids 

331 image = next((images[i] for i in parent_ids if i in images), None) 

332 if image is None: 

333 continue 

334 partition = text.partition or "" 

335 if exclude and partition == exclude: 

336 continue 

337 samples.append(OCRSample(image, str(text.data).strip(), partition)) 

338 if max_items is not None and len(samples) >= max_items: 

339 return samples 

340 return samples 

341 

342 def prepare_training_data( 

343 self, 

344 inputs: list[str], 

345 output: Path, 

346 validation: str = "", 

347 exclude: str = "", 

348 max_items: int | None = None, 

349 ) -> Path: 

350 """Export line images to OUTPUT/{train,validation} with labels.jsonl files.""" 

351 samples = self._samples(inputs, exclude, max_items) 

352 if not samples: 

353 raise ValueError( 

354 f"No transcribed images found for the outputs of {self.name!r}" 

355 ) 

356 for split in SPLITS: 

357 if (output / split).exists(): 

358 shutil.rmtree(output / split) 

359 (output / split).mkdir(parents=True) 

360 counts = dict.fromkeys(SPLITS, 0) 

361 labels = { 

362 split: open(output / split / "labels.jsonl", "w", encoding="utf-8") 

363 for split in SPLITS 

364 } 

365 try: 

366 for sample in track(samples, description="Exporting images"): 

367 split = ( 

368 "validation" 

369 if validation and sample.partition == validation 

370 else "train" 

371 ) 

372 name = f"{counts[split]:07d}.png" 

373 _rgb(sample.image.pil()).save(output / split / name) 

374 labels[split].write( 

375 json.dumps({"file": name, "text": sample.text}, ensure_ascii=False) 

376 + "\n" 

377 ) 

378 counts[split] += 1 

379 finally: 

380 for stream in labels.values(): 

381 stream.close() 

382 training_progress( 

383 f"Exported {counts['train']} training and {counts['validation']} validation images" 

384 ) 

385 if not counts["train"]: 

386 raise ValueError("No training images remain after partitioning") 

387 return output 

388 

389 def _evaluate(self, dataset, batch: int) -> dict: 

390 import torch 

391 

392 self._model.eval() 

393 losses, predictions, references = [], [], [] 

394 for start in track(range(0, len(dataset), batch), description="Validating"): 

395 images, texts = zip(*(dataset[i] for i in range(start, min(start + batch, len(dataset))))) 

396 with torch.inference_mode(): 

397 inputs = self._to_device(self._training_batch(list(images), list(texts))) 

398 losses.append(self._model(**inputs).loss.item()) 

399 predictions.extend(self._generate(list(images))) 

400 references.extend(texts) 

401 return { 

402 "val_loss": sum(losses) / len(losses), 

403 "cer": character_error_rate(predictions, references), 

404 } 

405 

406 @command 

407 def train( 

408 self, 

409 inputs: Annotated[ 

410 list[str], 

411 Arg( 

412 required=False, 

413 default=[], 

414 help="Results YAML files, result directories, or parent directories containing transcribed images. May be omitted when reusing an existing export.", 

415 ), 

416 ], 

417 model: Annotated[ 

418 str, 

419 Arg( 

420 help="Hugging Face model ID or local save_pretrained directory to fine-tune. Omit to continue from the configured model." 

421 ), 

422 ] = "", 

423 output: Annotated[ 

424 Path | None, 

425 Arg( 

426 help="Directory for exported images, metrics.csv and the best model. Defaults to a timestamped directory; required with --reuse-data." 

427 ), 

428 ] = None, 

429 validation: Annotated[ 

430 str, 

431 Arg( 

432 help="Partition used for validation and best-model selection by character error rate. Omit to train without validation." 

433 ), 

434 ] = "", 

435 exclude: Annotated[ 

436 str, 

437 Arg(help="Partition excluded from both training and validation."), 

438 ] = "", 

439 epochs: Annotated[int, Arg(help="Number of training epochs.")] = 5, 

440 batch: Annotated[int, Arg(help="Number of images per batch.")] = 4, 

441 accumulate: Annotated[ 

442 int, 

443 Arg(help="Number of batches to accumulate before each optimizer step."), 

444 ] = 1, 

445 learning_rate: Annotated[ 

446 float, Arg(help="Initial learning rate for AdamW.") 

447 ] = 0.00001, 

448 weight_decay: Annotated[ 

449 float, Arg(help="Weight decay used for regularization.") 

450 ] = 0.0, 

451 lora: Annotated[ 

452 bool, 

453 Arg( 

454 help="Train low-rank adapters (requires peft) instead of all weights; adapters are merged into the saved model." 

455 ), 

456 ] = False, 

457 lora_rank: Annotated[int, Arg(help="Rank of the LoRA adapters.")] = 16, 

458 freeze_vision: Annotated[ 

459 bool, 

460 Arg( 

461 help="Freeze vision-encoder parameters and train only the language model and projector." 

462 ), 

463 ] = False, 

464 gradient_checkpointing: Annotated[ 

465 bool, 

466 Arg(help="Recompute activations in the backward pass to save memory."), 

467 ] = False, 

468 early_stop: Annotated[ 

469 int, 

470 Arg( 

471 help="Stop after this many epochs without character-error-rate improvement; 0 disables." 

472 ), 

473 ] = 3, 

474 max_items: Annotated[ 

475 int | None, 

476 Arg( 

477 help="Maximum transcribed images to load across both splits, after exclusions. Omit for all." 

478 ), 

479 ] = None, 

480 reuse_data: Annotated[ 

481 bool, 

482 Arg( 

483 help="Reuse OUTPUT/dataset when both splits exist instead of exporting again. Requires --output." 

484 ), 

485 ] = False, 

486 keep_log: Annotated[ 

487 bool, 

488 Arg( 

489 help="Keep exported data, metrics and checkpoints after copying the best model into the pipeline." 

490 ), 

491 ] = True, 

492 seed: Annotated[ 

493 int, Arg(help="Random seed for shuffling and initialization.") 

494 ] = 0, 

495 wandb: Annotated[ 

496 bool, 

497 Arg( 

498 help="Log epoch metrics to Weights & Biases. Project: <pipeline-directory>-<task>; run: output directory name; entity: W&B settings or WANDB_ENTITY." 

499 ), 

500 ] = False, 

501 ) -> Path: 

502 """Fine-tune the model on transcribed images and save the best model to the pipeline.""" 

503 import torch 

504 

505 if min(epochs, batch, accumulate, lora_rank) < 1: 

506 raise ValueError("epochs, batch, accumulate and lora_rank must be positive") 

507 if reuse_data and output is None: 

508 raise ValueError("--reuse-data requires --output") 

509 if self.pipeline is None: 

510 raise RuntimeError(f"Task {self.name!r} is not attached to a pipeline") 

511 output = ( 

512 Path(output).expanduser().resolve() 

513 if output is not None 

514 else Path.cwd() / datetime.now().strftime("%Y%m%d_%H%M%S") 

515 ) 

516 dataset_dir = output / "dataset" 

517 if reuse_data and all( 

518 (dataset_dir / split / "labels.jsonl").is_file() for split in SPLITS 

519 ): 

520 training_progress(f"Reusing exported dataset: {dataset_dir}") 

521 else: 

522 if not inputs: 

523 raise ValueError("Supply training inputs to export the dataset") 

524 self.prepare_training_data( 

525 inputs, dataset_dir, validation, exclude, max_items=max_items 

526 ) 

527 train_set = _ExportedLines(dataset_dir / "train") 

528 val_set = _ExportedLines(dataset_dir / "validation") 

529 if not len(train_set): 

530 raise ValueError(f"No training images in {dataset_dir / 'train'}") 

531 

532 random.seed(seed) 

533 torch.manual_seed(seed) 

534 training_progress(f"Loading {model or self.model}") 

535 self._load(model or self.model) 

536 network = self._model 

537 if gradient_checkpointing: 

538 network.gradient_checkpointing_enable() 

539 if lora: 

540 network.enable_input_require_grads() 

541 if lora: 

542 try: 

543 from peft import ( 

544 LoraConfig, 

545 get_peft_model, 

546 get_peft_model_state_dict, 

547 set_peft_model_state_dict, 

548 ) 

549 except ModuleNotFoundError as error: 

550 raise ImportError("--lora requires peft: pip install peft") from error 

551 network = get_peft_model( 

552 network, 

553 LoraConfig( 

554 r=lora_rank, 

555 lora_alpha=2 * lora_rank, 

556 target_modules="all-linear", 

557 lora_dropout=0.05, 

558 ), 

559 ) 

560 if freeze_vision: 

561 frozen = 0 

562 for name, parameter in network.named_parameters(): 

563 if any(part in name for part in ("vision", "visual", "sam_model")): 

564 parameter.requires_grad_(False) 

565 frozen += 1 

566 if not frozen: 

567 raise ValueError( 

568 f"No vision parameters found to freeze in {type(self._model).__name__}" 

569 ) 

570 parameters = [p for p in network.parameters() if p.requires_grad] 

571 if not parameters: 

572 raise ValueError("No trainable parameters remain") 

573 optimizer = torch.optim.AdamW( 

574 parameters, lr=learning_rate, weight_decay=weight_decay 

575 ) 

576 steps = epochs * -(-len(train_set) // (batch * accumulate)) 

577 scheduler = torch.optim.lr_scheduler.LambdaLR( 

578 optimizer, lambda step: max(0.0, 1 - step / max(1, steps)) 

579 ) 

580 training_progress( 

581 f"Training {self.name}: {len(train_set)} training and {len(val_set)} validation images, " 

582 f"epochs={epochs}, batch={batch}x{accumulate}, device={self._model.device}" 

583 ) 

584 

585 best_dir = output / "best" 

586 metrics_path = output / "metrics.csv" 

587 metrics_path.write_text("epoch,train_loss,val_loss,cer\n") 

588 best_cer, stale, best_adapters = float("inf"), 0, None 

589 started = time.monotonic() 

590 run = None 

591 if wandb: 

592 try: 

593 import wandb as sdk 

594 except ModuleNotFoundError as error: 

595 raise ImportError("--wandb requires wandb: pip install wandb") from error 

596 run = sdk.init( 

597 project=f"{self.pipeline.name}-{self.name}", 

598 name=output.name, 

599 dir=str(output), 

600 config={ 

601 "model": str(model or self.model), 

602 "prompt": self.prompt, 

603 "train_images": len(train_set), 

604 "validation_images": len(val_set), 

605 "epochs": epochs, 

606 "batch": batch, 

607 "accumulate": accumulate, 

608 "learning_rate": learning_rate, 

609 "weight_decay": weight_decay, 

610 "lora": lora, 

611 "lora_rank": lora_rank if lora else None, 

612 "freeze_vision": freeze_vision, 

613 "gradient_checkpointing": gradient_checkpointing, 

614 "seed": seed, 

615 }, 

616 ) 

617 run.define_metric("epoch") 

618 run.define_metric("*", step_metric="epoch") 

619 try: 

620 for epoch in range(1, epochs + 1): 

621 network.train() 

622 order = list(range(len(train_set))) 

623 random.shuffle(order) 

624 total, count = 0.0, 0 

625 optimizer.zero_grad() 

626 batches = [order[i : i + batch] for i in range(0, len(order), batch)] 

627 for step, indices in enumerate( 

628 track(batches, description=f"Epoch {epoch}/{epochs}"), 1 

629 ): 

630 images, texts = zip(*(train_set[i] for i in indices)) 

631 inputs_ = self._to_device( 

632 self._training_batch(list(images), list(texts)) 

633 ) 

634 loss = network(**inputs_).loss 

635 (loss / accumulate).backward() 

636 total, count = total + loss.item(), count + 1 

637 if step % accumulate == 0 or step == len(batches): 

638 optimizer.step() 

639 scheduler.step() 

640 optimizer.zero_grad() 

641 metrics = {"train_loss": total / count} 

642 if len(val_set): 

643 metrics |= self._evaluate(val_set, batch) 

644 training_progress( 

645 f"Epoch {epoch}: " 

646 + ", ".join(f"{name}={value:.4f}" for name, value in metrics.items()) 

647 ) 

648 if run is not None: 

649 run.log({"epoch": epoch, **metrics}) 

650 with open(metrics_path, "a") as stream: 

651 stream.write( 

652 f"{epoch},{metrics['train_loss']},{metrics.get('val_loss', '')},{metrics.get('cer', '')}\n" 

653 ) 

654 # Without validation the latest epoch is kept. 

655 cer = metrics.get("cer", -epoch) 

656 if cer < best_cer: 

657 best_cer, stale = cer, 0 

658 if run is not None and "cer" in metrics: 

659 run.summary["best_cer"] = cer 

660 run.summary["best_epoch"] = epoch 

661 if best_dir.exists(): 

662 shutil.rmtree(best_dir) 

663 if lora: 

664 # Adapters are small: keep the best in memory and merge once at the end. 

665 best_adapters = { 

666 name: value.detach().cpu().clone() 

667 for name, value in get_peft_model_state_dict(network).items() 

668 } 

669 else: 

670 network.save_pretrained(best_dir) 

671 self._processor.save_pretrained(best_dir) 

672 else: 

673 stale += 1 

674 if early_stop and stale >= early_stop: 

675 training_progress(f"Stopping early after {epoch} epochs") 

676 break 

677 finally: 

678 if run is not None: 

679 run.finish() 

680 

681 if lora: 

682 set_peft_model_state_dict(network, best_adapters) 

683 network.merge_and_unload().save_pretrained(best_dir) 

684 self._processor.save_pretrained(best_dir) 

685 

686 destination = self.pipeline.path / f"{self.name}-{output.name}" 

687 if destination.exists(): 

688 shutil.rmtree(destination) 

689 shutil.copytree(best_dir, destination) 

690 self.model = destination.name 

691 self._model = self._processor = None 

692 self.pipeline.data[self.name]["model"] = destination.name 

693 self.pipeline.save(self.name) 

694 training_progress( 

695 f"Saved model to {destination} ({time.monotonic() - started:.1f}s)" 

696 ) 

697 if not keep_log: 

698 shutil.rmtree(output, ignore_errors=True) 

699 return destination