"""
Donut
Copyright (c) 2022-present NAVER Corp.
MIT License
"""
import argparse
import datetime
import json
import os
import random
from io import BytesIO
from os.path import basename
from pathlib import Path
import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint
from pytorch_lightning.loggers.tensorboard import TensorBoardLogger
from pytorch_lightning.plugins import CheckpointIO
from pytorch_lightning.utilities import rank_zero_only
from sconf import Config
from donut import DonutDataset
from lightning_module import DonutDataPLModule, DonutModelPLModule
class CustomCheckpointIO(CheckpointIO):
def save_checkpoint(self, checkpoint, path, storage_options=None):
del checkpoint["state_dict"]
torch.save(checkpoint, path)
def load_checkpoint(self, path, storage_options=None):
checkpoint = torch.load(path + "artifacts.ckpt")
state_dict = torch.load(path + "pytorch_model.bin")
checkpoint["state_dict"] = {"model." + key: value for key, value in state_dict.items()}
return checkpoint
def remove_checkpoint(self, path) -> None:
return super().remove_checkpoint(path)
@rank_zero_only
def save_config_file(config, path):
if not Path(path).exists():
os.makedirs(path)
save_path = Path(path) / "config.yaml"
print(config.dumps())
with open(save_path, "w") as f:
f.write(config.dumps(modified_color=None, quote_str=True))
print(f"Config is saved at {save_path}")
class ProgressBar(pl.callbacks.TQDMProgressBar):
def __init__(self, config):
super().__init__()
self.enable = True
self.config = config
def disable(self):
self.enable = False
def get_metrics(self, trainer, model):
items = super().get_metrics(trainer, model)
items.pop("v_num", None)
items["exp_name"] = f"{self.config.get('exp_name', '')}"
items["exp_version"] = f"{self.config.get('exp_version', '')}"
return items
def set_seed(seed):
pytorch_lightning_version = int(pl.__version__[0])
if pytorch_lightning_version < 2:
pl.utilities.seed.seed_everything(seed, workers=True)
else:
import lightning_fabric
lightning_fabric.utilities.seed.seed_everything(seed, workers=True)
def train(config):
set_seed(config.get("seed", 42))
model_module = DonutModelPLModule(config)
data_module = DonutDataPLModule(config)
# add datasets to data_module
datasets = {"train": [], "validation": []}
for i, dataset_name_or_path in enumerate(config.dataset_name_or_paths):
task_name = os.path.basename(dataset_name_or_path) # e.g., cord-v2, docvqa, rvlcdip, ...
# add categorical special tokens (optional)
if task_name == "rvlcdip":
model_module.model.decoder.add_special_tokens([
"