File size: 16,826 Bytes
8207382 | 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 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import errno
import os
import pickle
import json
from packaging import version
import paddle
from ppocr.utils.logging import get_logger
from ppocr.utils.network import maybe_download_params
try:
import encryption # Attempt to import the encryption module for AIStudio's encryption model
encrypted = encryption.is_encryption_needed()
except ImportError:
print("Skipping import of the encryption module.")
encrypted = False # Encryption is not needed if the module cannot be imported
__all__ = ["load_model"]
# just to determine the inference model file format
def get_FLAGS_json_format_model():
# json format by default
return os.environ.get("FLAGS_json_format_model", "1").lower() in ("1", "true", "t")
FLAGS_json_format_model = get_FLAGS_json_format_model()
def _mkdir_if_not_exist(path, logger):
"""
mkdir if not exists, ignore the exception when multiprocess mkdir together
"""
if not os.path.exists(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(path):
logger.warning(
"be happy if some process has already created {}".format(path)
)
else:
raise OSError("Failed to mkdir {}".format(path))
def load_model(config, model, optimizer=None, model_type="det", ema=None):
"""
load model from checkpoint or pretrained_model
"""
logger = get_logger()
global_config = config["Global"]
checkpoints = global_config.get("checkpoints")
pretrained_model = global_config.get("pretrained_model")
best_model_dict = {}
is_float16 = False
is_nlp_model = model_type == "kie" and config["Architecture"]["algorithm"] not in [
"SDMGR"
]
if is_nlp_model is True:
# NOTE: for kie model dsitillation, resume training is not supported now
if config["Architecture"]["algorithm"] in ["Distillation"]:
return best_model_dict
checkpoints = config["Architecture"]["Backbone"]["checkpoints"]
# load kie method metric
if checkpoints:
if os.path.exists(os.path.join(checkpoints, "metric.states")):
with open(os.path.join(checkpoints, "metric.states"), "rb") as f:
states_dict = pickle.load(f, encoding="latin1")
best_model_dict = states_dict.get("best_model_dict", {})
if "epoch" in states_dict:
best_model_dict["start_epoch"] = states_dict["epoch"] + 1
logger.info("resume from {}".format(checkpoints))
if optimizer is not None:
if checkpoints[-1] in ["/", "\\"]:
checkpoints = checkpoints[:-1]
if os.path.exists(checkpoints + ".pdopt"):
optim_dict = paddle.load(checkpoints + ".pdopt")
optimizer.set_state_dict(optim_dict)
else:
logger.warning(
"{}.pdopt is not exists, params of optimizer is not loaded".format(
checkpoints
)
)
return best_model_dict
if checkpoints:
if checkpoints.endswith(".pdparams"):
checkpoints = checkpoints.replace(".pdparams", "")
assert os.path.exists(
checkpoints + ".pdparams"
), "The {}.pdparams does not exists!".format(checkpoints)
# load params from trained model
params = paddle.load(checkpoints + ".pdparams")
state_dict = model.state_dict()
new_state_dict = {}
for key, value in state_dict.items():
if key not in params:
logger.warning(
"{} not in loaded params {} !".format(key, params.keys())
)
continue
pre_value = params[key]
if pre_value.dtype == paddle.float16:
is_float16 = True
if pre_value.dtype != value.dtype:
pre_value = pre_value.astype(value.dtype)
if list(value.shape) == list(pre_value.shape):
new_state_dict[key] = pre_value
else:
logger.warning(
"The shape of model params {} {} not matched with loaded params shape {} !".format(
key, value.shape, pre_value.shape
)
)
model.set_state_dict(new_state_dict)
if is_float16:
logger.info(
"The parameter type is float16, which is converted to float32 when loading"
)
if optimizer is not None:
if os.path.exists(checkpoints + ".pdopt"):
optim_dict = paddle.load(checkpoints + ".pdopt")
optimizer.set_state_dict(optim_dict)
else:
logger.warning(
"{}.pdopt is not exists, params of optimizer is not loaded".format(
checkpoints
)
)
if os.path.exists(checkpoints + ".states"):
with open(checkpoints + ".states", "rb") as f:
states_dict = pickle.load(f, encoding="latin1")
best_model_dict = states_dict.get("best_model_dict", {})
best_model_dict["acc"] = 0.0
if "epoch" in states_dict:
best_model_dict["start_epoch"] = states_dict["epoch"] + 1
logger.info("resume from {}".format(checkpoints))
# Restore EMA state if available
if ema is not None:
pdema_path = checkpoints + ".pdema"
if os.path.exists(pdema_path):
ema_data = paddle.load(pdema_path)
# .pdparams contains EMA weights; restore original training weights
if "train_state" in ema_data:
train_sd = ema_data["train_state"]
cur_sd = model.state_dict()
for k in cur_sd:
if k in train_sd:
if list(cur_sd[k].shape) == list(train_sd[k].shape):
cur_sd[k] = train_sd[k]
model.set_state_dict(cur_sd)
logger.info(
"EMA: restored training weights from {}".format(pdema_path)
)
# Restore EMA shadow weights + step
if "ema_state" in ema_data and "step" in ema_data:
ema.set_state_dict(ema_data)
logger.info(
"EMA: restored shadow weights (step={}) from {}".format(
ema_data["step"], pdema_path
)
)
elif pretrained_model:
is_float16 = load_pretrained_params(model, pretrained_model)
else:
logger.info("train from scratch")
best_model_dict["is_float16"] = is_float16
return best_model_dict
def load_pretrained_params(model, path):
logger = get_logger()
path = maybe_download_params(path)
if path.endswith(".pdparams"):
path = path.replace(".pdparams", "")
assert os.path.exists(
path + ".pdparams"
), "The {}.pdparams does not exists!".format(path)
params = paddle.load(path + ".pdparams")
state_dict = model.state_dict()
new_state_dict = {}
is_float16 = False
for k1 in params.keys():
if k1 not in state_dict.keys():
logger.warning("The pretrained params {} not in model".format(k1))
else:
if params[k1].dtype == paddle.float16:
is_float16 = True
if params[k1].dtype != state_dict[k1].dtype:
params[k1] = params[k1].astype(state_dict[k1].dtype)
if list(state_dict[k1].shape) == list(params[k1].shape):
new_state_dict[k1] = params[k1]
else:
logger.warning(
"The shape of model params {} {} not matched with loaded params {} {} !".format(
k1, state_dict[k1].shape, k1, params[k1].shape
)
)
model.set_state_dict(new_state_dict)
if is_float16:
logger.info(
"The parameter type is float16, which is converted to float32 when loading"
)
logger.info("load pretrain successful from {}".format(path))
return is_float16
def save_model(
model,
optimizer,
model_path,
logger,
config,
is_best=False,
prefix="ppocr",
ema=None,
train_state=None,
**kwargs,
):
"""
save model to the target path
"""
_mkdir_if_not_exist(model_path, logger)
model_prefix = os.path.join(model_path, prefix)
if prefix == "best_accuracy":
best_model_path = os.path.join(model_path, "best_model")
_mkdir_if_not_exist(best_model_path, logger)
paddle.save(optimizer.state_dict(), model_prefix + ".pdopt")
if prefix == "best_accuracy":
paddle.save(
optimizer.state_dict(), os.path.join(best_model_path, "model.pdopt")
)
is_nlp_model = config["Architecture"]["model_type"] == "kie" and config[
"Architecture"
]["algorithm"] not in ["SDMGR"]
if is_nlp_model is not True:
paddle.save(model.state_dict(), model_prefix + ".pdparams")
metric_prefix = model_prefix
# Save EMA state for training resumption
if ema is not None and train_state is not None:
paddle.save(
{
"train_state": train_state,
"ema_state": ema.state_dict,
"step": ema.step,
},
model_prefix + ".pdema",
)
if prefix == "best_accuracy":
paddle.save(
model.state_dict(), os.path.join(best_model_path, "model.pdparams")
)
if ema is not None and train_state is not None:
paddle.save(
{
"train_state": train_state,
"ema_state": ema.state_dict,
"step": ema.step,
},
os.path.join(best_model_path, "model.pdema"),
)
else: # for kie system, we follow the save/load rules in NLP
if config["Global"]["distributed"]:
arch = model._layers
else:
arch = model
if config["Architecture"]["algorithm"] in ["Distillation"]:
arch = arch.Student
arch.backbone.model.save_pretrained(model_prefix)
metric_prefix = os.path.join(model_prefix, "metric")
if prefix == "best_accuracy":
arch.backbone.model.save_pretrained(best_model_path)
save_model_info = kwargs.pop("save_model_info", False)
if save_model_info:
with open(os.path.join(model_path, f"{prefix}.info.json"), "w") as f:
json.dump(kwargs, f)
logger.info("Already save model info in {}".format(model_path))
if prefix != "latest":
done_flag = kwargs.pop("done_flag", False)
update_train_results(config, prefix, save_model_info, done_flag=done_flag)
# save metric and config
with open(metric_prefix + ".states", "wb") as f:
pickle.dump(kwargs, f, protocol=2)
if is_best:
logger.info("save best model is to {}".format(model_prefix))
else:
logger.info("save model in {}".format(model_prefix))
def update_train_results(config, prefix, metric_info, done_flag=False, last_num=5):
if paddle.distributed.get_rank() != 0:
return
assert last_num >= 1
train_results_path = os.path.join(
config["Global"]["save_model_dir"], "train_result.json"
)
save_model_tag = ["pdparams", "pdopt", "pdstates"]
paddle_version = version.parse(paddle.__version__)
if FLAGS_json_format_model or paddle_version >= version.parse("3.0.0"):
save_inference_files = {
"inference_config": "inference.yml",
"pdmodel": "inference.json",
"pdiparams": "inference.pdiparams",
}
else:
save_inference_files = {
"inference_config": "inference.yml",
"pdmodel": "inference.pdmodel",
"pdiparams": "inference.pdiparams",
"pdiparams.info": "inference.pdiparams.info",
}
if os.path.exists(train_results_path):
with open(train_results_path, "r") as fp:
train_results = json.load(fp)
else:
train_results = {}
train_results["model_name"] = config["Global"]["model_name"]
label_dict_path = config["Global"].get("character_dict_path", "")
if label_dict_path != "":
label_dict_path = os.path.abspath(label_dict_path)
if not os.path.exists(label_dict_path):
label_dict_path = ""
train_results["label_dict"] = label_dict_path
train_results["train_log"] = "train.log"
train_results["visualdl_log"] = ""
train_results["config"] = "config.yaml"
train_results["models"] = {}
for i in range(1, last_num + 1):
train_results["models"][f"last_{i}"] = {}
train_results["models"]["best"] = {}
train_results["done_flag"] = done_flag
if "best" in prefix:
if "acc" in metric_info["metric"]:
metric_score = metric_info["metric"]["acc"]
elif "precision" in metric_info["metric"]:
metric_score = metric_info["metric"]["precision"]
elif "exp_rate" in metric_info["metric"]:
metric_score = metric_info["metric"]["exp_rate"]
else:
raise ValueError("No metric score found.")
train_results["models"]["best"]["score"] = metric_score
for tag in save_model_tag:
if tag == "pdparams" and encrypted:
train_results["models"]["best"][tag] = os.path.join(
prefix,
(
f"{prefix}.encrypted.{tag}"
if tag != "pdstates"
else f"{prefix}.states"
),
)
else:
train_results["models"]["best"][tag] = os.path.join(
prefix,
f"{prefix}.{tag}" if tag != "pdstates" else f"{prefix}.states",
)
for key in save_inference_files:
train_results["models"]["best"][key] = os.path.join(
prefix, "inference", save_inference_files[key]
)
else:
for i in range(last_num - 1, 0, -1):
train_results["models"][f"last_{i + 1}"] = train_results["models"][
f"last_{i}"
].copy()
if "acc" in metric_info["metric"]:
metric_score = metric_info["metric"]["acc"]
elif "precision" in metric_info["metric"]:
metric_score = metric_info["metric"]["precision"]
elif "exp_rate" in metric_info["metric"]:
metric_score = metric_info["metric"]["exp_rate"]
else:
metric_score = 0
train_results["models"][f"last_{1}"]["score"] = metric_score
for tag in save_model_tag:
if tag == "pdparams" and encrypted:
train_results["models"][f"last_{1}"][tag] = os.path.join(
prefix,
(
f"{prefix}.encrypted.{tag}"
if tag != "pdstates"
else f"{prefix}.states"
),
)
else:
train_results["models"][f"last_{1}"][tag] = os.path.join(
prefix,
f"{prefix}.{tag}" if tag != "pdstates" else f"{prefix}.states",
)
for key in save_inference_files:
train_results["models"][f"last_{1}"][key] = os.path.join(
prefix, "inference", save_inference_files[key]
)
with open(train_results_path, "w") as fp:
json.dump(train_results, fp)
|