model.py 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503
  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 contextlib
  15. import inspect
  16. import os
  17. import pickle
  18. import socket
  19. import time
  20. import warnings
  21. import numpy as np
  22. import paddle
  23. import paddle.distributed as dist
  24. from paddle import base
  25. from paddle.autograd import no_grad
  26. from paddle.base import core
  27. from paddle.base.executor import global_scope
  28. from paddle.base.framework import (
  29. Variable,
  30. _current_expected_place as _get_device,
  31. _get_paddle_place,
  32. )
  33. from paddle.distributed import fleet
  34. from paddle.distributed.fleet.base import role_maker
  35. from paddle.framework import in_dynamic_mode
  36. from paddle.framework.io_utils import is_belong_to_optimizer
  37. from paddle.io import DataLoader, Dataset, DistributedBatchSampler
  38. from paddle.jit.translated_layer import INFER_MODEL_SUFFIX, INFER_PARAMS_SUFFIX
  39. from paddle.metric import Metric
  40. from paddle.static import InputSpec as Input
  41. from .callbacks import EarlyStopping, config_callbacks
  42. from .model_summary import summary
  43. __all__ = []
  44. _parallel_context_initialized = False
  45. def to_list(value):
  46. if value is None:
  47. return value
  48. if isinstance(value, (list, tuple)):
  49. return list(value)
  50. return [value]
  51. def to_numpy(var):
  52. assert isinstance(var, (Variable, base.core.eager.Tensor)), "not a variable"
  53. if isinstance(var, base.core.eager.Tensor):
  54. return np.array(var)
  55. t = global_scope().find_var(var.name).get_tensor()
  56. return np.array(t)
  57. def flatten_list(l):
  58. assert isinstance(l, list), "not a list"
  59. outl = []
  60. splits = []
  61. for sl in l:
  62. assert isinstance(sl, list), "sub content not a list"
  63. splits.append(len(sl))
  64. outl += sl
  65. return outl, splits
  66. def restore_flatten_list(l, splits):
  67. outl = []
  68. for split in splits:
  69. assert len(l) >= split, "list length invalid"
  70. sl, l = l[:split], l[split:]
  71. outl.append(sl)
  72. return outl
  73. def extract_args(func):
  74. return inspect.getfullargspec(func).args
  75. def _all_gather(x):
  76. output = []
  77. dist.all_gather(output, x)
  78. output = paddle.concat(output, axis=0)
  79. return output
  80. def wait_server_ready(endpoints):
  81. assert not isinstance(endpoints, str)
  82. while True:
  83. all_ok = True
  84. not_ready_endpoints = []
  85. for ep in endpoints:
  86. ip_port = ep.split(":")
  87. with contextlib.closing(
  88. socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  89. ) as sock:
  90. sock.settimeout(2)
  91. result = sock.connect_ex((ip_port[0], int(ip_port[1])))
  92. if result != 0:
  93. all_ok = False
  94. not_ready_endpoints.append(ep)
  95. if not all_ok:
  96. time.sleep(3)
  97. else:
  98. break
  99. def init_communicator(
  100. program, rank, nranks, wait_port, current_endpoint, endpoints
  101. ):
  102. if nranks < 2:
  103. return
  104. endpoints_str = ",".join(endpoints)
  105. other_endpoints = endpoints[:]
  106. other_endpoints.remove(current_endpoint)
  107. block = program.global_block()
  108. if rank == 0 and wait_port:
  109. wait_server_ready(other_endpoints)
  110. if core.is_compiled_with_cuda():
  111. nccl_id_var = block.create_var(
  112. name=base.unique_name.generate('nccl_id'),
  113. persistable=True,
  114. type=base.core.VarDesc.VarType.RAW,
  115. )
  116. block.append_op(
  117. type='c_gen_nccl_id',
  118. inputs={},
  119. outputs={'Out': nccl_id_var},
  120. attrs={
  121. 'rank': rank,
  122. 'endpoint': current_endpoint,
  123. 'other_endpoints': other_endpoints,
  124. },
  125. )
  126. block.append_op(
  127. type='c_comm_init',
  128. inputs={'X': nccl_id_var},
  129. outputs={},
  130. attrs={
  131. 'nranks': nranks,
  132. 'rank': rank,
  133. 'ring_id': 0,
  134. 'endpoints': endpoints_str,
  135. },
  136. )
  137. elif core.is_compiled_with_xpu():
  138. bkcl_id_var = block.create_var(
  139. name=base.unique_name.generate('bkcl_id'),
  140. persistable=True,
  141. type=base.core.VarDesc.VarType.RAW,
  142. )
  143. block.append_op(
  144. type='c_gen_bkcl_id',
  145. inputs={},
  146. outputs={'Out': bkcl_id_var},
  147. attrs={
  148. 'rank': rank,
  149. 'endpoint': current_endpoint,
  150. 'other_endpoints': other_endpoints,
  151. },
  152. )
  153. block.append_op(
  154. type='c_comm_init',
  155. inputs={'X': bkcl_id_var},
  156. outputs={},
  157. attrs={
  158. 'nranks': nranks,
  159. 'rank': rank,
  160. 'ring_id': 0,
  161. 'endpoints': endpoints_str,
  162. },
  163. )
  164. elif (
  165. paddle.distributed.ParallelEnv().device_type
  166. in paddle.device.get_all_custom_device_type()
  167. ):
  168. xccl_id_var = block.create_var(
  169. name=base.unique_name.generate('xccl_id'),
  170. persistable=True,
  171. type=base.core.VarDesc.VarType.RAW,
  172. )
  173. block.append_op(
  174. type='c_gen_xccl_id',
  175. inputs={},
  176. outputs={'Out': xccl_id_var},
  177. attrs={
  178. 'rank': rank,
  179. 'endpoint': current_endpoint,
  180. 'other_endpoints': other_endpoints,
  181. },
  182. )
  183. block.append_op(
  184. type='c_comm_init',
  185. inputs={'X': xccl_id_var},
  186. outputs={},
  187. attrs={
  188. 'nranks': nranks,
  189. 'rank': rank,
  190. 'ring_id': 0,
  191. 'endpoints': endpoints_str,
  192. },
  193. )
  194. def prepare_distributed_context(place=None):
  195. if place is None:
  196. place = (
  197. base.CUDAPlace(paddle.distributed.ParallelEnv().dev_id)
  198. if paddle.distributed.ParallelEnv().nranks > 1
  199. else base.CUDAPlace(0)
  200. )
  201. place = _get_paddle_place(place)
  202. strategy = paddle.distributed.parallel.ParallelStrategy()
  203. strategy.nranks = paddle.distributed.ParallelEnv().nranks
  204. strategy.local_rank = paddle.distributed.ParallelEnv().local_rank
  205. strategy.trainer_endpoints = (
  206. paddle.distributed.ParallelEnv().trainer_endpoints
  207. )
  208. strategy.current_endpoint = (
  209. paddle.distributed.ParallelEnv().current_endpoint
  210. )
  211. if strategy.nranks < 2:
  212. return
  213. global _parallel_context_initialized
  214. if not _parallel_context_initialized and isinstance(place, base.CUDAPlace):
  215. def _init_context():
  216. communicator_prog = base.Program()
  217. init_communicator(
  218. communicator_prog,
  219. strategy.local_rank,
  220. strategy.nranks,
  221. True,
  222. strategy.current_endpoint,
  223. strategy.trainer_endpoints,
  224. )
  225. exe = base.Executor(place)
  226. exe.run(communicator_prog)
  227. if in_dynamic_mode():
  228. base.disable_dygraph()
  229. _init_context()
  230. base.enable_dygraph(place)
  231. else:
  232. assert "Only support CUDAPlace for now."
  233. _parallel_context_initialized = True
  234. return strategy
  235. def _update_input_info(inputs):
  236. "Get input shape list by given inputs in Model initialization."
  237. shapes = None
  238. dtypes = None
  239. if isinstance(inputs, Input):
  240. shapes = [list(inputs.shape)]
  241. dtypes = [inputs.dtype]
  242. elif isinstance(inputs, (list, tuple)):
  243. shapes = [list(input.shape) for input in inputs]
  244. dtypes = [input.dtype for input in inputs]
  245. elif isinstance(inputs, dict):
  246. shapes = [list(inputs[name].shape) for name in inputs]
  247. dtypes = [inputs[name].dtype for name in inputs]
  248. else:
  249. return None
  250. return shapes, dtypes
  251. class StaticGraphAdapter:
  252. """
  253. Model training/inference with a static graph.
  254. """
  255. def __init__(self, model):
  256. super().__init__()
  257. self.model = model
  258. # with `_build_once` gone, parameters are now created in `__init__`
  259. # so we need to keep track of the parameters already created
  260. self._startup_prog = base.default_startup_program()
  261. self._orig_prog = base.default_main_program()
  262. self._label_vars = {} # label variables
  263. self._input_vars = {} # label variables
  264. self._endpoints = {}
  265. self._loss_endpoint = None
  266. self._executor = None
  267. self._progs = {}
  268. self._compiled_progs = {}
  269. self._merge_count = {
  270. 'eval_total': 0,
  271. 'test_total': 0,
  272. 'eval_batch': 0,
  273. 'test_batch': 0,
  274. }
  275. self._nranks = paddle.distributed.ParallelEnv().nranks
  276. self._local_rank = paddle.distributed.ParallelEnv().local_rank
  277. self._amp_level = "O0"
  278. self._amp_configs = {}
  279. self._amp_custom_lists = {}
  280. self._use_fp16_guard = None
  281. @property
  282. def mode(self):
  283. return self.model.mode
  284. @mode.setter
  285. def mode(self, value):
  286. self.model.mode = value
  287. def train_batch(self, inputs, labels=None, update=True):
  288. assert (
  289. self.model._optimizer
  290. ), "model not ready, please call `model.prepare()` first"
  291. self.mode = 'train'
  292. assert (
  293. update is True
  294. ), "Does not support `update == False` in static graph mode by now."
  295. return self._run(inputs, labels)
  296. def eval_batch(self, inputs, labels=None):
  297. self.mode = 'eval'
  298. return self._run(inputs, labels)
  299. def predict_batch(self, inputs):
  300. self.mode = 'test'
  301. return self._run(inputs, None)
  302. def parameters(self, *args, **kwargs):
  303. return self.model.network.parameters(*args, **kwargs)
  304. def save(self, path):
  305. def _save(state, path):
  306. if not state:
  307. return
  308. state = {
  309. k: to_numpy(v) if isinstance(v, Variable) else v
  310. for k, v in state.items()
  311. }
  312. with open(path, 'wb') as f:
  313. pickle.dump(state, f)
  314. base = os.path.basename(path)
  315. assert base != "", "path should be of 'dirname/filename' format"
  316. dir_name = os.path.dirname(path)
  317. if dir_name and not os.path.exists(dir_name):
  318. os.makedirs(dir_name)
  319. param_path = path + ".pdparams"
  320. _save(self.model.network.state_dict(), param_path)
  321. prog = self._progs.get('train', None)
  322. if prog is None or self.model._optimizer is None:
  323. return
  324. # XXX `optimizer.state_dict()` only work in dygraph mode
  325. optim_path = path + ".pdopt"
  326. optim = {
  327. p.name: p for p in filter(is_belong_to_optimizer, prog.list_vars())
  328. }
  329. if not optim:
  330. return
  331. _save(optim, optim_path)
  332. # TODO: Support save/load scaler state in static graph
  333. def load(self, param_state_pairs, optim_state):
  334. if self._executor is None:
  335. executor = base.Executor(base.CPUPlace())._default_executor
  336. else:
  337. executor = self._executor._default_executor
  338. # restore parameter states
  339. base.core._create_loaded_parameter(
  340. [param for param, state in param_state_pairs],
  341. global_scope(),
  342. executor,
  343. )
  344. for param, state in param_state_pairs:
  345. self._set_var(param, state)
  346. # restore optimizer states
  347. # FIXME what if a different optimizer is used?
  348. if not self.model._optimizer or not optim_state:
  349. return
  350. self._load_optimizer(optim_state, executor)
  351. def _load_optimizer(self, state, executor):
  352. prog = self._progs.get('train', None)
  353. optim = list(filter(is_belong_to_optimizer, prog.list_vars()))
  354. if not optim:
  355. return
  356. base.core._create_loaded_parameter(optim, global_scope(), executor)
  357. converted_state = dict(state)
  358. for var in optim:
  359. if var.name in ["@LR_DECAY_COUNTER@", "global_step"]:
  360. # When using learning rate scheduler, dygraph would name the
  361. # global step var as "global_step" to save, while static-graph
  362. # would has a state var named as "@LR_DECAY_COUNTER@".
  363. # NOTE: dygraph saved global_step is 1 larger than that in
  364. # static-graph, since the time of global_step to increase is
  365. # different.
  366. state_val = (
  367. (np.array(converted_state.pop("global_step")) - 1)
  368. if "global_step" in converted_state
  369. else converted_state.pop("@LR_DECAY_COUNTER@", None)
  370. )
  371. if state_val is not None:
  372. converted_state[var.name] = state_val
  373. elif var.name.startswith("learning_rate_"):
  374. # When using static learning rate, static-graph would make it
  375. # a persistable var named 'unique_name.generate("learning_rate")',
  376. # However, dygraph wouldn't save it.
  377. if var.name not in state:
  378. continue
  379. else:
  380. # moment and other accumulators
  381. if var.name not in converted_state:
  382. # try to convert from dygraph name
  383. opt_name = self.model._optimizer._name
  384. opt_cls_name = self.model._optimizer.__class__.__name__
  385. opt_unq_name = None
  386. for name in self.model._optimizer._accumulators.keys():
  387. accum_name = (
  388. name
  389. if opt_name is None
  390. else name[len(opt_name) + 1 :]
  391. )
  392. for (
  393. param_name,
  394. state_var,
  395. ) in self.model._optimizer._accumulators[name].items():
  396. if opt_unq_name is None:
  397. # can not infer out the exact unique(opt_name),
  398. # thus try to extract rather than generate
  399. for state_key in sorted(
  400. state.keys(),
  401. key=lambda x: len(x),
  402. reverse=True,
  403. ):
  404. prefix = (
  405. param_name
  406. + "_"
  407. + (
  408. opt_cls_name
  409. if opt_name is None
  410. else opt_name
  411. )
  412. + "_"
  413. )
  414. if state_key.startswith(prefix):
  415. prefix_offset = state_key[
  416. len(prefix) :
  417. ].find("_") + len(prefix)
  418. opt_unq_name = state_key[
  419. len(
  420. param_name + "_"
  421. ) : prefix_offset
  422. ]
  423. # TODO: assert
  424. # assert opt_unq_name is None
  425. # gen(param.name + "_" + gen(opt_name) + "_" + accum_name)
  426. # always end with "_0" since the unique optimizer._name
  427. dy_state_name = (
  428. param_name
  429. + "_"
  430. + opt_unq_name
  431. + "_"
  432. + accum_name
  433. + "_0"
  434. )
  435. converted_state[
  436. state_var.name
  437. ] = converted_state.pop(dy_state_name)
  438. assert (
  439. var.name in converted_state
  440. ), f"variable [{var.name}] is not in optimizer state file"
  441. self._set_var(var, converted_state[var.name])
  442. def _set_var(self, var, ndarray):
  443. t = global_scope().find_var(var.name).get_tensor()
  444. p = t._place()
  445. if p.is_cpu_place():
  446. place = base.CPUPlace()
  447. elif p.is_cuda_pinned_place():
  448. place = base.CUDAPinnedPlace()
  449. else:
  450. p = base.core.Place()
  451. p.set_place(t._place())
  452. place = base.CUDAPlace(p.gpu_device_id())
  453. t.set(ndarray, place)
  454. def _run(self, inputs, labels=None):
  455. compiled_prog = self._compiled_progs.get(self.mode, None)
  456. assert (
  457. compiled_prog
  458. ), "Model is not ready, please call `model.prepare()` first"
  459. inputs = to_list(inputs)
  460. if labels is not None:
  461. labels = to_list(labels)
  462. assert len(inputs) == len(self._input_vars[self.mode]), (
  463. "number of inputs"
  464. + " does not match number of arguments of `forward` method"
  465. )
  466. feed = {}
  467. input_names = [v.name for v in self._input_vars[self.mode]]
  468. input_dtypes = [v.dtype for v in self._input_vars[self.mode]]
  469. for idx, n in enumerate(input_names):
  470. # train and test may take different arguments
  471. if inputs[idx] is not None:
  472. feed[n] = inputs[idx]
  473. if self._amp_level == 'O2' and input_dtypes[idx] == paddle.float16:
  474. if isinstance(feed[n], core.LoDTensor):
  475. feed[n] = feed[n]._as_type(core.VarDesc.VarType.FP16)
  476. elif isinstance(feed[n], np.array):
  477. feed[n] = feed[n].astype('float16')
  478. if labels is not None:
  479. for idx, v in enumerate(self._label_vars[self.mode]):
  480. feed[v.name] = labels[idx]
  481. endpoints = self._endpoints[self.mode]
  482. if self.mode == 'test':
  483. fetch_list = endpoints['output']
  484. else:
  485. metric_list, metric_splits = flatten_list(endpoints['metric'])
  486. fetch_list = endpoints['loss'] + metric_list
  487. num_loss = len(endpoints['loss'])
  488. # if fetch Variable is same as input Variable, do not fetch
  489. # from program, get it from input directly
  490. pruned_fetch_list = []
  491. pruned_fetch_idx_name_map = [""] * len(fetch_list)
  492. for i, fetch_var in enumerate(fetch_list):
  493. if fetch_var.name in feed.keys():
  494. pruned_fetch_idx_name_map[i] = fetch_var.name
  495. else:
  496. pruned_fetch_list.append(fetch_var)
  497. rets = self._executor.run(
  498. compiled_prog,
  499. feed=feed,
  500. fetch_list=pruned_fetch_list,
  501. return_numpy=False,
  502. )
  503. # restore pruned fetch_list Variable from feeds
  504. for i, name in enumerate(pruned_fetch_idx_name_map):
  505. if len(name) > 0:
  506. rets.insert(i, feed[name])
  507. # LoDTensor cannot be fetch as numpy directly
  508. rets = [np.array(v) for v in rets]
  509. if self.mode == 'test':
  510. return rets[:]
  511. metric_states = restore_flatten_list(rets[num_loss:], metric_splits)
  512. metrics = []
  513. for metric, state in zip(self.model._metrics, metric_states):
  514. # cut off padding size
  515. if (
  516. self.mode != 'train'
  517. and self.model._test_dataloader is not None
  518. and isinstance(self.model._test_dataloader, DataLoader)
  519. and self._nranks > 1
  520. ):
  521. total_size = len(self.model._test_dataloader.dataset)
  522. # TODO: fixme if have better way to get batch size
  523. samples = state[0].shape[0]
  524. current_count = self._merge_count.get(self.mode + '_total', 0)
  525. if current_count + samples >= total_size:
  526. state = [
  527. s[: int(total_size - current_count), ...] for s in state
  528. ]
  529. self._merge_count[self.mode + '_total'] = 0
  530. self._merge_count[self.mode + '_batch'] = int(
  531. total_size - current_count
  532. )
  533. else:
  534. self._merge_count[self.mode + '_total'] += samples
  535. self._merge_count[self.mode + '_batch'] = samples
  536. metrics.append(metric.update(*state))
  537. if num_loss and len(metrics):
  538. return rets[:num_loss], metrics
  539. else:
  540. return rets[:num_loss] if num_loss else metrics
  541. def prepare(self):
  542. modes = ['train', 'eval', 'test']
  543. for mode in modes:
  544. self._make_program(mode)
  545. self._compile_and_initialize(self._progs[mode], mode)
  546. def _make_program(self, mode):
  547. prog = self._progs.get(mode, None)
  548. if prog is not None:
  549. return
  550. prog = self._orig_prog.clone()
  551. # NOTE: When defining learning rate scheduling in static-graph, ops to
  552. # increase the global step var and calculate learning rate would be
  553. # prepended into _orig_prog. test program marked by `_orig_prog.clone`
  554. # also would include these ops. Thus must prune these ops in test
  555. # program, otherwise the global step would be changed in test.
  556. if mode != 'train':
  557. for op in list(prog.global_block().ops):
  558. prog.global_block()._remove_op(0)
  559. if (
  560. mode == 'train'
  561. and self.model._optimizer
  562. and self.model._optimizer._learning_rate_map
  563. ):
  564. # HACK workaround learning rate map issue
  565. lr_var = self.model._optimizer._learning_rate_map[self._orig_prog]
  566. new_lr_var = prog.global_block().vars[lr_var.name]
  567. self.model._optimizer._learning_rate_map[prog] = new_lr_var
  568. losses = []
  569. metrics = []
  570. with base.program_guard(prog, self._startup_prog):
  571. inputs = self.model._inputs
  572. labels = self.model._labels if self.model._labels else []
  573. inputs = [k._create_feed_layer() for k in to_list(inputs)]
  574. labels = [k._create_feed_layer() for k in to_list(labels)]
  575. self._label_vars[mode] = labels
  576. outputs = to_list(self.model.network.forward(*inputs))
  577. if mode != 'test' and self.model._loss:
  578. losses = self.model._loss(*(outputs + labels))
  579. if self._nranks > 1 and mode != 'train':
  580. outputs = [_all_gather(o) for o in outputs]
  581. if mode != 'test':
  582. labels = [_all_gather(l) for l in labels]
  583. if mode != 'test':
  584. for metric in self.model._metrics:
  585. metrics.append(to_list(metric.compute(*(outputs + labels))))
  586. if mode == 'train' and self.model._optimizer:
  587. self._loss_endpoint = paddle.add_n(losses)
  588. if self._nranks > 1:
  589. role = role_maker.PaddleCloudRoleMaker(is_collective=True)
  590. fleet.init(role)
  591. dist_strategy = fleet.DistributedStrategy()
  592. if self._amp_level != 'O0':
  593. dist_strategy.amp = True
  594. dist_strategy.amp_configs = self._amp_configs.copy()
  595. dist_strategy.amp_configs.update(self._amp_custom_lists)
  596. dist_strategy.amp_configs['use_pure_fp16'] = (
  597. self._amp_level == 'O2'
  598. )
  599. self.model._optimizer = fleet.distributed_optimizer(
  600. self.model._optimizer, strategy=dist_strategy
  601. )
  602. elif self._amp_level != "O0" and core.is_compiled_with_cuda:
  603. amp_lists = (
  604. paddle.static.amp.AutoMixedPrecisionLists(
  605. **self._amp_custom_lists
  606. )
  607. if self._amp_custom_lists
  608. else None
  609. )
  610. self.model._optimizer = paddle.static.amp.decorate(
  611. self.model._optimizer,
  612. amp_lists=amp_lists,
  613. use_pure_fp16=self._amp_level == "O2",
  614. use_fp16_guard=self._use_fp16_guard,
  615. **self._amp_configs,
  616. )
  617. self.model._optimizer.minimize(self._loss_endpoint)
  618. if mode != 'train': # clone again to put it in test mode
  619. prog = prog.clone(for_test=True)
  620. self._input_vars[mode] = inputs
  621. self._progs[mode] = prog
  622. self._endpoints[mode] = {
  623. "output": outputs,
  624. "loss": to_list(losses),
  625. "metric": metrics,
  626. }
  627. def _compile_and_initialize(self, prog, mode):
  628. compiled_prog = self._compiled_progs.get(mode, None)
  629. if compiled_prog is not None:
  630. return compiled_prog
  631. assert (
  632. self.model._place is not None
  633. ), "device is not set, please call `model.prepare()` first"
  634. place = self.model._place
  635. # XXX *ALL WEIGHTS* should be initialized upon model construction
  636. # even if `forward()` may run different code path for different mode
  637. # therefore startup program only needs to run once
  638. if self._executor is None:
  639. self._executor = base.Executor(place)
  640. # XXX incremental initialization
  641. uninitialized = []
  642. for var_py in self._startup_prog.list_vars():
  643. var = base.global_scope().find_var(var_py.name)
  644. if (
  645. not var_py.name.startswith('nccl_id')
  646. and var
  647. and var.get_tensor()._is_initialized()
  648. ):
  649. continue
  650. uninitialized.append(var_py)
  651. # for RawProgramOptimizer, it will insert OP with no outputs like:
  652. # c_comm_init(inputs={X=['comm_id_0']}
  653. # but we cannot prune this op.
  654. block = self._startup_prog.global_block()
  655. for op in block.ops:
  656. if op.type == "c_comm_init":
  657. uninitialized.append(op)
  658. if uninitialized:
  659. startup_prog = self._startup_prog._prune(uninitialized)
  660. self._executor.run(startup_prog)
  661. if (
  662. self._amp_level == "O2"
  663. and mode == 'train'
  664. and core.is_compiled_with_cuda()
  665. ):
  666. self.model._optimizer.amp_init(place)
  667. if self._nranks < 2:
  668. compiled_prog = base.CompiledProgram(prog)
  669. else:
  670. compiled_prog = prog
  671. self._compiled_progs[mode] = compiled_prog
  672. class DynamicGraphAdapter:
  673. def __init__(self, model):
  674. super().__init__()
  675. self.model = model
  676. self._nranks = paddle.distributed.ParallelEnv().nranks
  677. self._local_rank = paddle.distributed.ParallelEnv().local_rank
  678. self._merge_count = {
  679. 'eval_total': 0,
  680. 'test_total': 0,
  681. 'eval_batch': 0,
  682. 'test_batch': 0,
  683. }
  684. self._input_info = None
  685. self._amp_level = "O0"
  686. self._amp_configs = {}
  687. self._amp_custom_lists = {}
  688. self._use_fp16_guard = True
  689. if self._nranks > 1:
  690. dist.init_parallel_env()
  691. strategy = paddle.distributed.parallel.ParallelStrategy()
  692. strategy.nranks = paddle.distributed.ParallelEnv().nranks
  693. strategy.local_rank = paddle.distributed.ParallelEnv().local_rank
  694. strategy.trainer_endpoints = (
  695. paddle.distributed.ParallelEnv().trainer_endpoints
  696. )
  697. strategy.current_endpoint = (
  698. paddle.distributed.ParallelEnv().current_endpoint
  699. )
  700. self.ddp_model = paddle.DataParallel(self.model.network, strategy)
  701. @property
  702. def mode(self):
  703. return self.model.mode
  704. @mode.setter
  705. def mode(self, value):
  706. self.model.mode = value
  707. # TODO multi device in dygraph mode not implemented at present time
  708. def train_batch(self, inputs, labels=None, update=True):
  709. assert (
  710. self.model._optimizer
  711. ), "model not ready, please call `model.prepare()` first"
  712. self.model.network.train()
  713. self.mode = 'train'
  714. inputs = to_list(inputs)
  715. self._input_info = _update_input_info(inputs)
  716. labels = labels or []
  717. labels = [paddle.to_tensor(l) for l in to_list(labels)]
  718. # scaler should be initialized only once
  719. if self._amp_level != "O0" and self.model._scaler is None:
  720. self.model._scaler = paddle.amp.GradScaler(**self._amp_configs)
  721. with paddle.amp.auto_cast(
  722. enable=self._amp_level != 'O0',
  723. **self._amp_custom_lists,
  724. level=self._amp_level,
  725. ):
  726. if self._nranks > 1:
  727. outputs = self.ddp_model(*[paddle.to_tensor(x) for x in inputs])
  728. else:
  729. outputs = self.model.network(
  730. *[paddle.to_tensor(x) for x in inputs]
  731. )
  732. losses = self.model._loss(*(to_list(outputs) + labels))
  733. losses = to_list(losses)
  734. final_loss = paddle.add_n(losses)
  735. if self._amp_level != "O0":
  736. scaled = self.model._scaler.scale(final_loss)
  737. scaled.backward()
  738. if update:
  739. self.model._scaler.minimize(self.model._optimizer, scaled)
  740. self.model.network.clear_gradients()
  741. else:
  742. final_loss.backward()
  743. if update:
  744. self.model._optimizer.minimize(final_loss)
  745. self.model.network.clear_gradients()
  746. metrics = []
  747. for metric in self.model._metrics:
  748. metric_outs = metric.compute(*(to_list(outputs) + labels))
  749. m = metric.update(*[to_numpy(m) for m in to_list(metric_outs)])
  750. metrics.append(m)
  751. return (
  752. ([to_numpy(l) for l in losses], metrics)
  753. if len(metrics) > 0
  754. else [to_numpy(l) for l in losses]
  755. )
  756. def eval_batch(self, inputs, labels=None):
  757. self.model.network.eval()
  758. self.mode = 'eval'
  759. inputs = to_list(inputs)
  760. self._input_info = _update_input_info(inputs)
  761. labels = labels or []
  762. labels = [paddle.to_tensor(l) for l in to_list(labels)]
  763. outputs = self.model.network(*[paddle.to_tensor(x) for x in inputs])
  764. # Transform data to expected device
  765. expected_device = paddle.device.get_device()
  766. for o in to_list(outputs):
  767. o._to(device=expected_device)
  768. for l in labels:
  769. l._to(device=expected_device)
  770. if self.model._loss:
  771. losses = self.model._loss(*(to_list(outputs) + labels))
  772. losses = to_list(losses)
  773. if self._nranks > 1:
  774. outputs = [_all_gather(o) for o in to_list(outputs)]
  775. labels = [_all_gather(l) for l in labels]
  776. if self.model._test_dataloader is not None and isinstance(
  777. self.model._test_dataloader, DataLoader
  778. ):
  779. total_size = len(self.model._test_dataloader.dataset)
  780. samples = outputs[0].shape[0]
  781. current_count = self._merge_count.get(self.mode + '_total', 0)
  782. if current_count + samples >= total_size:
  783. outputs = [
  784. o[: int(total_size - current_count)] for o in outputs
  785. ]
  786. labels = [
  787. l[: int(total_size - current_count)] for l in labels
  788. ]
  789. self._merge_count[self.mode + '_total'] = 0
  790. self._merge_count[self.mode + '_batch'] = int(
  791. total_size - current_count
  792. )
  793. else:
  794. self._merge_count[self.mode + '_total'] += samples
  795. self._merge_count[self.mode + '_batch'] = samples
  796. metrics = []
  797. for metric in self.model._metrics:
  798. # cut off padding value.
  799. metric_outs = metric.compute(*(to_list(outputs) + labels))
  800. m = metric.update(*[to_numpy(m) for m in to_list(metric_outs)])
  801. metrics.append(m)
  802. if self.model._loss and len(metrics):
  803. return [to_numpy(l) for l in losses], metrics
  804. elif self.model._loss:
  805. return [to_numpy(l) for l in losses]
  806. else:
  807. return metrics
  808. def predict_batch(self, inputs):
  809. self.model.network.eval()
  810. self.mode = 'test'
  811. inputs = [paddle.to_tensor(x) for x in to_list(inputs)]
  812. self._input_info = _update_input_info(inputs)
  813. outputs = self.model.network(*inputs)
  814. if self._nranks > 1 and isinstance(self.model._place, base.CUDAPlace):
  815. outputs = [_all_gather(o) for o in to_list(outputs)]
  816. return [to_numpy(o) for o in to_list(outputs)]
  817. def parameters(self, *args, **kwargs):
  818. return self.model.network.parameters(*args, **kwargs)
  819. def save(self, path):
  820. params = self.model.network.state_dict()
  821. paddle.save(params, path + '.pdparams')
  822. if self.model._optimizer is not None:
  823. if self.model._optimizer.state_dict():
  824. optim = self.model._optimizer.state_dict()
  825. paddle.save(optim, path + '.pdopt')
  826. if hasattr(self.model, '_scaler') and self.model._scaler is not None:
  827. if self.model._scaler.state_dict():
  828. scaler = self.model._scaler.state_dict()
  829. paddle.save(scaler, path + '.pdscaler')
  830. def load(self, param_state_pairs, optim_state, scaler_state=None):
  831. # restore parameter states
  832. for param, state in param_state_pairs:
  833. param.set_value(state)
  834. if hasattr(self.model, '_scaler') and self.model._scaler is not None:
  835. if scaler_state:
  836. self.model._scaler.load_state_dict(scaler_state)
  837. # restore optimizer states
  838. if not self.model._optimizer or not optim_state:
  839. return
  840. # If optimizer performs set_state_dict when state vars haven't been created,
  841. # which would happen when set_state_dict before minimize, the state would be
  842. # stored in optimizer._accumulators_holder and loaded lazily.
  843. # To contrive this when loading from static-graph saved states, extend
  844. # state dict to include keys named according to dygraph naming rules.
  845. # TODO: if len(self.model._optimizer._accumulators) > 0
  846. converted_state = dict(optim_state)
  847. opt_unq_name = self.model._optimizer._name
  848. if opt_unq_name is None:
  849. opt_unq_name = ''
  850. opt_cls_name = self.model._optimizer.__class__.__name__
  851. opt_name = opt_unq_name[: opt_unq_name.rfind("_")] # remove suffix idx
  852. param_names = [param.name for param in self.model.network.parameters()]
  853. for var_name, state_var in sorted(
  854. optim_state.items(), key=lambda x: len(x[0]), reverse=True
  855. ):
  856. if var_name in ["@LR_DECAY_COUNTER@", "global_step"]:
  857. # NOTE: dygraph saved global_step is 1 larger than that in
  858. # static-graph, since the time of global_step to increase is
  859. # different.
  860. if var_name == "@LR_DECAY_COUNTER@":
  861. converted_state["global_step"] = (
  862. np.array(converted_state.pop("@LR_DECAY_COUNTER@")) + 1
  863. )
  864. else:
  865. # moment and other accumulators
  866. # extend state dict to include promising dygraph names
  867. for param_name in param_names:
  868. if var_name.startswith(param_name + "_" + opt_name):
  869. # when init optimizer with name
  870. accum_name = var_name[
  871. len(param_name + "_" + opt_name + "_") :
  872. ]
  873. elif (
  874. var_name.startswith(param_name + "_")
  875. and opt_name == opt_cls_name
  876. ):
  877. # when init optimizer without name
  878. accum_name = var_name[len(param_name + "_") :]
  879. else:
  880. continue
  881. # remove suffix idx
  882. accum_name = accum_name[: accum_name.rfind("_")]
  883. # state names always end with "_0" in dygraph because of the
  884. # unique optimizer._name
  885. dy_state_name = (
  886. param_name
  887. + "_"
  888. + opt_unq_name
  889. + "_"
  890. + accum_name
  891. + "_0"
  892. )
  893. converted_state[dy_state_name] = state_var
  894. if not hasattr(self.model._optimizer, 'set_state_dict'):
  895. warnings.warn(
  896. "paddle.base.optimizer is deprecated in API 2.0, please use paddle.optimizer instead."
  897. )
  898. self.model._optimizer.set_dict(converted_state)
  899. else:
  900. self.model._optimizer.set_state_dict(converted_state)
  901. def prepare(self):
  902. if (
  903. self._amp_level == "O2"
  904. and self.model.mode == 'train'
  905. and core.is_compiled_with_cuda()
  906. ):
  907. self.model.network, self.model._optimizer = paddle.amp.decorate(
  908. models=self.model.network,
  909. optimizers=self.model._optimizer,
  910. level='O2',
  911. )
  912. if self._amp_level != "O0":
  913. self.model._scaler = None
  914. class Model:
  915. """
  916. An Model object is network with training and inference features.
  917. Dynamic graph and static graph are supported at the same time,
  918. switched by `paddle.enable_static()`. The usage is as follows.
  919. But note, the switching between dynamic and static should be before
  920. instantiating a Model. The input description, i.e, paddle.static.InputSpec,
  921. must be required for static graph.
  922. When training on GPU, auto mixed precision (AMP O1) and pure float16
  923. (AMP O2) training are both supported in static graph mode and dynamic mode.
  924. In static graph mode, before training with pure float16 (AMP O2),
  925. `multi_precision` could be set to True when creating optimizer, which can
  926. avoid poor accuracy or slow convergence in a way, and inputs of dtype float
  927. should be cast to float16 by users. `paddle.static.amp.fp16_guard` API
  928. should be also used to limit the range of pure float16 training, otherwise,
  929. 'use_fp16_guard' should be set to False by users. However, limiting the
  930. range of is not supported during training using AMP.
  931. Args:
  932. network (paddle.nn.Layer): The network is an instance of
  933. paddle.nn.Layer.
  934. inputs (InputSpec|list|tuple|dict|None, optional): `inputs`, entry points of network,
  935. could be a InputSpec instance, or list/tuple of InputSpec instances,
  936. or dict ({name: InputSpec}), and it couldn't be None in static
  937. graph. Default: None.
  938. labels (InputSpec|list|tuple|None, optional): `labels`, entry points of network,
  939. could be a InputSpec instance or list/tuple of InputSpec instances,
  940. or None. For static graph, if labels is required in loss,
  941. labels must be set. Otherwise, it could be None. Default: None.
  942. Examples:
  943. 1. A common example
  944. .. code-block:: python
  945. :name: code-example1
  946. >>> import paddle
  947. >>> import paddle.nn as nn
  948. >>> import paddle.vision.transforms as T
  949. >>> from paddle.static import InputSpec
  950. >>> device = paddle.set_device('cpu') # or 'gpu'
  951. >>> net = nn.Sequential(
  952. ... nn.Flatten(1),
  953. ... nn.Linear(784, 200),
  954. ... nn.Tanh(),
  955. ... nn.Linear(200, 10))
  956. ...
  957. >>> # inputs and labels are not required for dynamic graph.
  958. >>> input = InputSpec([None, 784], 'float32', 'x')
  959. >>> label = InputSpec([None, 1], 'int64', 'label')
  960. >>> model = paddle.Model(net, input, label)
  961. >>> optim = paddle.optimizer.SGD(learning_rate=1e-3,
  962. ... parameters=model.parameters())
  963. ...
  964. >>> model.prepare(optim,
  965. ... paddle.nn.CrossEntropyLoss(),
  966. ... paddle.metric.Accuracy())
  967. ...
  968. >>> transform = T.Compose([
  969. ... T.Transpose(),
  970. ... T.Normalize([127.5], [127.5])
  971. >>> ])
  972. >>> data = paddle.vision.datasets.MNIST(mode='train', transform=transform)
  973. >>> model.fit(data, epochs=2, batch_size=32, verbose=1)
  974. 2. An example using mixed precision training.
  975. .. code-block:: python
  976. :name: code-example2
  977. >>> # doctest: +REQUIRES(env:GPU)
  978. >>> import paddle
  979. >>> paddle.device.set_device('gpu')
  980. >>> import paddle.nn as nn
  981. >>> import paddle.vision.transforms as T
  982. >>> def run_example_code():
  983. ... device = paddle.set_device('gpu')
  984. ...
  985. ... net = nn.Sequential(nn.Flatten(1), nn.Linear(784, 200), nn.Tanh(),
  986. ... nn.Linear(200, 10))
  987. ...
  988. ... model = paddle.Model(net)
  989. ... optim = paddle.optimizer.SGD(learning_rate=1e-3, parameters=model.parameters())
  990. ...
  991. ... amp_configs = {
  992. ... "level": "O1",
  993. ... "custom_white_list": {'conv2d'},
  994. ... "use_dynamic_loss_scaling": True
  995. ... }
  996. ... model.prepare(optim,
  997. ... paddle.nn.CrossEntropyLoss(),
  998. ... paddle.metric.Accuracy(),
  999. ... amp_configs=amp_configs)
  1000. ...
  1001. ... transform = T.Compose([T.Transpose(), T.Normalize([127.5], [127.5])])
  1002. ... data = paddle.vision.datasets.MNIST(mode='train', transform=transform)
  1003. ... model.fit(data, epochs=2, batch_size=32, verbose=1)
  1004. ...
  1005. >>> # mixed precision training is only supported on GPU now.
  1006. >>> if paddle.is_compiled_with_cuda():
  1007. ... run_example_code()
  1008. ...
  1009. """
  1010. def __init__(self, network, inputs=None, labels=None):
  1011. self.mode = 'train'
  1012. self.network = network
  1013. self._inputs = None
  1014. self._labels = None
  1015. self._loss = None
  1016. self._loss_weights = None
  1017. self._optimizer = None
  1018. self._input_info = None
  1019. self._is_shape_inferred = False
  1020. self._test_dataloader = None
  1021. self.stop_training = False
  1022. if not in_dynamic_mode():
  1023. if not isinstance(inputs, (list, tuple, dict, Input)):
  1024. raise TypeError(
  1025. "'inputs' must be list or tuple or dict, and couldn't be None."
  1026. )
  1027. elif inputs:
  1028. self._input_info = _update_input_info(inputs)
  1029. self._inputs = self._verify_spec(inputs, is_input=True)
  1030. self._labels = self._verify_spec(labels)
  1031. # init backend
  1032. if in_dynamic_mode():
  1033. self._adapter = DynamicGraphAdapter(self)
  1034. else:
  1035. self._adapter = StaticGraphAdapter(self)
  1036. def train_batch(self, inputs, labels=None, update=True):
  1037. """
  1038. Run one training step on one batch of data. And using `update` indicates
  1039. whether optimizer update gradients computing by this batch.
  1040. Args:
  1041. inputs (numpy.ndarray|Tensor|list): Batch of input data. It could
  1042. be a numpy array or paddle.Tensor, or a list of arrays or
  1043. tensors (in case the model has multiple inputs).
  1044. labels (numpy.ndarray|Tensor|list, optional): Batch of labels. It could be
  1045. a numpy array or paddle.Tensor, or a list of arrays or tensors
  1046. (in case the model has multiple labels). If has no labels,
  1047. set None. Default: None.
  1048. update (bool, optional): Whether update parameters after loss.backward() computing.
  1049. Set it to False to accumulate gradients. Default: True.
  1050. Returns:
  1051. A list of scalar training loss if the model has no metrics,
  1052. or a tuple (list of scalar loss, list of metrics) if the model
  1053. set metrics.
  1054. Examples:
  1055. .. code-block:: python
  1056. >>> import paddle
  1057. >>> import paddle.nn as nn
  1058. >>> from paddle.static import InputSpec
  1059. >>> paddle.seed(2023)
  1060. >>> device = paddle.set_device('cpu') # or 'gpu'
  1061. >>> net = nn.Sequential(
  1062. ... nn.Linear(784, 200),
  1063. ... nn.Tanh(),
  1064. ... nn.Linear(200, 10))
  1065. ...
  1066. >>> input = InputSpec([None, 784], 'float32', 'x')
  1067. >>> label = InputSpec([None, 1], 'int64', 'label')
  1068. >>> model = paddle.Model(net, input, label)
  1069. >>> optim = paddle.optimizer.SGD(learning_rate=1e-3,
  1070. ... parameters=model.parameters())
  1071. >>> model.prepare(optim, paddle.nn.CrossEntropyLoss())
  1072. >>> data = paddle.rand((4, 784), dtype="float32")
  1073. >>> label = paddle.randint(0, 10, (4, 1), dtype="int64")
  1074. >>> loss = model.train_batch([data], [label])
  1075. >>> print(loss)
  1076. [array(3.0039132, dtype=float32)]
  1077. """
  1078. loss = self._adapter.train_batch(inputs, labels, update)
  1079. if in_dynamic_mode() and self._input_info is None:
  1080. self._update_inputs()
  1081. return loss
  1082. @no_grad()
  1083. def eval_batch(self, inputs, labels=None):
  1084. """
  1085. Run one evaluating step on a batch of data.
  1086. Args:
  1087. inputs (numpy.ndarray|Tensor|list): Batch of input data. It could
  1088. be a numpy array or paddle.Tensor, or a list of arrays or
  1089. tensors (in case the model has multiple inputs).
  1090. labels (numpy.ndarray|Tensor|list, optional): Batch of labels. It could be
  1091. a numpy array or paddle.Tensor, or a list of arrays or tensors
  1092. (in case the model has multiple labels). If has no labels,
  1093. set None. Default: None.
  1094. Returns:
  1095. A list of scalar testing loss if the model has no metrics,
  1096. or a tuple (list of scalar loss, list of metrics) if the model
  1097. set metrics.
  1098. Examples:
  1099. .. code-block:: python
  1100. >>> import paddle
  1101. >>> import paddle.nn as nn
  1102. >>> from paddle.static import InputSpec
  1103. >>> paddle.seed(2023)
  1104. >>> device = paddle.set_device('cpu') # or 'gpu'
  1105. >>> net = nn.Sequential(
  1106. ... nn.Linear(784, 200),
  1107. ... nn.Tanh(),
  1108. ... nn.Linear(200, 10))
  1109. ...
  1110. >>> input = InputSpec([None, 784], 'float32', 'x')
  1111. >>> label = InputSpec([None, 1], 'int64', 'label')
  1112. >>> model = paddle.Model(net, input, label)
  1113. >>> optim = paddle.optimizer.SGD(learning_rate=1e-3,
  1114. ... parameters=model.parameters())
  1115. >>> model.prepare(optim,
  1116. ... paddle.nn.CrossEntropyLoss(),
  1117. ... metrics=paddle.metric.Accuracy())
  1118. >>> data = paddle.rand((4, 784), dtype="float32")
  1119. >>> label = paddle.randint(0, 10, (4, 1), dtype="int64")
  1120. >>> loss, acc = model.eval_batch([data], [label])
  1121. >>> print(loss, acc)
  1122. [array(3.0039132, dtype=float32)] [0.0]
  1123. """
  1124. loss = self._adapter.eval_batch(inputs, labels)
  1125. if in_dynamic_mode() and self._input_info is None:
  1126. self._update_inputs()
  1127. return loss
  1128. @no_grad()
  1129. def predict_batch(self, inputs):
  1130. """
  1131. Run one predicting step on a batch of data.
  1132. Args:
  1133. inputs (numpy.ndarray|Tensor|list): Batch of input data. It could
  1134. be a numpy array or paddle.Tensor, or a list of arrays or
  1135. tensors (in case the model has multiple inputs).
  1136. Returns:
  1137. A list of numpy.ndarray of predictions, that is the outputs
  1138. of Model forward.
  1139. Examples:
  1140. .. code-block:: python
  1141. >>> import paddle
  1142. >>> import paddle.nn as nn
  1143. >>> from paddle.static import InputSpec
  1144. >>> paddle.seed(2023)
  1145. >>> device = paddle.set_device('cpu') # or 'gpu'
  1146. >>> input = InputSpec([None, 784], 'float32', 'x')
  1147. >>> label = InputSpec([None, 1], 'int64', 'label')
  1148. >>> net = nn.Sequential(
  1149. ... nn.Linear(784, 200),
  1150. ... nn.Tanh(),
  1151. ... nn.Linear(200, 10),
  1152. ... nn.Softmax())
  1153. ...
  1154. >>> model = paddle.Model(net, input, label)
  1155. >>> model.prepare()
  1156. >>> data = paddle.rand((1, 784), dtype="float32")
  1157. >>> out = model.predict_batch([data])
  1158. >>> print(out)
  1159. [array([[0.10844935, 0.04650883, 0.11790176, 0.04962315, 0.10899059,
  1160. 0.08197589, 0.03125402, 0.03232312, 0.3786293 , 0.04434395]],
  1161. dtype=float32)]
  1162. """
  1163. loss = self._adapter.predict_batch(inputs)
  1164. if in_dynamic_mode() and self._input_info is None:
  1165. self._update_inputs()
  1166. return loss
  1167. def save(self, path, training=True):
  1168. """
  1169. This function saves parameters, optimizer information or model and
  1170. parameters only for inference to path. It depends on the parameter
  1171. `training`.
  1172. If `training` is set to True, the parameters saved contain all
  1173. the trainable Variable, will save to a file with suffix ".pdparams".
  1174. The optimizer information contains all the variable used by optimizer.
  1175. For Adam optimizer, contains beta1, beta2, momentum etc. All the
  1176. information will save to a file with suffix ".pdopt". (If the optimizer
  1177. have no variable need to save (like SGD), the fill will not generated).
  1178. This function will silently overwrite existing file at the target location.
  1179. If `training` is set to False, only inference model will be saved.
  1180. Args:
  1181. path (str): The file prefix to save model. The format
  1182. is 'dirname/file_prefix' or 'file_prefix'. if empty str.
  1183. A exception will be raised.
  1184. training (bool, optional): Whether to save for training. If not, save
  1185. for inference only. Default: True.
  1186. Returns:
  1187. None
  1188. Examples:
  1189. .. code-block:: python
  1190. >>> import paddle
  1191. >>> import paddle.nn as nn
  1192. >>> import paddle.vision.transforms as T
  1193. >>> from paddle.static import InputSpec
  1194. >>> from paddle.vision.datasets import MNIST
  1195. >>> dynamic = True # False
  1196. >>> # If use static graph, do not set
  1197. >>> if not dynamic:
  1198. ... paddle.enable_static()
  1199. >>> transform = T.Compose([T.Transpose(),
  1200. ... T.Normalize([127.5], [127.5])])
  1201. >>> train_dataset = MNIST(mode='train', transform=transform)
  1202. >>> train_loader = paddle.io.DataLoader(train_dataset, batch_size=64)
  1203. >>> val_dataset = MNIST(mode='test', transform=transform)
  1204. >>> val_loader = paddle.io.DataLoader(val_dataset, batch_size=64)
  1205. >>> input = InputSpec([None, 1, 28, 28], 'float32', 'image')
  1206. >>> label = InputSpec([None, 1], 'int64', 'label')
  1207. >>> model = paddle.Model(paddle.vision.models.LeNet(), input, label)
  1208. >>> optim = paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters())
  1209. >>> model.prepare(optim, paddle.nn.CrossEntropyLoss(), paddle.metric.Accuracy(topk=(1, 2)))
  1210. >>> model.fit(train_loader, val_loader, epochs=2, verbose=0)
  1211. >>> model.save('checkpoint/test') # save for training
  1212. >>> model.save('inference_model', False) # save for inference
  1213. """
  1214. if paddle.distributed.ParallelEnv().local_rank == 0:
  1215. if not training:
  1216. self._save_inference_model(path)
  1217. else:
  1218. self._adapter.save(path)
  1219. def load(self, path, skip_mismatch=False, reset_optimizer=False):
  1220. """
  1221. Load from files storing the model states and optimizer states. The file
  1222. for optimizer states is not necessary if no need to restore the optimizer.
  1223. NOTE: parameters are retrieved out from the file storing model states
  1224. according to their structured names.
  1225. For fine-tuning or transfer-learning models where some of the layers have
  1226. changed, keep parameters needed to restore have same structured names in
  1227. the pre-trained model and fine-tuning model.
  1228. Args:
  1229. path (str): The prefix of files storing the model states and
  1230. optimizer states. The files would be `path.pdparams` and
  1231. `path.pdopt` separately, and the latter is not necessary
  1232. when no need to restore.
  1233. skip_mismatch (bool, optional): Whether to skip the loading of mismatch
  1234. parameter or raise an error when mismatch happens (not found
  1235. the parameter in file storing model states of or receives a
  1236. mismatch shape). Default: False.
  1237. reset_optimizer (bool, optional): If True, ignore the providing file storing
  1238. optimizer states and initialize optimizer states from scratch.
  1239. Otherwise, restore optimizer states from `path.pdopt` if
  1240. a optimizer has been set to the model. Default: False.
  1241. Returns:
  1242. None
  1243. Examples:
  1244. .. code-block:: python
  1245. >>> import paddle
  1246. >>> import paddle.nn as nn
  1247. >>> from paddle.static import InputSpec
  1248. >>> device = paddle.set_device('cpu')
  1249. >>> input = InputSpec([None, 784], 'float32', 'x')
  1250. >>> model = paddle.Model(nn.Sequential(
  1251. ... nn.Linear(784, 200),
  1252. ... nn.Tanh(),
  1253. ... nn.Linear(200, 10),
  1254. ... nn.Softmax()), input)
  1255. ...
  1256. >>> model.save('checkpoint/test')
  1257. >>> model.load('checkpoint/test')
  1258. """
  1259. def _load_state_from_path(path):
  1260. if not os.path.exists(path):
  1261. return
  1262. with open(path, 'rb') as f:
  1263. return pickle.load(f, encoding='latin1')
  1264. def _check_match(key, param):
  1265. state = param_state.get(key, None)
  1266. if state is None:
  1267. raise ValueError(f"{key} is not found in the providing file.")
  1268. if list(state.shape) != list(param.shape):
  1269. raise ValueError(
  1270. f"{key} receives a shape {list(state.shape)}, but the expected shape is {list(param.shape)}."
  1271. )
  1272. return param, state
  1273. def _strip_postfix(path):
  1274. path, ext = os.path.splitext(path)
  1275. assert ext in [
  1276. '',
  1277. '.pdparams',
  1278. '.pdopt',
  1279. '.pdmodel',
  1280. ], f"Unknown postfix {ext} from weights"
  1281. return path
  1282. path = _strip_postfix(path)
  1283. param_state = _load_state_from_path(path + ".pdparams")
  1284. assert param_state, "Failed to load parameters, please check path."
  1285. matched_param_state = []
  1286. for key, param in self.network.state_dict().items():
  1287. try:
  1288. match_res = _check_match(key, param)
  1289. except ValueError as err:
  1290. if skip_mismatch:
  1291. warnings.warn(f"Skip loading for {key}. " + str(err))
  1292. # reset optimizer when mismatch happens
  1293. reset_optimizer = True
  1294. else:
  1295. raise err
  1296. matched_param_state.append(match_res)
  1297. optim_state = (
  1298. None if reset_optimizer else _load_state_from_path(path + ".pdopt")
  1299. )
  1300. # TODO: support save/load scaler state in static graph
  1301. if in_dynamic_mode():
  1302. scaler_state = None
  1303. if hasattr(self, '_scaler') and self._scaler is not None:
  1304. if os.path.exists(path + '.pdscaler'):
  1305. scaler_state = paddle.load(path + '.pdscaler')
  1306. return self._adapter.load(
  1307. matched_param_state, optim_state, scaler_state
  1308. )
  1309. else:
  1310. return self._adapter.load(matched_param_state, optim_state)
  1311. def parameters(self, *args, **kwargs):
  1312. """
  1313. Returns a list of parameters of the model.
  1314. Returns:
  1315. A list of Parameter in static graph.
  1316. A list of ParamBase in dynamic graph.
  1317. Examples:
  1318. .. code-block:: python
  1319. >>> import paddle
  1320. >>> import paddle.nn as nn
  1321. >>> from paddle.static import InputSpec
  1322. >>> paddle.seed(2023)
  1323. >>> input = InputSpec([None, 784], 'float32', 'x')
  1324. >>> model = paddle.Model(nn.Sequential(
  1325. ... nn.Linear(784, 200),
  1326. ... nn.Tanh(),
  1327. ... nn.Linear(200, 10)), input)
  1328. ...
  1329. >>> params = model.parameters()
  1330. >>> print(params)
  1331. [Parameter containing:
  1332. Tensor(shape=[784, 200], dtype=float32, place=Place(cpu), stop_gradient=False,
  1333. [[ 0.05713400, 0.00314646, -0.03754271, ..., -0.02529256,
  1334. 0.04872842, -0.06670858],
  1335. ...,
  1336. [ 0.06268418, 0.06550254, -0.02103353, ..., 0.06395906,
  1337. 0.05509177, -0.06355451]]), Parameter containing:
  1338. Tensor(shape=[200], dtype=float32, place=Place(cpu), stop_gradient=False,
  1339. [0., 0., 0., ..., 0., 0.]), Parameter containing:
  1340. Tensor(shape=[200, 10], dtype=float32, place=Place(cpu), stop_gradient=False,
  1341. [[ 0.12933084, 0.07726504, 0.05336720, ..., 0.10865459,
  1342. 0.06605886, 0.13684085],
  1343. ...,
  1344. [-0.10171061, -0.01649965, -0.13420501, ..., 0.11190581,
  1345. -0.12700224, 0.02916957]]), Parameter containing:
  1346. Tensor(shape=[10], dtype=float32, place=Place(cpu), stop_gradient=False,
  1347. [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])]
  1348. """
  1349. return self._adapter.parameters()
  1350. def _prepare_amp(self, amp_configs):
  1351. def _check_pure_fp16_configs():
  1352. # pure float16 training has some restricts now
  1353. if self._adapter._amp_level == "O2" and self._optimizer._grad_clip:
  1354. # clip by value is not supported
  1355. assert isinstance(
  1356. self._optimizer._grad_clip,
  1357. (paddle.nn.ClipGradByGlobalNorm, paddle.nn.ClipGradByNorm),
  1358. ), "Only ClipGradByNorm and ClipGradByGlobalNorm are supported in amp training with level=O2 currently."
  1359. self._adapter._amp_custom_lists = {}
  1360. self._adapter._amp_configs = {}
  1361. # check and get level of mixed precision training
  1362. if not amp_configs:
  1363. self._adapter._amp_level = 'O0'
  1364. return
  1365. elif isinstance(amp_configs, str):
  1366. if amp_configs not in ('O0', 'O1', 'O2'):
  1367. raise ValueError(
  1368. "The level of amp_configs should be 'O0', 'O1' or 'O2'."
  1369. )
  1370. self._adapter._amp_level = amp_configs
  1371. _check_pure_fp16_configs()
  1372. return
  1373. else:
  1374. if 'level' not in amp_configs:
  1375. self._adapter._amp_level = 'O1'
  1376. elif amp_configs['level'] not in ('O0', 'O1', 'O2'):
  1377. raise ValueError(
  1378. "amp_configs['level'] should be 'O0', 'O1' or 'O2'."
  1379. )
  1380. else:
  1381. self._adapter._amp_level = amp_configs['level']
  1382. amp_config_key_set = set(amp_configs.keys()) - {'level'}
  1383. if not amp_config_key_set or self._adapter._amp_level == 'O0':
  1384. return
  1385. if 'use_pure_fp16' in amp_configs:
  1386. raise ValueError(
  1387. "'use_pure_fp16' is an invalid parameter, the level of mixed precision training only depends on 'O1' or 'O2'."
  1388. )
  1389. _check_pure_fp16_configs()
  1390. # construct amp_custom_lists
  1391. if self._adapter._amp_level != 'O0' and amp_config_key_set:
  1392. for param_name in [
  1393. 'custom_white_list',
  1394. 'custom_black_list',
  1395. 'custom_black_varnames',
  1396. ]:
  1397. if param_name in amp_config_key_set:
  1398. self._adapter._amp_custom_lists[param_name] = amp_configs[
  1399. param_name
  1400. ]
  1401. amp_config_key_set -= {param_name}
  1402. def _check_amp_configs(amp_config_key_set):
  1403. accepted_param_set = {
  1404. 'init_loss_scaling',
  1405. 'incr_ratio',
  1406. 'decr_ratio',
  1407. 'incr_every_n_steps',
  1408. 'decr_every_n_nan_or_inf',
  1409. 'use_dynamic_loss_scaling',
  1410. 'use_fp16_guard',
  1411. }
  1412. if amp_config_key_set - accepted_param_set:
  1413. raise ValueError(
  1414. f"Except for 'level', the keys of 'amp_configs' must be accepted by mixed precision APIs, but {tuple(amp_config_key_set - accepted_param_set)} could not be recognized."
  1415. )
  1416. if 'use_fp16_guard' in amp_config_key_set:
  1417. if in_dynamic_mode():
  1418. raise ValueError(
  1419. "'use_fp16_guard' is supported in static graph mode only."
  1420. )
  1421. self._adapter._use_fp16_guard = amp_configs['use_fp16_guard']
  1422. amp_config_key_set.remove('use_fp16_guard')
  1423. return amp_config_key_set
  1424. amp_configs_set = _check_amp_configs(amp_config_key_set)
  1425. for key in amp_configs_set:
  1426. self._adapter._amp_configs[key] = amp_configs[key]
  1427. def prepare(
  1428. self, optimizer=None, loss=None, metrics=None, amp_configs=None
  1429. ):
  1430. """
  1431. Configures the model before running.
  1432. Args:
  1433. optimizer (Optimizer|None, optional): Optimizer must be set in training
  1434. and should be a Optimizer instance. It can be None in eval
  1435. and test mode. Default: None.
  1436. loss (Loss|Callable|None, optional): Loss function can
  1437. be a `paddle.nn.Layer` instance or any callable function
  1438. taken the predicted values and ground truth values as input.
  1439. It can be None when there is no loss. Default: None.
  1440. metrics (Metric|list[Metric]|None, optional): If metrics is set, all
  1441. metrics will be calculated and output in train/eval mode. Default: None.
  1442. amp_configs (str|dict|None, optional): AMP configurations. If AMP or pure
  1443. float16 training is used, the key 'level' of 'amp_configs'
  1444. should be set to 'O1' or 'O2' respectively. Otherwise, the
  1445. value of 'level' defaults to 'O0', which means float32
  1446. training. In addition to 'level', parameters consistent with
  1447. mixed precision API could also be passed in. The supported
  1448. keys are: 'init_loss_scaling', 'incr_ratio', 'decr_ratio',
  1449. 'incr_every_n_steps', 'decr_every_n_nan_or_inf',
  1450. 'use_dynamic_loss_scaling', 'custom_white_list',
  1451. 'custom_black_list', and 'custom_black_varnames'or
  1452. 'use_fp16_guard' is only supported in static graph mode. Mixed
  1453. precision API documentations :ref:`api_paddle_amp_auto_cast`
  1454. and :ref:`api_paddle_amp_GradScaler` could be referenced
  1455. for details. For convenience, 'amp_configs' could be set to
  1456. 'O1' or 'O2' if no more parameters are needed. 'amp_configs'
  1457. could be None in float32 training. Default: None.
  1458. Returns:
  1459. None
  1460. """
  1461. self._place = _get_device()
  1462. if isinstance(self._place, base.CUDAPlace):
  1463. global _parallel_context_initialized
  1464. if (
  1465. paddle.distributed.ParallelEnv().nranks > 1
  1466. and not _parallel_context_initialized
  1467. ):
  1468. if in_dynamic_mode():
  1469. main_prog_seed = base.default_main_program().random_seed
  1470. startup_prog_seed = (
  1471. base.default_startup_program().random_seed
  1472. )
  1473. base.disable_dygraph()
  1474. paddle.disable_static(self._place)
  1475. # enable_dygraph would create and switch to a new program,
  1476. # thus also copy seed to the new program
  1477. base.default_main_program().random_seed = main_prog_seed
  1478. base.default_startup_program().random_seed = (
  1479. startup_prog_seed
  1480. )
  1481. else:
  1482. prepare_distributed_context(self._place)
  1483. _parallel_context_initialized = True
  1484. self._optimizer = optimizer
  1485. if loss is not None:
  1486. if not isinstance(loss, paddle.nn.Layer) and not callable(loss):
  1487. raise TypeError(
  1488. "'loss' must be sub classes of `paddle.nn.Layer` or any callable function."
  1489. )
  1490. self._loss = loss
  1491. metrics = metrics or []
  1492. for metric in to_list(metrics):
  1493. assert isinstance(
  1494. metric, Metric
  1495. ), f"{metric.__class__.__name__} is not sub class of Metric"
  1496. self._metrics = to_list(metrics)
  1497. self._prepare_amp(amp_configs)
  1498. self._adapter.prepare()
  1499. def fit(
  1500. self,
  1501. train_data=None,
  1502. eval_data=None,
  1503. batch_size=1,
  1504. epochs=1,
  1505. eval_freq=1,
  1506. log_freq=10,
  1507. save_dir=None,
  1508. save_freq=1,
  1509. verbose=2,
  1510. drop_last=False,
  1511. shuffle=True,
  1512. num_workers=0,
  1513. callbacks=None,
  1514. accumulate_grad_batches=1,
  1515. num_iters=None,
  1516. ):
  1517. """
  1518. Trains the model for a fixed number of epochs. If `eval_data` is set,
  1519. evaluation will be done at the end of each epoch.
  1520. Args:
  1521. train_data (Dataset|DataLoader, optional): An iterable data loader is used for
  1522. train. An instance of paddle paddle.io.Dataset or
  1523. paddle.io.Dataloader is recommended. Default: None.
  1524. eval_data (Dataset|DataLoader, optional): An iterable data loader is used for
  1525. evaluation at the end of epoch. If None, will not do evaluation.
  1526. An instance of paddle.io.Dataset or paddle.io.Dataloader
  1527. is recommended. Default: None.
  1528. batch_size (int|list, optional): The batch size of train_data and eval_data. When
  1529. train_data and eval_data are both the instance of Dataloader, this
  1530. parameter will be ignored. Default: 1.
  1531. epochs (int, optional): The number of epochs to train the model. Default: 1.
  1532. eval_freq (int, optional): The frequency, in number of epochs, an evaluation
  1533. is performed. Default: 1.
  1534. log_freq (int, optional): The frequency, in number of steps, the training logs
  1535. are printed. Default: 10.
  1536. save_dir(str|None, optional): The directory to save checkpoint during training.
  1537. If None, will not save checkpoint. Default: None.
  1538. save_freq (int, optional): The frequency, in number of epochs, to save
  1539. checkpoint. Default: 1.
  1540. verbose (int, optional): The verbosity mode, should be 0, 1, or 2. 0 = silent,
  1541. 1 = progress bar, 2 = one line per epoch. Default: 2.
  1542. drop_last (bool, optional): Whether drop the last incomplete batch of
  1543. train_data when dataset size is not divisible by the batch size.
  1544. When train_data is an instance of Dataloader, this parameter
  1545. will be ignored. Default: False.
  1546. shuffle (bool, optional): Whether to shuffle train_data. When train_data is
  1547. an instance of Dataloader, this parameter will be ignored.
  1548. Default: True.
  1549. num_workers (int, optional): The number of subprocess to load data, 0 for no
  1550. subprocess used and loading data in main process.
  1551. When train_data and eval_data are both the instance of
  1552. Dataloader, this parameter will be ignored. Default: 0.
  1553. callbacks (Callback|None, optional): A list of `Callback` instances to apply
  1554. during training. If None, :ref:`api_paddle_callbacks_ProgBarLogger` and
  1555. :ref:`api_paddle_callbacks_ModelCheckpoint` are automatically inserted. Default: None.
  1556. accumulate_grad_batches (int, optional): The number of batches to accumulate gradient
  1557. during training process before optimizer updates. It can mimic large batch
  1558. size. Default: 1.
  1559. num_iters (int|None, optional): The number of iterations to evaluate the model.
  1560. If None, evaluate on whole input dataset, otherwise, evaluate `num_iters` times.
  1561. Default: None.
  1562. Returns:
  1563. None
  1564. Examples:
  1565. 1. An example use Dataset and set batch size, shuffle in fit.
  1566. How to make a batch is done internally.
  1567. .. code-block:: python
  1568. :name: code-example3
  1569. >>> # doctest: +TIMEOUT(80)
  1570. >>> import paddle
  1571. >>> import paddle.vision.transforms as T
  1572. >>> from paddle.vision.datasets import MNIST
  1573. >>> from paddle.static import InputSpec
  1574. >>> dynamic = True
  1575. >>> if not dynamic:
  1576. ... paddle.enable_static()
  1577. ...
  1578. >>> transform = T.Compose([T.Transpose(),
  1579. ... T.Normalize([127.5], [127.5])])
  1580. >>> train_dataset = MNIST(mode='train', transform=transform)
  1581. >>> val_dataset = MNIST(mode='test', transform=transform)
  1582. >>> input = InputSpec([None, 1, 28, 28], 'float32', 'image')
  1583. >>> label = InputSpec([None, 1], 'int64', 'label')
  1584. >>> model = paddle.Model(
  1585. ... paddle.vision.models.LeNet(),
  1586. ... input, label)
  1587. >>> optim = paddle.optimizer.Adam(
  1588. ... learning_rate=0.001, parameters=model.parameters())
  1589. >>> model.prepare(
  1590. ... optim,
  1591. ... paddle.nn.CrossEntropyLoss(),
  1592. ... paddle.metric.Accuracy(topk=(1, 2)))
  1593. >>> model.fit(train_dataset,
  1594. ... val_dataset,
  1595. ... epochs=2,
  1596. ... batch_size=64,
  1597. ... save_dir='mnist_checkpoint')
  1598. ...
  1599. 2. An example use DataLoader, batch size and shuffle is set in
  1600. DataLoader.
  1601. .. code-block:: python
  1602. :name: code-example4
  1603. >>> # doctest: +TIMEOUT(80)
  1604. >>> import paddle
  1605. >>> import paddle.vision.transforms as T
  1606. >>> from paddle.vision.datasets import MNIST
  1607. >>> from paddle.static import InputSpec
  1608. >>> dynamic = True
  1609. >>> if not dynamic:
  1610. ... paddle.enable_static()
  1611. ...
  1612. >>> transform = T.Compose([T.Transpose(),
  1613. ... T.Normalize([127.5], [127.5])])
  1614. >>> train_dataset = MNIST(mode='train', transform=transform)
  1615. >>> train_loader = paddle.io.DataLoader(train_dataset,
  1616. ... batch_size=64)
  1617. >>> val_dataset = MNIST(mode='test', transform=transform)
  1618. >>> val_loader = paddle.io.DataLoader(val_dataset,
  1619. ... batch_size=64)
  1620. ...
  1621. >>> input = InputSpec([None, 1, 28, 28], 'float32', 'image')
  1622. >>> label = InputSpec([None, 1], 'int64', 'label')
  1623. >>> model = paddle.Model(
  1624. ... paddle.vision.models.LeNet(), input, label)
  1625. >>> optim = paddle.optimizer.Adam(
  1626. ... learning_rate=0.001, parameters=model.parameters())
  1627. >>> model.prepare(
  1628. ... optim,
  1629. ... paddle.nn.CrossEntropyLoss(),
  1630. ... paddle.metric.Accuracy(topk=(1, 2)))
  1631. >>> model.fit(train_loader,
  1632. ... val_loader,
  1633. ... epochs=2,
  1634. ... save_dir='mnist_checkpoint')
  1635. ...
  1636. """
  1637. assert train_data is not None, "train_data must be given!"
  1638. if isinstance(batch_size, (tuple, list)) and all(
  1639. isinstance(x, int) for x in batch_size
  1640. ):
  1641. assert (
  1642. len(batch_size) == 2
  1643. ), "batch_size length error, expected train_batch_size and eval_batch_size."
  1644. train_batch_size, eval_batch_size = batch_size
  1645. elif isinstance(batch_size, int):
  1646. train_batch_size, eval_batch_size = batch_size, batch_size
  1647. if isinstance(train_data, Dataset):
  1648. train_sampler = DistributedBatchSampler(
  1649. train_data,
  1650. batch_size=train_batch_size,
  1651. shuffle=shuffle,
  1652. drop_last=drop_last,
  1653. )
  1654. train_loader = DataLoader(
  1655. train_data,
  1656. batch_sampler=train_sampler,
  1657. places=self._place,
  1658. num_workers=num_workers,
  1659. return_list=True,
  1660. )
  1661. else:
  1662. train_loader = train_data
  1663. if eval_data is not None and isinstance(eval_data, Dataset):
  1664. eval_sampler = DistributedBatchSampler(
  1665. eval_data, batch_size=eval_batch_size
  1666. )
  1667. eval_loader = DataLoader(
  1668. eval_data,
  1669. batch_sampler=eval_sampler,
  1670. places=self._place,
  1671. num_workers=num_workers,
  1672. return_list=True,
  1673. )
  1674. elif eval_data is not None:
  1675. eval_loader = eval_data
  1676. else:
  1677. eval_loader = None
  1678. do_eval = eval_loader is not None
  1679. self._test_dataloader = eval_loader
  1680. self._accumulate = accumulate_grad_batches
  1681. steps = self._len_data_loader(train_loader)
  1682. self.num_iters = num_iters
  1683. if (
  1684. num_iters is not None
  1685. and isinstance(num_iters, int)
  1686. and isinstance(steps, int)
  1687. ):
  1688. assert num_iters > 0, "num_iters must be greater than 0!"
  1689. epochs = (num_iters // steps) + 1
  1690. steps = min(num_iters, steps)
  1691. cbks = config_callbacks(
  1692. callbacks,
  1693. model=self,
  1694. epochs=epochs,
  1695. steps=steps,
  1696. log_freq=log_freq,
  1697. save_freq=save_freq,
  1698. save_dir=save_dir,
  1699. verbose=verbose,
  1700. metrics=self._metrics_name(),
  1701. )
  1702. if any(isinstance(k, EarlyStopping) for k in cbks) and not do_eval:
  1703. warnings.warn("EarlyStopping needs validation data.")
  1704. cbks.on_begin('train')
  1705. for epoch in range(epochs):
  1706. cbks.on_epoch_begin(epoch)
  1707. logs = self._run_one_epoch(train_loader, cbks, 'train')
  1708. cbks.on_epoch_end(epoch, logs)
  1709. if do_eval and epoch % eval_freq == 0:
  1710. eval_steps = self._len_data_loader(eval_loader)
  1711. cbks.on_begin(
  1712. 'eval',
  1713. {'steps': eval_steps, 'metrics': self._metrics_name()},
  1714. )
  1715. eval_logs = self._run_one_epoch(eval_loader, cbks, 'eval')
  1716. cbks.on_end('eval', eval_logs)
  1717. if self.stop_training:
  1718. break
  1719. cbks.on_end('train', logs)
  1720. self._test_dataloader = None
  1721. def evaluate(
  1722. self,
  1723. eval_data,
  1724. batch_size=1,
  1725. log_freq=10,
  1726. verbose=2,
  1727. num_workers=0,
  1728. callbacks=None,
  1729. num_iters=None,
  1730. ):
  1731. """
  1732. Evaluate the loss and metrics of the model on input dataset.
  1733. Args:
  1734. eval_data (Dataset|DataLoader): An iterable data loader is used for
  1735. evaluation. An instance of paddle.io.Dataset or
  1736. paddle.io.Dataloader is recommended.
  1737. batch_size (int, optional): The batch size of train_data and eval_data.
  1738. When eval_data is the instance of Dataloader, this argument will be
  1739. ignored. Default: 1.
  1740. log_freq (int, optional): The frequency, in number of steps, the eval logs
  1741. are printed. Default: 10.
  1742. verbose (int, optional): The verbosity mode, should be 0, 1, or 2. 0 = silent,
  1743. 1 = progress bar, 2 = one line per epoch. Default: 2.
  1744. num_workers (int, optional): The number of subprocess to load data,
  1745. 0 for no subprocess used and loading data in main process. When
  1746. train_data and eval_data are both the instance of Dataloader,
  1747. this parameter will be ignored. Default: 0.
  1748. callbacks (Callback|None, optional): A list of `Callback` instances to apply
  1749. during training. If None, `ProgBarLogger` and `ModelCheckpoint`
  1750. are automatically inserted. Default: None.
  1751. num_iters (int|None, optional): The number of iterations to evaluate the model.
  1752. If None, evaluate on whole input dataset, otherwise, evaluate `num_iters` times.
  1753. Default: None.
  1754. Returns:
  1755. dict: Result of metric. The key is the names of Metric,
  1756. value is a scalar or numpy.array.
  1757. Examples:
  1758. .. code-block:: python
  1759. >>> # doctest: +SKIP('Cause each step's acc and using time are not same when repeat running')
  1760. >>> import paddle
  1761. >>> import paddle.vision.transforms as T
  1762. >>> from paddle.static import InputSpec
  1763. >>> # declarative mode
  1764. >>> transform = T.Compose([T.Transpose(),
  1765. ... T.Normalize([127.5], [127.5])])
  1766. >>> val_dataset = paddle.vision.datasets.MNIST(mode='test', transform=transform)
  1767. >>> input = InputSpec([-1, 1, 28, 28], 'float32', 'image')
  1768. >>> label = InputSpec([None, 1], 'int64', 'label')
  1769. >>> model = paddle.Model(paddle.vision.models.LeNet(), input, label)
  1770. >>> model.prepare(metrics=paddle.metric.Accuracy())
  1771. >>> result = model.evaluate(val_dataset, batch_size=64)
  1772. >>> print(result)
  1773. {'acc': 0.0699}
  1774. """
  1775. if eval_data is not None and isinstance(eval_data, Dataset):
  1776. eval_sampler = DistributedBatchSampler(
  1777. eval_data, batch_size=batch_size
  1778. )
  1779. eval_loader = DataLoader(
  1780. eval_data,
  1781. batch_sampler=eval_sampler,
  1782. places=self._place,
  1783. num_workers=num_workers,
  1784. return_list=True,
  1785. )
  1786. else:
  1787. eval_loader = eval_data
  1788. self._test_dataloader = eval_loader
  1789. cbks = config_callbacks(
  1790. callbacks,
  1791. model=self,
  1792. log_freq=log_freq,
  1793. verbose=verbose,
  1794. metrics=self._metrics_name(),
  1795. )
  1796. eval_steps = self._len_data_loader(eval_loader)
  1797. self.num_iters = num_iters
  1798. if (
  1799. num_iters is not None
  1800. and isinstance(num_iters, int)
  1801. and isinstance(eval_steps, int)
  1802. ):
  1803. assert num_iters > 0, "num_iters must be greater than 0!"
  1804. eval_steps = min(num_iters, eval_steps)
  1805. self.num_iters = eval_steps
  1806. cbks.on_begin(
  1807. 'eval', {'steps': eval_steps, 'metrics': self._metrics_name()}
  1808. )
  1809. logs = self._run_one_epoch(eval_loader, cbks, 'eval')
  1810. cbks.on_end('eval', logs)
  1811. self._test_dataloader = None
  1812. eval_result = {}
  1813. for k in self._metrics_name():
  1814. eval_result[k] = logs[k]
  1815. return eval_result
  1816. def predict(
  1817. self,
  1818. test_data,
  1819. batch_size=1,
  1820. num_workers=0,
  1821. stack_outputs=False,
  1822. verbose=1,
  1823. callbacks=None,
  1824. ):
  1825. """
  1826. Compute the output predictions on testing data.
  1827. Args:
  1828. test_data (Dataset|DataLoader): An iterable data loader is used for
  1829. predict. An instance of paddle.io.Dataset or paddle.io.Dataloader
  1830. is recommended.
  1831. batch_size (int, optional): The batch size of test_data. When test_data is the
  1832. instance of Dataloader, this argument will be ignored. Default: 1.
  1833. num_workers (int, optional): The number of subprocess to load data, 0 for no subprocess
  1834. used and loading data in main process. When test_data is the instance of Dataloader,
  1835. this argument will be ignored. Default: 0.
  1836. stack_outputs (bool, optional): Whether stack output field like a batch, as for an output
  1837. field of a sample is in shape [X, Y], test_data contains N samples, predict
  1838. output field will be in shape [N, X, Y] if stack_output is True, and will
  1839. be a length N list in shape [[X, Y], [X, Y], ..., [X, Y]] if stack_outputs
  1840. is False. stack_outputs as False is used for LoDTensor output situation,
  1841. it is recommended set as True if outputs contains no LoDTensor. Default: False.
  1842. verbose (int, optional): The verbosity mode, should be 0, 1, or 2. 0 = silent,
  1843. 1 = progress bar, 2 = one line per batch. Default: 1.
  1844. callbacks(Callback, optional): A Callback instance, Default: None.
  1845. Returns:
  1846. list: output of models.
  1847. Examples:
  1848. .. code-block:: python
  1849. >>> import numpy as np
  1850. >>> import paddle
  1851. >>> from paddle.static import InputSpec
  1852. >>> class MnistDataset(paddle.vision.datasets.MNIST):
  1853. ... def __init__(self, mode, return_label=True):
  1854. ... super().__init__(mode=mode)
  1855. ... self.return_label = return_label
  1856. ...
  1857. ... def __getitem__(self, idx):
  1858. ... img = np.reshape(self.images[idx], [1, 28, 28])
  1859. ... if self.return_label:
  1860. ... return img, np.array(self.labels[idx]).astype('int64')
  1861. ... return img
  1862. ...
  1863. ... def __len__(self):
  1864. ... return len(self.images)
  1865. ...
  1866. >>> test_dataset = MnistDataset(mode='test', return_label=False)
  1867. >>> # imperative mode
  1868. >>> input = InputSpec([-1, 1, 28, 28], 'float32', 'image')
  1869. >>> model = paddle.Model(paddle.vision.models.LeNet(), input)
  1870. >>> model.prepare()
  1871. >>> result = model.predict(test_dataset, batch_size=64)
  1872. >>> print(len(result[0]), result[0][0].shape)
  1873. 157 (64, 10)
  1874. >>> # declarative mode
  1875. >>> device = paddle.set_device('cpu')
  1876. >>> paddle.enable_static()
  1877. >>> input = InputSpec([-1, 1, 28, 28], 'float32', 'image')
  1878. >>> model = paddle.Model(paddle.vision.models.LeNet(), input)
  1879. >>> model.prepare()
  1880. >>> result = model.predict(test_dataset, batch_size=64)
  1881. >>> print(len(result[0]), result[0][0].shape)
  1882. 157 (64, 10)
  1883. """
  1884. if test_data is not None and isinstance(test_data, Dataset):
  1885. test_sampler = DistributedBatchSampler(
  1886. test_data, batch_size=batch_size
  1887. )
  1888. test_loader = DataLoader(
  1889. test_data,
  1890. batch_sampler=test_sampler,
  1891. places=self._place,
  1892. num_workers=num_workers,
  1893. return_list=True,
  1894. )
  1895. else:
  1896. test_loader = test_data
  1897. self._test_dataloader = test_loader
  1898. cbks = config_callbacks(callbacks, model=self, verbose=verbose)
  1899. test_steps = self._len_data_loader(test_loader)
  1900. logs = {'steps': test_steps}
  1901. cbks.on_begin('predict', logs)
  1902. outputs = []
  1903. logs, outputs = self._run_one_epoch(test_loader, cbks, 'predict')
  1904. outputs = list(zip(*outputs))
  1905. # NOTE: for lod tensor output, we should not stack outputs
  1906. # for stacking may lose its detail info
  1907. if stack_outputs:
  1908. outputs = [np.vstack(outs) for outs in outputs]
  1909. self._test_dataloader = None
  1910. cbks.on_end('predict', logs)
  1911. return outputs
  1912. def _save_inference_model(self, path):
  1913. """
  1914. Save inference model can be used in static or dynamic mode.
  1915. Args:
  1916. path (str): The path prefix to save model. The format is
  1917. ``dirname/file_prefix`` or ``file_prefix``.
  1918. Returns:
  1919. None
  1920. """
  1921. if in_dynamic_mode():
  1922. with base.framework._dygraph_guard(None):
  1923. layer = self.network
  1924. if self._input_info is None: # No provided or inferred
  1925. raise RuntimeError(
  1926. "Saving inference model needs 'inputs' or running before saving. Please specify 'inputs' in Model initialization or input training data and perform a training for shape derivation."
  1927. )
  1928. if self._is_shape_inferred:
  1929. warnings.warn(
  1930. "'inputs' was not specified when Model initialization, so the input shape to be saved will be the shape derived from the user's actual inputs. The input shape to be saved is %s. For saving correct input shapes, please provide 'inputs' for Model initialization."
  1931. % self._input_info[0]
  1932. )
  1933. paddle.jit.save(layer, path, input_spec=self._inputs)
  1934. else:
  1935. # Path check
  1936. file_prefix = os.path.basename(path)
  1937. if file_prefix == "":
  1938. raise ValueError(
  1939. "The input path MUST be format of dirname/file_prefix "
  1940. "[dirname\\file_prefix in Windows system], but received "
  1941. "file_prefix is empty string."
  1942. )
  1943. dirname = os.path.dirname(path)
  1944. if dirname and not os.path.exists(dirname):
  1945. os.makedirs(dirname)
  1946. model_path = dirname
  1947. model_filename = file_prefix + INFER_MODEL_SUFFIX
  1948. params_filename = file_prefix + INFER_PARAMS_SUFFIX
  1949. prog = self._adapter._progs.get('test', None)
  1950. assert (
  1951. prog
  1952. ), "Model is not ready, please call `model.prepare()` first"
  1953. infer_prog = prog.clone(for_test=True)
  1954. inputs = list(self._adapter._input_vars['test'])
  1955. endpoints = self._adapter._endpoints['test']['output']
  1956. paddle.static.save_inference_model(
  1957. model_path,
  1958. inputs,
  1959. endpoints,
  1960. self._adapter._executor,
  1961. program=infer_prog,
  1962. )
  1963. def _run_one_epoch(
  1964. self,
  1965. data_loader,
  1966. callbacks,
  1967. mode,
  1968. logs={},
  1969. ):
  1970. outputs = []
  1971. for step, data in enumerate(data_loader):
  1972. # Data might come from different types of data_loader and have
  1973. # different format, as following:
  1974. # 1. DataLoader in static graph:
  1975. # [[input1, input2, ..., label1, label2, ...]]
  1976. # 2. DataLoader in dygraph
  1977. # [input1, input2, ..., label1, label2, ...]
  1978. # 3. custumed iterator yield concated inputs and labels:
  1979. # [input1, input2, ..., label1, label2, ...]
  1980. # 4. custumed iterator yield separated inputs and labels:
  1981. # ([input1, input2, ...], [label1, label2, ...])
  1982. # To handle all of these, flatten (nested) list to list.
  1983. data = paddle.utils.flatten(data)
  1984. # LoDTensor.shape is callable, where LoDTensor comes from
  1985. # DataLoader in static graph
  1986. batch_size = (
  1987. data[0].shape()[0]
  1988. if callable(data[0].shape)
  1989. else data[0].shape[0]
  1990. )
  1991. callbacks.on_batch_begin(mode, step, logs)
  1992. if mode != 'predict':
  1993. _inputs = [data[: len(self._inputs)], data[len(self._inputs) :]]
  1994. if mode == 'train':
  1995. _inputs.append(
  1996. (step + 1) % self._accumulate == 0
  1997. or step + 1 == len(data_loader)
  1998. )
  1999. outs = getattr(self, mode + '_batch')(*_inputs)
  2000. if self._metrics and self._loss:
  2001. metrics = [[float(l) for l in outs[0]]]
  2002. elif self._loss:
  2003. metrics = [[float(l) for l in outs]]
  2004. else:
  2005. metrics = []
  2006. # metrics
  2007. for metric in self._metrics:
  2008. res = metric.accumulate()
  2009. metrics.extend(to_list(res))
  2010. assert len(self._metrics_name()) == len(metrics)
  2011. for k, v in zip(self._metrics_name(), metrics):
  2012. logs[k] = v
  2013. else:
  2014. if self._inputs is not None:
  2015. outs = self.predict_batch(data[: len(self._inputs)])
  2016. else:
  2017. outs = self.predict_batch(data)
  2018. outputs.append(outs)
  2019. logs['step'] = step
  2020. if (
  2021. mode == 'train'
  2022. or self._adapter._merge_count.get(mode + '_batch', 0) <= 0
  2023. ):
  2024. logs['batch_size'] = (
  2025. batch_size * paddle.distributed.ParallelEnv().nranks
  2026. )
  2027. else:
  2028. logs['batch_size'] = self._adapter._merge_count[mode + '_batch']
  2029. callbacks.on_batch_end(mode, step, logs)
  2030. if hasattr(self, 'num_iters') and self.num_iters is not None:
  2031. self.num_iters -= 1
  2032. if self.num_iters <= 0:
  2033. self.stop_training = True
  2034. del self.num_iters
  2035. break
  2036. self._reset_metrics()
  2037. if mode == 'predict':
  2038. return logs, outputs
  2039. return logs
  2040. def summary(self, input_size=None, dtype=None):
  2041. """Prints a string summary of the network.
  2042. Args:
  2043. input_size (tuple|InputSpec|list[tuple|InputSpec], optional): Size of input tensor.
  2044. if not set, input_size will get from ``self._inputs`` if network only have
  2045. one input, input_size can be tuple or InputSpec. if model have multiple
  2046. input, input_size must be a list which contain every input's shape. Default: None.
  2047. dtype (str, optional): If dtype is None, 'float32' will be used, Default: None.
  2048. Returns:
  2049. Dict: A summary of the network including total params and total trainable params.
  2050. Examples:
  2051. .. code-block:: python
  2052. >>> import paddle
  2053. >>> from paddle.static import InputSpec
  2054. >>> input = InputSpec([None, 1, 28, 28], 'float32', 'image')
  2055. >>> label = InputSpec([None, 1], 'int64', 'label')
  2056. >>> model = paddle.Model(paddle.vision.models.LeNet(), input, label)
  2057. >>> optim = paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters())
  2058. >>> model.prepare(optim, paddle.nn.CrossEntropyLoss())
  2059. >>> params_info = model.summary()
  2060. >>> print(params_info)
  2061. ---------------------------------------------------------------------------
  2062. Layer (type) Input Shape Output Shape Param #
  2063. ===========================================================================
  2064. Conv2D-1 [[1, 1, 28, 28]] [1, 6, 28, 28] 60
  2065. ReLU-1 [[1, 6, 28, 28]] [1, 6, 28, 28] 0
  2066. MaxPool2D-1 [[1, 6, 28, 28]] [1, 6, 14, 14] 0
  2067. Conv2D-2 [[1, 6, 14, 14]] [1, 16, 10, 10] 2,416
  2068. ReLU-2 [[1, 16, 10, 10]] [1, 16, 10, 10] 0
  2069. MaxPool2D-2 [[1, 16, 10, 10]] [1, 16, 5, 5] 0
  2070. Linear-1 [[1, 400]] [1, 120] 48,120
  2071. Linear-2 [[1, 120]] [1, 84] 10,164
  2072. Linear-3 [[1, 84]] [1, 10] 850
  2073. ===========================================================================
  2074. Total params: 61,610
  2075. Trainable params: 61,610
  2076. Non-trainable params: 0
  2077. ---------------------------------------------------------------------------
  2078. Input size (MB): 0.00
  2079. Forward/backward pass size (MB): 0.11
  2080. Params size (MB): 0.24
  2081. Estimated Total Size (MB): 0.35
  2082. ---------------------------------------------------------------------------
  2083. {'total_params': 61610, 'trainable_params': 61610}
  2084. """
  2085. assert (
  2086. input_size is not None or self._inputs is not None
  2087. ), "'input_size' or 'self._input' must be set"
  2088. if input_size is not None:
  2089. _input_size = input_size
  2090. else:
  2091. _input_size = self._inputs
  2092. return summary(self.network, _input_size, dtypes=dtype)
  2093. def _verify_spec(self, specs, shapes=None, dtypes=None, is_input=False):
  2094. out_specs = []
  2095. if specs is None:
  2096. # Note(Aurelius84): If not specific specs of `Input`, using argument names of `forward` function
  2097. # to generate `Input`. But how can we know the actual shape of each input tensor?
  2098. if is_input:
  2099. arg_names = extract_args(self.network.forward)[1:]
  2100. # While Saving inference model in dygraph, and providing inputs only in running.
  2101. if (
  2102. shapes is not None
  2103. and dtypes is not None
  2104. and in_dynamic_mode()
  2105. ):
  2106. out_specs = [
  2107. Input(name=n, dtype=dtypes[i], shape=shapes[i])
  2108. for i, n in enumerate(arg_names)
  2109. ]
  2110. else:
  2111. out_specs = [Input(name=n, shape=[None]) for n in arg_names]
  2112. else:
  2113. out_specs = to_list(specs)
  2114. elif isinstance(specs, dict):
  2115. assert is_input is False
  2116. out_specs = [
  2117. specs[n]
  2118. for n in extract_args(self.network.forward)
  2119. if n != 'self'
  2120. ]
  2121. else:
  2122. out_specs = to_list(specs)
  2123. # Note: checks each element has specified `name`.
  2124. if out_specs is not None:
  2125. for i, spec in enumerate(out_specs):
  2126. assert isinstance(spec, Input)
  2127. if spec.name is None:
  2128. raise ValueError(
  2129. f"Requires Input[{i}].name != None, but receive `None` with {spec}."
  2130. )
  2131. return out_specs
  2132. def _reset_metrics(self):
  2133. for metric in self._metrics:
  2134. metric.reset()
  2135. def _metrics_name(self):
  2136. metrics_name = ['loss'] if self._loss else []
  2137. for m in self._metrics:
  2138. metrics_name.extend(to_list(m.name()))
  2139. return metrics_name
  2140. def _len_data_loader(self, data_loader):
  2141. try:
  2142. steps = len(data_loader)
  2143. except Exception:
  2144. steps = None
  2145. return steps
  2146. def _update_inputs(self):
  2147. "Update self._inputs according to given inputs."
  2148. self._input_info = self._adapter._input_info
  2149. if self._input_info is not None and len(self._input_info) == 2:
  2150. self._inputs = self._verify_spec(
  2151. None, self._input_info[0], self._input_info[1], True
  2152. )
  2153. self._is_shape_inferred = True