forked from Irene-PHAM/mrz-extraction
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
147 lines (122 loc) · 5.12 KB
/
train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""
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 torch
import pytorch_lightning as pl
from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint
from pytorch_lightning.loggers import MLFlowLogger
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
import mlflow
from mlflow import MlflowClient
os.makedirs("./outputs", exist_ok=True)
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}")
@rank_zero_only
def mlfow_log(model, path):
mlflow.pytorch.log_model(model, path)
def train(config):
pl.utilities.seed.seed_everything(config.get("seed", 42), workers=True)
model_module = DonutModelPLModule(config)
data_module = DonutDataPLModule(config)
# add datasets to data_module
datasets = {"train": [], "validation": []}
path_list = [config.dataset_name_or_paths]
for i, dataset_name_or_path in enumerate(path_list):
task_name = os.path.basename(dataset_name_or_path) # e.g., cord-v2, docvqa, rvlcdip, ...
# add <-1> for None
model_module.model.decoder.add_special_tokens(["<-1/>"])
for split in ["train", "validation"]:
datasets[split].append(
DonutDataset(
dataset_name_or_path=dataset_name_or_path,
donut_model=model_module.model,
max_length=config.max_length,
split=split,
task_start_token=config.task_start_tokens[i]
if config.get("task_start_tokens", None)
else f"<s_{task_name}>",
prompt_end_token= f"<s_{task_name}>",
sort_json_key=config.sort_json_key,
)
)
data_module.train_datasets = datasets["train"]
data_module.val_datasets = datasets["validation"]
mlf_logger = MLFlowLogger(experiment_name=config.exp_name)
lr_callback = LearningRateMonitor(logging_interval="step")
checkpoint_callback = ModelCheckpoint(
monitor="val_metric",
dirpath=Path(config.result_path) / config.exp_name / config.exp_version,
filename="artifacts",
save_top_k=3,
save_last=False,
mode="min",
)
custom_ckpt = CustomCheckpointIO()
trainer = pl.Trainer(
resume_from_checkpoint=config.get("resume_from_checkpoint_path", None),
num_nodes=config.get("num_nodes", 1),
devices=1,
#strategy= pl.strategies.DDPStrategy(timeout=datetime.timedelta(seconds=3600)),
strategy="ddp",
accelerator="gpu",
plugins=custom_ckpt,
max_epochs=config.max_epochs,
max_steps=config.max_steps,
val_check_interval=config.val_check_interval,
check_val_every_n_epoch=config.check_val_every_n_epoch,
gradient_clip_val=config.gradient_clip_val,
precision=16,
num_sanity_val_steps=0,
logger=mlf_logger,
callbacks=[lr_callback, checkpoint_callback],
)
with mlflow.start_run(run_id=mlf_logger.run_id) as run:
trainer.fit(model_module, data_module)
mlfow_log(model_module.model, "mlfmodel")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--config", type=str, required=True)
parser.add_argument("--exp_version", type=str, required=False)
parser.add_argument("--exp_name", type=str, required=False)
parser.add_argument("--tracking_uri", type=str, required=False)
args, left_argv = parser.parse_known_args()
config = Config(args.config)
config.argv_update(left_argv)
config.exp_name = "donut_distributed_1" if not args.exp_name else args.exp_name # basename(args.config).split(".")[0]
config.exp_version = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") if not args.exp_version else args.exp_version
config.tracking_uri = "" if not args.tracking_uri else args.tracking_uri
save_config_file(config, Path(config.result_path) / config.exp_name / config.exp_version / config.tracking_uri)
train(config)