__init__.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import copy
  15. import importlib
  16. from paddle.jit import to_static
  17. from paddle.static import InputSpec
  18. from .base_model import BaseModel
  19. from .distillation_model import DistillationModel
  20. __all__ = ["build_model", "apply_to_static"]
  21. def build_model(config):
  22. config = copy.deepcopy(config)
  23. if not "name" in config:
  24. arch = BaseModel(config)
  25. else:
  26. name = config.pop("name")
  27. mod = importlib.import_module(__name__)
  28. arch = getattr(mod, name)(config)
  29. return arch
  30. def apply_to_static(model, config, logger):
  31. if config["Global"].get("to_static", False) is not True:
  32. return model
  33. assert "image_shape" in config[
  34. "Global"], "image_shape must be assigned for static training mode..."
  35. supported_list = ["DB", "SVTR"]
  36. if config["Architecture"]["algorithm"] in ["Distillation"]:
  37. algo = list(config["Architecture"]["Models"].values())[0]["algorithm"]
  38. else:
  39. algo = config["Architecture"]["algorithm"]
  40. assert algo in supported_list, f"algorithms that supports static training must in in {supported_list} but got {algo}"
  41. specs = [
  42. InputSpec(
  43. [None] + config["Global"]["image_shape"], dtype='float32')
  44. ]
  45. if algo == "SVTR":
  46. specs.append([
  47. InputSpec(
  48. [None, config["Global"]["max_text_length"]],
  49. dtype='int64'), InputSpec(
  50. [None, config["Global"]["max_text_length"]], dtype='int64'),
  51. InputSpec(
  52. [None], dtype='int64'), InputSpec(
  53. [None], dtype='float64')
  54. ])
  55. model = to_static(model, input_spec=specs)
  56. logger.info("Successfully to apply @to_static with specs: {}".format(specs))
  57. return model