data_parallel_model.py 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222
  1. ## @package data_parallel_model
  2. # Module caffe2.python.data_parallel_model
  3. from collections import OrderedDict
  4. from future.utils import viewitems, viewkeys, viewvalues
  5. import logging
  6. import copy
  7. from multiprocessing import cpu_count
  8. from caffe2.python import \
  9. model_helper, dyndep, scope, workspace, core, memonger, utils
  10. from caffe2.proto import caffe2_pb2
  11. import numpy as np
  12. import warnings
  13. dyndep.InitOpsLibrary("@/caffe2/caffe2/contrib/gloo:gloo_ops")
  14. # We only import nccl operators when the machine has GPUs
  15. # Otherwise the binary can be compiled with CPU-only mode, and
  16. # will not be able to find those modules
  17. if workspace.NumGpuDevices() > 0:
  18. dyndep.InitOpsLibrary("@/caffe2/caffe2/contrib/nccl:nccl_ops")
  19. dyndep.InitOpsLibrary("@/caffe2/caffe2/contrib/gloo:gloo_ops_gpu")
  20. log = logging.getLogger("data_parallel_model")
  21. log.setLevel(logging.INFO)
  22. _DEFAULT_TIMEOUT_SEC = 30
  23. _DEFAULT_BARRIER_NET_TIMEOUT_SEC = 300
  24. def Parallelize_GPU(*args, **kwargs):
  25. kwargs['cpu_device'] = False
  26. Parallelize(*args, **kwargs)
  27. def Parallelize_CPU(*args, **kwargs):
  28. kwargs['cpu_device'] = True
  29. Parallelize(*args, **kwargs)
  30. def Parallelize_iDeep(*args, **kwargs):
  31. kwargs['ideep'] = True
  32. Parallelize(*args, **kwargs)
  33. def Parallelize(
  34. model_helper_obj,
  35. input_builder_fun,
  36. forward_pass_builder_fun,
  37. param_update_builder_fun=None,
  38. optimizer_builder_fun=None,
  39. post_sync_builder_fun=None,
  40. pre_grad_net_transformer_fun=None,
  41. net_transformer_fun=None,
  42. devices=None,
  43. rendezvous=None,
  44. net_type='dag',
  45. broadcast_computed_params=True,
  46. optimize_gradient_memory=False,
  47. dynamic_memory_management=False,
  48. blobs_to_keep=None,
  49. use_nccl=False,
  50. max_concurrent_distributed_ops=16,
  51. cpu_device=False,
  52. ideep=False,
  53. num_threads_per_device=4,
  54. shared_model=False,
  55. combine_spatial_bn=False,
  56. barrier_net_timeout_sec=_DEFAULT_BARRIER_NET_TIMEOUT_SEC,
  57. ):
  58. '''
  59. Function to create a model that can run on many GPUs or CPUs.
  60. model_helper_obj: an object of ModelHelper
  61. input_builder_fun:
  62. Function that adds the input operators
  63. Note: Remember to instantiate reader outside of this
  64. function so all devices share same reader object.
  65. Signature: input_builder_fun(model)
  66. forward_pass_builder_fun:
  67. Function to add the operators to the model.
  68. Must return list of loss-blob references that
  69. are used to build the gradient. Loss scale parameter
  70. is passed, as you should scale the loss of your model
  71. by 1.0 / the total number of devices.
  72. Signature: forward_pass_builder_fun(model, loss_scale)
  73. param_update_builder_fun:
  74. Function that adds operators that are run after
  75. gradient update, such as updating the weights and
  76. weight decaying. This is called for each GPU separately.
  77. Signature: param_update_builder_fun(model)
  78. optimizer_builder_fun:
  79. Alternative to param_update_builder_fun, allows one
  80. to add an optimizer for the whole model. Called only
  81. once, without name or devicescope.
  82. net_transformer_fun:
  83. Optional function to transform the network after the
  84. network is built. It will be called once (NOT once per
  85. GPU.)
  86. Signature:
  87. net_transformer_fun(
  88. model, num_devices, device_prefix, device_type)
  89. pre_grad_net_transformer_fun:
  90. Optional function to transform the network similar to
  91. net_transformer_fun, but happens before gradient ops
  92. been add.
  93. Signature: pre_grad_net_transformer_fun(model)
  94. post_sync_builder_fun:
  95. Function applied after initial parameter sync has been
  96. completed, such as keeping multi-precision parameters
  97. in sync.
  98. Signature: post_sync_builder_fun(model)
  99. devices: List of GPU ids, such as [0, 1, 2, 3],
  100. rendezvous: used for rendezvous in distributed computation, if None
  101. then only one node is used. To create rendezvous,
  102. use <TBD>.
  103. net_type: Network type
  104. optimize_gradient_memory: whether to apply 'memonger' to share blobs
  105. shared_model (only for CPU) use same parameters on each device
  106. in gradient computation to reduce memory footprint.
  107. dynamic_memory_management: Whether to apply dynamic memory optimization
  108. by freeing unused blobs. The underlying (de)allocation
  109. uses cached allocator. For GPU training PLEASE MAKE SURE
  110. caffe2_cuda_memory_pool is set.
  111. blobs_to_keep : A list of blob names to keep and don't free during
  112. dynamic memory optimization (for example loss blob).
  113. cpu_device Use CPU instead of GPU.
  114. ideep Use ideep.
  115. combine_spatial_bn:
  116. When set to True, applies batch normalization across
  117. all devices within the node. If False, batch
  118. normalization will be done separately for each device.
  119. This option is currently only supported on the CPU.
  120. barrier_net_timeout_sec:
  121. The timeout in seconds of the barrier net, which is run
  122. to synchronize shards before a training epoch starts.
  123. Defaults to 300 seconds.
  124. '''
  125. assert scope.CurrentDeviceScope() is None \
  126. or scope.CurrentDeviceScope().device_type == caffe2_pb2.CPU, \
  127. "Parallelize must be called without device-scope, \
  128. device scope was: {}".format(scope.CurrentDeviceScope())
  129. if devices is None:
  130. if not (cpu_device or ideep):
  131. devices = list(range(0, workspace.NumCudaDevices()))
  132. else:
  133. devices = list(range(0, cpu_count()))
  134. if not (cpu_device or ideep):
  135. for gpu in devices:
  136. if gpu >= workspace.NumGpuDevices():
  137. log.warning("** Only {} GPUs available, GPUs {} requested".format(
  138. workspace.NumGpuDevices(), devices))
  139. break
  140. model_helper_obj._device_type = workspace.GpuDeviceType
  141. model_helper_obj._device_prefix = "gpu"
  142. model_helper_obj._shared_model = False
  143. device_name = "GPU"
  144. assert shared_model is False, "Shared model only supported on CPU"
  145. elif ideep:
  146. model_helper_obj._device_type = caffe2_pb2.IDEEP
  147. model_helper_obj._device_prefix = "ideep"
  148. device_name = "IDEEP"
  149. model_helper_obj._shared_model = shared_model
  150. if shared_model and rendezvous is not None:
  151. assert "Shared model only supported on single-node currently"
  152. else:
  153. model_helper_obj._device_type = caffe2_pb2.CPU
  154. model_helper_obj._device_prefix = "cpu"
  155. device_name = "CPU"
  156. model_helper_obj._shared_model = shared_model
  157. if shared_model and rendezvous is not None:
  158. assert "Shared model only supported on single-node currently"
  159. log.info("Parallelizing model for devices: {}".format(devices))
  160. extra_workers = 8 if rendezvous is not None else 0 # best-guess
  161. num_workers = len(devices) * num_threads_per_device + extra_workers
  162. max_concurrent_distributed_ops =\
  163. min(max_concurrent_distributed_ops, num_workers - 1)
  164. model_helper_obj.net.Proto().num_workers = num_workers
  165. model_helper_obj.net.Proto().type = net_type
  166. # Store some information in the model -- a bit ugly
  167. model_helper_obj._devices = devices
  168. model_helper_obj._rendezvous = rendezvous
  169. model_helper_obj._sync_barrier_net = None
  170. model_helper_obj._broadcast_context = None
  171. model_helper_obj._grad_names = []
  172. assert isinstance(model_helper_obj, model_helper.ModelHelper)
  173. # Keep track of params that were in the model before: they are not
  174. # data parallel, so we need to handle them separately
  175. non_datapar_params = copy.copy(model_helper_obj.params)
  176. # Add input and model
  177. log.info("Create input and model training operators")
  178. losses_by_gpu = {}
  179. num_shards = 1 if rendezvous is None else rendezvous['num_shards']
  180. loss_scale = 1.0 / (len(devices) * num_shards)
  181. has_parameter_updates = param_update_builder_fun is not None or \
  182. optimizer_builder_fun is not None
  183. assert not (
  184. param_update_builder_fun is not None and
  185. optimizer_builder_fun is not None
  186. ), 'Can only specify one of param_update_builder_fun, optimizer_builder_fun'
  187. # Check that a model that is used for validation/testing has
  188. # init_params False, otherwise running the param init net will overwrite
  189. # synchronized values by the training net
  190. if not has_parameter_updates and model_helper_obj.init_params:
  191. log.warning('')
  192. log.warning("############# WARNING #############")
  193. log.warning("Model {}/{} is used for testing/validation but".format(
  194. model_helper_obj.name, model_helper_obj))
  195. log.warning("has init_params=True!")
  196. log.warning("This can conflict with model training.")
  197. log.warning("Please ensure model = ModelHelper(init_params=False)")
  198. log.warning('####################################')
  199. log.warning('')
  200. # TODO: make into assert
  201. for device in devices:
  202. device_opt = core.DeviceOption(model_helper_obj._device_type, device)
  203. with core.DeviceScope(device_opt):
  204. with core.NameScope("{}_{}".format(model_helper_obj._device_prefix,
  205. device)):
  206. log.info("Model for {} : {}".format(device_name, device))
  207. input_builder_fun(model_helper_obj)
  208. losses = forward_pass_builder_fun(model_helper_obj, loss_scale)
  209. # Losses are not needed for test net
  210. if has_parameter_updates:
  211. assert isinstance(losses, list), \
  212. 'Model builder function must return list of loss blobs'
  213. for loss in losses:
  214. assert isinstance(loss, core.BlobReference), \
  215. 'Model builder func must return list of loss blobs'
  216. losses_by_gpu[device] = losses
  217. _ValidateParams(model_helper_obj.params)
  218. # Create parameter map
  219. model_helper_obj._device_grouped_blobs =\
  220. _GroupByDevice(model_helper_obj, devices,
  221. model_helper_obj.params, non_datapar_params)
  222. # computed params
  223. computed_params_grouped =\
  224. _GroupByDevice(model_helper_obj, devices,
  225. model_helper_obj.GetComputedParams(''), [])
  226. model_helper_obj._device_grouped_blobs.update(computed_params_grouped)
  227. model_helper_obj._param_names =\
  228. list(viewkeys(model_helper_obj._device_grouped_blobs))
  229. model_helper_obj._computed_param_names =\
  230. list(viewkeys(computed_params_grouped))
  231. if pre_grad_net_transformer_fun:
  232. pre_grad_net_transformer_fun(model_helper_obj)
  233. if has_parameter_updates:
  234. log.info("Adding gradient operators")
  235. _AddGradientOperators(devices, model_helper_obj, losses_by_gpu)
  236. if net_transformer_fun:
  237. net_transformer_fun(
  238. model_helper_obj,
  239. len(devices),
  240. model_helper_obj._device_prefix,
  241. model_helper_obj._device_type)
  242. if not has_parameter_updates:
  243. log.info("Parameter update function not defined --> only forward")
  244. _InferBlobDevice(model_helper_obj)
  245. return
  246. if combine_spatial_bn:
  247. assert(has_parameter_updates), \
  248. 'combine_spatial_bn should only be used for train model'
  249. _InterleaveOps(model_helper_obj)
  250. if cpu_device:
  251. _CPUInterDeviceBatchNormalization(model_helper_obj)
  252. else:
  253. _GPUInterDeviceBatchNormalization(model_helper_obj)
  254. _ValidateParams(model_helper_obj.params)
  255. # Group gradients by device and register to blob lookup
  256. param_to_grad = model_helper_obj.param_to_grad
  257. grads_ordered = [param_to_grad[p] for p in
  258. model_helper_obj.params if p in param_to_grad]
  259. non_datapar_grads = [param_to_grad[p] for p in non_datapar_params]
  260. gradients_grouped = _GroupByDevice(
  261. model_helper_obj,
  262. devices,
  263. grads_ordered,
  264. non_datapar_grads
  265. )
  266. model_helper_obj._device_grouped_blobs.update(gradients_grouped)
  267. model_helper_obj._grad_names = list(viewkeys(gradients_grouped))
  268. model_helper_obj._losses_by_gpu = losses_by_gpu
  269. _InferBlobDevice(model_helper_obj)
  270. log.info("Add gradient all-reduces for SyncSGD")
  271. if broadcast_computed_params:
  272. _BroadcastComputedParams(devices, model_helper_obj, rendezvous, use_nccl)
  273. if len(model_helper_obj._grad_names) > 0:
  274. # Gradients in reverse order
  275. reverse_ordered_grads = _GetReverseOrderedGrads(model_helper_obj)
  276. assert(len(reverse_ordered_grads) > 0)
  277. _AllReduceBlobs(
  278. reverse_ordered_grads,
  279. devices,
  280. model_helper_obj,
  281. model_helper_obj.net,
  282. rendezvous,
  283. use_nccl,
  284. max_concurrent_distributed_ops,
  285. )
  286. else:
  287. log.info("NOTE: Param builder function did not create any parameters.")
  288. log.info("Post-iteration operators for updating params")
  289. num_shards = 1 if rendezvous is None else rendezvous['num_shards']
  290. all_params = set(model_helper_obj.GetParams(''))
  291. if shared_model:
  292. _PruneParametersForSharing(model_helper_obj)
  293. if param_update_builder_fun is not None:
  294. for device in devices:
  295. device_opt = core.DeviceOption(model_helper_obj._device_type, device)
  296. with core.DeviceScope(device_opt):
  297. with core.NameScope(
  298. "{}_{}".format(model_helper_obj._device_prefix, device)
  299. ):
  300. param_update_builder_fun(model_helper_obj)
  301. else:
  302. log.info("Calling optimizer builder function")
  303. optimizer = optimizer_builder_fun(model_helper_obj)
  304. model_helper_obj._optimizer = optimizer
  305. (sync_blobs, sync_names) = _ComputeBlobsToSync(model_helper_obj)
  306. sync_blobs_grouped = _GroupByDevice(
  307. model_helper_obj,
  308. devices,
  309. sync_blobs,
  310. [],
  311. )
  312. model_helper_obj._device_grouped_blobs.update(sync_blobs_grouped)
  313. _InferBlobDevice(model_helper_obj)
  314. _AnalyzeOperators(model_helper_obj)
  315. # Configure dagnet to run with only one worker on the first iteration,
  316. # to prevent concurrency problems with allocs and nccl.
  317. arg = model_helper_obj.Proto().arg.add()
  318. arg.name = "first_iter_only_one_worker"
  319. arg.i = 1
  320. # Add initial parameter syncs
  321. log.info("Add initial parameter sync")
  322. _SyncAllParams(
  323. devices,
  324. model_helper_obj,
  325. model_helper_obj.param_init_net,
  326. model_helper_obj.param_init_net,
  327. rendezvous,
  328. sync_names,
  329. max_concurrent_distributed_ops=1
  330. )
  331. # Handle any operations that need to be done after parameter sync
  332. # i.e. making sure multi-precision copies of parameters are up-to-date
  333. if post_sync_builder_fun is not None:
  334. for device in devices:
  335. device_opt = core.DeviceOption(model_helper_obj._device_type, device)
  336. with core.DeviceScope(device_opt):
  337. with core.NameScope(
  338. "{}_{}".format(model_helper_obj._device_prefix, device)
  339. ):
  340. post_sync_builder_fun(model_helper_obj)
  341. assert not (optimize_gradient_memory and dynamic_memory_management), \
  342. """It is not advised to use gradient optimization ('memonger')
  343. with dynamic memory management."""
  344. if optimize_gradient_memory:
  345. _OptimizeGradientMemorySimple(model_helper_obj, losses_by_gpu, devices)
  346. if dynamic_memory_management:
  347. _AddDynamicMemoryOptimization(model_helper_obj, blobs_to_keep, devices)
  348. model_helper_obj._data_parallel_model_init_nets = [
  349. model_helper_obj.param_init_net,
  350. ]
  351. model_helper_obj._data_parallel_model_nets = [
  352. model_helper_obj.net
  353. ]
  354. _AddBarrierToModelNets(model_helper_obj, barrier_net_timeout_sec)
  355. if shared_model:
  356. _RemapParameterBlobsForSharedModel(model_helper_obj, all_params)
  357. def Parallelize_GPU_BMUF(*args, **kwargs):
  358. kwargs['cpu_device'] = False
  359. Parallelize_BMUF(*args, **kwargs)
  360. def Parallelize_CPU_BMUF(*args, **kwargs):
  361. kwargs['cpu_device'] = True
  362. Parallelize_BMUF(*args, **kwargs)
  363. def Parallelize_BMUF(
  364. model_helper_obj,
  365. input_builder_fun,
  366. forward_pass_builder_fun,
  367. param_update_builder_fun,
  368. block_learning_rate=1.0,
  369. block_momentum=None,
  370. devices=None,
  371. rendezvous=None,
  372. net_type='dag',
  373. master_device=None,
  374. use_nccl=False,
  375. nesterov=False,
  376. optimize_gradient_memory=False,
  377. reset_momentum_sgd=False,
  378. warmup_iterations=None,
  379. max_concurrent_distributed_ops=4,
  380. add_blobs_to_sync=None,
  381. num_threads_per_device=4,
  382. cpu_device=False,
  383. barrier_net_timeout_sec=_DEFAULT_BARRIER_NET_TIMEOUT_SEC,
  384. ):
  385. '''
  386. Function to create model that run on many GPUs and creates a net for
  387. parameter_updates that can be run independently for number of iterations
  388. then followed by another net that runs once to compute the final parameter
  389. updates according to block wise model update filtering rule described
  390. in : Scalable Training of Deep Learning Machines by Incremental Block
  391. Training with Intra-block Parallel Optimization and Blockwise Model-Update
  392. Filtering (ICASSP 2016).
  393. '''
  394. assert scope.CurrentDeviceScope() is None \
  395. or scope.CurrentDeviceScope().device_type == caffe2_pb2.CPU, \
  396. "Parallelize must be called without device-scope, \
  397. device scope was: {}".format(scope.CurrentDeviceScope())
  398. assert isinstance(model_helper_obj, model_helper.ModelHelper)
  399. if devices is None:
  400. devices = list(range(0, workspace.NumGpuDevices()))
  401. if master_device is None:
  402. master_device = devices[0]
  403. if not cpu_device:
  404. for gpu in devices:
  405. if gpu >= workspace.NumGpuDevices():
  406. log.warning("** Only {} GPUs available, GPUs {} requested".format(
  407. workspace.NumGpuDevices(), devices))
  408. break
  409. model_helper_obj._device_type = workspace.GpuDeviceType
  410. model_helper_obj._device_prefix = "gpu"
  411. else:
  412. model_helper_obj._device_type = caffe2_pb2.CPU
  413. model_helper_obj._device_prefix = "cpu"
  414. model_helper_obj._devices = devices
  415. model_helper_obj._rendezvous = rendezvous
  416. model_helper_obj._sync_barrier_net = None
  417. model_helper_obj._broadcast_context = None
  418. model_helper_obj._shared_model = False
  419. master_dev_opt = core.DeviceOption(model_helper_obj._device_type, master_device)
  420. # question: rendezvous structure
  421. num_shards = rendezvous['num_shards'] if rendezvous else 1
  422. # num_devices is #devices across all machines
  423. num_devices = len(devices) * num_shards
  424. # num_workers is #threads to execute the DAG per shard
  425. num_workers = num_threads_per_device * len(devices)
  426. if rendezvous:
  427. num_workers += 8
  428. loss_scale = 1.0 / num_devices
  429. if block_momentum is None:
  430. block_momentum = 1.0 - 1.0 / num_devices
  431. max_concurrent_distributed_ops = min(
  432. max_concurrent_distributed_ops,
  433. num_workers - 1
  434. )
  435. model_helper_obj.net.Proto().num_workers = num_workers
  436. model_helper_obj.net.Proto().type = net_type
  437. # A net for initializing global model parameters. Its called once in the
  438. # same step as net parameters initialization.
  439. model_helper_obj._global_model_init_net = core.Net('global_model_init')
  440. model_helper_obj._global_model_init_net.Proto().type = net_type
  441. model_helper_obj._global_model_init_net.Proto().num_workers = \
  442. num_workers
  443. # A net for computing final parameter updates. Its will run once after
  444. # running net (local models updates) for `num_local_iterations` times.
  445. model_helper_obj._global_model_param_updates_net = core.Net('global_model')
  446. model_helper_obj._global_model_param_updates_net.Proto().type = net_type
  447. model_helper_obj._global_model_param_updates_net.Proto().num_workers = \
  448. num_workers
  449. def _v(param):
  450. return "{}_v".format(param)
  451. def _g(param):
  452. return "{}_g".format(param)
  453. def _v_prev(param):
  454. return "{}_prev".format(param)
  455. # Keep track of params that were in the model before: they are not
  456. # data parallel, so we need to handle them separately
  457. non_datapar_params = copy.copy(model_helper_obj.params)
  458. model_helper_obj._losses_by_gpu = {}
  459. def _InitializeModels(gpu_id):
  460. input_builder_fun(model_helper_obj)
  461. loss = forward_pass_builder_fun(model_helper_obj, loss_scale)
  462. model_helper_obj._losses_by_gpu[gpu_id] = loss
  463. _ForEachDevice(
  464. devices,
  465. _InitializeModels,
  466. device_type=model_helper_obj._device_type,
  467. device_prefix=model_helper_obj._device_prefix,
  468. scoped=True
  469. )
  470. _ValidateParams(model_helper_obj.params)
  471. model_helper_obj._device_grouped_blobs =\
  472. _GroupByDevice(model_helper_obj, devices,
  473. model_helper_obj.params, non_datapar_params)
  474. model_helper_obj._param_names =\
  475. list(viewkeys(model_helper_obj._device_grouped_blobs))
  476. _AddGradientOperators(
  477. devices, model_helper_obj, model_helper_obj._losses_by_gpu
  478. )
  479. _ValidateParams(model_helper_obj.params)
  480. _InferBlobDevice(model_helper_obj)
  481. def _InitializeParamUpdate(gpu_id):
  482. param_update_builder_fun(model_helper_obj)
  483. _ForEachDevice(
  484. devices,
  485. _InitializeParamUpdate,
  486. device_type=model_helper_obj._device_type,
  487. device_prefix=model_helper_obj._device_prefix,
  488. scoped=True
  489. )
  490. model_parameter_names = list(
  491. viewkeys(model_helper_obj._device_grouped_blobs)
  492. )
  493. if warmup_iterations is not None:
  494. model_helper_obj._warmup_iterations = warmup_iterations
  495. # A net for broadcasting gpu-0 (master shard) parameters after
  496. # running net for `warmup_iterartions`.
  497. model_helper_obj._warmup_broadcast = core.Net('warmup-broadcast')
  498. model_helper_obj._warmup_broadcast.Proto().type = net_type
  499. model_helper_obj._warmup_broadcast.Proto().num_workers = \
  500. num_workers
  501. _SyncAllParams(
  502. devices,
  503. model_helper_obj,
  504. model_helper_obj.param_init_net,
  505. model_helper_obj._warmup_broadcast,
  506. rendezvous,
  507. model_parameter_names,
  508. max_concurrent_distributed_ops
  509. )
  510. for param_name in viewkeys(model_helper_obj._device_grouped_blobs):
  511. param = model_helper_obj._device_grouped_blobs[param_name][master_device]
  512. with core.DeviceScope(master_dev_opt):
  513. model_helper_obj._warmup_broadcast.Copy(param, _g(param))
  514. # (Step-0) Initialize momentum parameters on master device.
  515. for param_name in viewkeys(model_helper_obj._device_grouped_blobs):
  516. param = model_helper_obj._device_grouped_blobs[param_name][master_device]
  517. with core.DeviceScope(master_dev_opt):
  518. model_helper_obj._global_model_init_net.ConstantFill(
  519. param, _v(param), value=0.0
  520. )
  521. model_helper_obj._global_model_init_net.Copy(param, _g(param))
  522. if nesterov:
  523. model_helper_obj._global_model_init_net.ConstantFill(
  524. param, _v_prev(param), value=0.0
  525. )
  526. # (Step-1) Update models for num_local_iterations.
  527. # (Step-2) Compute post-local-updates average of the params.
  528. # Sum model params across GPUs and store resutls in param_avg blob.
  529. _AllReduceBlobs(
  530. model_parameter_names,
  531. devices,
  532. model_helper_obj,
  533. model_helper_obj._global_model_param_updates_net,
  534. rendezvous,
  535. use_nccl,
  536. max_concurrent_distributed_ops
  537. )
  538. # (Step-3) Update momentum params :
  539. # param_v = block_momentum * param_v
  540. # + block_learning_Rate * (param_avg - param)
  541. # if nesterov momentum:
  542. # param = param + param_v
  543. # - block_momentum * (param_v - param_v_prev)
  544. # param_v_prev = param_v
  545. # else:
  546. # param = param + param_v
  547. for param_name in model_parameter_names:
  548. param = model_helper_obj._device_grouped_blobs[param_name][master_device]
  549. with core.DeviceScope(master_dev_opt):
  550. # TODO(ataei) : Stop building the graph here to get model average ?
  551. model_helper_obj._global_model_param_updates_net.Scale(
  552. param, param, scale=1.0 / num_devices
  553. )
  554. model_helper_obj._global_model_param_updates_net.Sub(
  555. [param, _g(param)], param
  556. )
  557. model_helper_obj._global_model_param_updates_net.Scale(
  558. param, param, scale=block_learning_rate
  559. )
  560. model_helper_obj._global_model_param_updates_net.Scale(
  561. _v(param), _v(param), scale=block_momentum
  562. )
  563. model_helper_obj._global_model_param_updates_net.Add(
  564. [_v(param), param], _v(param)
  565. )
  566. model_helper_obj._global_model_param_updates_net.Add(
  567. [_g(param), _v(param)], _g(param)
  568. )
  569. if nesterov:
  570. model_helper_obj._global_model_param_updates_net.Sub(
  571. [_v(param), _v_prev(param)], _v_prev(param)
  572. )
  573. model_helper_obj._global_model_param_updates_net.Scale(
  574. _v_prev(param), _v_prev(param), scale=block_momentum
  575. )
  576. model_helper_obj._global_model_param_updates_net.Sub(
  577. [_g(param), _v_prev(param)], _g(param)
  578. )
  579. model_helper_obj._global_model_param_updates_net.Copy(
  580. _v(param), _v_prev(param)
  581. )
  582. model_helper_obj._global_model_param_updates_net.Copy(
  583. _g(param), param
  584. )
  585. _SyncAllParams(
  586. devices,
  587. model_helper_obj,
  588. model_helper_obj.param_init_net,
  589. model_helper_obj._global_model_param_updates_net,
  590. rendezvous,
  591. model_parameter_names,
  592. max_concurrent_distributed_ops
  593. )
  594. # Add additional syncs
  595. if add_blobs_to_sync is not None:
  596. AddBlobSync(
  597. model_helper_obj,
  598. add_blobs_to_sync,
  599. net=model_helper_obj._global_model_param_updates_net)
  600. # Reset momentum-SGD parameters
  601. if reset_momentum_sgd:
  602. momentum_ops = [op for op in model_helper_obj.net.Proto().op
  603. if op.type == 'MomentumSGDUpdate']
  604. for op in momentum_ops:
  605. momentum_blob = op.input[1]
  606. with core.DeviceScope(op.device_option):
  607. model_helper_obj._global_model_param_updates_net.ConstantFill(
  608. [momentum_blob], momentum_blob, value=0.0
  609. )
  610. if optimize_gradient_memory:
  611. _OptimizeGradientMemorySimple(
  612. model_helper_obj, model_helper_obj._losses_by_gpu, devices
  613. )
  614. model_helper_obj._data_parallel_model_init_nets = [
  615. model_helper_obj.param_init_net,
  616. model_helper_obj._global_model_init_net
  617. ]
  618. model_helper_obj._data_parallel_model_nets = [
  619. model_helper_obj.net,
  620. (model_helper_obj._global_model_param_updates_net, 1)
  621. ]
  622. _AddBarrierToModelNets(model_helper_obj, barrier_net_timeout_sec)
  623. def CreateNet(model, overwrite=False):
  624. for net_iters in model._data_parallel_model_nets:
  625. if isinstance(net_iters, tuple):
  626. workspace.CreateNet(net_iters[0], overwrite=overwrite)
  627. else:
  628. workspace.CreateNet(net_iters, overwrite=overwrite)
  629. def RunInitNet(model):
  630. for init_net in model._data_parallel_model_init_nets:
  631. workspace.RunNetOnce(init_net)
  632. CreateNet(model)
  633. def RunWarmup(model):
  634. workspace.RunNet(model.net, model._warmup_iterations)
  635. workspace.RunNetOnce(model._warmup_broadcast)
  636. def RunNet(model, num_iterations):
  637. for net_iter in model._data_parallel_model_nets:
  638. if isinstance(net_iter, tuple):
  639. workspace.RunNet(net_iter[0].Proto().name, net_iter[1])
  640. else:
  641. workspace.RunNet(net_iter, num_iterations)
  642. def _AddBarrierToModelNets(model, barrier_net_timeout_sec):
  643. if model._rendezvous is not None and model._rendezvous['engine'] == 'GLOO':
  644. # Synchronize DPM at the start of each epoch. This allows shards that
  645. # starts an epoch sooner to wait for slower shards. Without this,
  646. # shards that are faster than others will begin training the next epoch
  647. # while stragglers are blocked on IO, and may timeout after 30 seconds
  648. # (_DEFAULT_TIMEOUT_SEC).
  649. # We pass in model.param_init_net so that the barrier net can be run as
  650. # part of the param_init_net.
  651. model._barrier_init_net = core.Net("barrier_init_net")
  652. model._barrier_net = _CreateBarrierNet(model, model._barrier_init_net,
  653. "pre_training", barrier_net_timeout_sec)
  654. model._data_parallel_model_init_nets.insert(0, model._barrier_init_net)
  655. model._data_parallel_model_nets.insert(0, model._barrier_net)
  656. def _CreateBarrierNet(model, init_net, name_prefix, timeout_sec):
  657. log.info("Creating barrier net")
  658. assert model._rendezvous['engine'] == 'GLOO', "Engine does not support barrier"
  659. comm_world = _CreateOrCloneCommonWorld(
  660. init_net,
  661. name_prefix + "_barrier_cw",
  662. rendezvous=model._rendezvous,
  663. timeout_sec=timeout_sec,
  664. )
  665. barrier_net = core.Net(name_prefix + "_barrier_net")
  666. barrier_net.Barrier(
  667. inputs=[comm_world],
  668. outputs=[],
  669. engine=model._rendezvous['engine'],
  670. )
  671. return barrier_net
  672. # DEPRECATED: See warnings below.
  673. def Synchronize(model, timeout_sec=_DEFAULT_BARRIER_NET_TIMEOUT_SEC):
  674. warnings.warn("The Synchronize API has been deprecated. We now have a "
  675. "barrier net which runs before training to ensure all hosts wait "
  676. "before training starts. The default timeout for the barrier is "
  677. "300s and it can be overridden using the barrier_net_timeout_sec "
  678. "parameter when calling Parallelize.",
  679. category=DeprecationWarning, stacklevel=2)
  680. if model._rendezvous is None or model._rendezvous['num_shards'] <= 1:
  681. # Single host case
  682. return
  683. if model._sync_barrier_net is None:
  684. barrier_init_net = core.Net("sync_barrier_init_net")
  685. model._sync_barrier_net = _CreateBarrierNet(
  686. model, barrier_init_net, "sync", timeout_sec)
  687. workspace.RunNetOnce(barrier_init_net)
  688. workspace.CreateNet(model._sync_barrier_net)
  689. model._sync_barrier_net_timeout = timeout_sec
  690. assert model._sync_barrier_net_timeout == timeout_sec, \
  691. "Must use fixed timeout, {} != {}".format(
  692. model._sync_barrier_net_timeout, timeout_sec
  693. )
  694. log.info("Synchronize run barrier net.")
  695. workspace.RunNet(model._sync_barrier_net)
  696. def ConvertNetForDevice(net, device=None):
  697. '''
  698. Converts all blobs in the net to have namescope gpu_X, and correct
  699. device scope. You can use this to enable AppendNet with a
  700. forward_pass_builder_fun:
  701. def builder_fun(model):
  702. ...
  703. model.net.AppendNet(
  704. data_parallel_model.ConvertNetForDevice(othermodel.net))
  705. model.param_init_net.AppendNet(
  706. data_parallel_model.ConvertNetForDevice(othermodel.param_init_net))
  707. '''
  708. mnet = copy.deepcopy(net)
  709. if device is None:
  710. device = scope.CurrentDeviceScope()
  711. if core.IsGPUDeviceType(device.device_type):
  712. device_prefix = "gpu"
  713. elif device.device_type == caffe2_pb2.IDEEP:
  714. device_prefix = "ideep"
  715. else:
  716. device_prefix = "cpu"
  717. namescope = "{}_{}/".format(device_prefix, device.device_id)
  718. for op in mnet.Proto().op:
  719. if "RecurrentNetwork" in op.type:
  720. raise NotImplementedError("RecurrentNetwork conversion not yet supported")
  721. for i, inputb in enumerate(op.input):
  722. op.input[i] = namescope + inputb
  723. for i, outputb in enumerate(op.output):
  724. op.output[i] = namescope + outputb
  725. for i, blob in enumerate(op.control_input):
  726. op.control_input[i] = namescope + blob
  727. op.device_option.CopyFrom(device)
  728. for i, einp in enumerate(mnet.Proto().external_input):
  729. mnet.Proto().external_input[i] = namescope + einp
  730. for i, eoutp in enumerate(mnet.Proto().external_output):
  731. mnet.Proto().external_output[i] = namescope + eoutp
  732. return mnet
  733. def _ForEachDevice(devices, f, device_type, device_prefix, scoped=False,
  734. *args, **kwargs):
  735. for device in devices:
  736. device_opt = core.DeviceOption(device_type, device)
  737. with core.DeviceScope(device_opt):
  738. if scoped:
  739. with core.NameScope("{}_{}".format(device_prefix, device)):
  740. f(device, *args, **kwargs)
  741. else:
  742. f(device, *args, **kwargs)
  743. def _AddGradientOperators(devices, model, losses_by_gpu):
  744. def create_grad(lossp):
  745. return model.ConstantFill(lossp, str(lossp) + "_grad", value=1.0)
  746. loss_grad = {}
  747. # Explicitly need to create gradients on each GPU
  748. for gpu_id in devices:
  749. device = core.DeviceOption(model._device_type, gpu_id)
  750. with core.DeviceScope(device):
  751. for l in losses_by_gpu[gpu_id]:
  752. lg = create_grad(l)
  753. loss_grad[str(l)] = str(lg)
  754. model.AddGradientOperators(loss_grad)
  755. def ExtractPredictorNet(model, inputs, outputs, device):
  756. '''
  757. Returns (net, params) that can be exported to be used as a prediction
  758. net.
  759. '''
  760. master_device = model._devices[0]
  761. prefix = "{}_{}/".format(model._device_prefix, master_device)
  762. prefix_inputs = [prefix + str(b) for b in inputs]
  763. prefix_outputs = [prefix + str(b) for b in outputs]
  764. (predictor_net, export_blobs) = model_helper.ExtractPredictorNet(
  765. net_proto=model.net.Proto(),
  766. input_blobs=prefix_inputs,
  767. output_blobs=prefix_outputs,
  768. device=device,
  769. renames={
  770. a: b
  771. for (a, b) in zip(prefix_inputs + prefix_outputs, inputs + outputs)
  772. },
  773. )
  774. return (predictor_net, export_blobs)
  775. def GetCheckpointParams(model):
  776. '''
  777. Returns a set of blobs that are needed for a complete check point.
  778. They are blobs for the first gpu and iteration blobs.
  779. '''
  780. (all_blobs, _) = _ComputeBlobsToSync(model)
  781. first_gpu_blobs = {
  782. b
  783. for b in all_blobs
  784. if str(b)
  785. .startswith("{}_{}/".format(model._device_prefix, model._devices[0]))
  786. }
  787. # Add iteration blobs that do not have namescope separately, since
  788. # it is important to checkpoint iteration counter
  789. iteration_blobs = set()
  790. for op in model.net.Proto().op:
  791. if op.type == 'Iter' or op.type == 'AtomicIter':
  792. if not op.output[0].startswith("{}_".format(model._device_prefix)):
  793. iteration_blobs.add(op.output[0])
  794. return first_gpu_blobs.union(iteration_blobs)
  795. def FinalizeAfterCheckpoint(model, blobs=None, cpu_mode=False):
  796. '''
  797. This function should be called after loading parameters from a
  798. checkpoint / initial parameters file.
  799. '''
  800. if not hasattr(model, "_checkpoint_net"):
  801. if blobs is None:
  802. (_, uniq_blob_names) = _ComputeBlobsToSync(model)
  803. else:
  804. uniq_blob_names = [stripBlobName(p) for p in blobs]
  805. # Synchronize to the blob lookup map, as the provided
  806. # blobs might have non-parameters, such as momentum blobs.
  807. log.info("Creating checkpoint synchronization net")
  808. devices = model.GetDevices()
  809. for name in uniq_blob_names:
  810. if name not in model._device_grouped_blobs:
  811. grouped = {
  812. d:
  813. core.BlobReference("{}_{}{}{}".format(
  814. model._device_prefix,
  815. d,
  816. scope._NAMESCOPE_SEPARATOR,
  817. name)
  818. ) for d in devices}
  819. model._device_grouped_blobs[name] = grouped
  820. model._checkpoint_net = core.Net("checkpoint_sync_net")
  821. if not cpu_mode:
  822. model._checkpoint_net.RunAllOnGPU()
  823. checkpoint_init_net = None
  824. if (model._rendezvous is not None and model._rendezvous['num_shards'] > 1):
  825. checkpoint_init_net = core.Net("checkpoint_init_net")
  826. if not cpu_mode:
  827. checkpoint_init_net.RunAllOnGPU()
  828. _SyncAllParams(
  829. devices,
  830. model,
  831. checkpoint_init_net,
  832. model._checkpoint_net,
  833. model._rendezvous,
  834. uniq_blob_names,
  835. max_concurrent_distributed_ops=1
  836. )
  837. if (checkpoint_init_net):
  838. workspace.RunNetOnce(checkpoint_init_net)
  839. workspace.CreateNet(model._checkpoint_net)
  840. # Run the sync
  841. log.info("Run checkpoint net")
  842. workspace.RunNet(model._checkpoint_net.Proto().name)
  843. def GetLearningRateBlobNames(model):
  844. '''
  845. Returns a list of learning rates blob names used in the optimizer.
  846. '''
  847. if model._optimizer is not None:
  848. if model._device_type == caffe2_pb2.CPU or model._device_type == caffe2_pb2.IDEEP:
  849. return [model._optimizer.get_cpu_blob_name('lr')]
  850. elif core.IsGPUDeviceType(model._device_type):
  851. return [model._optimizer.get_gpu_blob_name('lr', gpu, '')
  852. for gpu in model._devices]
  853. else:
  854. raise Exception(
  855. "Unsupported device type : {}".format(model._device_type)
  856. )
  857. else:
  858. lr_blob_names = []
  859. for op in model.net.Proto().op:
  860. if op.type == "LearningRate":
  861. lr_blob_names.append(op.output(0))
  862. return lr_blob_names
  863. def _Broadcast(devices, model, net, param, use_nccl=False):
  864. # Copy params from gpu_0 to other
  865. master_dev = devices[0]
  866. if use_nccl:
  867. if _IsGPUBlob(model, param):
  868. master_device_opt = core.DeviceOption(model._device_type, master_dev)
  869. with core.DeviceScope(master_device_opt):
  870. # Note that the root is the root _rank_ and not the root
  871. # _device_. Thus we always use root=0, regardless of the
  872. # devices used.
  873. net.NCCLBroadcast(
  874. list(viewvalues(model._device_grouped_blobs[param])),
  875. list(viewvalues(model._device_grouped_blobs[param])),
  876. root=0,
  877. )
  878. return
  879. for dev_idx in devices[1:]:
  880. if _IsGPUBlob(model, param):
  881. device_opt = core.DeviceOption(workspace.GpuDeviceType, dev_idx)
  882. else:
  883. device_opt = core.DeviceOption(caffe2_pb2.IDEEP, 0) if _IsIDEEPBlob(model, param) else \
  884. core.DeviceOption(caffe2_pb2.CPU, 0)
  885. with core.DeviceScope(device_opt):
  886. net.Copy(
  887. model._device_grouped_blobs[param][master_dev],
  888. model._device_grouped_blobs[param][dev_idx]
  889. )
  890. def _AllReduce(devices, model, net, param, use_nccl=False, control_input=None):
  891. blobs_group = list(viewvalues(model._device_grouped_blobs[param]))
  892. if model._device_type == caffe2_pb2.CUDA and use_nccl:
  893. # TODO: for _shared_model, do only NCCLReduce
  894. model.NCCLAllreduce(
  895. blobs_group, blobs_group, control_input=control_input
  896. )
  897. return
  898. if model._device_type == workspace.GpuDeviceType:
  899. p2p_access_pattern = workspace.GetGpuPeerAccessPattern()
  900. else:
  901. p2p_access_pattern = None
  902. def sumN(*dev_indices):
  903. """Create a Sum op for 2 or more blobs on different devices.
  904. Saves the result on the first device.
  905. Args:
  906. dev_indices -- a list of device indices, which can be translated into
  907. CUDA identifiers with model._devices
  908. """
  909. devices = [model._devices[idx] for idx in dev_indices]
  910. blobs = [blobs_group[idx] for idx in dev_indices]
  911. device_opt = core.DeviceOption(model._device_type, devices[0])
  912. with core.DeviceScope(device_opt):
  913. for i, peer in enumerate(devices):
  914. if i == 0:
  915. continue # Skip the first device
  916. if p2p_access_pattern is not None and p2p_access_pattern.size and not p2p_access_pattern[
  917. devices[0], peer
  918. ]:
  919. # Copy from peer to d0
  920. blobs[i] = model.Copy(
  921. blobs[i],
  922. 'gpu_{}/{}_gpu{}_copy'.format(devices[0], param, peer)
  923. )
  924. net.Sum(blobs, [blobs[0]], name='dpm')
  925. if len(devices) == 16:
  926. # Special tree reduction for 16 gpus, TODO generalize like in muji.py
  927. for j in range(8):
  928. sumN(j * 2, j * 2 + 1)
  929. for j in range(4):
  930. sumN(j * 4, j * 4 + 2)
  931. for j in range(2):
  932. sumN(j * 8, j * 8 + 4)
  933. sumN(0, 8)
  934. elif len(devices) == 8:
  935. for j in range(4):
  936. sumN(j * 2, j * 2 + 1)
  937. for j in range(2):
  938. sumN(j * 4, j * 4 + 2)
  939. sumN(0, 4)
  940. elif len(devices) == 4:
  941. sumN(0, 1)
  942. sumN(2, 3)
  943. sumN(0, 2)
  944. else:
  945. sumN(*range(len(devices)))
  946. # TODO: for _shared_model, no need to broadcast
  947. _Broadcast(devices, model, net, param)
  948. def _SyncAllParams(
  949. devices,
  950. model,
  951. init_net,
  952. net,
  953. rendezvous,
  954. unique_param_names,
  955. max_concurrent_distributed_ops=4
  956. ):
  957. if rendezvous is None or rendezvous['num_shards'] <= 1:
  958. _SyncAllParamsSingleHost(devices, model, net, unique_param_names)
  959. else:
  960. _SyncAllParamsDistributed(
  961. devices,
  962. model,
  963. init_net,
  964. net,
  965. rendezvous,
  966. unique_param_names,
  967. max_concurrent_distributed_ops
  968. )
  969. def AddBlobSync(model, blobs, net=None):
  970. '''
  971. Sync a blob across devices and hosts
  972. '''
  973. if len(blobs) == 0:
  974. return
  975. net = model.net if net is None else net
  976. for b in blobs:
  977. assert not b.startswith(model._device_prefix), \
  978. "Provide unprefixed blob name: {}".format(b)
  979. model._device_grouped_blobs[b] = {
  980. d: core.BlobReference("{}_{}/{}".format(model._device_prefix, d, b))
  981. for d in model._devices
  982. }
  983. _SyncAllParams(
  984. model._devices,
  985. model,
  986. model.param_init_net,
  987. net,
  988. model._rendezvous,
  989. set(blobs))
  990. def AddDistributedBlobSync(model, blobs):
  991. '''
  992. Sync blobs across machines (but not across devices)
  993. '''
  994. if model._rendezvous is None:
  995. return
  996. synth_name = "_".join([str(b) for b in blobs])
  997. comm_world = _CreateOrCloneCommonWorld(
  998. model.param_init_net,
  999. "blob_sync_cw_" + synth_name,
  1000. rendezvous=model._rendezvous,
  1001. )
  1002. model.net.Allreduce(
  1003. inputs=[comm_world] + blobs,
  1004. outputs=blobs,
  1005. engine=model._rendezvous['engine'],
  1006. )
  1007. def _SyncAllParamsDistributed(
  1008. devices,
  1009. model,
  1010. init_net,
  1011. net,
  1012. rendezvous,
  1013. unique_param_names,
  1014. max_concurrent_distributed_ops
  1015. ):
  1016. assert rendezvous['num_shards'] > 1
  1017. gpu_device_opt = core.DeviceOption(model._device_type, devices[0])
  1018. cpu_device_opt = core.DeviceOption(caffe2_pb2.CPU)
  1019. ideep_device_opt = core.DeviceOption(caffe2_pb2.IDEEP)
  1020. if model._broadcast_context is None:
  1021. model._broadcast_context = CollectivesConcurrencyControl(
  1022. "broadcast",
  1023. max_concurrent_distributed_ops,
  1024. init_net,
  1025. rendezvous
  1026. )
  1027. context = model._broadcast_context
  1028. for param_name in sorted(unique_param_names):
  1029. master_param = model._device_grouped_blobs[param_name][devices[0]]
  1030. params_group = list(viewvalues(model._device_grouped_blobs[param_name]))
  1031. def broadcast(params):
  1032. comm_world, control_input = context.get_control_and_context(params)
  1033. net.Broadcast(
  1034. inputs=[comm_world] + params,
  1035. outputs=params,
  1036. name=param_name,
  1037. engine=rendezvous['engine'],
  1038. control_input=control_input
  1039. )
  1040. device_opt = gpu_device_opt if _IsGPUBlob(
  1041. model, param_name
  1042. ) else ideep_device_opt if _IsIDEEPBlob(model, param_name) else cpu_device_opt
  1043. if rendezvous['engine'] == 'GLOO':
  1044. with core.DeviceScope(device_opt):
  1045. broadcast(params_group)
  1046. else:
  1047. # Copy between GPU and CPU
  1048. with core.DeviceScope(device_opt):
  1049. param_cpu = net.CopyGPUToCPU(
  1050. master_param,
  1051. str(master_param) + "cpu"
  1052. )
  1053. with core.DeviceScope(cpu_device_opt):
  1054. broadcast([param_cpu])
  1055. with core.DeviceScope(device_opt):
  1056. net.CopyCPUToGPU(param_cpu, master_param)
  1057. # Broadcast locally
  1058. _Broadcast(devices, model, net, param_name)
  1059. def _SyncAllParamsSingleHost(devices, model, net, unique_param_names):
  1060. for param in unique_param_names:
  1061. _Broadcast(devices, model, net, param)
  1062. def _AllReduceBlobs(blob_names, devices, model, net, rendezvous, use_nccl,
  1063. max_concurrent_distributed_ops):
  1064. if rendezvous is None or rendezvous['num_shards'] <= 1:
  1065. _AllReduceBlobsSingleHost(
  1066. blob_names,
  1067. devices,
  1068. model,
  1069. net,
  1070. use_nccl
  1071. )
  1072. else:
  1073. _AllReduceBlobsDistributed(
  1074. blob_names,
  1075. devices,
  1076. model,
  1077. net,
  1078. rendezvous,
  1079. max_concurrent_distributed_ops,
  1080. )
  1081. def _PruneParametersForSharing(model):
  1082. assert model._shared_model
  1083. master_prefix = "{}_{}/".format(model._device_prefix, model._devices[0])
  1084. # Remove non-master parameters so that they will not receive parameter
  1085. # update operators.
  1086. model.params = model.GetParams(master_prefix)
  1087. paramset = set(model.params)
  1088. model.param_to_grad = {
  1089. p: model.param_to_grad[p]
  1090. for p in model.param_to_grad if p in paramset
  1091. }
  1092. model.weights = [w for w in model.weights if w in paramset]
  1093. model.biases = [w for w in model.biases if w in paramset]
  1094. def _RemapParameterBlobsForSharedModel(model, all_params):
  1095. assert model._shared_model
  1096. master_prefix = "{}_{}/".format(
  1097. model._device_prefix, model._devices[0])
  1098. log.info("Remapping param blobs to master -> {}".format(master_prefix))
  1099. master_params = set(model.GetParams())
  1100. # Remove all but master params
  1101. def modify_ops(net):
  1102. ops = []
  1103. for op in net.Proto().op:
  1104. delete_op = False
  1105. # Delete ops that output non-master version of parameter
  1106. for outp in op.output:
  1107. if outp in all_params and outp not in master_params:
  1108. delete_op = True
  1109. log.debug("Delete b/c {}: {}".format(outp, str(op)))
  1110. break
  1111. if delete_op:
  1112. continue
  1113. # Remap inputs to point to the master param
  1114. for j, inp in enumerate(op.input):
  1115. if inp in all_params and inp not in master_params:
  1116. op.input[j] = master_prefix + stripBlobName(inp)
  1117. ops.append(op)
  1118. del net.Proto().op[:]
  1119. net.Proto().op.extend(ops)
  1120. modify_ops(model.param_init_net)
  1121. modify_ops(model.net)
  1122. class CollectivesConcurrencyControl(object):
  1123. """
  1124. Creates common worlds (up to max_concurrent_context) and manage the
  1125. sequential execution of collectives that shares the same context with
  1126. cyclic control inputs.
  1127. """
  1128. def __init__(
  1129. self,
  1130. name,
  1131. max_concurrent_context,
  1132. param_init_net,
  1133. rendezvous
  1134. ):
  1135. self.name = name
  1136. self.param_init_net = param_init_net
  1137. self.max_concurrent_context = max_concurrent_context
  1138. self.counter = 0
  1139. self.common_worlds = []
  1140. self.control_inputs = []
  1141. self.rendezvous = rendezvous
  1142. def get_control_and_context(self, control_output_blob):
  1143. common_world, control_input = [None, None]
  1144. current_slot = self.counter % self.max_concurrent_context
  1145. if len(self.common_worlds) < self.max_concurrent_context:
  1146. common_world = _CreateOrCloneCommonWorld(
  1147. self.param_init_net,
  1148. "{}_{}_cw".format(self.name, current_slot),
  1149. rendezvous=self.rendezvous,
  1150. )
  1151. self.common_worlds.append(common_world)
  1152. self.control_inputs.append(control_output_blob)
  1153. else:
  1154. common_world = self.common_worlds[current_slot]
  1155. control_input = self.control_inputs[current_slot]
  1156. self.control_inputs[current_slot] = control_output_blob
  1157. self.counter += 1
  1158. return common_world, control_input
  1159. def _AllReduceBlobsDistributed(
  1160. blob_names,
  1161. devices,
  1162. model,
  1163. net,
  1164. rendezvous,
  1165. max_concurrent_distributed_ops,
  1166. ):
  1167. num_workers = model.net.Proto().num_workers
  1168. assert num_workers > 1, "Please specify more than 1 worker"
  1169. all_reduce_engine = rendezvous['engine']
  1170. master_device_opt = core.DeviceOption(model._device_type, devices[0])
  1171. reducing_device_opt = master_device_opt
  1172. context = CollectivesConcurrencyControl(
  1173. "allreduce",
  1174. max_concurrent_distributed_ops,
  1175. model.param_init_net,
  1176. rendezvous
  1177. )
  1178. nccl_control_blob = None
  1179. for blob_name in blob_names:
  1180. master_blob = model._device_grouped_blobs[blob_name][devices[0]]
  1181. blobs_group = list(viewvalues(model._device_grouped_blobs[blob_name]))
  1182. assert master_blob in blobs_group
  1183. # Remark: NCCLReduce does not support in-place modifications
  1184. # so we need a temporary blob
  1185. reduced_blob = str(master_blob) + "_red"
  1186. def allreduce(blobs, **kwargs):
  1187. with core.DeviceScope(reducing_device_opt):
  1188. comm_world, control_input = \
  1189. context.get_control_and_context(blobs[0])
  1190. net.Allreduce(
  1191. inputs=[comm_world] + blobs,
  1192. outputs=blobs,
  1193. name=blob_name,
  1194. engine=all_reduce_engine,
  1195. control_input=control_input,
  1196. **kwargs
  1197. )
  1198. if rendezvous['engine'] == 'GLOO':
  1199. # With Gloo cross GPU and cross machine allreduce
  1200. # can be executed in a single operation.
  1201. # Try to use GPUDirect if transport == ibverbs.
  1202. allreduce(
  1203. blobs_group,
  1204. gpu_direct=(rendezvous.get("transport", None) == "ibverbs"),
  1205. )
  1206. else:
  1207. # Step 1: sum blobs from local GPUs to master GPU
  1208. with core.DeviceScope(master_device_opt):
  1209. model.ConstantFill(master_blob, reduced_blob, value=0.0)
  1210. # Temp fix since NCCLReduce does not work
  1211. net.NCCLAllreduce(
  1212. blobs_group,
  1213. blobs_group,
  1214. control_input=nccl_control_blob,
  1215. )
  1216. nccl_control_blob = blobs_group[0]
  1217. net.Copy(master_blob, reduced_blob)
  1218. # Step 2: allreduce between all hosts, between master GPUs
  1219. allreduce([reduced_blob])
  1220. with core.DeviceScope(master_device_opt):
  1221. net.Copy(reduced_blob, master_blob)
  1222. # Step 3: broadcast locally
  1223. _Broadcast(devices, model, net, blob_name)
  1224. def _AllReduceBlobsSingleHost(blob_names, devices, model, net, use_nccl):
  1225. """Performs NCCL AllReduce to distribute blobs to all the GPUs."""
  1226. if len(devices) == 1:
  1227. return
  1228. # Now we need to Allreduce blobs on all the GPUs.
  1229. # Pick GPU #0 as a master GPU.
  1230. master_device_opt = core.DeviceOption(model._device_type, devices[0])
  1231. last_out = None
  1232. concatenated_idx = set()
  1233. for blob_name in blob_names:
  1234. # Group by blob_name for reduce.
  1235. blobs_group = list(viewvalues(model._device_grouped_blobs[blob_name]))
  1236. if len(blobs_group) == 1:
  1237. # Non-reducible
  1238. continue
  1239. assert len(blobs_group) == len(devices), \
  1240. "Each GPU from {}, should have a copy of {}.".format(
  1241. devices, blob_name)
  1242. if _IsGPUBlob(model, blob_name):
  1243. with core.DeviceScope(master_device_opt):
  1244. if not isinstance(blobs_group[0], core.GradientSlice):
  1245. _AllReduce(
  1246. devices, model, net, blob_name, use_nccl, last_out
  1247. )
  1248. # last_out is used to serialize the execution of nccls
  1249. last_out = blobs_group[0]
  1250. else:
  1251. # Sparse gradients: all-gather for indices and values
  1252. master_ns = "{}_{}".format(model._device_prefix, devices[0])
  1253. '''
  1254. Skip if we have already copied concatenated indices
  1255. to the indices of GradientSlice. This happens when two
  1256. or more grad blobs are gathered with the same indices
  1257. blob
  1258. '''
  1259. skip_idx_concat = False
  1260. for g in blobs_group:
  1261. if g.indices in concatenated_idx:
  1262. skip_idx_concat = True
  1263. if not skip_idx_concat:
  1264. grad_idx_concat, _ = net.Concat(
  1265. [g.indices for g in blobs_group],
  1266. ["{}/{}_index_concat".format(master_ns, blob_name),
  1267. "{}/{}_index_splitinfo".format(master_ns, blob_name)],
  1268. axis=0,
  1269. name="note:data_parallel_model")
  1270. for gpu, g in viewitems(model._device_grouped_blobs[blob_name]):
  1271. device_opt = core.DeviceOption(model._device_type, gpu)
  1272. with core.DeviceScope(device_opt):
  1273. model.Copy(grad_idx_concat, g.indices)
  1274. concatenated_idx.add(g.indices)
  1275. grad_val_concat, _ = net.Concat(
  1276. [g.values for g in blobs_group],
  1277. ["{}/{}_val_concat".format(master_ns, blob_name),
  1278. "{}/{}_val_splitinfo".format(master_ns, blob_name)],
  1279. axis=0, name="note:data_parallel_model")
  1280. for gpu, g in viewitems(model._device_grouped_blobs[blob_name]):
  1281. device_opt = core.DeviceOption(model._device_type, gpu)
  1282. with core.DeviceScope(device_opt):
  1283. model.Copy(grad_val_concat, g.values)
  1284. elif _IsIDEEPBlob(model, blob_name):
  1285. assert not isinstance(blobs_group[0], core.GradientSlice), \
  1286. "Synchronizing gradient slices not supported"
  1287. with core.DeviceScope(core.DeviceOption(caffe2_pb2.IDEEP)):
  1288. net.Sum(blobs_group, [blobs_group[0]])
  1289. if not model._shared_model:
  1290. _Broadcast(devices, model, net, blob_name)
  1291. else:
  1292. assert not isinstance(blobs_group[0], core.GradientSlice), \
  1293. "Synchronizing gradient slices not supported"
  1294. with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):
  1295. # Poor man's allreduce
  1296. net.Sum(blobs_group, [blobs_group[0]])
  1297. if not model._shared_model:
  1298. _Broadcast(devices, model, net, blob_name)
  1299. def _BroadcastComputedParams(devices, model, rendezvous, use_nccl=False):
  1300. if rendezvous is None:
  1301. _BroadcastComputedParamsSingleHost(devices, model, use_nccl)
  1302. else:
  1303. _BroadcastComputedParamsDistributed(devices, model, rendezvous, use_nccl)
  1304. def _BroadcastComputedParamsDistributed(
  1305. devices,
  1306. model,
  1307. rendezvous,
  1308. use_nccl=False
  1309. ):
  1310. _BroadcastComputedParamsSingleHost(devices, model, use_nccl)
  1311. log.warn("Distributed broadcast of computed params is not implemented yet")
  1312. def _BroadcastComputedParamsSingleHost(devices, model, use_nccl=False):
  1313. '''
  1314. Average computed params over all devices
  1315. '''
  1316. if len(devices) == 1:
  1317. return
  1318. for param_name in model._computed_param_names:
  1319. # Copy from master to others -- averaging would be perhaps better,
  1320. # but currently NCCLAllReduce is too prone to deadlock
  1321. _Broadcast(devices, model, model.net, param_name, use_nccl)
  1322. def _GetReverseOrderedGrads(model):
  1323. '''
  1324. Returns the gradients in reverse order (namespace stripped),
  1325. for the optimal synchronization order.
  1326. '''
  1327. return list(reversed(model._grad_names))
  1328. # A helper function to extract a parameter's name
  1329. def stripBlobName(param):
  1330. # Format is "a/b/c/d" -> "b/c/d"
  1331. if isinstance(param, core.GradientSlice):
  1332. return stripBlobName(param.indices) + ":" + stripBlobName(param.values)
  1333. else:
  1334. name = str(param)
  1335. return name[name.index(scope._NAMESCOPE_SEPARATOR) + 1:]
  1336. def _AnalyzeOperators(model):
  1337. '''
  1338. Look at all the operators and check that they do not cross device scopes
  1339. '''
  1340. for op in model.Proto().op:
  1341. if "NCCL" in op.type or "Copy" in op.type or "Concat" in op.type:
  1342. continue
  1343. if "Sum" == op.type and op.name == "dpm":
  1344. continue
  1345. if "Allreduce" in op.type and "GLOO" in op.engine:
  1346. continue
  1347. op_dev = op.device_option
  1348. op_gpu = op_dev.device_id
  1349. # This avoids failing on operators that are only for CPU
  1350. if not core.IsGPUDeviceType(op_dev.device_type):
  1351. continue
  1352. namescope = "{}_{}/".format(model._device_prefix, op_gpu)
  1353. for inp in list(op.input) + list(op.output):
  1354. if inp.startswith("{}_".format(model._device_prefix)
  1355. ) and not inp.startswith(namescope):
  1356. raise Exception(
  1357. "Blob {} of op {}, should have namescope {}. Op: {}".format(
  1358. inp,
  1359. op.type,
  1360. "{}_{}/".format(model._device_prefix, op_gpu),
  1361. str(op),
  1362. )
  1363. )
  1364. def _InferBlobDevice(model):
  1365. '''
  1366. Assign blob to device option based on the operator outputing it
  1367. '''
  1368. mapping = {}
  1369. def map_ops(proto):
  1370. for op in proto.op:
  1371. device_option = op.device_option
  1372. if op.type == "Iter":
  1373. # Hack for Iters which have blob in CPU context
  1374. device_option = caffe2_pb2.DeviceOption()
  1375. device_option.device_type = caffe2_pb2.CPU
  1376. for b in list(op.input) + list(op.output):
  1377. if b not in mapping:
  1378. mapping[b] = device_option
  1379. if op.type.startswith('RecurrentNetwork'):
  1380. step_args = [a for a in op.arg if a.name.endswith("step_net")]
  1381. for step_arg in step_args:
  1382. map_ops(step_arg.n)
  1383. map_ops(model.param_init_net.Proto())
  1384. map_ops(model.net.Proto())
  1385. model._blob_to_device = mapping
  1386. def _IsIDEEPBlob(model, blob_name):
  1387. if blob_name in model._blob_to_device:
  1388. return model._blob_to_device[blob_name].device_type == caffe2_pb2.IDEEP
  1389. else:
  1390. blob_name = "{}_{}/{}".format(
  1391. model._device_prefix, model._devices[0], blob_name
  1392. )
  1393. if blob_name not in model._blob_to_device:
  1394. return model._device_type == caffe2_pb2.IDEEP
  1395. return model._blob_to_device[blob_name].device_type == caffe2_pb2.IDEEP
  1396. def _IsGPUBlob(model, blob_name):
  1397. if blob_name in model._blob_to_device:
  1398. return core.IsGPUDeviceType(model._blob_to_device[blob_name].device_type)
  1399. else:
  1400. blob_name = "{}_{}/{}".format(
  1401. model._device_prefix, model._devices[0], blob_name
  1402. )
  1403. if blob_name not in model._blob_to_device:
  1404. return core.IsGPUDeviceType(model._device_type)
  1405. return core.IsGPUDeviceType(model._blob_to_device[blob_name].device_type)
  1406. def _GroupByDevice(model, devices, params, non_data_params):
  1407. '''
  1408. Groups blobs by device, returning a map of [blobname] = {0: BlobRef, 1: ..}.
  1409. Returns ordered dictionary, ensuring the original order.
  1410. '''
  1411. grouped = OrderedDict()
  1412. # Only consider params that were created to be "data parallel"
  1413. params = params[len(non_data_params):]
  1414. for _i, p in enumerate(params):
  1415. assert isinstance(p, core.BlobReference) or \
  1416. isinstance(p, core.GradientSlice), \
  1417. "Param {} is not BlobReference or GradientSlice".format(p)
  1418. name = stripBlobName(p)
  1419. gpuid = None
  1420. if isinstance(p, core.BlobReference):
  1421. gpuid = int(p.GetNameScope().split("_")[1].split("/")[0])
  1422. assert "{}_{}/".format(model._device_prefix, gpuid) in p.GetNameScope(),\
  1423. "Param {} expected to have namescope '{}_{}'".format(str(p), model._device_prefix, gpuid)
  1424. else:
  1425. gpuid = int(p.indices.GetNameScope().split("_")[1].split("/")[0])
  1426. assert "{}_{}/".format(model._device_prefix, gpuid) in p.indices.GetNameScope(),\
  1427. "Indices {} expected to have namescope '{}_{}'".format(str(p), model._device_prefix, gpuid)
  1428. assert "{}_{}/".format(model._device_prefix, gpuid) in p.values.GetNameScope(),\
  1429. "Values {} expected to have namescope '{}_{}'".format(str(p), model._device_prefix, gpuid)
  1430. if name not in grouped:
  1431. grouped[name] = {}
  1432. grouped[name][gpuid] = p
  1433. return grouped
  1434. def _ValidateParams(params):
  1435. set_params = set(params)
  1436. if len(params) > len(set_params):
  1437. dupes = []
  1438. sp = sorted(params)
  1439. for j, p in enumerate(sp):
  1440. if j > 0 and sp[j - 1] == p:
  1441. dupes.append(p)
  1442. assert len(params) == len(set_params), \
  1443. "Duplicate entries in params: {}".format(dupes)
  1444. def _ComputeBlobsToSync(model):
  1445. '''
  1446. We sync all blobs that are generated by param init net and
  1447. are 'data parallel', i.e assigned to a device
  1448. '''
  1449. sync_names = set()
  1450. # We don't sync params if the model is shared
  1451. if model._shared_model:
  1452. blobs_to_sync = [str(p) for p in model.GetComputedParams('')]
  1453. sync_names = [stripBlobName(p) for p in blobs_to_sync]
  1454. else:
  1455. blobs_to_sync = []
  1456. for op in model.param_init_net.Proto().op:
  1457. dp_outputs = [
  1458. o for o in op.output
  1459. if o.startswith("{}_".format(model._device_prefix))
  1460. ]
  1461. sync_names.update([stripBlobName(o) for o in dp_outputs])
  1462. blobs_to_sync.extend(dp_outputs)
  1463. # Sanity check
  1464. diff = set(model._param_names) - sync_names
  1465. assert diff == set(), \
  1466. "Some params not instantiated in param init net: {}".format(diff)
  1467. # Remove duplicates and sort
  1468. prefixlen = len(model._device_prefix) + 1
  1469. def extract_sort_key(b):
  1470. # Sort first based on device id, and then by whole string
  1471. deviceid = int(b[prefixlen:b.index(scope._NAMESCOPE_SEPARATOR)])
  1472. return (deviceid, b)
  1473. blobs_to_sync = sorted(
  1474. list(set(blobs_to_sync)),
  1475. key=extract_sort_key)
  1476. blobs_to_sync = [core.BlobReference(b) for b in blobs_to_sync]
  1477. return (blobs_to_sync, sync_names)
  1478. def _OptimizeGradientMemorySimple(model, losses_by_gpu, devices):
  1479. log.warning("------- DEPRECATED API, please use " +
  1480. "data_parallel_model.OptimizeGradientMemory() ----- ")
  1481. for device in devices:
  1482. namescope = "{}_{}/".format(model._device_prefix, device)
  1483. model.net._net = memonger.share_grad_blobs(
  1484. model.net,
  1485. losses_by_gpu[device],
  1486. set(viewvalues(model.param_to_grad)),
  1487. namescope,
  1488. share_activations=False,
  1489. )
  1490. def _AddDynamicMemoryOptimization(model, blobs_to_keep, devices):
  1491. blobs_to_keep_all_devices = set()
  1492. if blobs_to_keep is not None:
  1493. for device in devices:
  1494. for blob_name in blobs_to_keep:
  1495. blobs_to_keep_all_devices.add(
  1496. "{}_{}/{}".format(model._device_prefix, device, blob_name)
  1497. )
  1498. if model._rendezvous is not None:
  1499. # GLOO operators expect the tensor addresses to remain same over
  1500. # iterations so we need to remove param grads from the dynamic memory
  1501. # management.
  1502. blobs_to_keep_all_devices.update(
  1503. [str(b) for b in viewvalues(model.param_to_grad)]
  1504. )
  1505. model.net._net = memonger.release_blobs_when_used(
  1506. model.net.Proto(),
  1507. blobs_to_keep_all_devices
  1508. )
  1509. def OptimizeGradientMemory(model,
  1510. input_shapes,
  1511. excluded_blobs,
  1512. recycle_activations):
  1513. """
  1514. Optimize memory usage of the backward pass by recycling blobs for gradient
  1515. inputs that have been 'used'.
  1516. input_shapes: dict of blob name to shape for the inputs of the model.
  1517. Pass empty dictionary if not known.
  1518. excluded_blobs: list of blobs that cannot be recycled. These are blobs
  1519. that you will access externally.
  1520. recycle_activations: whether to also recycle forward pass activations
  1521. """
  1522. if input_shapes is not None:
  1523. input_shapes_all_devices = {}
  1524. for b, shp in viewitems(input_shapes):
  1525. for d in model._devices:
  1526. input_shapes_all_devices["{}_{}/{}".
  1527. format(model._device_prefix, d, b)] = shp
  1528. (shapes, types) = workspace.InferShapesAndTypes(
  1529. [model.param_init_net, model.net],
  1530. input_shapes_all_devices,
  1531. )
  1532. else:
  1533. shapes = None
  1534. for device in model._devices:
  1535. namescope = "{}_{}/".format(model._device_prefix, device)
  1536. excluded_blobs_by_device = set(namescope + b for b in excluded_blobs)
  1537. model.net._net = memonger.share_grad_blobs(
  1538. model.net,
  1539. model._losses_by_gpu[device],
  1540. set(viewvalues(model.param_to_grad)),
  1541. namescope,
  1542. dont_share_blobs=excluded_blobs_by_device,
  1543. share_activations=recycle_activations,
  1544. blob_shapes=shapes,
  1545. )
  1546. def _CreateOrCloneCommonWorld(
  1547. net,
  1548. common_world_blob,
  1549. rendezvous,
  1550. name=None,
  1551. timeout_sec=None):
  1552. if timeout_sec is None:
  1553. timeout_sec = _DEFAULT_TIMEOUT_SEC
  1554. timeout_ms = timeout_sec * 1000
  1555. # Check if there is an existing CreateCommonWorld
  1556. # with the same timeout we're looking for. If so,
  1557. # we can clone it instead of creating a new one.
  1558. existing = None
  1559. for op in net.Proto().op:
  1560. if op.type != "CreateCommonWorld":
  1561. continue
  1562. # Find common world timeout
  1563. op_timeout_ms = -1
  1564. for arg in op.arg:
  1565. if arg.name == 'timeout_ms':
  1566. op_timeout_ms = arg.i
  1567. break
  1568. if op_timeout_ms != timeout_ms:
  1569. continue
  1570. # This common world was created with the same timeout we're
  1571. # looking for, so we can clone it
  1572. existing = op.output[0]
  1573. break
  1574. if name is None:
  1575. name = "{}_op".format(common_world_blob)
  1576. if existing is not None:
  1577. comm_world = net.CloneCommonWorld(
  1578. [existing],
  1579. common_world_blob,
  1580. name=name,
  1581. engine=rendezvous['engine'],
  1582. )
  1583. else:
  1584. kwargs=dict()
  1585. if 'transport' in rendezvous:
  1586. kwargs['transport'] = rendezvous['transport']
  1587. if 'interface' in rendezvous:
  1588. kwargs['interface'] = rendezvous['interface']
  1589. if 'mpi_rendezvous' in rendezvous:
  1590. kwargs['mpi_rendezvous'] = rendezvous['mpi_rendezvous']
  1591. comm_world = net.CreateCommonWorld(
  1592. rendezvous['kv_handler'] or [],
  1593. common_world_blob,
  1594. name=name,
  1595. size=rendezvous['num_shards'],
  1596. rank=rendezvous['shard_id'],
  1597. engine=rendezvous['engine'],
  1598. timeout_ms=timeout_ms,
  1599. **kwargs
  1600. )
  1601. return comm_world
  1602. def _RunComparison(model, blob_name, device=None):
  1603. if device is None:
  1604. device = model._blob_to_device[blob_name]
  1605. with core.DeviceScope(device):
  1606. rendezvous = model._rendezvous
  1607. if rendezvous is None or rendezvous['num_shards'] == 1:
  1608. return True
  1609. test_data_arr = np.zeros(rendezvous['num_shards']).astype(np.float32)
  1610. test_data_arr[rendezvous['shard_id']] = 1
  1611. workspace.FeedBlob("compare_arr", test_data_arr)
  1612. comparison_net = core.Net("allcompare_net")
  1613. kwargs=dict()
  1614. if 'mpi_rendezvous' in rendezvous:
  1615. kwargs['mpi_rendezvous'] = rendezvous['mpi_rendezvous']
  1616. comm_world = comparison_net.CreateCommonWorld(
  1617. rendezvous['kv_handler'] or [],
  1618. "initial_sync",
  1619. name=model.net.Proto().name + ".cw_master_select",
  1620. size=rendezvous['num_shards'],
  1621. rank=rendezvous['shard_id'],
  1622. engine=rendezvous['engine'],
  1623. **kwargs
  1624. )
  1625. blob_name_checksum = blob_name + "_checksum"
  1626. comparison_net.SumSqrElements(
  1627. [blob_name], [blob_name_checksum], average=False
  1628. )
  1629. blob_name_gather = blob_name + "_gather"
  1630. comparison_net.Mul(
  1631. inputs=["compare_arr", blob_name_checksum],
  1632. outputs=blob_name_gather,
  1633. broadcast=1
  1634. )
  1635. comparison_net.Allreduce(
  1636. inputs=[comm_world, blob_name_gather],
  1637. outputs=[blob_name_gather],
  1638. engine=rendezvous['engine'],
  1639. )
  1640. workspace.RunNetOnce(comparison_net)
  1641. gather_arr = workspace.FetchBlob(blob_name_gather)
  1642. baseline = gather_arr[0]
  1643. for i in range(rendezvous['num_shards']):
  1644. assert gather_arr[i] == baseline, \
  1645. "allcompare failed on shard {}.".format(rendezvous['shard_id'])
  1646. return True
  1647. def _InterleaveOps(model):
  1648. '''
  1649. Data Parallel Model creates a net with ops in one device grouped together.
  1650. This will interleave the ops so that each op for each device is next
  1651. to each other in the net. Kind of like combining decks of cards. This
  1652. ensures that progress is made along the critical path roughly concurrently
  1653. for each device, which is important due to the extra intra-node
  1654. synchronization required for multi-device batch normalization.
  1655. '''
  1656. orig_ops = list(model.net.Proto().op)
  1657. num_devices = len(model._devices)
  1658. num_ops_per_dev = len(orig_ops) // num_devices
  1659. assert num_devices * num_ops_per_dev == len(orig_ops), \
  1660. 'Number of ops per device in original net is not uniform'
  1661. new_ops = []
  1662. ops = {d: [] for d in range(num_devices)}
  1663. for op in orig_ops:
  1664. ops[op.device_option.device_id].append(op)
  1665. for j in range(num_ops_per_dev):
  1666. tp = None
  1667. for d in model._devices:
  1668. if tp is None:
  1669. tp = ops[d][j].type
  1670. new_ops.append(ops[d][j])
  1671. # Sanity
  1672. assert ops[d][j].type == tp, \
  1673. "Type mismatch {} / {}".format(tp, ops[d][j].type)
  1674. del model.net.Proto().op[:]
  1675. model.net.Proto().op.extend(new_ops)
  1676. def _CPUInterDeviceBatchNormalization(model):
  1677. orig_ops = list(model.net.Proto().op)
  1678. new_ops = []
  1679. num_devices = len(model._devices)
  1680. batch_norm_ops = []
  1681. injected_ops = []
  1682. spatial_bn_phase = False
  1683. sums_blobs = []
  1684. sumsq_blobs = []
  1685. name = []
  1686. input_blob_name = None
  1687. spatial_bn_gradient_phase = False
  1688. scale_grad_blobs = []
  1689. bias_grad_blobs = []
  1690. def _cpuReduce(param, input_blobs, destination_blobs):
  1691. """
  1692. Reduce results from multiple cpus and distributes the results back
  1693. to each device. This is done by copying values to cpu_0 and summing
  1694. them. The cpu_0 result is then copied back to each of the devices.
  1695. param: the name of the data (blobs) to reduce
  1696. input_blobs: the list of blobs to reduce
  1697. destination_blobs: list of blobs to copy the result to
  1698. """
  1699. added_ops = []
  1700. result_blob = "cpu_0/" + param + "_combined"
  1701. added_ops.append(core.CreateOperator("Sum", input_blobs, result_blob))
  1702. for blob in destination_blobs:
  1703. added_ops.append(core.CreateOperator("Copy", result_blob, blob))
  1704. return added_ops
  1705. for op in orig_ops:
  1706. if op.type != 'SpatialBN' and op.type != 'SpatialBNGradient':
  1707. if spatial_bn_phase:
  1708. new_ops.extend(injected_ops)
  1709. new_ops.append(
  1710. core.CreateOperator("Sum",
  1711. sums_blobs,
  1712. input_blob_name + "_sums_combined"))
  1713. new_ops.append(
  1714. core.CreateOperator("Sum",
  1715. sumsq_blobs,
  1716. input_blob_name + "_sumsq_combined"))
  1717. new_ops.extend(batch_norm_ops)
  1718. injected_ops = []
  1719. batch_norm_ops = []
  1720. sums_blobs = []
  1721. sumsq_blobs = []
  1722. spatial_bn_phase = False
  1723. input_blob_name = None
  1724. elif spatial_bn_gradient_phase:
  1725. new_ops.extend(injected_ops)
  1726. new_ops.extend(_cpuReduce(
  1727. stripBlobName(scale_grad_blobs[0]),
  1728. scale_grad_blobs,
  1729. scale_grad_blobs))
  1730. new_ops.extend(_cpuReduce(
  1731. stripBlobName(bias_grad_blobs[0]),
  1732. bias_grad_blobs,
  1733. bias_grad_blobs))
  1734. new_ops.extend(batch_norm_ops)
  1735. injected_ops = []
  1736. batch_norm_ops = []
  1737. scale_grad_blobs = []
  1738. bias_grad_blobs = []
  1739. spatial_bn_gradient_phase = False
  1740. new_ops.append(op)
  1741. elif op.type == 'SpatialBN':
  1742. spatial_bn_phase = True
  1743. if input_blob_name is None:
  1744. input_blob_name = op.input[0]
  1745. name = op.input[0]
  1746. injected_ops.append(
  1747. core.CreateOperator(
  1748. "ChannelStats",
  1749. name,
  1750. [name + "_sums", name + "_sumsq"]))
  1751. sums_blobs.append(name + "_sums")
  1752. sumsq_blobs.append(name + "_sumsq")
  1753. op.input.append(input_blob_name + "_sums_combined")
  1754. op.input.append(input_blob_name + "_sumsq_combined")
  1755. op.arg.extend([utils.MakeArgument("num_batches", num_devices)])
  1756. batch_norm_ops.append(op)
  1757. elif op.type == 'SpatialBNGradient':
  1758. spatial_bn_gradient_phase = True
  1759. injected_ops.append(
  1760. core.CreateOperator("ChannelBackpropStats",
  1761. [op.input[0], op.input[3], op.input[4],
  1762. op.input[2]],
  1763. [op.output[1], op.output[2]]))
  1764. scale_grad_blobs.append(op.output[1])
  1765. bias_grad_blobs.append(op.output[2])
  1766. op.arg.extend([utils.MakeArgument("num_batches", num_devices)])
  1767. op.input.extend([op.output[1], op.output[2]])
  1768. batch_norm_ops.append(op)
  1769. assert not spatial_bn_phase, \
  1770. "Net modification for cpu inter-device batch normalization failed"
  1771. del model.net.Proto().op[:]
  1772. model.net.Proto().op.extend(new_ops)
  1773. def _GPUInterDeviceBatchNormalization(model):
  1774. orig_ops = list(model.net.Proto().op)
  1775. new_ops = []
  1776. num_devices = len(model._devices)
  1777. batch_norm_ops = []
  1778. injected_ops = []
  1779. spatial_bn_phase = False
  1780. sums_blobs = []
  1781. sumsq_blobs = []
  1782. name = []
  1783. input_blob_name = None
  1784. spatial_bn_gradient_phase = False
  1785. scale_grad_blobs = []
  1786. bias_grad_blobs = []
  1787. master_device = "cpu_0"
  1788. master_device_option = core.DeviceOption(caffe2_pb2.CPU)
  1789. def _gpuReduce(param, num_devices, master_device, result_blobs=None):
  1790. """
  1791. Reduces results from multiple gpus and distributes the results back
  1792. to each device. This is done by copying values to the master device
  1793. and summing them. The master device result is then copied back to
  1794. each of the devices.
  1795. param: the name of the data (blobs) to reduce
  1796. num_devices: the number of devices
  1797. master_device: the device to copy/compute values on
  1798. result_blobs: optional list of result blobs to copy to
  1799. """
  1800. added_ops = []
  1801. source_blobs = []
  1802. destination_blobs = []
  1803. if result_blobs is None:
  1804. result_blobs = [
  1805. "gpu_{}/{}_combined".format(i, param) for i in range(num_devices)
  1806. ]
  1807. for i in range(num_devices):
  1808. device_option = core.DeviceOption(model._device_type, i)
  1809. source_blobs.append("gpu_{}/{}".format(i, param))
  1810. destination_blobs.append(
  1811. "{}/{}_gpu_{}_copy".format(master_device, param, i))
  1812. added_ops.append(
  1813. core.CreateOperator(
  1814. "CopyGPUToCPU",
  1815. source_blobs[i],
  1816. destination_blobs[i],
  1817. device_option=device_option))
  1818. added_ops.append(
  1819. core.CreateOperator(
  1820. "Sum",
  1821. destination_blobs,
  1822. "{}/{}_combined".format(master_device, param),
  1823. device_option=master_device_option))
  1824. for i in range(num_devices):
  1825. device_option = core.DeviceOption(model._device_type, i)
  1826. added_ops.append(
  1827. core.CreateOperator(
  1828. "CopyCPUToGPU",
  1829. "{}/{}_combined".format(master_device, param),
  1830. result_blobs[i],
  1831. device_option=device_option))
  1832. return added_ops
  1833. for op in orig_ops:
  1834. if op.type != 'SpatialBN' and op.type != 'SpatialBNGradient':
  1835. if spatial_bn_phase:
  1836. new_ops.extend(injected_ops)
  1837. new_ops.extend(_gpuReduce(
  1838. stripBlobName(input_blob_name) + "_sums",
  1839. num_devices,
  1840. master_device,
  1841. ))
  1842. new_ops.extend(_gpuReduce(
  1843. stripBlobName(input_blob_name) + "_sumsq",
  1844. num_devices,
  1845. master_device,
  1846. ))
  1847. new_ops.extend(batch_norm_ops)
  1848. injected_ops = []
  1849. batch_norm_ops = []
  1850. sums_blobs = []
  1851. sumsq_blobs = []
  1852. spatial_bn_phase = False
  1853. input_blob_name = None
  1854. elif spatial_bn_gradient_phase:
  1855. new_ops.extend(injected_ops)
  1856. new_ops.extend(_gpuReduce(
  1857. stripBlobName(scale_grad_blobs[0]),
  1858. num_devices,
  1859. master_device,
  1860. scale_grad_blobs,
  1861. ))
  1862. new_ops.extend(_gpuReduce(
  1863. stripBlobName(bias_grad_blobs[0]),
  1864. num_devices,
  1865. master_device,
  1866. bias_grad_blobs,
  1867. ))
  1868. new_ops.extend(batch_norm_ops)
  1869. injected_ops = []
  1870. batch_norm_ops = []
  1871. scale_grad_blobs = []
  1872. bias_grad_blobs = []
  1873. spatial_bn_gradient_phase = False
  1874. new_ops.append(op)
  1875. elif op.type == 'SpatialBN':
  1876. spatial_bn_phase = True
  1877. if input_blob_name is None:
  1878. input_blob_name = op.input[0]
  1879. name = op.input[0]
  1880. device_option = core.DeviceOption(
  1881. model._device_type,
  1882. op.device_option.device_id,
  1883. )
  1884. injected_ops.append(
  1885. core.CreateOperator(
  1886. "ChannelStats",
  1887. name,
  1888. [name + "_sums", name + "_sumsq"],
  1889. device_option=device_option))
  1890. sums_blobs.append(name + "_sums")
  1891. sumsq_blobs.append(name + "_sumsq")
  1892. op.input.append(name + "_sums_combined")
  1893. op.input.append(name + "_sumsq_combined")
  1894. op.arg.extend([utils.MakeArgument("num_batches", num_devices)])
  1895. batch_norm_ops.append(op)
  1896. elif op.type == 'SpatialBNGradient':
  1897. spatial_bn_gradient_phase = True
  1898. device_option = core.DeviceOption(
  1899. model._device_type,
  1900. op.device_option.device_id,
  1901. )
  1902. injected_ops.append(
  1903. core.CreateOperator("ChannelBackpropStats",
  1904. [op.input[0], op.input[3], op.input[4],
  1905. op.input[2]],
  1906. [op.output[1], op.output[2]],
  1907. device_option=device_option))
  1908. scale_grad_blobs.append(op.output[1])
  1909. bias_grad_blobs.append(op.output[2])
  1910. op.arg.extend([utils.MakeArgument("num_batches", num_devices)])
  1911. op.input.extend([op.output[1], op.output[2]])
  1912. batch_norm_ops.append(op)
  1913. assert not spatial_bn_phase, \
  1914. "Net modification for gpu inter-device batch normalization failed"
  1915. del model.net.Proto().op[:]
  1916. model.net.Proto().op.extend(new_ops)