|
| 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 | + |
| 15 | +from __future__ import print_function |
| 16 | +from utils.static_ps.reader_helper import get_reader, get_example_num, get_file_list, get_word_num |
| 17 | +from utils.static_ps.program_helper import get_model, get_strategy, set_dump_config |
| 18 | +from utils.static_ps.metric_helper import set_zero, get_global_auc |
| 19 | +from utils.static_ps.common import YamlHelper, is_distributed_env |
| 20 | +import argparse |
| 21 | +import time |
| 22 | +import sys |
| 23 | +import paddle.distributed.fleet as fleet |
| 24 | +import paddle.distributed.fleet.base.role_maker as role_maker |
| 25 | +import paddle |
| 26 | +import os |
| 27 | +import warnings |
| 28 | +import logging |
| 29 | +import ast |
| 30 | +import numpy as np |
| 31 | +import struct |
| 32 | +from utils.utils_single import auc |
| 33 | + |
| 34 | +__dir__ = os.path.dirname(os.path.abspath(__file__)) |
| 35 | +sys.path.append(os.path.abspath(os.path.join(__dir__, '..'))) |
| 36 | + |
| 37 | +logging.basicConfig( |
| 38 | + format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO) |
| 39 | +logger = logging.getLogger(__name__) |
| 40 | + |
| 41 | + |
| 42 | +def parse_args(): |
| 43 | + parser = argparse.ArgumentParser("PaddleRec train script") |
| 44 | + parser.add_argument("-o", "--opt", nargs='*', type=str) |
| 45 | + parser.add_argument( |
| 46 | + '-m', |
| 47 | + '--config_yaml', |
| 48 | + type=str, |
| 49 | + required=True, |
| 50 | + help='config file path') |
| 51 | + parser.add_argument( |
| 52 | + '-bf16', |
| 53 | + '--pure_bf16', |
| 54 | + type=ast.literal_eval, |
| 55 | + default=False, |
| 56 | + help="whether use bf16") |
| 57 | + args = parser.parse_args() |
| 58 | + args.abs_dir = os.path.dirname(os.path.abspath(args.config_yaml)) |
| 59 | + yaml_helper = YamlHelper() |
| 60 | + config = yaml_helper.load_yaml(args.config_yaml) |
| 61 | + # modify config from command |
| 62 | + if args.opt: |
| 63 | + for parameter in args.opt: |
| 64 | + parameter = parameter.strip() |
| 65 | + key, value = parameter.split("=") |
| 66 | + if type(config.get(key)) is int: |
| 67 | + value = int(value) |
| 68 | + if type(config.get(key)) is float: |
| 69 | + value = float(value) |
| 70 | + if type(config.get(key)) is bool: |
| 71 | + value = (True if value.lower() == "true" else False) |
| 72 | + config[key] = value |
| 73 | + config["yaml_path"] = args.config_yaml |
| 74 | + config["config_abs_dir"] = args.abs_dir |
| 75 | + config["pure_bf16"] = args.pure_bf16 |
| 76 | + yaml_helper.print_yaml(config) |
| 77 | + return config |
| 78 | + |
| 79 | + |
| 80 | +def bf16_to_fp32(val): |
| 81 | + return np.float32(struct.unpack('<f', struct.pack('<I', val << 16))[0]) |
| 82 | + |
| 83 | + |
| 84 | +class Main(object): |
| 85 | + def __init__(self, config): |
| 86 | + self.metrics = {} |
| 87 | + self.config = config |
| 88 | + self.input_data = None |
| 89 | + self.reader = None |
| 90 | + self.exe = None |
| 91 | + self.train_result_dict = {} |
| 92 | + self.train_result_dict["speed"] = [] |
| 93 | + self.train_result_dict["auc"] = [] |
| 94 | + self.model = None |
| 95 | + self.pure_bf16 = self.config['pure_bf16'] |
| 96 | + |
| 97 | + def run(self): |
| 98 | + self.init_fleet_with_gloo() |
| 99 | + self.network() |
| 100 | + if fleet.is_server(): |
| 101 | + self.run_server() |
| 102 | + elif fleet.is_worker(): |
| 103 | + self.run_worker() |
| 104 | + fleet.stop_worker() |
| 105 | + self.record_result() |
| 106 | + logger.info("Run Success, Exit.") |
| 107 | + |
| 108 | + def init_fleet_with_gloo(use_gloo=True): |
| 109 | + if use_gloo: |
| 110 | + os.environ["PADDLE_WITH_GLOO"] = "1" |
| 111 | + role = role_maker.PaddleCloudRoleMaker() |
| 112 | + fleet.init(role) |
| 113 | + else: |
| 114 | + fleet.init() |
| 115 | + |
| 116 | + def network(self): |
| 117 | + self.model = get_model(self.config) |
| 118 | + self.input_data = self.model.create_feeds() |
| 119 | + self.inference_feed_var = self.model.create_feeds() |
| 120 | + self.init_reader() |
| 121 | + self.metrics = self.model.net(self.input_data) |
| 122 | + self.inference_target_var = self.model.inference_target_var |
| 123 | + logger.info("cpu_num: {}".format(os.getenv("CPU_NUM"))) |
| 124 | + self.model.create_optimizer(get_strategy(self.config)) |
| 125 | + |
| 126 | + def run_server(self): |
| 127 | + logger.info("Run Server Begin") |
| 128 | + fleet.init_server(config.get("runner.warmup_model_path")) |
| 129 | + fleet.run_server() |
| 130 | + |
| 131 | + def run_worker(self): |
| 132 | + logger.info("Run Worker Begin") |
| 133 | + use_cuda = int(config.get("runner.use_gpu")) |
| 134 | + use_auc = config.get("runner.use_auc", False) |
| 135 | + place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace() |
| 136 | + self.exe = paddle.static.Executor(place) |
| 137 | + |
| 138 | + with open("./{}_worker_main_program.prototxt".format( |
| 139 | + fleet.worker_index()), 'w+') as f: |
| 140 | + f.write(str(paddle.static.default_main_program())) |
| 141 | + with open("./{}_worker_startup_program.prototxt".format( |
| 142 | + fleet.worker_index()), 'w+') as f: |
| 143 | + f.write(str(paddle.static.default_startup_program())) |
| 144 | + |
| 145 | + self.exe.run(paddle.static.default_startup_program()) |
| 146 | + if self.pure_bf16: |
| 147 | + self.model.optimizer.amp_init(self.exe.place) |
| 148 | + fleet.init_worker() |
| 149 | + |
| 150 | + init_model_path = config.get("runner.infer_load_path") |
| 151 | + model_mode = config.get("runner.model_mode", 0) |
| 152 | + #if fleet.is_first_worker(): |
| 153 | + #fleet.load_inference_model(init_model_path, mode=int(model_mode)) |
| 154 | + #fleet.barrier_worker() |
| 155 | + |
| 156 | + save_model_path = self.config.get("runner.model_save_path") |
| 157 | + if save_model_path and (not os.path.exists(save_model_path)): |
| 158 | + os.makedirs(save_model_path) |
| 159 | + |
| 160 | + reader_type = self.config.get("runner.reader_type", "QueueDataset") |
| 161 | + epochs = int(self.config.get("runner.epochs")) |
| 162 | + sync_mode = self.config.get("runner.sync_mode") |
| 163 | + opt_info = paddle.static.default_main_program()._fleet_opt |
| 164 | + if use_auc is True: |
| 165 | + opt_info['stat_var_names'] = [ |
| 166 | + self.model.stat_pos.name, self.model.stat_neg.name |
| 167 | + ] |
| 168 | + else: |
| 169 | + opt_info['stat_var_names'] = [] |
| 170 | + |
| 171 | + if reader_type == "InmemoryDataset": |
| 172 | + self.reader.load_into_memory() |
| 173 | + |
| 174 | + for epoch in range(epochs): |
| 175 | + fleet.load_inference_model( |
| 176 | + os.path.join(init_model_path, str(epoch)), |
| 177 | + mode=int(model_mode)) |
| 178 | + epoch_start_time = time.time() |
| 179 | + |
| 180 | + if sync_mode == "heter": |
| 181 | + self.heter_train_loop(epoch) |
| 182 | + elif reader_type == "QueueDataset": |
| 183 | + self.dataset_train_loop(epoch) |
| 184 | + elif reader_type == "InmemoryDataset": |
| 185 | + self.dataset_train_loop(epoch) |
| 186 | + |
| 187 | + epoch_time = time.time() - epoch_start_time |
| 188 | + epoch_speed = self.example_nums / epoch_time |
| 189 | + if use_auc is True: |
| 190 | + global_auc = get_global_auc(paddle.static.global_scope(), |
| 191 | + self.model.stat_pos.name, |
| 192 | + self.model.stat_neg.name) |
| 193 | + self.train_result_dict["auc"].append(global_auc) |
| 194 | + set_zero(self.model.stat_pos.name, |
| 195 | + paddle.static.global_scope()) |
| 196 | + set_zero(self.model.stat_neg.name, |
| 197 | + paddle.static.global_scope()) |
| 198 | + set_zero(self.model.batch_stat_pos.name, |
| 199 | + paddle.static.global_scope()) |
| 200 | + set_zero(self.model.batch_stat_neg.name, |
| 201 | + paddle.static.global_scope()) |
| 202 | + logger.info( |
| 203 | + "Epoch: {}, using time: {} second, ips: {} {}/sec. auc: {}". |
| 204 | + format(epoch, epoch_time, epoch_speed, self.count_method, |
| 205 | + global_auc)) |
| 206 | + else: |
| 207 | + logger.info( |
| 208 | + "Epoch: {}, using time {} second, ips {} {}/sec.".format( |
| 209 | + epoch, epoch_time, epoch_speed, self.count_method)) |
| 210 | + |
| 211 | + self.train_result_dict["speed"].append(epoch_speed) |
| 212 | + |
| 213 | + model_dir = "{}/{}".format(save_model_path, epoch) |
| 214 | + |
| 215 | + if reader_type == "InmemoryDataset": |
| 216 | + self.reader.release_memory() |
| 217 | + |
| 218 | + def init_reader(self): |
| 219 | + if fleet.is_server(): |
| 220 | + return |
| 221 | + self.config["runner.reader_type"] = self.config.get( |
| 222 | + "runner.reader_type", "QueueDataset") |
| 223 | + self.reader, self.file_list = get_reader(self.input_data, config) |
| 224 | + self.example_nums = 0 |
| 225 | + self.count_method = self.config.get("runner.example_count_method", |
| 226 | + "example") |
| 227 | + if self.count_method == "example": |
| 228 | + self.example_nums = get_example_num(self.file_list) |
| 229 | + elif self.count_method == "word": |
| 230 | + self.example_nums = get_word_num(self.file_list) |
| 231 | + else: |
| 232 | + raise ValueError( |
| 233 | + "Set static_benchmark.example_count_method for example / word for example count." |
| 234 | + ) |
| 235 | + |
| 236 | + def dataset_train_loop(self, epoch): |
| 237 | + logger.info("Epoch: {}, Running Dataset Begin.".format(epoch)) |
| 238 | + fetch_info = [ |
| 239 | + "Epoch {} Var {}".format(epoch, var_name) |
| 240 | + for var_name in self.metrics |
| 241 | + ] |
| 242 | + fetch_vars = [var for _, var in self.metrics.items()] |
| 243 | + print_step = int(config.get("runner.print_interval")) |
| 244 | + |
| 245 | + debug = config.get("runner.dataset_debug", False) |
| 246 | + if config.get("runner.need_dump"): |
| 247 | + debug = True |
| 248 | + dump_fields_path = "{}/{}".format( |
| 249 | + config.get("runner.dump_fields_path"), epoch) |
| 250 | + set_dump_config(paddle.static.default_main_program(), { |
| 251 | + "dump_fields_path": dump_fields_path, |
| 252 | + "dump_fields": config.get("runner.dump_fields") |
| 253 | + }) |
| 254 | + print(paddle.static.default_main_program()._fleet_opt) |
| 255 | + self.exe.infer_from_dataset( |
| 256 | + program=paddle.static.default_main_program(), |
| 257 | + dataset=self.reader, |
| 258 | + fetch_list=fetch_vars, |
| 259 | + fetch_info=fetch_info, |
| 260 | + print_period=print_step, |
| 261 | + debug=debug) |
| 262 | + |
| 263 | + def heter_train_loop(self, epoch): |
| 264 | + logger.info( |
| 265 | + "Epoch: {}, Running Begin. Check running metrics at heter_log". |
| 266 | + format(epoch)) |
| 267 | + reader_type = self.config.get("runner.reader_type") |
| 268 | + if reader_type == "QueueDataset": |
| 269 | + self.exe.infer_from_dataset( |
| 270 | + program=paddle.static.default_main_program(), |
| 271 | + dataset=self.reader, |
| 272 | + debug=config.get("runner.dataset_debug")) |
| 273 | + elif reader_type == "DataLoader": |
| 274 | + batch_id = 0 |
| 275 | + train_run_cost = 0.0 |
| 276 | + total_examples = 0 |
| 277 | + self.reader.start() |
| 278 | + while True: |
| 279 | + try: |
| 280 | + train_start = time.time() |
| 281 | + # --------------------------------------------------- # |
| 282 | + self.exe.run(program=paddle.static.default_main_program()) |
| 283 | + # --------------------------------------------------- # |
| 284 | + train_run_cost += time.time() - train_start |
| 285 | + total_examples += self.config.get("runner.batch_size") |
| 286 | + batch_id += 1 |
| 287 | + print_step = int(config.get("runner.print_period")) |
| 288 | + if batch_id % print_step == 0: |
| 289 | + profiler_string = "" |
| 290 | + profiler_string += "avg_batch_cost: {} sec, ".format( |
| 291 | + format((train_run_cost) / print_step, '.5f')) |
| 292 | + profiler_string += "avg_samples: {}, ".format( |
| 293 | + format(total_examples / print_step, '.5f')) |
| 294 | + profiler_string += "ips: {} {}/sec ".format( |
| 295 | + format(total_examples / (train_run_cost), '.5f'), |
| 296 | + self.count_method) |
| 297 | + logger.info("Epoch: {}, Batch: {}, {}".format( |
| 298 | + epoch, batch_id, profiler_string)) |
| 299 | + train_run_cost = 0.0 |
| 300 | + total_examples = 0 |
| 301 | + except paddle.core.EOFException: |
| 302 | + self.reader.reset() |
| 303 | + break |
| 304 | + |
| 305 | + def record_result(self): |
| 306 | + logger.info("train_result_dict: {}".format(self.train_result_dict)) |
| 307 | + with open("./train_result_dict.txt", 'w+') as f: |
| 308 | + f.write(str(self.train_result_dict)) |
| 309 | + |
| 310 | + |
| 311 | +if __name__ == "__main__": |
| 312 | + paddle.enable_static() |
| 313 | + config = parse_args() |
| 314 | + os.environ["CPU_NUM"] = str(config.get("runner.thread_num")) |
| 315 | + benchmark_main = Main(config) |
| 316 | + benchmark_main.run() |
0 commit comments