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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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
"""Collection of generative models."""

import torch as th
import ttools

import rendering
import modules

LOG = ttools.get_logger(__name__)


class BaseModel(th.nn.Module):
    def sample_z(self, bs, device="cpu"):
        return th.randn(bs, self.zdim).to(device)


class BaseVectorModel(BaseModel):
    def get_vector(self, z):
        _, scenes = self._forward(z)
        return scenes

    def _forward(self, x):
        raise NotImplementedError()

    def forward(self, z):
        # Only return the raster
        return self._forward(z)[0]


class BezierVectorGenerator(BaseVectorModel):
    NUM_SEGMENTS = 2
    def __init__(self, num_strokes=4,
                 zdim=128, width=32, imsize=32,
                 color_output=False,
                 stroke_width=None):
        super(BezierVectorGenerator, self).__init__()

        if stroke_width is None:
            self.stroke_width = (0.5, 3.0)
            LOG.warning("Setting default stroke with %s", self.stroke_width)
        else:
            self.stroke_width = stroke_width

        self.imsize = imsize
        self.num_strokes = num_strokes
        self.zdim = zdim

        self.trunk = th.nn.Sequential(
            th.nn.Linear(zdim, width),
            th.nn.SELU(inplace=True),

            th.nn.Linear(width, 2*width),
            th.nn.SELU(inplace=True),

            th.nn.Linear(2*width, 4*width),
            th.nn.SELU(inplace=True),

            th.nn.Linear(4*width, 8*width),
            th.nn.SELU(inplace=True),
        )

        # 4 points bezier with n_segments -> 3*n_segments + 1 points
        self.point_predictor = th.nn.Sequential(
            th.nn.Linear(8*width, 
                         2*self.num_strokes*(
                             BezierVectorGenerator.NUM_SEGMENTS*3 + 1)),
            th.nn.Tanh()  # bound spatial extent
        )

        self.width_predictor = th.nn.Sequential(
            th.nn.Linear(8*width, self.num_strokes),
            th.nn.Sigmoid()
        )

        self.alpha_predictor = th.nn.Sequential(
            th.nn.Linear(8*width, self.num_strokes),
            th.nn.Sigmoid()
        )

        self.color_predictor = None
        if color_output:
            self.color_predictor = th.nn.Sequential(
                th.nn.Linear(8*width, 3*self.num_strokes),
                th.nn.Sigmoid()
            )

    def _forward(self, z):
        bs = z.shape[0]

        feats = self.trunk(z)
        all_points = self.point_predictor(feats)
        all_alphas = self.alpha_predictor(feats)

        if self.color_predictor:
            all_colors = self.color_predictor(feats)
            all_colors = all_colors.view(bs, self.num_strokes, 3)
        else:
            all_colors = None

        all_widths = self.width_predictor(feats)
        min_width = self.stroke_width[0]
        max_width = self.stroke_width[1]
        all_widths = (max_width - min_width) * all_widths + min_width

        all_points = all_points.view(
            bs, self.num_strokes, BezierVectorGenerator.NUM_SEGMENTS*3+1, 2)

        output, scenes = rendering.bezier_render(all_points, all_widths, all_alphas,
                                         colors=all_colors,
                                         canvas_size=self.imsize)

        # map to [-1, 1]
        output = output*2.0 - 1.0

        return output, scenes


class VectorGenerator(BaseVectorModel):
    def __init__(self, num_strokes=4,
                 zdim=128, width=32, imsize=32,
                 color_output=False,
                 stroke_width=None):
        super(VectorGenerator, self).__init__()

        if stroke_width is None:
            self.stroke_width = (0.5, 3.0)
            LOG.warning("Setting default stroke with %s", self.stroke_width)
        else:
            self.stroke_width = stroke_width

        self.imsize = imsize
        self.num_strokes = num_strokes
        self.zdim = zdim

        self.trunk = th.nn.Sequential(
            th.nn.Linear(zdim, width),
            th.nn.SELU(inplace=True),

            th.nn.Linear(width, 2*width),
            th.nn.SELU(inplace=True),

            th.nn.Linear(2*width, 4*width),
            th.nn.SELU(inplace=True),

            th.nn.Linear(4*width, 8*width),
            th.nn.SELU(inplace=True),
        )

        # straight lines so n_segments -> n_segments - 1 points
        self.point_predictor = th.nn.Sequential(
            th.nn.Linear(8*width, 2*(self.num_strokes*2)),
            th.nn.Tanh()  # bound spatial extent
        )

        self.width_predictor = th.nn.Sequential(
            th.nn.Linear(8*width, self.num_strokes),
            th.nn.Sigmoid()
        )

        self.alpha_predictor = th.nn.Sequential(
            th.nn.Linear(8*width, self.num_strokes),
            th.nn.Sigmoid()
        )

        self.color_predictor = None
        if color_output:
            self.color_predictor = th.nn.Sequential(
                th.nn.Linear(8*width, 3*self.num_strokes),
                th.nn.Sigmoid()
            )

    def _forward(self, z):
        bs = z.shape[0]

        feats = self.trunk(z)

        all_points = self.point_predictor(feats)

        all_alphas = self.alpha_predictor(feats)

        if self.color_predictor:
            all_colors = self.color_predictor(feats)
            all_colors = all_colors.view(bs, self.num_strokes, 3)
        else:
            all_colors = None

        all_widths = self.width_predictor(feats)
        min_width = self.stroke_width[0]
        max_width = self.stroke_width[1]
        all_widths = (max_width - min_width) * all_widths + min_width

        all_points = all_points.view(bs, self.num_strokes, 2, 2)
        output, scenes = rendering.line_render(all_points, all_widths, all_alphas,
                                       colors=all_colors,
                                       canvas_size=self.imsize)

        # map to [-1, 1]
        output = output*2.0 - 1.0

        return output, scenes


class RNNVectorGenerator(BaseVectorModel):
    def __init__(self, num_strokes=64,
                 zdim=128, width=32, imsize=32,
                 hidden_size=512, dropout=0.9,
                 color_output=False,
                 num_layers=3, stroke_width=None):
        super(RNNVectorGenerator, self).__init__()


        if stroke_width is None:
            self.stroke_width = (0.5, 3.0)
            LOG.warning("Setting default stroke with %s", self.stroke_width)
        else:
            self.stroke_width = stroke_width

        self.num_layers = num_layers
        self.imsize = imsize
        self.num_strokes = num_strokes
        self.hidden_size = hidden_size
        self.zdim = zdim

        self.hidden_cell_predictor = th.nn.Linear(
            zdim, 2*hidden_size*num_layers)

        self.lstm = th.nn.LSTM(
            zdim, hidden_size,
            num_layers=self.num_layers, dropout=dropout,
            batch_first=True)

        # straight lines so n_segments -> n_segments - 1 points
        self.point_predictor = th.nn.Sequential(
            th.nn.Linear(hidden_size, 2*2),  # 2 points, (x,y)
            th.nn.Tanh()  # bound spatial extent
        )

        self.width_predictor = th.nn.Sequential(
            th.nn.Linear(hidden_size, 1),
            th.nn.Sigmoid()
        )

        self.alpha_predictor = th.nn.Sequential(
            th.nn.Linear(hidden_size, 1),
            th.nn.Sigmoid()
        )

    def _forward(self, z, hidden_and_cell=None):
        steps = self.num_strokes

        # z is passed at each step, duplicate it
        bs = z.shape[0]
        expanded_z = z.unsqueeze(1).repeat(1, steps, 1)

        # First step in the RNN
        if hidden_and_cell is None:
            # Initialize from latent vector
            hidden_and_cell = self.hidden_cell_predictor(th.tanh(z))
            hidden = hidden_and_cell[:, :self.hidden_size*self.num_layers]
            hidden = hidden.view(-1, self.num_layers, self.hidden_size)
            hidden = hidden.permute(1, 0, 2).contiguous()
            cell = hidden_and_cell[:, self.hidden_size*self.num_layers:]
            cell = cell.view(-1, self.num_layers, self.hidden_size)
            cell = cell.permute(1, 0, 2).contiguous()
            hidden_and_cell = (hidden, cell)

        feats, hidden_and_cell = self.lstm(expanded_z, hidden_and_cell)
        hidden, cell = hidden_and_cell

        feats = feats.reshape(bs*steps, self.hidden_size)

        all_points = self.point_predictor(feats).view(bs, steps, 2, 2)
        all_alphas = self.alpha_predictor(feats).view(bs, steps)
        all_widths = self.width_predictor(feats).view(bs, steps)

        min_width = self.stroke_width[0]
        max_width = self.stroke_width[1]
        all_widths = (max_width - min_width) * all_widths + min_width

        output, scenes = rendering.line_render(all_points, all_widths, all_alphas,
                                        canvas_size=self.imsize)

        # map to [-1, 1]
        output = output*2.0 - 1.0

        return output, scenes


class ChainRNNVectorGenerator(BaseVectorModel):
    """Strokes form a single long chain."""
    def __init__(self, num_strokes=64,
                 zdim=128, width=32, imsize=32,
                 hidden_size=512, dropout=0.9,
                 color_output=False,
                 num_layers=3, stroke_width=None):
        super(ChainRNNVectorGenerator, self).__init__()

        if stroke_width is None:
            self.stroke_width = (0.5, 3.0)
            LOG.warning("Setting default stroke with %s", self.stroke_width)
        else:
            self.stroke_width = stroke_width

        self.num_layers = num_layers
        self.imsize = imsize
        self.num_strokes = num_strokes
        self.hidden_size = hidden_size
        self.zdim = zdim

        self.hidden_cell_predictor = th.nn.Linear(
            zdim, 2*hidden_size*num_layers)

        self.lstm = th.nn.LSTM(
            zdim, hidden_size,
            num_layers=self.num_layers, dropout=dropout,
            batch_first=True)

        # straight lines so n_segments -> n_segments - 1 points
        self.point_predictor = th.nn.Sequential(
            th.nn.Linear(hidden_size, 2),  # 1 point, (x,y)
            th.nn.Tanh()  # bound spatial extent
        )

        self.width_predictor = th.nn.Sequential(
            th.nn.Linear(hidden_size, 1),
            th.nn.Sigmoid()
        )

        self.alpha_predictor = th.nn.Sequential(
            th.nn.Linear(hidden_size, 1),
            th.nn.Sigmoid()
        )

    def _forward(self, z, hidden_and_cell=None):
        steps = self.num_strokes

        # z is passed at each step, duplicate it
        bs = z.shape[0]
        expanded_z = z.unsqueeze(1).repeat(1, steps, 1)

        # First step in the RNN
        if hidden_and_cell is None:
            # Initialize from latent vector
            hidden_and_cell = self.hidden_cell_predictor(th.tanh(z))
            hidden = hidden_and_cell[:, :self.hidden_size*self.num_layers]
            hidden = hidden.view(-1, self.num_layers, self.hidden_size)
            hidden = hidden.permute(1, 0, 2).contiguous()
            cell = hidden_and_cell[:, self.hidden_size*self.num_layers:]
            cell = cell.view(-1, self.num_layers, self.hidden_size)
            cell = cell.permute(1, 0, 2).contiguous()
            hidden_and_cell = (hidden, cell)

        feats, hidden_and_cell = self.lstm(expanded_z, hidden_and_cell)
        hidden, cell = hidden_and_cell

        feats = feats.reshape(bs*steps, self.hidden_size)

        # Construct the chain
        end_points = self.point_predictor(feats).view(bs, steps, 1, 2)
        start_points = th.cat([
            # first point is canvas center
            th.zeros(bs, 1, 1, 2, device=feats.device),
            end_points[:, 1:, :, :]], 1)
        all_points = th.cat([start_points, end_points], 2)

        all_alphas = self.alpha_predictor(feats).view(bs, steps)
        all_widths = self.width_predictor(feats).view(bs, steps)

        min_width = self.stroke_width[0]
        max_width = self.stroke_width[1]
        all_widths = (max_width - min_width) * all_widths + min_width

        output, scenes = rendering.line_render(all_points, all_widths, all_alphas,
                                        canvas_size=self.imsize)

        # map to [-1, 1]
        output = output*2.0 - 1.0

        return output, scenes


class Generator(BaseModel):
    def __init__(self, width=64, imsize=32, zdim=128,
                 stroke_width=None,
                 color_output=False,
                 num_strokes=4):
        super(Generator, self).__init__()
        assert imsize == 32

        self.imsize = imsize
        self.zdim = zdim

        num_in_chans = self.zdim // (2*2)
        num_out_chans = 3 if color_output else 1

        self.net = th.nn.Sequential(
            th.nn.ConvTranspose2d(num_in_chans, width*8, 4, padding=1,
                                  stride=2),
            th.nn.LeakyReLU(0.2, inplace=True),
            th.nn.Conv2d(width*8, width*8, 3, padding=1),
            th.nn.BatchNorm2d(width*8),
            th.nn.LeakyReLU(0.2, inplace=True),
            # 4x4

            th.nn.ConvTranspose2d(8*width, 4*width, 4, padding=1, stride=2),
            th.nn.LeakyReLU(0.2, inplace=True),
            th.nn.Conv2d(4*width, 4*width, 3, padding=1),
            th.nn.BatchNorm2d(width*4),
            th.nn.LeakyReLU(0.2, inplace=True),
            # 8x8

            th.nn.ConvTranspose2d(4*width, 2*width, 4, padding=1, stride=2),
            th.nn.LeakyReLU(0.2, inplace=True),
            th.nn.Conv2d(2*width, 2*width, 3, padding=1),
            th.nn.BatchNorm2d(width*2),
            th.nn.LeakyReLU(0.2, inplace=True),
            # 16x16

            th.nn.ConvTranspose2d(2*width, width, 4, padding=1, stride=2),
            th.nn.LeakyReLU(0.2, inplace=True),
            th.nn.Conv2d(width, width, 3, padding=1),
            th.nn.BatchNorm2d(width),
            th.nn.LeakyReLU(0.2, inplace=True),
            # 32x32

            th.nn.Conv2d(width, width, 3, padding=1),
            th.nn.BatchNorm2d(width),
            th.nn.LeakyReLU(0.2, inplace=True),
            th.nn.Conv2d(width, width, 3, padding=1),
            th.nn.LeakyReLU(0.2, inplace=True),
            th.nn.Conv2d(width, num_out_chans, 1),

            th.nn.Tanh(),
        )

    def forward(self, z):
        bs = z.shape[0]
        num_in_chans = self.zdim // (2*2)
        raster = self.net(z.view(bs, num_in_chans, 2, 2))
        return raster


class Discriminator(th.nn.Module):
    def __init__(self, conditional=False, width=64, color_output=False):
        super(Discriminator, self).__init__()

        self.conditional = conditional

        sn = th.nn.utils.spectral_norm

        num_chan_in = 3 if color_output else 1

        self.net = th.nn.Sequential(
            th.nn.Conv2d(num_chan_in, width, 3, padding=1),
            th.nn.LeakyReLU(0.2, inplace=True),
            th.nn.Conv2d(width, 2*width, 4, padding=1, stride=2),
            th.nn.LeakyReLU(0.2, inplace=True),
            # 16x16

            sn(th.nn.Conv2d(2*width, 2*width, 3, padding=1)),
            th.nn.LeakyReLU(0.2, inplace=True),
            sn(th.nn.Conv2d(2*width, 4*width, 4, padding=1, stride=2)),
            th.nn.LeakyReLU(0.2, inplace=True),
            # 8x8

            sn(th.nn.Conv2d(4*width, 4*width, 3, padding=1)),
            th.nn.LeakyReLU(0.2, inplace=True),
            sn(th.nn.Conv2d(4*width, width*4, 4, padding=1, stride=2)),
            th.nn.LeakyReLU(0.2, inplace=True),
            # 4x4

            sn(th.nn.Conv2d(4*width, 4*width, 3, padding=1)),
            th.nn.LeakyReLU(0.2, inplace=True),
            sn(th.nn.Conv2d(4*width, width*4, 4, padding=1, stride=2)),
            th.nn.LeakyReLU(0.2, inplace=True),
            # 2x2

            modules.Flatten(),
            th.nn.Linear(width*4*2*2, 1),
        )

    def forward(self, x):
        out = self.net(x)
        return out