Skip to content

Commit 011aa1e

Browse files
committed
Use forward() instead of __call__()
1 parent ec243b9 commit 011aa1e

File tree

6 files changed

+28
-22
lines changed

6 files changed

+28
-22
lines changed

dezero/layers.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
import weakref
23
import numpy as np
34
import dezero.functions as F
45
from dezero import cuda
@@ -18,11 +19,16 @@ def __setattr__(self, name, value):
1819
self._params.add(name)
1920
super().__setattr__(name, value)
2021

21-
def __call__(self, *args, **kwargs):
22-
return self.forward(*args, **kwargs)
22+
def __call__(self, *inputs):
23+
outputs = self.forward(*inputs)
24+
if not isinstance(outputs, tuple):
25+
outputs = (outputs,)
26+
self.inputs = [weakref.ref(x) for x in inputs]
27+
self.outputs = [weakref.ref(y) for y in outputs]
28+
return outputs if len(outputs) > 1 else outputs[0]
2329

24-
def forward(self, *args, **kwargs):
25-
return self.__call__(*args, **kwargs)
30+
def forward(self, inputs):
31+
raise NotImplementedError()
2632

2733
def params(self):
2834
for name in self._params:
@@ -101,7 +107,7 @@ def _init_W(self, xp=np):
101107
W_data = xp.random.randn(I, O).astype(self.dtype) * np.sqrt(1 / I)
102108
self.W.data = W_data
103109

104-
def __call__(self, x):
110+
def forward(self, x):
105111
if self.W.data is None:
106112
self.in_size = x.shape[1]
107113
xp = cuda.get_array_module(x)
@@ -150,7 +156,7 @@ def _init_W(self, xp=np):
150156
W_data = xp.random.randn(OC, C, KH, KW).astype(self.dtype) * scale
151157
self.W.data = W_data
152158

153-
def __call__(self, x):
159+
def forward(self, x):
154160
if self.W.data is None:
155161
self.in_channels = x.shape[1]
156162
xp = cuda.get_array_module(x)
@@ -199,7 +205,7 @@ def _init_W(self, xp=np):
199205
W_data = xp.random.randn(C, OC, KH, KW).astype(self.dtype) * scale
200206
self.W.data = W_data
201207

202-
def __call__(self, x):
208+
def forward(self, x):
203209
if self.W.data is None:
204210
self.in_channels = x.shape[1]
205211
xp = cuda.get_array_module(x)
@@ -231,7 +237,7 @@ def __init__(self, hidden_size, in_size=None):
231237
def reset_state(self):
232238
self.h = None
233239

234-
def __call__(self, x):
240+
def forward(self, x):
235241
if self.h is None:
236242
h_new = F.tanh(self.x2h(x))
237243
else:
@@ -259,7 +265,7 @@ def reset_state(self):
259265
self.h = None
260266
self.c = None
261267

262-
def __call__(self, x):
268+
def forward(self, x):
263269
if self.h is None:
264270
f = F.sigmoid(self.x2f(x))
265271
i = F.sigmoid(self.x2i(x))

dezero/models.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
# =============================================================================
1212
class Model(Layer):
1313
def plot(self, *inputs, to_file='model.png'):
14-
y = self.__call__(*inputs)
14+
y = self.forward(*inputs)
1515
return utils.plot_dot_graph(y, verbose=True, to_file=to_file)
1616

1717

@@ -23,7 +23,7 @@ def __init__(self, *layers):
2323
setattr(self, 'l' + str(i), layer)
2424
self.layers.append(layer)
2525

26-
def __call__(self, x):
26+
def forward(self, x):
2727
for layer in self.layers:
2828
x = layer(x)
2929
return x
@@ -40,7 +40,7 @@ def __init__(self, fc_output_sizes, activation=F.sigmoid):
4040
setattr(self, 'l' + str(i), layer)
4141
self.layers.append(layer)
4242

43-
def __call__(self, x):
43+
def forward(self, x):
4444
for l in self.layers[:-1]:
4545
x = self.activation(l(x))
4646
return self.layers[-1](x)
@@ -75,7 +75,7 @@ def __init__(self, pretrained=False):
7575
weights_path = utils.get_file(VGG16.WEIGHTS_PATH)
7676
self.load_weights(weights_path)
7777

78-
def __call__(self, x):
78+
def forward(self, x):
7979
x = F.relu(self.conv1_1(x))
8080
x = F.relu(self.conv1_2(x))
8181
x = F.pooling(x, 2, 2)
@@ -143,7 +143,7 @@ def __init__(self, n_layers=152, pretrained=False):
143143
weights_path = utils.get_file(ResNet.WEIGHTS_PATH.format(n_layers))
144144
self.load_weights(weights_path)
145145

146-
def __call__(self, x):
146+
def forward(self, x):
147147
x = F.relu(self.bn1(self.conv1(x)))
148148
x = F.pooling(x, kernel_size=3, stride=2)
149149
x = self.res2(x)
@@ -271,5 +271,5 @@ class SqueezeNet(Model):
271271
def __init__(self, pretrained=False):
272272
pass
273273

274-
def __call__(self, x):
274+
def forward(self, x):
275275
pass

dezero/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,15 +236,15 @@ def numerical_grad(f, x, *args, **kwargs):
236236
237237
Args:
238238
f (callable): A function which gets `Variable`s and returns `Variable`s.
239-
x (`ndarray` or `dezero.Variable`): A traget `Variable` for computing
239+
x (`ndarray` or `dezero.Variable`): A target `Variable` for computing
240240
the gradient.
241241
*args: If `f` needs variables except `x`, you can specify with this
242242
argument.
243243
**kwargs: If `f` needs keyword variables, you can specify with this
244244
argument.
245245
246246
Returns:
247-
`ndarray`:
247+
`ndarray`: Gradient.
248248
"""
249249
eps = 1e-4
250250

examples/spiral.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def __init__(self, hidden_size, out_size):
2525
self.l2 = L.Linear(out_size)
2626
self.bn1 = L.BatchNorm()
2727

28-
def __call__(self, x):
28+
def forward(self, x):
2929
y = F.sigmoid(self.bn1(self.l1(x)))
3030
y = self.l2(y)
3131
return y

examples/vae.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def __init__(self, latent_size):
2727
self.linear2 = L.Linear(latent_size)
2828
self.linear3 = L.Linear(latent_size)
2929

30-
def __call__(self, x):
30+
def forward(self, x):
3131
x = F.relu(self.conv1(x))
3232
x = F.relu(self.conv2(x))
3333
x = F.relu(self.conv3(x))
@@ -53,7 +53,7 @@ def __init__(self):
5353
self.deconv = L.Deconv2d(32, kernel_size=4, stride=2, pad=1)
5454
self.conv = L.Conv2d(1, kernel_size=3, stride=1, pad=1)
5555

56-
def __call__(self, x):
56+
def forward(self, x):
5757
x = F.relu(self.linear(x))
5858
x = F.reshape(x, (-1,) + self.to_shape) # reshape to (-1, C, H, W)
5959
x = F.relu(self.deconv(x))
@@ -68,7 +68,7 @@ def __init__(self, latent_size):
6868
self.encoder = Encoder(latent_size)
6969
self.decoder = Decoder()
7070

71-
def __call__(self, x, C=1.0, k=1):
71+
def forward(self, x, C=1.0, k=1):
7272
"""Call loss function of VAE.
7373
The loss value is equal to ELBO (Evidence Lower Bound)
7474
multiplied by -1.

steps/step45.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def __init__(self, hidden_size, out_size):
2323
self.l1 = L.Linear(hidden_size)
2424
self.l2 = L.Linear(out_size)
2525

26-
def __call__(self, x):
26+
def forward(self, x):
2727
y = F.sigmoid(self.l1(x))
2828
y = self.l2(y)
2929
return y

0 commit comments

Comments
 (0)