├── .gitignore
├── LICENSE
├── README.md
├── assets
└── PMN_teaser.png
├── download_data.sh
├── environment-latest.yml
├── environment.yml
├── main.py
├── models
├── __init__.py
├── classifier.py
├── communication.py
├── fgsbir
│ ├── model.py
│ └── networks.py
├── pmn.py
└── transformer.py
├── save_processed_images.py
├── trainer.py
└── utils
├── arguments.py
├── coords_utils.py
├── data.py
├── distance_transform.py
├── metrics.py
├── plt_blit.py
└── transformations.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Custom
2 | log*/
3 | data/
4 |
5 | # Byte-compiled / optimized / DLL files
6 | __pycache__/
7 | *.py[cod]
8 | *$py.class
9 |
10 | # C extensions
11 | *.so
12 |
13 | # Distribution / packaging
14 | .Python
15 | build/
16 | develop-eggs/
17 | dist/
18 | downloads/
19 | eggs/
20 | .eggs/
21 | lib/
22 | lib64/
23 | parts/
24 | sdist/
25 | var/
26 | wheels/
27 | share/python-wheels/
28 | *.egg-info/
29 | .installed.cfg
30 | *.egg
31 | MANIFEST
32 |
33 | # PyInstaller
34 | # Usually these files are written by a python script from a template
35 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
36 | *.manifest
37 | *.spec
38 |
39 | # Installer logs
40 | pip-log.txt
41 | pip-delete-this-directory.txt
42 |
43 | # Unit test / coverage reports
44 | htmlcov/
45 | .tox/
46 | .nox/
47 | .coverage
48 | .coverage.*
49 | .cache
50 | nosetests.xml
51 | coverage.xml
52 | *.cover
53 | *.py,cover
54 | .hypothesis/
55 | .pytest_cache/
56 | cover/
57 |
58 | # Translations
59 | *.mo
60 | *.pot
61 |
62 | # Django stuff:
63 | *.log
64 | local_settings.py
65 | db.sqlite3
66 | db.sqlite3-journal
67 |
68 | # Flask stuff:
69 | instance/
70 | .webassets-cache
71 |
72 | # Scrapy stuff:
73 | .scrapy
74 |
75 | # Sphinx documentation
76 | docs/_build/
77 |
78 | # PyBuilder
79 | .pybuilder/
80 | target/
81 |
82 | # Jupyter Notebook
83 | .ipynb_checkpoints
84 |
85 | # IPython
86 | profile_default/
87 | ipython_config.py
88 |
89 | # pyenv
90 | # For a library or package, you might want to ignore these files since the code is
91 | # intended to run in multiple environments; otherwise, check them in:
92 | # .python-version
93 |
94 | # pipenv
95 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
96 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
97 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
98 | # install all needed dependencies.
99 | #Pipfile.lock
100 |
101 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
102 | __pypackages__/
103 |
104 | # Celery stuff
105 | celerybeat-schedule
106 | celerybeat.pid
107 |
108 | # SageMath parsed files
109 | *.sage.py
110 |
111 | # Environments
112 | .env
113 | .venv
114 | env/
115 | venv/
116 | ENV/
117 | env.bak/
118 | venv.bak/
119 |
120 | # Spyder project settings
121 | .spyderproject
122 | .spyproject
123 |
124 | # Rope project settings
125 | .ropeproject
126 |
127 | # mkdocs documentation
128 | /site
129 |
130 | # mypy
131 | .mypy_cache/
132 | .dmypy.json
133 | dmypy.json
134 |
135 | # Pyre type checker
136 | .pyre/
137 |
138 | # pytype static type analyzer
139 | .pytype/
140 |
141 | # Cython debug symbols
142 | cython_debug/
143 |
144 | # IDEA
145 | .idea/
146 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
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 |
635 | Copyright (C)
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 .
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 | Copyright (C)
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 | .
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 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Abstracting Sketches through Simple Primitives
2 |
3 | [[Blog]](https://www.eml-unitue.de/publication/abstracting-sketches-through-simple-primitives) [[Paper]](https://arxiv.org/abs/2207.13543)
4 |
5 | This is the official PyTorch code for our ECCV 2022 paper on Abstracting Sketches through Simple Primitives. It allows training and testing of our Primitive Matching Network (PMN) on Quickdraw, ShoeV2 and ChairV2 datasets.
6 |
7 | 
8 |
9 |
10 | ## Installation
11 | All Python dependencies can be installed into a conda environment with the provided environment.yml file. To setup the code and environment, run the following commands.
12 |
13 | 1. Clone the repository
14 | ```shell
15 | git clone https://github.com/ExplainableML/sketch-primitives.git
16 | cd sketch-primitives
17 | ```
18 | 2. Create conda environment (you can try to use `environment-latest.yml` if you want to use the latest PyTorch version)
19 | ```shell
20 | conda env create -f environment.yml
21 | ```
22 | 3. Activate environment
23 | ```shell
24 | conda activate sketch-primitives
25 | ```
26 | 4. The script `./download_data.sh` downloads Quickdraw, ShoeV2 and ChairV2 into `./data`
27 |
28 |
29 | ## Usage
30 | The following commands are examples for training the PMN model. To see all possible parameters, use `python main.py --help`. By default, logs are saved into `./log` including model checkpoints and tensorboards. Data is expected to be in `./data` unless otherwise specified.
31 |
32 |
33 | ### Classification on Quickdraw
34 | * Train sketch classifier on the original dataset for evaluation purposes.
35 | ```
36 | python main.py --log-name classifier_quickdraw09 --model-type classifier --dataset quickdraw09
37 | ```
38 |
39 | * Train the PMN model self-supervised to do sketch abstractions with primitives.
40 | ```
41 | python main.py --log-name pmn_quickdraw09 --model-type pmn --dataset quickdraw09
42 | ```
43 |
44 | * Process the dataset with PMN to create a new dataset consisting of primitive reconstructions.
45 | ```
46 | python save_processed_images.py --log-name pmn_quickdraw09_processed --model-type pmn --dataset quickdraw09 --test ./log/pmn_quickdraw09/model_best_acc.pt --only-save-coords
47 | ```
48 |
49 | * Evaluate PMN reconstructions using a communication task with limited budget and the previously trained sketch classifier.
50 | ```
51 | python main.py --log-name pmn_communication_quickdraw09 --model-type communication --dataset quickdraw09 --loss-model-type class --loss-model-ckpt ./log/classifier_quickdraw09/model_best_acc.pt --budget 0.3 --test 1 --preprocessed-root ./log/pmn_quickdraw09_processed/data/coords/
52 | ```
53 |
54 |
55 | ### Fine-grainded Sketch-based Image retrieval (FG-SBIR) on ShoeV2 and ChairV2
56 | * Create sketch images with our rendering (to avoid distribution shift).
57 | ```
58 | python save_processed_images.py --log-name chairv2_processed --model-type none --dataset chairv2
59 | ln -sf $(pwd)/log/chairv2_processed/data/imgs data/chairv2/sketch_picture_files
60 | ```
61 |
62 | * Train a sketch-based image retrieval model on the original data for use as an evaluation model.
63 | ```
64 | python main.py --log-name fgsbir_chairv2 --model-type fgsbir --dataset chairv2 --load-fgsbir-photos
65 | ```
66 |
67 | * Train the PMN model self-supervised to do sketch abstractions with primitives.
68 | ```
69 | python main.py --log-name pmn_chairv2 --model-type pmn --dataset chairv2
70 | ```
71 |
72 | * Process the dataset with PMN to create a new dataset consisting of primitive reconstructions including sketch images for a specific budget.
73 | ```
74 | python save_processed_images.py --log-name pmn_chairv2_processed_budget0.3 --model-type pmn --dataset chairv2 --test ./log/pmn_chairv2/model_best_acc.pt --budget 0.3 --loss-model-type none --add-comm-model --load-fgsbir-photos
75 | ```
76 |
77 | * Process the dataset with PMN to create a new dataset consisting of primitive reconstructions including sketch images for a specific budget.
78 | ```
79 | python save_processed_images.py --log-name pmn_chairv2_processed_budget0.3 --model-type pmn --dataset chairv2 --test ./log/pmn_chairv2/model_best_acc.pt --budget 0.3 --loss-model-type none --add-comm-model --load-fgsbir-photos
80 | ln -sf $(pwd)/log/pmn_chairv2_processed_budget0.3/data/imgs data/chairv2/sketch_picture_files
81 | ```
82 |
83 | * Evaluate PMN reconstructions on the previously trained FG-SBIR model.
84 | ```
85 | python main.py --log-name pmn_communication_chairv2_budget0.3 --model-type fgsbir --dataset chairv2 --load-fgsbir-photos --test log/fgsbir_chairv2/model_best_acc.pt
86 | ```
87 |
88 |
89 | ## Citation
90 | If you use this code, please cite
91 | ```
92 | @inproceedings{alaniz2022primitives,
93 | title = {Abstracting Sketches through Simple Primitives},
94 | author = {Alaniz, S. and Mancini, M. and Dutta, A. and Marcos, D. and Akata, Z.},
95 | booktitle = {Proceedings of the European Conference on Computer Vision (ECCV)},
96 | year = {2022}
97 | }
98 | ```
99 |
--------------------------------------------------------------------------------
/assets/PMN_teaser.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ExplainableML/sketch-primitives/32b025c9bb29bc0354cf2a06075a942ac7712ad6/assets/PMN_teaser.png
--------------------------------------------------------------------------------
/download_data.sh:
--------------------------------------------------------------------------------
1 | mkdir -p ./data
2 | cd ./data
3 |
4 | # Download and extract ShoeV2 and ChairV2
5 | wget https://nc.mlcloud.uni-tuebingen.de/index.php/s/ZsydaSGocdxSy2k/download -O datav2.tar.gz
6 | tar xvf datav2.tar.gz
7 | rm datav2.tar.gz
8 |
9 | # Download and extract Quickdraw09
10 | wget https://nc.mlcloud.uni-tuebingen.de/index.php/s/JLeNSFQdGgkEPet/download -O quickdraw09.tar.gz
11 | tar xvf quickdraw09.tar.gz
12 | rm quickdraw09.tar.gz
13 |
--------------------------------------------------------------------------------
/environment-latest.yml:
--------------------------------------------------------------------------------
1 | name: sketch-primitives
2 | channels:
3 | - pytorch
4 | - nvidia
5 | - conda-forge
6 | - defaults
7 | dependencies:
8 | - matplotlib
9 | - numpy
10 | - pillow
11 | - pip
12 | - python
13 | - pytorch
14 | - pytorch-cuda
15 | - tar
16 | - tensorboard
17 | - torchvision
18 | - tqdm
19 | - wget
20 |
--------------------------------------------------------------------------------
/environment.yml:
--------------------------------------------------------------------------------
1 | name: sketch-primitives
2 | channels:
3 | - pytorch
4 | - conda-forge
5 | - defaults
6 | dependencies:
7 | - cudatoolkit=10.2
8 | - matplotlib=3.5.2
9 | - numpy=1.23.1
10 | - pillow=9.2.0
11 | - pip=22.1.2
12 | - python=3.10.5
13 | - pytorch=1.12.0
14 | - tar=1.34
15 | - tensorboard=2.9.1
16 | - torchvision=0.13.0
17 | - tqdm=4.64.0
18 | - wget=1.20.3
19 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import os
2 | import datetime
3 |
4 | import numpy as np
5 | import torch
6 |
7 | from models import get_model
8 | from utils.data import get_data
9 | from utils.arguments import parser
10 | from trainer import Trainer
11 |
12 | if __name__ == '__main__':
13 | args = parser.parse_args()
14 |
15 | DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
16 |
17 | # Add timestamp to logdir
18 | if args.log_name is None:
19 | LOG_DIR = os.path.join(args.log_dir,
20 | datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
21 | else:
22 | LOG_DIR = os.path.join(args.log_dir,
23 | args.log_name)
24 |
25 | if args.test is not None:
26 | torch.manual_seed(42)
27 | np.random.seed(42)
28 |
29 | dataloader_coords, n_classes, label_names = get_data(
30 | args.data_dir, args.dataset, batch_size=args.batch_size,
31 | train=True,
32 | preprocessed_root=args.preprocessed_root,
33 | load_fgsbir_photos=args.load_fgsbir_photos,
34 | resample_strokes=not args.no_stroke_resampling,
35 | max_stroke_length=args.max_stroke_length
36 | )
37 |
38 | test_dataloader_coords, _, _ = get_data(
39 | args.data_dir, args.dataset, batch_size=args.n_log_img,
40 | train=False,
41 | preprocessed_root=args.preprocessed_root,
42 | load_fgsbir_photos=args.load_fgsbir_photos,
43 | resample_strokes=not args.no_stroke_resampling,
44 | max_stroke_length=args.max_stroke_length
45 | )
46 |
47 | model = get_model(args, n_classes, DEVICE)
48 |
49 | if args.test is not None and not args.model_type == 'communication':
50 | model.load_state_dict(torch.load(args.test))
51 |
52 | if args.test is not None:
53 | torch.manual_seed(42)
54 | np.random.seed(42)
55 |
56 | trainer = Trainer(args.model_type, model, args.test is None, args.learning_rate, args.epochs, dataloader_coords, test_dataloader_coords, label_names, DEVICE, LOG_DIR, args.log_every, args.n_log_img, args.save_every, args.view_scale, args.weight_decay)
57 | trainer.run()
58 |
--------------------------------------------------------------------------------
/models/__init__.py:
--------------------------------------------------------------------------------
1 | import torch
2 |
3 | from .pmn import PrimitiveMatchingNetwork
4 | from .classifier import SketchClassifier
5 | from .communication import Communication
6 | from .fgsbir.model import FGSBIR_Model
7 |
8 | def get_model(args, n_classes, DEVICE):
9 | if args.model_type == 'none':
10 | model = None
11 | elif args.model_type == 'pmn':
12 | model = PrimitiveMatchingNetwork(
13 | temperature=args.temperature,
14 | use_pos_embed=args.use_pos_embed,
15 | use_sinusoid_embed=args.use_sinusoid_embed,
16 | transformations=args.transformations,
17 | use_proportion_scale=args.use_proportion_scale,
18 | transform_bound=args.transform_bound,
19 | Nz=args.Nz,
20 | dt_gamma=args.dt_gamma,
21 | learn_compatibility=args.learn_compatibility)
22 | model = model.to(DEVICE)
23 |
24 | elif args.model_type == 'classifier':
25 | model = SketchClassifier(n_classes=n_classes, use_pos_embed=args.use_pos_embed,
26 | use_sinusoid_embed=args.use_sinusoid_embed).to(DEVICE)
27 | elif args.model_type == 'communication':
28 | if args.loss_model_type == 'class':
29 | classifier = SketchClassifier(n_classes=n_classes, use_pos_embed=args.use_pos_embed,
30 | use_sinusoid_embed=args.use_sinusoid_embed).to(DEVICE)
31 | elif args.loss_model_type == 'fgsbir':
32 | classifier = FGSBIR_Model(backbone=args.fgsbir_backbone,
33 | ce_temp=args.temperature).to(DEVICE)
34 | elif args.loss_model_type == 'none':
35 | classifier = None
36 | else:
37 | raise NotImplementedError
38 |
39 | if args.loss_model_type != 'none':
40 | classifier.load_state_dict(torch.load(args.loss_model_ckpt))
41 |
42 | if args.loss_model_type == 'class':
43 | classifier = classifier.encoder
44 |
45 | model = Communication(classifier=classifier,
46 | loss_type=args.loss_model_type,
47 | comm_mode=args.comm_mode,
48 | budget=args.budget,
49 | ).to(DEVICE)
50 | elif args.model_type == 'fgsbir':
51 | model = FGSBIR_Model(backbone=args.fgsbir_backbone,
52 | ce_temp=args.temperature,
53 | loss_type=args.loss_model_type).to(DEVICE)
54 | else:
55 | raise NotImplementedError
56 |
57 | return model
58 |
59 |
--------------------------------------------------------------------------------
/models/classifier.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 | from torchvision.models import resnet18
5 |
6 | from .transformer import StrokeEncoderTransformer
7 |
8 | class SketchClassifier(nn.Module):
9 | def __init__(self, n_classes, Nz=256, use_pos_embed=False,
10 | use_sinusoid_embed=False, stroke_len=25):
11 | super().__init__()
12 | self.Nz = Nz
13 | self.encoder = StrokeEncoderTransformer(
14 | Nz=Nz, embed_sketch=True, n_layer_strokes=3, use_pos_embed=use_pos_embed,
15 | use_sinusoid_embed=use_sinusoid_embed, out_dim=n_classes, stroke_len=stroke_len
16 | )
17 | self.criterion = nn.CrossEntropyLoss(reduction='none')
18 |
19 | def forward(self, x_raw, label, n_strokes, scale, translate, stroke_lens, seq_mask, position, **kwargs):
20 | # encode:
21 | cls_logits, _ = self.encoder(x_raw.transpose(0, 1), n_strokes, scale, translate, stroke_lens, seq_mask, position)
22 | loss = self.criterion(cls_logits, label)
23 |
24 | _, pred_main = torch.max(cls_logits, 1)
25 | acc = (label == pred_main).float()
26 | clspred_main_prob = torch.softmax(cls_logits, dim=1).gather(1, pred_main.unsqueeze(1)).squeeze(1)
27 |
28 | output = {'loss': loss,
29 | 'acc_main': acc,
30 | 'cls_pred_main': pred_main,
31 | 'cls_pred_main_prob': clspred_main_prob,
32 | 'pcoords_raw': x_raw,
33 | 'pcoords_n_strokes': n_strokes,
34 | 'pcoords_scale': scale,
35 | 'pcoords_translate': translate,
36 | 'pcoords_seq_mask': seq_mask}
37 |
38 | return output
39 |
--------------------------------------------------------------------------------
/models/communication.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 | from torchvision.models import resnet18
5 | import torchvision.transforms as transforms
6 | import matplotlib.pyplot as plt
7 |
8 | from .transformer import StrokeEncoderTransformer
9 | from utils.plt_blit import BlitManager
10 | from utils.coords_utils import make_image_fast
11 |
12 | def calc_segments_per_sketch(segments, stroke_lens, n_strokes):
13 | if len(segments) == 1:
14 | segments = segments[0]
15 | elif not isinstance(segments, torch.Tensor):
16 | segments = torch.stack(segments).T.flatten()
17 |
18 | grouped_segments = []
19 | group = []
20 | cnt = 0
21 | sid = 0
22 | for seg in segments:
23 | group.append(seg)
24 | cnt += seg
25 | if cnt == stroke_lens[sid]:
26 | grouped_segments.append(torch.stack(group))
27 | cnt = 0
28 | sid += 1
29 | group = []
30 |
31 | grouped_segments_len = [gs.shape[0] for gs in grouped_segments]
32 |
33 | segments_per_sketch = []
34 | cnt = 0
35 | for n_s in n_strokes:
36 | segments_per_sketch.append(sum(grouped_segments_len[cnt:cnt+n_s]))
37 | cnt += n_s
38 | segments_per_sketch = torch.tensor(segments_per_sketch, device=n_strokes.device)
39 |
40 | return grouped_segments, grouped_segments_len, segments_per_sketch
41 |
42 | class Communication(nn.Module):
43 | def __init__(self, classifier, Nz=256, comm_mode='human',
44 | loss_type='class', budget=1.0):
45 | super().__init__()
46 | assert comm_mode in ['human', 'random']
47 | self.Nz = Nz
48 | self.classifier = classifier
49 | if self.classifier is not None:
50 | for p in self.classifier.parameters():
51 | p.requires_grad = False
52 |
53 | self.criterion = nn.CrossEntropyLoss(reduction='none')
54 | self.comm_mode = comm_mode
55 | self.loss_type = loss_type
56 | self.budget = budget
57 | self.gamma = 0.9
58 |
59 | if self.loss_type == 'fgsbir' and not self.classifier.use_transformer:
60 | fig, ax = plt.subplots(figsize=(2.99, 2.99), constrained_layout=True)
61 | ax.set_axis_off()
62 | fig.add_axes(ax)
63 | self.blit_manager = BlitManager(ax, fig.canvas)
64 | fig.canvas.draw()
65 |
66 | self.img_transform = transforms.Normalize(mean=[0.485, 0.456, 0.406],
67 | std=[0.229, 0.224, 0.225])
68 |
69 |
70 | def forward(self, x_raw, label, n_strokes, scale, translate, segments=None, stroke_lens=None, seq_mask=None, position=None, **kwargs):
71 |
72 | grouped_segments, grouped_segments_len, segments_per_sketch = calc_segments_per_sketch(
73 | segments, stroke_lens,
74 | kwargs['n_strokes_orig'] if 'n_strokes_orig' in kwargs else n_strokes
75 | )
76 |
77 | # encode:
78 | ol_size = (n_strokes.shape[0], n_strokes.max().item())
79 | if self.comm_mode.endswith('human'):
80 | arange_size = ol_size[1]
81 | order_logits = -torch.arange(arange_size, dtype=x_raw.dtype, device=x_raw.device).unsqueeze(0).expand((ol_size[0], arange_size))
82 | order_logits = order_logits.view(ol_size)
83 | else: # 'random'
84 | order_logits = torch.randn(ol_size, device=x_raw.device)
85 |
86 | padding_mask = torch.zeros(ol_size, device=x_raw.device, dtype=torch.bool)
87 | stroke_id = 0
88 | for i, n_s in enumerate(n_strokes):
89 | pad_len = ol_size[1] - n_s
90 | if pad_len != 0:
91 | padding_mask[i, -pad_len:] = True
92 | stroke_id += n_s
93 |
94 | order_logits = order_logits.masked_fill(padding_mask, float('-inf'))
95 | order_all = torch.full_like(order_logits, float('-inf'))
96 |
97 | final_cls_logits = None
98 | all_cls_logits = []
99 | cls_input = torch.zeros_like(x_raw)
100 | mask = torch.ones_like(padding_mask)
101 | grad_neg_mask = torch.zeros_like(x_raw[:, 0, 0])
102 | points_mask = None
103 | losses = []
104 |
105 | budget_n_strokes = torch.ceil(segments_per_sketch * self.budget).int()
106 | budget_n_strokes = torch.stack([budget_n_strokes, n_strokes]).min(0)[0]
107 | n_iters = max(budget_n_strokes)
108 |
109 | for i in range(n_iters):
110 | done = order_logits.isinf().sum(1) == order_logits.shape[1]
111 | done = done.unsqueeze(1).expand(order_logits.shape)
112 |
113 | order_logits = order_logits.masked_fill(done, 0.)
114 |
115 | next_order = F.one_hot(order_logits.argmax(dim=1), num_classes=order_logits.shape[1])
116 | next_order = next_order.float()
117 |
118 | next_order_flat = []
119 | global_stroke_id = 0
120 | for bi, (no, n_s) in enumerate(zip(next_order, n_strokes)):
121 | next_order_flat.append(no[:n_s])
122 | global_stroke_id += n_s
123 | next_order_flat = torch.cat(next_order_flat)
124 | next_order_flat = next_order_flat.masked_fill(next_order_flat.isnan(), 0.)
125 |
126 | active_sketches = i < budget_n_strokes
127 | active_strokes = torch.cat([a.repeat(n_s) for a, n_s in zip(active_sketches, n_strokes)])
128 |
129 | grad_neg_mask += active_strokes * next_order_flat
130 | cls_input = x_raw * grad_neg_mask.unsqueeze(-1).unsqueeze(-1)
131 | points_mask_input = None
132 | mask = mask & ~(active_sketches.unsqueeze(1) & next_order.bool()).detach()
133 | if self.loss_type == 'fgsbir':
134 | if not self.classifier.use_transformer:
135 | sketch_images= []
136 | n_s = list(n_strokes)
137 | # TODO: remove duplicate code
138 | if points_mask_input is None:
139 | for ci, s, t in zip(cls_input.split(n_s), scale.split(n_s), translate.split(n_s)):
140 | sketch_img = make_image_fast(self.blit_manager, (ci.cpu(), s.cpu(), t.cpu(), None), no_axis=True, color='black', linewidth=1, enlarge=2.0, arbitrary_mask=True)
141 | sketch_images.append(self.img_transform(torch.tensor(sketch_img, dtype=torch.float)/255.))
142 | else:
143 | for ci, s, t, m in zip(cls_input.split(n_s), scale.split(n_s), translate.split(n_s), points_mask_input[:, :-1].split(n_s)):
144 | sketch_img = make_image_fast(self.blit_manager, (ci.cpu(), s.cpu(), t.cpu(), m.cpu()), no_axis=True, color='black', linewidth=1, enlarge=2.0, arbitrary_mask=True)
145 | sketch_images.append(self.img_transform(torch.tensor(sketch_img, dtype=torch.float)/255.))
146 | kwargs['sketch_img'] = torch.stack(sketch_images).to(cls_input)
147 | outputs = self.classifier(cls_input, n_strokes, scale, translate, seq_mask=seq_mask, position=position, stroke_lens=stroke_lens, mask=torch.cat([mask, torch.zeros_like(mask[:, :1])], dim=1), points_mask=points_mask_input, **kwargs)
148 | cls_loss = outputs['loss'][active_sketches]
149 | sketch_feature = outputs['sketch_feature']
150 | image_feature = outputs['image_feature']
151 | elif self.loss_type == 'class':
152 | cls_logits, _ = self.classifier(cls_input.transpose(0, 1), n_strokes, scale, translate, seq_mask=seq_mask, position=position, mask=torch.cat([mask, torch.zeros_like(mask[:, :1])], dim=1), points_mask=points_mask_input, **kwargs)
153 |
154 | all_cls_logits.append(cls_logits)
155 | if final_cls_logits is None:
156 | final_cls_logits = cls_logits.clone().detach()
157 | else:
158 | final_cls_logits[active_sketches] = cls_logits[active_sketches].clone().detach()
159 |
160 | cls_loss = self.criterion(cls_logits[active_sketches], label[active_sketches])
161 | cls_rank = (cls_logits.argsort(1, descending=True) == label.unsqueeze(1)).nonzero()[:, 1]
162 | elif self.loss_type == 'none':
163 | cls_loss = torch.tensor([0.])
164 | else:
165 | raise NotImplementedError
166 |
167 | losses.append(cls_loss)
168 |
169 | order_all += 1
170 | order_all = order_all.masked_fill(next_order.bool() & active_sketches.unsqueeze(1), 0.)
171 |
172 | order_logits = order_logits.masked_fill(next_order.bool(), float('-inf'))
173 |
174 | loss = torch.cat(losses)
175 | assert not loss.isnan().any()
176 |
177 | if self.loss_type == 'class':
178 | _, pred_main = torch.max(final_cls_logits, 1)
179 | acc = (label == pred_main).float()
180 |
181 | all_cls_logits = torch.stack(all_cls_logits, dim=1)
182 | _, all_pred_main = torch.max(all_cls_logits, 2)
183 | all_acc = (label.unsqueeze(1) == all_pred_main).float()
184 | clspred_main_prob = torch.softmax(all_cls_logits, dim=2).gather(2, all_pred_main.unsqueeze(2)).squeeze(2)
185 |
186 | x_raw_reordered = []
187 | scale_reordered = []
188 | translate_reordered = []
189 | order_ids_reordered = []
190 | n_s = n_strokes.cpu().numpy().tolist()
191 | xr = x_raw.split(n_s)
192 | sc = scale.split(n_s)
193 | tr = translate.split(n_s)
194 | pcoords_n_strokes = budget_n_strokes
195 |
196 | for ol, x, s, t, n_s in zip(order_all, xr, sc, tr, pcoords_n_strokes):
197 | assert n_s == (~ol.isinf()).sum()
198 | order = ol.argsort(dim=0, descending=True)
199 | order = order[:n_s]
200 | x_raw_reordered.append(x[order])
201 | scale_reordered.append(s[order])
202 | translate_reordered.append(t[order])
203 | x_raw_reordered = torch.cat(x_raw_reordered)
204 | scale_reordered = torch.cat(scale_reordered)
205 | translate_reordered = torch.cat(translate_reordered)
206 |
207 | if self.loss_type == 'class':
208 | output = {'loss': loss,
209 | 'acc_main': acc,
210 | 'acc_main_all': all_acc,
211 | 'cls_pred_main': all_pred_main,
212 | 'cls_pred_main_prob': clspred_main_prob,
213 | 'pcoords_raw': x_raw_reordered,
214 | 'pcoords_n_strokes': pcoords_n_strokes,
215 | 'pcoords_scale': scale_reordered,
216 | 'pcoords_translate': translate_reordered,
217 | 'pcoords_seq_mask': None,
218 | 'segments_per_sketch': segments_per_sketch,
219 | }
220 | elif self.loss_type == 'fgsbir':
221 | output = {'loss': loss,
222 | 'pcoords_raw': x_raw_reordered,
223 | 'pcoords_n_strokes': pcoords_n_strokes,
224 | 'pcoords_scale': scale_reordered,
225 | 'pcoords_translate': translate_reordered,
226 | 'pcoords_seq_mask': None,
227 | 'segments_per_sketch': segments_per_sketch,
228 | 'sketch_feature': sketch_feature.detach(),
229 | 'image_feature': image_feature.detach(),
230 | }
231 | else:
232 | output = {'loss': loss,
233 | 'pcoords_raw': x_raw_reordered,
234 | 'pcoords_n_strokes': pcoords_n_strokes,
235 | 'pcoords_scale': scale_reordered,
236 | 'pcoords_translate': translate_reordered,
237 | 'pcoords_seq_mask': None,
238 | 'segments_per_sketch': segments_per_sketch,
239 | 'stroke_ids': order_ids_reordered,
240 | }
241 |
242 | return output
243 |
244 | def draw(self, **inputs):
245 | return self.forward(**inputs)
246 |
--------------------------------------------------------------------------------
/models/fgsbir/model.py:
--------------------------------------------------------------------------------
1 | import torch.nn as nn
2 | from ..transformer import StrokeEncoderTransformer
3 | from .networks import VGG_Network, InceptionV3_Network, Resnet50_Network
4 | from torch import optim
5 | import torch
6 | import numpy as np
7 | import time
8 | import torch.nn.functional as F
9 |
10 |
11 | class FGSBIR_Model(nn.Module):
12 | def __init__(self, backbone, Nz=256, loss_type='cross_entropy', ce_temp=0.2):
13 | super(FGSBIR_Model, self).__init__()
14 | self.sample_embedding_network = eval(backbone + '_Network(scale=Nz//2)')
15 |
16 | self.loss_type = loss_type
17 |
18 | if self.loss_type == 'cross_entropy':
19 | temperature = torch.tensor([ce_temp])
20 | self.register_buffer('temperature', temperature)
21 | self.criterion = nn.CrossEntropyLoss(reduction='none')
22 | else:
23 | self.loss = nn.TripletMarginLoss(margin=0.2)
24 |
25 | def forward(self, x_raw, n_strokes, scale, translate, seq_mask,
26 | positive_img, negative_img, sketch_img, positive_name,
27 | mask=None, **kwargs):
28 |
29 | positive_feature = self.sample_embedding_network(positive_img)
30 | sketch_feature = self.sample_embedding_network(sketch_img, finetune=True)
31 |
32 | if self.loss_type == 'cross_entropy':
33 | labels = torch.arange(sketch_feature.shape[0]).to(sketch_feature.device)
34 |
35 | positive_name = np.array(positive_name)
36 | mask = [pn == positive_name for pn in positive_name]
37 | mask = np.stack(mask)
38 | np.fill_diagonal(mask, False)
39 | mask_bool = torch.tensor(mask)
40 | mask = torch.zeros_like(mask_bool, dtype=torch.float)
41 | mask = mask.masked_fill(mask_bool, -np.inf).to(sketch_feature.device)
42 |
43 | similarity_matrix = torch.matmul(sketch_feature, positive_feature.T) / self.temperature
44 | loss = (self.criterion(similarity_matrix+mask, labels) + self.criterion(similarity_matrix.T+mask, labels)) / 2.
45 | else:
46 | negative_feature = self.sample_embedding_network(negative_img)
47 | loss = self.loss(sketch_feature, positive_feature, negative_feature)
48 |
49 | output = {'loss': loss,
50 | 'pcoords_raw': x_raw,
51 | 'pcoords_n_strokes': n_strokes,
52 | 'pcoords_scale': scale,
53 | 'pcoords_translate': translate,
54 | 'pcoords_seq_mask': seq_mask,
55 | 'sketch_feature': sketch_feature.detach(),
56 | 'image_feature': positive_feature.detach()}
57 |
58 | return output
59 |
--------------------------------------------------------------------------------
/models/fgsbir/networks.py:
--------------------------------------------------------------------------------
1 | import torch.nn as nn
2 | import torchvision.models as backbone_
3 | import torch.nn.functional as F
4 | import torch
5 |
6 |
7 |
8 | class Resnet50_Network(nn.Module):
9 | def __init__(self):
10 | super(Resnet50_Network, self).__init__()
11 | backbone = backbone_.resnet50(weights=backbone_.ResNet50_Weights.DEFAULT) #resnet50, resnet18, resnet34
12 |
13 | self.features = nn.Sequential()
14 | for name, module in backbone.named_children():
15 | if name not in ['avgpool', 'fc']:
16 | self.features.add_module(name, module)
17 | self.pool_method = nn.AdaptiveMaxPool2d(1)
18 |
19 |
20 | def forward(self, input, bb_box = None):
21 | x = self.features(input)
22 | x = self.pool_method(x)
23 | x = torch.flatten(x, 1)
24 | return F.normalize(x)
25 |
26 |
27 | class VGG_Network(nn.Module):
28 | def __init__(self):
29 | super(VGG_Network, self).__init__()
30 | self.backbone = backbone_.vgg16(weights=backbone_.VGG16_Weights.DEFAULT).features
31 | self.pool_method = nn.AdaptiveMaxPool2d(1)
32 |
33 | def forward(self, input, bb_box = None):
34 | x = self.backbone(input)
35 | x = self.pool_method(x).view(-1, 512)
36 | return F.normalize(x)
37 |
38 | class InceptionV3_Network(nn.Module):
39 | def __init__(self, scale=128, use_att=False):
40 | super(InceptionV3_Network, self).__init__()
41 | self.use_att = use_att
42 | self.scale = scale
43 | backbone = backbone_.inception_v3(weights=backbone_.Inception_V3_Weights.DEFAULT)
44 |
45 | ## Extract Inception Layers ##
46 | self.Conv2d_1a_3x3 = backbone.Conv2d_1a_3x3
47 | self.Conv2d_2a_3x3 = backbone.Conv2d_2a_3x3
48 | self.Conv2d_2b_3x3 = backbone.Conv2d_2b_3x3
49 | self.Conv2d_3b_1x1 = backbone.Conv2d_3b_1x1
50 | self.Conv2d_4a_3x3 = backbone.Conv2d_4a_3x3
51 | self.Mixed_5b = backbone.Mixed_5b
52 | self.Mixed_5c = backbone.Mixed_5c
53 | self.Mixed_5d = backbone.Mixed_5d
54 | self.Mixed_6a = backbone.Mixed_6a
55 | self.Mixed_6b = backbone.Mixed_6b
56 | self.Mixed_6c = backbone.Mixed_6c
57 | self.Mixed_6d = backbone.Mixed_6d
58 | self.Mixed_6e = backbone.Mixed_6e
59 |
60 | self.Mixed_7a = backbone.Mixed_7a
61 | self.Mixed_7b = backbone.Mixed_7b
62 | self.Mixed_7c = backbone.Mixed_7c
63 | #self.pool_method = nn.AdaptiveMaxPool2d(1) # as default
64 | self.pool_method = nn.AdaptiveAvgPool2d(1) # as default
65 |
66 | if self.use_att:
67 | self.att_conv = nn.Conv2d(2048, 2048, kernel_size=1)
68 |
69 | if self.scale is not None:
70 | self.scale_fn = nn.Linear(2048, self.scale)
71 |
72 | self.finetuned_scale_fn = None
73 |
74 | def forward(self, x, finetune=False):
75 | # N x 3 x 299 x 299
76 | x = self.Conv2d_1a_3x3(x)
77 | # N x 32 x 149 x 149
78 | x = self.Conv2d_2a_3x3(x)
79 | # N x 32 x 147 x 147
80 | x = self.Conv2d_2b_3x3(x)
81 | # N x 64 x 147 x 147
82 | x = F.max_pool2d(x, kernel_size=3, stride=2)
83 | # N x 64 x 73 x 73
84 | x = self.Conv2d_3b_1x1(x)
85 | # N x 80 x 73 x 73
86 | x = self.Conv2d_4a_3x3(x)
87 | # N x 192 x 71 x 71
88 | x = F.max_pool2d(x, kernel_size=3, stride=2)
89 | # N x 192 x 35 x 35
90 | x = self.Mixed_5b(x)
91 | # N x 256 x 35 x 35
92 | x = self.Mixed_5c(x)
93 | # N x 288 x 35 x 35
94 | x = self.Mixed_5d(x)
95 | # N x 288 x 35 x 35
96 | x = self.Mixed_6a(x)
97 | # N x 768 x 17 x 17
98 | x = self.Mixed_6b(x)
99 | # N x 768 x 17 x 17
100 | x = self.Mixed_6c(x)
101 | # N x 768 x 17 x 17
102 | x = self.Mixed_6d(x)
103 | # N x 768 x 17 x 17
104 | x = self.Mixed_6e(x)
105 | # N x 768 x 17 x 17
106 | x = self.Mixed_7a(x)
107 | # N x 1280 x 8 x 8
108 | x = self.Mixed_7b(x)
109 | # N x 2048 x 8 x 8
110 | backbone_tensor = self.Mixed_7c(x)
111 | if self.use_att:
112 | att = self.att_conv(backbone_tensor)
113 | backbone_tensor = backbone_tensor + backbone_tensor * torch.softmax(att, dim=1)
114 | if finetune and self.finetuned_scale_fn is not None:
115 | feature = self.finetuned_scale_fn(backbone_tensor)
116 | else:
117 | feature = self.pool_method(backbone_tensor).view(-1, 2048)
118 | if self.scale is not None:
119 | feature = self.scale_fn(feature)
120 |
121 | return F.normalize(feature)
122 |
--------------------------------------------------------------------------------
/models/pmn.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 | from torch.distributions import Categorical
5 | import numpy as np
6 |
7 | from .transformer import StrokeEncoderTransformer
8 |
9 | from utils.coords_utils import resample_stroke, normalize_strokes
10 | from utils.distance_transform import compute_distance_transform_l2, make_coordinate_grid
11 | from utils.transformations import ToTransformMatrix, get_predefined_primitives, transform_primitives
12 |
13 |
14 | class PrimitiveMatchingNetwork(nn.Module):
15 | def __init__(self, Nz=256,
16 | temperature=0.2,
17 | primitive_names=['square', 'triangle', 'circle', 'line', 'halfcircle', 'u', 'corner', 'dot'],
18 | n_stroke_points=25,
19 | dt_gamma=6., use_pos_embed=False,
20 | use_sinusoid_embed=False,
21 | transform_bound=None, use_proportion_scale=False,
22 | learn_compatibility=False, transformations='rsr'):
23 | super().__init__()
24 | self.Nz = Nz
25 | self.encoder = StrokeEncoderTransformer(
26 | Nz=Nz, embed_sketch=False, n_layer_strokes=6,
27 | use_pos_embed=use_pos_embed, use_sinusoid_embed=use_sinusoid_embed
28 | )
29 |
30 | #ALL_TRANSFORMATIONS = ['translate', 'rotate', 'scale_full_bounded', 'scale_full', 'uni_scale', 'proportion_scale', 'shear_x', 'shear_y'][::-1]
31 |
32 | transforms = []
33 | self.parameters_per_transform = []
34 | for ts in transformations:
35 | if ts == 'r':
36 | transforms.append('rotate')
37 | self.parameters_per_transform.append(1)
38 | elif ts == 's':
39 | if use_proportion_scale:
40 | transforms.append('proportion_scale')
41 | self.parameters_per_transform.append(1)
42 | else:
43 | transforms.append('scale_full')
44 | self.parameters_per_transform.append(2)
45 | elif ts == 'h':
46 | transforms.append('shear_x')
47 | transforms.append('shear_y')
48 | self.parameters_per_transform.append(1)
49 | self.parameters_per_transform.append(1)
50 |
51 | self.transformations = transforms
52 | self.transformation_layers = nn.ModuleList([ToTransformMatrix(t, bound=transform_bound) for t in self.transformations])
53 |
54 | self.learn_compatibility = learn_compatibility
55 | self.n_stroke_points = n_stroke_points
56 |
57 | self.init_primitives(primitive_names)
58 |
59 | primnet_in = 2 * Nz
60 | if self.learn_compatibility:
61 | primnet_in = primnet_in // 2
62 | self.primnet = nn.Sequential(
63 | nn.Linear(primnet_in, primnet_in//2),
64 | nn.BatchNorm1d(primnet_in//2),
65 | nn.ReLU(inplace=True),
66 | nn.Linear(primnet_in//2, primnet_in//4),
67 | nn.BatchNorm1d(primnet_in//4),
68 | nn.ReLU(inplace=True),
69 | nn.Linear(primnet_in//4,
70 | sum(self.parameters_per_transform))
71 | )
72 |
73 | temperature = torch.tensor([temperature])
74 | self.register_buffer('temperature', temperature)
75 |
76 | self.dt_gamma = dt_gamma
77 | self.criterion = nn.CrossEntropyLoss(reduction='none')
78 | self.params_criterion = nn.MSELoss(reduction='none')
79 |
80 | self.init_distance_transform()
81 |
82 | self.cache_labels_feats = None
83 | self.cache_tgt_labels = None
84 | self.cache_tgt_masks = None
85 |
86 | def init_primitives(self, primitive_names):
87 | self.primitive_names = primitive_names
88 | primitives = get_predefined_primitives(
89 | primitive_names, n_points=self.n_stroke_points
90 | )
91 | self.register_buffer('primitives', primitives)
92 | self.num_primitives = len(primitive_names)
93 |
94 | prim_is_dot = torch.tensor([torch.unique(pt).nelement() == 1 for pt in self.primitives])
95 | self.register_buffer('prim_is_dot', prim_is_dot.unsqueeze(0).unsqueeze(-1))
96 | self.prim_has_dot = self.prim_is_dot.any()
97 | if self.prim_has_dot:
98 | self.prim_dot_id = self.prim_is_dot[0, :, 0].nonzero(as_tuple=False).item()
99 | else:
100 | self.prim_dot_id = None
101 |
102 | primitives_seq_mask = torch.zeros(self.primitives.shape[:2], dtype=torch.bool)
103 | self.register_buffer('primitives_seq_mask', primitives_seq_mask)
104 | primitives_position = torch.linspace(-1., 1., steps=self.primitives.shape[1]).unsqueeze(0).repeat(self.primitives.shape[0], 1)
105 | self.register_buffer('primitives_position', primitives_position)
106 |
107 | def init_distance_transform(self):
108 | self.grid_size = 32
109 | coordinate_grid = make_coordinate_grid(self.grid_size)
110 | grid_sqz = coordinate_grid.repeat(1, self.n_stroke_points-1, 1, 1, 1)
111 | self.register_buffer('grid_sqz', grid_sqz)
112 |
113 | def calc_min_l2_dist(self, recon, target, resample=False, roll=False, invert=False):
114 | l2_dist = torch.linalg.norm(recon - target, dim=-1).mean(-1)
115 | min_l2_dist = l2_dist
116 |
117 | if resample:
118 | recon = torch.stack([resample_stroke(s.cpu(), n=self.n_stroke_points)[..., :2].to(s) for s in recon])
119 | l2_dist_res = torch.linalg.norm(recon - target, dim=-1).mean(-1)
120 | #min_l2_dist = torch.stack([min_l2_dist, l2_dist_res], dim=-1).min(-1)[0]
121 | min_l2_dist = l2_dist_res
122 |
123 | if invert:
124 | l2_dist_inv = torch.linalg.norm(recon.flip(dims=(1,)) - target, dim=-1).mean(-1)
125 | min_l2_dist = torch.stack([min_l2_dist, l2_dist_inv], dim=-1).min(-1)[0]
126 |
127 | if roll:
128 | best_l2_dist_roll = None
129 | for i in range(1, recon.shape[1]):
130 | recon_roll = recon.roll(i, dims=(1,))
131 | l2_dist_roll = torch.linalg.norm(recon_roll - target, dim=-1).mean(-1)
132 | if best_l2_dist_roll is None:
133 | best_l2_dist_roll = l2_dist_roll
134 | else:
135 | best_l2_dist_roll = torch.stack([best_l2_dist_roll, l2_dist_roll], dim=-1).min(-1)[0]
136 | if invert:
137 | l2_dist_roll_inv = torch.linalg.norm(recon_roll.flip(dims=(1,)) - target, dim=-1).mean(-1)
138 | best_l2_dist_roll = torch.stack([best_l2_dist_roll, l2_dist_roll_inv], dim=-1).min(-1)[0]
139 |
140 | min_l2_dist = torch.stack([min_l2_dist, best_l2_dist_roll], dim=-1).min(-1)[0]
141 |
142 | out = {'l2_dist_min': min_l2_dist, 'l2_dist_base': l2_dist}
143 | if resample:
144 | out['l2_dist_resample'] = l2_dist_res
145 |
146 | if invert:
147 | out['l2_dist_invert'] = l2_dist_inv
148 |
149 | if roll:
150 | out['l2_dist_roll'] = best_l2_dist_roll
151 |
152 | return out
153 |
154 | def forward(self, x_raw, x_raw_aug=None,
155 | n_strokes=None, scale=None, translate=None,
156 | seq_mask=None, position=None, n_tgt=None, main_mask=None,
157 | **kwargs):
158 |
159 | batch = x_raw
160 | target = x_raw_aug
161 |
162 | n_tgt = max(batch.shape[0], self.primitives.shape[0])
163 | if self.primitives.shape[0] > batch.shape[0]:
164 | print('WARNING: More primitives than batch strokes. Untested scenario.')
165 | target = self.primitives
166 | tgt_seq_mask = self.primitives_seq_mask
167 | tgt_position = self.primitives_position
168 |
169 | # encode:
170 | z, z_params = self.encoder(batch.transpose(0, 1), seq_mask=seq_mask, position=position)[0].split([self.Nz//2, self.Nz//2], dim=-1)
171 | zt, zt_params = self.encoder(target.transpose(0, 1), seq_mask=tgt_seq_mask, position=tgt_position)[0].split([self.Nz//2, self.Nz//2], dim=-1)
172 |
173 | if self.learn_compatibility:
174 | output = self.info_nce_loss(z, zt, n_tgt, main_mask, ignore_loss=((not self.training) or self.learn_compatibility))
175 | if self.learn_compatibility:
176 | prim_logits = output['pred_main_logits']
177 |
178 | output = {}
179 | output['loss'] = 0.
180 |
181 | if not self.learn_compatibility:
182 | z_params = torch.cat([z, z_params], dim=-1)
183 | zt_params = torch.cat([zt, zt_params], dim=-1)
184 |
185 | z_params = z_params.unsqueeze(1)
186 | zt_params = zt_params.unsqueeze(0)
187 | z_params = z_params.expand(z_params.shape[0], zt_params.shape[1], z_params.shape[2])
188 | zt_params = zt_params.expand(z_params.shape[0], zt_params.shape[1], zt_params.shape[2])
189 | z_params = z_params.reshape(-1, z_params.shape[-1])
190 | zt_params = zt_params.reshape(-1, zt_params.shape[-1])
191 |
192 | primnet_in = torch.cat([z_params, zt_params], dim=-1)
193 |
194 | prims_params = self.primnet(primnet_in)
195 |
196 | prims_params = prims_params.split(self.parameters_per_transform, dim=-1)
197 | prim_params = []
198 | for p, s, t in zip(prims_params, self.parameters_per_transform, self.transformations):
199 | pt = p.view(-1, self.num_primitives, s)
200 | if t == 'proportion_scale':
201 | pt = torch.cat([pt, -pt], dim=-1)
202 | if self.prim_has_dot:
203 | pt = pt.masked_fill(self.prim_is_dot, 0.)
204 | prim_params.append(pt)
205 |
206 | prims = transform_primitives(
207 | target, self.transformation_layers, prim_params
208 | #target, self.transformation_layers_noop, parameters_aug.split([2, 2], dim=-1)
209 | )
210 |
211 | prims = prims.squeeze(-3).squeeze(-2)[..., :2]
212 | prims = normalize_strokes(prims)[0]
213 |
214 | if self.training or not self.learn_compatibility:
215 | dt_loss = 10. * compute_distance_transform_l2(batch, prims, self.grid_sqz, batch_mask=seq_mask, gamma=self.dt_gamma)
216 | else:
217 | dt_loss = 0.
218 | if self.learn_compatibility:
219 | if self.training:
220 | if self.prim_has_dot:
221 | loss_mask = dt_loss[:, self.prim_dot_id].isclose(torch.tensor([0.], device=dt_loss.device)).unsqueeze(1)
222 | dt_loss = dt_loss.masked_fill(loss_mask, 0.)
223 |
224 | dt_loss = (dt_loss * torch.softmax(prim_logits, dim=1)).sum(1)
225 | prim_ids = prim_logits.argmax(dim=1, keepdim=True).unsqueeze(-1).unsqueeze(-1)
226 | if self.prim_has_dot:
227 | if self.training:
228 | prim_ids[loss_mask] = self.prim_dot_id
229 | else:
230 | dot_mask = batch.isclose(torch.tensor([0.], device=batch.device)).sum([-2, -1]) == (batch.shape[-2]*batch.shape[-1])
231 | prim_ids[dot_mask] = self.prim_dot_id
232 |
233 | else:
234 | prim_ids = dt_loss.argmin(dim=1, keepdim=True).unsqueeze(-1).unsqueeze(-1)
235 | if self.prim_has_dot:
236 | loss_mask = dt_loss[:, self.prim_dot_id].isclose(torch.tensor([0.], device=dt_loss.device)).unsqueeze(1)
237 | dt_loss = dt_loss.masked_fill(loss_mask, 0.)
238 | dt_loss = dt_loss.mean(1)
239 |
240 | prims = prims.gather(1, prim_ids.expand(prims.size(0), 1, prims.size(2), prims.size(3)))
241 | prims = prims.squeeze(1)
242 |
243 | output['pcoords_prim_id'] = prim_ids.squeeze(-1)
244 | output['loss'] += dt_loss
245 |
246 | output['pcoords_raw'] = prims
247 | output['pcoords_n_strokes'] = n_strokes
248 | output['pcoords_scale'] = scale
249 | output['pcoords_translate'] = translate
250 | output['pcoords_seq_mask'] = self.primitives_seq_mask[:1].expand(prims.shape[:2])
251 | output['pcoords_position'] = self.primitives_position[:1].expand(prims.shape[:2])
252 |
253 | return output
254 |
255 | def info_nce_loss(self, features, targets, n_tgt=None, main_mask=None,
256 | ignore_loss=False):
257 |
258 | if n_tgt is None:
259 | n_tgt = targets.shape[0]
260 | labels = torch.arange(n_tgt).to(features.device)
261 |
262 | features = F.normalize(features, dim=-1)
263 | targets = F.normalize(targets, dim=-1)
264 |
265 | similarity_matrix = torch.matmul(features, targets.T) / self.temperature
266 | main_simmat = similarity_matrix[:n_tgt]
267 | if main_mask is not None:
268 | main_simmat += main_mask
269 | mod_simmat = similarity_matrix.T[:n_tgt]
270 | if not ignore_loss:
271 | loss_main = self.criterion(main_simmat, labels)
272 | loss_mod = self.criterion(mod_simmat, labels)
273 | total_loss = (loss_main + loss_mod) / 2
274 | else:
275 | total_loss = 0.
276 |
277 | labels_mod = labels[:mod_simmat.shape[0]]
278 |
279 | _, pred_main = torch.max(main_simmat, 1)
280 | acc_main = (labels[:pred_main.shape[0]] == pred_main).float()
281 | _, pred_mod = torch.max(mod_simmat, 1)
282 | acc_mod = (labels_mod[:pred_mod.shape[0]] == pred_mod).float()
283 |
284 | output = {'loss': total_loss,
285 | 'acc_main': acc_main,
286 | 'acc_mod': acc_mod,
287 | 'pred_main': pred_main,
288 | 'pred_mod': pred_mod,
289 | 'pred_main_logits': main_simmat}
290 |
291 | return output
292 |
293 | def l2_eval(self, batch):
294 | prims = self.draw(batch)
295 | l2_dist = self.calc_min_l2_dist(prims, batch, resample=True, roll=True, invert=True)
296 | dist_transform = compute_distance_transform_l2(prims, batch, self.grid_sqz, gamma=self.dt_gamma)
297 | return l2_dist['l2_dist_min'], dist_transform
298 |
299 | def draw(self, **inputs):
300 | return self.forward(**inputs)
301 |
302 | def compute_l2(self,prims,batch):
303 | return self.calc_min_l2_dist(prims, batch, resample=True, roll=True, invert=True)
304 |
--------------------------------------------------------------------------------
/models/transformer.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 | import numpy as np
5 |
6 |
7 | class StrokeEncoderTransformer(nn.Module):
8 | def __init__(self, Nz=128, enc_hidden_size=128, dropout=0.1, stroke_len=25,
9 | embed_sketch=True, n_layer_strokes=3, n_layer_sketch=3,
10 | use_pos_embed=True, use_sinusoid_embed=False, fourier_scale=1.,
11 | out_dim=None, use_embed_token=True, return_points_embed=False):
12 | super().__init__()
13 | if out_dim is None:
14 | out_dim = Nz
15 | self.enc_hidden_size = enc_hidden_size
16 | self.embed_sketch = embed_sketch
17 | self.stroke_len = stroke_len
18 | self.use_pos_embed = use_pos_embed
19 | self.sinusoid_embed = use_sinusoid_embed
20 | self.use_embed_token = use_embed_token
21 | self.return_points_embed = return_points_embed
22 | # Transformer:
23 | encoder_layer = nn.TransformerEncoderLayer(
24 | enc_hidden_size, 8, dim_feedforward=4*enc_hidden_size,
25 | dropout=dropout, activation='gelu'
26 | )
27 | self.stroke_transformer = nn.TransformerEncoder(
28 | encoder_layer, num_layers=n_layer_strokes
29 | )
30 | self.fc_in = nn.Linear(2, enc_hidden_size)
31 | self.fc_out = nn.Linear(enc_hidden_size, out_dim)
32 | if self.use_pos_embed and not self.sinusoid_embed:
33 | self.pos_embed = nn.Parameter(torch.randn(stroke_len+1, 1, enc_hidden_size))
34 | else:
35 | self.embed_token = nn.Parameter(torch.randn(1, 1, enc_hidden_size))
36 | if self.use_pos_embed:
37 | self.fc_pos_embed = nn.Linear(enc_hidden_size//(2*3)*2, enc_hidden_size)
38 |
39 | if self.sinusoid_embed:
40 | randn = fourier_scale * torch.randn((1, enc_hidden_size//(2*3)))
41 | #randn = fourier_scale * torch.randn((3, enc_hidden_size//2))
42 | self.register_buffer('fourier_randn', randn)
43 |
44 | if self.embed_sketch:
45 | if self.sinusoid_embed:
46 | self.fc_transform = nn.Linear((enc_hidden_size//(2*3))*2*3, enc_hidden_size)
47 | #self.fc_transform = nn.Linear(enc_hidden_size, enc_hidden_size)
48 | else:
49 | self.fc_transform = nn.Linear(3, enc_hidden_size)
50 | self.sketch_transformer = nn.TransformerEncoder(encoder_layer,
51 | num_layers=n_layer_sketch)
52 | self.sketch_embed = nn.Parameter(torch.randn(1, enc_hidden_size))
53 | # active dropout:
54 | self.train()
55 |
56 | def pad_stroke_sequence(self, inputs, stroke_lens):
57 | max_stroke_len = max(stroke_lens)
58 | offset = 0
59 | strokes = []
60 | mask = torch.ones((len(stroke_lens), max_stroke_len+1), device=inputs.device, dtype=torch.bool)
61 | mask[:, -1] = False
62 | if self.use_pos_embed:
63 | positions = torch.zeros(max_stroke_len, (len(stroke_lens)), device=inputs.device)
64 | else:
65 | positions = None
66 | for i, sl in enumerate(stroke_lens):
67 | strokes.append(torch.cat([inputs[offset:offset+sl],
68 | torch.zeros((max_stroke_len-sl, 2), device=inputs.device)]))
69 | mask[i, :sl] = False
70 | if self.use_pos_embed:
71 | positions[:sl, i] = torch.linspace(-1, 1., steps=sl, device=inputs.device)
72 | offset += sl
73 | return torch.stack(strokes, dim=1), mask, max_stroke_len, positions
74 |
75 | def forward(self, inputs, n_strokes=None, scale=None, translate=None, stroke_lens=None, seq_mask=None, position=None, mask=None, points_mask=None, **kwargs):
76 | if inputs.dim() == 2:
77 | inputs, seq_mask, slen, pos = self.pad_stroke_sequence(inputs.transpose(0, 1), stroke_lens)
78 | if points_mask is None:
79 | points_mask = seq_mask
80 | else:
81 | points_mask = points_mask | seq_mask
82 | elif seq_mask is not None:
83 | slen = inputs.shape[0]
84 | pos = position.transpose(0, 1)
85 | seq_mask = torch.cat([seq_mask, torch.zeros_like(seq_mask[:, :1])], dim=1)
86 | if points_mask is None:
87 | points_mask = seq_mask
88 | else:
89 | points_mask = points_mask | seq_mask
90 | else:
91 | slen = self.stroke_len
92 | embed = self.fc_in(inputs)
93 | if self.use_pos_embed:
94 | if self.sinusoid_embed:
95 | pos_embed = (2.*np.pi*pos.unsqueeze(-1)) @ self.fourier_randn
96 | pos_embed = torch.cat([torch.sin(pos_embed), torch.cos(pos_embed)], dim=-1)
97 | pos_embed = self.fc_pos_embed(pos_embed)
98 | pos_embed = torch.cat([pos_embed, self.embed_token.expand(1, pos_embed.shape[1], pos_embed.shape[2])])
99 | else:
100 | pos_embed = self.pos_embed
101 | else:
102 | pos_embed = torch.cat([torch.zeros((slen, 1, self.enc_hidden_size), device=embed.device), self.embed_token])
103 | embed = torch.cat([embed, torch.zeros((1, embed.size(1), embed.size(2)), device=embed.device)]) + pos_embed
104 | embed = self.stroke_transformer(embed, src_key_padding_mask=points_mask)
105 | if self.return_points_embed:
106 | points_embed = embed[:-1]
107 | embed = embed[-1]
108 |
109 | if self.embed_sketch:
110 | transform = torch.cat([scale, translate], dim=-1).squeeze(1)
111 | if self.sinusoid_embed:
112 | transform = (2.*np.pi*transform.unsqueeze(-1)) @ self.fourier_randn
113 | #transform = (2.*np.pi*transform) @ self.fourier_randn
114 | transform = torch.cat([torch.sin(transform), torch.cos(transform)], dim=-1)
115 | transform = transform.flatten(-2)
116 | transform_embed = self.fc_transform(transform)
117 | embed = embed + transform_embed
118 |
119 | embed_batch = torch.split(embed, n_strokes.tolist())
120 | seq_len = n_strokes.max()
121 | batch = []
122 | padding_mask = []
123 | for eb in embed_batch:
124 | pad_len = seq_len-eb.size(0)
125 | padding = torch.zeros((pad_len, eb.size(1)), device=eb.device)
126 | embd = torch.cat([eb, padding])
127 | if self.use_embed_token:
128 | embd = torch.cat([embd, self.sketch_embed])
129 | batch.append(embd)
130 | if mask is None:
131 | pad_mask = torch.zeros(seq_len+(1 if self.use_embed_token else 0),
132 | device=eb.device, dtype=torch.bool)
133 | if self.use_embed_token:
134 | pad_mask[-pad_len-1:-1] = True
135 | elif pad_len != 0:
136 | pad_mask[-pad_len:] = True
137 | padding_mask.append(pad_mask)
138 |
139 | batch = torch.stack(batch, dim=1)
140 | if mask is None:
141 | padding_mask = torch.stack(padding_mask, dim=0)
142 | else:
143 | padding_mask = mask
144 | embed = self.sketch_transformer(batch, src_key_padding_mask=padding_mask)
145 | if self.use_embed_token:
146 | embed = embed[-1]
147 | else:
148 | padding_mask = None
149 |
150 | if self.return_points_embed:
151 | return self.fc_out(embed), points_embed, padding_mask
152 | else:
153 | return self.fc_out(embed), padding_mask
154 |
--------------------------------------------------------------------------------
/save_processed_images.py:
--------------------------------------------------------------------------------
1 | import datetime
2 | import os
3 | from itertools import islice
4 |
5 | import torch
6 | from tqdm import tqdm
7 |
8 | from models import get_model
9 | from models.communication import calc_segments_per_sketch
10 | from utils.arguments import parser
11 | from utils.data import get_data
12 |
13 |
14 | def split_by_lengths(seq, num):
15 | it = iter(seq)
16 | for x in num:
17 | out = list(islice(it, x))
18 | if out:
19 | yield out
20 | else:
21 | return # StopIteration
22 | remain = list(it)
23 | if remain:
24 | yield remain
25 |
26 |
27 | if __name__ == "__main__":
28 | args = parser.parse_args()
29 |
30 | DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
31 |
32 | # Add timestamp to logdir
33 | if args.log_name is None:
34 | LOG_DIR = os.path.join(
35 | args.log_dir, datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
36 | )
37 | else:
38 | LOG_DIR = os.path.join(args.log_dir, args.log_name)
39 |
40 | dataloader_coords, n_classes, label_names = get_data(
41 | args.data_dir,
42 | args.dataset,
43 | batch_size=args.batch_size,
44 | train=True,
45 | preprocessed_root=args.preprocessed_root,
46 | load_fgsbir_photos=args.load_fgsbir_photos,
47 | resample_strokes=not args.no_stroke_resampling,
48 | max_stroke_length=args.max_stroke_length,
49 | shuffle=False,
50 | )
51 |
52 | test_dataloader_coords, _, _ = get_data(
53 | args.data_dir,
54 | args.dataset,
55 | batch_size=args.n_log_img,
56 | train=False,
57 | preprocessed_root=args.preprocessed_root,
58 | load_fgsbir_photos=args.load_fgsbir_photos,
59 | resample_strokes=not args.no_stroke_resampling,
60 | max_stroke_length=args.max_stroke_length,
61 | shuffle=False,
62 | )
63 |
64 | if args.model_type == "none":
65 | model = None
66 | else:
67 | model = get_model(args, 9, DEVICE)
68 |
69 | if args.test is not None and (
70 | not args.model_type == "communication" or args.loss_model_type != "none"
71 | ):
72 | model.load_state_dict(torch.load(args.test))
73 | model.eval()
74 |
75 | model_type = args.model_type
76 | if args.add_comm_model:
77 | args.model_type = "communication"
78 | comm_model = get_model(args, 9, DEVICE)
79 | n_iters = 2
80 | else:
81 | comm_model = None
82 | n_iters = 1
83 |
84 | loaders = [("test", test_dataloader_coords), ("train", dataloader_coords)]
85 | # Preprocess strokes
86 | with torch.no_grad():
87 | for dset, dset_loader in loaders:
88 | new_coords_list = []
89 | for batch in tqdm(dset_loader, desc=f"Pre-processing data {dset}"):
90 | for k in batch.keys():
91 | if k in [
92 | "x_raw",
93 | "x_raw_aug",
94 | "scale",
95 | "scale_aug",
96 | "translate",
97 | "translate_aug",
98 | "parameters_aug",
99 | ]:
100 | if isinstance(batch[k], list):
101 | batch[k] = batch[k][0]
102 | if k == "n_strokes_aug":
103 | batch[k] = torch.stack(batch[k], dim=1).view(-1)
104 | if isinstance(batch[k], torch.Tensor):
105 | batch[k] = batch[k].to("cuda")
106 |
107 | orig_strokes = batch["n_strokes"]
108 | for citer in range(n_iters):
109 | strokes = batch["n_strokes"]
110 | if model is None:
111 | points = list(
112 | batch["x_raw"].to("cpu").split(list(strokes), dim=0)
113 | )
114 | scale = list(
115 | batch["scale"].to("cpu").split(list(strokes), dim=0)
116 | )
117 | translate = list(
118 | batch["translate"].to("cpu").split(list(strokes), dim=0)
119 | )
120 | stroke_lens = batch["stroke_lens"].split(list(strokes), dim=0)
121 | _, _, segments_per_sketch = calc_segments_per_sketch(
122 | batch["segments"], batch["stroke_lens"], batch["n_strokes"]
123 | )
124 | segments = batch["segments"].split(
125 | list(segments_per_sketch), dim=0
126 | )
127 |
128 | new_coords_list += [
129 | {
130 | "x_raw": x.detach().cpu(),
131 | "label": l.item(),
132 | "n_strokes": n.detach().cpu(),
133 | "scale": s.detach().cpu(),
134 | "translate": t.detach().cpu(),
135 | "segments": se.detach().cpu(),
136 | "stroke_lens": sl.detach().cpu(),
137 | }
138 | for x, l, n, s, t, se, sl in zip(
139 | points,
140 | batch["label"],
141 | strokes,
142 | scale,
143 | translate,
144 | segments,
145 | stroke_lens,
146 | )
147 | ]
148 |
149 | else:
150 | if comm_model is not None and citer == 1:
151 | new_coords = comm_model(**batch)
152 | else:
153 | new_coords = model.draw(**batch)
154 |
155 | if citer == 1 or model_type in ["pmn", "communication"]:
156 | if comm_model is not None and citer == 0:
157 | for k, v in new_coords.items():
158 | if k == "pcoords_raw":
159 | batch["x_raw"] = v
160 | elif k.startswith("pcoords"):
161 | batch[k.replace("pcoords_", "")] = v
162 | batch["n_strokes_orig"] = orig_strokes
163 | else:
164 | strokes = new_coords["pcoords_n_strokes"]
165 | if isinstance(new_coords["pcoords_raw"], list):
166 | offset = 0
167 | points = []
168 | for n_s in strokes:
169 | points.append(
170 | [
171 | p.detach().cpu()
172 | for p in new_coords["pcoords_raw"]
173 | ][offset : offset + n_s]
174 | )
175 | offset += n_s
176 | else:
177 | points = list(
178 | new_coords["pcoords_raw"]
179 | .detach()
180 | .to("cpu")
181 | .split(list(strokes), dim=0)
182 | )
183 | scale = list(
184 | new_coords["pcoords_scale"]
185 | .to("cpu")
186 | .split(list(strokes), dim=0)
187 | )
188 | translate = list(
189 | new_coords["pcoords_translate"]
190 | .to("cpu")
191 | .split(list(strokes), dim=0)
192 | )
193 |
194 | stroke_lens = batch["stroke_lens"].split(
195 | list(orig_strokes), dim=0
196 | )
197 | _, _, segments_per_sketch = calc_segments_per_sketch(
198 | batch["segments"],
199 | batch["stroke_lens"],
200 | batch["n_strokes"],
201 | )
202 | segments = batch["segments"].split(
203 | list(segments_per_sketch), dim=0
204 | )
205 | new_coords_list += [
206 | {
207 | "x_raw": x,
208 | "label": l.item(),
209 | "n_strokes": n.detach().cpu(),
210 | "scale": s.detach().cpu(),
211 | "translate": t.detach().cpu(),
212 | "segments": se.detach().cpu(),
213 | "stroke_lens": sl.detach().cpu(),
214 | }
215 | for x, l, n, s, t, se, sl in zip(
216 | points,
217 | batch["label"],
218 | strokes,
219 | scale,
220 | translate,
221 | segments,
222 | stroke_lens,
223 | )
224 | ]
225 |
226 | if "pcoords_prim_id" in new_coords:
227 | prim_ids = list(
228 | new_coords["pcoords_prim_id"]
229 | .to("cpu")
230 | .split(list(strokes), dim=0)
231 | )
232 | for i, pi in enumerate(prim_ids):
233 | new_coords_list[-len(prim_ids) :][i][
234 | "prim_id"
235 | ] = pi.detach().cpu()
236 |
237 | else:
238 | sketches = list(split_by_lengths((new_coords), strokes))
239 | split_scale = list(
240 | batch["scale"].split(list(strokes), dim=0)
241 | )
242 | split_translate = list(
243 | batch["translate"].split(list(strokes), dim=0)
244 | )
245 | new_strokes = torch.Tensor([]).to("cpu")
246 | scales = torch.Tensor([]).to("cuda")
247 | translates = torch.Tensor([]).to("cuda")
248 | strokes = list(strokes)
249 | for i in range(len(sketches)):
250 | strokes[i] = 0
251 | for j in range(len(sketches[i])):
252 | scales = torch.cat(
253 | [
254 | scales,
255 | split_scale[i][j].repeat(
256 | len(sketches[i][j]), 1, 1
257 | ),
258 | ],
259 | dim=0,
260 | )
261 | translates = torch.cat(
262 | [
263 | translates,
264 | split_translate[i][j].repeat(
265 | len(sketches[i][j]), 1, 1
266 | ),
267 | ],
268 | dim=0,
269 | )
270 | new_strokes = torch.cat(
271 | [new_strokes, sketches[i][j]], dim=0
272 | )
273 | strokes[i] += len(sketches[i][j])
274 |
275 | if comm_model is not None:
276 | batch["x_raw"] = new_strokes.to(batch["x_raw"])
277 | batch["n_strokes"] = torch.tensor(strokes).to(
278 | batch["n_strokes"]
279 | )
280 | batch["scale"] = scales.to(batch["scale"])
281 | batch["translate"] = translates.to(batch["translate"])
282 | batch["n_strokes_orig"] = orig_strokes
283 | else:
284 | scale = list(scales.split(strokes, dim=0))
285 | translate = list(translates.split(strokes, dim=0))
286 | points = list(new_strokes.split(strokes, dim=0))
287 | strokes = torch.tensor(strokes)
288 | stroke_lens = batch["stroke_lens"].split(
289 | list(batch["n_strokes"]), dim=0
290 | )
291 | _, _, segments_per_sketch = calc_segments_per_sketch(
292 | batch["segments"],
293 | batch["stroke_lens"],
294 | batch["n_strokes"],
295 | )
296 | segments = batch["segments"].split(
297 | list(segments_per_sketch), dim=0
298 | )
299 |
300 | new_coords_list += [
301 | {
302 | "x_raw": x,
303 | "label": l.item(),
304 | "n_strokes": n,
305 | "scale": s.detach().cpu(),
306 | "translate": t.detach().cpu(),
307 | "segments": se.detach().cpu(),
308 | "stroke_lens": sl.detach().cpu(),
309 | "n_strokes_orig": n_orig.detach().cpu(),
310 | }
311 | for x, l, n, s, t, se, sl, n_orig in zip(
312 | points,
313 | batch["label"],
314 | strokes,
315 | scale,
316 | translate,
317 | segments,
318 | stroke_lens,
319 | orig_strokes,
320 | )
321 | ]
322 |
323 | dset_loader.dataset.set_preprocessed(new_coords_list)
324 | dset_loader.dataset.save_preprocessed(
325 | os.path.join(LOG_DIR, "data"),
326 | save_images=not args.only_save_coords,
327 | suffix=".npy",
328 | )
329 |
--------------------------------------------------------------------------------
/trainer.py:
--------------------------------------------------------------------------------
1 | import os
2 | from collections import defaultdict
3 | from contextlib import nullcontext
4 |
5 | import numpy as np
6 | import torch
7 | import torch.nn.functional as F
8 | import torchvision.transforms as transforms
9 | from tqdm import tqdm
10 | import matplotlib.pyplot as plt
11 |
12 | from utils.metrics import TbLogger, Accumulator, log_metrics, log_images
13 | from utils.coords_utils import PRIM_COLORS, PRIM_ORDER, make_image_fast
14 | from utils.plt_blit import BlitManager
15 |
16 |
17 | class Trainer:
18 | def __init__(self, model_type, model, train, learning_rate, epochs,
19 | dataloader, test_dataloader, label_names, device, log_dir,
20 | log_every, n_log_img, save_every, view_scale, weight_decay):
21 | self.model_type = model_type
22 | self.model = model
23 | self.train = train
24 | self.epochs = epochs if self.train else 1
25 | self.dataloader = dataloader
26 | self.test_dataloader = test_dataloader
27 | self.label_names = label_names
28 | self.device = device
29 | self.log_dir = log_dir + ('' if self.train else '_test')
30 | self.log_every = log_every
31 | self.n_log_img = n_log_img
32 | self.save_every = save_every
33 | self.view_scale = view_scale
34 | self.best_result = None
35 |
36 | self.tblogger = TbLogger(self.log_dir)
37 | if self.train:
38 | self.optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
39 |
40 | self.metrics = defaultdict(Accumulator)
41 | self.update_steps = 0
42 | self.blit_manager = None
43 |
44 | def run(self):
45 | for e in range(self.epochs):
46 | if not self.train:
47 | self.test_dataloader.generator.manual_seed(42)
48 | tqdm_loader = tqdm(self.dataloader if self.train else self.test_dataloader)
49 |
50 | self.update_steps = self.run_epoch(tqdm_loader, self.train,
51 | self.update_steps)
52 |
53 | if self.train:
54 | self.test_dataloader.generator.manual_seed(42)
55 | self.run_epoch(tqdm(self.test_dataloader), False, 0)
56 |
57 | self.tblogger.close()
58 |
59 | def update_metrics(self, outputs, train):
60 | prefix = 'train' if train else 'test'
61 |
62 | if isinstance(outputs['loss'],float):
63 | self.metrics[f'{prefix}/loss'].add(value=outputs['loss'])
64 | else:
65 | self.metrics[f'{prefix}/loss'].add(value=outputs['loss'].mean().item())
66 |
67 | if 'acc_main' in outputs:
68 | self.metrics[f'{prefix}/acc'].add(value=outputs['acc_main'].mean().item())
69 | if 'acc_mod' in outputs:
70 | self.metrics[f'{prefix}/acc_mod'].add(value=outputs['acc_mod'].mean().item())
71 | if 'cls_acc_main' in outputs and 'cls_acc_mod' in outputs and outputs['cls_acc_main'] is not None and outputs['cls_acc_mod'] is not None:
72 | self.metrics[f'{prefix}/cls_acc'].add(value=outputs['cls_acc_main'].mean().item())
73 | self.metrics[f'{prefix}/cls_acc_mod'].add(value=outputs['cls_acc_mod'].mean().item())
74 | for k, v in outputs.items():
75 | if k.startswith('l2_dist'):
76 | self.metrics[f'{prefix}/{k}'].add(value=v.mean().item())
77 |
78 | def run_epoch(self, loader, train, steps):
79 | if self.model_type == 'communication':
80 | budget_acc = torch.zeros(20)
81 | segment_acc = []
82 | total_cnt = 0
83 | if self.model_type == 'fgsbir' or (self.model_type == 'communication' and self.model.loss_type == 'fgsbir'):
84 | sketch_names = []
85 | sketch_features = []
86 | image_names = []
87 | images_features = []
88 |
89 | for idx, batch in enumerate(loader):
90 | for k in batch.keys():
91 | if k in ['x_raw', 'x_raw_aug', 'scale', 'scale_aug',
92 | 'translate', 'translate_aug', 'parameters_aug']:
93 | if isinstance(batch[k], list):
94 | batch[k] = batch[k][0]
95 | if k == 'n_strokes_aug':
96 | batch[k] = torch.stack(batch[k], dim=1).view(-1)
97 | if isinstance(batch[k], torch.Tensor):
98 | batch[k] = batch[k].to(self.device)
99 |
100 | if train:
101 | self.optimizer.zero_grad()
102 | ctx = nullcontext()
103 | else:
104 | self.model.eval()
105 | ctx = torch.no_grad()
106 |
107 | with ctx:
108 | outputs = self.run_model(batch, train)
109 |
110 | if train:
111 | outputs['loss'].mean().backward()
112 | self.optimizer.step()
113 | else:
114 | self.model.train()
115 |
116 | self.update_metrics(outputs, train=train)
117 |
118 | steps += 1
119 |
120 | if steps % 100 == 0 and train:
121 | log_metrics(self.metrics, self.tblogger, steps)
122 | self.metrics = defaultdict(Accumulator)
123 |
124 | if steps % self.log_every == 0:
125 | postfix = '' #if train else f'/{steps}'
126 | all_log_images = self.log_images(batch, outputs, train,
127 | coords_type='x_raw' if 'pcoords_raw' in outputs else 'x')
128 |
129 | for phase, log_imgs, n_img in all_log_images:
130 | img_tensor = F.interpolate(log_imgs, size=(self.view_scale, self.view_scale))
131 | log_images(f'image_drawing_{phase}{postfix}', img_tensor, n_img, self.tblogger, steps if train else self.update_steps)
132 |
133 | if steps % self.save_every == 0:
134 | torch.save(self.model.state_dict(), os.path.join(self.log_dir, 'model_latest.pt'))
135 |
136 | if self.model_type == 'communication' and self.model.loss_type == 'class':
137 | if outputs['segments_per_sketch'] is None:
138 | seq_lens = batch['n_strokes'].detach().cpu()
139 | max_seq_lens = outputs['pcoords_n_strokes'].detach().cpu()
140 | else:
141 | seq_lens = outputs['segments_per_sketch'].detach().cpu()
142 | max_seq_lens = outputs['pcoords_n_strokes'].detach().cpu()
143 |
144 | acc_all = outputs['acc_main_all'].detach().cpu()
145 | budget = torch.arange(seq_lens.max()).unsqueeze(0).repeat(seq_lens.shape[0], 1)
146 | budget = (budget+1) / seq_lens.unsqueeze(1)
147 | for b in range(20):
148 | curr_budget = ((b+1)/20)
149 | if self.model.budget is not None and curr_budget > self.model.budget:
150 | budget_acc[b] = budget_acc[b-1]
151 | continue
152 | budget_mask = budget >= curr_budget
153 | budget_arg = budget_mask.float().argmax(dim=1)
154 | budget_arg = torch.stack([budget_arg, max_seq_lens-1]).min(0)[0]
155 | budget_acc[b] += acc_all.gather(1, budget_arg.unsqueeze(1)).sum()
156 |
157 | if not train:
158 | for aa, bud, seq in zip (acc_all, budget, seq_lens):
159 | if self.model.budget is None:
160 | sl = seq
161 | else:
162 | sl = int(np.ceil(seq * self.model.budget))
163 | segment_acc.append(list(zip(bud[:sl].numpy(), aa[:sl].numpy())))
164 |
165 | total_cnt += acc_all.shape[0]
166 |
167 | if self.model_type == 'fgsbir' or (self.model_type == 'communication' and self.model.loss_type == 'fgsbir'):
168 | sketch_features.extend(outputs['sketch_feature'].cpu())
169 | sketch_names.extend(batch['positive_name'])
170 |
171 | for name, img_feat in zip(batch['positive_name'], outputs['image_feature'].cpu()):
172 | if name not in image_names:
173 | image_names.append(name)
174 | images_features.append(img_feat)
175 |
176 | if self.model_type == 'fgsbir' or (self.model_type == 'communication' and self.model.loss_type == 'fgsbir'):
177 | rank = []
178 | images_features = torch.stack(images_features)
179 |
180 | for name, sketch_feature in zip(sketch_names, sketch_features):
181 | position_query = image_names.index(name)
182 |
183 | if self.model.loss_type == 'cross_entropy':
184 | distance = -torch.matmul(sketch_feature.unsqueeze(0), images_features.T)
185 | target_distance = -torch.matmul(sketch_feature.unsqueeze(0), images_features[position_query].unsqueeze(1))
186 | else:
187 | distance = F.pairwise_distance(sketch_feature.unsqueeze(0), images_features)
188 | target_distance = F.pairwise_distance(sketch_feature.unsqueeze(0),
189 | images_features[position_query].unsqueeze(0))
190 |
191 | rank.append(distance.le(target_distance).sum().item())
192 |
193 | rank = np.array(rank)
194 | top1 = (rank <= 1).sum() / rank.shape[0]
195 | top5 = (rank <= 5).sum() / rank.shape[0]
196 | top10 = (rank <= 10).sum() / rank.shape[0]
197 | prefix = 'train' if train else 'test'
198 | self.metrics[f'{prefix}/acc'].add(value=top1)
199 | self.metrics[f'{prefix}/acc5'].add(value=top5)
200 | self.metrics[f'{prefix}/acc10'].add(value=top10)
201 |
202 | if self.model_type == 'communication' and self.model.loss_type == 'class':
203 | prefix = 'train' if train else 'test'
204 | for b, acc in enumerate(budget_acc):
205 | self.metrics[f'{prefix}/budget_acc_{(b+1)/20}'].add(value=acc.item()/total_cnt)
206 |
207 |
208 | aggregated = log_metrics(self.metrics, self.tblogger, steps if train else self.update_steps)
209 | self.metrics = defaultdict(Accumulator)
210 | if not train:
211 | is_best = False
212 | if 'test/acc' in aggregated:
213 | current_acc = aggregated['test/acc']
214 | if self.best_result is None or self.best_result < current_acc:
215 | self.best_result = current_acc
216 | is_best = True
217 |
218 | else:
219 | current_loss = aggregated['test/loss']
220 | if self.best_result is None or self.best_result > current_loss:
221 | self.best_result = current_loss
222 | is_best = True
223 |
224 | if is_best:
225 | torch.save(self.model.state_dict(), os.path.join(self.log_dir, 'model_best_acc.pt'))
226 | if 'test/acc' in aggregated:
227 | with open(os.path.join(self.log_dir, 'test_acc.txt'), 'w') as f:
228 | f.write(f'Acc: {self.best_result}\n')
229 | if 'test/acc5' in aggregated:
230 | f.write(f'Acc 5: {aggregated["test/acc5"]}\n')
231 | if 'test/acc10' in aggregated:
232 | f.write(f'Acc 10: {aggregated["test/acc10"]}\n')
233 | if self.model_type == 'communication' and self.model.loss_type == 'class':
234 | f.write('Budget Acc: ' + ' '.join([str(ba.item()/total_cnt) for ba in budget_acc]))
235 |
236 | if self.model_type == 'communication' and self.model.loss_type == 'class':
237 | segments = sorted(set([s for segs in segment_acc for s, _ in segs]))
238 | seg_acc = np.zeros(len(segments))
239 | for segs in segment_acc:
240 | last_idx = 0
241 | last_acc = 0.
242 | for bud, acc in segs:
243 | curr_idx = segments.index(bud)
244 | seg_acc[last_idx:curr_idx] += last_acc
245 | last_idx = curr_idx
246 | last_acc = acc
247 | seg_acc[last_idx:] += last_acc
248 | #segment_acc = [[k, v] for k, v in sorted(segment_acc.items())]
249 | #segment_acc = np.array(segment_acc)
250 | seg_acc = seg_acc / total_cnt
251 | with open(os.path.join(self.log_dir, 'budget_acc.txt'), 'w') as f:
252 | for bud, acc in zip(segments, seg_acc):
253 | f.write(f'{bud} {acc}\n')
254 |
255 | return steps
256 |
257 | def init_blit_manager(self):
258 | fig, ax = plt.subplots()
259 | self.blit_manager = BlitManager(ax, fig.canvas)
260 | fig.canvas.draw()
261 |
262 | def log_images(self, inputs, outputs, train, coords_type='x'):
263 | if self.blit_manager is None:
264 | self.init_blit_manager()
265 |
266 | if coords_type == 'x':
267 | x_input = inputs['x'].detach().cpu().numpy()
268 | if 'x_aug' in inputs:
269 | x_aug_input = inputs['x_aug'].detach().cpu().numpy()
270 | pcoords = outputs['pcoords'].detach().cpu().numpy()
271 | elif coords_type == 'x_raw':
272 | def preprocess_raw(inputs, base, prefix='', postfix=''):
273 | if isinstance(inputs[prefix+base+postfix], list):
274 | x_raw = [x.detach().cpu().numpy() for x in inputs[prefix+base+postfix]]
275 | else:
276 | x_raw = inputs[prefix+base+postfix].detach().cpu().numpy()
277 | scale = inputs[prefix+'scale'+postfix].detach().cpu().numpy()
278 | translate = inputs[prefix+'translate'+postfix].detach().cpu().numpy()
279 | seq_mask = inputs[prefix+'seq_mask'+postfix]
280 | if seq_mask is not None:
281 | seq_mask= seq_mask.detach().cpu().numpy()
282 | if prefix+'prim_id'+postfix in inputs and self.model_type == 'pmn':
283 | prim_id = inputs[prefix+'prim_id'+postfix].detach().cpu().numpy()
284 | color_per_id = [PRIM_COLORS[PRIM_ORDER.index(prim_name)] for prim_name in self.model.primitive_names[:-1] + ['circle']]
285 | else:
286 | prim_id = None
287 | offset = 0
288 | x_input = []
289 | colors = []
290 | for nstr in inputs[prefix+'n_strokes'+postfix]:
291 | x_input.append((x_raw[offset:offset+nstr],
292 | scale[offset:offset+nstr],
293 | translate[offset:offset+nstr],
294 | seq_mask[offset:offset+nstr] if seq_mask is not None else seq_mask))
295 | if prim_id is None:
296 | colors.append(None)
297 | else:
298 | colors.append([color_per_id[pi.item()] for pi in prim_id[offset:offset+nstr]])
299 | offset += nstr
300 | return x_input, colors
301 | x_input, _ = preprocess_raw(inputs, 'x_raw')
302 | if 'x_aug' in inputs or 'x_raw_aug' in inputs:
303 | x_aug_input, _ = preprocess_raw(inputs, 'x_raw', postfix='_aug')
304 | pcoords, pcoords_colors = preprocess_raw(outputs, 'raw', prefix='pcoords_')
305 | else:
306 | raise NotImplementedError
307 |
308 | gt = {aug: [] for aug in range(outputs['n_augment'])}
309 | pred = []
310 | in_img = []
311 | if 'x_img' in inputs:
312 | orig_img = []
313 | for idx in range(min(self.n_log_img, len(x_input))):
314 | if 'x_img' in inputs:
315 | orig_img.append(inputs['x_img'][idx].to('cpu'))
316 | in_img.append(torch.tensor(make_image_fast(self.blit_manager, x_input[idx], self.label_names[inputs['label'][idx]], 1.)))
317 | for aug in range(outputs['n_augment']):
318 | if 'cls_pred_mod' in outputs and outputs['cls_pred_mod'] is not None:
319 | cls_name = self.label_names[outputs['cls_pred_mod'][outputs['n_augment']*idx+aug]]
320 | cls_prob = outputs['cls_pred_mod_prob'][outputs['n_augment']*idx+aug]
321 | else:
322 | cls_name = None
323 | cls_prob = None
324 | gt[aug].append(torch.tensor(make_image_fast(self.blit_manager, x_aug_input[outputs['n_augment']*idx+aug], cls_name, cls_prob)))
325 |
326 | if self.model_type in ['pmn', 'classifier', 'fgsbir']:
327 | if 'cls_pred_main' in outputs and outputs['cls_pred_main'] is not None:
328 | cls_name = self.label_names[outputs['cls_pred_main'][idx]]
329 | cls_prob = outputs['cls_pred_main_prob'][idx]
330 | else:
331 | cls_name = None
332 | cls_prob = None
333 | pred.append(torch.tensor(make_image_fast(self.blit_manager, pcoords[idx], cls_name, cls_prob, color=pcoords_colors[idx])))
334 | elif self.model_type == 'communication':
335 | max_seq_len = (outputs['pcoords_n_strokes'][:min(self.n_log_img, len(x_input))]).max().item()
336 | pred_idx = []
337 | for seq_idx in range(max_seq_len):
338 | if 'cls_pred_main' in outputs and outputs['cls_pred_main'] is not None:
339 | cls_name = self.label_names[outputs['cls_pred_main'][idx][seq_idx]]
340 | cls_prob = outputs['cls_pred_main_prob'][idx][seq_idx]
341 | else:
342 | cls_name = None
343 | cls_prob = None
344 | pred_idx.append(torch.tensor(make_image_fast(self.blit_manager, pcoords[idx], cls_name, cls_prob, max_seq_len=seq_idx+1)))
345 | pred.append(pred_idx)
346 | else:
347 | raise NotImplementedError
348 |
349 | if self.model_type == 'communication':
350 | pred = list(map(list, zip(*pred)))
351 | pred = [item for sublist in pred for item in sublist]
352 |
353 | log_imgs_train = [torch.stack(in_img,dim=0), torch.stack(pred,dim=0)] + [torch.stack(gt[aug],dim=0) for aug in range(outputs['n_augment'])]
354 |
355 | if self.model_type == 'fgsbir':
356 | inv_transform = transforms.Compose([
357 | transforms.Normalize(mean = [ 0., 0., 0. ],
358 | std = [ 1/0.229, 1/0.224, 1/0.225 ]),
359 | transforms.Normalize(mean = [ -0.485, -0.456, -0.406 ],
360 | std = [ 1., 1., 1. ]),
361 | transforms.Resize(480),
362 | transforms.Pad((80, 0)),
363 | ])
364 | log_imgs_train.append((inv_transform(inputs['positive_img']) * 255).byte().cpu())
365 | log_imgs_train.append((inv_transform(inputs['negative_img']) * 255).byte().cpu())
366 |
367 | log_imgs_train = torch.cat(log_imgs_train,dim=0)
368 |
369 | imgs = [('train' if train else 'test', log_imgs_train, min(self.n_log_img, len(x_input)))]
370 | return imgs
371 |
372 |
373 | def run_model(self, inputs, train):
374 | outputs = self.model(**inputs)
375 | #outputs['n_augment'] = 1 if self.model_type == 'pmn' and not self.model.finetune_prims and (not self.model.train_prims or self.model.learned_prims) else 0
376 | outputs['n_augment'] = 0
377 |
378 |
379 | return outputs
380 |
--------------------------------------------------------------------------------
/utils/arguments.py:
--------------------------------------------------------------------------------
1 | import argparse
2 |
3 | parser = argparse.ArgumentParser()
4 |
5 | parser.add_argument('--data-dir', default='./data', help='Root directory for the data')
6 | parser.add_argument('--preprocessed-root', default=None, help='Path to preprocessed data')
7 | parser.add_argument('--dataset', default='quickdraw09', help='Dataset to train/test')
8 | parser.add_argument('--model-type', default='pmn', help='Model type')
9 | parser.add_argument('--learning-rate', type=float, default=0.0001, help='Learning rate')
10 | parser.add_argument('--batch-size', type=int, default=32, help='Training batch size')
11 | parser.add_argument('--epochs', type=int, default=500, help='Number of epochs')
12 | parser.add_argument('--weight-decay', type=float, default=0., help='Weight decay for optimizer')
13 | parser.add_argument('--Nz', type=int, default=256, help='Latent dimension')
14 | parser.add_argument('--dt-gamma', type=float, default=6., help='Gamma for distance transform')
15 | parser.add_argument('--temperature', type=float, default=0.2, help='Temperature for contrastive loss')
16 | parser.add_argument('--transformations', type=str, default='rsr')
17 | parser.add_argument('--use-proportion-scale', action='store_true', default=False)
18 | parser.add_argument('--transform-bound', type=float, default=None)
19 | parser.add_argument('--learn-compatibility', action='store_true', default=False)
20 | parser.add_argument('--n-log-img', type=int, default=50, help='Number of images to display in the logger')
21 | parser.add_argument('--log-dir', default='./log', help='Root directory for the logs')
22 | parser.add_argument('--log-every', type=int, default=500, help='How often to log')
23 | parser.add_argument('--save-every', type=int, default=5000, help='How often to save model')
24 | parser.add_argument('--log-name', default='test', help='Name of the logs')
25 | parser.add_argument('--loss-model-ckpt', type=str, default=None, help='Checkpoint used as the loss model')
26 | parser.add_argument('--loss-model-type', default='cross_entropy', help='Loss to use for the loss model')
27 | parser.add_argument('--view-scale', type=int, default=256, help='Size of log images')
28 | parser.add_argument('--test', default=None, type=str, help='Checkpoint used for test set evaluation')
29 |
30 | # Position embedding
31 | parser.add_argument('--use-pos-embed', action='store_true', default=False, help='Use positional embeddings')
32 | parser.add_argument('--use-sinusoid-embed', action='store_true', default=False, help='Use sinusoid positional embeddings')
33 |
34 | #FGSBIR
35 | parser.add_argument('--fgsbir-backbone', default='InceptionV3')
36 | parser.add_argument('--load-fgsbir-photos', action='store_true', default=False, help='Load photo images for retrieval task')
37 |
38 | #Communication
39 | parser.add_argument('--comm-mode', default='human')
40 | parser.add_argument('--budget', type=float, default=1.0)
41 |
42 | # Data optimization
43 | parser.add_argument('--no-stroke-resampling', action='store_true', default=False)
44 | parser.add_argument('--max-stroke-length', type=int, default=25)
45 |
46 | # Save processed images
47 | parser.add_argument('--add-comm-model', action='store_true', default=False)
48 | parser.add_argument('--only-save-coords', action='store_true', default=False)
49 |
--------------------------------------------------------------------------------
/utils/coords_utils.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import torch
3 | from matplotlib.figure import Figure
4 | from matplotlib.axes import Axes
5 |
6 | PRIM_COLORS = ['#E69F00', '#009E73', '#CC79A7', '#56B4E9', '#D55E00', '#0072B2', '#785EF0']
7 | PRIM_ORDER = ['halfcircle', 'circle', 'line', 'corner', 'triangle', 'square', 'u']
8 |
9 | def get_stroke_stats(strokes, scale_margin=0.01):
10 | mins = strokes.min(dim=-2, keepdim=True)[0]
11 | maxs = strokes.max(dim=-2, keepdim=True)[0]
12 | sizes = (maxs - mins)
13 | scale = sizes.max(dim=-1, keepdim=True)[0]
14 | scale += scale * scale_margin
15 | # replace 0. scales with margin
16 | scale = scale.masked_fill(scale.isclose(torch.tensor([0.], device=scale.device)), scale_margin)
17 | translation = (mins + maxs) / 2.
18 | aspect = sizes / scale
19 | return scale, translation, aspect
20 |
21 | def normalize_strokes(strokes):
22 | scale, translation, _ = get_stroke_stats(strokes)
23 | strokes = (strokes - translation) / scale * 2.
24 | return strokes, scale, translation
25 |
26 | def preprocess_transformer(seq, resample_strokes=False, resample_size=25,
27 | points_per_primitive=3):
28 | assert seq[0, 2] == 1., seq[0]
29 |
30 | strokes = split_seq_into_strokes(seq, max_seq_len=None if resample_strokes else resample_size)
31 | segments_len = [int(np.ceil(len(s)/points_per_primitive)) for s in strokes]
32 | if resample_strokes:
33 | strokes = [resample_stroke(s, resample_size) for s in strokes]
34 | strokes = torch.stack(strokes)
35 | strokes = (strokes[:, :, :2] - 127.5) / 127.5
36 | strokes, scale, translation = normalize_strokes(strokes)
37 | stroke_lens = tuple([torch.tensor(resample_size).unsqueeze(0) for _ in strokes])
38 | mask = torch.zeros(strokes.shape[:2], dtype=torch.bool)
39 | position = torch.linspace(-1., 1., steps=resample_size).unsqueeze(0).repeat(len(strokes), 1)
40 | else:
41 | strokes = [(s[:, :2] - 127.5) / 127.5 for s in strokes]
42 | strokes, scale, translation = zip(*[normalize_strokes(s) for s in strokes])
43 | scale, translation = torch.stack(scale), torch.stack(translation)
44 | stroke_lens = tuple([torch.tensor(len(s)).unsqueeze(0) for s in strokes])
45 | strokes_tensor = torch.zeros((len(strokes), resample_size, 2))
46 | mask = torch.ones(strokes_tensor.shape[:2], dtype=torch.bool)
47 | position = torch.zeros(strokes_tensor.shape[:2])
48 | for i, s in enumerate(strokes):
49 | slen = len(s)
50 | strokes_tensor[i, :slen] = s
51 | mask[i, :slen] = False
52 | position[i, :slen] = torch.linspace(-1., 1., steps=slen)
53 | strokes = strokes_tensor
54 |
55 | segments = []
56 | for i, sl in enumerate(segments_len):
57 | if resample_strokes:
58 | sl = min(resample_size, sl)
59 | seg = []
60 | cnt = stroke_lens[i].item()
61 | for n_remain in range(sl, 0, -1):
62 | seg.append(int(np.round(cnt / n_remain)))
63 | cnt -= seg[-1]
64 | segments.append(seg)
65 |
66 | return strokes, len(strokes), scale, translation, segments, stroke_lens, mask, position
67 |
68 | def preprocess_sequence(seq, Nmax=99):
69 | assert seq[0, 2] == 1., seq[0]
70 | nonzero = torch.nonzero(seq.sum(-1) == 0.)
71 | if nonzero.nelement() == 0:
72 | len_seq = Nmax
73 | else:
74 | len_seq = nonzero[0].item() - 1
75 | if seq.shape[0] < Nmax+1:
76 | seq = torch.cat([seq, torch.zeros(Nmax+1-seq.shape[0], 4)])
77 | new_seq = (seq[:,:2]- 127.5) / 127.5
78 | new_seq = new_seq[1:] - new_seq[:-1]
79 | new_seq = torch.cat([new_seq, seq[1:, 2:], torch.zeros((Nmax, 1))], dim=1)
80 | new_seq[len_seq-1:,4] = 1
81 | new_seq[len_seq-1:,2:4] = 0
82 | new_seq[len_seq:,0:2] = 0
83 | return new_seq, len_seq
84 |
85 |
86 | def split_seq_into_strokes(orig_seq, max_seq_len=None):
87 | split_idx = [0]+list(torch.where(orig_seq[:,-1]>0)[0]+1)
88 | split_idx = [(split_idx[i+1]-split_idx[i]).item() for i in range(len(split_idx)-1)]
89 | pad_len = orig_seq.shape[0] - sum(split_idx)
90 | if pad_len > 0:
91 | split_idx.append(pad_len)
92 |
93 | current_strokes = list(torch.split(orig_seq, split_idx))
94 | if max_seq_len is not None:
95 | updated_strokes = []
96 | for stroke in current_strokes:
97 | if stroke.shape[0] > max_seq_len and not (stroke[0] == 0.).all().item():
98 | n_splits = int(np.ceil(stroke.shape[0] / max_seq_len))
99 | if stroke.shape[0] > (max_seq_len*n_splits-n_splits+1):
100 | n_splits += 1
101 |
102 | new_strokes = []
103 | offset = 0
104 | for n_remain in range(n_splits, 0, -1):
105 | stroke_len = int(np.round((stroke.shape[0]+n_remain-1-offset) / n_remain))
106 | new_strokes.append(stroke[offset:offset+stroke_len])
107 | offset = offset + stroke_len - 1
108 |
109 | updated_strokes.extend(new_strokes)
110 | else:
111 | updated_strokes.append(stroke)
112 | current_strokes = updated_strokes
113 |
114 | is_padded = (current_strokes[-1][0] == 0.).all().item()
115 | if is_padded:
116 | current_strokes = current_strokes[:-1]
117 |
118 | pnt_strokes = []
119 | for i, stroke in enumerate(current_strokes):
120 | if stroke.shape[0] == 1:
121 | pnt_strokes.append(i)
122 | for i in reversed(pnt_strokes):
123 | del current_strokes[i]
124 |
125 | return current_strokes
126 |
127 |
128 | def resample_strokes(current_strokes, resample_ratios, max_points):
129 | avail_points = max_points - sum([c.shape[0] for c in current_strokes])
130 | new_strokes = []
131 | for curr_stroke in current_strokes:
132 | n_pnts = curr_stroke.shape[0]
133 | ratio = np.random.rand() * (resample_ratios[1] - resample_ratios[0]) + resample_ratios[0]
134 | while (new_n_pnts := max(2, int(np.around(n_pnts * ratio)))) - n_pnts > avail_points:
135 | ratio = np.random.rand() * (resample_ratios[1] - resample_ratios[0]) + resample_ratios[0]
136 | new_strokes.append(resample_stroke(curr_stroke.clone(), new_n_pnts))
137 | avail_points -= new_n_pnts - n_pnts
138 | return new_strokes
139 |
140 |
141 | def make_image_fast(blit_manager, sequence, class_name=None, class_prob=None, no_axis=False, color=None, max_seq_len=None, linewidth=3, enlarge=1.0, arbitrary_mask=False):
142 | if isinstance(sequence, tuple):
143 | # raw stroke-based coordinates
144 | seq, scale, translate, seq_mask = sequence
145 | if isinstance(seq, list):
146 | strokes = [(se / 2 * sc + tr) * enlarge for se, sc, tr in zip(seq, scale, translate)]
147 | else:
148 | strokes = (seq / 2 * scale + translate) * enlarge
149 | check_end = False
150 | else:
151 | # relative coordinates
152 | sequence[:, 0] = np.cumsum(sequence[:, 0])
153 | sequence[:, 1] = np.cumsum(sequence[:, 1])
154 | """plot drawing with separated strokes"""
155 | strokes = np.split(sequence, np.where(sequence[:, 3] + sequence[:, 4] > 0)[0] + 1)
156 | strokes[0] = np.concatenate([strokes[0][0][np.newaxis], strokes[0]], axis=0)
157 | strokes[0][0, :2] = 0.
158 | check_end = True
159 | seq_mask = None
160 |
161 | if max_seq_len is not None:
162 | if max_seq_len > len(strokes):
163 | strokes = []
164 | else:
165 | strokes = strokes[:max_seq_len]
166 |
167 | if isinstance(blit_manager, Axes):
168 | ax = blit_manager
169 | artists = []
170 | else:
171 | ax = blit_manager.ax
172 | artists = blit_manager.get_artists()
173 | if len(artists) == 0:
174 | ax.set_xlim(-2, 2)
175 | ax.set_ylim(-2, 2)
176 | ax.set_aspect('equal')
177 | if no_axis:
178 | ax.set_axis_off()
179 | txt = ax.text(-2.2, 2.2, '', size=20, animated=True)
180 | blit_manager.add_artist(txt)
181 | else:
182 | txt = artists[0]
183 |
184 | if not no_axis and class_name is not None and class_prob is not None:
185 | txt.set_text(f'{class_name} ({class_prob:.2%})')
186 | else:
187 | txt.set_text('')
188 |
189 | if arbitrary_mask and seq_mask is not None:
190 | new_strokes = []
191 | for s, m in zip(strokes, seq_mask):
192 | used = np.argwhere(~m).flatten()
193 | stroke_sections = []
194 | start = None
195 | for u in used:
196 | if start is None:
197 | start = u
198 | elif u != last_u + 1:
199 | stroke_sections.append((start, last_u))
200 | start = u
201 | last_u = u
202 | if start is not None:
203 | stroke_sections.append((start, last_u))
204 |
205 | for sec_start, sec_end in stroke_sections:
206 | new_strokes.append(s[sec_start:sec_end+1])
207 |
208 | strokes = new_strokes
209 | seq_mask = None
210 |
211 | n_strokes = 0
212 | for i, s in enumerate(strokes):
213 | if s.size == 0:
214 | break
215 |
216 | x = s[:, 0]
217 | y = -s[:, 1]
218 | if seq_mask is not None:
219 | seq_len = np.argwhere(seq_mask[i]).flatten()
220 | if len(seq_len) > 0:
221 | x = x[:seq_len[0]]
222 | y = y[:seq_len[0]]
223 |
224 | if (x == x[0]).all() and (y == y[0]).all():
225 | marker = 'o'
226 | else:
227 | marker = ''
228 |
229 | if color is not None:
230 | if isinstance(color, list):
231 | c = color[i]
232 | else:
233 | c = color
234 |
235 | if i+1 < len(artists):
236 | artists[i+1].set_data(x, y)
237 | artists[i+1].set_marker(marker)
238 | if color is not None:
239 | artists[i+1].set_color(c)
240 | else:
241 | if color is not None:
242 | (line,) = ax.plot(x, y, marker=marker, linewidth=linewidth, animated=True, color=c)
243 | else:
244 | (line,) = ax.plot(x, y, marker=marker, linewidth=linewidth, animated=True)
245 | blit_manager.add_artist(line)
246 |
247 | n_strokes += 1
248 | if check_end and s[-1, 4] == 1:
249 | break
250 |
251 | # don't show unused artists
252 | for i in range(n_strokes+1, len(artists)):
253 | artists[i].set_data([], [])
254 |
255 | if not isinstance(blit_manager, Axes):
256 | blit_manager.update()
257 | # grab the pixel buffer and dump it into a numpy array
258 | img = np.array(blit_manager.canvas.renderer.buffer_rgba())[:, :, :3]
259 | img = np.moveaxis(img, -1, 0)
260 |
261 | return img
262 |
263 |
264 | def resample_data(edge_list, n=20, random=True, endpoint=False):
265 | total_edge_length = sum([e[0] for e in edge_list])
266 | if random:
267 | locations = sorted(np.random.rand(n) * total_edge_length)
268 | else:
269 | if endpoint:
270 | locations = np.linspace(0., total_edge_length, num=n)
271 | else:
272 | locations = np.linspace(0., total_edge_length, num=n+1)[:-1]
273 |
274 | points = []
275 | loc_i = 0
276 | curr_length = 0
277 | for edge in edge_list:
278 | start_pnt = edge[1]
279 | end_pnt = edge[2]
280 | edge_length = edge[0]
281 | while loc_i < n and (rel_length := locations[loc_i] - curr_length) <= edge_length:
282 | if edge_length == 0.:
283 | pnt = start_pnt
284 | else:
285 | pnt = start_pnt + rel_length/edge_length * (end_pnt - start_pnt)
286 | points.append(pnt)
287 | loc_i += 1
288 |
289 | curr_length += edge[0]
290 |
291 | points = np.array(points)
292 | assert (~np.isnan(points)).all()
293 |
294 | return points
295 |
296 | def resample_stroke(stroke, n):
297 | pnts = stroke[:, :2].numpy()
298 | edge_list = [[np.linalg.norm(pnts[i] - pnts[i+1]), pnts[i], pnts[i+1]] for i in range(pnts.shape[0]-1)]
299 | re_pnts = resample_data(edge_list, n, random=False, endpoint=True)
300 | new_stroke = torch.from_numpy(re_pnts)
301 | states = torch.zeros(new_stroke.shape, dtype=new_stroke.dtype)
302 | states[:, 0] = 1.
303 | states[-1, 0] = 0.
304 | states[-1, 1] = 1.
305 | new_stroke = torch.cat([new_stroke, states], dim=1)
306 | return new_stroke
307 |
--------------------------------------------------------------------------------
/utils/data.py:
--------------------------------------------------------------------------------
1 | import os
2 | import collections
3 | from itertools import chain, combinations
4 | import pickle
5 | import re
6 |
7 | import matplotlib.pyplot as plt
8 | import numpy as np
9 | import torch
10 | import torchvision
11 | import torch.utils.data as data
12 | import torchvision.transforms as transforms
13 | import torchvision.transforms.functional as F
14 | from tqdm import tqdm
15 | from PIL import Image
16 | import copy
17 |
18 | from .coords_utils import preprocess_sequence, preprocess_transformer, make_image_fast
19 | from .transformations import transform_primitives, ToTransformMatrix
20 | from .plt_blit import BlitManager
21 |
22 | from torch.utils.data._utils.collate import default_collate
23 |
24 |
25 | def sketch_collate(batch):
26 | r"""Puts each data field into a tensor with outer dimension batch size"""
27 |
28 | elem = batch[0]
29 | if isinstance(elem, collections.abc.Mapping):
30 | return {key: sketch_collate([d[key] for d in batch]) for key in elem}
31 | elif isinstance(elem, collections.abc.Sequence) and not isinstance(elem, str):
32 | # check to make sure that the elements in batch have consistent size
33 | it = iter(batch)
34 | elem = next(it)
35 | elem_size = len(elem)
36 | elem_dims = elem[0].dim() if isinstance(elem[0], torch.Tensor) else 0
37 | if not all(len(elem) == elem_size for elem in it) or elem_dims > 1 or isinstance(elem, tuple):
38 | batch = sum(batch, tuple())
39 |
40 | if elem_dims > 0:
41 | return torch.cat(batch)
42 | else:
43 | transposed = zip(*batch)
44 | return [sketch_collate(samples) for samples in transposed]
45 | else:
46 | return default_collate(batch)
47 |
48 |
49 |
50 |
51 | class PreprocessedSketchDataset(data.Dataset):
52 | def __init__(self, coordinate_path_root, sketch_list, idx_class=0,
53 | original_strokes_list=None, load_fgsbir_photos=False,
54 | original_path_root=None):
55 | self.coordinate_path_root = coordinate_path_root
56 | self.load_fgsbir_photos = load_fgsbir_photos
57 |
58 | with open(sketch_list) as sketch_url_file:
59 | sketch_url_list = sketch_url_file.readlines()
60 |
61 | self.coordinate_urls, sketch_url_list = self.get_coords_list(coordinate_path_root, sketch_url_list)
62 |
63 | self.labels = [int(sketch_url.strip().split(' ')[1])
64 | for sketch_url in sketch_url_list]
65 | label_names = [sketch_url.strip().split(' ')[0].split('/')[idx_class + 1]
66 | for sketch_url in sketch_url_list]
67 |
68 | if self.load_fgsbir_photos:
69 | assert original_path_root is not None
70 | alt_coordinate_urls, _ = self.get_coords_list(os.path.join(original_path_root, 'picture_files'), sketch_url_list)
71 | self.picture_urls = [re.sub('_[^_]*\.pt', '.png', cu.replace('/train/', '/').replace('/test/', '/')) for cu in alt_coordinate_urls]
72 | self.unique_picture_urls = set(self.picture_urls)
73 |
74 | self.img_transform = transforms.Compose([
75 | transforms.Resize(299), transforms.ToTensor(),
76 | transforms.Normalize(mean=[0.485, 0.456, 0.406],
77 | std=[0.229, 0.224, 0.225])
78 | ])
79 |
80 | self.original_strokes = None
81 |
82 | self.label_names = np.unique(label_names)
83 |
84 | self.n_classes = len(self.label_names)
85 | self.keys = ['x_raw', 'scale', 'translate', 'seq_mask', 'position']
86 |
87 |
88 |
89 | def __len__(self):
90 | return len(self.coordinate_urls)
91 |
92 | def get_coords_list(self, coordinate_path_root, sketch_url_list):
93 | return [os.path.join(coordinate_path_root, (sketch_url.strip(
94 | ).split(' ')[0]).replace('.npy', '.pt')) for sketch_url in sketch_url_list], sketch_url_list
95 |
96 |
97 | def __getitem__(self, item):
98 | coordinate = torch.load(self.coordinate_urls[item])
99 | assert coordinate['label'] == self.labels[item]
100 |
101 | if isinstance(coordinate['x_raw'], list):
102 | split_scale = list(coordinate['scale'].split(1, dim=0))
103 | split_translate = list(coordinate['translate'].split(1, dim=0))
104 | coordinate['n_strokes'] = 0
105 | for i in range(len(coordinate['x_raw'])):
106 | split_scale[i] = split_scale[i].repeat(coordinate['x_raw'][i].shape[0],1,1)
107 | split_translate[i] = split_translate[i].repeat(coordinate['x_raw'][i].shape[0],1,1)
108 | coordinate['n_strokes']+=coordinate['x_raw'][i].shape[0]
109 | coordinate['x_raw'] = torch.cat(coordinate['x_raw'],dim=0).float()
110 | coordinate['scale'] = torch.cat(split_scale,dim=0).float()
111 | coordinate['translate'] = torch.cat(split_translate,dim=0).float()
112 |
113 | for k in coordinate.keys():
114 | if isinstance(coordinate[k], np.ndarray):
115 | coordinate[k] = torch.from_numpy(coordinate[k]).float()
116 | elif k == 'scale' and isinstance(coordinate[k], float):
117 | coordinate[k] = torch.tensor([[[coordinate[k]]]])
118 | elif k == 'stroke_lens' and isinstance(coordinate[k], int):
119 | coordinate[k] = torch.tensor([coordinate[k]])
120 |
121 | coordinate['seq_mask'] = torch.zeros(coordinate['x_raw'].shape[:2], dtype=torch.bool)
122 | coordinate['position'] = torch.linspace(-1., 1., steps=coordinate['x_raw'].shape[1]).unsqueeze(0).repeat(coordinate['x_raw'].shape[0], 1)
123 | data_dict = {k: coordinate[k].split(1, dim=0) for k in self.keys}
124 | data_dict['label'] = coordinate['label']
125 | data_dict['n_strokes'] = coordinate['n_strokes']
126 | if isinstance(coordinate['segments'], int):
127 | data_dict['segments'] = tuple([torch.tensor(coordinate['segments']).unsqueeze(0)])
128 | else:
129 | data_dict['segments'] = tuple([c.unsqueeze(0) for c in coordinate['segments']])
130 | data_dict['stroke_lens'] = tuple([s.unsqueeze(0) for s in coordinate['stroke_lens']])
131 |
132 | if 'prim_id' in coordinate:
133 | if isinstance(coordinate['prim_id'], int):
134 | coordinate['prim_id'] = torch.tensor([[[coordinate['prim_id']]]])
135 | data_dict['prim_id'] = coordinate['prim_id'].split(1, dim=0)
136 |
137 | if 'n_strokes_orig' in coordinate:
138 | data_dict['n_strokes_orig'] = coordinate['n_strokes_orig']
139 |
140 | if self.load_fgsbir_photos:
141 | # TODO: duplicate code
142 | positive_path = self.picture_urls[item]
143 | uniq_urls = set(self.unique_picture_urls)
144 | uniq_urls.remove(positive_path)
145 | negative_path = np.random.choice(list(uniq_urls))
146 | positive_img = Image.open(positive_path).convert('RGB')
147 | negative_img = Image.open(negative_path).convert('RGB')
148 | positive_img = self.img_transform(positive_img)
149 | negative_img = self.img_transform(negative_img)
150 | data_dict['positive_img'] = positive_img
151 | data_dict['negative_img'] = negative_img
152 | data_dict['positive_name'] = positive_path.split('/')[-1].split('.')[0]
153 |
154 | if self.original_strokes is not None:
155 | data_dict['original_n_strokes'] = self.original_strokes[item]
156 | data_dict['name'] = item
157 | return data_dict
158 |
159 | def save_img(self, path, suffix='.pt', process=True):
160 | fig, ax = plt.subplots(figsize=(2.24, 2.24))
161 | ax.set_axis_off()
162 | fig.add_axes(ax)
163 | self.blit_manager = BlitManager(ax, fig.canvas)
164 | fig.canvas.draw()
165 | for item in tqdm(range(len(self.coordinate_urls)), desc='Saving images'):
166 | file_path = self.coordinate_urls[item]
167 | relative_path = os.path.relpath(file_path, self.coordinate_path_root)
168 | file_path = os.path.join(path, relative_path).replace(suffix, '.png')
169 | os.makedirs(os.path.dirname(file_path), exist_ok=True)
170 | coordinate = torch.load(self.coordinate_urls[item])
171 | sequence_raw = coordinate['x_raw']
172 | scale = coordinate['scale']
173 | translate = coordinate['translate']
174 |
175 | if isinstance(sequence_raw, list):
176 | sequence_img = torch.cat(
177 | [((sequence_raw[i] / sequence_raw[i].abs().max()) / 2 * scale[i] + translate[i]) for i in
178 | range(len(sequence_raw))], dim=0).numpy()
179 | else:
180 | sequence_img = (sequence_raw / 2 * scale + translate).numpy()
181 | x_img = make_image_fast(self.blit_manager, (sequence_img, 3.0, 0.0, None), no_axis=True, color='black')
182 | im = Image.fromarray(np.moveaxis(x_img, 0, -1).astype(np.uint8))
183 | im.save(file_path)
184 |
185 | def add_strokes_to_list(self, file_name):
186 | full_text = ""
187 | for item in tqdm(range(len(self.coordinate_urls)), desc='Updating file'):
188 | data = self.__getitem__(item)
189 | n_strokes = data['n_strokes']
190 | label = data['label']
191 | file_path = self.coordinate_urls[item]
192 | relative_path = os.path.relpath(file_path, self.coordinate_path_root)
193 | text = relative_path + ' ' + str(label) + ' ' + str(n_strokes.item())
194 | full_text+=text+'\n'
195 |
196 | with open(file_name, 'w') as file:
197 | file.write(full_text)
198 |
199 | def save_preprocessed(self, root, suffix='.pt'):
200 | self.save_img(os.path.join(root, 'imgs'), suffix)
201 | #self.save_coords(os.path.join(root, 'coords'), suffix)
202 |
203 |
204 | class SketchDataset(data.Dataset):
205 | def __init__(self, coordinate_path_root, sketch_list,
206 | idx_class=0, preprocessed=None,
207 | Nmax=99, load_fgsbir_photos=False,
208 | points_per_primitives=3, resample_strokes=False,
209 | max_stroke_length=25):
210 | self.coordinate_path_root = coordinate_path_root
211 | self.preprocessed = preprocessed
212 | self.Nmax = Nmax
213 | self.load_fgsbir_photos = load_fgsbir_photos
214 | self.points_per_primitive = points_per_primitives
215 | self.resample_strokes = resample_strokes
216 | self.max_stroke_length = max_stroke_length
217 |
218 | with open(sketch_list) as sketch_url_file:
219 | sketch_url_list = sketch_url_file.readlines()
220 |
221 | self.coordinate_urls, sketch_url_list = self.get_coords_list(coordinate_path_root, sketch_url_list)
222 |
223 | self.labels = [int(sketch_url.strip().split(' ')[-1])
224 | for sketch_url in sketch_url_list]
225 | label_names = [sketch_url.strip().split(' ')[0].split('/')[idx_class + 1]
226 | for sketch_url in sketch_url_list]
227 | self.label_names = np.unique(label_names)
228 |
229 | if self.load_fgsbir_photos:
230 | self.sketch_picture_urls = [re.sub('.npy', '.png', cu.replace('coordinate_files', 'sketch_picture_files')) for cu in self.coordinate_urls]
231 | self.picture_urls = [re.sub('_[^_]*\.npy', '.png', cu.replace('coordinate_files', 'picture_files').replace('/train/', '/').replace('/test/', '/')) for cu in self.coordinate_urls]
232 | self.unique_picture_urls = set(self.picture_urls)
233 |
234 | self.img_transform = transforms.Compose([
235 | transforms.Resize(299), transforms.ToTensor(),
236 | transforms.Normalize(mean=[0.485, 0.456, 0.406],
237 | std=[0.229, 0.224, 0.225]),
238 | #transforms.RandomHorizontalFlip(),
239 | ])
240 |
241 | self.n_classes = len(self.label_names)
242 |
243 | def __len__(self):
244 | return len(self.coordinate_urls)
245 |
246 | def set_preprocessed(self, preprocessed):
247 | print('Setting preprocessed')
248 | self.preprocessed = preprocessed
249 |
250 | def get_coords_list(self, coordinate_path_root, sketch_url_list):
251 | return [os.path.join(coordinate_path_root, (sketch_url.strip(
252 | ).split(' ')[0]).replace('png', 'npy')) for sketch_url in sketch_url_list], sketch_url_list
253 |
254 | def read_coordinates(self, coordinate_urls, idx, normalize=False):
255 | coordinate = np.load(coordinate_urls[idx], encoding='latin1', allow_pickle=True)
256 |
257 | if coordinate.dtype == 'object':
258 | coordinate = coordinate[0]
259 |
260 | coordinate = coordinate.astype('float32')
261 | coordinate = torch.from_numpy(coordinate)
262 | if normalize:
263 | coordinate[:, :2] = ((coordinate[:, :2] - coordinate[:, :2].min()) / (
264 | coordinate[:, :2] - coordinate[:, :2].min()).max()) * 255
265 |
266 | return coordinate
267 |
268 | def save_img(self, path, suffix='.svg', process=True):
269 | fig, ax = plt.subplots(figsize=(2.99, 2.99), constrained_layout=True)
270 | ax.set_axis_off()
271 | fig.add_axes(ax)
272 | self.blit_manager = BlitManager(ax, fig.canvas)
273 | fig.canvas.draw()
274 | for item in tqdm(range(len(self.coordinate_urls)), desc='Saving images'):
275 | file_path = self.coordinate_urls[item]
276 | relative_path = os.path.relpath(file_path, self.coordinate_path_root)
277 | file_path = os.path.join(path, relative_path).replace(suffix, '.png')
278 | os.makedirs(os.path.dirname(file_path), exist_ok=True)
279 | coordinate = self.read_coordinates(self.coordinate_urls, item)
280 | sequence_raw = self.preprocessed[item]['x_raw']
281 | scale = self.preprocessed[item]['scale']
282 | translate = self.preprocessed[item]['translate']
283 |
284 | x_img = make_image_fast(self.blit_manager, (sequence_raw, scale, translate, None), no_axis=True, color='black', linewidth=1, enlarge=2.0)
285 | im = Image.fromarray(np.moveaxis(x_img, 0, -1).astype(np.uint8))
286 | im.save(file_path)
287 |
288 | def save_coords(self, path, suffix='.svg'):
289 | for item in tqdm(range(len(self.coordinate_urls)), desc='Saving coords'):
290 | file_path = self.coordinate_urls[item]
291 | relative_path = os.path.relpath(file_path, self.coordinate_path_root)
292 | file_path = os.path.join(path, relative_path).replace(suffix, '.pt')
293 | os.makedirs(os.path.dirname(file_path), exist_ok=True)
294 | coordinate = self.preprocessed[item]
295 | for k in coordinate.keys():
296 | if isinstance(coordinate[k], torch.Tensor):
297 | if coordinate[k].numel() == 1:
298 | coordinate[k] = coordinate[k].item()
299 | else:
300 | coordinate[k] = coordinate[k].detach().cpu().numpy()
301 | coordinate['path'] = relative_path
302 | torch.save(coordinate, file_path)
303 |
304 | def add_strokes_to_list(self, file_name):
305 | full_text = ""
306 | for item in tqdm(range(len(self.coordinate_urls)), desc='Updating file'):
307 | coordinate = self.read_coordinates(self.coordinate_urls, item)
308 | file_path = self.coordinate_urls[item]
309 | relative_path = os.path.relpath(file_path, self.coordinate_path_root)
310 | _, n_strokes, _, _ = preprocess_transformer(coordinate)
311 | text = relative_path + ' ' + str(self.labels[item]) + ' ' + str(n_strokes)
312 | full_text+=text+'\n'
313 | with open(file_name, 'w') as file:
314 | file.write(full_text)
315 |
316 |
317 | def save_preprocessed(self, root, suffix='.svg', save_images=True):
318 | if save_images:
319 | self.save_img(os.path.join(root, 'imgs'), suffix)
320 | self.save_coords(os.path.join(root, 'coords'), suffix)
321 |
322 | def __getitem__(self, item):
323 | label = self.labels[item]
324 |
325 | coordinate = self.read_coordinates(self.coordinate_urls, item)
326 |
327 | sequence, length = preprocess_sequence(coordinate, Nmax=self.Nmax)
328 | sequence_raw, n_strokes, scale, translate, segments, stroke_lens, mask, position = preprocess_transformer(
329 | coordinate, resample_strokes=self.resample_strokes,
330 | points_per_primitive=self.points_per_primitive,
331 | resample_size=self.max_stroke_length
332 | )
333 | if self.preprocessed is not None:
334 | sequence_raw = self.preprocessed[item]
335 | # TODO: check if all calculated values match with preprocessed
336 | assert False
337 |
338 | sequence_raw = sequence_raw.split(1, dim=0)
339 | scale = scale.split(1, dim=0)
340 | translate = translate.split(1, dim=0)
341 | position = position.split(1, dim=0)
342 | if mask is not None:
343 | mask = mask.split(1, dim=0)
344 |
345 | data_dict = {
346 | 'x': sequence,
347 | 'length': length,
348 | 'label': label,
349 | 'x_raw': sequence_raw,
350 | 'n_strokes': n_strokes,
351 | 'scale': scale,
352 | 'translate': translate,
353 | 'segments': tuple([torch.tensor(s).unsqueeze(0) for seg in segments for s in seg]),
354 | 'stroke_lens': stroke_lens,
355 | 'seq_mask': mask,
356 | 'position': position,
357 | 'data_id': item
358 | }
359 |
360 | if self.load_fgsbir_photos:
361 | positive_path = self.picture_urls[item]
362 | sketch_img_path = self.sketch_picture_urls[item]
363 | uniq_urls = set(self.unique_picture_urls)
364 | uniq_urls.remove(positive_path)
365 | negative_path = np.random.choice(list(uniq_urls))
366 | positive_img = Image.open(positive_path).convert('RGB')
367 | negative_img = Image.open(negative_path).convert('RGB')
368 | if os.path.exists(sketch_img_path):
369 | sketch_img = Image.open(sketch_img_path).convert('RGB')
370 | else:
371 | sketch_img = None
372 | positive_img = self.img_transform(positive_img)
373 | negative_img = self.img_transform(negative_img)
374 | if sketch_img is not None:
375 | sketch_img = self.img_transform(sketch_img)
376 | data_dict['sketch_img'] = sketch_img
377 | else:
378 | data_dict['sketch_img'] = -1
379 | data_dict['positive_img'] = positive_img
380 | data_dict['negative_img'] = negative_img
381 | data_dict['positive_name'] = positive_path.split('/')[-1].split('.')[0]
382 |
383 | return data_dict
384 |
385 |
386 | def get_data(data_root='./data', name='MNIST', batch_size=128, train=True,
387 | shuffle=True,
388 | preprocessed_root=None,
389 | original_strokes_list=None, load_fgsbir_photos=False,
390 | resample_strokes=False, max_stroke_length=25):
391 |
392 | if name == 'quickdraw':
393 | data_dir = os.path.join(data_root, 'quickdraw')
394 |
395 | data_dir_coords = os.path.join(data_dir, 'coordinate_files')
396 | data_dir = os.path.join(data_dir, 'picture_files')
397 | if train:
398 | sketch_list = os.path.join(data_dir_coords, 'train.txt')
399 | if preprocessed_root is not None:
400 | data_coords = PreprocessedSketchDataset(coordinate_path_root=preprocessed_root,
401 | sketch_list=sketch_list,
402 | original_strokes_list=original_strokes_list)
403 | else:
404 | data_coords = SketchDataset(
405 | data_dir_coords, sketch_list=sketch_list,
406 | resample_strokes=resample_strokes,
407 | max_stroke_length=max_stroke_length
408 | )
409 | else:
410 | sketch_list = os.path.join(data_dir_coords, 'test.txt')
411 | if preprocessed_root is not None:
412 | data_coords = PreprocessedSketchDataset(coordinate_path_root=preprocessed_root,
413 | sketch_list=sketch_list,
414 | original_strokes_list=original_strokes_list)
415 | else:
416 | data_coords = SketchDataset(
417 | data_dir_coords, sketch_list=sketch_list,
418 | resample_strokes=resample_strokes,
419 | max_stroke_length=max_stroke_length
420 | )
421 |
422 | elif name == 'quickdraw09':
423 | data_dir_coords = os.path.join(data_root, 'quickdraw09')
424 |
425 | if train:
426 | sketch_list = os.path.join(data_dir_coords, 'train.txt')
427 |
428 | if preprocessed_root is not None:
429 | data_coords = PreprocessedSketchDataset(
430 | coordinate_path_root=preprocessed_root,
431 | sketch_list=sketch_list,
432 | original_strokes_list=original_strokes_list)
433 | else:
434 | data_coords = SketchDataset(
435 | data_dir_coords, sketch_list=sketch_list,
436 | Nmax=160,
437 | resample_strokes=resample_strokes,
438 | max_stroke_length=max_stroke_length
439 | )
440 | else:
441 | sketch_list = os.path.join(data_dir_coords, 'test.txt')
442 | if preprocessed_root is not None:
443 | data_coords = PreprocessedSketchDataset(
444 | coordinate_path_root=preprocessed_root,
445 | sketch_list=sketch_list,
446 | original_strokes_list=original_strokes_list)
447 | else:
448 | data_coords = SketchDataset(
449 | data_dir_coords, sketch_list=sketch_list,
450 | Nmax=160,
451 | resample_strokes=resample_strokes,
452 | max_stroke_length=max_stroke_length
453 | )
454 |
455 |
456 | elif name in ['chairv2', 'shoev2']:
457 | data_dir = os.path.join(data_root, name)
458 | data_dir_coords = os.path.join(data_dir, 'coordinate_files')
459 |
460 | if train:
461 | sketch_list = os.path.join(data_dir_coords, 'train.txt')
462 | else:
463 | sketch_list = os.path.join(data_dir_coords, 'test.txt')
464 |
465 | if preprocessed_root is not None:
466 | data_coords = PreprocessedSketchDataset(
467 | coordinate_path_root=preprocessed_root, sketch_list=sketch_list,
468 | original_strokes_list=original_strokes_list,
469 | load_fgsbir_photos=load_fgsbir_photos, original_path_root=data_dir)
470 | else:
471 | data_coords = SketchDataset(
472 | data_dir_coords, sketch_list=sketch_list,
473 | Nmax=520, load_fgsbir_photos=load_fgsbir_photos,
474 | resample_strokes=resample_strokes,
475 | max_stroke_length=max_stroke_length
476 | )
477 |
478 | else:
479 | raise NotImplementedError
480 |
481 | if not train:
482 | generator = torch.Generator()
483 | generator.manual_seed(42)
484 | else:
485 | generator = None
486 |
487 | # Initialize dataloaders
488 | loader_coords = torch.utils.data.DataLoader(data_coords, batch_size, shuffle=shuffle, num_workers=8,
489 | generator=generator, collate_fn=sketch_collate)
490 |
491 | return loader_coords, data_coords.n_classes, data_coords.label_names
492 |
--------------------------------------------------------------------------------
/utils/distance_transform.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn.functional as F
3 |
4 | def compute_distance_transform_l2(batch, prims, grid_sqz, batch_mask=None,
5 | prims_mask=None, gamma=3.):
6 | gt_dist = distance_transform(batch, grid_sqz, mask=batch_mask, gamma=gamma)
7 | if prims.dim() == 4:
8 | dims = prims.shape
9 | prims = prims.view(-1, prims.size(2), prims.size(3))
10 | else:
11 | dims = None
12 | prim_dist = distance_transform(prims, grid_sqz, mask=prims_mask, gamma=gamma)
13 | if dims is not None:
14 | prim_dist = prim_dist.view(dims[0], dims[1], prim_dist.size(-2), prim_dist.size(-1))
15 | gt_dist = gt_dist.unsqueeze(1).expand(prim_dist.size())
16 | return F.mse_loss(gt_dist, prim_dist, reduction='none').mean([-2, -1])
17 |
18 | def make_coordinate_grid(dim, scale=1.5):
19 | """
20 | Create a meshgrid [-1,1] x [-1,1] of given spatial_size.
21 | """
22 | h, w = (dim, dim)
23 | x = torch.arange(w).float()
24 | y = torch.arange(h).float()
25 |
26 | yy = y.view(-1, 1).repeat(1, w)
27 | xx = x.view(1, -1).repeat(h, 1)
28 |
29 | meshed = (torch.cat([xx.unsqueeze_(2), yy.unsqueeze_(2)], 2).unsqueeze(0).unsqueeze(0) / (h - 1) * 2) - 1
30 | meshed *= scale
31 |
32 | return meshed
33 |
34 | def distance_transform(kps, grid_sqz, gamma=3., glb=False, mask=None):
35 | grid_size = grid_sqz.shape[-2]
36 | grid_sqz = grid_sqz.repeat(kps.size(0),1, 1, 1, 1)
37 | # kps = torch.index_select(kps_, 2, torch.LongTensor([1, 0]).to(kps_.device))
38 | pi_set = kps[:, :-1].unsqueeze(-2).unsqueeze(-2)
39 | pj_set = kps[:, 1:].unsqueeze(-2).unsqueeze(-2)
40 |
41 | # Compute r
42 | v_set = (pi_set - pj_set).repeat(1, 1, grid_size, grid_size, 1)
43 | v_norm = (v_set.pow(2)).sum(-1).unsqueeze(-1)
44 | u_set = (grid_sqz - pj_set)
45 |
46 | uv = torch.bmm(u_set.view(-1, 1, 2), (v_set).view(-1, 2, 1)).view(kps.shape[0], -1, grid_size, grid_size, 1)
47 | rs = torch.clamp(uv / v_norm, 0, 1)#.detach()
48 | rs.masked_scatter_(rs.isnan(), uv)
49 | #rs = rs.detach()
50 |
51 | betas = ((u_set - rs * v_set).pow(2)).sum(-1)
52 | betas = torch.exp(-gamma * betas)
53 |
54 | if mask is not None:
55 | betas = betas * (~mask[:, 1:]).float().unsqueeze(-1).unsqueeze(-1)
56 |
57 | betas = betas.max(1)[0]
58 | if glb:
59 | betas = betas.max(0)[0]
60 |
61 | return betas
62 |
--------------------------------------------------------------------------------
/utils/metrics.py:
--------------------------------------------------------------------------------
1 | from collections import defaultdict
2 | from typing import Dict
3 | import os
4 | import numpy as np
5 |
6 | import torch
7 | import torchvision
8 |
9 | from torch.utils.tensorboard import SummaryWriter
10 |
11 |
12 | class TbLogger(object):
13 | def __init__(self, log_dir: str):
14 | self.log_dir = os.path.expanduser(log_dir)
15 | self.tb_writer = SummaryWriter(log_dir=log_dir, flush_secs=10)
16 |
17 | def log_metrics(self, metrics: Dict, global_step):
18 | metrics = metrics.copy()
19 | # Scalars and images
20 | for key, value in metrics.items():
21 | if 'image' in key:
22 | # 3D shape of [3, H, W] with channels R G B
23 | self.tb_writer.add_image(**value, global_step=global_step)
24 | elif isinstance(value, np.ndarray) and len(value) > 1:
25 | for n, v in enumerate(value):
26 | self.tb_writer.add_scalar(f'{key}_{n}', v, global_step)
27 | else:
28 | self.tb_writer.add_scalar(key, value, global_step)
29 |
30 | def close(self):
31 | self.tb_writer.close()
32 |
33 |
34 | class Accumulator(object):
35 | def __init__(self, name='accumulator'):
36 | self.name = name
37 | self.value = 0.0
38 | self.count = 0.0
39 |
40 | def add(self, value, count=1):
41 | if isinstance(value, torch.Tensor):
42 | assert value.dim() == 0
43 | value = value.item()
44 | self.value += value * count
45 | self.count += count
46 |
47 | def reset(self):
48 | self.value = 0.0
49 | self.count = 0.0
50 |
51 | @property
52 | def avg(self):
53 | return self.value / self.count
54 |
55 |
56 | def log_metrics(metrics, summary_logger, global_step):
57 | aggregated = dict()
58 | for name, v in metrics.items():
59 | if isinstance(v, Accumulator):
60 | v = v.avg
61 | aggregated[name] = v
62 | summary_logger.log_metrics(metrics=aggregated, global_step=global_step)
63 | return aggregated
64 |
65 |
66 | def log_images(tag, img_tensor, n_row, summary_logger, global_step):
67 | metrics = defaultdict(Accumulator)
68 | img_tensor = torchvision.utils.make_grid(img_tensor, nrow=n_row)
69 | if img_tensor.dtype != torch.uint8:
70 | # Add 0.5 after unnormalizing to [0, 255] to round to nearest integer
71 | img_tensor = img_tensor.mul(255).add_(0.5).clamp_(0, 255)
72 | img_tensor = img_tensor.to(dtype=torch.uint8)
73 | metrics[tag] = {'tag': tag, 'img_tensor': img_tensor}
74 | log_metrics(metrics, summary_logger, global_step)
75 |
--------------------------------------------------------------------------------
/utils/plt_blit.py:
--------------------------------------------------------------------------------
1 | class BlitManager:
2 | def __init__(self, ax, canvas, animated_artists=()):
3 | """
4 | Parameters
5 | ----------
6 | canvas : FigureCanvasAgg
7 | The canvas to work with, this only works for sub-classes of the Agg
8 | canvas which have the `~FigureCanvasAgg.copy_from_bbox` and
9 | `~FigureCanvasAgg.restore_region` methods.
10 |
11 | animated_artists : Iterable[Artist]
12 | List of the artists to manage
13 | """
14 | self.ax = ax
15 | self.canvas = canvas
16 | self._bg = None
17 | self._artists = []
18 |
19 | for a in animated_artists:
20 | self.add_artist(a)
21 | # grab the background on every draw
22 | self.cid = canvas.mpl_connect("draw_event", self.on_draw)
23 |
24 | def on_draw(self, event):
25 | """Callback to register with 'draw_event'."""
26 | cv = self.canvas
27 | if event is not None:
28 | if event.canvas != cv:
29 | raise RuntimeError
30 | self._bg = cv.copy_from_bbox(cv.figure.bbox)
31 | self._draw_animated()
32 |
33 | def get_artists(self):
34 | return self._artists
35 |
36 | def add_artist(self, art):
37 | """
38 | Add an artist to be managed.
39 |
40 | Parameters
41 | ----------
42 | art : Artist
43 |
44 | The artist to be added. Will be set to 'animated' (just
45 | to be safe). *art* must be in the figure associated with
46 | the canvas this class is managing.
47 |
48 | """
49 | if art.figure != self.canvas.figure:
50 | raise RuntimeError
51 | art.set_animated(True)
52 | self._artists.append(art)
53 |
54 | def _draw_animated(self):
55 | """Draw all of the animated artists."""
56 | fig = self.canvas.figure
57 | for a in self._artists:
58 | fig.draw_artist(a)
59 |
60 | def update(self):
61 | """Update the screen with animated artists."""
62 | cv = self.canvas
63 | fig = cv.figure
64 | # paranoia in case we missed the draw event,
65 | if self._bg is None:
66 | self.on_draw(None)
67 | else:
68 | # restore the background
69 | cv.restore_region(self._bg)
70 | # draw all of the animated artists
71 | self._draw_animated()
72 | # update the GUI state
73 | cv.blit(fig.bbox)
74 | # let the GUI event loop process anything it has to do
75 | cv.flush_events()
76 |
--------------------------------------------------------------------------------
/utils/transformations.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import torch
3 | import torch.nn as nn
4 | import torch.nn.functional as F
5 |
6 | from utils.coords_utils import normalize_strokes
7 |
8 | ALLOWED_TRANSFORMATIONS = ['identity', 'translate_x', 'translate_y', 'translate', 'scale', 'scale_full_bounded', 'scale_full', 'uni_scale', 'proportion_scale', 'shear_x', 'shear_y', 'rotate']
9 |
10 |
11 | class CosSin(nn.Module):
12 | def __init__(self, dim):
13 | super(CosSin, self).__init__()
14 | self.dim = dim
15 |
16 | def forward(self, input):
17 | return torch.cat([torch.cos(input), torch.sin(input)], dim=self.dim)
18 |
19 |
20 | class ToTransformMatrix(nn.Module):
21 | def __init__(self, transformation, no_activation=False, bound=None):
22 | super(ToTransformMatrix, self).__init__()
23 |
24 | assert transformation in ALLOWED_TRANSFORMATIONS
25 |
26 |
27 | if transformation == 'identity':
28 | mul = [
29 | [[0, 0, 0],
30 | [0, 0, 0],
31 | [0, 0, 0]]
32 | ]
33 | bias = [[1, 0, 0],
34 | [0, 1, 0],
35 | [0, 0, 1]]
36 |
37 | def identity(x):
38 | return x
39 | activation = identity
40 |
41 | elif transformation == 'translate':
42 | mul = [
43 | [[0, 0, 1],
44 | [0, 0, 0],
45 | [0, 0, 0]],
46 |
47 | [[0, 0, 0],
48 | [0, 0, 1],
49 | [0, 0, 0]]
50 | ]
51 | bias = [[1, 0, 0],
52 | [0, 1, 0],
53 | [0, 0, 1]]
54 | #activation = nn.Tanh()
55 | def translate_act(x):
56 | return torch.tanh(x)# * 0.9
57 | activation = translate_act
58 |
59 | elif transformation == 'translate_x':
60 | mul = [
61 | [[0, 0, 1],
62 | [0, 0, 0],
63 | [0, 0, 0]]
64 | ]
65 | bias = [[1, 0, 0],
66 | [0, 1, 0],
67 | [0, 0, 1]]
68 | #activation = nn.Tanh()
69 | def translate_act(x):
70 | return torch.tanh(x)# * 0.9
71 | activation = translate_act
72 |
73 | elif transformation == 'translate_y':
74 | mul = [
75 | [[0, 0, 0],
76 | [0, 0, 1],
77 | [0, 0, 0]]
78 | ]
79 | bias = [[1, 0, 0],
80 | [0, 1, 0],
81 | [0, 0, 1]]
82 | #activation = nn.Tanh()
83 | def translate_act(x):
84 | return torch.tanh(x)# * 0.9
85 | activation = translate_act
86 |
87 | elif transformation == 'scale_full':
88 | mul = [
89 | [[1, 0, 0],
90 | [0, 0, 0],
91 | [0, 0, 0]],
92 |
93 | [[0, 0, 0],
94 | [0, 1, 0],
95 | [0, 0, 0]]
96 | ]
97 |
98 | bias = [[0, 0, 0],
99 | [0, 0, 0],
100 | [0, 0, 1]]
101 |
102 | activation = torch.exp
103 |
104 | elif transformation == 'scale_full_bounded':
105 | mul = [
106 | [[1, 0, 0],
107 | [0, 0, 0],
108 | [0, 0, 0]],
109 |
110 | [[0, 0, 0],
111 | [0, 1, 0],
112 | [0, 0, 0]]
113 | ]
114 |
115 | bias = [[0, 0, 0],
116 | [0, 0, 0],
117 | [0, 0, 1]]
118 |
119 | def scale_act(x):
120 | return torch.exp(x) + (bound if bound is not None else 0.)
121 | activation = scale_act
122 |
123 | elif transformation == 'scale':
124 | mul = [
125 | [[1, 0, 0],
126 | [0, 0, 0],
127 | [0, 0, 0]],
128 |
129 | [[0, 0, 0],
130 | [0, 1, 0],
131 | [0, 0, 0]]
132 | ]
133 |
134 | bias = [[0, 0, 0],
135 | [0, 0, 0],
136 | [0, 0, 1]]
137 |
138 | def scale_act(x):
139 | return 2. * torch.sigmoid(x) + 0.1
140 | activation = scale_act
141 |
142 | elif transformation == 'uni_scale':
143 | mul = [
144 | [[1, 0, 0],
145 | [0, 1, 0],
146 | [0, 0, 0]]
147 | ]
148 |
149 | bias = [[0, 0, 0],
150 | [0, 0, 0],
151 | [0, 0, 1]]
152 |
153 | def scale_act(x):
154 | return 2. * torch.sigmoid(x) + 0.02
155 | activation = scale_act
156 |
157 | elif transformation == 'proportion_scale':
158 | mul = [
159 | [[-1, 0, 0],
160 | [0, 0, 0],
161 | [0, 0, 0]],
162 |
163 | [[0, 0, 0],
164 | [0, -1, 0],
165 | [0, 0, 0]]
166 | ]
167 |
168 | bias = [[1. + (bound if bound is not None else 0.02), 0, 0],
169 | [0, 1. + (bound if bound is not None else 0.02) , 0],
170 | [0, 0, 1]]
171 |
172 | def scale_act(x):
173 | return F.relu(torch.tanh(x))
174 | activation = scale_act
175 |
176 | elif transformation == 'shear_x':
177 | mul = [
178 | [[0, 1, 0],
179 | [0, 0, 0],
180 | [0, 0, 0]]
181 | ]
182 | bias = [[1, 0, 0],
183 | [0, 1, 0],
184 | [0, 0, 1]]
185 | activation = nn.Tanh()
186 |
187 | elif transformation == 'shear_y':
188 | mul = [
189 | [[0, 0, 0],
190 | [1, 0, 0],
191 | [0, 0, 0]]
192 | ]
193 | bias = [[1, 0, 0],
194 | [0, 1, 0],
195 | [0, 0, 1]]
196 | activation = nn.Tanh()
197 |
198 | elif transformation == 'rotate':
199 | mul = [
200 | [[1, 0, 0],
201 | [0, 1, 0],
202 | [0, 0, 0]],
203 |
204 | [[0, -1, 0],
205 | [1, 0, 0],
206 | [0, 0, 0]]
207 | ]
208 | bias = [[0, 0, 0],
209 | [0, 0, 0],
210 | [0, 0, 1]]
211 | activation = CosSin(dim=2)
212 |
213 | self.mul = nn.Parameter(torch.tensor(mul).float().unsqueeze(0).unsqueeze(1),
214 | requires_grad=False)
215 | self.bias = nn.Parameter(torch.tensor(bias).float().unsqueeze(0).unsqueeze(1),
216 | requires_grad=False)
217 | if no_activation:
218 | self.activation = None
219 | else:
220 | self.activation = activation
221 |
222 | def forward(self, input):
223 | if not (self.activation is None):
224 | input = self.activation(input)
225 | return (input.unsqueeze(3).unsqueeze(4) * self.mul).sum(2) + self.bias
226 |
227 |
228 | def add_edge_points(points, n_points):
229 | points = np.array(points)
230 | new_points = []
231 | pnts_per_egdge = (n_points-1) // (len(points)-1)
232 | extra_points = (n_points-1) % (len(points)-1)
233 | for i in range(len(points)-1):
234 | if extra_points > 0:
235 | extra_points -= 1
236 | ep = 1
237 | else:
238 | ep = 0
239 | edge_points = np.linspace(points[i], points[i+1], pnts_per_egdge+ep, endpoint=False)
240 | new_points.append(edge_points)
241 | new_points.append(points[-1][np.newaxis])
242 | new_points = np.concatenate(new_points)
243 | return new_points
244 |
245 |
246 | def create_circle(n_points, scale=0.5, percent=1.):
247 | x = np.linspace(0., 2*np.pi*percent, n_points)
248 | points = np.stack([np.sin(x), np.cos(x)], axis=1)
249 | points = points * scale
250 | return points
251 |
252 |
253 | def get_predefined_primitives(primitive_names, n_points=25, normalize=True,
254 | scale=1.):
255 | points = []
256 |
257 | for pname in primitive_names:
258 | # Square
259 | if pname == 'square':
260 | pnts = [[-0.5, -0.5], [-0.5, 0.5], [0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]]
261 | pnts = add_edge_points(pnts, n_points)
262 | points.append(torch.from_numpy(pnts).float())
263 |
264 | # Triangle
265 | elif pname == 'triangle':
266 | pnts = [[-0.5, 0.44], [0.5, 0.44], [0., -0.44], [-0.5, 0.44]]
267 | pnts = add_edge_points(pnts, n_points)
268 | points.append(torch.from_numpy(pnts).float())
269 |
270 | # Circle
271 | elif pname == 'circle':
272 | pnts = create_circle(n_points)
273 | points.append(torch.from_numpy(pnts).float())
274 |
275 | # Half-circle
276 | elif pname == 'halfcircle':
277 | pnts = create_circle(n_points, percent=0.5)
278 | points.append(torch.from_numpy(pnts).float())
279 |
280 | # Line
281 | elif pname == 'line':
282 | pnts = [[-0.5, 0.], [0.5, 0.]]
283 | pnts = add_edge_points(pnts, n_points)
284 | points.append(torch.from_numpy(pnts).float())
285 |
286 | # Corner
287 | elif pname == 'corner':
288 | pnts = [[-0.5, -0.5], [-0.5, 0.5], [0.5, 0.5]]
289 | pnts = add_edge_points(pnts, n_points)
290 | points.append(torch.from_numpy(pnts).float())
291 |
292 | # u
293 | elif pname == 'u':
294 | pnts = [[-0.5, -0.5], [-0.5, 0.5], [0.5, 0.5], [0.5, -0.5]]
295 | pnts = add_edge_points(pnts, n_points)
296 | points.append(torch.from_numpy(pnts).float())
297 |
298 | # dot (single point
299 | elif pname == 'dot':
300 | pnts = [[0., 0.]]
301 | pnts = np.array(pnts).repeat(n_points, axis=0)
302 | points.append(torch.from_numpy(pnts).float())
303 |
304 | primitives = torch.stack(points)
305 | if normalize:
306 | primitives, _, _ = normalize_strokes(primitives)
307 |
308 | if scale != 1.:
309 | primitives = primitives * scale
310 |
311 | return primitives
312 |
313 | def compute_full_transformation(transform_layers, transformation_parameters):
314 | mat = None
315 | for t_layer, params in zip(transform_layers, transformation_parameters):
316 | t_mat = t_layer(params)
317 |
318 | if mat is None:
319 | mat = t_mat
320 | else:
321 | mat = t_mat @ mat
322 |
323 | return mat
324 |
325 |
326 | def transform_primitives(primitives, transform_layers, transforms_params, prim_ids=None):
327 | full_transforms = compute_full_transformation(transform_layers, transforms_params)
328 |
329 | if prim_ids is None:
330 | if primitives.size(0) != transforms_params[0].size(0):
331 | full_prim_htan = primitives.unsqueeze(0).expand([transforms_params[0].size(0)]+list(primitives.size()))
332 | else:
333 | full_prim_htan = primitives.unsqueeze(2)
334 | else:
335 | full_prim_htan = primitives.unsqueeze(0).repeat(prim_ids.size(0), 1, 1, 1).gather(1, prim_ids.repeat(1, 1, primitives.size(1), primitives.size(2)))
336 |
337 | full_prim_htan = torch.cat(
338 | [full_prim_htan, torch.ones(full_prim_htan.size()[:-1]).unsqueeze(-1).to(full_prim_htan.device)], dim=-1)
339 |
340 | full_prim_htan = full_prim_htan.unsqueeze(-2) @ full_transforms.unsqueeze(-3).transpose(-2, -1)
341 |
342 | return full_prim_htan
343 |
--------------------------------------------------------------------------------