-
Notifications
You must be signed in to change notification settings - Fork 35
/
dcgan.go
198 lines (171 loc) · 5.97 KB
/
dcgan.go
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package main
import (
"flag"
"fmt"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"log"
"reflect"
"strings"
"time"
torch "github.com/wangkuiyi/gotorch"
nn "github.com/wangkuiyi/gotorch/nn"
F "github.com/wangkuiyi/gotorch/nn/functional"
"github.com/wangkuiyi/gotorch/nn/initializer"
"github.com/wangkuiyi/gotorch/vision/imageloader"
"github.com/wangkuiyi/gotorch/vision/transforms"
)
var data = flag.String("data", "", "path to dataset")
var device torch.Device
func weightInit(m nn.IModule) {
if strings.Contains(m.Name(), "Conv") {
fv := reflect.ValueOf(m.(*nn.Module).Outer()).Elem()
for i := 0; i < fv.NumField(); i++ {
v := fv.Field(i)
f := fv.Type().Field(i)
if f.Name == "Weight" {
w := v.Interface().(torch.Tensor)
initializer.Normal(&w, 0.0, 0.02)
}
}
} else if strings.Contains(m.Name(), "BatchNorm") {
fv := reflect.ValueOf(m.(*nn.Module).Outer()).Elem()
for i := 0; i < fv.NumField(); i++ {
v := fv.Field(i)
f := fv.Type().Field(i)
if f.Name == "Weight" {
w := v.Interface().(torch.Tensor)
initializer.Normal(&w, 1.0, 0.02)
} else if f.Name == "Bias" {
w := v.Interface().(torch.Tensor)
initializer.Zeros(&w)
}
}
}
}
func generator(nz int64, nc int64, ngf int64) *nn.SequentialModule {
return nn.Sequential(
nn.ConvTranspose2d(nz, ngf*8, 4, 1, 0, 0, 1, false, 1, "zero"),
nn.BatchNorm2d(ngf*8, 1e-5, 0.1, true, true),
nn.Functional(func(in torch.Tensor) torch.Tensor { return F.Relu(in, true) }),
nn.ConvTranspose2d(ngf*8, ngf*4, 4, 2, 1, 0, 1, false, 1, "zero"),
nn.BatchNorm2d(ngf*4, 1e-5, 0.1, true, true),
nn.Functional(func(in torch.Tensor) torch.Tensor { return F.Relu(in, true) }),
nn.ConvTranspose2d(ngf*4, ngf*2, 4, 2, 1, 0, 1, false, 1, "zero"),
nn.BatchNorm2d(ngf*2, 1e-5, 0.1, true, true),
nn.Functional(func(in torch.Tensor) torch.Tensor { return F.Relu(in, true) }),
nn.ConvTranspose2d(ngf*2, ngf, 4, 2, 1, 0, 1, false, 1, "zero"),
nn.BatchNorm2d(ngf, 1e-5, 0.1, true, true),
nn.Functional(func(in torch.Tensor) torch.Tensor { return F.Relu(in, true) }),
nn.ConvTranspose2d(ngf, nc, 4, 2, 1, 0, 1, false, 1, "zero"),
nn.Functional(torch.Tanh),
)
}
func discriminator(nc int64, ndf int64) *nn.SequentialModule {
return nn.Sequential(
nn.Conv2d(nc, ndf, 4, 2, 1, 1, 1, false, "zeros"),
nn.Functional(func(in torch.Tensor) torch.Tensor { return F.LeakyRelu(in, 0.2, true) }),
nn.Conv2d(ndf, ndf*2, 4, 2, 1, 1, 1, false, "zeros"),
nn.BatchNorm2d(ndf*2, 1e-5, 0.1, true, true),
nn.Functional(func(in torch.Tensor) torch.Tensor { return F.LeakyRelu(in, 0.2, true) }),
nn.Conv2d(ndf*2, ndf*4, 4, 2, 1, 1, 1, false, "zeros"),
nn.BatchNorm2d(ndf*4, 1e-5, 0.1, true, true),
nn.Functional(func(in torch.Tensor) torch.Tensor { return F.LeakyRelu(in, 0.2, true) }),
nn.Conv2d(ndf*4, ndf*8, 4, 2, 1, 1, 1, false, "zeros"),
nn.BatchNorm2d(ndf*8, 1e-5, 0.1, true, true),
nn.Functional(func(in torch.Tensor) torch.Tensor { return F.LeakyRelu(in, 0.2, true) }),
nn.Conv2d(ndf*8, 1, 4, 1, 0, 1, 1, false, "zeros"),
nn.Functional(torch.Sigmoid),
)
}
func celebaLoader(data string, vocab map[string]int, mbSize int) *imageloader.ImageLoader {
imageSize := 64
trans := transforms.Compose(transforms.Resize(imageSize),
transforms.CenterCrop(imageSize),
transforms.ToTensor(),
transforms.Normalize([]float32{0.5, 0.5, 0.5}, []float32{0.5, 0.5, 0.5}))
loader, e := imageloader.New(data, vocab, trans, mbSize, mbSize*2, time.Now().UnixNano(), torch.IsCUDAAvailable(), "rgb")
if e != nil {
panic(e)
}
return loader
}
func main() {
flag.Parse()
if torch.IsCUDAAvailable() {
log.Println("CUDA is valid")
device = torch.NewDevice("cuda")
} else {
log.Println("No CUDA found; CPU only")
device = torch.NewDevice("cpu")
}
initializer.ManualSeed(999)
nc := int64(3)
nz := int64(100)
ngf := int64(64)
ndf := int64(64)
lr := 0.0002
epochs := 15
checkpointStep := 500
batchSize := 128
fixedNoise := torch.RandN([]int64{64, nz, 1, 1}, false).CopyTo(device)
netG := generator(nz, nc, ngf)
netG.To(device)
netG.Apply(weightInit)
netD := discriminator(nc, ndf)
netD.To(device)
netD.Apply(weightInit)
optimizerD := torch.Adam(lr, 0.5, 0.999, 0.0)
optimizerD.AddParameters(netD.Parameters())
optimizerG := torch.Adam(lr, 0.5, 0.999, 0.0)
optimizerG.AddParameters(netG.Parameters())
vocab, e := imageloader.BuildLabelVocabularyFromTgz(*data)
if e != nil {
log.Fatal(e)
}
i := 0
for epoch := 0; epoch < epochs; epoch++ {
trainLoader := celebaLoader(*data, vocab, batchSize)
for trainLoader.Scan() {
// (1) update D network
// train with real
optimizerD.ZeroGrad()
data, _ := trainLoader.Minibatch()
data = data.CopyTo(device)
label := torch.Empty([]int64{data.Shape()[0]}, false).CopyTo(device)
initializer.Ones(&label)
output := netD.Forward(data).(torch.Tensor).View(-1, 1).Squeeze(1)
errDReal := F.BinaryCrossEntropy(output, label, torch.Tensor{}, "mean")
errDReal.Backward()
// train with fake
noise := torch.RandN([]int64{data.Shape()[0], nz, 1, 1}, false).CopyTo(device)
fake := netG.Forward(noise).(torch.Tensor)
initializer.Zeros(&label)
output = netD.Forward(fake.Detach()).(torch.Tensor).View(-1, 1).Squeeze(1)
errDFake := F.BinaryCrossEntropy(output, label, torch.Tensor{}, "mean")
errDFake.Backward()
errD := errDReal.Item().(float32) + errDFake.Item().(float32)
optimizerD.Step()
// (2) update G network
optimizerG.ZeroGrad()
initializer.Ones(&label)
output = netD.Forward(fake).(torch.Tensor).View(-1, 1).Squeeze(1)
errG := F.BinaryCrossEntropy(output, label, torch.Tensor{}, "mean")
errG.Backward()
optimizerG.Step()
log.Printf("\t Epoch: %04d/%05d \t Step: %05d \t Loss_D: %2.4f \t Loss_G: %2.4f \n",
epoch, epochs, i, errD, errG.Item())
if i%checkpointStep == 0 {
samples := netG.Forward(fixedNoise).(torch.Tensor)
ckName := fmt.Sprintf("gotorch-dcgan-sample-%d.pt", i)
samples.Detach().Save(ckName)
}
i++
}
if e := trainLoader.Err(); e != nil {
log.Fatal(e)
}
}
torch.FinishGC()
}