forked from PaddlePaddle/PaddleRec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatic_fl_trainer.py
executable file
·169 lines (145 loc) · 5.62 KB
/
static_fl_trainer.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 print_function
from utils.static_ps.reader_helper import get_reader, get_infer_reader, get_example_num, get_file_list, get_word_num
from utils.static_ps.program_helper import get_model, get_strategy, set_dump_config
from utils.static_ps.common_ps import YamlHelper, is_distributed_env
import argparse
import time
import sys
import paddle.distributed.fleet as fleet
import paddle.distributed.fleet.base.role_maker as role_maker
from paddle.distributed.ps.coordinator import FLClient
import paddle
import os
import warnings
import logging
import ast
import numpy as np
import struct
__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.abspath(os.path.join(__dir__, '..')))
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
def parse_args():
parser = argparse.ArgumentParser("PaddleRec train script")
parser.add_argument(
'-m',
'--config_yaml',
type=str,
required=True,
help='config file path')
parser.add_argument(
'-bf16',
'--pure_bf16',
type=ast.literal_eval,
default=False,
help="whether use bf16")
args = parser.parse_args()
args.abs_dir = os.path.dirname(os.path.abspath(args.config_yaml))
yaml_helper = YamlHelper()
config = yaml_helper.load_yaml(args.config_yaml)
config["yaml_path"] = args.config_yaml
config["config_abs_dir"] = args.abs_dir
config["pure_bf16"] = args.pure_bf16
yaml_helper.print_yaml(config)
return config
def bf16_to_fp32(val):
return np.float32(struct.unpack('<f', struct.pack('<I', val << 16))[0])
class MyFLClient(FLClient):
def __init__(self):
pass
class Trainer(object):
def __init__(self, config):
self.metrics = {}
self.config = config
self.input_data = None
self.train_dataset = None
self.test_dataset = None
self.model = None
self.pure_bf16 = self.config['pure_bf16']
self.use_cuda = int(self.config.get("runner.use_gpu"))
self.place = paddle.CUDAPlace(0) if self.use_cuda else paddle.CPUPlace(
)
self.role = None
def run(self):
self.init_fleet()
self.init_network()
if fleet.is_server():
self.run_server()
elif fleet.is_worker():
self.init_reader()
self.run_worker()
elif fleet.is_coordinator():
self.run_coordinator()
logger.info("Run Success, Exit.")
def init_fleet(self, use_gloo=True):
if use_gloo:
os.environ["PADDLE_WITH_GLOO"] = "1"
self.role = role_maker.PaddleCloudRoleMaker()
fleet.init(self.role)
else:
fleet.init()
def init_network(self):
self.model = get_model(self.config)
self.input_data = self.model.create_feeds()
self.metrics = self.model.net(self.input_data)
self.model.create_optimizer(get_strategy(self.config)) ## get_strategy
if self.pure_bf16:
self.model.optimizer.amp_init(self.place)
def init_reader(self):
self.train_dataset, self.train_file_list = get_reader(self.input_data,
config)
self.test_dataset, self.test_file_list = get_infer_reader(
self.input_data, config)
if self.role is not None:
self.fl_client = MyFLClient()
self.fl_client.set_basic_config(self.role, self.config,
self.metrics)
else:
raise ValueError("self.role is none")
self.fl_client.set_train_dataset_info(self.train_dataset,
self.train_file_list)
self.fl_client.set_test_dataset_info(self.test_dataset,
self.test_file_list)
example_nums = 0
self.count_method = self.config.get("runner.example_count_method",
"example")
if self.count_method == "example":
example_nums = get_example_num(self.train_file_list)
elif self.count_method == "word":
example_nums = get_word_num(self.train_file_list)
else:
raise ValueError(
"Set static_benchmark.example_count_method for example / word for example count."
)
self.fl_client.set_train_example_num(example_nums)
def run_coordinator(self):
logger.info("Run Coordinator Begin")
fleet.init_coordinator()
fleet.make_fl_strategy()
def run_server(self):
logger.info("Run Server Begin")
fleet.init_server(config.get("runner.warmup_model_path"))
fleet.run_server()
def run_worker(self):
logger.info("Run Worker Begin")
self.fl_client.run()
if __name__ == "__main__":
paddle.enable_static()
config = parse_args()
os.environ["CPU_NUM"] = str(config.get("runner.thread_num"))
trainer = Trainer(config)
trainer.run()