Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
POSTECH-CVLab
GitHub Repository: POSTECH-CVLab/PyTorch-StudioGAN
Path: blob/master/src/sync_batchnorm/replicate.py
809 views
1
"""
2
-*- coding: utf-8 -*-
3
File : replicate.py
4
Author : Jiayuan Mao
5
Email : [email protected]
6
Date : 27/01/2018
7
8
This file is part of Synchronized-BatchNorm-PyTorch.
9
https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
10
Distributed under MIT License.
11
12
MIT License
13
14
Copyright (c) 2018 Jiayuan MAO
15
16
Permission is hereby granted, free of charge, to any person obtaining a copy
17
of this software and associated documentation files (the "Software"), to deal
18
in the Software without restriction, including without limitation the rights
19
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20
copies of the Software, and to permit persons to whom the Software is
21
furnished to do so, subject to the following conditions:
22
23
The above copyright notice and this permission notice shall be included in all
24
copies or substantial portions of the Software.
25
26
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32
SOFTWARE.
33
"""
34
35
import functools
36
37
from torch.nn.parallel.data_parallel import DataParallel
38
39
__all__ = ['CallbackContext', 'execute_replication_callbacks', 'DataParallelWithCallback', 'patch_replication_callback']
40
41
42
class CallbackContext(object):
43
pass
44
45
46
def execute_replication_callbacks(modules):
47
"""
48
Execute an replication callback `__data_parallel_replicate__` on each module created by original replication.
49
50
The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)`
51
52
Note that, as all modules are isomorphism, we assign each sub-module with a context
53
(shared among multiple copies of this module on different devices).
54
Through this context, different copies can share some information.
55
56
We guarantee that the callback on the master copy (the first copy) will be called ahead of calling the callback
57
of any slave copies.
58
"""
59
master_copy = modules[0]
60
nr_modules = len(list(master_copy.modules()))
61
ctxs = [CallbackContext() for _ in range(nr_modules)]
62
63
for i, module in enumerate(modules):
64
for j, m in enumerate(module.modules()):
65
if hasattr(m, '__data_parallel_replicate__'):
66
m.__data_parallel_replicate__(ctxs[j], i)
67
68
69
class DataParallelWithCallback(DataParallel):
70
"""
71
Data Parallel with a replication callback.
72
73
An replication callback `__data_parallel_replicate__` of each module will be invoked after being created by
74
original `replicate` function.
75
The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)`
76
77
Examples:
78
> sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False)
79
> sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1])
80
# sync_bn.__data_parallel_replicate__ will be invoked.
81
"""
82
def replicate(self, module, device_ids):
83
modules = super(DataParallelWithCallback, self).replicate(module, device_ids)
84
execute_replication_callbacks(modules)
85
return modules
86
87
88
def patch_replication_callback(data_parallel):
89
"""
90
Monkey-patch an existing `DataParallel` object. Add the replication callback.
91
Useful when you have customized `DataParallel` implementation.
92
93
Examples:
94
> sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False)
95
> sync_bn = DataParallel(sync_bn, device_ids=[0, 1])
96
> patch_replication_callback(sync_bn)
97
# this is equivalent to
98
> sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False)
99
> sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1])
100
"""
101
102
assert isinstance(data_parallel, DataParallel)
103
104
old_replicate = data_parallel.replicate
105
106
@functools.wraps(old_replicate)
107
def new_replicate(module, device_ids):
108
modules = old_replicate(module, device_ids)
109
execute_replication_callbacks(modules)
110
return modules
111
112
data_parallel.replicate = new_replicate
113
114