-
Notifications
You must be signed in to change notification settings - Fork 203
/
snresnet.py
74 lines (68 loc) · 3.15 KB
/
snresnet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import chainer
from chainer import functions as F
from source.links.sn_embed_id import SNEmbedID
from source.links.sn_linear import SNLinear
from dis_models.resblocks import Block, OptimizedBlock
class SNResNetProjectionDiscriminator(chainer.Chain):
def __init__(self, ch=64, n_classes=0, activation=F.relu):
super(SNResNetProjectionDiscriminator, self).__init__()
self.activation = activation
initializer = chainer.initializers.GlorotUniform()
with self.init_scope():
self.block1 = OptimizedBlock(3, ch)
self.block2 = Block(ch, ch * 2, activation=activation, downsample=True)
self.block3 = Block(ch * 2, ch * 4, activation=activation, downsample=True)
self.block4 = Block(ch * 4, ch * 8, activation=activation, downsample=True)
self.block5 = Block(ch * 8, ch * 16, activation=activation, downsample=True)
self.block6 = Block(ch * 16, ch * 16, activation=activation, downsample=False)
self.l7 = SNLinear(ch * 16, 1, initialW=initializer)
if n_classes > 0:
self.l_y = SNEmbedID(n_classes, ch * 16, initialW=initializer)
def __call__(self, x, y=None):
h = x
h = self.block1(h)
h = self.block2(h)
h = self.block3(h)
h = self.block4(h)
h = self.block5(h)
h = self.block6(h)
h = self.activation(h)
h = F.sum(h, axis=(2, 3)) # Global pooling
output = self.l7(h)
if y is not None:
w_y = self.l_y(y)
output += F.sum(w_y * h, axis=1, keepdims=True)
return output
class SNResNetConcatDiscriminator(chainer.Chain):
def __init__(self, ch=64, n_classes=0, activation=F.relu, dim_emb=128):
super(SNResNetConcatDiscriminator, self).__init__()
self.activation = activation
initializer = chainer.initializers.GlorotUniform()
with self.init_scope():
self.block1 = OptimizedBlock(3, ch)
self.block2 = Block(ch, ch * 2, activation=activation, downsample=True)
self.block3 = Block(ch * 2, ch * 4, activation=activation, downsample=True)
self.l_y = SNEmbedID(n_classes, dim_emb, initialW=initializer)
self.block4 = Block(ch * 4 + dim_emb, ch * 8, activation=activation, downsample=True)
self.block5 = Block(ch * 8, ch * 16, activation=activation, downsample=True)
self.block6 = Block(ch * 16, ch * 16, activation=activation, downsample=False)
self.l7 = SNLinear(ch * 16, 1, initialW=initializer)
def __call__(self, x, y=None):
h = x
h = self.block1(h)
h = self.block2(h)
h = self.block3(h)
if y is not None:
emb = self.l_y(y)
H, W = h.shape[2], h.shape[3]
emb = F.broadcast_to(
F.reshape(emb, (emb.shape[0], emb.shape[1], 1, 1)),
(emb.shape[0], emb.shape[1], H, W))
h = F.concat([h, emb], axis=1)
h = self.block4(h)
h = self.block5(h)
h = self.block6(h)
h = self.activation(h)
h = F.sum(h, axis=(2, 3)) # Global pooling
output = self.l7(h)
return output