vlbthambawita commited on
Commit
7f49ac7
1 Parent(s): 8faf760
.gitattributes CHANGED
The diff for this file is too large to render. See raw diff
 
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md CHANGED
@@ -1,3 +1,63 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A Fast and Stable GAN for Small and High Resolution Imagesets - pytorch
2
+ The official pytorch implementation of the paper "Towards Faster and Stabilized GAN Training for High-fidelity Few-shot Image Synthesis", the paper can be found [here](https://arxiv.org/abs/2101.04775).
3
+
4
+ ## 0. Data
5
+ The datasets used in the paper can be found at [link](https://drive.google.com/file/d/1aAJCZbXNHyraJ6Mi13dSbe7pTyfPXha0/view?usp=sharing).
6
+
7
+ After testing on over 20 datasets with each has less than 100 images, this GAN converges on 80% of them.
8
+ I still cannot summarize an obvious pattern of the "good properties" for a dataset which this GAN can converge on, please feel free to try with your own datasets.
9
+
10
+
11
+ ## 1. Description
12
+ The code is structured as follows:
13
+ * models.py: all the models' structure definition.
14
+
15
+ * operation.py: the helper functions and data loading methods during training.
16
+
17
+ * train.py: the main entry of the code, execute this file to train the model, the intermediate results and checkpoints will be automatically saved periodically into a folder "train_results".
18
+
19
+ * eval.py: generates images from a trained generator into a folder, which can be used to calculate FID score.
20
+
21
+ * benchmarking: the functions we used to compute FID are located here, it automatically downloads the pytorch official inception model.
22
+
23
+ * lpips: this folder contains the code to compute the LPIPS score, the inception model is also automatically download from official location.
24
+
25
+ * scripts: this folder contains many scripts you can use to play around the trained model. Including:
26
+ 1. style_mix.py: style-mixing as introduced in the paper;
27
+ 2. generate_video.py: generating a continuous video from the interpolation of generated images;
28
+ 3. find_nearest_neighbor.py: given a generated image, find the closest real-image from the training set;
29
+ 4. train_backtracking_one.py: given a real-image, find the latent vector of this image from a trained Generator.
30
+
31
+ ## 2. How to run
32
+ Place all your training images in a folder, and simply call
33
+ ```
34
+ python train.py --path /path/to/RGB-image-folder
35
+ ```
36
+ You can also see all the training options by:
37
+ ```
38
+ python train.py --help
39
+ ```
40
+ The code will automatically create a new folder (you have to specify the name of the folder using --name option) to store the trained checkpoints and intermediate synthesis results.
41
+
42
+ Once finish training, you can generate 100 images (or as many as you want) by:
43
+ ```
44
+ cd ./train_results/name_of_your_training/
45
+ python eval.py --n_sample 100
46
+ ```
47
+
48
+ ## 3. Pre-trained models
49
+ The pre-trained models and the respective code of each model are shared [here](https://drive.google.com/drive/folders/1nCpr84nKkrs9-aVMET5h8gqFbUYJRPLR?usp=sharing).
50
+
51
+ You can also use FastGAN to generate images with a pre-packaged Docker image, hosted on the Replicate registry: https://beta.replicate.ai/odegeasslbc/FastGAN
52
+
53
+ ## 4. Important notes
54
+ 1. The provided code is for research use only.
55
+ 2. Different model and training configurations are needed on different datasets. You may have to tune the hyper-parameters to get the best results on your own datasets.
56
+
57
+ 2.1. The hyper-parameters includes: the augmentation options, the model depth (how many layers), the model width (channel numbers of each layer). To change these, you have to change the code in models.py and train.py directly.
58
+
59
+ 2.2. Please check the code in the shared pre-trained models on how each of them are configured differently on different datasets. Especially, compare the models.py for ffhq and art datasets, you will get an idea on what chages could be made on different datasets.
60
+
61
+ ## 5. Other notes
62
+ 1. The provided scripts are not well organized, contributions are welcomed to clean them.
63
+ 2. An third-party implementation of this paper can be found [here](https://github.com/lucidrains/lightweight-gan), where some other techniques are included. I suggest you try both implementation if you find one of them does not work.
benchmarking/benchmark.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from torchvision import models
5
+ from torchvision.models import inception_v3, Inception3
6
+ from torchvision.utils import save_image
7
+
8
+ try:
9
+ from torchvision.models.utils import load_state_dict_from_url
10
+ except ImportError:
11
+ from torch.utils.model_zoo import load_url as load_state_dict_from_url
12
+
13
+ import numpy as np
14
+ from scipy import linalg
15
+ from tqdm import tqdm
16
+ import pickle
17
+ import os
18
+
19
+ # Inception weights ported to Pytorch from
20
+ # http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz
21
+ FID_WEIGHTS_URL = 'https://github.com/mseitzer/pytorch-fid/releases/download/fid_weights/pt_inception-2015-12-05-6726825d.pth'
22
+
23
+
24
+ class InceptionV3(nn.Module):
25
+ """Pretrained InceptionV3 network returning feature maps"""
26
+
27
+ # Index of default block of inception to return,
28
+ # corresponds to output of final average pooling
29
+ DEFAULT_BLOCK_INDEX = 3
30
+
31
+ # Maps feature dimensionality to their output blocks indices
32
+ BLOCK_INDEX_BY_DIM = {
33
+ 64: 0, # First max pooling features
34
+ 192: 1, # Second max pooling featurs
35
+ 768: 2, # Pre-aux classifier features
36
+ 2048: 3 # Final average pooling features
37
+ }
38
+
39
+ def __init__(self,
40
+ output_blocks=[DEFAULT_BLOCK_INDEX],
41
+ resize_input=True,
42
+ normalize_input=True,
43
+ requires_grad=False,
44
+ use_fid_inception=True):
45
+ """Build pretrained InceptionV3
46
+ Parameters
47
+ ----------
48
+ output_blocks : list of int
49
+ Indices of blocks to return features of. Possible values are:
50
+ - 0: corresponds to output of first max pooling
51
+ - 1: corresponds to output of second max pooling
52
+ - 2: corresponds to output which is fed to aux classifier
53
+ - 3: corresponds to output of final average pooling
54
+ resize_input : bool
55
+ If true, bilinearly resizes input to width and height 299 before
56
+ feeding input to model. As the network without fully connected
57
+ layers is fully convolutional, it should be able to handle inputs
58
+ of arbitrary size, so resizing might not be strictly needed
59
+ normalize_input : bool
60
+ If true, scales the input from range (0, 1) to the range the
61
+ pretrained Inception network expects, namely (-1, 1)
62
+ requires_grad : bool
63
+ If true, parameters of the model require gradients. Possibly useful
64
+ for finetuning the network
65
+ use_fid_inception : bool
66
+ If true, uses the pretrained Inception model used in Tensorflow's
67
+ FID implementation. If false, uses the pretrained Inception model
68
+ available in torchvision. The FID Inception model has different
69
+ weights and a slightly different structure from torchvision's
70
+ Inception model. If you want to compute FID scores, you are
71
+ strongly advised to set this parameter to true to get comparable
72
+ results.
73
+ """
74
+ super(InceptionV3, self).__init__()
75
+
76
+ self.resize_input = resize_input
77
+ self.normalize_input = normalize_input
78
+ self.output_blocks = sorted(output_blocks)
79
+ self.last_needed_block = max(output_blocks)
80
+
81
+ assert self.last_needed_block <= 3, \
82
+ 'Last possible output block index is 3'
83
+
84
+ self.blocks = nn.ModuleList()
85
+
86
+ if use_fid_inception:
87
+ inception = fid_inception_v3()
88
+ else:
89
+ inception = models.inception_v3(pretrained=True)
90
+
91
+ # Block 0: input to maxpool1
92
+ block0 = [
93
+ inception.Conv2d_1a_3x3,
94
+ inception.Conv2d_2a_3x3,
95
+ inception.Conv2d_2b_3x3,
96
+ nn.MaxPool2d(kernel_size=3, stride=2)
97
+ ]
98
+ self.blocks.append(nn.Sequential(*block0))
99
+
100
+ # Block 1: maxpool1 to maxpool2
101
+ if self.last_needed_block >= 1:
102
+ block1 = [
103
+ inception.Conv2d_3b_1x1,
104
+ inception.Conv2d_4a_3x3,
105
+ nn.MaxPool2d(kernel_size=3, stride=2)
106
+ ]
107
+ self.blocks.append(nn.Sequential(*block1))
108
+
109
+ # Block 2: maxpool2 to aux classifier
110
+ if self.last_needed_block >= 2:
111
+ block2 = [
112
+ inception.Mixed_5b,
113
+ inception.Mixed_5c,
114
+ inception.Mixed_5d,
115
+ inception.Mixed_6a,
116
+ inception.Mixed_6b,
117
+ inception.Mixed_6c,
118
+ inception.Mixed_6d,
119
+ inception.Mixed_6e,
120
+ ]
121
+ self.blocks.append(nn.Sequential(*block2))
122
+
123
+ # Block 3: aux classifier to final avgpool
124
+ if self.last_needed_block >= 3:
125
+ block3 = [
126
+ inception.Mixed_7a,
127
+ inception.Mixed_7b,
128
+ inception.Mixed_7c,
129
+ nn.AdaptiveAvgPool2d(output_size=(1, 1))
130
+ ]
131
+ self.blocks.append(nn.Sequential(*block3))
132
+
133
+ for param in self.parameters():
134
+ param.requires_grad = requires_grad
135
+
136
+ def forward(self, inp):
137
+ """Get Inception feature maps
138
+ Parameters
139
+ ----------
140
+ inp : torch.autograd.Variable
141
+ Input tensor of shape Bx3xHxW. Values are expected to be in
142
+ range (0, 1)
143
+ Returns
144
+ -------
145
+ List of torch.autograd.Variable, corresponding to the selected output
146
+ block, sorted ascending by index
147
+ """
148
+ outp = []
149
+ x = inp
150
+
151
+ if self.resize_input:
152
+ x = F.interpolate(x,
153
+ size=(299, 299),
154
+ mode='bilinear',
155
+ align_corners=False)
156
+
157
+ if self.normalize_input:
158
+ x = 2 * x - 1 # Scale from range (0, 1) to range (-1, 1)
159
+
160
+ for idx, block in enumerate(self.blocks):
161
+ x = block(x)
162
+ if idx in self.output_blocks:
163
+ outp.append(x)
164
+
165
+ if idx == self.last_needed_block:
166
+ break
167
+
168
+ return outp
169
+
170
+
171
+ def fid_inception_v3():
172
+ """Build pretrained Inception model for FID computation
173
+ The Inception model for FID computation uses a different set of weights
174
+ and has a slightly different structure than torchvision's Inception.
175
+ This method first constructs torchvision's Inception and then patches the
176
+ necessary parts that are different in the FID Inception model.
177
+ """
178
+ inception = models.inception_v3(num_classes=1008,
179
+ aux_logits=False,
180
+ pretrained=False)
181
+ inception.Mixed_5b = FIDInceptionA(192, pool_features=32)
182
+ inception.Mixed_5c = FIDInceptionA(256, pool_features=64)
183
+ inception.Mixed_5d = FIDInceptionA(288, pool_features=64)
184
+ inception.Mixed_6b = FIDInceptionC(768, channels_7x7=128)
185
+ inception.Mixed_6c = FIDInceptionC(768, channels_7x7=160)
186
+ inception.Mixed_6d = FIDInceptionC(768, channels_7x7=160)
187
+ inception.Mixed_6e = FIDInceptionC(768, channels_7x7=192)
188
+ inception.Mixed_7b = FIDInceptionE_1(1280)
189
+ inception.Mixed_7c = FIDInceptionE_2(2048)
190
+
191
+ state_dict = load_state_dict_from_url(FID_WEIGHTS_URL, progress=True)
192
+ inception.load_state_dict(state_dict)
193
+ return inception
194
+
195
+
196
+ class FIDInceptionA(models.inception.InceptionA):
197
+ """InceptionA block patched for FID computation"""
198
+ def __init__(self, in_channels, pool_features):
199
+ super(FIDInceptionA, self).__init__(in_channels, pool_features)
200
+
201
+ def forward(self, x):
202
+ branch1x1 = self.branch1x1(x)
203
+
204
+ branch5x5 = self.branch5x5_1(x)
205
+ branch5x5 = self.branch5x5_2(branch5x5)
206
+
207
+ branch3x3dbl = self.branch3x3dbl_1(x)
208
+ branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
209
+ branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)
210
+
211
+ # Patch: Tensorflow's average pool does not use the padded zero's in
212
+ # its average calculation
213
+ branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
214
+ count_include_pad=False)
215
+ branch_pool = self.branch_pool(branch_pool)
216
+
217
+ outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool]
218
+ return torch.cat(outputs, 1)
219
+
220
+
221
+ class FIDInceptionC(models.inception.InceptionC):
222
+ """InceptionC block patched for FID computation"""
223
+ def __init__(self, in_channels, channels_7x7):
224
+ super(FIDInceptionC, self).__init__(in_channels, channels_7x7)
225
+
226
+ def forward(self, x):
227
+ branch1x1 = self.branch1x1(x)
228
+
229
+ branch7x7 = self.branch7x7_1(x)
230
+ branch7x7 = self.branch7x7_2(branch7x7)
231
+ branch7x7 = self.branch7x7_3(branch7x7)
232
+
233
+ branch7x7dbl = self.branch7x7dbl_1(x)
234
+ branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl)
235
+ branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl)
236
+ branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl)
237
+ branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl)
238
+
239
+ # Patch: Tensorflow's average pool does not use the padded zero's in
240
+ # its average calculation
241
+ branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
242
+ count_include_pad=False)
243
+ branch_pool = self.branch_pool(branch_pool)
244
+
245
+ outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool]
246
+ return torch.cat(outputs, 1)
247
+
248
+
249
+ class FIDInceptionE_1(models.inception.InceptionE):
250
+ """First InceptionE block patched for FID computation"""
251
+ def __init__(self, in_channels):
252
+ super(FIDInceptionE_1, self).__init__(in_channels)
253
+
254
+ def forward(self, x):
255
+ branch1x1 = self.branch1x1(x)
256
+
257
+ branch3x3 = self.branch3x3_1(x)
258
+ branch3x3 = [
259
+ self.branch3x3_2a(branch3x3),
260
+ self.branch3x3_2b(branch3x3),
261
+ ]
262
+ branch3x3 = torch.cat(branch3x3, 1)
263
+
264
+ branch3x3dbl = self.branch3x3dbl_1(x)
265
+ branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
266
+ branch3x3dbl = [
267
+ self.branch3x3dbl_3a(branch3x3dbl),
268
+ self.branch3x3dbl_3b(branch3x3dbl),
269
+ ]
270
+ branch3x3dbl = torch.cat(branch3x3dbl, 1)
271
+
272
+ # Patch: Tensorflow's average pool does not use the padded zero's in
273
+ # its average calculation
274
+ branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
275
+ count_include_pad=False)
276
+ branch_pool = self.branch_pool(branch_pool)
277
+
278
+ outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
279
+ return torch.cat(outputs, 1)
280
+
281
+
282
+ class FIDInceptionE_2(models.inception.InceptionE):
283
+ """Second InceptionE block patched for FID computation"""
284
+ def __init__(self, in_channels):
285
+ super(FIDInceptionE_2, self).__init__(in_channels)
286
+
287
+ def forward(self, x):
288
+ branch1x1 = self.branch1x1(x)
289
+
290
+ branch3x3 = self.branch3x3_1(x)
291
+ branch3x3 = [
292
+ self.branch3x3_2a(branch3x3),
293
+ self.branch3x3_2b(branch3x3),
294
+ ]
295
+ branch3x3 = torch.cat(branch3x3, 1)
296
+
297
+ branch3x3dbl = self.branch3x3dbl_1(x)
298
+ branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
299
+ branch3x3dbl = [
300
+ self.branch3x3dbl_3a(branch3x3dbl),
301
+ self.branch3x3dbl_3b(branch3x3dbl),
302
+ ]
303
+ branch3x3dbl = torch.cat(branch3x3dbl, 1)
304
+
305
+ # Patch: The FID Inception model uses max pooling instead of average
306
+ # pooling. This is likely an error in this specific Inception
307
+ # implementation, as other Inception models use average pooling here
308
+ # (which matches the description in the paper).
309
+ branch_pool = F.max_pool2d(x, kernel_size=3, stride=1, padding=1)
310
+ branch_pool = self.branch_pool(branch_pool)
311
+
312
+ outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
313
+ return torch.cat(outputs, 1)
314
+
315
+
316
+ class Inception3Feature(Inception3):
317
+ def forward(self, x):
318
+ if x.shape[2] != 299 or x.shape[3] != 299:
319
+ x = F.interpolate(x, size=(299, 299), mode='bilinear', align_corners=True)
320
+
321
+ x = self.Conv2d_1a_3x3(x) # 299 x 299 x 3
322
+ x = self.Conv2d_2a_3x3(x) # 149 x 149 x 32
323
+ x = self.Conv2d_2b_3x3(x) # 147 x 147 x 32
324
+ x = F.max_pool2d(x, kernel_size=3, stride=2) # 147 x 147 x 64
325
+
326
+ x = self.Conv2d_3b_1x1(x) # 73 x 73 x 64
327
+ x = self.Conv2d_4a_3x3(x) # 73 x 73 x 80
328
+ x = F.max_pool2d(x, kernel_size=3, stride=2) # 71 x 71 x 192
329
+
330
+ x = self.Mixed_5b(x) # 35 x 35 x 192
331
+ x = self.Mixed_5c(x) # 35 x 35 x 256
332
+ x = self.Mixed_5d(x) # 35 x 35 x 288
333
+
334
+ x = self.Mixed_6a(x) # 35 x 35 x 288
335
+ x = self.Mixed_6b(x) # 17 x 17 x 768
336
+ x = self.Mixed_6c(x) # 17 x 17 x 768
337
+ x = self.Mixed_6d(x) # 17 x 17 x 768
338
+ x = self.Mixed_6e(x) # 17 x 17 x 768
339
+
340
+ x = self.Mixed_7a(x) # 17 x 17 x 768
341
+ x = self.Mixed_7b(x) # 8 x 8 x 1280
342
+ x = self.Mixed_7c(x) # 8 x 8 x 2048
343
+
344
+ x = F.avg_pool2d(x, kernel_size=8) # 8 x 8 x 2048
345
+
346
+ return x.view(x.shape[0], x.shape[1]) # 1 x 1 x 2048
347
+
348
+
349
+ def load_patched_inception_v3():
350
+ # inception = inception_v3(pretrained=True)
351
+ # inception_feat = Inception3Feature()
352
+ # inception_feat.load_state_dict(inception.state_dict())
353
+ inception_feat = InceptionV3([3], normalize_input=False)
354
+
355
+ return inception_feat
356
+
357
+
358
+ @torch.no_grad()
359
+ def extract_features(loader, inception, device):
360
+ pbar = tqdm(loader)
361
+
362
+ feature_list = []
363
+
364
+ for img in pbar:
365
+ img = img.to(device)
366
+ feature = inception(img)[0].view(img.shape[0], -1)
367
+ feature_list.append(feature.to('cpu'))
368
+
369
+ features = torch.cat(feature_list, 0)
370
+
371
+ return features
372
+
373
+
374
+
375
+ @torch.no_grad()
376
+ def extract_feature_from_samples(generator, inception, device='cuda'):
377
+ n_batch = n_sample // batch_size
378
+ resid = n_sample - (n_batch * batch_size)
379
+ batch_sizes = [batch_size] * n_batch + [resid]
380
+ features = []
381
+
382
+ for batch in tqdm(batch_sizes):
383
+ latent = torch.randn(batch, 512, device=device)
384
+ img, _ = g([latent], truncation=truncation, truncation_latent=truncation_latent)
385
+ feat = inception(img)[0].view(img.shape[0], -1)
386
+ features.append(feat.to('cpu'))
387
+
388
+ features = torch.cat(features, 0)
389
+
390
+ return features
391
+
392
+
393
+ @torch.no_grad()
394
+ def extract_feature_from_generator_fn(generator_fn, inception, device='cuda', total=1000):
395
+ features = []
396
+ for batch in tqdm(generator_fn, total=total):
397
+ feat = inception(batch)[0].view(batch.shape[0], -1)
398
+ features.append(feat.to('cpu'))
399
+
400
+ features = torch.cat(features, 0).detach()
401
+ return features.numpy()
402
+
403
+
404
+ def calc_fid(sample_features, real_features=None, real_mean=None, real_cov=None, eps=1e-6):
405
+ sample_mean = np.mean(sample_features, 0)
406
+ sample_cov = np.cov(sample_features, rowvar=False)
407
+
408
+ if real_features is not None:
409
+ real_mean = np.mean(real_features, 0)
410
+ real_cov = np.cov(real_features, rowvar=False)
411
+
412
+ cov_sqrt, _ = linalg.sqrtm(sample_cov @ real_cov, disp=False)
413
+
414
+ if not np.isfinite(cov_sqrt).all():
415
+ print('product of cov matrices is singular')
416
+ offset = np.eye(sample_cov.shape[0]) * eps
417
+ cov_sqrt = linalg.sqrtm((sample_cov + offset) @ (real_cov + offset))
418
+
419
+ if np.iscomplexobj(cov_sqrt):
420
+ if not np.allclose(np.diagonal(cov_sqrt).imag, 0, atol=1e-3):
421
+ m = np.max(np.abs(cov_sqrt.imag))
422
+
423
+ raise ValueError(f'Imaginary component {m}')
424
+
425
+ cov_sqrt = cov_sqrt.real
426
+
427
+ mean_diff = sample_mean - real_mean
428
+ mean_norm = mean_diff @ mean_diff
429
+
430
+ trace = np.trace(sample_cov) + np.trace(real_cov) - 2 * np.trace(cov_sqrt)
431
+
432
+ fid = mean_norm + trace
433
+
434
+ return fid
435
+
436
+
437
+ if __name__ == "__main__":
438
+ #from utils import PairedMultiDataset, InfiniteSamplerWrapper, make_folders, AverageMeter
439
+ from torch.utils.data import DataLoader
440
+ from torchvision import utils as vutils
441
+
442
+ IM_SIZE = 1024
443
+ BATCH_SIZE = 16
444
+ DATALOADER_WORKERS = 8
445
+ NBR_CLS = 2000
446
+ TRIAL_NAME = 'trial_vae_512_1'
447
+ SAVE_FOLDER = './'
448
+
449
+ from torchvision.datasets import ImageFolder
450
+
451
+ '''
452
+ data_root_colorful = '../images/celebA/CelebA_512/img'
453
+ data_root_sketch_1 = './sketch_simplification/vggadin_iter_700'
454
+ data_root_sketch_2 = './sketch_simplification/vggadin_iter_1900'
455
+ data_root_sketch_3 = './sketch_simplification/vggadin_iter_2300'
456
+
457
+ dataset = PairedMultiDataset(data_root_colorful, data_root_sketch_1, data_root_sketch_2, data_root_sketch_3, im_size=IM_SIZE, rand_crop=False)
458
+ dataloader = iter(DataLoader(dataset, BATCH_SIZE, shuffle=False, num_workers=DATALOADER_WORKERS, pin_memory=True))
459
+
460
+
461
+ from pretrain_ae import StyleEncoder, ContentEncoder, Decoder
462
+ import pickle
463
+ from refine_ae_as_gan import AE, RefineGenerator
464
+ from utils import load_params
465
+
466
+ net_ig = RefineGenerator().cuda()
467
+ net_ig = nn.DataParallel(net_ig)
468
+
469
+ ckpt = './train_results/trial_refine_ae_as_gan_1024_2/models/4.pth'
470
+ if ckpt is not None:
471
+ ckpt = torch.load(ckpt)
472
+ #net_ig.load_state_dict(ckpt['ig'])
473
+ #net_id.load_state_dict(ckpt['id'])
474
+ net_ig_ema = ckpt['ig_ema']
475
+ load_params(net_ig, net_ig_ema)
476
+ net_ig = net_ig.module
477
+ #net_ig.eval()
478
+
479
+ net_ae = AE()
480
+ net_ae.load_state_dicts('./train_results/trial_vae_512_1/models/176000.pth')
481
+ net_ae.cuda()
482
+ net_ae.eval()
483
+
484
+ #style_encoder = StyleEncoder(nbr_cls=NBR_CLS).cuda()
485
+ #content_encoder = ContentEncoder().cuda()
486
+ #decoder = Decoder().cuda()
487
+ '''
488
+
489
+ def real_image_loader(dataloader, n_batches=10):
490
+ counter = 0
491
+ while counter < n_batches:
492
+ counter += 1
493
+ rgb_img, _ = next(dataloader)
494
+ if counter == 1:
495
+ vutils.save_image(0.5*(rgb_img+1), 'tmp_real.jpg')
496
+ yield rgb_img.cuda()
497
+
498
+ '''
499
+ @torch.no_grad()
500
+ def image_generator_1(dataloader, n_batches=10):
501
+ counter = 0
502
+ while counter < n_batches:
503
+ counter += 1
504
+ rgb_img, _, _, skt_img = next(dataloader)
505
+ rgb_img = rgb_img.cuda()
506
+ skt_img = skt_img.cuda()
507
+
508
+ style_feat, _ = style_encoder(rgb_img)
509
+ content_feats = content_encoder( F.interpolate( skt_img , size=512 ) )
510
+ gimg = decoder(content_feats, style_feat)
511
+
512
+ vutils.save_image(0.5*(gimg+1), 'tmp.jpg')
513
+ yield gimg
514
+
515
+ from utils import true_randperm
516
+ @torch.no_grad()
517
+ def image_generator(dataset, net_ae, net_ig, n_batches=500):
518
+ counter = 0
519
+ dataloader = iter(DataLoader(dataset, BATCH_SIZE, shuffle=False, num_workers=DATALOADER_WORKERS, pin_memory=False))
520
+
521
+ while counter < n_batches:
522
+ counter += 1
523
+ rgb_img, _, _, skt_img = next(dataloader)
524
+ rgb_img = F.interpolate( rgb_img, size=512 ).cuda()
525
+ skt_img = F.interpolate( skt_img, size=512 ).cuda()
526
+
527
+ #perm = true_randperm(rgb_img.shape[0], device=rgb_img.device)
528
+
529
+ gimg_ae, style_feat = net_ae(skt_img, rgb_img)
530
+ g_image = net_ig(gimg_ae, style_feat, skt_img)
531
+ if counter == 1:
532
+ vutils.save_image(0.5*(g_image+1), 'tmp.jpg')
533
+ yield g_image
534
+ '''
535
+ inception = load_patched_inception_v3().cuda()
536
+ inception.eval()
537
+
538
+ path_a = '../../../database/images/celebaMask/CelebA_1024'
539
+ path_b = '../../stylegan/celebahq_samples'
540
+
541
+ from torchvision import transforms
542
+
543
+ transform = transforms.Compose(
544
+ [
545
+ transforms.Resize( (299, 299) ),
546
+ #transforms.RandomHorizontalFlip(p=0.5 if args.flip else 0),
547
+ transforms.ToTensor(),
548
+ transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
549
+ ]
550
+ )
551
+
552
+ dset_a = ImageFolder(path_a, transform)
553
+ loader_a = iter(DataLoader(dset_a, batch_size=16, num_workers=4))
554
+
555
+ real_features = extract_feature_from_generator_fn(
556
+ real_image_loader(loader_a, n_batches=900), inception )
557
+ real_mean = np.mean(real_features, 0)
558
+ real_cov = np.cov(real_features, rowvar=False)
559
+
560
+ #pickle.dump({'feats': real_features, 'mean': real_mean, 'cov': real_cov}, open('celeba_fid_feats.npy','wb') )
561
+
562
+ #real_features = pickle.load( open('celeba_fid_feats.npy', 'rb') )
563
+ #real_mean = real_features['mean']
564
+ #real_cov = real_features['cov']
565
+ #sample_features = extract_feature_from_generator_fn( real_image_loader(dataloader, n_batches=100), inception )
566
+
567
+ dset_b = ImageFolder(path_b, transform)
568
+ loader_b = iter(DataLoader(dset_b, batch_size=16, num_workers=4))
569
+
570
+ sample_features = extract_feature_from_generator_fn(
571
+ real_image_loader(loader_b, n_batches=900), inception )
572
+ #sample_features = extract_feature_from_generator_fn(
573
+ # image_generator(dataset, net_ae, net_ig, n_batches=1800), inception,
574
+ # total=1800 )
575
+
576
+ #fid = calc_fid(sample_features, real_mean=real_features['mean'], real_cov=real_features['cov'])
577
+ fid = calc_fid(sample_features, real_mean=real_mean, real_cov=real_cov)
578
+
579
+ print(fid)
benchmarking/calc_inception.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import pickle
3
+ import os
4
+
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+ from torch.utils.data import DataLoader
9
+ from torchvision import transforms
10
+ from torchvision.models import inception_v3, Inception3
11
+ import numpy as np
12
+ from tqdm import tqdm
13
+
14
+ from inception import InceptionV3
15
+ from torchvision.datasets import ImageFolder
16
+
17
+ class Inception3Feature(Inception3):
18
+ def forward(self, x):
19
+ if x.shape[2] != 299 or x.shape[3] != 299:
20
+ x = F.interpolate(x, size=(299, 299), mode='bilinear', align_corners=True)
21
+
22
+ x = self.Conv2d_1a_3x3(x) # 299 x 299 x 3
23
+ x = self.Conv2d_2a_3x3(x) # 149 x 149 x 32
24
+ x = self.Conv2d_2b_3x3(x) # 147 x 147 x 32
25
+ x = F.max_pool2d(x, kernel_size=3, stride=2) # 147 x 147 x 64
26
+
27
+ x = self.Conv2d_3b_1x1(x) # 73 x 73 x 64
28
+ x = self.Conv2d_4a_3x3(x) # 73 x 73 x 80
29
+ x = F.max_pool2d(x, kernel_size=3, stride=2) # 71 x 71 x 192
30
+
31
+ x = self.Mixed_5b(x) # 35 x 35 x 192
32
+ x = self.Mixed_5c(x) # 35 x 35 x 256
33
+ x = self.Mixed_5d(x) # 35 x 35 x 288
34
+
35
+ x = self.Mixed_6a(x) # 35 x 35 x 288
36
+ x = self.Mixed_6b(x) # 17 x 17 x 768
37
+ x = self.Mixed_6c(x) # 17 x 17 x 768
38
+ x = self.Mixed_6d(x) # 17 x 17 x 768
39
+ x = self.Mixed_6e(x) # 17 x 17 x 768
40
+
41
+ x = self.Mixed_7a(x) # 17 x 17 x 768
42
+ x = self.Mixed_7b(x) # 8 x 8 x 1280
43
+ x = self.Mixed_7c(x) # 8 x 8 x 2048
44
+
45
+ x = F.avg_pool2d(x, kernel_size=8) # 8 x 8 x 2048
46
+
47
+ return x.view(x.shape[0], x.shape[1]) # 1 x 1 x 2048
48
+
49
+
50
+ def load_patched_inception_v3():
51
+ # inception = inception_v3(pretrained=True)
52
+ # inception_feat = Inception3Feature()
53
+ # inception_feat.load_state_dict(inception.state_dict())
54
+ inception_feat = InceptionV3([3], normalize_input=False)
55
+
56
+ return inception_feat
57
+
58
+
59
+ @torch.no_grad()
60
+ def extract_features(loader, inception, device):
61
+ pbar = tqdm(loader)
62
+
63
+ feature_list = []
64
+
65
+ for img,_ in pbar:
66
+ img = img.to(device)
67
+ feature = inception(img)[0].view(img.shape[0], -1)
68
+ feature_list.append(feature.to('cpu'))
69
+
70
+ features = torch.cat(feature_list, 0)
71
+
72
+ return features
73
+
74
+
75
+ if __name__ == '__main__':
76
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
77
+
78
+ parser = argparse.ArgumentParser(
79
+ description='Calculate Inception v3 features for datasets'
80
+ )
81
+ parser.add_argument('--size', type=int, default=256)
82
+ parser.add_argument('--batch', default=64, type=int, help='batch size')
83
+ parser.add_argument('--n_sample', type=int, default=50000)
84
+ parser.add_argument('--flip', action='store_true')
85
+ parser.add_argument('path', metavar='PATH', help='path to datset lmdb file')
86
+
87
+ args = parser.parse_args()
88
+
89
+ inception = load_patched_inception_v3().eval().to(device)
90
+
91
+ transform = transforms.Compose(
92
+ [
93
+ transforms.Resize( (args.size, args.size) ),
94
+ transforms.RandomHorizontalFlip(p=0.5 if args.flip else 0),
95
+ transforms.ToTensor(),
96
+ transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
97
+ ]
98
+ )
99
+
100
+ dset = ImageFolder(args.path, transform)
101
+ loader = DataLoader(dset, batch_size=args.batch, num_workers=4)
102
+
103
+ features = extract_features(loader, inception, device).numpy()
104
+
105
+ features = features[: args.n_sample]
106
+
107
+ print(f'extracted {features.shape[0]} features')
108
+
109
+ mean = np.mean(features, 0)
110
+ cov = np.cov(features, rowvar=False)
111
+
112
+ name = os.path.splitext(os.path.basename(args.path))[0]
113
+
114
+ print({'mean': mean.mean(), 'cov': cov.mean()})
115
+ with open(f'inception_{name}.pkl', 'wb') as f:
116
+ pickle.dump({'mean': mean, 'cov': cov, 'size': args.size, 'path': args.path}, f)
benchmarking/fid.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import pickle
3
+
4
+ import torch
5
+ from torch import nn
6
+ import numpy as np
7
+ from scipy import linalg
8
+ from tqdm import tqdm
9
+
10
+ from torchvision import transforms
11
+ from torchvision.datasets import ImageFolder
12
+ from torch.utils.data import DataLoader
13
+
14
+ from calc_inception import load_patched_inception_v3
15
+ import os
16
+
17
+ @torch.no_grad()
18
+ def extract_features(loader, inception, device):
19
+ pbar = tqdm(loader)
20
+
21
+ feature_list = []
22
+
23
+ for img,_ in pbar:
24
+ img = img.to(device)
25
+ feature = inception(img)[0].view(img.shape[0], -1)
26
+ feature_list.append(feature.to('cpu'))
27
+
28
+ features = torch.cat(feature_list, 0)
29
+
30
+ return features
31
+
32
+
33
+ def calc_fid(sample_mean, sample_cov, real_mean, real_cov, eps=1e-6):
34
+ cov_sqrt, _ = linalg.sqrtm(sample_cov @ real_cov, disp=False)
35
+
36
+ if not np.isfinite(cov_sqrt).all():
37
+ print('product of cov matrices is singular')
38
+ offset = np.eye(sample_cov.shape[0]) * eps
39
+ cov_sqrt = linalg.sqrtm((sample_cov + offset) @ (real_cov + offset))
40
+
41
+ if np.iscomplexobj(cov_sqrt):
42
+ if not np.allclose(np.diagonal(cov_sqrt).imag, 0, atol=1e-3):
43
+ m = np.max(np.abs(cov_sqrt.imag))
44
+
45
+ raise ValueError(f'Imaginary component {m}')
46
+
47
+ cov_sqrt = cov_sqrt.real
48
+
49
+ mean_diff = sample_mean - real_mean
50
+ mean_norm = mean_diff @ mean_diff
51
+
52
+ trace = np.trace(sample_cov) + np.trace(real_cov) - 2 * np.trace(cov_sqrt)
53
+
54
+ fid = mean_norm + trace
55
+
56
+ return fid
57
+
58
+
59
+ if __name__ == '__main__':
60
+ device = 'cuda'
61
+
62
+ parser = argparse.ArgumentParser()
63
+
64
+ parser.add_argument('--batch', type=int, default=64)
65
+ parser.add_argument('--size', type=int, default=256)
66
+ parser.add_argument('--path_a', type=str)
67
+ parser.add_argument('--path_b', type=str)
68
+ parser.add_argument('--iter', type=int, default=3)
69
+ parser.add_argument('--end', type=int, default=13)
70
+
71
+ args = parser.parse_args()
72
+
73
+ inception = load_patched_inception_v3().eval().to(device)
74
+
75
+ transform = transforms.Compose(
76
+ [
77
+ transforms.Resize( (args.size, args.size) ),
78
+ #transforms.RandomHorizontalFlip(p=0.5 if args.flip else 0),
79
+ transforms.ToTensor(),
80
+ transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
81
+ ]
82
+ )
83
+
84
+ dset_a = ImageFolder(args.path_a, transform)
85
+ loader_a = DataLoader(dset_a, batch_size=args.batch, num_workers=4)
86
+
87
+ features_a = extract_features(loader_a, inception, device).numpy()
88
+ print(f'extracted {features_a.shape[0]} features')
89
+
90
+ real_mean = np.mean(features_a, 0)
91
+ real_cov = np.cov(features_a, rowvar=False)
92
+
93
+ #for folder in os.listdir(args.path_b):
94
+ for folder in range(args.iter,args.end+1):
95
+ folder = 'eval_%d'%(folder*10000)
96
+ if os.path.exists(os.path.join( args.path_b, folder )):
97
+ print(folder)
98
+ dset_b = ImageFolder( os.path.join( args.path_b, folder ), transform)
99
+ loader_b = DataLoader(dset_b, batch_size=args.batch, num_workers=4)
100
+
101
+ features_b = extract_features(loader_b, inception, device).numpy()
102
+ print(f'extracted {features_b.shape[0]} features')
103
+
104
+ sample_mean = np.mean(features_b, 0)
105
+ sample_cov = np.cov(features_b, rowvar=False)
106
+
107
+ fid = calc_fid(sample_mean, sample_cov, real_mean, real_cov)
108
+
109
+ print(folder, ' fid:', fid)
benchmarking/inception.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from torchvision import models
5
+
6
+ try:
7
+ from torchvision.models.utils import load_state_dict_from_url
8
+ except ImportError:
9
+ from torch.utils.model_zoo import load_url as load_state_dict_from_url
10
+
11
+ # Inception weights ported to Pytorch from
12
+ # http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz
13
+ FID_WEIGHTS_URL = 'https://github.com/mseitzer/pytorch-fid/releases/download/fid_weights/pt_inception-2015-12-05-6726825d.pth'
14
+
15
+
16
+ class InceptionV3(nn.Module):
17
+ """Pretrained InceptionV3 network returning feature maps"""
18
+
19
+ # Index of default block of inception to return,
20
+ # corresponds to output of final average pooling
21
+ DEFAULT_BLOCK_INDEX = 3
22
+
23
+ # Maps feature dimensionality to their output blocks indices
24
+ BLOCK_INDEX_BY_DIM = {
25
+ 64: 0, # First max pooling features
26
+ 192: 1, # Second max pooling featurs
27
+ 768: 2, # Pre-aux classifier features
28
+ 2048: 3 # Final average pooling features
29
+ }
30
+
31
+ def __init__(self,
32
+ output_blocks=[DEFAULT_BLOCK_INDEX],
33
+ resize_input=True,
34
+ normalize_input=True,
35
+ requires_grad=False,
36
+ use_fid_inception=True):
37
+ """Build pretrained InceptionV3
38
+
39
+ Parameters
40
+ ----------
41
+ output_blocks : list of int
42
+ Indices of blocks to return features of. Possible values are:
43
+ - 0: corresponds to output of first max pooling
44
+ - 1: corresponds to output of second max pooling
45
+ - 2: corresponds to output which is fed to aux classifier
46
+ - 3: corresponds to output of final average pooling
47
+ resize_input : bool
48
+ If true, bilinearly resizes input to width and height 299 before
49
+ feeding input to model. As the network without fully connected
50
+ layers is fully convolutional, it should be able to handle inputs
51
+ of arbitrary size, so resizing might not be strictly needed
52
+ normalize_input : bool
53
+ If true, scales the input from range (0, 1) to the range the
54
+ pretrained Inception network expects, namely (-1, 1)
55
+ requires_grad : bool
56
+ If true, parameters of the model require gradients. Possibly useful
57
+ for finetuning the network
58
+ use_fid_inception : bool
59
+ If true, uses the pretrained Inception model used in Tensorflow's
60
+ FID implementation. If false, uses the pretrained Inception model
61
+ available in torchvision. The FID Inception model has different
62
+ weights and a slightly different structure from torchvision's
63
+ Inception model. If you want to compute FID scores, you are
64
+ strongly advised to set this parameter to true to get comparable
65
+ results.
66
+ """
67
+ super(InceptionV3, self).__init__()
68
+
69
+ self.resize_input = resize_input
70
+ self.normalize_input = normalize_input
71
+ self.output_blocks = sorted(output_blocks)
72
+ self.last_needed_block = max(output_blocks)
73
+
74
+ assert self.last_needed_block <= 3, \
75
+ 'Last possible output block index is 3'
76
+
77
+ self.blocks = nn.ModuleList()
78
+
79
+ if use_fid_inception:
80
+ inception = fid_inception_v3()
81
+ else:
82
+ inception = models.inception_v3(pretrained=True)
83
+
84
+ # Block 0: input to maxpool1
85
+ block0 = [
86
+ inception.Conv2d_1a_3x3,
87
+ inception.Conv2d_2a_3x3,
88
+ inception.Conv2d_2b_3x3,
89
+ nn.MaxPool2d(kernel_size=3, stride=2)
90
+ ]
91
+ self.blocks.append(nn.Sequential(*block0))
92
+
93
+ # Block 1: maxpool1 to maxpool2
94
+ if self.last_needed_block >= 1:
95
+ block1 = [
96
+ inception.Conv2d_3b_1x1,
97
+ inception.Conv2d_4a_3x3,
98
+ nn.MaxPool2d(kernel_size=3, stride=2)
99
+ ]
100
+ self.blocks.append(nn.Sequential(*block1))
101
+
102
+ # Block 2: maxpool2 to aux classifier
103
+ if self.last_needed_block >= 2:
104
+ block2 = [
105
+ inception.Mixed_5b,
106
+ inception.Mixed_5c,
107
+ inception.Mixed_5d,
108
+ inception.Mixed_6a,
109
+ inception.Mixed_6b,
110
+ inception.Mixed_6c,
111
+ inception.Mixed_6d,
112
+ inception.Mixed_6e,
113
+ ]
114
+ self.blocks.append(nn.Sequential(*block2))
115
+
116
+ # Block 3: aux classifier to final avgpool
117
+ if self.last_needed_block >= 3:
118
+ block3 = [
119
+ inception.Mixed_7a,
120
+ inception.Mixed_7b,
121
+ inception.Mixed_7c,
122
+ nn.AdaptiveAvgPool2d(output_size=(1, 1))
123
+ ]
124
+ self.blocks.append(nn.Sequential(*block3))
125
+
126
+ for param in self.parameters():
127
+ param.requires_grad = requires_grad
128
+
129
+ def forward(self, inp):
130
+ """Get Inception feature maps
131
+
132
+ Parameters
133
+ ----------
134
+ inp : torch.autograd.Variable
135
+ Input tensor of shape Bx3xHxW. Values are expected to be in
136
+ range (0, 1)
137
+
138
+ Returns
139
+ -------
140
+ List of torch.autograd.Variable, corresponding to the selected output
141
+ block, sorted ascending by index
142
+ """
143
+ outp = []
144
+ x = inp
145
+
146
+ if self.resize_input:
147
+ x = F.interpolate(x,
148
+ size=(299, 299),
149
+ mode='bilinear',
150
+ align_corners=False)
151
+
152
+ if self.normalize_input:
153
+ x = 2 * x - 1 # Scale from range (0, 1) to range (-1, 1)
154
+
155
+ for idx, block in enumerate(self.blocks):
156
+ x = block(x)
157
+ if idx in self.output_blocks:
158
+ outp.append(x)
159
+
160
+ if idx == self.last_needed_block:
161
+ break
162
+
163
+ return outp
164
+
165
+
166
+ def fid_inception_v3():
167
+ """Build pretrained Inception model for FID computation
168
+
169
+ The Inception model for FID computation uses a different set of weights
170
+ and has a slightly different structure than torchvision's Inception.
171
+
172
+ This method first constructs torchvision's Inception and then patches the
173
+ necessary parts that are different in the FID Inception model.
174
+ """
175
+ inception = models.inception_v3(num_classes=1008,
176
+ aux_logits=False,
177
+ pretrained=False)
178
+ inception.Mixed_5b = FIDInceptionA(192, pool_features=32)
179
+ inception.Mixed_5c = FIDInceptionA(256, pool_features=64)
180
+ inception.Mixed_5d = FIDInceptionA(288, pool_features=64)
181
+ inception.Mixed_6b = FIDInceptionC(768, channels_7x7=128)
182
+ inception.Mixed_6c = FIDInceptionC(768, channels_7x7=160)
183
+ inception.Mixed_6d = FIDInceptionC(768, channels_7x7=160)
184
+ inception.Mixed_6e = FIDInceptionC(768, channels_7x7=192)
185
+ inception.Mixed_7b = FIDInceptionE_1(1280)
186
+ inception.Mixed_7c = FIDInceptionE_2(2048)
187
+
188
+ state_dict = load_state_dict_from_url(FID_WEIGHTS_URL, progress=True)
189
+ inception.load_state_dict(state_dict)
190
+ return inception
191
+
192
+
193
+ class FIDInceptionA(models.inception.InceptionA):
194
+ """InceptionA block patched for FID computation"""
195
+ def __init__(self, in_channels, pool_features):
196
+ super(FIDInceptionA, self).__init__(in_channels, pool_features)
197
+
198
+ def forward(self, x):
199
+ branch1x1 = self.branch1x1(x)
200
+
201
+ branch5x5 = self.branch5x5_1(x)
202
+ branch5x5 = self.branch5x5_2(branch5x5)
203
+
204
+ branch3x3dbl = self.branch3x3dbl_1(x)
205
+ branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
206
+ branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)
207
+
208
+ # Patch: Tensorflow's average pool does not use the padded zero's in
209
+ # its average calculation
210
+ branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
211
+ count_include_pad=False)
212
+ branch_pool = self.branch_pool(branch_pool)
213
+
214
+ outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool]
215
+ return torch.cat(outputs, 1)
216
+
217
+
218
+ class FIDInceptionC(models.inception.InceptionC):
219
+ """InceptionC block patched for FID computation"""
220
+ def __init__(self, in_channels, channels_7x7):
221
+ super(FIDInceptionC, self).__init__(in_channels, channels_7x7)
222
+
223
+ def forward(self, x):
224
+ branch1x1 = self.branch1x1(x)
225
+
226
+ branch7x7 = self.branch7x7_1(x)
227
+ branch7x7 = self.branch7x7_2(branch7x7)
228
+ branch7x7 = self.branch7x7_3(branch7x7)
229
+
230
+ branch7x7dbl = self.branch7x7dbl_1(x)
231
+ branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl)
232
+ branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl)
233
+ branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl)
234
+ branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl)
235
+
236
+ # Patch: Tensorflow's average pool does not use the padded zero's in
237
+ # its average calculation
238
+ branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
239
+ count_include_pad=False)
240
+ branch_pool = self.branch_pool(branch_pool)
241
+
242
+ outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool]
243
+ return torch.cat(outputs, 1)
244
+
245
+
246
+ class FIDInceptionE_1(models.inception.InceptionE):
247
+ """First InceptionE block patched for FID computation"""
248
+ def __init__(self, in_channels):
249
+ super(FIDInceptionE_1, self).__init__(in_channels)
250
+
251
+ def forward(self, x):
252
+ branch1x1 = self.branch1x1(x)
253
+
254
+ branch3x3 = self.branch3x3_1(x)
255
+ branch3x3 = [
256
+ self.branch3x3_2a(branch3x3),
257
+ self.branch3x3_2b(branch3x3),
258
+ ]
259
+ branch3x3 = torch.cat(branch3x3, 1)
260
+
261
+ branch3x3dbl = self.branch3x3dbl_1(x)
262
+ branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
263
+ branch3x3dbl = [
264
+ self.branch3x3dbl_3a(branch3x3dbl),
265
+ self.branch3x3dbl_3b(branch3x3dbl),
266
+ ]
267
+ branch3x3dbl = torch.cat(branch3x3dbl, 1)
268
+
269
+ # Patch: Tensorflow's average pool does not use the padded zero's in
270
+ # its average calculation
271
+ branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
272
+ count_include_pad=False)
273
+ branch_pool = self.branch_pool(branch_pool)
274
+
275
+ outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
276
+ return torch.cat(outputs, 1)
277
+
278
+
279
+ class FIDInceptionE_2(models.inception.InceptionE):
280
+ """Second InceptionE block patched for FID computation"""
281
+ def __init__(self, in_channels):
282
+ super(FIDInceptionE_2, self).__init__(in_channels)
283
+
284
+ def forward(self, x):
285
+ branch1x1 = self.branch1x1(x)
286
+
287
+ branch3x3 = self.branch3x3_1(x)
288
+ branch3x3 = [
289
+ self.branch3x3_2a(branch3x3),
290
+ self.branch3x3_2b(branch3x3),
291
+ ]
292
+ branch3x3 = torch.cat(branch3x3, 1)
293
+
294
+ branch3x3dbl = self.branch3x3dbl_1(x)
295
+ branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
296
+ branch3x3dbl = [
297
+ self.branch3x3dbl_3a(branch3x3dbl),
298
+ self.branch3x3dbl_3b(branch3x3dbl),
299
+ ]
300
+ branch3x3dbl = torch.cat(branch3x3dbl, 1)
301
+
302
+ # Patch: The FID Inception model uses max pooling instead of average
303
+ # pooling. This is likely an error in this specific Inception
304
+ # implementation, as other Inception models use average pooling here
305
+ # (which matches the description in the paper).
306
+ branch_pool = F.max_pool2d(x, kernel_size=3, stride=1, padding=1)
307
+ branch_pool = self.branch_pool(branch_pool)
308
+
309
+ outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
310
+ return torch.cat(outputs, 1)
custom_data.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.utils.data import Dataset
3
+ import os
4
+ from natsort import natsorted
5
+ import cv2
6
+ import glob
7
+ import numpy as np
8
+ from PIL import Image
9
+ from skimage import io as img
10
+
11
+ class ImageAndMaskData(Dataset):
12
+
13
+ def __init__(self, img_dir, mask_dir, transform=None):
14
+
15
+
16
+ self.images = natsorted(glob.glob(img_dir + "/*"))
17
+ self.masks = natsorted(glob.glob(mask_dir + "/*"))
18
+
19
+ self.imgs_and_masks = list(zip(self.images, self.masks))
20
+
21
+ self.transform = transform
22
+
23
+ def __len__(self):
24
+
25
+ return len(self.imgs_and_masks)
26
+
27
+ def __getitem__(self, idx):
28
+
29
+ data = self.imgs_and_masks[idx]
30
+
31
+ img_path = data[0] # image
32
+ mask_path = data[1] # mask
33
+
34
+ #img = cv2.imread(img_path)
35
+ img = np.array(Image.open(img_path))
36
+ mask = np.array(Image.open(mask_path))[:,:,0:1] # take only one channel from mask
37
+ #print(mask.shape)
38
+ #print(mask.sum())
39
+
40
+ sample = np.concatenate((img, mask), axis=2)
41
+ #sample = torch.tensor(sample).to(torch.float)
42
+
43
+ #sample = img
44
+
45
+ sample = Image.fromarray(sample)
46
+
47
+ #sample = sample.permute((2, 0, 1))
48
+
49
+ # convert to 0,1 range
50
+ #sample = sample/255
51
+
52
+
53
+ #print(sample.shape)
54
+
55
+ #print(img.shape)
56
+ #print(mask.shape)
57
+ if self.transform:
58
+ sample = self.transform(sample)
59
+
60
+
61
+
62
+ return sample
63
+
64
+
65
+ # New functions to match with SinGAN-Seg process
66
+
67
+ def make_4_chs_img(image_path, mask_path):
68
+ im = img.imread(image_path)
69
+ mask = img.imread(mask_path)
70
+
71
+ # modifications - 22.02.2022
72
+ mask = (mask > 127)*255 # to get clean mask
73
+ # mask = 255 - (mask > 127)*255 # to get inverted mask
74
+ #print(np.unique(mask))
75
+
76
+ return np.concatenate((im, mask[:,:,0:1]), axis=2)
77
+
78
+ def norm(x):
79
+ out = (x -0.5) *2
80
+ return out.clamp(-1, 1)
81
+
82
+ def denorm(x):
83
+ out = (x + 1) / 2
84
+ return out.clamp(0, 1)
85
+
86
+ def np2torch(x):
87
+ #if opt.nc_im == 3 or opt.nc_im == 4: # added opt.nc_im == 4 by vajira to handle 4 channel image
88
+ x = x[:,:,:]
89
+ x = x.transpose((2, 0, 1))/255
90
+
91
+ x = torch.from_numpy(x)
92
+ #if not(opt.not_cuda):
93
+ # x = move_to_gpu(x, opt.device)
94
+ #x = x.type(torch.cuda.FloatTensor) if not(opt.not_cuda) else x.type(torch.FloatTensor)
95
+ x = x.type(torch.FloatTensor)
96
+ #x = x.type(torch.FloatTensor)
97
+ x = norm(x)
98
+ return x
99
+
100
+
101
+
102
+ class ImageAndMaskDataFromSinGAN(Dataset):
103
+
104
+ def __init__(self, img_dir, mask_dir, transform=None):
105
+
106
+
107
+ self.images = natsorted(glob.glob(img_dir + "/*"))
108
+ self.masks = natsorted(glob.glob(mask_dir + "/*"))
109
+
110
+ self.imgs_and_masks = list(zip(self.images, self.masks))
111
+
112
+ self.transform = transform
113
+
114
+ def __len__(self):
115
+
116
+ return len(self.imgs_and_masks)
117
+
118
+ def __getitem__(self, idx):
119
+
120
+ data = self.imgs_and_masks[idx]
121
+
122
+ image_path = data[0] # image
123
+ mask_path = data[1] # mask
124
+
125
+ #img = cv2.imread(img_path)
126
+ #img = np.array(Image.open(img_path))
127
+ # mask = np.array(Image.open(mask_path))[:,:,0:1] # take only one channel from mask
128
+ #print(mask.shape)
129
+ #print(mask.sum())
130
+
131
+ #sample = np.concatenate((img, mask), axis=2)
132
+ #sample = torch.tensor(sample).to(torch.float)
133
+
134
+ #sample = img
135
+
136
+ sample = make_4_chs_img(image_path, mask_path)#Image.fromarray(sample)
137
+
138
+ sample = np2torch(sample)
139
+
140
+ sample = sample[0:4,:,:]
141
+
142
+ #sample = sample.permute((2, 0, 1))
143
+
144
+ # convert to 0,1 range
145
+ #sample = sample/255
146
+
147
+
148
+ #print(sample.shape)
149
+
150
+ #print(img.shape)
151
+ #print(mask.shape)
152
+ if self.transform:
153
+ sample = self.transform(sample)
154
+
155
+
156
+
157
+ return sample
158
+
159
+
160
+
161
+
162
+ if __name__ == "__main__":
163
+
164
+ dataset = ImageAndMaskDataFromSinGAN("/work/vajira/DATA/kvasir_seg/real_images_root/real_images",
165
+ "/work/vajira/DATA/kvasir_seg/real_masks_root/real_masks")
166
+
167
+ print(dataset[1].shape)
168
+
169
+ #cv2.imwrite("test.png", dataset[1])
170
+
171
+
diffaug.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Differentiable Augmentation for Data-Efficient GAN Training
2
+ # Shengyu Zhao, Zhijian Liu, Ji Lin, Jun-Yan Zhu, and Song Han
3
+ # https://arxiv.org/pdf/2006.10738
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+
8
+
9
+ def DiffAugment(x, policy='', channels_first=True):
10
+ if policy:
11
+ if not channels_first:
12
+ x = x.permute(0, 3, 1, 2)
13
+ for p in policy.split(','):
14
+ for f in AUGMENT_FNS[p]:
15
+ x = f(x)
16
+ if not channels_first:
17
+ x = x.permute(0, 2, 3, 1)
18
+ x = x.contiguous()
19
+ return x
20
+
21
+
22
+ def rand_brightness(x):
23
+ x = x + (torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5)
24
+ return x
25
+
26
+
27
+ def rand_saturation(x):
28
+ x_mean = x.mean(dim=1, keepdim=True)
29
+ x = (x - x_mean) * (torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) * 2) + x_mean
30
+ return x
31
+
32
+
33
+ def rand_contrast(x):
34
+ x_mean = x.mean(dim=[1, 2, 3], keepdim=True)
35
+ x = (x - x_mean) * (torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) + 0.5) + x_mean
36
+ return x
37
+
38
+
39
+ def rand_translation(x, ratio=0.125):
40
+ shift_x, shift_y = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5)
41
+ translation_x = torch.randint(-shift_x, shift_x + 1, size=[x.size(0), 1, 1], device=x.device)
42
+ translation_y = torch.randint(-shift_y, shift_y + 1, size=[x.size(0), 1, 1], device=x.device)
43
+ grid_batch, grid_x, grid_y = torch.meshgrid(
44
+ torch.arange(x.size(0), dtype=torch.long, device=x.device),
45
+ torch.arange(x.size(2), dtype=torch.long, device=x.device),
46
+ torch.arange(x.size(3), dtype=torch.long, device=x.device),
47
+ )
48
+ grid_x = torch.clamp(grid_x + translation_x + 1, 0, x.size(2) + 1)
49
+ grid_y = torch.clamp(grid_y + translation_y + 1, 0, x.size(3) + 1)
50
+ x_pad = F.pad(x, [1, 1, 1, 1, 0, 0, 0, 0])
51
+ x = x_pad.permute(0, 2, 3, 1).contiguous()[grid_batch, grid_x, grid_y].permute(0, 3, 1, 2)
52
+ return x
53
+
54
+
55
+ def rand_cutout(x, ratio=0.5):
56
+ cutout_size = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5)
57
+ offset_x = torch.randint(0, x.size(2) + (1 - cutout_size[0] % 2), size=[x.size(0), 1, 1], device=x.device)
58
+ offset_y = torch.randint(0, x.size(3) + (1 - cutout_size[1] % 2), size=[x.size(0), 1, 1], device=x.device)
59
+ grid_batch, grid_x, grid_y = torch.meshgrid(
60
+ torch.arange(x.size(0), dtype=torch.long, device=x.device),
61
+ torch.arange(cutout_size[0], dtype=torch.long, device=x.device),
62
+ torch.arange(cutout_size[1], dtype=torch.long, device=x.device),
63
+ )
64
+ grid_x = torch.clamp(grid_x + offset_x - cutout_size[0] // 2, min=0, max=x.size(2) - 1)
65
+ grid_y = torch.clamp(grid_y + offset_y - cutout_size[1] // 2, min=0, max=x.size(3) - 1)
66
+ mask = torch.ones(x.size(0), x.size(2), x.size(3), dtype=x.dtype, device=x.device)
67
+ mask[grid_batch, grid_x, grid_y] = 0
68
+ x = x * mask.unsqueeze(1)
69
+ return x
70
+
71
+
72
+ AUGMENT_FNS = {
73
+ 'color': [rand_brightness, rand_saturation, rand_contrast],
74
+ 'translation': [rand_translation],
75
+ 'cutout': [rand_cutout],
76
+ }
eval.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from torch import optim
4
+ import torch.nn.functional as F
5
+ from torchvision.datasets import ImageFolder
6
+ from torch.utils.data import DataLoader
7
+ from torchvision import utils as vutils
8
+
9
+ import os
10
+ import random
11
+ import argparse
12
+ from tqdm import tqdm
13
+
14
+ from models import Generator
15
+
16
+
17
+ def load_params(model, new_param):
18
+ for p, new_p in zip(model.parameters(), new_param):
19
+ p.data.copy_(new_p)
20
+
21
+ def resize(img):
22
+ return F.interpolate(img, size=256)
23
+
24
+ def batch_generate(zs, netG, batch=8):
25
+ g_images = []
26
+ with torch.no_grad():
27
+ for i in range(len(zs)//batch):
28
+ g_images.append( netG(zs[i*batch:(i+1)*batch]).cpu() )
29
+ if len(zs)%batch>0:
30
+ g_images.append( netG(zs[-(len(zs)%batch):]).cpu() )
31
+ return torch.cat(g_images)
32
+
33
+ def batch_save(images, folder_name):
34
+ if not os.path.exists(folder_name):
35
+ os.mkdir(folder_name)
36
+ for i, image in enumerate(images):
37
+ vutils.save_image(image.add(1).mul(0.5), folder_name+'/%d.jpg'%i)
38
+
39
+
40
+ if __name__ == "__main__":
41
+ parser = argparse.ArgumentParser(
42
+ description='generate images'
43
+ )
44
+ parser.add_argument('--ckpt', type=str)
45
+ parser.add_argument('--artifacts', type=str, default=".", help='path to artifacts.')
46
+ parser.add_argument('--cuda', type=int, default=0, help='index of gpu to use')
47
+ parser.add_argument('--start_iter', type=int, default=6)
48
+ parser.add_argument('--end_iter', type=int, default=10)
49
+
50
+ parser.add_argument('--dist', type=str, default='.')
51
+ parser.add_argument('--size', type=int, default=256)
52
+ parser.add_argument('--batch', default=16, type=int, help='batch size')
53
+ parser.add_argument('--n_sample', type=int, default=2000)
54
+ parser.add_argument('--big', action='store_true')
55
+ parser.add_argument('--im_size', type=int, default=1024)
56
+ parser.set_defaults(big=False)
57
+ args = parser.parse_args()
58
+
59
+ noise_dim = 256
60
+ device = torch.device('cuda:%d'%(args.cuda))
61
+
62
+ net_ig = Generator( ngf=64, nz=noise_dim, nc=3, im_size=args.im_size)#, big=args.big )
63
+ net_ig.to(device)
64
+
65
+ for epoch in [10000*i for i in range(args.start_iter, args.end_iter+1)]:
66
+ ckpt = f"{args.artifacts}/models/{epoch}.pth"
67
+ checkpoint = torch.load(ckpt, map_location=lambda a,b: a)
68
+ # Remove prefix `module`.
69
+ checkpoint['g'] = {k.replace('module.', ''): v for k, v in checkpoint['g'].items()}
70
+ net_ig.load_state_dict(checkpoint['g'])
71
+ #load_params(net_ig, checkpoint['g_ema'])
72
+
73
+ #net_ig.eval()
74
+ print('load checkpoint success, epoch %d'%epoch)
75
+
76
+ net_ig.to(device)
77
+
78
+ del checkpoint
79
+
80
+ dist = 'eval_%d'%(epoch)
81
+ dist = os.path.join(dist, 'img')
82
+ os.makedirs(dist, exist_ok=True)
83
+
84
+ with torch.no_grad():
85
+ for i in tqdm(range(args.n_sample//args.batch)):
86
+ noise = torch.randn(args.batch, noise_dim).to(device)
87
+ g_imgs = net_ig(noise)[0]
88
+ g_imgs = F.interpolate(g_imgs, 512)
89
+ for j, g_img in enumerate( g_imgs ):
90
+ vutils.save_image(g_img.add(1).mul(0.5),
91
+ os.path.join(dist, '%d.png'%(i*args.batch+j)))#, normalize=True, range=(-1,1))
generate.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ ' Commented
4
+ python generate_4ch.py --dist '/work/vajira/DATA/FastGAN_polyps/generated_1k_set_0' --save_option "image_only"
5
+ python generate_4ch.py --dist '/work/vajira/DATA/FastGAN_polyps/generated_1k_set_1' --save_option "image_only"
6
+ python generate_4ch.py --dist '/work/vajira/DATA/FastGAN_polyps/generated_1k_set_2' --save_option "image_only"
7
+ python generate_4ch.py --dist '/work/vajira/DATA/FastGAN_polyps/generated_1k_set_3' --save_option "image_only"
8
+ python generate_4ch.py --dist '/work/vajira/DATA/FastGAN_polyps/generated_1k_set_4' --save_option "image_only"
9
+ '
10
+
11
+ for i in 5 10 15 20 25 30 35 40 45 50
12
+ do
13
+ for s in 1 2 3 4
14
+ do
15
+ echo "working on $i ok..."
16
+ python generate_4ch.py --ckpt "/work/vajira/DL/FastGAN-pytorch/train_results/test_4ch_num_img_${i}/models/all_50000.pth" --dist "/work/vajira/DATA/FastGAN_polyps/data_from_small_models_for_FID/gen_${i}_set_${s}" --save_option "image_only" --n_sample $i
17
+ done
18
+ done
generate_2.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+
4
+ python generate_4ch.py --dist '/work/vajira/DATA/FastGAN_polyps/generated_samples_to_paper' --save_option "image_and_mask" --n_sample 10
5
+
6
+
generate_4ch.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from torch import optim
4
+ import torch.nn.functional as F
5
+ from torchvision.datasets import ImageFolder
6
+ from torch.utils.data import DataLoader
7
+ from torchvision import utils as vutils
8
+
9
+ import os
10
+ import random
11
+ import argparse
12
+ from tqdm import tqdm
13
+
14
+ from models import Generator
15
+
16
+
17
+ def load_params(model, new_param):
18
+ for p, new_p in zip(model.parameters(), new_param):
19
+ p.data.copy_(new_p)
20
+
21
+ def resize(img):
22
+ return F.interpolate(img, size=256)
23
+
24
+ def batch_generate(zs, netG, batch=8):
25
+ g_images = []
26
+ with torch.no_grad():
27
+ for i in range(len(zs)//batch):
28
+ g_images.append( netG(zs[i*batch:(i+1)*batch]).cpu() )
29
+ if len(zs)%batch>0:
30
+ g_images.append( netG(zs[-(len(zs)%batch):]).cpu() )
31
+ return torch.cat(g_images)
32
+
33
+ def batch_save(images, folder_name):
34
+ if not os.path.exists(folder_name):
35
+ os.mkdir(folder_name)
36
+ for i, image in enumerate(images):
37
+ vutils.save_image(image.add(1).mul(0.5), folder_name+'/%d.jpg'%i)
38
+
39
+
40
+ if __name__ == "__main__":
41
+ parser = argparse.ArgumentParser(
42
+ description='generate images'
43
+ )
44
+ parser.add_argument('--ckpt', type=str, default="/work/vajira/DL/FastGAN-pytorch/train_results/test1_4ch/models/all_50000.pth")
45
+ parser.add_argument('--artifacts', type=str, default=".", help='path to artifacts.')
46
+ parser.add_argument('--cuda', type=int, default=0, help='index of gpu to use')
47
+ parser.add_argument('--start_iter', type=int, default=6)
48
+ parser.add_argument('--end_iter', type=int, default=10)
49
+
50
+ parser.add_argument('--dist', type=str, default='/work/vajira/DATA/FastGAN_polyps/test')
51
+ parser.add_argument('--size', type=int, default=256)
52
+ parser.add_argument('--batch', default=1, type=int, help='batch size')
53
+ parser.add_argument('--n_sample', type=int, default=1000)
54
+ parser.add_argument('--big', action='store_true')
55
+ parser.add_argument('--im_size', type=int, default=256)
56
+ parser.add_argument("--save_option", default="image_and_mask", help="Options to svae output, image_only, mask_only, image_and_mask", choices=["image_only","mask_only", "image_and_mask"])
57
+ parser.set_defaults(big=False)
58
+ args = parser.parse_args()
59
+
60
+ noise_dim = 256
61
+ device = torch.device('cuda:%d'%(args.cuda))
62
+
63
+ net_ig = Generator( ngf=64, nz=noise_dim, nc=4, im_size=args.im_size)#, big=args.big )
64
+ net_ig.to(device)
65
+
66
+ #for epoch in [10000*i for i in range(args.start_iter, args.end_iter+1)]:
67
+ ckpt = args.ckpt #f"{args.artifacts}/models/{epoch}.pth"
68
+ #checkpoint = torch.load(ckpt, map_location=lambda a,b: a)
69
+ checkpoint = torch.load(ckpt)
70
+ # Remove prefix `module`.
71
+ checkpoint['g'] = {k.replace('module.', ''): v for k, v in checkpoint['g'].items()}
72
+ net_ig.load_state_dict(checkpoint['g'])
73
+ #load_params(net_ig, checkpoint['g_ema'])
74
+
75
+ #net_ig.eval()
76
+ print("load checkpoint success")
77
+
78
+ net_ig.to(device)
79
+
80
+ del checkpoint
81
+
82
+ #dist = 'eval_%d'%(epoch)
83
+ #dist = os.path.join(args.dist, 'img')
84
+ dist = args.dist
85
+ os.makedirs(dist, exist_ok=True)
86
+
87
+ with torch.no_grad():
88
+ for i in tqdm(range(args.n_sample//args.batch)):
89
+ noise = torch.randn(args.batch, noise_dim).to(device)
90
+ g_imgs = net_ig(noise)[0]
91
+ g_imgs = F.interpolate(g_imgs, 512)
92
+
93
+
94
+ for j, g_img in enumerate( g_imgs ):
95
+ #print("img sahpe=", g_img.shape)
96
+ g_mask = g_img.add(1).mul(0.5)[-1, :, :].expand(3, -1, -1)
97
+ g_img = g_img.add(1).mul(0.5)[0:3, :, :]
98
+
99
+ # Clean generated data using clamping
100
+ g_mask = torch.clamp(g_mask, min=0, max=1)
101
+ g_img = torch.clamp(g_img, min=0, max=1)
102
+ #print(g_mask.type())
103
+ g_mask = (g_mask > 0.5) * 1.0
104
+ #print(g_mask.type())
105
+
106
+ #print("gmask_min:", g_mask.min())
107
+ #print("gmask_max:", g_mask.max())
108
+ #exit()
109
+
110
+ #print("img sahpe=", g_img.shape)
111
+
112
+ if args.save_option == "image_and_mask":
113
+ vutils.save_image(g_img,
114
+ os.path.join(dist, '%d_img.png'%(i*args.batch+j)))#, normalize=True, range=(-1,1))
115
+ vutils.save_image(g_mask,
116
+ os.path.join(dist, '%d_mask.png'%(i*args.batch+j))) #, normalize=True, range=(0,1))
117
+
118
+ elif args.save_option == "image_only":
119
+ vutils.save_image(g_img,
120
+ os.path.join(dist, '%d_img.png'%(i*args.batch+j)))#, normalize=True, range=(-1,1))
121
+
122
+ elif args.save_option == "mask_only":
123
+ vutils.save_image(g_mask,
124
+ os.path.join(dist, '%d_mask.png'%(i*args.batch+j)))#, normalize=True, range=(-1,1))
125
+ else:
126
+ print("wrong choise to save option.")
models.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn.utils import spectral_norm
4
+ import torch.nn.functional as F
5
+
6
+ import random
7
+
8
+ seq = nn.Sequential
9
+
10
+ def weights_init(m):
11
+ classname = m.__class__.__name__
12
+ if classname.find('Conv') != -1:
13
+ try:
14
+ m.weight.data.normal_(0.0, 0.02)
15
+ except:
16
+ pass
17
+ elif classname.find('BatchNorm') != -1:
18
+ m.weight.data.normal_(1.0, 0.02)
19
+ m.bias.data.fill_(0)
20
+
21
+ def conv2d(*args, **kwargs):
22
+ return spectral_norm(nn.Conv2d(*args, **kwargs))
23
+
24
+ def convTranspose2d(*args, **kwargs):
25
+ return spectral_norm(nn.ConvTranspose2d(*args, **kwargs))
26
+
27
+ def batchNorm2d(*args, **kwargs):
28
+ return nn.BatchNorm2d(*args, **kwargs)
29
+
30
+ def linear(*args, **kwargs):
31
+ return spectral_norm(nn.Linear(*args, **kwargs))
32
+
33
+ class PixelNorm(nn.Module):
34
+ def forward(self, input):
35
+ return input * torch.rsqrt(torch.mean(input ** 2, dim=1, keepdim=True) + 1e-8)
36
+
37
+ class Reshape(nn.Module):
38
+ def __init__(self, shape):
39
+ super().__init__()
40
+ self.target_shape = shape
41
+
42
+ def forward(self, feat):
43
+ batch = feat.shape[0]
44
+ return feat.view(batch, *self.target_shape)
45
+
46
+
47
+ class GLU(nn.Module):
48
+ def forward(self, x):
49
+ nc = x.size(1)
50
+ assert nc % 2 == 0, 'channels dont divide 2!'
51
+ nc = int(nc/2)
52
+ return x[:, :nc] * torch.sigmoid(x[:, nc:])
53
+
54
+
55
+ class NoiseInjection(nn.Module):
56
+ def __init__(self):
57
+ super().__init__()
58
+
59
+ self.weight = nn.Parameter(torch.zeros(1), requires_grad=True)
60
+
61
+ def forward(self, feat, noise=None):
62
+ if noise is None:
63
+ batch, _, height, width = feat.shape
64
+ noise = torch.randn(batch, 1, height, width).to(feat.device)
65
+
66
+ return feat + self.weight * noise
67
+
68
+
69
+ class Swish(nn.Module):
70
+ def forward(self, feat):
71
+ return feat * torch.sigmoid(feat)
72
+
73
+
74
+ class SEBlock(nn.Module):
75
+ def __init__(self, ch_in, ch_out):
76
+ super().__init__()
77
+
78
+ self.main = nn.Sequential( nn.AdaptiveAvgPool2d(4),
79
+ conv2d(ch_in, ch_out, 4, 1, 0, bias=False), Swish(),
80
+ conv2d(ch_out, ch_out, 1, 1, 0, bias=False), nn.Sigmoid() )
81
+
82
+ def forward(self, feat_small, feat_big):
83
+ return feat_big * self.main(feat_small)
84
+
85
+
86
+ class InitLayer(nn.Module):
87
+ def __init__(self, nz, channel):
88
+ super().__init__()
89
+
90
+ self.init = nn.Sequential(
91
+ convTranspose2d(nz, channel*2, 4, 1, 0, bias=False),
92
+ batchNorm2d(channel*2), GLU() )
93
+
94
+ def forward(self, noise):
95
+ noise = noise.view(noise.shape[0], -1, 1, 1)
96
+ return self.init(noise)
97
+
98
+
99
+ def UpBlock(in_planes, out_planes):
100
+ block = nn.Sequential(
101
+ nn.Upsample(scale_factor=2, mode='nearest'),
102
+ conv2d(in_planes, out_planes*2, 3, 1, 1, bias=False),
103
+ #convTranspose2d(in_planes, out_planes*2, 4, 2, 1, bias=False),
104
+ batchNorm2d(out_planes*2), GLU())
105
+ return block
106
+
107
+
108
+ def UpBlockComp(in_planes, out_planes):
109
+ block = nn.Sequential(
110
+ nn.Upsample(scale_factor=2, mode='nearest'),
111
+ conv2d(in_planes, out_planes*2, 3, 1, 1, bias=False),
112
+ #convTranspose2d(in_planes, out_planes*2, 4, 2, 1, bias=False),
113
+ NoiseInjection(),
114
+ batchNorm2d(out_planes*2), GLU(),
115
+ conv2d(out_planes, out_planes*2, 3, 1, 1, bias=False),
116
+ NoiseInjection(),
117
+ batchNorm2d(out_planes*2), GLU()
118
+ )
119
+ return block
120
+
121
+
122
+ class Generator(nn.Module):
123
+ def __init__(self, ngf=64, nz=100, nc=3, im_size=1024):
124
+ super(Generator, self).__init__()
125
+
126
+ nfc_multi = {4:16, 8:8, 16:4, 32:2, 64:2, 128:1, 256:0.5, 512:0.25, 1024:0.125}
127
+ nfc = {}
128
+ for k, v in nfc_multi.items():
129
+ nfc[k] = int(v*ngf)
130
+
131
+ self.im_size = im_size
132
+
133
+ self.init = InitLayer(nz, channel=nfc[4])
134
+
135
+ self.feat_8 = UpBlockComp(nfc[4], nfc[8])
136
+ self.feat_16 = UpBlock(nfc[8], nfc[16])
137
+ self.feat_32 = UpBlockComp(nfc[16], nfc[32])
138
+ self.feat_64 = UpBlock(nfc[32], nfc[64])
139
+ self.feat_128 = UpBlockComp(nfc[64], nfc[128])
140
+ self.feat_256 = UpBlock(nfc[128], nfc[256])
141
+
142
+ self.se_64 = SEBlock(nfc[4], nfc[64])
143
+ self.se_128 = SEBlock(nfc[8], nfc[128])
144
+ self.se_256 = SEBlock(nfc[16], nfc[256])
145
+
146
+ self.to_128 = conv2d(nfc[128], nc, 1, 1, 0, bias=False)
147
+ self.to_big = conv2d(nfc[im_size], nc, 3, 1, 1, bias=False)
148
+
149
+ if im_size > 256:
150
+ self.feat_512 = UpBlockComp(nfc[256], nfc[512])
151
+ self.se_512 = SEBlock(nfc[32], nfc[512])
152
+ if im_size > 512:
153
+ self.feat_1024 = UpBlock(nfc[512], nfc[1024])
154
+
155
+ def forward(self, input):
156
+
157
+ feat_4 = self.init(input)
158
+ feat_8 = self.feat_8(feat_4)
159
+ feat_16 = self.feat_16(feat_8)
160
+ feat_32 = self.feat_32(feat_16)
161
+
162
+ feat_64 = self.se_64( feat_4, self.feat_64(feat_32) )
163
+
164
+ feat_128 = self.se_128( feat_8, self.feat_128(feat_64) )
165
+
166
+ feat_256 = self.se_256( feat_16, self.feat_256(feat_128) )
167
+
168
+ if self.im_size == 256:
169
+ return [self.to_big(feat_256), self.to_128(feat_128)]
170
+
171
+ feat_512 = self.se_512( feat_32, self.feat_512(feat_256) )
172
+ if self.im_size == 512:
173
+ return [self.to_big(feat_512), self.to_128(feat_128)]
174
+
175
+ feat_1024 = self.feat_1024(feat_512)
176
+
177
+ im_128 = torch.tanh(self.to_128(feat_128))
178
+ im_1024 = torch.tanh(self.to_big(feat_1024))
179
+
180
+ return [im_1024, im_128]
181
+
182
+
183
+ class DownBlock(nn.Module):
184
+ def __init__(self, in_planes, out_planes):
185
+ super(DownBlock, self).__init__()
186
+
187
+ self.main = nn.Sequential(
188
+ conv2d(in_planes, out_planes, 4, 2, 1, bias=False),
189
+ batchNorm2d(out_planes), nn.LeakyReLU(0.2, inplace=True),
190
+ )
191
+
192
+ def forward(self, feat):
193
+ return self.main(feat)
194
+
195
+
196
+ class DownBlockComp(nn.Module):
197
+ def __init__(self, in_planes, out_planes):
198
+ super(DownBlockComp, self).__init__()
199
+
200
+ self.main = nn.Sequential(
201
+ conv2d(in_planes, out_planes, 4, 2, 1, bias=False),
202
+ batchNorm2d(out_planes), nn.LeakyReLU(0.2, inplace=True),
203
+ conv2d(out_planes, out_planes, 3, 1, 1, bias=False),
204
+ batchNorm2d(out_planes), nn.LeakyReLU(0.2)
205
+ )
206
+
207
+ self.direct = nn.Sequential(
208
+ nn.AvgPool2d(2, 2),
209
+ conv2d(in_planes, out_planes, 1, 1, 0, bias=False),
210
+ batchNorm2d(out_planes), nn.LeakyReLU(0.2))
211
+
212
+ def forward(self, feat):
213
+ return (self.main(feat) + self.direct(feat)) / 2
214
+
215
+
216
+ class Discriminator(nn.Module):
217
+ def __init__(self, ndf=64, nc=3, im_size=512):
218
+ super(Discriminator, self).__init__()
219
+ self.ndf = ndf
220
+ self.im_size = im_size
221
+
222
+ nfc_multi = {4:16, 8:16, 16:8, 32:4, 64:2, 128:1, 256:0.5, 512:0.25, 1024:0.125}
223
+ nfc = {}
224
+ for k, v in nfc_multi.items():
225
+ nfc[k] = int(v*ndf)
226
+
227
+ if im_size == 1024:
228
+ self.down_from_big = nn.Sequential(
229
+ conv2d(nc, nfc[1024], 4, 2, 1, bias=False),
230
+ nn.LeakyReLU(0.2, inplace=True),
231
+ conv2d(nfc[1024], nfc[512], 4, 2, 1, bias=False),
232
+ batchNorm2d(nfc[512]),
233
+ nn.LeakyReLU(0.2, inplace=True))
234
+ elif im_size == 512:
235
+ self.down_from_big = nn.Sequential(
236
+ conv2d(nc, nfc[512], 4, 2, 1, bias=False),
237
+ nn.LeakyReLU(0.2, inplace=True) )
238
+ elif im_size == 256:
239
+ self.down_from_big = nn.Sequential(
240
+ conv2d(nc, nfc[512], 3, 1, 1, bias=False),
241
+ nn.LeakyReLU(0.2, inplace=True) )
242
+
243
+ self.down_4 = DownBlockComp(nfc[512], nfc[256])
244
+ self.down_8 = DownBlockComp(nfc[256], nfc[128])
245
+ self.down_16 = DownBlockComp(nfc[128], nfc[64])
246
+ self.down_32 = DownBlockComp(nfc[64], nfc[32])
247
+ self.down_64 = DownBlockComp(nfc[32], nfc[16])
248
+
249
+ self.rf_big = nn.Sequential(
250
+ conv2d(nfc[16] , nfc[8], 1, 1, 0, bias=False),
251
+ batchNorm2d(nfc[8]), nn.LeakyReLU(0.2, inplace=True),
252
+ conv2d(nfc[8], 1, 4, 1, 0, bias=False))
253
+
254
+ self.se_2_16 = SEBlock(nfc[512], nfc[64])
255
+ self.se_4_32 = SEBlock(nfc[256], nfc[32])
256
+ self.se_8_64 = SEBlock(nfc[128], nfc[16])
257
+
258
+ self.down_from_small = nn.Sequential(
259
+ conv2d(nc, nfc[256], 4, 2, 1, bias=False),
260
+ nn.LeakyReLU(0.2, inplace=True),
261
+ DownBlock(nfc[256], nfc[128]),
262
+ DownBlock(nfc[128], nfc[64]),
263
+ DownBlock(nfc[64], nfc[32]), )
264
+
265
+ self.rf_small = conv2d(nfc[32], 1, 4, 1, 0, bias=False)
266
+
267
+ self.decoder_big = SimpleDecoder(nfc[16], nc)
268
+ self.decoder_part = SimpleDecoder(nfc[32], nc)
269
+ self.decoder_small = SimpleDecoder(nfc[32], nc)
270
+
271
+ def forward(self, imgs, label, part=None):
272
+ if type(imgs) is not list:
273
+ imgs = [F.interpolate(imgs, size=self.im_size), F.interpolate(imgs, size=128)]
274
+
275
+ feat_2 = self.down_from_big(imgs[0])
276
+ feat_4 = self.down_4(feat_2)
277
+ feat_8 = self.down_8(feat_4)
278
+
279
+ feat_16 = self.down_16(feat_8)
280
+ feat_16 = self.se_2_16(feat_2, feat_16)
281
+
282
+ feat_32 = self.down_32(feat_16)
283
+ feat_32 = self.se_4_32(feat_4, feat_32)
284
+
285
+ feat_last = self.down_64(feat_32)
286
+ feat_last = self.se_8_64(feat_8, feat_last)
287
+
288
+ #rf_0 = torch.cat([self.rf_big_1(feat_last).view(-1),self.rf_big_2(feat_last).view(-1)])
289
+ #rff_big = torch.sigmoid(self.rf_factor_big)
290
+ rf_0 = self.rf_big(feat_last).view(-1)
291
+
292
+ feat_small = self.down_from_small(imgs[1])
293
+ #rf_1 = torch.cat([self.rf_small_1(feat_small).view(-1),self.rf_small_2(feat_small).view(-1)])
294
+ rf_1 = self.rf_small(feat_small).view(-1)
295
+
296
+ if label=='real':
297
+ rec_img_big = self.decoder_big(feat_last)
298
+ rec_img_small = self.decoder_small(feat_small)
299
+
300
+ assert part is not None
301
+ rec_img_part = None
302
+ if part==0:
303
+ rec_img_part = self.decoder_part(feat_32[:,:,:8,:8])
304
+ if part==1:
305
+ rec_img_part = self.decoder_part(feat_32[:,:,:8,8:])
306
+ if part==2:
307
+ rec_img_part = self.decoder_part(feat_32[:,:,8:,:8])
308
+ if part==3:
309
+ rec_img_part = self.decoder_part(feat_32[:,:,8:,8:])
310
+
311
+ return torch.cat([rf_0, rf_1]) , [rec_img_big, rec_img_small, rec_img_part]
312
+
313
+ return torch.cat([rf_0, rf_1])
314
+
315
+
316
+ class SimpleDecoder(nn.Module):
317
+ """docstring for CAN_SimpleDecoder"""
318
+ def __init__(self, nfc_in=64, nc=3):
319
+ super(SimpleDecoder, self).__init__()
320
+
321
+ nfc_multi = {4:16, 8:8, 16:4, 32:2, 64:2, 128:1, 256:0.5, 512:0.25, 1024:0.125}
322
+ nfc = {}
323
+ for k, v in nfc_multi.items():
324
+ nfc[k] = int(v*32)
325
+
326
+ def upBlock(in_planes, out_planes):
327
+ block = nn.Sequential(
328
+ nn.Upsample(scale_factor=2, mode='nearest'),
329
+ conv2d(in_planes, out_planes*2, 3, 1, 1, bias=False),
330
+ batchNorm2d(out_planes*2), GLU())
331
+ return block
332
+
333
+ self.main = nn.Sequential( nn.AdaptiveAvgPool2d(8),
334
+ upBlock(nfc_in, nfc[16]) ,
335
+ upBlock(nfc[16], nfc[32]),
336
+ upBlock(nfc[32], nfc[64]),
337
+ upBlock(nfc[64], nfc[128]),
338
+ conv2d(nfc[128], nc, 3, 1, 1, bias=False),
339
+ nn.Tanh() )
340
+
341
+ def forward(self, input):
342
+ # input shape: c x 4 x 4
343
+ return self.main(input)
344
+
345
+ from random import randint
346
+ def random_crop(image, size):
347
+ h, w = image.shape[2:]
348
+ ch = randint(0, h-size-1)
349
+ cw = randint(0, w-size-1)
350
+ return image[:,:,ch:ch+size,cw:cw+size]
351
+
352
+ class TextureDiscriminator(nn.Module):
353
+ def __init__(self, ndf=64, nc=3, im_size=512):
354
+ super(TextureDiscriminator, self).__init__()
355
+ self.ndf = ndf
356
+ self.im_size = im_size
357
+
358
+ nfc_multi = {4:16, 8:8, 16:8, 32:4, 64:2, 128:1, 256:0.5, 512:0.25, 1024:0.125}
359
+ nfc = {}
360
+ for k, v in nfc_multi.items():
361
+ nfc[k] = int(v*ndf)
362
+
363
+ self.down_from_small = nn.Sequential(
364
+ conv2d(nc, nfc[256], 4, 2, 1, bias=False),
365
+ nn.LeakyReLU(0.2, inplace=True),
366
+ DownBlock(nfc[256], nfc[128]),
367
+ DownBlock(nfc[128], nfc[64]),
368
+ DownBlock(nfc[64], nfc[32]), )
369
+ self.rf_small = nn.Sequential(
370
+ conv2d(nfc[16], 1, 4, 1, 0, bias=False))
371
+
372
+ self.decoder_small = SimpleDecoder(nfc[32], nc)
373
+
374
+ def forward(self, img, label):
375
+ img = random_crop(img, size=128)
376
+
377
+ feat_small = self.down_from_small(img)
378
+ rf = self.rf_small(feat_small).view(-1)
379
+
380
+ if label=='real':
381
+ rec_img_small = self.decoder_small(feat_small)
382
+
383
+ return rf, rec_img_small, img
384
+
385
+ return rf
operation.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import torch
4
+ import torch.utils.data as data
5
+ from torch.utils.data import Dataset
6
+ from PIL import Image
7
+ from copy import deepcopy
8
+ import shutil
9
+ import json
10
+
11
+ def InfiniteSampler(n):
12
+ """Data sampler"""
13
+ i = n - 1
14
+ order = np.random.permutation(n)
15
+ while True:
16
+ yield order[i]
17
+ i += 1
18
+ if i >= n:
19
+ np.random.seed()
20
+ order = np.random.permutation(n)
21
+ i = 0
22
+
23
+
24
+ class InfiniteSamplerWrapper(data.sampler.Sampler):
25
+ """Data sampler wrapper"""
26
+ def __init__(self, data_source):
27
+ self.num_samples = len(data_source)
28
+
29
+ def __iter__(self):
30
+ return iter(InfiniteSampler(self.num_samples))
31
+
32
+ def __len__(self):
33
+ return 2 ** 31
34
+
35
+
36
+ def copy_G_params(model):
37
+ flatten = deepcopy(list(p.data for p in model.parameters()))
38
+ return flatten
39
+
40
+
41
+ def load_params(model, new_param):
42
+ for p, new_p in zip(model.parameters(), new_param):
43
+ p.data.copy_(new_p)
44
+
45
+
46
+ def get_dir(args):
47
+ task_name = 'train_results/' + args.name
48
+ saved_model_folder = os.path.join( task_name, 'models')
49
+ saved_image_folder = os.path.join( task_name, 'images')
50
+
51
+ os.makedirs(saved_model_folder, exist_ok=True)
52
+ os.makedirs(saved_image_folder, exist_ok=True)
53
+
54
+ for f in os.listdir('./'):
55
+ if '.py' in f:
56
+ shutil.copy(f, task_name+'/'+f)
57
+
58
+ with open( os.path.join(saved_model_folder, '../args.txt'), 'w') as f:
59
+ json.dump(args.__dict__, f, indent=2)
60
+
61
+ return saved_model_folder, saved_image_folder
62
+
63
+
64
+ class ImageFolder(Dataset):
65
+ """docstring for ArtDataset"""
66
+ def __init__(self, root, transform=None):
67
+ super( ImageFolder, self).__init__()
68
+ self.root = root
69
+
70
+ self.frame = self._parse_frame()
71
+ self.transform = transform
72
+
73
+ def _parse_frame(self):
74
+ frame = []
75
+ img_names = os.listdir(self.root)
76
+ img_names.sort()
77
+ for i in range(len(img_names)):
78
+ image_path = os.path.join(self.root, img_names[i])
79
+ if image_path[-4:] == '.jpg' or image_path[-4:] == '.png' or image_path[-5:] == '.jpeg':
80
+ frame.append(image_path)
81
+ return frame
82
+
83
+ def __len__(self):
84
+ return len(self.frame)
85
+
86
+ def __getitem__(self, idx):
87
+ file = self.frame[idx]
88
+ img = Image.open(file).convert('RGB')
89
+
90
+ if self.transform:
91
+ img = self.transform(img)
92
+
93
+ return img
94
+
95
+
96
+
97
+ from io import BytesIO
98
+ import lmdb
99
+ from torch.utils.data import Dataset
100
+
101
+
102
+ class MultiResolutionDataset(Dataset):
103
+ def __init__(self, path, transform, resolution=256):
104
+ self.env = lmdb.open(
105
+ path,
106
+ max_readers=32,
107
+ readonly=True,
108
+ lock=False,
109
+ readahead=False,
110
+ meminit=False,
111
+ )
112
+
113
+ if not self.env:
114
+ raise IOError('Cannot open lmdb dataset', path)
115
+
116
+ with self.env.begin(write=False) as txn:
117
+ self.length = int(txn.get('length'.encode('utf-8')).decode('utf-8'))
118
+
119
+ self.resolution = resolution
120
+ self.transform = transform
121
+
122
+ def __len__(self):
123
+ return self.length
124
+
125
+ def __getitem__(self, index):
126
+ with self.env.begin(write=False) as txn:
127
+ key = f'{self.resolution}-{str(index).zfill(5)}'.encode('utf-8')
128
+ img_bytes = txn.get(key)
129
+ #key_asp = f'aspect_ratio-{str(index).zfill(5)}'.encode('utf-8')
130
+ #aspect_ratio = float(txn.get(key_asp).decode())
131
+
132
+ buffer = BytesIO(img_bytes)
133
+ img = Image.open(buffer)
134
+ img = self.transform(img)
135
+
136
+ return img
137
+
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ tqdm==4.56.0
3
+ scipy==1.6.0
4
+ scikit-image==0.18.2
5
+ ipdb==0.13.4
6
+ pandas==1.2.1
7
+ lmdb==1.0.0
8
+ opencv-python==4.5.1.48
9
+ easing-functions==1.0.4
10
+ torch
11
+ torchvision
scripts/find_nearest_neighbor.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from eval import load_params
2
+ import torch
3
+ from torch import nn
4
+ from torch import optim
5
+ import torch.nn.functional as F
6
+ from torchvision.datasets import ImageFolder
7
+ from torch.utils.data import DataLoader
8
+ from torchvision import utils as vutils
9
+ from torchvision import transforms
10
+ import os
11
+ import random
12
+ import argparse
13
+ from tqdm import tqdm
14
+
15
+ from models import Generator
16
+ from operation import load_params, InfiniteSamplerWrapper
17
+
18
+ noise_dim = 256
19
+ device = torch.device('cuda:%d'%(0))
20
+
21
+ im_size = 512
22
+ net_ig = Generator( ngf=64, nz=noise_dim, nc=3, im_size=im_size)#, big=args.big )
23
+ net_ig.to(device)
24
+
25
+ epoch = 50000
26
+ ckpt = './models/all_%d.pth'%(epoch)
27
+ checkpoint = torch.load(ckpt, map_location=lambda a,b: a)
28
+ net_ig.load_state_dict(checkpoint['g'])
29
+ load_params(net_ig, checkpoint['g_ema'])
30
+
31
+ batch = 8
32
+ noise = torch.randn(batch, noise_dim).to(device)
33
+ g_imgs = net_ig(noise)[0]
34
+
35
+ vutils.save_image(g_imgs.add(1).mul(0.5),
36
+ os.path.join('./', '%d.png'%(2)))
37
+
38
+
39
+ transform_list = [
40
+ transforms.Resize((int(256),int(256))),
41
+ transforms.ToTensor(),
42
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
43
+ ]
44
+ trans = transforms.Compose(transform_list)
45
+ data_root = '/media/database/images/first_1k'
46
+ dataset = ImageFolder(root=data_root, transform=trans)
47
+
48
+ import lpips
49
+ percept = lpips.PerceptualLoss(model='net-lin', net='vgg', use_gpu=True)
50
+
51
+ the_image = g_imgs[0].unsqueeze(0)
52
+ def find_closest(the_image):
53
+ the_image = F.interpolate(the_image, size=256)
54
+ small = 100
55
+ close_image = None
56
+ for i in tqdm(range(len(dataset))):
57
+ real_iamge = dataset[i][0].unsqueeze(0).to(device)
58
+
59
+ dis = percept(the_image, real_iamge).sum()
60
+ if dis < small:
61
+ small = dis
62
+ close_image = real_iamge
63
+ return close_image, small
64
+
65
+ all_dist = []
66
+ batch = 8
67
+ result_path = 'nn_track'
68
+ import os
69
+ os.makedirs(result_path, exist_ok=True)
70
+ for j in range(8):
71
+ with torch.no_grad():
72
+ noise = torch.randn(batch, noise_dim).to(device)
73
+ g_imgs = net_ig(noise)[0]
74
+
75
+ for n in range(batch):
76
+ the_image = g_imgs[n].unsqueeze(0)
77
+
78
+ close_0, dis = find_closest(the_image)
79
+
80
+ vutils.save_image(torch.cat([F.interpolate(the_image,256), close_0]).add(1).mul(0.5), \
81
+ result_path+'/nn_%d.jpg'%(j*batch+n))
82
+ all_dist.append(dis.view(1))
83
+
84
+ new_all_dist = []
85
+ for v in all_dist:
86
+ new_all_dist.append(v.view(1))
87
+ print(torch.cat(new_all_dist).mean())
scripts/generate_video.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from easing_functions.easing import LinearInOut
2
+ import torch
3
+ import pandas as pd
4
+ from torchvision import utils as vutils
5
+ import os
6
+ import cv2
7
+ from tqdm import tqdm
8
+ from scipy import io
9
+ import numpy as np
10
+ import argparse
11
+
12
+ from easing_functions import QuadEaseInOut
13
+ from easing_functions import SineEaseIn, SineEaseInOut, SineEaseOut
14
+ from easing_functions import ElasticEaseIn, ElasticEaseInOut, ElasticEaseOut
15
+
16
+ ease_fn_dict = {'QuadEaseInOut': QuadEaseInOut,
17
+ 'SineEaseIn': SineEaseIn,
18
+ 'SineEaseInOut': SineEaseInOut,
19
+ 'SineEaseOut': SineEaseOut,
20
+ 'ElasticEaseIn': ElasticEaseIn,
21
+ 'ElasticEaseInOut': ElasticEaseInOut,
22
+ 'ElasticEaseOut': ElasticEaseOut,
23
+ 'Linear': LinearInOut}
24
+
25
+ def interpolate(z1, z2, num_interp):
26
+ # this is a "first frame included, last frame excluded" interpolation
27
+ w = torch.linspace(0, 1, num_interp+1)
28
+ interp_zs = []
29
+ for n in range(num_interp):
30
+ interp_zs.append( (z2*w[n].item() + z1*(1-w[n].item())).unsqueeze(0) )
31
+ return torch.cat(interp_zs)
32
+
33
+
34
+
35
+ def interpolate_ease_inout(z1, z2, num_interp, ease_fn, model_type='freeform'):
36
+ # this is a "first frame included, last frame excluded" interpolation
37
+ w = ease_fn(start=0, end=1, duration=num_interp+1)
38
+ interp_zs = []
39
+
40
+ # just to make sure the latent vectors in the right shape
41
+ if model_type == 'freeform':
42
+ z1 = z1.view(1, -1)
43
+ z2 = z2.view(1, -1)
44
+ if model_type == 'stylegan2':
45
+ if type(z1) is list:
46
+ z1 = [z1[0].view(1, -1), z1[1].view(1, -1)]
47
+ else:
48
+ z1 = [z1.view(1, -1), z1.view(1, -1)]
49
+ if type(z2) is list:
50
+ z2 = [z2[0].view(1, -1), z2[1].view(1, -1)]
51
+ else:
52
+ z2 = [z2.view(1, -1), z2.view(1, -1)]
53
+
54
+ for n in range(num_interp):
55
+ if model_type == 'freeform':
56
+ interp_zs.append( z2*w.ease(n) + z1*(1-w.ease(n)) )
57
+ if model_type == 'stylegan2':
58
+ interp_zs.append( [ z2[0]*w.ease(n) + z1[0]*(1-w.ease(n)),
59
+ z2[1]*w.ease(n) + z1[1]*(1-w.ease(n)) ] )
60
+ return interp_zs
61
+
62
+ @torch.no_grad()
63
+ def net_generate(netG, z, model_type='freeform', im_size=1024):
64
+
65
+ if model_type == 'stylegan2':
66
+ z_contents = []
67
+ z_styles = []
68
+ for zidx in range(len(z)):
69
+ z_contents.append(z[zidx][0])
70
+ z_styles.append(z[zidx][1])
71
+ z = [ torch.cat(z_contents), torch.cat(z_styles) ]
72
+ gimg = netG( z, inject_index=8, input_is_latent=True, randomize_noise=False )[0].cpu()
73
+ elif model_type == 'freeform':
74
+ z = torch.cat(z)
75
+ gimg = netG(z)[0].cpu()
76
+
77
+ return torch.nn.functional.interpolate(gimg, im_size)
78
+
79
+ def batch_generate_and_save(netG, zs, folder_name, batch_size=8, model_type='freeform', im_size=1024):
80
+ # zs is a list of vectors if model is freeform
81
+ # zs is a list of lists, each list is 2 vectors, if model is stylegan
82
+ t = 0
83
+ num = 0
84
+ if len(zs) < batch_size:
85
+ gimgs = net_generate(netG, zs, model_type, im_size=im_size).cpu()
86
+ for image in gimgs:
87
+ vutils.save_image( image.add(1).mul(0.5), folder_name+"/%d.jpg"%(num) )
88
+ num += 1
89
+
90
+ for k in tqdm(range(len(zs)//batch_size)):
91
+ gimgs = net_generate(netG, zs[k*batch_size:(k+1)*batch_size], model_type, im_size=im_size)
92
+ for image in gimgs:
93
+ vutils.save_image( image.add(1).mul(0.5), folder_name+"/%d.jpg"%(num) )
94
+ num += 1
95
+ t = k
96
+
97
+ if len(zs)%batch_size>0:
98
+ gimgs = net_generate(netG, zs[(t+1)*batch_size:], model_type, im_size=im_size)
99
+ for image in gimgs:
100
+ vutils.save_image( image.add(1).mul(0.5), folder_name+"/%d.jpg"%(num) )
101
+ num += 1
102
+
103
+
104
+
105
+ def batch_save(images, folder_name, start_num=0):
106
+ os.makedirs(folder_name, exist_ok=True)
107
+ num = start_num
108
+ for image in images:
109
+ vutils.save_image( image.add(1).mul(0.5), folder_name+"/%d.jpg"%(num) )
110
+ num += 1
111
+
112
+
113
+ def read_img_and_make_video(dist, video_name, fps):
114
+ img_array = []
115
+ for i in tqdm(range(len(os.listdir(dist)))):
116
+ try:
117
+ filename = dist+'/%d.jpg'%(i)
118
+ img = cv2.imread(filename)
119
+ height, width, layers = img.shape
120
+ size = (width,height)
121
+ img_array.append(img)
122
+ except:
123
+ print('error at: %d'%i)
124
+
125
+ if '.mp4' not in video_name:
126
+ video_name += '.mp4'
127
+ out = cv2.VideoWriter(video_name,cv2.VideoWriter_fourcc(*'mp4v'), fps, size)
128
+ for i in range(len(img_array)):
129
+ out.write(img_array[i])
130
+ out.release()
131
+
132
+ from shutil import rmtree
133
+
134
+ def make_video_from_latents(net, selected_latents, frames_dist_folder, video_name, fps, video_length, ease_fn, model_type, im_size=1024):
135
+ # selected_latents: the latent noise of user selected key-frame images, it is a list
136
+ # each item in the list is a vector if the model is freeform,
137
+ # each item in the list is a list of two vectors if the model is stylegan2
138
+ # frames_dist_folder: the folder path to save the generated images to make the video
139
+ # fps: is the frames we generate per second
140
+ # video_length: is the time of the video, in seconds. For example: 30 means a video length of 30 seconds
141
+ # ease_fn: user selected type of transitions between each key-frame
142
+
143
+ # first calculate how many images need to generate
144
+ try:
145
+ rmtree(frames_dist_folder)
146
+ except:
147
+ pass
148
+ os.makedirs(frames_dist_folder, exist_ok=True)
149
+
150
+ nbr_generate = fps*video_length
151
+ nbr_keyframe = len(selected_latents)
152
+ nbr_interpolation = 1 + nbr_generate // (nbr_keyframe - 1)
153
+
154
+
155
+ main_zs = []
156
+ for idx in range(nbr_keyframe-1):
157
+ main_zs += interpolate_ease_inout(selected_latents[idx],
158
+ selected_latents[idx+1], nbr_interpolation, ease_fn, model_type)
159
+
160
+
161
+ print('generating images ...')
162
+ batch_generate_and_save(net, main_zs, folder_name=frames_dist_folder, batch_size=8, model_type=model_type, im_size=im_size)
163
+ print('making videos ...')
164
+ read_img_and_make_video(frames_dist_folder, video_name, fps=fps)
165
+
166
+
167
+ if __name__ == "__main__":
168
+
169
+
170
+ device = torch.device('cuda:%d'%(0))
171
+
172
+ load_model_err = 0
173
+
174
+ from models import Generator as Generator_freeform
175
+
176
+ frames_dist_folder = 'project_video_frames' # a folder to save generated images
177
+ ckpt_path = './time_1024_1/models/180000.pth' # path to the checkpoint
178
+ video_name = 'videl_keyframe_15' # name of the generated video
179
+
180
+ model_type = 'freeform'
181
+ net = Generator_freeform(ngf=64, nz=100)
182
+ net.load_state_dict(torch.load(ckpt_path)['g'])
183
+ net.to(device)
184
+ net.eval()
185
+
186
+
187
+ try:
188
+ rmtree(frames_dist_folder)
189
+ except:
190
+ pass
191
+ os.makedirs(frames_dist_folder, exist_ok=True)
192
+
193
+ fps = 30
194
+ minutes = 1
195
+ im_size = 1024
196
+
197
+ ease_fn=ease_fn_dict['SineEaseInOut']
198
+
199
+ init_kf_nbr = 15
200
+ nbr_key_frames_per_minute = [init_kf_nbr-i for i in range(minutes)]
201
+ nbr_key_frames_total = sum(nbr_key_frames_per_minute)
202
+ noises = torch.randn( nbr_key_frames_total , 100).to(device)
203
+ user_selected_noises = [n for n in noises]
204
+ nbr_interpolation_list = [[fps*60//nbr_kf]*nbr_kf for nbr_kf in nbr_key_frames_per_minute]
205
+ nbl = []
206
+ for nb in nbr_interpolation_list:
207
+ nbl += nb
208
+
209
+ print(len(nbl))
210
+ print(len(user_selected_noises))# , print("mismatch size")
211
+ main_zs = []
212
+ for idx in range(len(user_selected_noises)-1):
213
+ main_zs += interpolate_ease_inout(user_selected_noises[idx],
214
+ user_selected_noises[idx+1], nbl[idx], ease_fn, model_type)
215
+ for idx in range(100):
216
+ main_zs.append(main_zs[-1])
217
+ print('generating images ...')
218
+ batch_generate_and_save(net, main_zs, folder_name=frames_dist_folder, batch_size=8, model_type=model_type, im_size=im_size)
219
+ print('making videos ...')
220
+ read_img_and_make_video(frames_dist_folder, video_name, fps=fps)
221
+
scripts/style_mix.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import torch.optim as optim
4
+ import torch.nn.functional as F
5
+ from torch.utils.data.dataloader import DataLoader
6
+ from torchvision import transforms
7
+ from torchvision import utils as vutils
8
+
9
+ import argparse
10
+ from tqdm import tqdm
11
+
12
+ from models import weights_init, Discriminator, Generator
13
+ from operation import copy_G_params, load_params, get_dir
14
+ from operation import ImageFolder, InfiniteSamplerWrapper
15
+ from diffaug import DiffAugment
16
+
17
+
18
+
19
+ ndf = 64
20
+ ngf = 64
21
+ nz = 256
22
+ nlr = 0.0002
23
+ nbeta1 = 0.5
24
+ use_cuda = True
25
+ multi_gpu = False
26
+ dataloader_workers = 8
27
+ current_iteration = 0
28
+ save_interval = 100
29
+ device = 'cuda:0'
30
+ im_size = 256
31
+
32
+
33
+ netG = Generator(ngf=ngf, nz=nz, im_size=im_size)
34
+ netG.apply(weights_init)
35
+
36
+ netD = Discriminator(ndf=ndf, im_size=im_size)
37
+ netD.apply(weights_init)
38
+
39
+ netG.to(device)
40
+ netD.to(device)
41
+
42
+ avg_param_G = copy_G_params(netG)
43
+
44
+ fixed_noise = torch.FloatTensor(8, nz).normal_(0, 1).to(device)
45
+
46
+ optimizerG = optim.Adam(netG.parameters(), lr=nlr, betas=(nbeta1, 0.999))
47
+ optimizerD = optim.Adam(netD.parameters(), lr=nlr, betas=(nbeta1, 0.999))
48
+
49
+ j = 4
50
+ checkpoint = "./models/all_%d.pth"%(j*10000)
51
+ ckpt = torch.load(checkpoint)
52
+ netG.load_state_dict(ckpt['g'])
53
+ netD.load_state_dict(ckpt['d'])
54
+ avg_param_G = ckpt['g_ema']
55
+ load_params(netG, avg_param_G)
56
+
57
+ bs = 8
58
+ noise_a = torch.randn(bs, nz).to(device)
59
+ noise_b = torch.randn(bs, nz).to(device)
60
+
61
+ def get_early_features(net, noise):
62
+ feat_4 = net.init(noise)
63
+ feat_8 = net.feat_8(feat_4)
64
+ feat_16 = net.feat_16(feat_8)
65
+ feat_32 = net.feat_32(feat_16)
66
+ feat_64 = net.feat_64(feat_32)
67
+ return feat_8, feat_16, feat_32, feat_64
68
+
69
+ def get_late_features(net, im_size, feat_64, feat_8, feat_16, feat_32):
70
+ feat_128 = net.feat_128(feat_64)
71
+ feat_128 = net.se_128(feat_8, feat_128)
72
+
73
+ feat_256 = net.feat_256(feat_128)
74
+ feat_256 = net.se_256(feat_16, feat_256)
75
+ if im_size==256:
76
+ return net.to_big(feat_256)
77
+
78
+ feat_512 = net.feat_512(feat_256)
79
+ feat_512 = net.se_512(feat_32, feat_512)
80
+ if im_size==512:
81
+ return net.to_big(feat_512)
82
+
83
+ feat_1024 = net.feat_1024(feat_512)
84
+ return net.to_big(feat_1024)
85
+
86
+
87
+ feat_8_a, feat_16_a, feat_32_a, feat_64_a = get_early_features(netG, noise_a)
88
+ feat_8_b, feat_16_b, feat_32_b, feat_64_b = get_early_features(netG, noise_b)
89
+
90
+ images_b = get_late_features(netG, im_size, feat_64_b, feat_8_b, feat_16_b, feat_32_b)
91
+ images_a = get_late_features(netG, im_size, feat_64_a, feat_8_a, feat_16_a, feat_32_a)
92
+
93
+ imgs = [ torch.ones(1, 3, im_size, im_size) ]
94
+ imgs.append(images_b.cpu())
95
+ for i in range(bs):
96
+ imgs.append(images_a[i].unsqueeze(0).cpu())
97
+
98
+ gimgs = get_late_features(netG, im_size, feat_64_a[i].unsqueeze(0).repeat(bs, 1, 1, 1), feat_8_b, feat_16_b, feat_32_b)
99
+ imgs.append(gimgs.cpu())
100
+
101
+ imgs = torch.cat(imgs)
102
+ vutils.save_image(imgs.add(1).mul(0.5), 'style_mix_1.jpg', nrow=bs+1)
scripts/train_backtracking_all.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn, real, select
3
+ import torch.optim as optim
4
+ import torch.nn.functional as F
5
+ from torch.utils.data.dataloader import DataLoader
6
+ from torchvision import transforms
7
+ from torchvision import utils as vutils
8
+
9
+ import argparse
10
+ from tqdm import tqdm
11
+
12
+ from models import weights_init, Discriminator, Generator, SimpleDecoder
13
+ from operation import copy_G_params, load_params, get_dir
14
+ from operation import ImageFolder, InfiniteSamplerWrapper
15
+ from diffaug import DiffAugment
16
+ policy = 'color,translation'
17
+ import lpips
18
+ percept = lpips.PerceptualLoss(model='net-lin', net='vgg', use_gpu=True)
19
+
20
+
21
+ #torch.backends.cudnn.benchmark = True
22
+
23
+
24
+ def crop_image_by_part(image, part):
25
+ hw = image.shape[2]//2
26
+ if part==0:
27
+ return image[:,:,:hw,:hw]
28
+ if part==1:
29
+ return image[:,:,:hw,hw:]
30
+ if part==2:
31
+ return image[:,:,hw:,:hw]
32
+ if part==3:
33
+ return image[:,:,hw:,hw:]
34
+
35
+ def train_d(net, data, label="real"):
36
+ """Train function of discriminator"""
37
+ if label=="real":
38
+ #pred, [rec_all, rec_small, rec_part], part = net(data, label)
39
+ pred = net(data, label)
40
+ err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 - pred).mean() #+ \
41
+ #percept( rec_all, F.interpolate(data, rec_all.shape[2]) ).sum() +\
42
+ #percept( rec_small, F.interpolate(data, rec_small.shape[2]) ).sum() +\
43
+ #percept( rec_part, F.interpolate(crop_image_by_part(data, part), rec_part.shape[2]) ).sum()
44
+ err.backward()
45
+ return pred.mean().item()#, rec_all, rec_small, rec_part
46
+ else:
47
+ pred = net(data, label)
48
+ err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 + pred).mean()
49
+ err.backward()
50
+ return pred.mean().item()
51
+
52
+ @torch.no_grad()
53
+ def interpolate(z1, z2, netG, img_name, step=8):
54
+ z = [ a*z2 + (1-a)*z1 for a in torch.linspace(0, 1, steps=step) ]
55
+ z = torch.cat(z).view(step, -1)
56
+ g_image = netG(z)[0]
57
+ vutils.save_image( g_image.add(1).mul(0.5), img_name , nrow=step)
58
+
59
+
60
+ def train(args):
61
+
62
+ data_root = args.path
63
+ total_iterations = args.iter
64
+ checkpoint = args.ckpt
65
+ batch_size = args.batch_size
66
+ im_size = args.im_size
67
+ ndf = 64
68
+ ngf = 64
69
+ nz = 256
70
+ nlr = 0.0002
71
+ nbeta1 = 0.5
72
+ use_cuda = True
73
+ multi_gpu = False
74
+ dataloader_workers = 8
75
+ current_iteration = 0
76
+ save_interval = 100
77
+ saved_model_folder, saved_image_folder = get_dir(args)
78
+
79
+ device = torch.device("cpu")
80
+ if use_cuda:
81
+ device = torch.device("cuda:0")
82
+
83
+ transform_list = [
84
+ transforms.Resize((int(im_size),int(im_size))),
85
+ transforms.RandomHorizontalFlip(),
86
+ transforms.ToTensor(),
87
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
88
+ ]
89
+ trans = transforms.Compose(transform_list)
90
+
91
+ dataset = ImageFolder(root=data_root, transform=trans, return_idx=True)
92
+ dataloader = iter(DataLoader(dataset, batch_size=batch_size, shuffle=False,
93
+ sampler=InfiniteSamplerWrapper(dataset), num_workers=dataloader_workers, pin_memory=True))
94
+
95
+ total_iterations = int(len(dataset)*100/batch_size)
96
+
97
+ netG = Generator(ngf=ngf, nz=nz, im_size=im_size)
98
+
99
+
100
+ ckpt = torch.load(checkpoint)
101
+ load_params( netG , ckpt['g_ema'] )
102
+ #netG.eval()
103
+ netG.to(device)
104
+
105
+ fixed_noise = torch.randn(len(dataset), nz, requires_grad=True, device=device)
106
+ optimizerG = optim.Adam([fixed_noise], lr=0.1, betas=(nbeta1, 0.999))
107
+
108
+ log_rec_loss = 0
109
+
110
+
111
+ for iteration in tqdm(range(current_iteration, total_iterations+1)):
112
+ real_image, noise_idx = next(dataloader)
113
+ real_image = real_image.to(device)
114
+
115
+ optimizerG.zero_grad()
116
+
117
+ select_noise = fixed_noise[noise_idx]
118
+ g_image = netG(select_noise)[0]
119
+
120
+ rec_loss = percept( F.avg_pool2d( g_image, 2, 2), F.avg_pool2d(real_image,2,2) ).sum() + 0.2*F.mse_loss(g_image, real_image)
121
+
122
+ rec_loss.backward()
123
+
124
+ optimizerG.step()
125
+
126
+ log_rec_loss += rec_loss.item()
127
+
128
+ if iteration % 100 == 0:
129
+ print("lpips loss g: %.5f"%(log_rec_loss/100))
130
+ log_rec_loss = 0
131
+
132
+ if iteration % (save_interval*10) == 0:
133
+
134
+ with torch.no_grad():
135
+ vutils.save_image( torch.cat([
136
+ real_image, g_image]).add(1).mul(0.5), saved_image_folder+'/rec_%d.jpg'%iteration , nrow=batch_size)
137
+
138
+ interpolate(fixed_noise[0], fixed_noise[1], netG, saved_image_folder+'/interpolate_0_1_%d.jpg'%iteration)
139
+
140
+ if iteration % (save_interval*10) == 0 or iteration == total_iterations:
141
+ torch.save(fixed_noise, saved_model_folder+'/%d.pth'%iteration)
142
+
143
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=dataloader_workers, pin_memory=True)
144
+
145
+ mean_lpips = 0
146
+ for idx, data in enumerate(dataloader):
147
+ real_image, noise_idx = data
148
+ real_image = real_image.to(device)
149
+
150
+ select_noise = fixed_noise[noise_idx]
151
+ g_image = netG(select_noise)[0]
152
+
153
+ rec_loss = percept( F.avg_pool2d( g_image, 2, 2), F.avg_pool2d(real_image,2,2) ).sum()
154
+ mean_lpips += rec_loss.sum()
155
+ mean_lpips /= len(dataset)
156
+ print(mean_lpips)
157
+
158
+
159
+ if __name__ == "__main__":
160
+ parser = argparse.ArgumentParser(description='region gan')
161
+
162
+ parser.add_argument('--path', type=str, default='../lmdbs/art_landscape_1k', help='path of resource dataset, should be a folder that has one or many sub image folders inside')
163
+ parser.add_argument('--cuda', type=int, default=0, help='index of gpu to use')
164
+ parser.add_argument('--name', type=str, default='test1', help='experiment name')
165
+ parser.add_argument('--iter', type=int, default=50000, help='number of iterations')
166
+ parser.add_argument('--start_iter', type=int, default=0, help='the iteration to start training')
167
+ parser.add_argument('--batch_size', type=int, default=4, help='mini batch number of images')
168
+ parser.add_argument('--im_size', type=int, default=1024, help='image resolution')
169
+ parser.add_argument('--ckpt', type=str, default='None', help='checkpoint weight path')
170
+
171
+
172
+ args = parser.parse_args()
173
+ print(args)
174
+
175
+ train(args)
scripts/train_backtracking_one.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import torch.optim as optim
4
+ import torch.nn.functional as F
5
+ from torch.utils.data.dataloader import DataLoader
6
+ from torchvision import transforms
7
+ from torchvision import utils as vutils
8
+
9
+ import argparse
10
+ from tqdm import tqdm
11
+
12
+ from models import weights_init, Discriminator, Generator, SimpleDecoder
13
+ from operation import copy_G_params, load_params, get_dir
14
+ from operation import ImageFolder, InfiniteSamplerWrapper
15
+ from diffaug import DiffAugment
16
+ policy = 'color,translation'
17
+ import lpips
18
+ percept = lpips.PerceptualLoss(model='net-lin', net='vgg', use_gpu=True)
19
+
20
+
21
+ #torch.backends.cudnn.benchmark = True
22
+
23
+
24
+ def crop_image_by_part(image, part):
25
+ hw = image.shape[2]//2
26
+ if part==0:
27
+ return image[:,:,:hw,:hw]
28
+ if part==1:
29
+ return image[:,:,:hw,hw:]
30
+ if part==2:
31
+ return image[:,:,hw:,:hw]
32
+ if part==3:
33
+ return image[:,:,hw:,hw:]
34
+
35
+ def train_d(net, data, label="real"):
36
+ """Train function of discriminator"""
37
+ if label=="real":
38
+ #pred, [rec_all, rec_small, rec_part], part = net(data, label)
39
+ pred = net(data, label)
40
+ err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 - pred).mean() #+ \
41
+ #percept( rec_all, F.interpolate(data, rec_all.shape[2]) ).sum() +\
42
+ #percept( rec_small, F.interpolate(data, rec_small.shape[2]) ).sum() +\
43
+ #percept( rec_part, F.interpolate(crop_image_by_part(data, part), rec_part.shape[2]) ).sum()
44
+ err.backward()
45
+ return pred.mean().item()#, rec_all, rec_small, rec_part
46
+ else:
47
+ pred = net(data, label)
48
+ err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 + pred).mean()
49
+ err.backward()
50
+ return pred.mean().item()
51
+
52
+ @torch.no_grad()
53
+ def interpolate(z1, z2, netG, img_name, step=8):
54
+ z = [ a*z2 + (1-a)*z1 for a in torch.linspace(0, 1, steps=step) ]
55
+ z = torch.cat(z).view(step, -1)
56
+ g_image = netG(z)[0]
57
+ vutils.save_image( g_image.add(1).mul(0.5), img_name , nrow=step)
58
+
59
+
60
+ def train(args):
61
+
62
+ data_root = args.path
63
+ total_iterations = args.iter
64
+ checkpoint = args.ckpt
65
+ batch_size = args.batch_size
66
+ im_size = args.im_size
67
+ ndf = 64
68
+ ngf = 64
69
+ nz = 256
70
+ nlr = 0.0002
71
+ nbeta1 = 0.5
72
+ use_cuda = True
73
+ multi_gpu = False
74
+ dataloader_workers = 8
75
+ current_iteration = 0
76
+ save_interval = 100
77
+ saved_model_folder, saved_image_folder = get_dir(args)
78
+
79
+ device = torch.device("cpu")
80
+ if use_cuda:
81
+ device = torch.device("cuda:0")
82
+
83
+ transform_list = [
84
+ transforms.Resize((int(im_size),int(im_size))),
85
+ transforms.RandomHorizontalFlip(),
86
+ transforms.ToTensor(),
87
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
88
+ ]
89
+ trans = transforms.Compose(transform_list)
90
+
91
+ dataset = ImageFolder(root=data_root, transform=trans)
92
+ dataloader = iter(DataLoader(dataset, batch_size=batch_size, shuffle=False,
93
+ sampler=InfiniteSamplerWrapper(dataset), num_workers=dataloader_workers, pin_memory=True))
94
+
95
+
96
+
97
+ netG = Generator(ngf=ngf, nz=nz, im_size=im_size)
98
+
99
+
100
+ ckpt = torch.load(checkpoint)
101
+ load_params( netG , ckpt['g_ema'] )
102
+ #netG.eval()
103
+ netG.to(device)
104
+
105
+ fixed_noise = torch.randn(batch_size, nz, requires_grad=True, device=device)
106
+ optimizerG = optim.Adam([fixed_noise], lr=0.1, betas=(nbeta1, 0.999))
107
+
108
+ real_image = next(dataloader).to(device)
109
+
110
+ log_rec_loss = 0
111
+
112
+ for iteration in tqdm(range(current_iteration, total_iterations+1)):
113
+
114
+ optimizerG.zero_grad()
115
+
116
+ g_image = netG(fixed_noise)[0]
117
+
118
+ rec_loss = percept( F.avg_pool2d( g_image, 2, 2), F.avg_pool2d(real_image,2,2) ).sum() + 0.2*F.mse_loss(g_image, real_image)
119
+
120
+ rec_loss.backward()
121
+
122
+ optimizerG.step()
123
+
124
+ log_rec_loss += rec_loss.item()
125
+
126
+ if iteration % 100 == 0:
127
+ print("lpips loss g: %.5f"%(log_rec_loss/100))
128
+ log_rec_loss = 0
129
+
130
+ if iteration % (save_interval*2) == 0:
131
+
132
+ with torch.no_grad():
133
+ vutils.save_image( torch.cat([
134
+ real_image, g_image]).add(1).mul(0.5), saved_image_folder+'/rec_%d.jpg'%iteration )
135
+
136
+ interpolate(fixed_noise[0], fixed_noise[1], netG, saved_image_folder+'/interpolate_0_1_%d.jpg'%iteration)
137
+
138
+ if iteration % (save_interval*5) == 0 or iteration == total_iterations:
139
+ torch.save(fixed_noise, saved_model_folder+'/%d.pth'%iteration)
140
+
141
+
142
+
143
+ if __name__ == "__main__":
144
+ parser = argparse.ArgumentParser(description='region gan')
145
+
146
+ parser.add_argument('--path', type=str, default='../lmdbs/art_landscape_1k', help='path of resource dataset, should be a folder that has one or many sub image folders inside')
147
+ parser.add_argument('--cuda', type=int, default=0, help='index of gpu to use')
148
+ parser.add_argument('--name', type=str, default='test1', help='experiment name')
149
+ parser.add_argument('--iter', type=int, default=50000, help='number of iterations')
150
+ parser.add_argument('--start_iter', type=int, default=0, help='the iteration to start training')
151
+ parser.add_argument('--batch_size', type=int, default=8, help='mini batch number of images')
152
+ parser.add_argument('--im_size', type=int, default=1024, help='image resolution')
153
+ parser.add_argument('--ckpt', type=str, default='None', help='checkpoint weight path')
154
+
155
+
156
+ args = parser.parse_args()
157
+ print(args)
158
+
159
+ train(args)
train.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import torch.optim as optim
4
+ import torch.nn.functional as F
5
+ from torch.utils.data.dataloader import DataLoader
6
+ from torchvision import transforms
7
+ from torchvision import utils as vutils
8
+
9
+ import argparse
10
+ import random
11
+ from tqdm import tqdm
12
+
13
+ from models import weights_init, Discriminator, Generator
14
+ from operation import copy_G_params, load_params, get_dir
15
+ from operation import ImageFolder, InfiniteSamplerWrapper
16
+ from diffaug import DiffAugment
17
+ policy = 'color,translation'
18
+ import lpips
19
+ percept = lpips.PerceptualLoss(model='net-lin', net='vgg', use_gpu=True)
20
+
21
+
22
+ #torch.backends.cudnn.benchmark = True
23
+
24
+
25
+ def crop_image_by_part(image, part):
26
+ hw = image.shape[2]//2
27
+ if part==0:
28
+ return image[:,:,:hw,:hw]
29
+ if part==1:
30
+ return image[:,:,:hw,hw:]
31
+ if part==2:
32
+ return image[:,:,hw:,:hw]
33
+ if part==3:
34
+ return image[:,:,hw:,hw:]
35
+
36
+ def train_d(net, data, label="real"):
37
+ """Train function of discriminator"""
38
+ if label=="real":
39
+ part = random.randint(0, 3)
40
+ pred, [rec_all, rec_small, rec_part] = net(data, label, part=part)
41
+ err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 - pred).mean() + \
42
+ percept( rec_all, F.interpolate(data, rec_all.shape[2]) ).sum() +\
43
+ percept( rec_small, F.interpolate(data, rec_small.shape[2]) ).sum() +\
44
+ percept( rec_part, F.interpolate(crop_image_by_part(data, part), rec_part.shape[2]) ).sum()
45
+ err.backward()
46
+ return pred.mean().item(), rec_all, rec_small, rec_part
47
+ else:
48
+ pred = net(data, label)
49
+ err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 + pred).mean()
50
+ err.backward()
51
+ return pred.mean().item()
52
+
53
+
54
+ def train(args):
55
+
56
+ data_root = args.path
57
+ total_iterations = args.iter
58
+ checkpoint = args.ckpt
59
+ batch_size = args.batch_size
60
+ im_size = args.im_size
61
+ ndf = 64
62
+ ngf = 64
63
+ nz = 256
64
+ nlr = 0.0002
65
+ nbeta1 = 0.5
66
+ use_cuda = True
67
+ multi_gpu = True
68
+ dataloader_workers = 8
69
+ current_iteration = 0
70
+ save_interval = 100
71
+ saved_model_folder, saved_image_folder = get_dir(args)
72
+
73
+ device = torch.device("cpu")
74
+ if use_cuda:
75
+ device = torch.device("cuda:0")
76
+
77
+ transform_list = [
78
+ transforms.Resize((int(im_size),int(im_size))),
79
+ transforms.RandomHorizontalFlip(),
80
+ transforms.ToTensor(),
81
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
82
+ ]
83
+ trans = transforms.Compose(transform_list)
84
+
85
+ if 'lmdb' in data_root:
86
+ from operation import MultiResolutionDataset
87
+ dataset = MultiResolutionDataset(data_root, trans, 1024)
88
+ else:
89
+ dataset = ImageFolder(root=data_root, transform=trans)
90
+
91
+ dataloader = iter(DataLoader(dataset, batch_size=batch_size, shuffle=False,
92
+ sampler=InfiniteSamplerWrapper(dataset), num_workers=dataloader_workers, pin_memory=True))
93
+ '''
94
+ loader = MultiEpochsDataLoader(dataset, batch_size=batch_size,
95
+ shuffle=True, num_workers=dataloader_workers,
96
+ pin_memory=True)
97
+ dataloader = CudaDataLoader(loader, 'cuda')
98
+ '''
99
+
100
+
101
+ #from model_s import Generator, Discriminator
102
+ netG = Generator(ngf=ngf, nz=nz, im_size=im_size)
103
+ netG.apply(weights_init)
104
+
105
+ netD = Discriminator(ndf=ndf, im_size=im_size)
106
+ netD.apply(weights_init)
107
+
108
+ netG.to(device)
109
+ netD.to(device)
110
+
111
+ avg_param_G = copy_G_params(netG)
112
+
113
+ fixed_noise = torch.FloatTensor(8, nz).normal_(0, 1).to(device)
114
+
115
+ if checkpoint != 'None':
116
+ ckpt = torch.load(checkpoint)
117
+ netG.load_state_dict(ckpt['g'])
118
+ netD.load_state_dict(ckpt['d'])
119
+ avg_param_G = ckpt['g_ema']
120
+ optimizerG.load_state_dict(ckpt['opt_g'])
121
+ optimizerD.load_state_dict(ckpt['opt_d'])
122
+ current_iteration = int(checkpoint.split('_')[-1].split('.')[0])
123
+ del ckpt
124
+
125
+ if multi_gpu:
126
+ netG = nn.DataParallel(netG.to(device))
127
+ netD = nn.DataParallel(netD.to(device))
128
+
129
+ optimizerG = optim.Adam(netG.parameters(), lr=nlr, betas=(nbeta1, 0.999))
130
+ optimizerD = optim.Adam(netD.parameters(), lr=nlr, betas=(nbeta1, 0.999))
131
+
132
+ for iteration in tqdm(range(current_iteration, total_iterations+1)):
133
+ real_image = next(dataloader)
134
+ real_image = real_image.to(device)
135
+ current_batch_size = real_image.size(0)
136
+ noise = torch.Tensor(current_batch_size, nz).normal_(0, 1).to(device)
137
+
138
+ fake_images = netG(noise)
139
+
140
+ real_image = DiffAugment(real_image, policy=policy)
141
+ fake_images = [DiffAugment(fake, policy=policy) for fake in fake_images]
142
+
143
+ ## 2. train Discriminator
144
+ netD.zero_grad()
145
+
146
+ err_dr, rec_img_all, rec_img_small, rec_img_part = train_d(netD, real_image, label="real")
147
+ train_d(netD, [fi.detach() for fi in fake_images], label="fake")
148
+ optimizerD.step()
149
+
150
+ ## 3. train Generator
151
+ netG.zero_grad()
152
+ pred_g = netD(fake_images, "fake")
153
+ err_g = -pred_g.mean()
154
+
155
+ err_g.backward()
156
+ optimizerG.step()
157
+
158
+ for p, avg_p in zip(netG.parameters(), avg_param_G):
159
+ avg_p.mul_(0.999).add_(0.001 * p.data)
160
+
161
+ if iteration % 100 == 0:
162
+ print("GAN: loss d: %.5f loss g: %.5f"%(err_dr, -err_g.item()))
163
+
164
+ if iteration % (save_interval*10) == 0:
165
+ backup_para = copy_G_params(netG)
166
+ load_params(netG, avg_param_G)
167
+ with torch.no_grad():
168
+ vutils.save_image(netG(fixed_noise)[0].add(1).mul(0.5), saved_image_folder+'/%d.jpg'%iteration, nrow=4)
169
+ vutils.save_image( torch.cat([
170
+ F.interpolate(real_image, 128),
171
+ rec_img_all, rec_img_small,
172
+ rec_img_part]).add(1).mul(0.5), saved_image_folder+'/rec_%d.jpg'%iteration )
173
+ load_params(netG, backup_para)
174
+
175
+ if iteration % (save_interval*50) == 0 or iteration == total_iterations:
176
+ backup_para = copy_G_params(netG)
177
+ load_params(netG, avg_param_G)
178
+ torch.save({'g':netG.state_dict(),'d':netD.state_dict()}, saved_model_folder+'/%d.pth'%iteration)
179
+ load_params(netG, backup_para)
180
+ torch.save({'g':netG.state_dict(),
181
+ 'd':netD.state_dict(),
182
+ 'g_ema': avg_param_G,
183
+ 'opt_g': optimizerG.state_dict(),
184
+ 'opt_d': optimizerD.state_dict()}, saved_model_folder+'/all_%d.pth'%iteration)
185
+
186
+ if __name__ == "__main__":
187
+ parser = argparse.ArgumentParser(description='region gan')
188
+
189
+ parser.add_argument('--path', type=str, default='../lmdbs/art_landscape_1k', help='path of resource dataset, should be a folder that has one or many sub image folders inside')
190
+ parser.add_argument('--cuda', type=int, default=1, help='index of gpu to use')
191
+ parser.add_argument('--name', type=str, default='test1', help='experiment name')
192
+ parser.add_argument('--iter', type=int, default=50000, help='number of iterations')
193
+ parser.add_argument('--start_iter', type=int, default=0, help='the iteration to start training')
194
+ parser.add_argument('--batch_size', type=int, default=8, help='mini batch number of images')
195
+ parser.add_argument('--im_size', type=int, default=256, help='image resolution')
196
+ parser.add_argument('--ckpt', type=str, default='None', help='checkpoint weight path if have one')
197
+
198
+
199
+ args = parser.parse_args()
200
+ print(args)
201
+
202
+ train(args)
train_4ch.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import torch.optim as optim
4
+ import torch.nn.functional as F
5
+ from torch.utils.data.dataloader import DataLoader
6
+ from torch.utils.data import Subset
7
+ from torchvision import transforms
8
+ from torchvision import utils as vutils
9
+
10
+ import argparse
11
+ import random
12
+ from tqdm import tqdm
13
+
14
+ from models import weights_init, Discriminator, Generator
15
+ from operation import copy_G_params, load_params, get_dir
16
+ from operation import ImageFolder, InfiniteSamplerWrapper
17
+ from diffaug import DiffAugment
18
+
19
+ #Vajira
20
+ from custom_data import ImageAndMaskDataFromSinGAN
21
+
22
+ policy = 'color,translation'
23
+ import lpips
24
+ percept = lpips.PerceptualLoss(model='net-lin', net='vgg', use_gpu=True)
25
+
26
+
27
+ #torch.backends.cudnn.benchmark = True
28
+
29
+
30
+ def crop_image_by_part(image, part):
31
+ hw = image.shape[2]//2
32
+ if part==0:
33
+ return image[:,:,:hw,:hw]
34
+ if part==1:
35
+ return image[:,:,:hw,hw:]
36
+ if part==2:
37
+ return image[:,:,hw:,:hw]
38
+ if part==3:
39
+ return image[:,:,hw:,hw:]
40
+
41
+ def train_d(net, data, label="real"):
42
+ """Train function of discriminator"""
43
+ if label=="real":
44
+ part = random.randint(0, 3)
45
+ #part = random.randint(0, 4)
46
+ pred, [rec_all, rec_small, rec_part] = net(data, label, part=part)
47
+
48
+ # new modifications
49
+ data_img = data[:,0:3, :, :]
50
+ rec_all_img = rec_all[:, 0:3, :, :]
51
+ rec_small_img = rec_small[:, 0:3, :, :]
52
+ rec_part_img = rec_part[:, 0:3, :, :]
53
+
54
+ #print("data shape=", data.shape)
55
+ #print("rec_all shape=", rec_all.shape)
56
+ err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 - pred).mean() + \
57
+ percept( rec_all_img, F.interpolate(data_img, rec_all.shape[2]) ).sum() +\
58
+ percept( rec_small_img, F.interpolate(data_img, rec_small.shape[2]) ).sum() +\
59
+ percept( rec_part_img, F.interpolate(crop_image_by_part(data_img, part), rec_part.shape[2]) ).sum()
60
+ err.backward()
61
+ return pred.mean().item(), rec_all, rec_small, rec_part
62
+ else:
63
+ pred = net(data, label)
64
+ err = F.relu( torch.rand_like(pred) * 0.2 + 0.8 + pred).mean()
65
+ err.backward()
66
+ return pred.mean().item()
67
+
68
+
69
+ def train(args):
70
+
71
+ #data_root = args.path
72
+ total_iterations = args.iter
73
+ checkpoint = args.ckpt
74
+ batch_size = args.batch_size
75
+ im_size = args.im_size
76
+ ndf = 64
77
+ ngf = 64
78
+ nz = 256
79
+ nlr = 0.0002
80
+ nbeta1 = 0.5
81
+ use_cuda = True
82
+ multi_gpu = True
83
+ dataloader_workers = 8
84
+ current_iteration = 0
85
+ save_interval = 100
86
+ saved_model_folder, saved_image_folder = get_dir(args)
87
+
88
+ device = torch.device("cpu")
89
+ if use_cuda:
90
+ device = torch.device("cuda:0")
91
+
92
+ transform_list = [
93
+ transforms.Resize((int(im_size),int(im_size))),
94
+ transforms.RandomHorizontalFlip(),
95
+ #transforms.ToTensor(), # removed by Vajira, check the dataloader
96
+ #transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) # removed by Vajira, check the dataloader
97
+ ]
98
+ trans = transforms.Compose(transform_list)
99
+
100
+ #if 'lmdb' in data_root:
101
+ # from operation import MultiResolutionDataset
102
+ # dataset = MultiResolutionDataset(data_root, trans, 1024)
103
+ #else:
104
+ #dataset = ImageFolder(root=data_root, transform=trans)
105
+ dataset = ImageAndMaskDataFromSinGAN(args.path_img, args.path_mask, transform=trans)
106
+ #print("dataset size=", len(dataset))
107
+ if args.num_imgs_to_train == -1 :
108
+ dataset = Subset(dataset, [i for i in range(0, len(dataset))])
109
+ else:
110
+ dataset = Subset(dataset, [i for i in range(0, args.num_imgs_to_train)]) # to control number of images to train
111
+ #print("dataset size=", len(dataset))
112
+
113
+ dataloader = iter(DataLoader(dataset, batch_size=batch_size, shuffle=False,
114
+ sampler=InfiniteSamplerWrapper(dataset), num_workers=dataloader_workers, pin_memory=True))
115
+ '''
116
+ loader = MultiEpochsDataLoader(dataset, batch_size=batch_size,
117
+ shuffle=True, num_workers=dataloader_workers,
118
+ pin_memory=True)
119
+ dataloader = CudaDataLoader(loader, 'cuda')
120
+ '''
121
+
122
+
123
+ #from model_s import Generator, Discriminator
124
+ netG = Generator(ngf=ngf, nz=nz, im_size=im_size, nc=args.nc)
125
+ netG.apply(weights_init)
126
+
127
+ netD = Discriminator(ndf=ndf, im_size=im_size, nc=args.nc)
128
+ netD.apply(weights_init)
129
+
130
+ netG.to(device)
131
+ netD.to(device)
132
+
133
+ avg_param_G = copy_G_params(netG)
134
+
135
+ fixed_noise = torch.FloatTensor(8, nz).normal_(0, 1).to(device)
136
+
137
+ if checkpoint != 'None':
138
+ ckpt = torch.load(checkpoint)
139
+ netG.load_state_dict(ckpt['g'])
140
+ netD.load_state_dict(ckpt['d'])
141
+ avg_param_G = ckpt['g_ema']
142
+ optimizerG.load_state_dict(ckpt['opt_g'])
143
+ optimizerD.load_state_dict(ckpt['opt_d'])
144
+ current_iteration = int(checkpoint.split('_')[-1].split('.')[0])
145
+ del ckpt
146
+
147
+ if multi_gpu:
148
+ netG = nn.DataParallel(netG.to(device))
149
+ netD = nn.DataParallel(netD.to(device))
150
+
151
+ optimizerG = optim.Adam(netG.parameters(), lr=nlr, betas=(nbeta1, 0.999))
152
+ optimizerD = optim.Adam(netD.parameters(), lr=nlr, betas=(nbeta1, 0.999))
153
+
154
+ for iteration in tqdm(range(current_iteration, total_iterations+1)):
155
+ real_image = next(dataloader)
156
+ real_image = real_image.to(device)
157
+ current_batch_size = real_image.size(0)
158
+ noise = torch.Tensor(current_batch_size, nz).normal_(0, 1).to(device)
159
+
160
+ fake_images = netG(noise)
161
+
162
+ real_image = DiffAugment(real_image, policy=policy)
163
+ fake_images = [DiffAugment(fake, policy=policy) for fake in fake_images]
164
+
165
+ ## 2. train Discriminator
166
+ netD.zero_grad()
167
+
168
+ err_dr, rec_img_all, rec_img_small, rec_img_part = train_d(netD, real_image, label="real")
169
+ train_d(netD, [fi.detach() for fi in fake_images], label="fake")
170
+ optimizerD.step()
171
+
172
+ ## 3. train Generator
173
+ netG.zero_grad()
174
+ pred_g = netD(fake_images, "fake")
175
+ err_g = -pred_g.mean()
176
+
177
+ err_g.backward()
178
+ optimizerG.step()
179
+
180
+ for p, avg_p in zip(netG.parameters(), avg_param_G):
181
+ avg_p.mul_(0.999).add_(0.001 * p.data)
182
+
183
+ if iteration % 100 == 0:
184
+ print("GAN: loss d: %.5f loss g: %.5f"%(err_dr, -err_g.item()))
185
+
186
+ if iteration % (save_interval*10) == 0:
187
+ backup_para = copy_G_params(netG)
188
+ load_params(netG, avg_param_G)
189
+ with torch.no_grad():
190
+ vutils.save_image(netG(fixed_noise)[0].add(1).mul(0.5), saved_image_folder+'/%d.png'%iteration, nrow=4)
191
+ vutils.save_image( torch.cat([
192
+ F.interpolate(real_image, 128),
193
+ rec_img_all, rec_img_small,
194
+ rec_img_part]).add(1).mul(0.5), saved_image_folder+'/rec_%d.png'%iteration )
195
+ load_params(netG, backup_para)
196
+
197
+ if iteration % (save_interval*50) == 0 or iteration == total_iterations:
198
+ backup_para = copy_G_params(netG)
199
+ load_params(netG, avg_param_G)
200
+ torch.save({'g':netG.state_dict(),'d':netD.state_dict()}, saved_model_folder+'/%d.pth'%iteration)
201
+ load_params(netG, backup_para)
202
+ torch.save({'g':netG.state_dict(),
203
+ 'd':netD.state_dict(),
204
+ 'g_ema': avg_param_G,
205
+ 'opt_g': optimizerG.state_dict(),
206
+ 'opt_d': optimizerD.state_dict()}, saved_model_folder+'/all_%d.pth'%iteration)
207
+
208
+ if __name__ == "__main__":
209
+ parser = argparse.ArgumentParser(description='region gan')
210
+
211
+ parser.add_argument('--path', type=str, default='../lmdbs/art_landscape_1k', help='path of resource dataset, should be a folder that has one or many sub image folders inside')
212
+ parser.add_argument('--cuda', type=int, default=1, help='index of gpu to use')
213
+ parser.add_argument('--name', type=str, default='test_4ch_num_img_5', help='experiment name')
214
+ parser.add_argument('--iter', type=int, default=50000, help='number of iterations')
215
+ parser.add_argument('--start_iter', type=int, default=0, help='the iteration to start training')
216
+ parser.add_argument('--batch_size', type=int, default=8, help='mini batch number of images')
217
+ parser.add_argument('--im_size', type=int, default=256, help='image resolution')
218
+ parser.add_argument('--ckpt', type=str, default='None', help='checkpoint weight path if have one')
219
+ # new parameters- added to process 4 channels data
220
+ parser.add_argument("--nc", type=int, default=4, help="number of channels in input images")
221
+ parser.add_argument("--path_img", default="/work/vajira/DATA/kvasir_seg/real_images_root/real_images", help="image directory")
222
+ parser.add_argument("--path_mask", default="/work/vajira/DATA/kvasir_seg/real_masks_root/real_masks", help = "mask directory")
223
+ parser.add_argument("--num_imgs_to_train", default=5, type=int, help="number of samples to train. -1 for use all")
224
+
225
+
226
+ args = parser.parse_args()
227
+ print(args)
228
+
229
+ train(args)
train_4ch.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ python train_4ch.py --num_imgs_to_train 5 --name test_4ch_num_img_5
4
+ python train_4ch.py --num_imgs_to_train 10 --name test_4ch_num_img_10
5
+ python train_4ch.py --num_imgs_to_train 15 --name test_4ch_num_img_15
6
+ python train_4ch.py --num_imgs_to_train 20 --name test_4ch_num_img_20
7
+ python train_4ch.py --num_imgs_to_train 25 --name test_4ch_num_img_25
8
+ python train_4ch.py --num_imgs_to_train 30 --name test_4ch_num_img_30
9
+ python train_4ch.py --num_imgs_to_train 35 --name test_4ch_num_img_35
10
+ python train_4ch.py --num_imgs_to_train 40 --name test_4ch_num_img_40
11
+ python train_4ch.py --num_imgs_to_train 45 --name test_4ch_num_img_45
12
+ python train_4ch.py --num_imgs_to_train 50 --name test_4ch_num_img_50