quant.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import os
  18. import sys
  19. __dir__ = os.path.dirname(os.path.abspath(__file__))
  20. sys.path.append(__dir__)
  21. sys.path.append(os.path.abspath(os.path.join(__dir__, "..", "..", "..")))
  22. sys.path.append(os.path.abspath(os.path.join(__dir__, "..", "..", "..", "tools")))
  23. import yaml
  24. import paddle
  25. import paddle.distributed as dist
  26. paddle.seed(2)
  27. from ppocr.data import build_dataloader, set_signal_handlers
  28. from ppocr.modeling.architectures import build_model
  29. from ppocr.losses import build_loss
  30. from ppocr.optimizer import build_optimizer
  31. from ppocr.postprocess import build_post_process
  32. from ppocr.metrics import build_metric
  33. from ppocr.utils.save_load import load_model
  34. import tools.program as program
  35. from paddleslim.dygraph.quant import QAT
  36. dist.get_world_size()
  37. class PACT(paddle.nn.Layer):
  38. def __init__(self):
  39. super(PACT, self).__init__()
  40. alpha_attr = paddle.ParamAttr(
  41. name=self.full_name() + ".pact",
  42. initializer=paddle.nn.initializer.Constant(value=20),
  43. learning_rate=1.0,
  44. regularizer=paddle.regularizer.L2Decay(2e-5),
  45. )
  46. self.alpha = self.create_parameter(shape=[1], attr=alpha_attr, dtype="float32")
  47. def forward(self, x):
  48. out_left = paddle.nn.functional.relu(x - self.alpha)
  49. out_right = paddle.nn.functional.relu(-self.alpha - x)
  50. x = x - out_left + out_right
  51. return x
  52. quant_config = {
  53. # weight preprocess type, default is None and no preprocessing is performed.
  54. "weight_preprocess_type": None,
  55. # activation preprocess type, default is None and no preprocessing is performed.
  56. "activation_preprocess_type": None,
  57. # weight quantize type, default is 'channel_wise_abs_max'
  58. "weight_quantize_type": "channel_wise_abs_max",
  59. # activation quantize type, default is 'moving_average_abs_max'
  60. "activation_quantize_type": "moving_average_abs_max",
  61. # weight quantize bit num, default is 8
  62. "weight_bits": 8,
  63. # activation quantize bit num, default is 8
  64. "activation_bits": 8,
  65. # data type after quantization, such as 'uint8', 'int8', etc. default is 'int8'
  66. "dtype": "int8",
  67. # window size for 'range_abs_max' quantization. default is 10000
  68. "window_size": 10000,
  69. # The decay coefficient of moving average, default is 0.9
  70. "moving_rate": 0.9,
  71. # for dygraph quantization, layers of type in quantizable_layer_type will be quantized
  72. "quantizable_layer_type": ["Conv2D", "Linear"],
  73. }
  74. def main(config, device, logger, vdl_writer):
  75. # init dist environment
  76. if config["Global"]["distributed"]:
  77. dist.init_parallel_env()
  78. global_config = config["Global"]
  79. # build dataloader
  80. set_signal_handlers()
  81. train_dataloader = build_dataloader(config, "Train", device, logger)
  82. if config["Eval"]:
  83. valid_dataloader = build_dataloader(config, "Eval", device, logger)
  84. else:
  85. valid_dataloader = None
  86. # build post process
  87. post_process_class = build_post_process(config["PostProcess"], global_config)
  88. # build model
  89. # for rec algorithm
  90. if hasattr(post_process_class, "character"):
  91. char_num = len(getattr(post_process_class, "character"))
  92. if config["Architecture"]["algorithm"] in [
  93. "Distillation",
  94. ]: # distillation model
  95. for key in config["Architecture"]["Models"]:
  96. if (
  97. config["Architecture"]["Models"][key]["Head"]["name"] == "MultiHead"
  98. ): # for multi head
  99. if config["PostProcess"]["name"] == "DistillationSARLabelDecode":
  100. char_num = char_num - 2
  101. # update SARLoss params
  102. assert (
  103. list(config["Loss"]["loss_config_list"][-1].keys())[0]
  104. == "DistillationSARLoss"
  105. )
  106. config["Loss"]["loss_config_list"][-1]["DistillationSARLoss"][
  107. "ignore_index"
  108. ] = (char_num + 1)
  109. out_channels_list = {}
  110. out_channels_list["CTCLabelDecode"] = char_num
  111. out_channels_list["SARLabelDecode"] = char_num + 2
  112. config["Architecture"]["Models"][key]["Head"][
  113. "out_channels_list"
  114. ] = out_channels_list
  115. else:
  116. config["Architecture"]["Models"][key]["Head"][
  117. "out_channels"
  118. ] = char_num
  119. elif config["Architecture"]["Head"]["name"] == "MultiHead": # for multi head
  120. if config["PostProcess"]["name"] == "SARLabelDecode":
  121. char_num = char_num - 2
  122. # update SARLoss params
  123. assert list(config["Loss"]["loss_config_list"][1].keys())[0] == "SARLoss"
  124. if config["Loss"]["loss_config_list"][1]["SARLoss"] is None:
  125. config["Loss"]["loss_config_list"][1]["SARLoss"] = {
  126. "ignore_index": char_num + 1
  127. }
  128. else:
  129. config["Loss"]["loss_config_list"][1]["SARLoss"]["ignore_index"] = (
  130. char_num + 1
  131. )
  132. out_channels_list = {}
  133. out_channels_list["CTCLabelDecode"] = char_num
  134. out_channels_list["SARLabelDecode"] = char_num + 2
  135. config["Architecture"]["Head"]["out_channels_list"] = out_channels_list
  136. else: # base rec model
  137. config["Architecture"]["Head"]["out_channels"] = char_num
  138. if config["PostProcess"]["name"] == "SARLabelDecode": # for SAR model
  139. config["Loss"]["ignore_index"] = char_num - 1
  140. model = build_model(config["Architecture"])
  141. pre_best_model_dict = dict()
  142. # load fp32 model to begin quantization
  143. pre_best_model_dict = load_model(
  144. config, model, None, config["Architecture"]["model_type"]
  145. )
  146. freeze_params = False
  147. if config["Architecture"]["algorithm"] in ["Distillation"]:
  148. for key in config["Architecture"]["Models"]:
  149. freeze_params = freeze_params or config["Architecture"]["Models"][key].get(
  150. "freeze_params", False
  151. )
  152. act = None if freeze_params else PACT
  153. quanter = QAT(config=quant_config, act_preprocess=act)
  154. quanter.quantize(model)
  155. if config["Global"]["distributed"]:
  156. model = paddle.DataParallel(model)
  157. # build loss
  158. loss_class = build_loss(config["Loss"])
  159. # build optim
  160. optimizer, lr_scheduler = build_optimizer(
  161. config["Optimizer"],
  162. epochs=config["Global"]["epoch_num"],
  163. step_each_epoch=len(train_dataloader),
  164. model=model,
  165. )
  166. # resume PACT training process
  167. pre_best_model_dict = load_model(
  168. config, model, optimizer, config["Architecture"]["model_type"]
  169. )
  170. # build metric
  171. eval_class = build_metric(config["Metric"])
  172. logger.info(
  173. "train dataloader has {} iters, valid dataloader has {} iters".format(
  174. len(train_dataloader), len(valid_dataloader)
  175. )
  176. )
  177. # start train
  178. program.train(
  179. config,
  180. train_dataloader,
  181. valid_dataloader,
  182. device,
  183. model,
  184. loss_class,
  185. optimizer,
  186. lr_scheduler,
  187. post_process_class,
  188. eval_class,
  189. pre_best_model_dict,
  190. logger,
  191. vdl_writer,
  192. )
  193. if __name__ == "__main__":
  194. config, device, logger, vdl_writer = program.preprocess(is_train=True)
  195. main(config, device, logger, vdl_writer)