razfar commited on
Commit
a232b82
1 Parent(s): daf23cc

added application files

Browse files
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .DS_Store
Inference/test.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ test
LICENSE.md ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md CHANGED
@@ -1,7 +1,7 @@
1
  ---
2
  title: Anything Counter
3
- emoji: 💩
4
- colorFrom: red
5
  colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 3.4.1
@@ -9,5 +9,3 @@ app_file: app.py
9
  pinned: false
10
  license: gpl-3.0
11
  ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
  title: Anything Counter
3
+ emoji: 🧮
4
+ colorFrom: purple
5
  colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 3.4.1
 
9
  pinned: false
10
  license: gpl-3.0
11
  ---
 
 
app.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+
4
+ import argparse
5
+ import time
6
+ from pathlib import Path
7
+
8
+ import cv2
9
+ import torch
10
+ import torch.backends.cudnn as cudnn
11
+ from numpy import random
12
+
13
+ from models.experimental import attempt_load
14
+ from utils.datasets import LoadStreams, LoadImages
15
+ from utils.general import (
16
+ check_img_size,
17
+ check_imshow,
18
+ non_max_suppression,
19
+ apply_classifier,
20
+ scale_coords,
21
+ xyxy2xywh,
22
+ set_logging,
23
+ increment_path,
24
+ )
25
+ from utils.plots import plot_one_box
26
+ from utils.torch_utils import (
27
+ select_device,
28
+ load_classifier,
29
+ time_synchronized,
30
+ TracedModel,
31
+ )
32
+ from PIL import Image
33
+
34
+ from huggingface_hub import hf_hub_download
35
+
36
+
37
+ def load_model(model_name):
38
+ model_path = hf_hub_download(
39
+ repo_id=f"Yolov7/{model_name}", filename=f"{model_name}.pt"
40
+ )
41
+
42
+ return model_path
43
+
44
+
45
+ loaded_model = load_model("yolov7")
46
+
47
+
48
+ def detect(img):
49
+ parser = argparse.ArgumentParser()
50
+ parser.add_argument(
51
+ "--weights", nargs="+", type=str, default=loaded_model, help="model.pt path(s)"
52
+ )
53
+ parser.add_argument(
54
+ "--source", type=str, default="Inference/", help="source"
55
+ ) # file/folder, 0 for webcam
56
+ parser.add_argument(
57
+ "--img-size", type=int, default=640, help="inference size (pixels)"
58
+ )
59
+ parser.add_argument(
60
+ "--conf-thres", type=float, default=0.25, help="object confidence threshold"
61
+ )
62
+ parser.add_argument(
63
+ "--iou-thres", type=float, default=0.45, help="IOU threshold for NMS"
64
+ )
65
+ parser.add_argument(
66
+ "--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu"
67
+ )
68
+ parser.add_argument("--view-img", action="store_true", help="display results")
69
+ parser.add_argument("--save-txt", action="store_true", help="save results to *.txt")
70
+ parser.add_argument(
71
+ "--save-conf", action="store_true", help="save confidences in --save-txt labels"
72
+ )
73
+ parser.add_argument(
74
+ "--nosave", action="store_true", help="do not save images/videos"
75
+ )
76
+ parser.add_argument(
77
+ "--classes",
78
+ nargs="+",
79
+ type=int,
80
+ help="filter by class: --class 0, or --class 0 2 3",
81
+ )
82
+ parser.add_argument(
83
+ "--agnostic-nms", action="store_true", help="class-agnostic NMS"
84
+ )
85
+ parser.add_argument("--augment", action="store_true", help="augmented inference")
86
+ parser.add_argument("--update", action="store_true", help="update all models")
87
+ parser.add_argument(
88
+ "--project", default="runs/detect", help="save results to project/name"
89
+ )
90
+ parser.add_argument("--name", default="exp", help="save results to project/name")
91
+ parser.add_argument(
92
+ "--exist-ok",
93
+ action="store_true",
94
+ help="existing project/name ok, do not increment",
95
+ )
96
+ parser.add_argument("--trace", action="store_true", help="trace model")
97
+ opt = parser.parse_args()
98
+ img.save("Inference/test.jpg")
99
+ source, weights, view_img, save_txt, imgsz, trace = (
100
+ opt.source,
101
+ opt.weights,
102
+ opt.view_img,
103
+ opt.save_txt,
104
+ opt.img_size,
105
+ opt.trace,
106
+ )
107
+ save_img = True # save inference images
108
+ webcam = (
109
+ source.isnumeric()
110
+ or source.endswith(".txt")
111
+ or source.lower().startswith(("rtsp://", "rtmp://", "http://", "https://"))
112
+ )
113
+
114
+ # Directories
115
+ save_dir = Path(
116
+ increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)
117
+ ) # increment run
118
+ (save_dir / "labels" if save_txt else save_dir).mkdir(
119
+ parents=True, exist_ok=True
120
+ ) # make dir
121
+
122
+ # Initialize
123
+ set_logging()
124
+ device = select_device(opt.device)
125
+ half = device.type != "cpu" # half precision only supported on CUDA
126
+
127
+ # Load model
128
+ model = attempt_load(weights, map_location=device) # load FP32 model
129
+ stride = int(model.stride.max()) # model stride
130
+ imgsz = check_img_size(imgsz, s=stride) # check img_size
131
+
132
+ if trace:
133
+ model = TracedModel(model, device, opt.img_size)
134
+
135
+ if half:
136
+ model.half() # to FP16
137
+
138
+ # Second-stage classifier
139
+ classify = False
140
+ if classify:
141
+ modelc = load_classifier(name="resnet101", n=2) # initialize
142
+ modelc.load_state_dict(
143
+ torch.load("weights/resnet101.pt", map_location=device)["model"]
144
+ ).to(device).eval()
145
+
146
+ # Set Dataloader
147
+ vid_path, vid_writer = None, None
148
+ if webcam:
149
+ view_img = check_imshow()
150
+ cudnn.benchmark = True # set True to speed up constant image size inference
151
+ dataset = LoadStreams(source, img_size=imgsz, stride=stride)
152
+ else:
153
+ dataset = LoadImages(source, img_size=imgsz, stride=stride)
154
+
155
+ # Get names and colors
156
+ names = model.module.names if hasattr(model, "module") else model.names
157
+ colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
158
+
159
+ # Run inference
160
+ if device.type != "cpu":
161
+ model(
162
+ torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))
163
+ ) # run once
164
+ t0 = time.time()
165
+ for path, img, im0s, vid_cap in dataset:
166
+ img = torch.from_numpy(img).to(device)
167
+ img = img.half() if half else img.float() # uint8 to fp16/32
168
+ img /= 255.0 # 0 - 255 to 0.0 - 1.0
169
+ if img.ndimension() == 3:
170
+ img = img.unsqueeze(0)
171
+
172
+ # Inference
173
+ t1 = time_synchronized()
174
+ pred = model(img, augment=opt.augment)[0]
175
+
176
+ # Apply NMS
177
+ pred = non_max_suppression(
178
+ pred,
179
+ opt.conf_thres,
180
+ opt.iou_thres,
181
+ classes=opt.classes,
182
+ agnostic=opt.agnostic_nms,
183
+ )
184
+ t2 = time_synchronized()
185
+
186
+ # Apply Classifier
187
+ if classify:
188
+ pred = apply_classifier(pred, modelc, img, im0s)
189
+
190
+ # Process detections
191
+ for i, det in enumerate(pred): # detections per image
192
+ if webcam: # batch_size >= 1
193
+ p, s, im0, frame = path[i], "%g: " % i, im0s[i].copy(), dataset.count
194
+ else:
195
+ p, s, im0, frame = path, "", im0s, getattr(dataset, "frame", 0)
196
+
197
+ p = Path(p) # to Path
198
+ save_path = str(save_dir / p.name) # img.jpg
199
+ txt_path = str(save_dir / "labels" / p.stem) + (
200
+ "" if dataset.mode == "image" else f"_{frame}"
201
+ ) # img.txt
202
+ s += "%gx%g " % img.shape[2:] # print string
203
+ gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
204
+ if len(det):
205
+ # Rescale boxes from img_size to im0 size
206
+ det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
207
+
208
+ # Print results
209
+ for c in det[:, -1].unique():
210
+ n = (det[:, -1] == c).sum() # detections per class
211
+ s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
212
+
213
+ # Write results
214
+ for *xyxy, conf, cls in reversed(det):
215
+ if save_txt: # Write to file
216
+ xywh = (
217
+ (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn)
218
+ .view(-1)
219
+ .tolist()
220
+ ) # normalized xywh
221
+ line = (
222
+ (cls, *xywh, conf) if opt.save_conf else (cls, *xywh)
223
+ ) # label format
224
+ with open(txt_path + ".txt", "a") as f:
225
+ f.write(("%g " * len(line)).rstrip() % line + "\n")
226
+
227
+ if save_img or view_img: # Add bbox to image
228
+ label = f"{names[int(cls)]} {conf:.2f}"
229
+ plot_one_box(
230
+ xyxy,
231
+ im0,
232
+ label=label,
233
+ color=colors[int(cls)],
234
+ line_thickness=3,
235
+ )
236
+
237
+ # Print time (inference + NMS)
238
+ # print(f'{s}Done. ({t2 - t1:.3f}s)')
239
+
240
+ # Stream results
241
+ if view_img:
242
+ cv2.imshow(str(p), im0)
243
+ cv2.waitKey(1) # 1 millisecond
244
+
245
+ # Save results (image with detections)
246
+ if save_img:
247
+ if dataset.mode == "image":
248
+ cv2.imwrite(save_path, im0)
249
+ else: # 'video' or 'stream'
250
+ if vid_path != save_path: # new video
251
+ vid_path = save_path
252
+ if isinstance(vid_writer, cv2.VideoWriter):
253
+ vid_writer.release() # release previous video writer
254
+ if vid_cap: # video
255
+ fps = vid_cap.get(cv2.CAP_PROP_FPS)
256
+ w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
257
+ h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
258
+ else: # stream
259
+ fps, w, h = 30, im0.shape[1], im0.shape[0]
260
+ save_path += ".mp4"
261
+ vid_writer = cv2.VideoWriter(
262
+ save_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h)
263
+ )
264
+ vid_writer.write(im0)
265
+
266
+ if save_txt or save_img:
267
+ s = (
268
+ f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}"
269
+ if save_txt
270
+ else ""
271
+ )
272
+ # print(f"Results saved to {save_dir}{s}")
273
+
274
+ print(f"Done. ({time.time() - t0:.3f}s)")
275
+
276
+ return Image.fromarray(im0[:, :, ::-1])
277
+
278
+
279
+ gr.Interface(
280
+ detect,
281
+ [gr.Image(type="pil")],
282
+ gr.Image(type="pil"),
283
+ title="Anything Counter",
284
+ ).launch(debug=True)
models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # init
models/common.py ADDED
@@ -0,0 +1,2019 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from copy import copy
3
+ from pathlib import Path
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ import requests
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from torchvision.ops import DeformConv2d
12
+ from PIL import Image
13
+ from torch.cuda import amp
14
+
15
+ from utils.datasets import letterbox
16
+ from utils.general import non_max_suppression, make_divisible, scale_coords, increment_path, xyxy2xywh
17
+ from utils.plots import color_list, plot_one_box
18
+ from utils.torch_utils import time_synchronized
19
+
20
+
21
+ ##### basic ####
22
+
23
+ def autopad(k, p=None): # kernel, padding
24
+ # Pad to 'same'
25
+ if p is None:
26
+ p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
27
+ return p
28
+
29
+
30
+ class MP(nn.Module):
31
+ def __init__(self, k=2):
32
+ super(MP, self).__init__()
33
+ self.m = nn.MaxPool2d(kernel_size=k, stride=k)
34
+
35
+ def forward(self, x):
36
+ return self.m(x)
37
+
38
+
39
+ class SP(nn.Module):
40
+ def __init__(self, k=3, s=1):
41
+ super(SP, self).__init__()
42
+ self.m = nn.MaxPool2d(kernel_size=k, stride=s, padding=k // 2)
43
+
44
+ def forward(self, x):
45
+ return self.m(x)
46
+
47
+
48
+ class ReOrg(nn.Module):
49
+ def __init__(self):
50
+ super(ReOrg, self).__init__()
51
+
52
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
53
+ return torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1)
54
+
55
+
56
+ class Concat(nn.Module):
57
+ def __init__(self, dimension=1):
58
+ super(Concat, self).__init__()
59
+ self.d = dimension
60
+
61
+ def forward(self, x):
62
+ return torch.cat(x, self.d)
63
+
64
+
65
+ class Chuncat(nn.Module):
66
+ def __init__(self, dimension=1):
67
+ super(Chuncat, self).__init__()
68
+ self.d = dimension
69
+
70
+ def forward(self, x):
71
+ x1 = []
72
+ x2 = []
73
+ for xi in x:
74
+ xi1, xi2 = xi.chunk(2, self.d)
75
+ x1.append(xi1)
76
+ x2.append(xi2)
77
+ return torch.cat(x1+x2, self.d)
78
+
79
+
80
+ class Shortcut(nn.Module):
81
+ def __init__(self, dimension=0):
82
+ super(Shortcut, self).__init__()
83
+ self.d = dimension
84
+
85
+ def forward(self, x):
86
+ return x[0]+x[1]
87
+
88
+
89
+ class Foldcut(nn.Module):
90
+ def __init__(self, dimension=0):
91
+ super(Foldcut, self).__init__()
92
+ self.d = dimension
93
+
94
+ def forward(self, x):
95
+ x1, x2 = x.chunk(2, self.d)
96
+ return x1+x2
97
+
98
+
99
+ class Conv(nn.Module):
100
+ # Standard convolution
101
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
102
+ super(Conv, self).__init__()
103
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
104
+ self.bn = nn.BatchNorm2d(c2)
105
+ self.act = nn.LeakyReLU(0.1, inplace=True) if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
106
+
107
+ def forward(self, x):
108
+ return self.act(self.bn(self.conv(x)))
109
+
110
+ def fuseforward(self, x):
111
+ return self.act(self.conv(x))
112
+
113
+
114
+ class RobustConv(nn.Module):
115
+ # Robust convolution (use high kernel size 7-11 for: downsampling and other layers). Train for 300 - 450 epochs.
116
+ def __init__(self, c1, c2, k=7, s=1, p=None, g=1, act=True, layer_scale_init_value=1e-6): # ch_in, ch_out, kernel, stride, padding, groups
117
+ super(RobustConv, self).__init__()
118
+ self.conv_dw = Conv(c1, c1, k=k, s=s, p=p, g=c1, act=act)
119
+ self.conv1x1 = nn.Conv2d(c1, c2, 1, 1, 0, groups=1, bias=True)
120
+ self.gamma = nn.Parameter(layer_scale_init_value * torch.ones(c2)) if layer_scale_init_value > 0 else None
121
+
122
+ def forward(self, x):
123
+ x = x.to(memory_format=torch.channels_last)
124
+ x = self.conv1x1(self.conv_dw(x))
125
+ if self.gamma is not None:
126
+ x = x.mul(self.gamma.reshape(1, -1, 1, 1))
127
+ return x
128
+
129
+
130
+ class RobustConv2(nn.Module):
131
+ # Robust convolution 2 (use [32, 5, 2] or [32, 7, 4] or [32, 11, 8] for one of the paths in CSP).
132
+ def __init__(self, c1, c2, k=7, s=4, p=None, g=1, act=True, layer_scale_init_value=1e-6): # ch_in, ch_out, kernel, stride, padding, groups
133
+ super(RobustConv2, self).__init__()
134
+ self.conv_strided = Conv(c1, c1, k=k, s=s, p=p, g=c1, act=act)
135
+ self.conv_deconv = nn.ConvTranspose2d(in_channels=c1, out_channels=c2, kernel_size=s, stride=s,
136
+ padding=0, bias=True, dilation=1, groups=1
137
+ )
138
+ self.gamma = nn.Parameter(layer_scale_init_value * torch.ones(c2)) if layer_scale_init_value > 0 else None
139
+
140
+ def forward(self, x):
141
+ x = self.conv_deconv(self.conv_strided(x))
142
+ if self.gamma is not None:
143
+ x = x.mul(self.gamma.reshape(1, -1, 1, 1))
144
+ return x
145
+
146
+
147
+ def DWConv(c1, c2, k=1, s=1, act=True):
148
+ # Depthwise convolution
149
+ return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
150
+
151
+
152
+ class GhostConv(nn.Module):
153
+ # Ghost Convolution https://github.com/huawei-noah/ghostnet
154
+ def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
155
+ super(GhostConv, self).__init__()
156
+ c_ = c2 // 2 # hidden channels
157
+ self.cv1 = Conv(c1, c_, k, s, None, g, act)
158
+ self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
159
+
160
+ def forward(self, x):
161
+ y = self.cv1(x)
162
+ return torch.cat([y, self.cv2(y)], 1)
163
+
164
+
165
+ class Stem(nn.Module):
166
+ # Stem
167
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
168
+ super(Stem, self).__init__()
169
+ c_ = int(c2/2) # hidden channels
170
+ self.cv1 = Conv(c1, c_, 3, 2)
171
+ self.cv2 = Conv(c_, c_, 1, 1)
172
+ self.cv3 = Conv(c_, c_, 3, 2)
173
+ self.pool = torch.nn.MaxPool2d(2, stride=2)
174
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
175
+
176
+ def forward(self, x):
177
+ x = self.cv1(x)
178
+ return self.cv4(torch.cat((self.cv3(self.cv2(x)), self.pool(x)), dim=1))
179
+
180
+
181
+ class DownC(nn.Module):
182
+ # Spatial pyramid pooling layer used in YOLOv3-SPP
183
+ def __init__(self, c1, c2, n=1, k=2):
184
+ super(DownC, self).__init__()
185
+ c_ = int(c1) # hidden channels
186
+ self.cv1 = Conv(c1, c_, 1, 1)
187
+ self.cv2 = Conv(c_, c2//2, 3, k)
188
+ self.cv3 = Conv(c1, c2//2, 1, 1)
189
+ self.mp = nn.MaxPool2d(kernel_size=k, stride=k)
190
+
191
+ def forward(self, x):
192
+ return torch.cat((self.cv2(self.cv1(x)), self.cv3(self.mp(x))), dim=1)
193
+
194
+
195
+ class SPP(nn.Module):
196
+ # Spatial pyramid pooling layer used in YOLOv3-SPP
197
+ def __init__(self, c1, c2, k=(5, 9, 13)):
198
+ super(SPP, self).__init__()
199
+ c_ = c1 // 2 # hidden channels
200
+ self.cv1 = Conv(c1, c_, 1, 1)
201
+ self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
202
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
203
+
204
+ def forward(self, x):
205
+ x = self.cv1(x)
206
+ return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
207
+
208
+
209
+ class Bottleneck(nn.Module):
210
+ # Darknet bottleneck
211
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
212
+ super(Bottleneck, self).__init__()
213
+ c_ = int(c2 * e) # hidden channels
214
+ self.cv1 = Conv(c1, c_, 1, 1)
215
+ self.cv2 = Conv(c_, c2, 3, 1, g=g)
216
+ self.add = shortcut and c1 == c2
217
+
218
+ def forward(self, x):
219
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
220
+
221
+
222
+ class Res(nn.Module):
223
+ # ResNet bottleneck
224
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
225
+ super(Res, self).__init__()
226
+ c_ = int(c2 * e) # hidden channels
227
+ self.cv1 = Conv(c1, c_, 1, 1)
228
+ self.cv2 = Conv(c_, c_, 3, 1, g=g)
229
+ self.cv3 = Conv(c_, c2, 1, 1)
230
+ self.add = shortcut and c1 == c2
231
+
232
+ def forward(self, x):
233
+ return x + self.cv3(self.cv2(self.cv1(x))) if self.add else self.cv3(self.cv2(self.cv1(x)))
234
+
235
+
236
+ class ResX(Res):
237
+ # ResNet bottleneck
238
+ def __init__(self, c1, c2, shortcut=True, g=32, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
239
+ super().__init__(c1, c2, shortcu, g, e)
240
+ c_ = int(c2 * e) # hidden channels
241
+
242
+
243
+ class Ghost(nn.Module):
244
+ # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
245
+ def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
246
+ super(Ghost, self).__init__()
247
+ c_ = c2 // 2
248
+ self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
249
+ DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
250
+ GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
251
+ self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
252
+ Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
253
+
254
+ def forward(self, x):
255
+ return self.conv(x) + self.shortcut(x)
256
+
257
+ ##### end of basic #####
258
+
259
+
260
+ ##### cspnet #####
261
+
262
+ class SPPCSPC(nn.Module):
263
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
264
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5, k=(5, 9, 13)):
265
+ super(SPPCSPC, self).__init__()
266
+ c_ = int(2 * c2 * e) # hidden channels
267
+ self.cv1 = Conv(c1, c_, 1, 1)
268
+ self.cv2 = Conv(c1, c_, 1, 1)
269
+ self.cv3 = Conv(c_, c_, 3, 1)
270
+ self.cv4 = Conv(c_, c_, 1, 1)
271
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
272
+ self.cv5 = Conv(4 * c_, c_, 1, 1)
273
+ self.cv6 = Conv(c_, c_, 3, 1)
274
+ self.cv7 = Conv(2 * c_, c2, 1, 1)
275
+
276
+ def forward(self, x):
277
+ x1 = self.cv4(self.cv3(self.cv1(x)))
278
+ y1 = self.cv6(self.cv5(torch.cat([x1] + [m(x1) for m in self.m], 1)))
279
+ y2 = self.cv2(x)
280
+ return self.cv7(torch.cat((y1, y2), dim=1))
281
+
282
+ class GhostSPPCSPC(SPPCSPC):
283
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
284
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5, k=(5, 9, 13)):
285
+ super().__init__(c1, c2, n, shortcut, g, e, k)
286
+ c_ = int(2 * c2 * e) # hidden channels
287
+ self.cv1 = GhostConv(c1, c_, 1, 1)
288
+ self.cv2 = GhostConv(c1, c_, 1, 1)
289
+ self.cv3 = GhostConv(c_, c_, 3, 1)
290
+ self.cv4 = GhostConv(c_, c_, 1, 1)
291
+ self.cv5 = GhostConv(4 * c_, c_, 1, 1)
292
+ self.cv6 = GhostConv(c_, c_, 3, 1)
293
+ self.cv7 = GhostConv(2 * c_, c2, 1, 1)
294
+
295
+
296
+ class GhostStem(Stem):
297
+ # Stem
298
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
299
+ super().__init__(c1, c2, k, s, p, g, act)
300
+ c_ = int(c2/2) # hidden channels
301
+ self.cv1 = GhostConv(c1, c_, 3, 2)
302
+ self.cv2 = GhostConv(c_, c_, 1, 1)
303
+ self.cv3 = GhostConv(c_, c_, 3, 2)
304
+ self.cv4 = GhostConv(2 * c_, c2, 1, 1)
305
+
306
+
307
+ class BottleneckCSPA(nn.Module):
308
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
309
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
310
+ super(BottleneckCSPA, self).__init__()
311
+ c_ = int(c2 * e) # hidden channels
312
+ self.cv1 = Conv(c1, c_, 1, 1)
313
+ self.cv2 = Conv(c1, c_, 1, 1)
314
+ self.cv3 = Conv(2 * c_, c2, 1, 1)
315
+ self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
316
+
317
+ def forward(self, x):
318
+ y1 = self.m(self.cv1(x))
319
+ y2 = self.cv2(x)
320
+ return self.cv3(torch.cat((y1, y2), dim=1))
321
+
322
+
323
+ class BottleneckCSPB(nn.Module):
324
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
325
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
326
+ super(BottleneckCSPB, self).__init__()
327
+ c_ = int(c2) # hidden channels
328
+ self.cv1 = Conv(c1, c_, 1, 1)
329
+ self.cv2 = Conv(c_, c_, 1, 1)
330
+ self.cv3 = Conv(2 * c_, c2, 1, 1)
331
+ self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
332
+
333
+ def forward(self, x):
334
+ x1 = self.cv1(x)
335
+ y1 = self.m(x1)
336
+ y2 = self.cv2(x1)
337
+ return self.cv3(torch.cat((y1, y2), dim=1))
338
+
339
+
340
+ class BottleneckCSPC(nn.Module):
341
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
342
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
343
+ super(BottleneckCSPC, self).__init__()
344
+ c_ = int(c2 * e) # hidden channels
345
+ self.cv1 = Conv(c1, c_, 1, 1)
346
+ self.cv2 = Conv(c1, c_, 1, 1)
347
+ self.cv3 = Conv(c_, c_, 1, 1)
348
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
349
+ self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
350
+
351
+ def forward(self, x):
352
+ y1 = self.cv3(self.m(self.cv1(x)))
353
+ y2 = self.cv2(x)
354
+ return self.cv4(torch.cat((y1, y2), dim=1))
355
+
356
+
357
+ class ResCSPA(BottleneckCSPA):
358
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
359
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
360
+ super().__init__(c1, c2, n, shortcut, g, e)
361
+ c_ = int(c2 * e) # hidden channels
362
+ self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
363
+
364
+
365
+ class ResCSPB(BottleneckCSPB):
366
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
367
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
368
+ super().__init__(c1, c2, n, shortcut, g, e)
369
+ c_ = int(c2) # hidden channels
370
+ self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
371
+
372
+
373
+ class ResCSPC(BottleneckCSPC):
374
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
375
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
376
+ super().__init__(c1, c2, n, shortcut, g, e)
377
+ c_ = int(c2 * e) # hidden channels
378
+ self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
379
+
380
+
381
+ class ResXCSPA(ResCSPA):
382
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
383
+ def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
384
+ super().__init__(c1, c2, n, shortcut, g, e)
385
+ c_ = int(c2 * e) # hidden channels
386
+ self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
387
+
388
+
389
+ class ResXCSPB(ResCSPB):
390
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
391
+ def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
392
+ super().__init__(c1, c2, n, shortcut, g, e)
393
+ c_ = int(c2) # hidden channels
394
+ self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
395
+
396
+
397
+ class ResXCSPC(ResCSPC):
398
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
399
+ def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
400
+ super().__init__(c1, c2, n, shortcut, g, e)
401
+ c_ = int(c2 * e) # hidden channels
402
+ self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
403
+
404
+
405
+ class GhostCSPA(BottleneckCSPA):
406
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
407
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
408
+ super().__init__(c1, c2, n, shortcut, g, e)
409
+ c_ = int(c2 * e) # hidden channels
410
+ self.m = nn.Sequential(*[Ghost(c_, c_) for _ in range(n)])
411
+
412
+
413
+ class GhostCSPB(BottleneckCSPB):
414
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
415
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
416
+ super().__init__(c1, c2, n, shortcut, g, e)
417
+ c_ = int(c2) # hidden channels
418
+ self.m = nn.Sequential(*[Ghost(c_, c_) for _ in range(n)])
419
+
420
+
421
+ class GhostCSPC(BottleneckCSPC):
422
+ # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
423
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
424
+ super().__init__(c1, c2, n, shortcut, g, e)
425
+ c_ = int(c2 * e) # hidden channels
426
+ self.m = nn.Sequential(*[Ghost(c_, c_) for _ in range(n)])
427
+
428
+ ##### end of cspnet #####
429
+
430
+
431
+ ##### yolor #####
432
+
433
+ class ImplicitA(nn.Module):
434
+ def __init__(self, channel, mean=0., std=.02):
435
+ super(ImplicitA, self).__init__()
436
+ self.channel = channel
437
+ self.mean = mean
438
+ self.std = std
439
+ self.implicit = nn.Parameter(torch.zeros(1, channel, 1, 1))
440
+ nn.init.normal_(self.implicit, mean=self.mean, std=self.std)
441
+
442
+ def forward(self, x):
443
+ return self.implicit + x
444
+
445
+
446
+ class ImplicitM(nn.Module):
447
+ def __init__(self, channel, mean=0., std=.02):
448
+ super(ImplicitM, self).__init__()
449
+ self.channel = channel
450
+ self.mean = mean
451
+ self.std = std
452
+ self.implicit = nn.Parameter(torch.ones(1, channel, 1, 1))
453
+ nn.init.normal_(self.implicit, mean=self.mean, std=self.std)
454
+
455
+ def forward(self, x):
456
+ return self.implicit * x
457
+
458
+ ##### end of yolor #####
459
+
460
+
461
+ ##### repvgg #####
462
+
463
+ class RepConv(nn.Module):
464
+ # Represented convolution
465
+ # https://arxiv.org/abs/2101.03697
466
+
467
+ def __init__(self, c1, c2, k=3, s=1, p=None, g=1, act=True, deploy=False):
468
+ super(RepConv, self).__init__()
469
+
470
+ self.deploy = deploy
471
+ self.groups = g
472
+ self.in_channels = c1
473
+ self.out_channels = c2
474
+
475
+ assert k == 3
476
+ assert autopad(k, p) == 1
477
+
478
+ padding_11 = autopad(k, p) - k // 2
479
+
480
+ self.act = nn.LeakyReLU(0.1, inplace=True) if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
481
+
482
+ if deploy:
483
+ self.rbr_reparam = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=True)
484
+
485
+ else:
486
+ self.rbr_identity = (nn.BatchNorm2d(num_features=c1) if c2 == c1 and s == 1 else None)
487
+
488
+ self.rbr_dense = nn.Sequential(
489
+ nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False),
490
+ nn.BatchNorm2d(num_features=c2),
491
+ )
492
+
493
+ self.rbr_1x1 = nn.Sequential(
494
+ nn.Conv2d( c1, c2, 1, s, padding_11, groups=g, bias=False),
495
+ nn.BatchNorm2d(num_features=c2),
496
+ )
497
+
498
+ def forward(self, inputs):
499
+ if hasattr(self, "rbr_reparam"):
500
+ return self.act(self.rbr_reparam(inputs))
501
+
502
+ if self.rbr_identity is None:
503
+ id_out = 0
504
+ else:
505
+ id_out = self.rbr_identity(inputs)
506
+
507
+ return self.act(self.rbr_dense(inputs) + self.rbr_1x1(inputs) + id_out)
508
+
509
+ def get_equivalent_kernel_bias(self):
510
+ kernel3x3, bias3x3 = self._fuse_bn_tensor(self.rbr_dense)
511
+ kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)
512
+ kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)
513
+ return (
514
+ kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid,
515
+ bias3x3 + bias1x1 + biasid,
516
+ )
517
+
518
+ def _pad_1x1_to_3x3_tensor(self, kernel1x1):
519
+ if kernel1x1 is None:
520
+ return 0
521
+ else:
522
+ return nn.functional.pad(kernel1x1, [1, 1, 1, 1])
523
+
524
+ def _fuse_bn_tensor(self, branch):
525
+ if branch is None:
526
+ return 0, 0
527
+ if isinstance(branch, nn.Sequential):
528
+ kernel = branch[0].weight
529
+ running_mean = branch[1].running_mean
530
+ running_var = branch[1].running_var
531
+ gamma = branch[1].weight
532
+ beta = branch[1].bias
533
+ eps = branch[1].eps
534
+ else:
535
+ assert isinstance(branch, nn.BatchNorm2d)
536
+ if not hasattr(self, "id_tensor"):
537
+ input_dim = self.in_channels // self.groups
538
+ kernel_value = np.zeros(
539
+ (self.in_channels, input_dim, 3, 3), dtype=np.float32
540
+ )
541
+ for i in range(self.in_channels):
542
+ kernel_value[i, i % input_dim, 1, 1] = 1
543
+ self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
544
+ kernel = self.id_tensor
545
+ running_mean = branch.running_mean
546
+ running_var = branch.running_var
547
+ gamma = branch.weight
548
+ beta = branch.bias
549
+ eps = branch.eps
550
+ std = (running_var + eps).sqrt()
551
+ t = (gamma / std).reshape(-1, 1, 1, 1)
552
+ return kernel * t, beta - running_mean * gamma / std
553
+
554
+ def repvgg_convert(self):
555
+ kernel, bias = self.get_equivalent_kernel_bias()
556
+ return (
557
+ kernel.detach().cpu().numpy(),
558
+ bias.detach().cpu().numpy(),
559
+ )
560
+
561
+ def fuse_conv_bn(self, conv, bn):
562
+
563
+ std = (bn.running_var + bn.eps).sqrt()
564
+ bias = bn.bias - bn.running_mean * bn.weight / std
565
+
566
+ t = (bn.weight / std).reshape(-1, 1, 1, 1)
567
+ weights = conv.weight * t
568
+
569
+ bn = nn.Identity()
570
+ conv = nn.Conv2d(in_channels = conv.in_channels,
571
+ out_channels = conv.out_channels,
572
+ kernel_size = conv.kernel_size,
573
+ stride=conv.stride,
574
+ padding = conv.padding,
575
+ dilation = conv.dilation,
576
+ groups = conv.groups,
577
+ bias = True,
578
+ padding_mode = conv.padding_mode)
579
+
580
+ conv.weight = torch.nn.Parameter(weights)
581
+ conv.bias = torch.nn.Parameter(bias)
582
+ return conv
583
+
584
+ def fuse_repvgg_block(self):
585
+ if self.deploy:
586
+ return
587
+ print(f"RepConv.fuse_repvgg_block")
588
+
589
+ self.rbr_dense = self.fuse_conv_bn(self.rbr_dense[0], self.rbr_dense[1])
590
+
591
+ self.rbr_1x1 = self.fuse_conv_bn(self.rbr_1x1[0], self.rbr_1x1[1])
592
+ rbr_1x1_bias = self.rbr_1x1.bias
593
+ weight_1x1_expanded = torch.nn.functional.pad(self.rbr_1x1.weight, [1, 1, 1, 1])
594
+
595
+ # Fuse self.rbr_identity
596
+ if (isinstance(self.rbr_identity, nn.BatchNorm2d) or isinstance(self.rbr_identity, nn.modules.batchnorm.SyncBatchNorm)):
597
+ # print(f"fuse: rbr_identity == BatchNorm2d or SyncBatchNorm")
598
+ identity_conv_1x1 = nn.Conv2d(
599
+ in_channels=self.in_channels,
600
+ out_channels=self.out_channels,
601
+ kernel_size=1,
602
+ stride=1,
603
+ padding=0,
604
+ groups=self.groups,
605
+ bias=False)
606
+ identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.to(self.rbr_1x1.weight.data.device)
607
+ identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.squeeze().squeeze()
608
+ # print(f" identity_conv_1x1.weight = {identity_conv_1x1.weight.shape}")
609
+ identity_conv_1x1.weight.data.fill_(0.0)
610
+ identity_conv_1x1.weight.data.fill_diagonal_(1.0)
611
+ identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.unsqueeze(2).unsqueeze(3)
612
+ # print(f" identity_conv_1x1.weight = {identity_conv_1x1.weight.shape}")
613
+
614
+ identity_conv_1x1 = self.fuse_conv_bn(identity_conv_1x1, self.rbr_identity)
615
+ bias_identity_expanded = identity_conv_1x1.bias
616
+ weight_identity_expanded = torch.nn.functional.pad(identity_conv_1x1.weight, [1, 1, 1, 1])
617
+ else:
618
+ # print(f"fuse: rbr_identity != BatchNorm2d, rbr_identity = {self.rbr_identity}")
619
+ bias_identity_expanded = torch.nn.Parameter( torch.zeros_like(rbr_1x1_bias) )
620
+ weight_identity_expanded = torch.nn.Parameter( torch.zeros_like(weight_1x1_expanded) )
621
+
622
+
623
+ #print(f"self.rbr_1x1.weight = {self.rbr_1x1.weight.shape}, ")
624
+ #print(f"weight_1x1_expanded = {weight_1x1_expanded.shape}, ")
625
+ #print(f"self.rbr_dense.weight = {self.rbr_dense.weight.shape}, ")
626
+
627
+ self.rbr_dense.weight = torch.nn.Parameter(self.rbr_dense.weight + weight_1x1_expanded + weight_identity_expanded)
628
+ self.rbr_dense.bias = torch.nn.Parameter(self.rbr_dense.bias + rbr_1x1_bias + bias_identity_expanded)
629
+
630
+ self.rbr_reparam = self.rbr_dense
631
+ self.deploy = True
632
+
633
+ if self.rbr_identity is not None:
634
+ del self.rbr_identity
635
+ self.rbr_identity = None
636
+
637
+ if self.rbr_1x1 is not None:
638
+ del self.rbr_1x1
639
+ self.rbr_1x1 = None
640
+
641
+ if self.rbr_dense is not None:
642
+ del self.rbr_dense
643
+ self.rbr_dense = None
644
+
645
+
646
+ class RepBottleneck(Bottleneck):
647
+ # Standard bottleneck
648
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
649
+ super().__init__(c1, c2, shortcut=True, g=1, e=0.5)
650
+ c_ = int(c2 * e) # hidden channels
651
+ self.cv2 = RepConv(c_, c2, 3, 1, g=g)
652
+
653
+
654
+ class RepBottleneckCSPA(BottleneckCSPA):
655
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
656
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
657
+ super().__init__(c1, c2, n, shortcut, g, e)
658
+ c_ = int(c2 * e) # hidden channels
659
+ self.m = nn.Sequential(*[RepBottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
660
+
661
+
662
+ class RepBottleneckCSPB(BottleneckCSPB):
663
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
664
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
665
+ super().__init__(c1, c2, n, shortcut, g, e)
666
+ c_ = int(c2) # hidden channels
667
+ self.m = nn.Sequential(*[RepBottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
668
+
669
+
670
+ class RepBottleneckCSPC(BottleneckCSPC):
671
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
672
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
673
+ super().__init__(c1, c2, n, shortcut, g, e)
674
+ c_ = int(c2 * e) # hidden channels
675
+ self.m = nn.Sequential(*[RepBottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
676
+
677
+
678
+ class RepRes(Res):
679
+ # Standard bottleneck
680
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
681
+ super().__init__(c1, c2, shortcut, g, e)
682
+ c_ = int(c2 * e) # hidden channels
683
+ self.cv2 = RepConv(c_, c_, 3, 1, g=g)
684
+
685
+
686
+ class RepResCSPA(ResCSPA):
687
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
688
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
689
+ super().__init__(c1, c2, n, shortcut, g, e)
690
+ c_ = int(c2 * e) # hidden channels
691
+ self.m = nn.Sequential(*[RepRes(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
692
+
693
+
694
+ class RepResCSPB(ResCSPB):
695
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
696
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
697
+ super().__init__(c1, c2, n, shortcut, g, e)
698
+ c_ = int(c2) # hidden channels
699
+ self.m = nn.Sequential(*[RepRes(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
700
+
701
+
702
+ class RepResCSPC(ResCSPC):
703
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
704
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
705
+ super().__init__(c1, c2, n, shortcut, g, e)
706
+ c_ = int(c2 * e) # hidden channels
707
+ self.m = nn.Sequential(*[RepRes(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
708
+
709
+
710
+ class RepResX(ResX):
711
+ # Standard bottleneck
712
+ def __init__(self, c1, c2, shortcut=True, g=32, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
713
+ super().__init__(c1, c2, shortcut, g, e)
714
+ c_ = int(c2 * e) # hidden channels
715
+ self.cv2 = RepConv(c_, c_, 3, 1, g=g)
716
+
717
+
718
+ class RepResXCSPA(ResXCSPA):
719
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
720
+ def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
721
+ super().__init__(c1, c2, n, shortcut, g, e)
722
+ c_ = int(c2 * e) # hidden channels
723
+ self.m = nn.Sequential(*[RepResX(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
724
+
725
+
726
+ class RepResXCSPB(ResXCSPB):
727
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
728
+ def __init__(self, c1, c2, n=1, shortcut=False, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
729
+ super().__init__(c1, c2, n, shortcut, g, e)
730
+ c_ = int(c2) # hidden channels
731
+ self.m = nn.Sequential(*[RepResX(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
732
+
733
+
734
+ class RepResXCSPC(ResXCSPC):
735
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
736
+ def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
737
+ super().__init__(c1, c2, n, shortcut, g, e)
738
+ c_ = int(c2 * e) # hidden channels
739
+ self.m = nn.Sequential(*[RepResX(c_, c_, shortcut, g, e=0.5) for _ in range(n)])
740
+
741
+ ##### end of repvgg #####
742
+
743
+
744
+ ##### transformer #####
745
+
746
+ class TransformerLayer(nn.Module):
747
+ # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
748
+ def __init__(self, c, num_heads):
749
+ super().__init__()
750
+ self.q = nn.Linear(c, c, bias=False)
751
+ self.k = nn.Linear(c, c, bias=False)
752
+ self.v = nn.Linear(c, c, bias=False)
753
+ self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
754
+ self.fc1 = nn.Linear(c, c, bias=False)
755
+ self.fc2 = nn.Linear(c, c, bias=False)
756
+
757
+ def forward(self, x):
758
+ x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
759
+ x = self.fc2(self.fc1(x)) + x
760
+ return x
761
+
762
+
763
+ class TransformerBlock(nn.Module):
764
+ # Vision Transformer https://arxiv.org/abs/2010.11929
765
+ def __init__(self, c1, c2, num_heads, num_layers):
766
+ super().__init__()
767
+ self.conv = None
768
+ if c1 != c2:
769
+ self.conv = Conv(c1, c2)
770
+ self.linear = nn.Linear(c2, c2) # learnable position embedding
771
+ self.tr = nn.Sequential(*[TransformerLayer(c2, num_heads) for _ in range(num_layers)])
772
+ self.c2 = c2
773
+
774
+ def forward(self, x):
775
+ if self.conv is not None:
776
+ x = self.conv(x)
777
+ b, _, w, h = x.shape
778
+ p = x.flatten(2)
779
+ p = p.unsqueeze(0)
780
+ p = p.transpose(0, 3)
781
+ p = p.squeeze(3)
782
+ e = self.linear(p)
783
+ x = p + e
784
+
785
+ x = self.tr(x)
786
+ x = x.unsqueeze(3)
787
+ x = x.transpose(0, 3)
788
+ x = x.reshape(b, self.c2, w, h)
789
+ return x
790
+
791
+ ##### end of transformer #####
792
+
793
+
794
+ ##### yolov5 #####
795
+
796
+ class Focus(nn.Module):
797
+ # Focus wh information into c-space
798
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
799
+ super(Focus, self).__init__()
800
+ self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
801
+ # self.contract = Contract(gain=2)
802
+
803
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
804
+ return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
805
+ # return self.conv(self.contract(x))
806
+
807
+
808
+ class SPPF(nn.Module):
809
+ # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
810
+ def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
811
+ super().__init__()
812
+ c_ = c1 // 2 # hidden channels
813
+ self.cv1 = Conv(c1, c_, 1, 1)
814
+ self.cv2 = Conv(c_ * 4, c2, 1, 1)
815
+ self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
816
+
817
+ def forward(self, x):
818
+ x = self.cv1(x)
819
+ y1 = self.m(x)
820
+ y2 = self.m(y1)
821
+ return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))
822
+
823
+
824
+ class Contract(nn.Module):
825
+ # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
826
+ def __init__(self, gain=2):
827
+ super().__init__()
828
+ self.gain = gain
829
+
830
+ def forward(self, x):
831
+ N, C, H, W = x.size() # assert (H / s == 0) and (W / s == 0), 'Indivisible gain'
832
+ s = self.gain
833
+ x = x.view(N, C, H // s, s, W // s, s) # x(1,64,40,2,40,2)
834
+ x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
835
+ return x.view(N, C * s * s, H // s, W // s) # x(1,256,40,40)
836
+
837
+
838
+ class Expand(nn.Module):
839
+ # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
840
+ def __init__(self, gain=2):
841
+ super().__init__()
842
+ self.gain = gain
843
+
844
+ def forward(self, x):
845
+ N, C, H, W = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
846
+ s = self.gain
847
+ x = x.view(N, s, s, C // s ** 2, H, W) # x(1,2,2,16,80,80)
848
+ x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
849
+ return x.view(N, C // s ** 2, H * s, W * s) # x(1,16,160,160)
850
+
851
+
852
+ class NMS(nn.Module):
853
+ # Non-Maximum Suppression (NMS) module
854
+ conf = 0.25 # confidence threshold
855
+ iou = 0.45 # IoU threshold
856
+ classes = None # (optional list) filter by class
857
+
858
+ def __init__(self):
859
+ super(NMS, self).__init__()
860
+
861
+ def forward(self, x):
862
+ return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes)
863
+
864
+
865
+ class autoShape(nn.Module):
866
+ # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
867
+ conf = 0.25 # NMS confidence threshold
868
+ iou = 0.45 # NMS IoU threshold
869
+ classes = None # (optional list) filter by class
870
+
871
+ def __init__(self, model):
872
+ super(autoShape, self).__init__()
873
+ self.model = model.eval()
874
+
875
+ def autoshape(self):
876
+ print('autoShape already enabled, skipping... ') # model already converted to model.autoshape()
877
+ return self
878
+
879
+ @torch.no_grad()
880
+ def forward(self, imgs, size=640, augment=False, profile=False):
881
+ # Inference from various sources. For height=640, width=1280, RGB images example inputs are:
882
+ # filename: imgs = 'data/samples/zidane.jpg'
883
+ # URI: = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg'
884
+ # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
885
+ # PIL: = Image.open('image.jpg') # HWC x(640,1280,3)
886
+ # numpy: = np.zeros((640,1280,3)) # HWC
887
+ # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
888
+ # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
889
+
890
+ t = [time_synchronized()]
891
+ p = next(self.model.parameters()) # for device and type
892
+ if isinstance(imgs, torch.Tensor): # torch
893
+ with amp.autocast(enabled=p.device.type != 'cpu'):
894
+ return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference
895
+
896
+ # Pre-process
897
+ n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images
898
+ shape0, shape1, files = [], [], [] # image and inference shapes, filenames
899
+ for i, im in enumerate(imgs):
900
+ f = f'image{i}' # filename
901
+ if isinstance(im, str): # filename or uri
902
+ im, f = np.asarray(Image.open(requests.get(im, stream=True).raw if im.startswith('http') else im)), im
903
+ elif isinstance(im, Image.Image): # PIL Image
904
+ im, f = np.asarray(im), getattr(im, 'filename', f) or f
905
+ files.append(Path(f).with_suffix('.jpg').name)
906
+ if im.shape[0] < 5: # image in CHW
907
+ im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
908
+ im = im[:, :, :3] if im.ndim == 3 else np.tile(im[:, :, None], 3) # enforce 3ch input
909
+ s = im.shape[:2] # HWC
910
+ shape0.append(s) # image shape
911
+ g = (size / max(s)) # gain
912
+ shape1.append([y * g for y in s])
913
+ imgs[i] = im # update
914
+ shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape
915
+ x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad
916
+ x = np.stack(x, 0) if n > 1 else x[0][None] # stack
917
+ x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW
918
+ x = torch.from_numpy(x).to(p.device).type_as(p) / 255. # uint8 to fp16/32
919
+ t.append(time_synchronized())
920
+
921
+ with amp.autocast(enabled=p.device.type != 'cpu'):
922
+ # Inference
923
+ y = self.model(x, augment, profile)[0] # forward
924
+ t.append(time_synchronized())
925
+
926
+ # Post-process
927
+ y = non_max_suppression(y, conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) # NMS
928
+ for i in range(n):
929
+ scale_coords(shape1, y[i][:, :4], shape0[i])
930
+
931
+ t.append(time_synchronized())
932
+ return Detections(imgs, y, files, t, self.names, x.shape)
933
+
934
+
935
+ class Detections:
936
+ # detections class for YOLOv5 inference results
937
+ def __init__(self, imgs, pred, files, times=None, names=None, shape=None):
938
+ super(Detections, self).__init__()
939
+ d = pred[0].device # device
940
+ gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im in imgs] # normalizations
941
+ self.imgs = imgs # list of images as numpy arrays
942
+ self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
943
+ self.names = names # class names
944
+ self.files = files # image filenames
945
+ self.xyxy = pred # xyxy pixels
946
+ self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
947
+ self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
948
+ self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
949
+ self.n = len(self.pred) # number of images (batch size)
950
+ self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms)
951
+ self.s = shape # inference BCHW shape
952
+
953
+ def display(self, pprint=False, show=False, save=False, render=False, save_dir=''):
954
+ colors = color_list()
955
+ for i, (img, pred) in enumerate(zip(self.imgs, self.pred)):
956
+ str = f'image {i + 1}/{len(self.pred)}: {img.shape[0]}x{img.shape[1]} '
957
+ if pred is not None:
958
+ for c in pred[:, -1].unique():
959
+ n = (pred[:, -1] == c).sum() # detections per class
960
+ str += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
961
+ if show or save or render:
962
+ for *box, conf, cls in pred: # xyxy, confidence, class
963
+ label = f'{self.names[int(cls)]} {conf:.2f}'
964
+ plot_one_box(box, img, label=label, color=colors[int(cls) % 10])
965
+ img = Image.fromarray(img.astype(np.uint8)) if isinstance(img, np.ndarray) else img # from np
966
+ if pprint:
967
+ print(str.rstrip(', '))
968
+ if show:
969
+ img.show(self.files[i]) # show
970
+ if save:
971
+ f = self.files[i]
972
+ img.save(Path(save_dir) / f) # save
973
+ print(f"{'Saved' * (i == 0)} {f}", end=',' if i < self.n - 1 else f' to {save_dir}\n')
974
+ if render:
975
+ self.imgs[i] = np.asarray(img)
976
+
977
+ def print(self):
978
+ self.display(pprint=True) # print results
979
+ print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' % self.t)
980
+
981
+ def show(self):
982
+ self.display(show=True) # show results
983
+
984
+ def save(self, save_dir='runs/hub/exp'):
985
+ save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/hub/exp') # increment save_dir
986
+ Path(save_dir).mkdir(parents=True, exist_ok=True)
987
+ self.display(save=True, save_dir=save_dir) # save results
988
+
989
+ def render(self):
990
+ self.display(render=True) # render results
991
+ return self.imgs
992
+
993
+ def pandas(self):
994
+ # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
995
+ new = copy(self) # return copy
996
+ ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
997
+ cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
998
+ for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
999
+ a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
1000
+ setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
1001
+ return new
1002
+
1003
+ def tolist(self):
1004
+ # return a list of Detections objects, i.e. 'for result in results.tolist():'
1005
+ x = [Detections([self.imgs[i]], [self.pred[i]], self.names, self.s) for i in range(self.n)]
1006
+ for d in x:
1007
+ for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
1008
+ setattr(d, k, getattr(d, k)[0]) # pop out of list
1009
+ return x
1010
+
1011
+ def __len__(self):
1012
+ return self.n
1013
+
1014
+
1015
+ class Classify(nn.Module):
1016
+ # Classification head, i.e. x(b,c1,20,20) to x(b,c2)
1017
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
1018
+ super(Classify, self).__init__()
1019
+ self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
1020
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
1021
+ self.flat = nn.Flatten()
1022
+
1023
+ def forward(self, x):
1024
+ z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
1025
+ return self.flat(self.conv(z)) # flatten to x(b,c2)
1026
+
1027
+ ##### end of yolov5 ######
1028
+
1029
+
1030
+ ##### orepa #####
1031
+
1032
+ def transI_fusebn(kernel, bn):
1033
+ gamma = bn.weight
1034
+ std = (bn.running_var + bn.eps).sqrt()
1035
+ return kernel * ((gamma / std).reshape(-1, 1, 1, 1)), bn.bias - bn.running_mean * gamma / std
1036
+
1037
+
1038
+ class ConvBN(nn.Module):
1039
+ def __init__(self, in_channels, out_channels, kernel_size,
1040
+ stride=1, padding=0, dilation=1, groups=1, deploy=False, nonlinear=None):
1041
+ super().__init__()
1042
+ if nonlinear is None:
1043
+ self.nonlinear = nn.Identity()
1044
+ else:
1045
+ self.nonlinear = nonlinear
1046
+ if deploy:
1047
+ self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
1048
+ stride=stride, padding=padding, dilation=dilation, groups=groups, bias=True)
1049
+ else:
1050
+ self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
1051
+ stride=stride, padding=padding, dilation=dilation, groups=groups, bias=False)
1052
+ self.bn = nn.BatchNorm2d(num_features=out_channels)
1053
+
1054
+ def forward(self, x):
1055
+ if hasattr(self, 'bn'):
1056
+ return self.nonlinear(self.bn(self.conv(x)))
1057
+ else:
1058
+ return self.nonlinear(self.conv(x))
1059
+
1060
+ def switch_to_deploy(self):
1061
+ kernel, bias = transI_fusebn(self.conv.weight, self.bn)
1062
+ conv = nn.Conv2d(in_channels=self.conv.in_channels, out_channels=self.conv.out_channels, kernel_size=self.conv.kernel_size,
1063
+ stride=self.conv.stride, padding=self.conv.padding, dilation=self.conv.dilation, groups=self.conv.groups, bias=True)
1064
+ conv.weight.data = kernel
1065
+ conv.bias.data = bias
1066
+ for para in self.parameters():
1067
+ para.detach_()
1068
+ self.__delattr__('conv')
1069
+ self.__delattr__('bn')
1070
+ self.conv = conv
1071
+
1072
+ class OREPA_3x3_RepConv(nn.Module):
1073
+
1074
+ def __init__(self, in_channels, out_channels, kernel_size,
1075
+ stride=1, padding=0, dilation=1, groups=1,
1076
+ internal_channels_1x1_3x3=None,
1077
+ deploy=False, nonlinear=None, single_init=False):
1078
+ super(OREPA_3x3_RepConv, self).__init__()
1079
+ self.deploy = deploy
1080
+
1081
+ if nonlinear is None:
1082
+ self.nonlinear = nn.Identity()
1083
+ else:
1084
+ self.nonlinear = nonlinear
1085
+
1086
+ self.kernel_size = kernel_size
1087
+ self.in_channels = in_channels
1088
+ self.out_channels = out_channels
1089
+ self.groups = groups
1090
+ assert padding == kernel_size // 2
1091
+
1092
+ self.stride = stride
1093
+ self.padding = padding
1094
+ self.dilation = dilation
1095
+
1096
+ self.branch_counter = 0
1097
+
1098
+ self.weight_rbr_origin = nn.Parameter(torch.Tensor(out_channels, int(in_channels/self.groups), kernel_size, kernel_size))
1099
+ nn.init.kaiming_uniform_(self.weight_rbr_origin, a=math.sqrt(1.0))
1100
+ self.branch_counter += 1
1101
+
1102
+
1103
+ if groups < out_channels:
1104
+ self.weight_rbr_avg_conv = nn.Parameter(torch.Tensor(out_channels, int(in_channels/self.groups), 1, 1))
1105
+ self.weight_rbr_pfir_conv = nn.Parameter(torch.Tensor(out_channels, int(in_channels/self.groups), 1, 1))
1106
+ nn.init.kaiming_uniform_(self.weight_rbr_avg_conv, a=1.0)
1107
+ nn.init.kaiming_uniform_(self.weight_rbr_pfir_conv, a=1.0)
1108
+ self.weight_rbr_avg_conv.data
1109
+ self.weight_rbr_pfir_conv.data
1110
+ self.register_buffer('weight_rbr_avg_avg', torch.ones(kernel_size, kernel_size).mul(1.0/kernel_size/kernel_size))
1111
+ self.branch_counter += 1
1112
+
1113
+ else:
1114
+ raise NotImplementedError
1115
+ self.branch_counter += 1
1116
+
1117
+ if internal_channels_1x1_3x3 is None:
1118
+ internal_channels_1x1_3x3 = in_channels if groups < out_channels else 2 * in_channels # For mobilenet, it is better to have 2X internal channels
1119
+
1120
+ if internal_channels_1x1_3x3 == in_channels:
1121
+ self.weight_rbr_1x1_kxk_idconv1 = nn.Parameter(torch.zeros(in_channels, int(in_channels/self.groups), 1, 1))
1122
+ id_value = np.zeros((in_channels, int(in_channels/self.groups), 1, 1))
1123
+ for i in range(in_channels):
1124
+ id_value[i, i % int(in_channels/self.groups), 0, 0] = 1
1125
+ id_tensor = torch.from_numpy(id_value).type_as(self.weight_rbr_1x1_kxk_idconv1)
1126
+ self.register_buffer('id_tensor', id_tensor)
1127
+
1128
+ else:
1129
+ self.weight_rbr_1x1_kxk_conv1 = nn.Parameter(torch.Tensor(internal_channels_1x1_3x3, int(in_channels/self.groups), 1, 1))
1130
+ nn.init.kaiming_uniform_(self.weight_rbr_1x1_kxk_conv1, a=math.sqrt(1.0))
1131
+ self.weight_rbr_1x1_kxk_conv2 = nn.Parameter(torch.Tensor(out_channels, int(internal_channels_1x1_3x3/self.groups), kernel_size, kernel_size))
1132
+ nn.init.kaiming_uniform_(self.weight_rbr_1x1_kxk_conv2, a=math.sqrt(1.0))
1133
+ self.branch_counter += 1
1134
+
1135
+ expand_ratio = 8
1136
+ self.weight_rbr_gconv_dw = nn.Parameter(torch.Tensor(in_channels*expand_ratio, 1, kernel_size, kernel_size))
1137
+ self.weight_rbr_gconv_pw = nn.Parameter(torch.Tensor(out_channels, in_channels*expand_ratio, 1, 1))
1138
+ nn.init.kaiming_uniform_(self.weight_rbr_gconv_dw, a=math.sqrt(1.0))
1139
+ nn.init.kaiming_uniform_(self.weight_rbr_gconv_pw, a=math.sqrt(1.0))
1140
+ self.branch_counter += 1
1141
+
1142
+ if out_channels == in_channels and stride == 1:
1143
+ self.branch_counter += 1
1144
+
1145
+ self.vector = nn.Parameter(torch.Tensor(self.branch_counter, self.out_channels))
1146
+ self.bn = nn.BatchNorm2d(out_channels)
1147
+
1148
+ self.fre_init()
1149
+
1150
+ nn.init.constant_(self.vector[0, :], 0.25) #origin
1151
+ nn.init.constant_(self.vector[1, :], 0.25) #avg
1152
+ nn.init.constant_(self.vector[2, :], 0.0) #prior
1153
+ nn.init.constant_(self.vector[3, :], 0.5) #1x1_kxk
1154
+ nn.init.constant_(self.vector[4, :], 0.5) #dws_conv
1155
+
1156
+
1157
+ def fre_init(self):
1158
+ prior_tensor = torch.Tensor(self.out_channels, self.kernel_size, self.kernel_size)
1159
+ half_fg = self.out_channels/2
1160
+ for i in range(self.out_channels):
1161
+ for h in range(3):
1162
+ for w in range(3):
1163
+ if i < half_fg:
1164
+ prior_tensor[i, h, w] = math.cos(math.pi*(h+0.5)*(i+1)/3)
1165
+ else:
1166
+ prior_tensor[i, h, w] = math.cos(math.pi*(w+0.5)*(i+1-half_fg)/3)
1167
+
1168
+ self.register_buffer('weight_rbr_prior', prior_tensor)
1169
+
1170
+ def weight_gen(self):
1171
+
1172
+ weight_rbr_origin = torch.einsum('oihw,o->oihw', self.weight_rbr_origin, self.vector[0, :])
1173
+
1174
+ weight_rbr_avg = torch.einsum('oihw,o->oihw', torch.einsum('oihw,hw->oihw', self.weight_rbr_avg_conv, self.weight_rbr_avg_avg), self.vector[1, :])
1175
+
1176
+ weight_rbr_pfir = torch.einsum('oihw,o->oihw', torch.einsum('oihw,ohw->oihw', self.weight_rbr_pfir_conv, self.weight_rbr_prior), self.vector[2, :])
1177
+
1178
+ weight_rbr_1x1_kxk_conv1 = None
1179
+ if hasattr(self, 'weight_rbr_1x1_kxk_idconv1'):
1180
+ weight_rbr_1x1_kxk_conv1 = (self.weight_rbr_1x1_kxk_idconv1 + self.id_tensor).squeeze()
1181
+ elif hasattr(self, 'weight_rbr_1x1_kxk_conv1'):
1182
+ weight_rbr_1x1_kxk_conv1 = self.weight_rbr_1x1_kxk_conv1.squeeze()
1183
+ else:
1184
+ raise NotImplementedError
1185
+ weight_rbr_1x1_kxk_conv2 = self.weight_rbr_1x1_kxk_conv2
1186
+
1187
+ if self.groups > 1:
1188
+ g = self.groups
1189
+ t, ig = weight_rbr_1x1_kxk_conv1.size()
1190
+ o, tg, h, w = weight_rbr_1x1_kxk_conv2.size()
1191
+ weight_rbr_1x1_kxk_conv1 = weight_rbr_1x1_kxk_conv1.view(g, int(t/g), ig)
1192
+ weight_rbr_1x1_kxk_conv2 = weight_rbr_1x1_kxk_conv2.view(g, int(o/g), tg, h, w)
1193
+ weight_rbr_1x1_kxk = torch.einsum('gti,gothw->goihw', weight_rbr_1x1_kxk_conv1, weight_rbr_1x1_kxk_conv2).view(o, ig, h, w)
1194
+ else:
1195
+ weight_rbr_1x1_kxk = torch.einsum('ti,othw->oihw', weight_rbr_1x1_kxk_conv1, weight_rbr_1x1_kxk_conv2)
1196
+
1197
+ weight_rbr_1x1_kxk = torch.einsum('oihw,o->oihw', weight_rbr_1x1_kxk, self.vector[3, :])
1198
+
1199
+ weight_rbr_gconv = self.dwsc2full(self.weight_rbr_gconv_dw, self.weight_rbr_gconv_pw, self.in_channels)
1200
+ weight_rbr_gconv = torch.einsum('oihw,o->oihw', weight_rbr_gconv, self.vector[4, :])
1201
+
1202
+ weight = weight_rbr_origin + weight_rbr_avg + weight_rbr_1x1_kxk + weight_rbr_pfir + weight_rbr_gconv
1203
+
1204
+ return weight
1205
+
1206
+ def dwsc2full(self, weight_dw, weight_pw, groups):
1207
+
1208
+ t, ig, h, w = weight_dw.size()
1209
+ o, _, _, _ = weight_pw.size()
1210
+ tg = int(t/groups)
1211
+ i = int(ig*groups)
1212
+ weight_dw = weight_dw.view(groups, tg, ig, h, w)
1213
+ weight_pw = weight_pw.squeeze().view(o, groups, tg)
1214
+
1215
+ weight_dsc = torch.einsum('gtihw,ogt->ogihw', weight_dw, weight_pw)
1216
+ return weight_dsc.view(o, i, h, w)
1217
+
1218
+ def forward(self, inputs):
1219
+ weight = self.weight_gen()
1220
+ out = F.conv2d(inputs, weight, bias=None, stride=self.stride, padding=self.padding, dilation=self.dilation, groups=self.groups)
1221
+
1222
+ return self.nonlinear(self.bn(out))
1223
+
1224
+ class RepConv_OREPA(nn.Module):
1225
+
1226
+ def __init__(self, c1, c2, k=3, s=1, padding=1, dilation=1, groups=1, padding_mode='zeros', deploy=False, use_se=False, nonlinear=nn.SiLU()):
1227
+ super(RepConv_OREPA, self).__init__()
1228
+ self.deploy = deploy
1229
+ self.groups = groups
1230
+ self.in_channels = c1
1231
+ self.out_channels = c2
1232
+
1233
+ self.padding = padding
1234
+ self.dilation = dilation
1235
+ self.groups = groups
1236
+
1237
+ assert k == 3
1238
+ assert padding == 1
1239
+
1240
+ padding_11 = padding - k // 2
1241
+
1242
+ if nonlinear is None:
1243
+ self.nonlinearity = nn.Identity()
1244
+ else:
1245
+ self.nonlinearity = nonlinear
1246
+
1247
+ if use_se:
1248
+ self.se = SEBlock(self.out_channels, internal_neurons=self.out_channels // 16)
1249
+ else:
1250
+ self.se = nn.Identity()
1251
+
1252
+ if deploy:
1253
+ self.rbr_reparam = nn.Conv2d(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=k, stride=s,
1254
+ padding=padding, dilation=dilation, groups=groups, bias=True, padding_mode=padding_mode)
1255
+
1256
+ else:
1257
+ self.rbr_identity = nn.BatchNorm2d(num_features=self.in_channels) if self.out_channels == self.in_channels and s == 1 else None
1258
+ self.rbr_dense = OREPA_3x3_RepConv(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=k, stride=s, padding=padding, groups=groups, dilation=1)
1259
+ self.rbr_1x1 = ConvBN(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=1, stride=s, padding=padding_11, groups=groups, dilation=1)
1260
+ print('RepVGG Block, identity = ', self.rbr_identity)
1261
+
1262
+
1263
+ def forward(self, inputs):
1264
+ if hasattr(self, 'rbr_reparam'):
1265
+ return self.nonlinearity(self.se(self.rbr_reparam(inputs)))
1266
+
1267
+ if self.rbr_identity is None:
1268
+ id_out = 0
1269
+ else:
1270
+ id_out = self.rbr_identity(inputs)
1271
+
1272
+ out1 = self.rbr_dense(inputs)
1273
+ out2 = self.rbr_1x1(inputs)
1274
+ out3 = id_out
1275
+ out = out1 + out2 + out3
1276
+
1277
+ return self.nonlinearity(self.se(out))
1278
+
1279
+
1280
+ # Optional. This improves the accuracy and facilitates quantization.
1281
+ # 1. Cancel the original weight decay on rbr_dense.conv.weight and rbr_1x1.conv.weight.
1282
+ # 2. Use like this.
1283
+ # loss = criterion(....)
1284
+ # for every RepVGGBlock blk:
1285
+ # loss += weight_decay_coefficient * 0.5 * blk.get_cust_L2()
1286
+ # optimizer.zero_grad()
1287
+ # loss.backward()
1288
+
1289
+ # Not used for OREPA
1290
+ def get_custom_L2(self):
1291
+ K3 = self.rbr_dense.weight_gen()
1292
+ K1 = self.rbr_1x1.conv.weight
1293
+ t3 = (self.rbr_dense.bn.weight / ((self.rbr_dense.bn.running_var + self.rbr_dense.bn.eps).sqrt())).reshape(-1, 1, 1, 1).detach()
1294
+ t1 = (self.rbr_1x1.bn.weight / ((self.rbr_1x1.bn.running_var + self.rbr_1x1.bn.eps).sqrt())).reshape(-1, 1, 1, 1).detach()
1295
+
1296
+ l2_loss_circle = (K3 ** 2).sum() - (K3[:, :, 1:2, 1:2] ** 2).sum() # The L2 loss of the "circle" of weights in 3x3 kernel. Use regular L2 on them.
1297
+ eq_kernel = K3[:, :, 1:2, 1:2] * t3 + K1 * t1 # The equivalent resultant central point of 3x3 kernel.
1298
+ l2_loss_eq_kernel = (eq_kernel ** 2 / (t3 ** 2 + t1 ** 2)).sum() # Normalize for an L2 coefficient comparable to regular L2.
1299
+ return l2_loss_eq_kernel + l2_loss_circle
1300
+
1301
+ def get_equivalent_kernel_bias(self):
1302
+ kernel3x3, bias3x3 = self._fuse_bn_tensor(self.rbr_dense)
1303
+ kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)
1304
+ kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)
1305
+ return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid
1306
+
1307
+ def _pad_1x1_to_3x3_tensor(self, kernel1x1):
1308
+ if kernel1x1 is None:
1309
+ return 0
1310
+ else:
1311
+ return torch.nn.functional.pad(kernel1x1, [1,1,1,1])
1312
+
1313
+ def _fuse_bn_tensor(self, branch):
1314
+ if branch is None:
1315
+ return 0, 0
1316
+ if not isinstance(branch, nn.BatchNorm2d):
1317
+ if isinstance(branch, OREPA_3x3_RepConv):
1318
+ kernel = branch.weight_gen()
1319
+ elif isinstance(branch, ConvBN):
1320
+ kernel = branch.conv.weight
1321
+ else:
1322
+ raise NotImplementedError
1323
+ running_mean = branch.bn.running_mean
1324
+ running_var = branch.bn.running_var
1325
+ gamma = branch.bn.weight
1326
+ beta = branch.bn.bias
1327
+ eps = branch.bn.eps
1328
+ else:
1329
+ if not hasattr(self, 'id_tensor'):
1330
+ input_dim = self.in_channels // self.groups
1331
+ kernel_value = np.zeros((self.in_channels, input_dim, 3, 3), dtype=np.float32)
1332
+ for i in range(self.in_channels):
1333
+ kernel_value[i, i % input_dim, 1, 1] = 1
1334
+ self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
1335
+ kernel = self.id_tensor
1336
+ running_mean = branch.running_mean
1337
+ running_var = branch.running_var
1338
+ gamma = branch.weight
1339
+ beta = branch.bias
1340
+ eps = branch.eps
1341
+ std = (running_var + eps).sqrt()
1342
+ t = (gamma / std).reshape(-1, 1, 1, 1)
1343
+ return kernel * t, beta - running_mean * gamma / std
1344
+
1345
+ def switch_to_deploy(self):
1346
+ if hasattr(self, 'rbr_reparam'):
1347
+ return
1348
+ print(f"RepConv_OREPA.switch_to_deploy")
1349
+ kernel, bias = self.get_equivalent_kernel_bias()
1350
+ self.rbr_reparam = nn.Conv2d(in_channels=self.rbr_dense.in_channels, out_channels=self.rbr_dense.out_channels,
1351
+ kernel_size=self.rbr_dense.kernel_size, stride=self.rbr_dense.stride,
1352
+ padding=self.rbr_dense.padding, dilation=self.rbr_dense.dilation, groups=self.rbr_dense.groups, bias=True)
1353
+ self.rbr_reparam.weight.data = kernel
1354
+ self.rbr_reparam.bias.data = bias
1355
+ for para in self.parameters():
1356
+ para.detach_()
1357
+ self.__delattr__('rbr_dense')
1358
+ self.__delattr__('rbr_1x1')
1359
+ if hasattr(self, 'rbr_identity'):
1360
+ self.__delattr__('rbr_identity')
1361
+
1362
+ ##### end of orepa #####
1363
+
1364
+
1365
+ ##### swin transformer #####
1366
+
1367
+ class WindowAttention(nn.Module):
1368
+
1369
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
1370
+
1371
+ super().__init__()
1372
+ self.dim = dim
1373
+ self.window_size = window_size # Wh, Ww
1374
+ self.num_heads = num_heads
1375
+ head_dim = dim // num_heads
1376
+ self.scale = qk_scale or head_dim ** -0.5
1377
+
1378
+ # define a parameter table of relative position bias
1379
+ self.relative_position_bias_table = nn.Parameter(
1380
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
1381
+
1382
+ # get pair-wise relative position index for each token inside the window
1383
+ coords_h = torch.arange(self.window_size[0])
1384
+ coords_w = torch.arange(self.window_size[1])
1385
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
1386
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
1387
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
1388
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
1389
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
1390
+ relative_coords[:, :, 1] += self.window_size[1] - 1
1391
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
1392
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
1393
+ self.register_buffer("relative_position_index", relative_position_index)
1394
+
1395
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
1396
+ self.attn_drop = nn.Dropout(attn_drop)
1397
+ self.proj = nn.Linear(dim, dim)
1398
+ self.proj_drop = nn.Dropout(proj_drop)
1399
+
1400
+ nn.init.normal_(self.relative_position_bias_table, std=.02)
1401
+ self.softmax = nn.Softmax(dim=-1)
1402
+
1403
+ def forward(self, x, mask=None):
1404
+
1405
+ B_, N, C = x.shape
1406
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
1407
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
1408
+
1409
+ q = q * self.scale
1410
+ attn = (q @ k.transpose(-2, -1))
1411
+
1412
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
1413
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
1414
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
1415
+ attn = attn + relative_position_bias.unsqueeze(0)
1416
+
1417
+ if mask is not None:
1418
+ nW = mask.shape[0]
1419
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
1420
+ attn = attn.view(-1, self.num_heads, N, N)
1421
+ attn = self.softmax(attn)
1422
+ else:
1423
+ attn = self.softmax(attn)
1424
+
1425
+ attn = self.attn_drop(attn)
1426
+
1427
+ # print(attn.dtype, v.dtype)
1428
+ try:
1429
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
1430
+ except:
1431
+ #print(attn.dtype, v.dtype)
1432
+ x = (attn.half() @ v).transpose(1, 2).reshape(B_, N, C)
1433
+ x = self.proj(x)
1434
+ x = self.proj_drop(x)
1435
+ return x
1436
+
1437
+ class Mlp(nn.Module):
1438
+
1439
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.):
1440
+ super().__init__()
1441
+ out_features = out_features or in_features
1442
+ hidden_features = hidden_features or in_features
1443
+ self.fc1 = nn.Linear(in_features, hidden_features)
1444
+ self.act = act_layer()
1445
+ self.fc2 = nn.Linear(hidden_features, out_features)
1446
+ self.drop = nn.Dropout(drop)
1447
+
1448
+ def forward(self, x):
1449
+ x = self.fc1(x)
1450
+ x = self.act(x)
1451
+ x = self.drop(x)
1452
+ x = self.fc2(x)
1453
+ x = self.drop(x)
1454
+ return x
1455
+
1456
+ def window_partition(x, window_size):
1457
+
1458
+ B, H, W, C = x.shape
1459
+ assert H % window_size == 0, 'feature map h and w can not divide by window size'
1460
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
1461
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
1462
+ return windows
1463
+
1464
+ def window_reverse(windows, window_size, H, W):
1465
+
1466
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
1467
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
1468
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
1469
+ return x
1470
+
1471
+
1472
+ class SwinTransformerLayer(nn.Module):
1473
+
1474
+ def __init__(self, dim, num_heads, window_size=8, shift_size=0,
1475
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
1476
+ act_layer=nn.SiLU, norm_layer=nn.LayerNorm):
1477
+ super().__init__()
1478
+ self.dim = dim
1479
+ self.num_heads = num_heads
1480
+ self.window_size = window_size
1481
+ self.shift_size = shift_size
1482
+ self.mlp_ratio = mlp_ratio
1483
+ # if min(self.input_resolution) <= self.window_size:
1484
+ # # if window size is larger than input resolution, we don't partition windows
1485
+ # self.shift_size = 0
1486
+ # self.window_size = min(self.input_resolution)
1487
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
1488
+
1489
+ self.norm1 = norm_layer(dim)
1490
+ self.attn = WindowAttention(
1491
+ dim, window_size=(self.window_size, self.window_size), num_heads=num_heads,
1492
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
1493
+
1494
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
1495
+ self.norm2 = norm_layer(dim)
1496
+ mlp_hidden_dim = int(dim * mlp_ratio)
1497
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
1498
+
1499
+ def create_mask(self, H, W):
1500
+ # calculate attention mask for SW-MSA
1501
+ img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
1502
+ h_slices = (slice(0, -self.window_size),
1503
+ slice(-self.window_size, -self.shift_size),
1504
+ slice(-self.shift_size, None))
1505
+ w_slices = (slice(0, -self.window_size),
1506
+ slice(-self.window_size, -self.shift_size),
1507
+ slice(-self.shift_size, None))
1508
+ cnt = 0
1509
+ for h in h_slices:
1510
+ for w in w_slices:
1511
+ img_mask[:, h, w, :] = cnt
1512
+ cnt += 1
1513
+
1514
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
1515
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
1516
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
1517
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
1518
+
1519
+ return attn_mask
1520
+
1521
+ def forward(self, x):
1522
+ # reshape x[b c h w] to x[b l c]
1523
+ _, _, H_, W_ = x.shape
1524
+
1525
+ Padding = False
1526
+ if min(H_, W_) < self.window_size or H_ % self.window_size!=0 or W_ % self.window_size!=0:
1527
+ Padding = True
1528
+ # print(f'img_size {min(H_, W_)} is less than (or not divided by) window_size {self.window_size}, Padding.')
1529
+ pad_r = (self.window_size - W_ % self.window_size) % self.window_size
1530
+ pad_b = (self.window_size - H_ % self.window_size) % self.window_size
1531
+ x = F.pad(x, (0, pad_r, 0, pad_b))
1532
+
1533
+ # print('2', x.shape)
1534
+ B, C, H, W = x.shape
1535
+ L = H * W
1536
+ x = x.permute(0, 2, 3, 1).contiguous().view(B, L, C) # b, L, c
1537
+
1538
+ # create mask from init to forward
1539
+ if self.shift_size > 0:
1540
+ attn_mask = self.create_mask(H, W).to(x.device)
1541
+ else:
1542
+ attn_mask = None
1543
+
1544
+ shortcut = x
1545
+ x = self.norm1(x)
1546
+ x = x.view(B, H, W, C)
1547
+
1548
+ # cyclic shift
1549
+ if self.shift_size > 0:
1550
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
1551
+ else:
1552
+ shifted_x = x
1553
+
1554
+ # partition windows
1555
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
1556
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
1557
+
1558
+ # W-MSA/SW-MSA
1559
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
1560
+
1561
+ # merge windows
1562
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
1563
+ shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C
1564
+
1565
+ # reverse cyclic shift
1566
+ if self.shift_size > 0:
1567
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
1568
+ else:
1569
+ x = shifted_x
1570
+ x = x.view(B, H * W, C)
1571
+
1572
+ # FFN
1573
+ x = shortcut + self.drop_path(x)
1574
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
1575
+
1576
+ x = x.permute(0, 2, 1).contiguous().view(-1, C, H, W) # b c h w
1577
+
1578
+ if Padding:
1579
+ x = x[:, :, :H_, :W_] # reverse padding
1580
+
1581
+ return x
1582
+
1583
+
1584
+ class SwinTransformerBlock(nn.Module):
1585
+ def __init__(self, c1, c2, num_heads, num_layers, window_size=8):
1586
+ super().__init__()
1587
+ self.conv = None
1588
+ if c1 != c2:
1589
+ self.conv = Conv(c1, c2)
1590
+
1591
+ # remove input_resolution
1592
+ self.blocks = nn.Sequential(*[SwinTransformerLayer(dim=c2, num_heads=num_heads, window_size=window_size,
1593
+ shift_size=0 if (i % 2 == 0) else window_size // 2) for i in range(num_layers)])
1594
+
1595
+ def forward(self, x):
1596
+ if self.conv is not None:
1597
+ x = self.conv(x)
1598
+ x = self.blocks(x)
1599
+ return x
1600
+
1601
+
1602
+ class STCSPA(nn.Module):
1603
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
1604
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
1605
+ super(STCSPA, self).__init__()
1606
+ c_ = int(c2 * e) # hidden channels
1607
+ self.cv1 = Conv(c1, c_, 1, 1)
1608
+ self.cv2 = Conv(c1, c_, 1, 1)
1609
+ self.cv3 = Conv(2 * c_, c2, 1, 1)
1610
+ num_heads = c_ // 32
1611
+ self.m = SwinTransformerBlock(c_, c_, num_heads, n)
1612
+ #self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
1613
+
1614
+ def forward(self, x):
1615
+ y1 = self.m(self.cv1(x))
1616
+ y2 = self.cv2(x)
1617
+ return self.cv3(torch.cat((y1, y2), dim=1))
1618
+
1619
+
1620
+ class STCSPB(nn.Module):
1621
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
1622
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
1623
+ super(STCSPB, self).__init__()
1624
+ c_ = int(c2) # hidden channels
1625
+ self.cv1 = Conv(c1, c_, 1, 1)
1626
+ self.cv2 = Conv(c_, c_, 1, 1)
1627
+ self.cv3 = Conv(2 * c_, c2, 1, 1)
1628
+ num_heads = c_ // 32
1629
+ self.m = SwinTransformerBlock(c_, c_, num_heads, n)
1630
+ #self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
1631
+
1632
+ def forward(self, x):
1633
+ x1 = self.cv1(x)
1634
+ y1 = self.m(x1)
1635
+ y2 = self.cv2(x1)
1636
+ return self.cv3(torch.cat((y1, y2), dim=1))
1637
+
1638
+
1639
+ class STCSPC(nn.Module):
1640
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
1641
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
1642
+ super(STCSPC, self).__init__()
1643
+ c_ = int(c2 * e) # hidden channels
1644
+ self.cv1 = Conv(c1, c_, 1, 1)
1645
+ self.cv2 = Conv(c1, c_, 1, 1)
1646
+ self.cv3 = Conv(c_, c_, 1, 1)
1647
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
1648
+ num_heads = c_ // 32
1649
+ self.m = SwinTransformerBlock(c_, c_, num_heads, n)
1650
+ #self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
1651
+
1652
+ def forward(self, x):
1653
+ y1 = self.cv3(self.m(self.cv1(x)))
1654
+ y2 = self.cv2(x)
1655
+ return self.cv4(torch.cat((y1, y2), dim=1))
1656
+
1657
+ ##### end of swin transformer #####
1658
+
1659
+
1660
+ ##### swin transformer v2 #####
1661
+
1662
+ class WindowAttention_v2(nn.Module):
1663
+
1664
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, attn_drop=0., proj_drop=0.,
1665
+ pretrained_window_size=[0, 0]):
1666
+
1667
+ super().__init__()
1668
+ self.dim = dim
1669
+ self.window_size = window_size # Wh, Ww
1670
+ self.pretrained_window_size = pretrained_window_size
1671
+ self.num_heads = num_heads
1672
+
1673
+ self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))), requires_grad=True)
1674
+
1675
+ # mlp to generate continuous relative position bias
1676
+ self.cpb_mlp = nn.Sequential(nn.Linear(2, 512, bias=True),
1677
+ nn.ReLU(inplace=True),
1678
+ nn.Linear(512, num_heads, bias=False))
1679
+
1680
+ # get relative_coords_table
1681
+ relative_coords_h = torch.arange(-(self.window_size[0] - 1), self.window_size[0], dtype=torch.float32)
1682
+ relative_coords_w = torch.arange(-(self.window_size[1] - 1), self.window_size[1], dtype=torch.float32)
1683
+ relative_coords_table = torch.stack(
1684
+ torch.meshgrid([relative_coords_h,
1685
+ relative_coords_w])).permute(1, 2, 0).contiguous().unsqueeze(0) # 1, 2*Wh-1, 2*Ww-1, 2
1686
+ if pretrained_window_size[0] > 0:
1687
+ relative_coords_table[:, :, :, 0] /= (pretrained_window_size[0] - 1)
1688
+ relative_coords_table[:, :, :, 1] /= (pretrained_window_size[1] - 1)
1689
+ else:
1690
+ relative_coords_table[:, :, :, 0] /= (self.window_size[0] - 1)
1691
+ relative_coords_table[:, :, :, 1] /= (self.window_size[1] - 1)
1692
+ relative_coords_table *= 8 # normalize to -8, 8
1693
+ relative_coords_table = torch.sign(relative_coords_table) * torch.log2(
1694
+ torch.abs(relative_coords_table) + 1.0) / np.log2(8)
1695
+
1696
+ self.register_buffer("relative_coords_table", relative_coords_table)
1697
+
1698
+ # get pair-wise relative position index for each token inside the window
1699
+ coords_h = torch.arange(self.window_size[0])
1700
+ coords_w = torch.arange(self.window_size[1])
1701
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
1702
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
1703
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
1704
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
1705
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
1706
+ relative_coords[:, :, 1] += self.window_size[1] - 1
1707
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
1708
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
1709
+ self.register_buffer("relative_position_index", relative_position_index)
1710
+
1711
+ self.qkv = nn.Linear(dim, dim * 3, bias=False)
1712
+ if qkv_bias:
1713
+ self.q_bias = nn.Parameter(torch.zeros(dim))
1714
+ self.v_bias = nn.Parameter(torch.zeros(dim))
1715
+ else:
1716
+ self.q_bias = None
1717
+ self.v_bias = None
1718
+ self.attn_drop = nn.Dropout(attn_drop)
1719
+ self.proj = nn.Linear(dim, dim)
1720
+ self.proj_drop = nn.Dropout(proj_drop)
1721
+ self.softmax = nn.Softmax(dim=-1)
1722
+
1723
+ def forward(self, x, mask=None):
1724
+
1725
+ B_, N, C = x.shape
1726
+ qkv_bias = None
1727
+ if self.q_bias is not None:
1728
+ qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
1729
+ qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
1730
+ qkv = qkv.reshape(B_, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
1731
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
1732
+
1733
+ # cosine attention
1734
+ attn = (F.normalize(q, dim=-1) @ F.normalize(k, dim=-1).transpose(-2, -1))
1735
+ logit_scale = torch.clamp(self.logit_scale, max=torch.log(torch.tensor(1. / 0.01))).exp()
1736
+ attn = attn * logit_scale
1737
+
1738
+ relative_position_bias_table = self.cpb_mlp(self.relative_coords_table).view(-1, self.num_heads)
1739
+ relative_position_bias = relative_position_bias_table[self.relative_position_index.view(-1)].view(
1740
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
1741
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
1742
+ relative_position_bias = 16 * torch.sigmoid(relative_position_bias)
1743
+ attn = attn + relative_position_bias.unsqueeze(0)
1744
+
1745
+ if mask is not None:
1746
+ nW = mask.shape[0]
1747
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
1748
+ attn = attn.view(-1, self.num_heads, N, N)
1749
+ attn = self.softmax(attn)
1750
+ else:
1751
+ attn = self.softmax(attn)
1752
+
1753
+ attn = self.attn_drop(attn)
1754
+
1755
+ try:
1756
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
1757
+ except:
1758
+ x = (attn.half() @ v).transpose(1, 2).reshape(B_, N, C)
1759
+
1760
+ x = self.proj(x)
1761
+ x = self.proj_drop(x)
1762
+ return x
1763
+
1764
+ def extra_repr(self) -> str:
1765
+ return f'dim={self.dim}, window_size={self.window_size}, ' \
1766
+ f'pretrained_window_size={self.pretrained_window_size}, num_heads={self.num_heads}'
1767
+
1768
+ def flops(self, N):
1769
+ # calculate flops for 1 window with token length of N
1770
+ flops = 0
1771
+ # qkv = self.qkv(x)
1772
+ flops += N * self.dim * 3 * self.dim
1773
+ # attn = (q @ k.transpose(-2, -1))
1774
+ flops += self.num_heads * N * (self.dim // self.num_heads) * N
1775
+ # x = (attn @ v)
1776
+ flops += self.num_heads * N * N * (self.dim // self.num_heads)
1777
+ # x = self.proj(x)
1778
+ flops += N * self.dim * self.dim
1779
+ return flops
1780
+
1781
+ class Mlp_v2(nn.Module):
1782
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.):
1783
+ super().__init__()
1784
+ out_features = out_features or in_features
1785
+ hidden_features = hidden_features or in_features
1786
+ self.fc1 = nn.Linear(in_features, hidden_features)
1787
+ self.act = act_layer()
1788
+ self.fc2 = nn.Linear(hidden_features, out_features)
1789
+ self.drop = nn.Dropout(drop)
1790
+
1791
+ def forward(self, x):
1792
+ x = self.fc1(x)
1793
+ x = self.act(x)
1794
+ x = self.drop(x)
1795
+ x = self.fc2(x)
1796
+ x = self.drop(x)
1797
+ return x
1798
+
1799
+
1800
+ def window_partition_v2(x, window_size):
1801
+
1802
+ B, H, W, C = x.shape
1803
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
1804
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
1805
+ return windows
1806
+
1807
+
1808
+ def window_reverse_v2(windows, window_size, H, W):
1809
+
1810
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
1811
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
1812
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
1813
+ return x
1814
+
1815
+
1816
+ class SwinTransformerLayer_v2(nn.Module):
1817
+
1818
+ def __init__(self, dim, num_heads, window_size=7, shift_size=0,
1819
+ mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0., drop_path=0.,
1820
+ act_layer=nn.SiLU, norm_layer=nn.LayerNorm, pretrained_window_size=0):
1821
+ super().__init__()
1822
+ self.dim = dim
1823
+ #self.input_resolution = input_resolution
1824
+ self.num_heads = num_heads
1825
+ self.window_size = window_size
1826
+ self.shift_size = shift_size
1827
+ self.mlp_ratio = mlp_ratio
1828
+ #if min(self.input_resolution) <= self.window_size:
1829
+ # # if window size is larger than input resolution, we don't partition windows
1830
+ # self.shift_size = 0
1831
+ # self.window_size = min(self.input_resolution)
1832
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
1833
+
1834
+ self.norm1 = norm_layer(dim)
1835
+ self.attn = WindowAttention_v2(
1836
+ dim, window_size=(self.window_size, self.window_size), num_heads=num_heads,
1837
+ qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop,
1838
+ pretrained_window_size=(pretrained_window_size, pretrained_window_size))
1839
+
1840
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
1841
+ self.norm2 = norm_layer(dim)
1842
+ mlp_hidden_dim = int(dim * mlp_ratio)
1843
+ self.mlp = Mlp_v2(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
1844
+
1845
+ def create_mask(self, H, W):
1846
+ # calculate attention mask for SW-MSA
1847
+ img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
1848
+ h_slices = (slice(0, -self.window_size),
1849
+ slice(-self.window_size, -self.shift_size),
1850
+ slice(-self.shift_size, None))
1851
+ w_slices = (slice(0, -self.window_size),
1852
+ slice(-self.window_size, -self.shift_size),
1853
+ slice(-self.shift_size, None))
1854
+ cnt = 0
1855
+ for h in h_slices:
1856
+ for w in w_slices:
1857
+ img_mask[:, h, w, :] = cnt
1858
+ cnt += 1
1859
+
1860
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
1861
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
1862
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
1863
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
1864
+
1865
+ return attn_mask
1866
+
1867
+ def forward(self, x):
1868
+ # reshape x[b c h w] to x[b l c]
1869
+ _, _, H_, W_ = x.shape
1870
+
1871
+ Padding = False
1872
+ if min(H_, W_) < self.window_size or H_ % self.window_size!=0 or W_ % self.window_size!=0:
1873
+ Padding = True
1874
+ # print(f'img_size {min(H_, W_)} is less than (or not divided by) window_size {self.window_size}, Padding.')
1875
+ pad_r = (self.window_size - W_ % self.window_size) % self.window_size
1876
+ pad_b = (self.window_size - H_ % self.window_size) % self.window_size
1877
+ x = F.pad(x, (0, pad_r, 0, pad_b))
1878
+
1879
+ # print('2', x.shape)
1880
+ B, C, H, W = x.shape
1881
+ L = H * W
1882
+ x = x.permute(0, 2, 3, 1).contiguous().view(B, L, C) # b, L, c
1883
+
1884
+ # create mask from init to forward
1885
+ if self.shift_size > 0:
1886
+ attn_mask = self.create_mask(H, W).to(x.device)
1887
+ else:
1888
+ attn_mask = None
1889
+
1890
+ shortcut = x
1891
+ x = x.view(B, H, W, C)
1892
+
1893
+ # cyclic shift
1894
+ if self.shift_size > 0:
1895
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
1896
+ else:
1897
+ shifted_x = x
1898
+
1899
+ # partition windows
1900
+ x_windows = window_partition_v2(shifted_x, self.window_size) # nW*B, window_size, window_size, C
1901
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
1902
+
1903
+ # W-MSA/SW-MSA
1904
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
1905
+
1906
+ # merge windows
1907
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
1908
+ shifted_x = window_reverse_v2(attn_windows, self.window_size, H, W) # B H' W' C
1909
+
1910
+ # reverse cyclic shift
1911
+ if self.shift_size > 0:
1912
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
1913
+ else:
1914
+ x = shifted_x
1915
+ x = x.view(B, H * W, C)
1916
+ x = shortcut + self.drop_path(self.norm1(x))
1917
+
1918
+ # FFN
1919
+ x = x + self.drop_path(self.norm2(self.mlp(x)))
1920
+ x = x.permute(0, 2, 1).contiguous().view(-1, C, H, W) # b c h w
1921
+
1922
+ if Padding:
1923
+ x = x[:, :, :H_, :W_] # reverse padding
1924
+
1925
+ return x
1926
+
1927
+ def extra_repr(self) -> str:
1928
+ return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \
1929
+ f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"
1930
+
1931
+ def flops(self):
1932
+ flops = 0
1933
+ H, W = self.input_resolution
1934
+ # norm1
1935
+ flops += self.dim * H * W
1936
+ # W-MSA/SW-MSA
1937
+ nW = H * W / self.window_size / self.window_size
1938
+ flops += nW * self.attn.flops(self.window_size * self.window_size)
1939
+ # mlp
1940
+ flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
1941
+ # norm2
1942
+ flops += self.dim * H * W
1943
+ return flops
1944
+
1945
+
1946
+ class SwinTransformer2Block(nn.Module):
1947
+ def __init__(self, c1, c2, num_heads, num_layers, window_size=7):
1948
+ super().__init__()
1949
+ self.conv = None
1950
+ if c1 != c2:
1951
+ self.conv = Conv(c1, c2)
1952
+
1953
+ # remove input_resolution
1954
+ self.blocks = nn.Sequential(*[SwinTransformerLayer_v2(dim=c2, num_heads=num_heads, window_size=window_size,
1955
+ shift_size=0 if (i % 2 == 0) else window_size // 2) for i in range(num_layers)])
1956
+
1957
+ def forward(self, x):
1958
+ if self.conv is not None:
1959
+ x = self.conv(x)
1960
+ x = self.blocks(x)
1961
+ return x
1962
+
1963
+
1964
+ class ST2CSPA(nn.Module):
1965
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
1966
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
1967
+ super(ST2CSPA, self).__init__()
1968
+ c_ = int(c2 * e) # hidden channels
1969
+ self.cv1 = Conv(c1, c_, 1, 1)
1970
+ self.cv2 = Conv(c1, c_, 1, 1)
1971
+ self.cv3 = Conv(2 * c_, c2, 1, 1)
1972
+ num_heads = c_ // 32
1973
+ self.m = SwinTransformer2Block(c_, c_, num_heads, n)
1974
+ #self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
1975
+
1976
+ def forward(self, x):
1977
+ y1 = self.m(self.cv1(x))
1978
+ y2 = self.cv2(x)
1979
+ return self.cv3(torch.cat((y1, y2), dim=1))
1980
+
1981
+
1982
+ class ST2CSPB(nn.Module):
1983
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
1984
+ def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
1985
+ super(ST2CSPB, self).__init__()
1986
+ c_ = int(c2) # hidden channels
1987
+ self.cv1 = Conv(c1, c_, 1, 1)
1988
+ self.cv2 = Conv(c_, c_, 1, 1)
1989
+ self.cv3 = Conv(2 * c_, c2, 1, 1)
1990
+ num_heads = c_ // 32
1991
+ self.m = SwinTransformer2Block(c_, c_, num_heads, n)
1992
+ #self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
1993
+
1994
+ def forward(self, x):
1995
+ x1 = self.cv1(x)
1996
+ y1 = self.m(x1)
1997
+ y2 = self.cv2(x1)
1998
+ return self.cv3(torch.cat((y1, y2), dim=1))
1999
+
2000
+
2001
+ class ST2CSPC(nn.Module):
2002
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
2003
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
2004
+ super(ST2CSPC, self).__init__()
2005
+ c_ = int(c2 * e) # hidden channels
2006
+ self.cv1 = Conv(c1, c_, 1, 1)
2007
+ self.cv2 = Conv(c1, c_, 1, 1)
2008
+ self.cv3 = Conv(c_, c_, 1, 1)
2009
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
2010
+ num_heads = c_ // 32
2011
+ self.m = SwinTransformer2Block(c_, c_, num_heads, n)
2012
+ #self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
2013
+
2014
+ def forward(self, x):
2015
+ y1 = self.cv3(self.m(self.cv1(x)))
2016
+ y2 = self.cv2(x)
2017
+ return self.cv4(torch.cat((y1, y2), dim=1))
2018
+
2019
+ ##### end of swin transformer v2 #####
models/experimental.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn as nn
4
+
5
+ from models.common import Conv, DWConv
6
+ from utils.google_utils import attempt_download
7
+
8
+
9
+ class CrossConv(nn.Module):
10
+ # Cross Convolution Downsample
11
+ def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
12
+ # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
13
+ super(CrossConv, self).__init__()
14
+ c_ = int(c2 * e) # hidden channels
15
+ self.cv1 = Conv(c1, c_, (1, k), (1, s))
16
+ self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
17
+ self.add = shortcut and c1 == c2
18
+
19
+ def forward(self, x):
20
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
21
+
22
+
23
+ class Sum(nn.Module):
24
+ # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
25
+ def __init__(self, n, weight=False): # n: number of inputs
26
+ super(Sum, self).__init__()
27
+ self.weight = weight # apply weights boolean
28
+ self.iter = range(n - 1) # iter object
29
+ if weight:
30
+ self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
31
+
32
+ def forward(self, x):
33
+ y = x[0] # no weight
34
+ if self.weight:
35
+ w = torch.sigmoid(self.w) * 2
36
+ for i in self.iter:
37
+ y = y + x[i + 1] * w[i]
38
+ else:
39
+ for i in self.iter:
40
+ y = y + x[i + 1]
41
+ return y
42
+
43
+
44
+ class MixConv2d(nn.Module):
45
+ # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595
46
+ def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
47
+ super(MixConv2d, self).__init__()
48
+ groups = len(k)
49
+ if equal_ch: # equal c_ per group
50
+ i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
51
+ c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
52
+ else: # equal weight.numel() per group
53
+ b = [c2] + [0] * groups
54
+ a = np.eye(groups + 1, groups, k=-1)
55
+ a -= np.roll(a, 1, axis=1)
56
+ a *= np.array(k) ** 2
57
+ a[0] = 1
58
+ c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
59
+
60
+ self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
61
+ self.bn = nn.BatchNorm2d(c2)
62
+ self.act = nn.LeakyReLU(0.1, inplace=True)
63
+
64
+ def forward(self, x):
65
+ return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
66
+
67
+
68
+ class Ensemble(nn.ModuleList):
69
+ # Ensemble of models
70
+ def __init__(self):
71
+ super(Ensemble, self).__init__()
72
+
73
+ def forward(self, x, augment=False):
74
+ y = []
75
+ for module in self:
76
+ y.append(module(x, augment)[0])
77
+ # y = torch.stack(y).max(0)[0] # max ensemble
78
+ # y = torch.stack(y).mean(0) # mean ensemble
79
+ y = torch.cat(y, 1) # nms ensemble
80
+ return y, None # inference, train output
81
+
82
+
83
+ def attempt_load(weights, map_location=None):
84
+ # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
85
+ model = Ensemble()
86
+ for w in weights if isinstance(weights, list) else [weights]:
87
+ # attempt_download(w)
88
+ ckpt = torch.load(w, map_location=map_location) # load
89
+ model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
90
+
91
+ # Compatibility updates
92
+ for m in model.modules():
93
+ if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
94
+ m.inplace = True # pytorch 1.7.0 compatibility
95
+ elif type(m) is nn.Upsample:
96
+ m.recompute_scale_factor = None # torch 1.11.0 compatibility
97
+ elif type(m) is Conv:
98
+ m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
99
+
100
+ if len(model) == 1:
101
+ return model[-1] # return model
102
+ else:
103
+ print('Ensemble created with %s\n' % weights)
104
+ for k in ['names', 'stride']:
105
+ setattr(model, k, getattr(model[-1], k))
106
+ return model # return ensemble
models/yolo.py ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import sys
4
+ from copy import deepcopy
5
+
6
+ sys.path.append("./") # to run '$ python *.py' files in subdirectories
7
+ logger = logging.getLogger(__name__)
8
+
9
+ from models.common import *
10
+ from models.experimental import *
11
+ from utils.autoanchor import check_anchor_order
12
+ from utils.general import make_divisible, check_file, set_logging
13
+ from utils.torch_utils import (
14
+ time_synchronized,
15
+ fuse_conv_and_bn,
16
+ model_info,
17
+ scale_img,
18
+ initialize_weights,
19
+ select_device,
20
+ copy_attr,
21
+ )
22
+ from utils.loss import SigmoidBin
23
+
24
+ try:
25
+ import thop # for FLOPS computation
26
+ except ImportError:
27
+ thop = None
28
+
29
+
30
+ class Detect(nn.Module):
31
+ stride = None # strides computed during build
32
+ export = False # onnx export
33
+
34
+ def __init__(self, nc=80, anchors=(), ch=()): # detection layer
35
+ super(Detect, self).__init__()
36
+ self.nc = nc # number of classes
37
+ self.no = nc + 5 # number of outputs per anchor
38
+ self.nl = len(anchors) # number of detection layers
39
+ self.na = len(anchors[0]) // 2 # number of anchors
40
+ self.grid = [torch.zeros(1)] * self.nl # init grid
41
+ a = torch.tensor(anchors).float().view(self.nl, -1, 2)
42
+ self.register_buffer("anchors", a) # shape(nl,na,2)
43
+ self.register_buffer(
44
+ "anchor_grid", a.clone().view(self.nl, 1, -1, 1, 1, 2)
45
+ ) # shape(nl,1,na,1,1,2)
46
+ self.m = nn.ModuleList(
47
+ nn.Conv2d(x, self.no * self.na, 1) for x in ch
48
+ ) # output conv
49
+
50
+ def forward(self, x):
51
+ # x = x.copy() # for profiling
52
+ z = [] # inference output
53
+ self.training |= self.export
54
+ for i in range(self.nl):
55
+ x[i] = self.m[i](x[i]) # conv
56
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
57
+ x[i] = (
58
+ x[i]
59
+ .view(bs, self.na, self.no, ny, nx)
60
+ .permute(0, 1, 3, 4, 2)
61
+ .contiguous()
62
+ )
63
+
64
+ if not self.training: # inference
65
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
66
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
67
+
68
+ y = x[i].sigmoid()
69
+ y[..., 0:2] = (y[..., 0:2] * 2.0 - 0.5 + self.grid[i]) * self.stride[
70
+ i
71
+ ] # xy
72
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
73
+ z.append(y.view(bs, -1, self.no))
74
+
75
+ return x if self.training else (torch.cat(z, 1), x)
76
+
77
+ @staticmethod
78
+ def _make_grid(nx=20, ny=20):
79
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
80
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
81
+
82
+
83
+ class IDetect(nn.Module):
84
+ stride = None # strides computed during build
85
+ export = False # onnx export
86
+
87
+ def __init__(self, nc=80, anchors=(), ch=()): # detection layer
88
+ super(IDetect, self).__init__()
89
+ self.nc = nc # number of classes
90
+ self.no = nc + 5 # number of outputs per anchor
91
+ self.nl = len(anchors) # number of detection layers
92
+ self.na = len(anchors[0]) // 2 # number of anchors
93
+ self.grid = [torch.zeros(1)] * self.nl # init grid
94
+ a = torch.tensor(anchors).float().view(self.nl, -1, 2)
95
+ self.register_buffer("anchors", a) # shape(nl,na,2)
96
+ self.register_buffer(
97
+ "anchor_grid", a.clone().view(self.nl, 1, -1, 1, 1, 2)
98
+ ) # shape(nl,1,na,1,1,2)
99
+ self.m = nn.ModuleList(
100
+ nn.Conv2d(x, self.no * self.na, 1) for x in ch
101
+ ) # output conv
102
+
103
+ self.ia = nn.ModuleList(ImplicitA(x) for x in ch)
104
+ self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch)
105
+
106
+ def forward(self, x):
107
+ # x = x.copy() # for profiling
108
+ z = [] # inference output
109
+ self.training |= self.export
110
+ for i in range(self.nl):
111
+ x[i] = self.m[i](self.ia[i](x[i])) # conv
112
+ x[i] = self.im[i](x[i])
113
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
114
+ x[i] = (
115
+ x[i]
116
+ .view(bs, self.na, self.no, ny, nx)
117
+ .permute(0, 1, 3, 4, 2)
118
+ .contiguous()
119
+ )
120
+
121
+ if not self.training: # inference
122
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
123
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
124
+
125
+ y = x[i].sigmoid()
126
+ y[..., 0:2] = (y[..., 0:2] * 2.0 - 0.5 + self.grid[i]) * self.stride[
127
+ i
128
+ ] # xy
129
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
130
+ z.append(y.view(bs, -1, self.no))
131
+
132
+ return x if self.training else (torch.cat(z, 1), x)
133
+
134
+ @staticmethod
135
+ def _make_grid(nx=20, ny=20):
136
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
137
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
138
+
139
+
140
+ class IAuxDetect(nn.Module):
141
+ stride = None # strides computed during build
142
+ export = False # onnx export
143
+
144
+ def __init__(self, nc=80, anchors=(), ch=()): # detection layer
145
+ super(IAuxDetect, self).__init__()
146
+ self.nc = nc # number of classes
147
+ self.no = nc + 5 # number of outputs per anchor
148
+ self.nl = len(anchors) # number of detection layers
149
+ self.na = len(anchors[0]) // 2 # number of anchors
150
+ self.grid = [torch.zeros(1)] * self.nl # init grid
151
+ a = torch.tensor(anchors).float().view(self.nl, -1, 2)
152
+ self.register_buffer("anchors", a) # shape(nl,na,2)
153
+ self.register_buffer(
154
+ "anchor_grid", a.clone().view(self.nl, 1, -1, 1, 1, 2)
155
+ ) # shape(nl,1,na,1,1,2)
156
+ self.m = nn.ModuleList(
157
+ nn.Conv2d(x, self.no * self.na, 1) for x in ch[: self.nl]
158
+ ) # output conv
159
+ self.m2 = nn.ModuleList(
160
+ nn.Conv2d(x, self.no * self.na, 1) for x in ch[self.nl :]
161
+ ) # output conv
162
+
163
+ self.ia = nn.ModuleList(ImplicitA(x) for x in ch[: self.nl])
164
+ self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch[: self.nl])
165
+
166
+ def forward(self, x):
167
+ # x = x.copy() # for profiling
168
+ z = [] # inference output
169
+ self.training |= self.export
170
+ for i in range(self.nl):
171
+ x[i] = self.m[i](self.ia[i](x[i])) # conv
172
+ x[i] = self.im[i](x[i])
173
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
174
+ x[i] = (
175
+ x[i]
176
+ .view(bs, self.na, self.no, ny, nx)
177
+ .permute(0, 1, 3, 4, 2)
178
+ .contiguous()
179
+ )
180
+
181
+ x[i + self.nl] = self.m2[i](x[i + self.nl])
182
+ x[i + self.nl] = (
183
+ x[i + self.nl]
184
+ .view(bs, self.na, self.no, ny, nx)
185
+ .permute(0, 1, 3, 4, 2)
186
+ .contiguous()
187
+ )
188
+
189
+ if not self.training: # inference
190
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
191
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
192
+
193
+ y = x[i].sigmoid()
194
+ y[..., 0:2] = (y[..., 0:2] * 2.0 - 0.5 + self.grid[i]) * self.stride[
195
+ i
196
+ ] # xy
197
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
198
+ z.append(y.view(bs, -1, self.no))
199
+
200
+ return x if self.training else (torch.cat(z, 1), x[: self.nl])
201
+
202
+ @staticmethod
203
+ def _make_grid(nx=20, ny=20):
204
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
205
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
206
+
207
+
208
+ class IBin(nn.Module):
209
+ stride = None # strides computed during build
210
+ export = False # onnx export
211
+
212
+ def __init__(self, nc=80, anchors=(), ch=(), bin_count=21): # detection layer
213
+ super(IBin, self).__init__()
214
+ self.nc = nc # number of classes
215
+ self.bin_count = bin_count
216
+
217
+ self.w_bin_sigmoid = SigmoidBin(bin_count=self.bin_count, min=0.0, max=4.0)
218
+ self.h_bin_sigmoid = SigmoidBin(bin_count=self.bin_count, min=0.0, max=4.0)
219
+ # classes, x,y,obj
220
+ self.no = (
221
+ nc + 3 + self.w_bin_sigmoid.get_length() + self.h_bin_sigmoid.get_length()
222
+ ) # w-bce, h-bce
223
+ # + self.x_bin_sigmoid.get_length() + self.y_bin_sigmoid.get_length()
224
+
225
+ self.nl = len(anchors) # number of detection layers
226
+ self.na = len(anchors[0]) // 2 # number of anchors
227
+ self.grid = [torch.zeros(1)] * self.nl # init grid
228
+ a = torch.tensor(anchors).float().view(self.nl, -1, 2)
229
+ self.register_buffer("anchors", a) # shape(nl,na,2)
230
+ self.register_buffer(
231
+ "anchor_grid", a.clone().view(self.nl, 1, -1, 1, 1, 2)
232
+ ) # shape(nl,1,na,1,1,2)
233
+ self.m = nn.ModuleList(
234
+ nn.Conv2d(x, self.no * self.na, 1) for x in ch
235
+ ) # output conv
236
+
237
+ self.ia = nn.ModuleList(ImplicitA(x) for x in ch)
238
+ self.im = nn.ModuleList(ImplicitM(self.no * self.na) for _ in ch)
239
+
240
+ def forward(self, x):
241
+
242
+ # self.x_bin_sigmoid.use_fw_regression = True
243
+ # self.y_bin_sigmoid.use_fw_regression = True
244
+ self.w_bin_sigmoid.use_fw_regression = True
245
+ self.h_bin_sigmoid.use_fw_regression = True
246
+
247
+ # x = x.copy() # for profiling
248
+ z = [] # inference output
249
+ self.training |= self.export
250
+ for i in range(self.nl):
251
+ x[i] = self.m[i](self.ia[i](x[i])) # conv
252
+ x[i] = self.im[i](x[i])
253
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
254
+ x[i] = (
255
+ x[i]
256
+ .view(bs, self.na, self.no, ny, nx)
257
+ .permute(0, 1, 3, 4, 2)
258
+ .contiguous()
259
+ )
260
+
261
+ if not self.training: # inference
262
+ if self.grid[i].shape[2:4] != x[i].shape[2:4]:
263
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
264
+
265
+ y = x[i].sigmoid()
266
+ y[..., 0:2] = (y[..., 0:2] * 2.0 - 0.5 + self.grid[i]) * self.stride[
267
+ i
268
+ ] # xy
269
+ # y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
270
+
271
+ # px = (self.x_bin_sigmoid.forward(y[..., 0:12]) + self.grid[i][..., 0]) * self.stride[i]
272
+ # py = (self.y_bin_sigmoid.forward(y[..., 12:24]) + self.grid[i][..., 1]) * self.stride[i]
273
+
274
+ pw = (
275
+ self.w_bin_sigmoid.forward(y[..., 2:24])
276
+ * self.anchor_grid[i][..., 0]
277
+ )
278
+ ph = (
279
+ self.h_bin_sigmoid.forward(y[..., 24:46])
280
+ * self.anchor_grid[i][..., 1]
281
+ )
282
+
283
+ # y[..., 0] = px
284
+ # y[..., 1] = py
285
+ y[..., 2] = pw
286
+ y[..., 3] = ph
287
+
288
+ y = torch.cat((y[..., 0:4], y[..., 46:]), dim=-1)
289
+
290
+ z.append(y.view(bs, -1, y.shape[-1]))
291
+
292
+ return x if self.training else (torch.cat(z, 1), x)
293
+
294
+ @staticmethod
295
+ def _make_grid(nx=20, ny=20):
296
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
297
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
298
+
299
+
300
+ class Model(nn.Module):
301
+ def __init__(
302
+ self, cfg="yolor-csp-c.yaml", ch=3, nc=None, anchors=None
303
+ ): # model, input channels, number of classes
304
+ super(Model, self).__init__()
305
+ self.traced = False
306
+ if isinstance(cfg, dict):
307
+ self.yaml = cfg # model dict
308
+ else: # is *.yaml
309
+ import yaml # for torch hub
310
+
311
+ self.yaml_file = Path(cfg).name
312
+ with open(cfg) as f:
313
+ self.yaml = yaml.load(f, Loader=yaml.SafeLoader) # model dict
314
+
315
+ # Define model
316
+ ch = self.yaml["ch"] = self.yaml.get("ch", ch) # input channels
317
+ if nc and nc != self.yaml["nc"]:
318
+ logger.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
319
+ self.yaml["nc"] = nc # override yaml value
320
+ if anchors:
321
+ logger.info(f"Overriding model.yaml anchors with anchors={anchors}")
322
+ self.yaml["anchors"] = round(anchors) # override yaml value
323
+ self.model, self.save = parse_model(
324
+ deepcopy(self.yaml), ch=[ch]
325
+ ) # model, savelist
326
+ self.names = [str(i) for i in range(self.yaml["nc"])] # default names
327
+ # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])
328
+
329
+ # Build strides, anchors
330
+ m = self.model[-1] # Detect()
331
+ if isinstance(m, Detect):
332
+ s = 256 # 2x min stride
333
+ m.stride = torch.tensor(
334
+ [s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]
335
+ ) # forward
336
+ m.anchors /= m.stride.view(-1, 1, 1)
337
+ check_anchor_order(m)
338
+ self.stride = m.stride
339
+ self._initialize_biases() # only run once
340
+ # print('Strides: %s' % m.stride.tolist())
341
+ if isinstance(m, IDetect):
342
+ s = 256 # 2x min stride
343
+ m.stride = torch.tensor(
344
+ [s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]
345
+ ) # forward
346
+ m.anchors /= m.stride.view(-1, 1, 1)
347
+ check_anchor_order(m)
348
+ self.stride = m.stride
349
+ self._initialize_biases() # only run once
350
+ # print('Strides: %s' % m.stride.tolist())
351
+ if isinstance(m, IAuxDetect):
352
+ s = 256 # 2x min stride
353
+ m.stride = torch.tensor(
354
+ [s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))[:4]]
355
+ ) # forward
356
+ # print(m.stride)
357
+ m.anchors /= m.stride.view(-1, 1, 1)
358
+ check_anchor_order(m)
359
+ self.stride = m.stride
360
+ self._initialize_aux_biases() # only run once
361
+ # print('Strides: %s' % m.stride.tolist())
362
+ if isinstance(m, IBin):
363
+ s = 256 # 2x min stride
364
+ m.stride = torch.tensor(
365
+ [s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]
366
+ ) # forward
367
+ m.anchors /= m.stride.view(-1, 1, 1)
368
+ check_anchor_order(m)
369
+ self.stride = m.stride
370
+ self._initialize_biases_bin() # only run once
371
+ # print('Strides: %s' % m.stride.tolist())
372
+
373
+ # Init weights, biases
374
+ initialize_weights(self)
375
+ self.info()
376
+ logger.info("")
377
+
378
+ def forward(self, x, augment=False, profile=False):
379
+ if augment:
380
+ img_size = x.shape[-2:] # height, width
381
+ s = [1, 0.83, 0.67] # scales
382
+ f = [None, 3, None] # flips (2-ud, 3-lr)
383
+ y = [] # outputs
384
+ for si, fi in zip(s, f):
385
+ xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
386
+ yi = self.forward_once(xi)[0] # forward
387
+ # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
388
+ yi[..., :4] /= si # de-scale
389
+ if fi == 2:
390
+ yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud
391
+ elif fi == 3:
392
+ yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr
393
+ y.append(yi)
394
+ return torch.cat(y, 1), None # augmented inference, train
395
+ else:
396
+ return self.forward_once(x, profile) # single-scale inference, train
397
+
398
+ def forward_once(self, x, profile=False):
399
+ y, dt = [], [] # outputs
400
+ for m in self.model:
401
+ if m.f != -1: # if not from previous layer
402
+ x = (
403
+ y[m.f]
404
+ if isinstance(m.f, int)
405
+ else [x if j == -1 else y[j] for j in m.f]
406
+ ) # from earlier layers
407
+
408
+ if not hasattr(self, "traced"):
409
+ self.traced = False
410
+
411
+ if self.traced:
412
+ if (
413
+ isinstance(m, Detect)
414
+ or isinstance(m, IDetect)
415
+ or isinstance(m, IAuxDetect)
416
+ ):
417
+ break
418
+
419
+ if profile:
420
+ c = isinstance(m, (Detect, IDetect, IAuxDetect, IBin))
421
+ o = (
422
+ thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0]
423
+ / 1e9
424
+ * 2
425
+ if thop
426
+ else 0
427
+ ) # FLOPS
428
+ for _ in range(10):
429
+ m(x.copy() if c else x)
430
+ t = time_synchronized()
431
+ for _ in range(10):
432
+ m(x.copy() if c else x)
433
+ dt.append((time_synchronized() - t) * 100)
434
+ print("%10.1f%10.0f%10.1fms %-40s" % (o, m.np, dt[-1], m.type))
435
+
436
+ x = m(x) # run
437
+
438
+ y.append(x if m.i in self.save else None) # save output
439
+
440
+ if profile:
441
+ print("%.1fms total" % sum(dt))
442
+ return x
443
+
444
+ def _initialize_biases(
445
+ self, cf=None
446
+ ): # initialize biases into Detect(), cf is class frequency
447
+ # https://arxiv.org/abs/1708.02002 section 3.3
448
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
449
+ m = self.model[-1] # Detect() module
450
+ for mi, s in zip(m.m, m.stride): # from
451
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
452
+ b.data[:, 4] += math.log(
453
+ 8 / (640 / s) ** 2
454
+ ) # obj (8 objects per 640 image)
455
+ b.data[:, 5:] += (
456
+ math.log(0.6 / (m.nc - 0.99))
457
+ if cf is None
458
+ else torch.log(cf / cf.sum())
459
+ ) # cls
460
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
461
+
462
+ def _initialize_aux_biases(
463
+ self, cf=None
464
+ ): # initialize biases into Detect(), cf is class frequency
465
+ # https://arxiv.org/abs/1708.02002 section 3.3
466
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
467
+ m = self.model[-1] # Detect() module
468
+ for mi, mi2, s in zip(m.m, m.m2, m.stride): # from
469
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
470
+ b.data[:, 4] += math.log(
471
+ 8 / (640 / s) ** 2
472
+ ) # obj (8 objects per 640 image)
473
+ b.data[:, 5:] += (
474
+ math.log(0.6 / (m.nc - 0.99))
475
+ if cf is None
476
+ else torch.log(cf / cf.sum())
477
+ ) # cls
478
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
479
+ b2 = mi2.bias.view(m.na, -1) # conv.bias(255) to (3,85)
480
+ b2.data[:, 4] += math.log(
481
+ 8 / (640 / s) ** 2
482
+ ) # obj (8 objects per 640 image)
483
+ b2.data[:, 5:] += (
484
+ math.log(0.6 / (m.nc - 0.99))
485
+ if cf is None
486
+ else torch.log(cf / cf.sum())
487
+ ) # cls
488
+ mi2.bias = torch.nn.Parameter(b2.view(-1), requires_grad=True)
489
+
490
+ def _initialize_biases_bin(
491
+ self, cf=None
492
+ ): # initialize biases into Detect(), cf is class frequency
493
+ # https://arxiv.org/abs/1708.02002 section 3.3
494
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
495
+ m = self.model[-1] # Bin() module
496
+ bc = m.bin_count
497
+ for mi, s in zip(m.m, m.stride): # from
498
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
499
+ old = b[:, (0, 1, 2, bc + 3)].data
500
+ obj_idx = 2 * bc + 4
501
+ b[:, :obj_idx].data += math.log(0.6 / (bc + 1 - 0.99))
502
+ b[:, obj_idx].data += math.log(
503
+ 8 / (640 / s) ** 2
504
+ ) # obj (8 objects per 640 image)
505
+ b[:, (obj_idx + 1) :].data += (
506
+ math.log(0.6 / (m.nc - 0.99))
507
+ if cf is None
508
+ else torch.log(cf / cf.sum())
509
+ ) # cls
510
+ b[:, (0, 1, 2, bc + 3)].data = old
511
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
512
+
513
+ def _print_biases(self):
514
+ m = self.model[-1] # Detect() module
515
+ for mi in m.m: # from
516
+ b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
517
+ print(
518
+ ("%6g Conv2d.bias:" + "%10.3g" * 6)
519
+ % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean())
520
+ )
521
+
522
+ # def _print_weights(self):
523
+ # for m in self.model.modules():
524
+ # if type(m) is Bottleneck:
525
+ # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
526
+
527
+ def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
528
+ print("Fusing layers... ")
529
+ for m in self.model.modules():
530
+ if isinstance(m, RepConv):
531
+ # print(f" fuse_repvgg_block")
532
+ m.fuse_repvgg_block()
533
+ elif isinstance(m, RepConv_OREPA):
534
+ # print(f" switch_to_deploy")
535
+ m.switch_to_deploy()
536
+ elif type(m) is Conv and hasattr(m, "bn"):
537
+ m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
538
+ delattr(m, "bn") # remove batchnorm
539
+ m.forward = m.fuseforward # update forward
540
+ self.info()
541
+ return self
542
+
543
+ def nms(self, mode=True): # add or remove NMS module
544
+ present = type(self.model[-1]) is NMS # last layer is NMS
545
+ if mode and not present:
546
+ print("Adding NMS... ")
547
+ m = NMS() # module
548
+ m.f = -1 # from
549
+ m.i = self.model[-1].i + 1 # index
550
+ self.model.add_module(name="%s" % m.i, module=m) # add
551
+ self.eval()
552
+ elif not mode and present:
553
+ print("Removing NMS... ")
554
+ self.model = self.model[:-1] # remove
555
+ return self
556
+
557
+ def autoshape(self): # add autoShape module
558
+ print("Adding autoShape... ")
559
+ m = autoShape(self) # wrap model
560
+ copy_attr(
561
+ m, self, include=("yaml", "nc", "hyp", "names", "stride"), exclude=()
562
+ ) # copy attributes
563
+ return m
564
+
565
+ def info(self, verbose=False, img_size=640): # print model information
566
+ model_info(self, verbose, img_size)
567
+
568
+
569
+ def parse_model(d, ch): # model_dict, input_channels(3)
570
+ logger.info(
571
+ "\n%3s%18s%3s%10s %-40s%-30s"
572
+ % ("", "from", "n", "params", "module", "arguments")
573
+ )
574
+ anchors, nc, gd, gw = (
575
+ d["anchors"],
576
+ d["nc"],
577
+ d["depth_multiple"],
578
+ d["width_multiple"],
579
+ )
580
+ na = (
581
+ (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors
582
+ ) # number of anchors
583
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
584
+
585
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
586
+ for i, (f, n, m, args) in enumerate(
587
+ d["backbone"] + d["head"]
588
+ ): # from, number, module, args
589
+ m = eval(m) if isinstance(m, str) else m # eval strings
590
+ for j, a in enumerate(args):
591
+ try:
592
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
593
+ except:
594
+ pass
595
+
596
+ n = max(round(n * gd), 1) if n > 1 else n # depth gain
597
+ if m in [
598
+ nn.Conv2d,
599
+ Conv,
600
+ RobustConv,
601
+ RobustConv2,
602
+ DWConv,
603
+ GhostConv,
604
+ RepConv,
605
+ RepConv_OREPA,
606
+ DownC,
607
+ SPP,
608
+ SPPF,
609
+ SPPCSPC,
610
+ GhostSPPCSPC,
611
+ MixConv2d,
612
+ Focus,
613
+ Stem,
614
+ GhostStem,
615
+ CrossConv,
616
+ Bottleneck,
617
+ BottleneckCSPA,
618
+ BottleneckCSPB,
619
+ BottleneckCSPC,
620
+ RepBottleneck,
621
+ RepBottleneckCSPA,
622
+ RepBottleneckCSPB,
623
+ RepBottleneckCSPC,
624
+ Res,
625
+ ResCSPA,
626
+ ResCSPB,
627
+ ResCSPC,
628
+ RepRes,
629
+ RepResCSPA,
630
+ RepResCSPB,
631
+ RepResCSPC,
632
+ ResX,
633
+ ResXCSPA,
634
+ ResXCSPB,
635
+ ResXCSPC,
636
+ RepResX,
637
+ RepResXCSPA,
638
+ RepResXCSPB,
639
+ RepResXCSPC,
640
+ Ghost,
641
+ GhostCSPA,
642
+ GhostCSPB,
643
+ GhostCSPC,
644
+ SwinTransformerBlock,
645
+ STCSPA,
646
+ STCSPB,
647
+ STCSPC,
648
+ SwinTransformer2Block,
649
+ ST2CSPA,
650
+ ST2CSPB,
651
+ ST2CSPC,
652
+ ]:
653
+ c1, c2 = ch[f], args[0]
654
+ if c2 != no: # if not output
655
+ c2 = make_divisible(c2 * gw, 8)
656
+
657
+ args = [c1, c2, *args[1:]]
658
+ if m in [
659
+ DownC,
660
+ SPPCSPC,
661
+ GhostSPPCSPC,
662
+ BottleneckCSPA,
663
+ BottleneckCSPB,
664
+ BottleneckCSPC,
665
+ RepBottleneckCSPA,
666
+ RepBottleneckCSPB,
667
+ RepBottleneckCSPC,
668
+ ResCSPA,
669
+ ResCSPB,
670
+ ResCSPC,
671
+ RepResCSPA,
672
+ RepResCSPB,
673
+ RepResCSPC,
674
+ ResXCSPA,
675
+ ResXCSPB,
676
+ ResXCSPC,
677
+ RepResXCSPA,
678
+ RepResXCSPB,
679
+ RepResXCSPC,
680
+ GhostCSPA,
681
+ GhostCSPB,
682
+ GhostCSPC,
683
+ STCSPA,
684
+ STCSPB,
685
+ STCSPC,
686
+ ST2CSPA,
687
+ ST2CSPB,
688
+ ST2CSPC,
689
+ ]:
690
+ args.insert(2, n) # number of repeats
691
+ n = 1
692
+ elif m is nn.BatchNorm2d:
693
+ args = [ch[f]]
694
+ elif m is Concat:
695
+ c2 = sum([ch[x] for x in f])
696
+ elif m is Chuncat:
697
+ c2 = sum([ch[x] for x in f])
698
+ elif m is Shortcut:
699
+ c2 = ch[f[0]]
700
+ elif m is Foldcut:
701
+ c2 = ch[f] // 2
702
+ elif m in [Detect, IDetect, IAuxDetect, IBin]:
703
+ args.append([ch[x] for x in f])
704
+ if isinstance(args[1], int): # number of anchors
705
+ args[1] = [list(range(args[1] * 2))] * len(f)
706
+ elif m is ReOrg:
707
+ c2 = ch[f] * 4
708
+ elif m is Contract:
709
+ c2 = ch[f] * args[0] ** 2
710
+ elif m is Expand:
711
+ c2 = ch[f] // args[0] ** 2
712
+ else:
713
+ c2 = ch[f]
714
+
715
+ m_ = (
716
+ nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args)
717
+ ) # module
718
+ t = str(m)[8:-2].replace("__main__.", "") # module type
719
+ np = sum([x.numel() for x in m_.parameters()]) # number params
720
+ m_.i, m_.f, m_.type, m_.np = (
721
+ i,
722
+ f,
723
+ t,
724
+ np,
725
+ ) # attach index, 'from' index, type, number params
726
+ logger.info("%3s%18s%3s%10.0f %-40s%-30s" % (i, f, n, np, t, args)) # print
727
+ save.extend(
728
+ x % i for x in ([f] if isinstance(f, int) else f) if x != -1
729
+ ) # append to savelist
730
+ layers.append(m_)
731
+ if i == 0:
732
+ ch = []
733
+ ch.append(c2)
734
+ return nn.Sequential(*layers), sorted(save)
735
+
736
+
737
+ if __name__ == "__main__":
738
+ parser = argparse.ArgumentParser()
739
+ parser.add_argument(
740
+ "--cfg", type=str, default="yolor-csp-c.yaml", help="model.yaml"
741
+ )
742
+ parser.add_argument(
743
+ "--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu"
744
+ )
745
+ parser.add_argument("--profile", action="store_true", help="profile model speed")
746
+ opt = parser.parse_args()
747
+ opt.cfg = check_file(opt.cfg) # check file
748
+ set_logging()
749
+ device = select_device(opt.device)
750
+
751
+ # Create model
752
+ model = Model(opt.cfg).to(device)
753
+ model.train()
754
+
755
+ if opt.profile:
756
+ img = torch.rand(1, 3, 640, 640).to(device)
757
+ y = model(img, profile=True)
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Usage: pip install -r requirements.txt
2
+
3
+ matplotlib>=3.2.2
4
+ numpy>=1.18.5
5
+ opencv-python>=4.1.1
6
+ Pillow>=7.1.2
7
+ PyYAML>=5.3.1
8
+ requests>=2.23.0
9
+ scipy>=1.4.1
10
+ torch>=1.7.0,!=1.12.0
11
+ torchvision>=0.8.1,!=0.13.0
12
+ tqdm>=4.41.0
13
+ thop
14
+ protobuf<4.21.3
15
+ pandas>=1.1.4
16
+ seaborn>=0.11.0
utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # init
utils/autoanchor.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-anchor utils
2
+
3
+ import numpy as np
4
+ import torch
5
+ import yaml
6
+ from scipy.cluster.vq import kmeans
7
+ from tqdm import tqdm
8
+
9
+ from utils.general import colorstr
10
+
11
+
12
+ def check_anchor_order(m):
13
+ # Check anchor order against stride order for YOLO Detect() module m, and correct if necessary
14
+ a = m.anchor_grid.prod(-1).view(-1) # anchor area
15
+ da = a[-1] - a[0] # delta a
16
+ ds = m.stride[-1] - m.stride[0] # delta s
17
+ if da.sign() != ds.sign(): # same order
18
+ print('Reversing anchor order')
19
+ m.anchors[:] = m.anchors.flip(0)
20
+ m.anchor_grid[:] = m.anchor_grid.flip(0)
21
+
22
+
23
+ def check_anchors(dataset, model, thr=4.0, imgsz=640):
24
+ # Check anchor fit to data, recompute if necessary
25
+ prefix = colorstr('autoanchor: ')
26
+ print(f'\n{prefix}Analyzing anchors... ', end='')
27
+ m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
28
+ shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
29
+ scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
30
+ wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
31
+
32
+ def metric(k): # compute metric
33
+ r = wh[:, None] / k[None]
34
+ x = torch.min(r, 1. / r).min(2)[0] # ratio metric
35
+ best = x.max(1)[0] # best_x
36
+ aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
37
+ bpr = (best > 1. / thr).float().mean() # best possible recall
38
+ return bpr, aat
39
+
40
+ anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors
41
+ bpr, aat = metric(anchors)
42
+ print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')
43
+ if bpr < 0.98: # threshold to recompute
44
+ print('. Attempting to improve anchors, please wait...')
45
+ na = m.anchor_grid.numel() // 2 # number of anchors
46
+ try:
47
+ anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
48
+ except Exception as e:
49
+ print(f'{prefix}ERROR: {e}')
50
+ new_bpr = metric(anchors)[0]
51
+ if new_bpr > bpr: # replace anchors
52
+ anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
53
+ m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference
54
+ m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
55
+ check_anchor_order(m)
56
+ print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')
57
+ else:
58
+ print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')
59
+ print('') # newline
60
+
61
+
62
+ def kmean_anchors(path='./data/coco.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
63
+ """ Creates kmeans-evolved anchors from training dataset
64
+
65
+ Arguments:
66
+ path: path to dataset *.yaml, or a loaded dataset
67
+ n: number of anchors
68
+ img_size: image size used for training
69
+ thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
70
+ gen: generations to evolve anchors using genetic algorithm
71
+ verbose: print all results
72
+
73
+ Return:
74
+ k: kmeans evolved anchors
75
+
76
+ Usage:
77
+ from utils.autoanchor import *; _ = kmean_anchors()
78
+ """
79
+ thr = 1. / thr
80
+ prefix = colorstr('autoanchor: ')
81
+
82
+ def metric(k, wh): # compute metrics
83
+ r = wh[:, None] / k[None]
84
+ x = torch.min(r, 1. / r).min(2)[0] # ratio metric
85
+ # x = wh_iou(wh, torch.tensor(k)) # iou metric
86
+ return x, x.max(1)[0] # x, best_x
87
+
88
+ def anchor_fitness(k): # mutation fitness
89
+ _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
90
+ return (best * (best > thr).float()).mean() # fitness
91
+
92
+ def print_results(k):
93
+ k = k[np.argsort(k.prod(1))] # sort small to large
94
+ x, best = metric(k, wh0)
95
+ bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
96
+ print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr')
97
+ print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, '
98
+ f'past_thr={x[x > thr].mean():.3f}-mean: ', end='')
99
+ for i, x in enumerate(k):
100
+ print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
101
+ return k
102
+
103
+ if isinstance(path, str): # *.yaml file
104
+ with open(path) as f:
105
+ data_dict = yaml.load(f, Loader=yaml.SafeLoader) # model dict
106
+ from utils.datasets import LoadImagesAndLabels
107
+ dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
108
+ else:
109
+ dataset = path # dataset
110
+
111
+ # Get label wh
112
+ shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
113
+ wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
114
+
115
+ # Filter
116
+ i = (wh0 < 3.0).any(1).sum()
117
+ if i:
118
+ print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.')
119
+ wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
120
+ # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
121
+
122
+ # Kmeans calculation
123
+ print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...')
124
+ s = wh.std(0) # sigmas for whitening
125
+ k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
126
+ assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}')
127
+ k *= s
128
+ wh = torch.tensor(wh, dtype=torch.float32) # filtered
129
+ wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered
130
+ k = print_results(k)
131
+
132
+ # Plot
133
+ # k, d = [None] * 20, [None] * 20
134
+ # for i in tqdm(range(1, 21)):
135
+ # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
136
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
137
+ # ax = ax.ravel()
138
+ # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
139
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
140
+ # ax[0].hist(wh[wh[:, 0]<100, 0],400)
141
+ # ax[1].hist(wh[wh[:, 1]<100, 1],400)
142
+ # fig.savefig('wh.png', dpi=200)
143
+
144
+ # Evolve
145
+ npr = np.random
146
+ f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
147
+ pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar
148
+ for _ in pbar:
149
+ v = np.ones(sh)
150
+ while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
151
+ v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
152
+ kg = (k.copy() * v).clip(min=2.0)
153
+ fg = anchor_fitness(kg)
154
+ if fg > f:
155
+ f, k = fg, kg.copy()
156
+ pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
157
+ if verbose:
158
+ print_results(k)
159
+
160
+ return print_results(k)
utils/datasets.py ADDED
@@ -0,0 +1,1320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dataset utils and dataloaders
2
+
3
+ import glob
4
+ import logging
5
+ import math
6
+ import os
7
+ import random
8
+ import shutil
9
+ import time
10
+ from itertools import repeat
11
+ from multiprocessing.pool import ThreadPool
12
+ from pathlib import Path
13
+ from threading import Thread
14
+
15
+ import cv2
16
+ import numpy as np
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from PIL import Image, ExifTags
20
+ from torch.utils.data import Dataset
21
+ from tqdm import tqdm
22
+
23
+ import pickle
24
+ from copy import deepcopy
25
+ #from pycocotools import mask as maskUtils
26
+ from torchvision.utils import save_image
27
+ from torchvision.ops import roi_pool, roi_align, ps_roi_pool, ps_roi_align
28
+
29
+ from utils.general import check_requirements, xyxy2xywh, xywh2xyxy, xywhn2xyxy, xyn2xy, segment2box, segments2boxes, \
30
+ resample_segments, clean_str
31
+ from utils.torch_utils import torch_distributed_zero_first
32
+
33
+ # Parameters
34
+ help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
35
+ img_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes
36
+ vid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes
37
+ logger = logging.getLogger(__name__)
38
+
39
+ # Get orientation exif tag
40
+ for orientation in ExifTags.TAGS.keys():
41
+ if ExifTags.TAGS[orientation] == 'Orientation':
42
+ break
43
+
44
+
45
+ def get_hash(files):
46
+ # Returns a single hash value of a list of files
47
+ return sum(os.path.getsize(f) for f in files if os.path.isfile(f))
48
+
49
+
50
+ def exif_size(img):
51
+ # Returns exif-corrected PIL size
52
+ s = img.size # (width, height)
53
+ try:
54
+ rotation = dict(img._getexif().items())[orientation]
55
+ if rotation == 6: # rotation 270
56
+ s = (s[1], s[0])
57
+ elif rotation == 8: # rotation 90
58
+ s = (s[1], s[0])
59
+ except:
60
+ pass
61
+
62
+ return s
63
+
64
+
65
+ def create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False,
66
+ rank=-1, world_size=1, workers=8, image_weights=False, quad=False, prefix=''):
67
+ # Make sure only the first process in DDP process the dataset first, and the following others can use the cache
68
+ with torch_distributed_zero_first(rank):
69
+ dataset = LoadImagesAndLabels(path, imgsz, batch_size,
70
+ augment=augment, # augment images
71
+ hyp=hyp, # augmentation hyperparameters
72
+ rect=rect, # rectangular training
73
+ cache_images=cache,
74
+ single_cls=opt.single_cls,
75
+ stride=int(stride),
76
+ pad=pad,
77
+ image_weights=image_weights,
78
+ prefix=prefix)
79
+
80
+ batch_size = min(batch_size, len(dataset))
81
+ nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, workers]) # number of workers
82
+ sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None
83
+ loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader
84
+ # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader()
85
+ dataloader = loader(dataset,
86
+ batch_size=batch_size,
87
+ num_workers=nw,
88
+ sampler=sampler,
89
+ pin_memory=True,
90
+ collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)
91
+ return dataloader, dataset
92
+
93
+
94
+ class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader):
95
+ """ Dataloader that reuses workers
96
+
97
+ Uses same syntax as vanilla DataLoader
98
+ """
99
+
100
+ def __init__(self, *args, **kwargs):
101
+ super().__init__(*args, **kwargs)
102
+ object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
103
+ self.iterator = super().__iter__()
104
+
105
+ def __len__(self):
106
+ return len(self.batch_sampler.sampler)
107
+
108
+ def __iter__(self):
109
+ for i in range(len(self)):
110
+ yield next(self.iterator)
111
+
112
+
113
+ class _RepeatSampler(object):
114
+ """ Sampler that repeats forever
115
+
116
+ Args:
117
+ sampler (Sampler)
118
+ """
119
+
120
+ def __init__(self, sampler):
121
+ self.sampler = sampler
122
+
123
+ def __iter__(self):
124
+ while True:
125
+ yield from iter(self.sampler)
126
+
127
+
128
+ class LoadImages: # for inference
129
+ def __init__(self, path, img_size=640, stride=32):
130
+ p = str(Path(path).absolute()) # os-agnostic absolute path
131
+ if '*' in p:
132
+ files = sorted(glob.glob(p, recursive=True)) # glob
133
+ elif os.path.isdir(p):
134
+ files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
135
+ elif os.path.isfile(p):
136
+ files = [p] # files
137
+ else:
138
+ raise Exception(f'ERROR: {p} does not exist')
139
+
140
+ images = [x for x in files if x.split('.')[-1].lower() in img_formats]
141
+ videos = [x for x in files if x.split('.')[-1].lower() in vid_formats]
142
+ ni, nv = len(images), len(videos)
143
+
144
+ self.img_size = img_size
145
+ self.stride = stride
146
+ self.files = images + videos
147
+ self.nf = ni + nv # number of files
148
+ self.video_flag = [False] * ni + [True] * nv
149
+ self.mode = 'image'
150
+ if any(videos):
151
+ self.new_video(videos[0]) # new video
152
+ else:
153
+ self.cap = None
154
+ assert self.nf > 0, f'No images or videos found in {p}. ' \
155
+ f'Supported formats are:\nimages: {img_formats}\nvideos: {vid_formats}'
156
+
157
+ def __iter__(self):
158
+ self.count = 0
159
+ return self
160
+
161
+ def __next__(self):
162
+ if self.count == self.nf:
163
+ raise StopIteration
164
+ path = self.files[self.count]
165
+
166
+ if self.video_flag[self.count]:
167
+ # Read video
168
+ self.mode = 'video'
169
+ ret_val, img0 = self.cap.read()
170
+ if not ret_val:
171
+ self.count += 1
172
+ self.cap.release()
173
+ if self.count == self.nf: # last video
174
+ raise StopIteration
175
+ else:
176
+ path = self.files[self.count]
177
+ self.new_video(path)
178
+ ret_val, img0 = self.cap.read()
179
+
180
+ self.frame += 1
181
+ print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.nframes}) {path}: ', end='')
182
+
183
+ else:
184
+ # Read image
185
+ self.count += 1
186
+ img0 = cv2.imread(path) # BGR
187
+ assert img0 is not None, 'Image Not Found ' + path
188
+ #print(f'image {self.count}/{self.nf} {path}: ', end='')
189
+
190
+ # Padded resize
191
+ img = letterbox(img0, self.img_size, stride=self.stride)[0]
192
+
193
+ # Convert
194
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
195
+ img = np.ascontiguousarray(img)
196
+
197
+ return path, img, img0, self.cap
198
+
199
+ def new_video(self, path):
200
+ self.frame = 0
201
+ self.cap = cv2.VideoCapture(path)
202
+ self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
203
+
204
+ def __len__(self):
205
+ return self.nf # number of files
206
+
207
+
208
+ class LoadWebcam: # for inference
209
+ def __init__(self, pipe='0', img_size=640, stride=32):
210
+ self.img_size = img_size
211
+ self.stride = stride
212
+
213
+ if pipe.isnumeric():
214
+ pipe = eval(pipe) # local camera
215
+ # pipe = 'rtsp://192.168.1.64/1' # IP camera
216
+ # pipe = 'rtsp://username:password@192.168.1.64/1' # IP camera with login
217
+ # pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg' # IP golf camera
218
+
219
+ self.pipe = pipe
220
+ self.cap = cv2.VideoCapture(pipe) # video capture object
221
+ self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
222
+
223
+ def __iter__(self):
224
+ self.count = -1
225
+ return self
226
+
227
+ def __next__(self):
228
+ self.count += 1
229
+ if cv2.waitKey(1) == ord('q'): # q to quit
230
+ self.cap.release()
231
+ cv2.destroyAllWindows()
232
+ raise StopIteration
233
+
234
+ # Read frame
235
+ if self.pipe == 0: # local camera
236
+ ret_val, img0 = self.cap.read()
237
+ img0 = cv2.flip(img0, 1) # flip left-right
238
+ else: # IP camera
239
+ n = 0
240
+ while True:
241
+ n += 1
242
+ self.cap.grab()
243
+ if n % 30 == 0: # skip frames
244
+ ret_val, img0 = self.cap.retrieve()
245
+ if ret_val:
246
+ break
247
+
248
+ # Print
249
+ assert ret_val, f'Camera Error {self.pipe}'
250
+ img_path = 'webcam.jpg'
251
+ print(f'webcam {self.count}: ', end='')
252
+
253
+ # Padded resize
254
+ img = letterbox(img0, self.img_size, stride=self.stride)[0]
255
+
256
+ # Convert
257
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
258
+ img = np.ascontiguousarray(img)
259
+
260
+ return img_path, img, img0, None
261
+
262
+ def __len__(self):
263
+ return 0
264
+
265
+
266
+ class LoadStreams: # multiple IP or RTSP cameras
267
+ def __init__(self, sources='streams.txt', img_size=640, stride=32):
268
+ self.mode = 'stream'
269
+ self.img_size = img_size
270
+ self.stride = stride
271
+
272
+ if os.path.isfile(sources):
273
+ with open(sources, 'r') as f:
274
+ sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
275
+ else:
276
+ sources = [sources]
277
+
278
+ n = len(sources)
279
+ self.imgs = [None] * n
280
+ self.sources = [clean_str(x) for x in sources] # clean source names for later
281
+ for i, s in enumerate(sources):
282
+ # Start the thread to read frames from the video stream
283
+ print(f'{i + 1}/{n}: {s}... ', end='')
284
+ url = eval(s) if s.isnumeric() else s
285
+ if 'youtube.com/' in url or 'youtu.be/' in url: # if source is YouTube video
286
+ check_requirements(('pafy', 'youtube_dl'))
287
+ import pafy
288
+ url = pafy.new(url).getbest(preftype="mp4").url
289
+ cap = cv2.VideoCapture(url)
290
+ assert cap.isOpened(), f'Failed to open {s}'
291
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
292
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
293
+ self.fps = cap.get(cv2.CAP_PROP_FPS) % 100
294
+
295
+ _, self.imgs[i] = cap.read() # guarantee first frame
296
+ thread = Thread(target=self.update, args=([i, cap]), daemon=True)
297
+ print(f' success ({w}x{h} at {self.fps:.2f} FPS).')
298
+ thread.start()
299
+ print('') # newline
300
+
301
+ # check for common shapes
302
+ s = np.stack([letterbox(x, self.img_size, stride=self.stride)[0].shape for x in self.imgs], 0) # shapes
303
+ self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
304
+ if not self.rect:
305
+ print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
306
+
307
+ def update(self, index, cap):
308
+ # Read next stream frame in a daemon thread
309
+ n = 0
310
+ while cap.isOpened():
311
+ n += 1
312
+ # _, self.imgs[index] = cap.read()
313
+ cap.grab()
314
+ if n == 4: # read every 4th frame
315
+ success, im = cap.retrieve()
316
+ self.imgs[index] = im if success else self.imgs[index] * 0
317
+ n = 0
318
+ time.sleep(1 / self.fps) # wait time
319
+
320
+ def __iter__(self):
321
+ self.count = -1
322
+ return self
323
+
324
+ def __next__(self):
325
+ self.count += 1
326
+ img0 = self.imgs.copy()
327
+ if cv2.waitKey(1) == ord('q'): # q to quit
328
+ cv2.destroyAllWindows()
329
+ raise StopIteration
330
+
331
+ # Letterbox
332
+ img = [letterbox(x, self.img_size, auto=self.rect, stride=self.stride)[0] for x in img0]
333
+
334
+ # Stack
335
+ img = np.stack(img, 0)
336
+
337
+ # Convert
338
+ img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416
339
+ img = np.ascontiguousarray(img)
340
+
341
+ return self.sources, img, img0, None
342
+
343
+ def __len__(self):
344
+ return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years
345
+
346
+
347
+ def img2label_paths(img_paths):
348
+ # Define label paths as a function of image paths
349
+ sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings
350
+ return ['txt'.join(x.replace(sa, sb, 1).rsplit(x.split('.')[-1], 1)) for x in img_paths]
351
+
352
+
353
+ class LoadImagesAndLabels(Dataset): # for training/testing
354
+ def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
355
+ cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):
356
+ self.img_size = img_size
357
+ self.augment = augment
358
+ self.hyp = hyp
359
+ self.image_weights = image_weights
360
+ self.rect = False if image_weights else rect
361
+ self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
362
+ self.mosaic_border = [-img_size // 2, -img_size // 2]
363
+ self.stride = stride
364
+ self.path = path
365
+ #self.albumentations = Albumentations() if augment else None
366
+
367
+ try:
368
+ f = [] # image files
369
+ for p in path if isinstance(path, list) else [path]:
370
+ p = Path(p) # os-agnostic
371
+ if p.is_dir(): # dir
372
+ f += glob.glob(str(p / '**' / '*.*'), recursive=True)
373
+ # f = list(p.rglob('**/*.*')) # pathlib
374
+ elif p.is_file(): # file
375
+ with open(p, 'r') as t:
376
+ t = t.read().strip().splitlines()
377
+ parent = str(p.parent) + os.sep
378
+ f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
379
+ # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
380
+ else:
381
+ raise Exception(f'{prefix}{p} does not exist')
382
+ self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats])
383
+ # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib
384
+ assert self.img_files, f'{prefix}No images found'
385
+ except Exception as e:
386
+ raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {help_url}')
387
+
388
+ # Check cache
389
+ self.label_files = img2label_paths(self.img_files) # labels
390
+ cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') # cached labels
391
+ if cache_path.is_file():
392
+ cache, exists = torch.load(cache_path), True # load
393
+ #if cache['hash'] != get_hash(self.label_files + self.img_files) or 'version' not in cache: # changed
394
+ # cache, exists = self.cache_labels(cache_path, prefix), False # re-cache
395
+ else:
396
+ cache, exists = self.cache_labels(cache_path, prefix), False # cache
397
+
398
+ # Display cache
399
+ nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total
400
+ if exists:
401
+ d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted"
402
+ tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results
403
+ assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}'
404
+
405
+ # Read cache
406
+ cache.pop('hash') # remove hash
407
+ cache.pop('version') # remove version
408
+ labels, shapes, self.segments = zip(*cache.values())
409
+ self.labels = list(labels)
410
+ self.shapes = np.array(shapes, dtype=np.float64)
411
+ self.img_files = list(cache.keys()) # update
412
+ self.label_files = img2label_paths(cache.keys()) # update
413
+ if single_cls:
414
+ for x in self.labels:
415
+ x[:, 0] = 0
416
+
417
+ n = len(shapes) # number of images
418
+ bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
419
+ nb = bi[-1] + 1 # number of batches
420
+ self.batch = bi # batch index of image
421
+ self.n = n
422
+ self.indices = range(n)
423
+
424
+ # Rectangular Training
425
+ if self.rect:
426
+ # Sort by aspect ratio
427
+ s = self.shapes # wh
428
+ ar = s[:, 1] / s[:, 0] # aspect ratio
429
+ irect = ar.argsort()
430
+ self.img_files = [self.img_files[i] for i in irect]
431
+ self.label_files = [self.label_files[i] for i in irect]
432
+ self.labels = [self.labels[i] for i in irect]
433
+ self.shapes = s[irect] # wh
434
+ ar = ar[irect]
435
+
436
+ # Set training image shapes
437
+ shapes = [[1, 1]] * nb
438
+ for i in range(nb):
439
+ ari = ar[bi == i]
440
+ mini, maxi = ari.min(), ari.max()
441
+ if maxi < 1:
442
+ shapes[i] = [maxi, 1]
443
+ elif mini > 1:
444
+ shapes[i] = [1, 1 / mini]
445
+
446
+ self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
447
+
448
+ # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
449
+ self.imgs = [None] * n
450
+ if cache_images:
451
+ if cache_images == 'disk':
452
+ self.im_cache_dir = Path(Path(self.img_files[0]).parent.as_posix() + '_npy')
453
+ self.img_npy = [self.im_cache_dir / Path(f).with_suffix('.npy').name for f in self.img_files]
454
+ self.im_cache_dir.mkdir(parents=True, exist_ok=True)
455
+ gb = 0 # Gigabytes of cached images
456
+ self.img_hw0, self.img_hw = [None] * n, [None] * n
457
+ results = ThreadPool(8).imap(lambda x: load_image(*x), zip(repeat(self), range(n)))
458
+ pbar = tqdm(enumerate(results), total=n)
459
+ for i, x in pbar:
460
+ if cache_images == 'disk':
461
+ if not self.img_npy[i].exists():
462
+ np.save(self.img_npy[i].as_posix(), x[0])
463
+ gb += self.img_npy[i].stat().st_size
464
+ else:
465
+ self.imgs[i], self.img_hw0[i], self.img_hw[i] = x
466
+ gb += self.imgs[i].nbytes
467
+ pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)'
468
+ pbar.close()
469
+
470
+ def cache_labels(self, path=Path('./labels.cache'), prefix=''):
471
+ # Cache dataset labels, check images and read shapes
472
+ x = {} # dict
473
+ nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, duplicate
474
+ pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files))
475
+ for i, (im_file, lb_file) in enumerate(pbar):
476
+ try:
477
+ # verify images
478
+ im = Image.open(im_file)
479
+ im.verify() # PIL verify
480
+ shape = exif_size(im) # image size
481
+ segments = [] # instance segments
482
+ assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
483
+ assert im.format.lower() in img_formats, f'invalid image format {im.format}'
484
+
485
+ # verify labels
486
+ if os.path.isfile(lb_file):
487
+ nf += 1 # label found
488
+ with open(lb_file, 'r') as f:
489
+ l = [x.split() for x in f.read().strip().splitlines()]
490
+ if any([len(x) > 8 for x in l]): # is segment
491
+ classes = np.array([x[0] for x in l], dtype=np.float32)
492
+ segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
493
+ l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
494
+ l = np.array(l, dtype=np.float32)
495
+ if len(l):
496
+ assert l.shape[1] == 5, 'labels require 5 columns each'
497
+ assert (l >= 0).all(), 'negative labels'
498
+ assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'
499
+ assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'
500
+ else:
501
+ ne += 1 # label empty
502
+ l = np.zeros((0, 5), dtype=np.float32)
503
+ else:
504
+ nm += 1 # label missing
505
+ l = np.zeros((0, 5), dtype=np.float32)
506
+ x[im_file] = [l, shape, segments]
507
+ except Exception as e:
508
+ nc += 1
509
+ print(f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}')
510
+
511
+ pbar.desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels... " \
512
+ f"{nf} found, {nm} missing, {ne} empty, {nc} corrupted"
513
+ pbar.close()
514
+
515
+ if nf == 0:
516
+ print(f'{prefix}WARNING: No labels found in {path}. See {help_url}')
517
+
518
+ x['hash'] = get_hash(self.label_files + self.img_files)
519
+ x['results'] = nf, nm, ne, nc, i + 1
520
+ x['version'] = 0.1 # cache version
521
+ torch.save(x, path) # save for next time
522
+ logging.info(f'{prefix}New cache created: {path}')
523
+ return x
524
+
525
+ def __len__(self):
526
+ return len(self.img_files)
527
+
528
+ # def __iter__(self):
529
+ # self.count = -1
530
+ # print('ran dataset iter')
531
+ # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
532
+ # return self
533
+
534
+ def __getitem__(self, index):
535
+ index = self.indices[index] # linear, shuffled, or image_weights
536
+
537
+ hyp = self.hyp
538
+ mosaic = self.mosaic and random.random() < hyp['mosaic']
539
+ if mosaic:
540
+ # Load mosaic
541
+ if random.random() < 0.8:
542
+ img, labels = load_mosaic(self, index)
543
+ else:
544
+ img, labels = load_mosaic9(self, index)
545
+ shapes = None
546
+
547
+ # MixUp https://arxiv.org/pdf/1710.09412.pdf
548
+ if random.random() < hyp['mixup']:
549
+ if random.random() < 0.8:
550
+ img2, labels2 = load_mosaic(self, random.randint(0, len(self.labels) - 1))
551
+ else:
552
+ img2, labels2 = load_mosaic9(self, random.randint(0, len(self.labels) - 1))
553
+ r = np.random.beta(8.0, 8.0) # mixup ratio, alpha=beta=8.0
554
+ img = (img * r + img2 * (1 - r)).astype(np.uint8)
555
+ labels = np.concatenate((labels, labels2), 0)
556
+
557
+ else:
558
+ # Load image
559
+ img, (h0, w0), (h, w) = load_image(self, index)
560
+
561
+ # Letterbox
562
+ shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
563
+ img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
564
+ shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
565
+
566
+ labels = self.labels[index].copy()
567
+ if labels.size: # normalized xywh to pixel xyxy format
568
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
569
+
570
+ if self.augment:
571
+ # Augment imagespace
572
+ if not mosaic:
573
+ img, labels = random_perspective(img, labels,
574
+ degrees=hyp['degrees'],
575
+ translate=hyp['translate'],
576
+ scale=hyp['scale'],
577
+ shear=hyp['shear'],
578
+ perspective=hyp['perspective'])
579
+
580
+
581
+ #img, labels = self.albumentations(img, labels)
582
+
583
+ # Augment colorspace
584
+ augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
585
+
586
+ # Apply cutouts
587
+ # if random.random() < 0.9:
588
+ # labels = cutout(img, labels)
589
+
590
+ if random.random() < hyp['paste_in']:
591
+ sample_labels, sample_images, sample_masks = [], [], []
592
+ while len(sample_labels) < 30:
593
+ sample_labels_, sample_images_, sample_masks_ = load_samples(self, random.randint(0, len(self.labels) - 1))
594
+ sample_labels += sample_labels_
595
+ sample_images += sample_images_
596
+ sample_masks += sample_masks_
597
+ #print(len(sample_labels))
598
+ if len(sample_labels) == 0:
599
+ break
600
+ labels = pastein(img, labels, sample_labels, sample_images, sample_masks)
601
+
602
+ nL = len(labels) # number of labels
603
+ if nL:
604
+ labels[:, 1:5] = xyxy2xywh(labels[:, 1:5]) # convert xyxy to xywh
605
+ labels[:, [2, 4]] /= img.shape[0] # normalized height 0-1
606
+ labels[:, [1, 3]] /= img.shape[1] # normalized width 0-1
607
+
608
+ if self.augment:
609
+ # flip up-down
610
+ if random.random() < hyp['flipud']:
611
+ img = np.flipud(img)
612
+ if nL:
613
+ labels[:, 2] = 1 - labels[:, 2]
614
+
615
+ # flip left-right
616
+ if random.random() < hyp['fliplr']:
617
+ img = np.fliplr(img)
618
+ if nL:
619
+ labels[:, 1] = 1 - labels[:, 1]
620
+
621
+ labels_out = torch.zeros((nL, 6))
622
+ if nL:
623
+ labels_out[:, 1:] = torch.from_numpy(labels)
624
+
625
+ # Convert
626
+ img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
627
+ img = np.ascontiguousarray(img)
628
+
629
+ return torch.from_numpy(img), labels_out, self.img_files[index], shapes
630
+
631
+ @staticmethod
632
+ def collate_fn(batch):
633
+ img, label, path, shapes = zip(*batch) # transposed
634
+ for i, l in enumerate(label):
635
+ l[:, 0] = i # add target image index for build_targets()
636
+ return torch.stack(img, 0), torch.cat(label, 0), path, shapes
637
+
638
+ @staticmethod
639
+ def collate_fn4(batch):
640
+ img, label, path, shapes = zip(*batch) # transposed
641
+ n = len(shapes) // 4
642
+ img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
643
+
644
+ ho = torch.tensor([[0., 0, 0, 1, 0, 0]])
645
+ wo = torch.tensor([[0., 0, 1, 0, 0, 0]])
646
+ s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale
647
+ for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
648
+ i *= 4
649
+ if random.random() < 0.5:
650
+ im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[
651
+ 0].type(img[i].type())
652
+ l = label[i]
653
+ else:
654
+ im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
655
+ l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
656
+ img4.append(im)
657
+ label4.append(l)
658
+
659
+ for i, l in enumerate(label4):
660
+ l[:, 0] = i # add target image index for build_targets()
661
+
662
+ return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4
663
+
664
+
665
+ # Ancillary functions --------------------------------------------------------------------------------------------------
666
+ def load_image(self, index):
667
+ # loads 1 image from dataset, returns img, original hw, resized hw
668
+ img = self.imgs[index]
669
+ if img is None: # not cached
670
+ path = self.img_files[index]
671
+ img = cv2.imread(path) # BGR
672
+ assert img is not None, 'Image Not Found ' + path
673
+ h0, w0 = img.shape[:2] # orig hw
674
+ r = self.img_size / max(h0, w0) # resize image to img_size
675
+ if r != 1: # always resize down, only resize up if training with augmentation
676
+ interp = cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR
677
+ img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp)
678
+ return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized
679
+ else:
680
+ return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized
681
+
682
+
683
+ def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
684
+ r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
685
+ hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
686
+ dtype = img.dtype # uint8
687
+
688
+ x = np.arange(0, 256, dtype=np.int16)
689
+ lut_hue = ((x * r[0]) % 180).astype(dtype)
690
+ lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
691
+ lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
692
+
693
+ img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)
694
+ cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
695
+
696
+
697
+ def hist_equalize(img, clahe=True, bgr=False):
698
+ # Equalize histogram on BGR image 'img' with img.shape(n,m,3) and range 0-255
699
+ yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
700
+ if clahe:
701
+ c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
702
+ yuv[:, :, 0] = c.apply(yuv[:, :, 0])
703
+ else:
704
+ yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
705
+ return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
706
+
707
+
708
+ def load_mosaic(self, index):
709
+ # loads images in a 4-mosaic
710
+
711
+ labels4, segments4 = [], []
712
+ s = self.img_size
713
+ yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y
714
+ indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
715
+ for i, index in enumerate(indices):
716
+ # Load image
717
+ img, _, (h, w) = load_image(self, index)
718
+
719
+ # place img in img4
720
+ if i == 0: # top left
721
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
722
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
723
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
724
+ elif i == 1: # top right
725
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
726
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
727
+ elif i == 2: # bottom left
728
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
729
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
730
+ elif i == 3: # bottom right
731
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
732
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
733
+
734
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
735
+ padw = x1a - x1b
736
+ padh = y1a - y1b
737
+
738
+ # Labels
739
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
740
+ if labels.size:
741
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
742
+ segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
743
+ labels4.append(labels)
744
+ segments4.extend(segments)
745
+
746
+ # Concat/clip labels
747
+ labels4 = np.concatenate(labels4, 0)
748
+ for x in (labels4[:, 1:], *segments4):
749
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
750
+ # img4, labels4 = replicate(img4, labels4) # replicate
751
+
752
+ # Augment
753
+ #img4, labels4, segments4 = remove_background(img4, labels4, segments4)
754
+ #sample_segments(img4, labels4, segments4, probability=self.hyp['copy_paste'])
755
+ img4, labels4, segments4 = copy_paste(img4, labels4, segments4, probability=self.hyp['copy_paste'])
756
+ img4, labels4 = random_perspective(img4, labels4, segments4,
757
+ degrees=self.hyp['degrees'],
758
+ translate=self.hyp['translate'],
759
+ scale=self.hyp['scale'],
760
+ shear=self.hyp['shear'],
761
+ perspective=self.hyp['perspective'],
762
+ border=self.mosaic_border) # border to remove
763
+
764
+ return img4, labels4
765
+
766
+
767
+ def load_mosaic9(self, index):
768
+ # loads images in a 9-mosaic
769
+
770
+ labels9, segments9 = [], []
771
+ s = self.img_size
772
+ indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
773
+ for i, index in enumerate(indices):
774
+ # Load image
775
+ img, _, (h, w) = load_image(self, index)
776
+
777
+ # place img in img9
778
+ if i == 0: # center
779
+ img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
780
+ h0, w0 = h, w
781
+ c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
782
+ elif i == 1: # top
783
+ c = s, s - h, s + w, s
784
+ elif i == 2: # top right
785
+ c = s + wp, s - h, s + wp + w, s
786
+ elif i == 3: # right
787
+ c = s + w0, s, s + w0 + w, s + h
788
+ elif i == 4: # bottom right
789
+ c = s + w0, s + hp, s + w0 + w, s + hp + h
790
+ elif i == 5: # bottom
791
+ c = s + w0 - w, s + h0, s + w0, s + h0 + h
792
+ elif i == 6: # bottom left
793
+ c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
794
+ elif i == 7: # left
795
+ c = s - w, s + h0 - h, s, s + h0
796
+ elif i == 8: # top left
797
+ c = s - w, s + h0 - hp - h, s, s + h0 - hp
798
+
799
+ padx, pady = c[:2]
800
+ x1, y1, x2, y2 = [max(x, 0) for x in c] # allocate coords
801
+
802
+ # Labels
803
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
804
+ if labels.size:
805
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
806
+ segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
807
+ labels9.append(labels)
808
+ segments9.extend(segments)
809
+
810
+ # Image
811
+ img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]
812
+ hp, wp = h, w # height, width previous
813
+
814
+ # Offset
815
+ yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border] # mosaic center x, y
816
+ img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
817
+
818
+ # Concat/clip labels
819
+ labels9 = np.concatenate(labels9, 0)
820
+ labels9[:, [1, 3]] -= xc
821
+ labels9[:, [2, 4]] -= yc
822
+ c = np.array([xc, yc]) # centers
823
+ segments9 = [x - c for x in segments9]
824
+
825
+ for x in (labels9[:, 1:], *segments9):
826
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
827
+ # img9, labels9 = replicate(img9, labels9) # replicate
828
+
829
+ # Augment
830
+ #img9, labels9, segments9 = remove_background(img9, labels9, segments9)
831
+ img9, labels9, segments9 = copy_paste(img9, labels9, segments9, probability=self.hyp['copy_paste'])
832
+ img9, labels9 = random_perspective(img9, labels9, segments9,
833
+ degrees=self.hyp['degrees'],
834
+ translate=self.hyp['translate'],
835
+ scale=self.hyp['scale'],
836
+ shear=self.hyp['shear'],
837
+ perspective=self.hyp['perspective'],
838
+ border=self.mosaic_border) # border to remove
839
+
840
+ return img9, labels9
841
+
842
+
843
+ def load_samples(self, index):
844
+ # loads images in a 4-mosaic
845
+
846
+ labels4, segments4 = [], []
847
+ s = self.img_size
848
+ yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y
849
+ indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
850
+ for i, index in enumerate(indices):
851
+ # Load image
852
+ img, _, (h, w) = load_image(self, index)
853
+
854
+ # place img in img4
855
+ if i == 0: # top left
856
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
857
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
858
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
859
+ elif i == 1: # top right
860
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
861
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
862
+ elif i == 2: # bottom left
863
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
864
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
865
+ elif i == 3: # bottom right
866
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
867
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
868
+
869
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
870
+ padw = x1a - x1b
871
+ padh = y1a - y1b
872
+
873
+ # Labels
874
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
875
+ if labels.size:
876
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
877
+ segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
878
+ labels4.append(labels)
879
+ segments4.extend(segments)
880
+
881
+ # Concat/clip labels
882
+ labels4 = np.concatenate(labels4, 0)
883
+ for x in (labels4[:, 1:], *segments4):
884
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
885
+ # img4, labels4 = replicate(img4, labels4) # replicate
886
+
887
+ # Augment
888
+ #img4, labels4, segments4 = remove_background(img4, labels4, segments4)
889
+ sample_labels, sample_images, sample_masks = sample_segments(img4, labels4, segments4, probability=0.5)
890
+
891
+ return sample_labels, sample_images, sample_masks
892
+
893
+
894
+ def copy_paste(img, labels, segments, probability=0.5):
895
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
896
+ n = len(segments)
897
+ if probability and n:
898
+ h, w, c = img.shape # height, width, channels
899
+ im_new = np.zeros(img.shape, np.uint8)
900
+ for j in random.sample(range(n), k=round(probability * n)):
901
+ l, s = labels[j], segments[j]
902
+ box = w - l[3], l[2], w - l[1], l[4]
903
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
904
+ if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
905
+ labels = np.concatenate((labels, [[l[0], *box]]), 0)
906
+ segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
907
+ cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
908
+
909
+ result = cv2.bitwise_and(src1=img, src2=im_new)
910
+ result = cv2.flip(result, 1) # augment segments (flip left-right)
911
+ i = result > 0 # pixels to replace
912
+ # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch
913
+ img[i] = result[i] # cv2.imwrite('debug.jpg', img) # debug
914
+
915
+ return img, labels, segments
916
+
917
+
918
+ def remove_background(img, labels, segments):
919
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
920
+ n = len(segments)
921
+ h, w, c = img.shape # height, width, channels
922
+ im_new = np.zeros(img.shape, np.uint8)
923
+ img_new = np.ones(img.shape, np.uint8) * 114
924
+ for j in range(n):
925
+ cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
926
+
927
+ result = cv2.bitwise_and(src1=img, src2=im_new)
928
+
929
+ i = result > 0 # pixels to replace
930
+ img_new[i] = result[i] # cv2.imwrite('debug.jpg', img) # debug
931
+
932
+ return img_new, labels, segments
933
+
934
+
935
+ def sample_segments(img, labels, segments, probability=0.5):
936
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
937
+ n = len(segments)
938
+ sample_labels = []
939
+ sample_images = []
940
+ sample_masks = []
941
+ if probability and n:
942
+ h, w, c = img.shape # height, width, channels
943
+ for j in random.sample(range(n), k=round(probability * n)):
944
+ l, s = labels[j], segments[j]
945
+ box = l[1].astype(int).clip(0,w-1), l[2].astype(int).clip(0,h-1), l[3].astype(int).clip(0,w-1), l[4].astype(int).clip(0,h-1)
946
+
947
+ #print(box)
948
+ if (box[2] <= box[0]) or (box[3] <= box[1]):
949
+ continue
950
+
951
+ sample_labels.append(l[0])
952
+
953
+ mask = np.zeros(img.shape, np.uint8)
954
+
955
+ cv2.drawContours(mask, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
956
+ sample_masks.append(mask[box[1]:box[3],box[0]:box[2],:])
957
+
958
+ result = cv2.bitwise_and(src1=img, src2=mask)
959
+ i = result > 0 # pixels to replace
960
+ mask[i] = result[i] # cv2.imwrite('debug.jpg', img) # debug
961
+ #print(box)
962
+ sample_images.append(mask[box[1]:box[3],box[0]:box[2],:])
963
+
964
+ return sample_labels, sample_images, sample_masks
965
+
966
+
967
+ def replicate(img, labels):
968
+ # Replicate labels
969
+ h, w = img.shape[:2]
970
+ boxes = labels[:, 1:].astype(int)
971
+ x1, y1, x2, y2 = boxes.T
972
+ s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
973
+ for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
974
+ x1b, y1b, x2b, y2b = boxes[i]
975
+ bh, bw = y2b - y1b, x2b - x1b
976
+ yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
977
+ x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
978
+ img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
979
+ labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
980
+
981
+ return img, labels
982
+
983
+
984
+ def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
985
+ # Resize and pad image while meeting stride-multiple constraints
986
+ shape = img.shape[:2] # current shape [height, width]
987
+ if isinstance(new_shape, int):
988
+ new_shape = (new_shape, new_shape)
989
+
990
+ # Scale ratio (new / old)
991
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
992
+ if not scaleup: # only scale down, do not scale up (for better test mAP)
993
+ r = min(r, 1.0)
994
+
995
+ # Compute padding
996
+ ratio = r, r # width, height ratios
997
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
998
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
999
+ if auto: # minimum rectangle
1000
+ dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
1001
+ elif scaleFill: # stretch
1002
+ dw, dh = 0.0, 0.0
1003
+ new_unpad = (new_shape[1], new_shape[0])
1004
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
1005
+
1006
+ dw /= 2 # divide padding into 2 sides
1007
+ dh /= 2
1008
+
1009
+ if shape[::-1] != new_unpad: # resize
1010
+ img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
1011
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
1012
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
1013
+ img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
1014
+ return img, ratio, (dw, dh)
1015
+
1016
+
1017
+ def random_perspective(img, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,
1018
+ border=(0, 0)):
1019
+ # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
1020
+ # targets = [cls, xyxy]
1021
+
1022
+ height = img.shape[0] + border[0] * 2 # shape(h,w,c)
1023
+ width = img.shape[1] + border[1] * 2
1024
+
1025
+ # Center
1026
+ C = np.eye(3)
1027
+ C[0, 2] = -img.shape[1] / 2 # x translation (pixels)
1028
+ C[1, 2] = -img.shape[0] / 2 # y translation (pixels)
1029
+
1030
+ # Perspective
1031
+ P = np.eye(3)
1032
+ P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
1033
+ P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
1034
+
1035
+ # Rotation and Scale
1036
+ R = np.eye(3)
1037
+ a = random.uniform(-degrees, degrees)
1038
+ # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
1039
+ s = random.uniform(1 - scale, 1.1 + scale)
1040
+ # s = 2 ** random.uniform(-scale, scale)
1041
+ R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
1042
+
1043
+ # Shear
1044
+ S = np.eye(3)
1045
+ S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
1046
+ S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
1047
+
1048
+ # Translation
1049
+ T = np.eye(3)
1050
+ T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
1051
+ T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
1052
+
1053
+ # Combined rotation matrix
1054
+ M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
1055
+ if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
1056
+ if perspective:
1057
+ img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))
1058
+ else: # affine
1059
+ img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
1060
+
1061
+ # Visualize
1062
+ # import matplotlib.pyplot as plt
1063
+ # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
1064
+ # ax[0].imshow(img[:, :, ::-1]) # base
1065
+ # ax[1].imshow(img2[:, :, ::-1]) # warped
1066
+
1067
+ # Transform label coordinates
1068
+ n = len(targets)
1069
+ if n:
1070
+ use_segments = any(x.any() for x in segments)
1071
+ new = np.zeros((n, 4))
1072
+ if use_segments: # warp segments
1073
+ segments = resample_segments(segments) # upsample
1074
+ for i, segment in enumerate(segments):
1075
+ xy = np.ones((len(segment), 3))
1076
+ xy[:, :2] = segment
1077
+ xy = xy @ M.T # transform
1078
+ xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
1079
+
1080
+ # clip
1081
+ new[i] = segment2box(xy, width, height)
1082
+
1083
+ else: # warp boxes
1084
+ xy = np.ones((n * 4, 3))
1085
+ xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
1086
+ xy = xy @ M.T # transform
1087
+ xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
1088
+
1089
+ # create new boxes
1090
+ x = xy[:, [0, 2, 4, 6]]
1091
+ y = xy[:, [1, 3, 5, 7]]
1092
+ new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
1093
+
1094
+ # clip
1095
+ new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
1096
+ new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
1097
+
1098
+ # filter candidates
1099
+ i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
1100
+ targets = targets[i]
1101
+ targets[:, 1:5] = new[i]
1102
+
1103
+ return img, targets
1104
+
1105
+
1106
+ def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
1107
+ # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
1108
+ w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
1109
+ w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
1110
+ ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
1111
+ return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
1112
+
1113
+
1114
+ def bbox_ioa(box1, box2):
1115
+ # Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2
1116
+ box2 = box2.transpose()
1117
+
1118
+ # Get the coordinates of bounding boxes
1119
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
1120
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
1121
+
1122
+ # Intersection area
1123
+ inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
1124
+ (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
1125
+
1126
+ # box2 area
1127
+ box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16
1128
+
1129
+ # Intersection over box2 area
1130
+ return inter_area / box2_area
1131
+
1132
+
1133
+ def cutout(image, labels):
1134
+ # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
1135
+ h, w = image.shape[:2]
1136
+
1137
+ # create random masks
1138
+ scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
1139
+ for s in scales:
1140
+ mask_h = random.randint(1, int(h * s))
1141
+ mask_w = random.randint(1, int(w * s))
1142
+
1143
+ # box
1144
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
1145
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
1146
+ xmax = min(w, xmin + mask_w)
1147
+ ymax = min(h, ymin + mask_h)
1148
+
1149
+ # apply random color mask
1150
+ image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
1151
+
1152
+ # return unobscured labels
1153
+ if len(labels) and s > 0.03:
1154
+ box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
1155
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
1156
+ labels = labels[ioa < 0.60] # remove >60% obscured labels
1157
+
1158
+ return labels
1159
+
1160
+
1161
+ def pastein(image, labels, sample_labels, sample_images, sample_masks):
1162
+ # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
1163
+ h, w = image.shape[:2]
1164
+
1165
+ # create random masks
1166
+ scales = [0.75] * 2 + [0.5] * 4 + [0.25] * 4 + [0.125] * 4 + [0.0625] * 6 # image size fraction
1167
+ for s in scales:
1168
+ if random.random() < 0.2:
1169
+ continue
1170
+ mask_h = random.randint(1, int(h * s))
1171
+ mask_w = random.randint(1, int(w * s))
1172
+
1173
+ # box
1174
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
1175
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
1176
+ xmax = min(w, xmin + mask_w)
1177
+ ymax = min(h, ymin + mask_h)
1178
+
1179
+ box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
1180
+ if len(labels):
1181
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
1182
+ else:
1183
+ ioa = np.zeros(1)
1184
+
1185
+ if (ioa < 0.30).all() and len(sample_labels) and (xmax > xmin+20) and (ymax > ymin+20): # allow 30% obscuration of existing labels
1186
+ sel_ind = random.randint(0, len(sample_labels)-1)
1187
+ #print(len(sample_labels))
1188
+ #print(sel_ind)
1189
+ #print((xmax-xmin, ymax-ymin))
1190
+ #print(image[ymin:ymax, xmin:xmax].shape)
1191
+ #print([[sample_labels[sel_ind], *box]])
1192
+ #print(labels.shape)
1193
+ hs, ws, cs = sample_images[sel_ind].shape
1194
+ r_scale = min((ymax-ymin)/hs, (xmax-xmin)/ws)
1195
+ r_w = int(ws*r_scale)
1196
+ r_h = int(hs*r_scale)
1197
+
1198
+ if (r_w > 10) and (r_h > 10):
1199
+ r_mask = cv2.resize(sample_masks[sel_ind], (r_w, r_h))
1200
+ r_image = cv2.resize(sample_images[sel_ind], (r_w, r_h))
1201
+ temp_crop = image[ymin:ymin+r_h, xmin:xmin+r_w]
1202
+ m_ind = r_mask > 0
1203
+ if m_ind.astype(np.int).sum() > 60:
1204
+ temp_crop[m_ind] = r_image[m_ind]
1205
+ #print(sample_labels[sel_ind])
1206
+ #print(sample_images[sel_ind].shape)
1207
+ #print(temp_crop.shape)
1208
+ box = np.array([xmin, ymin, xmin+r_w, ymin+r_h], dtype=np.float32)
1209
+ if len(labels):
1210
+ labels = np.concatenate((labels, [[sample_labels[sel_ind], *box]]), 0)
1211
+ else:
1212
+ labels = np.array([[sample_labels[sel_ind], *box]])
1213
+
1214
+ image[ymin:ymin+r_h, xmin:xmin+r_w] = temp_crop
1215
+
1216
+ return labels
1217
+
1218
+ class Albumentations:
1219
+ # YOLOv5 Albumentations class (optional, only used if package is installed)
1220
+ def __init__(self):
1221
+ self.transform = None
1222
+ import albumentations as A
1223
+
1224
+ self.transform = A.Compose([
1225
+ A.CLAHE(p=0.01),
1226
+ A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.01),
1227
+ A.RandomGamma(gamma_limit=[80, 120], p=0.01),
1228
+ A.Blur(p=0.01),
1229
+ A.MedianBlur(p=0.01),
1230
+ A.ToGray(p=0.01),
1231
+ A.ImageCompression(quality_lower=75, p=0.01),],
1232
+ bbox_params=A.BboxParams(format='pascal_voc', label_fields=['class_labels']))
1233
+
1234
+ #logging.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p))
1235
+
1236
+ def __call__(self, im, labels, p=1.0):
1237
+ if self.transform and random.random() < p:
1238
+ new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
1239
+ im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])
1240
+ return im, labels
1241
+
1242
+
1243
+ def create_folder(path='./new'):
1244
+ # Create folder
1245
+ if os.path.exists(path):
1246
+ shutil.rmtree(path) # delete output folder
1247
+ os.makedirs(path) # make new output folder
1248
+
1249
+
1250
+ def flatten_recursive(path='../coco'):
1251
+ # Flatten a recursive directory by bringing all files to top level
1252
+ new_path = Path(path + '_flat')
1253
+ create_folder(new_path)
1254
+ for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):
1255
+ shutil.copyfile(file, new_path / Path(file).name)
1256
+
1257
+
1258
+ def extract_boxes(path='../coco/'): # from utils.datasets import *; extract_boxes('../coco128')
1259
+ # Convert detection dataset into classification dataset, with one directory per class
1260
+
1261
+ path = Path(path) # images dir
1262
+ shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing
1263
+ files = list(path.rglob('*.*'))
1264
+ n = len(files) # number of files
1265
+ for im_file in tqdm(files, total=n):
1266
+ if im_file.suffix[1:] in img_formats:
1267
+ # image
1268
+ im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
1269
+ h, w = im.shape[:2]
1270
+
1271
+ # labels
1272
+ lb_file = Path(img2label_paths([str(im_file)])[0])
1273
+ if Path(lb_file).exists():
1274
+ with open(lb_file, 'r') as f:
1275
+ lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
1276
+
1277
+ for j, x in enumerate(lb):
1278
+ c = int(x[0]) # class
1279
+ f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
1280
+ if not f.parent.is_dir():
1281
+ f.parent.mkdir(parents=True)
1282
+
1283
+ b = x[1:] * [w, h, w, h] # box
1284
+ # b[2:] = b[2:].max() # rectangle to square
1285
+ b[2:] = b[2:] * 1.2 + 3 # pad
1286
+ b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
1287
+
1288
+ b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
1289
+ b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
1290
+ assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
1291
+
1292
+
1293
+ def autosplit(path='../coco', weights=(0.9, 0.1, 0.0), annotated_only=False):
1294
+ """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files
1295
+ Usage: from utils.datasets import *; autosplit('../coco')
1296
+ Arguments
1297
+ path: Path to images directory
1298
+ weights: Train, val, test weights (list)
1299
+ annotated_only: Only use images with an annotated txt file
1300
+ """
1301
+ path = Path(path) # images dir
1302
+ files = sum([list(path.rglob(f"*.{img_ext}")) for img_ext in img_formats], []) # image files only
1303
+ n = len(files) # number of files
1304
+ indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
1305
+
1306
+ txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
1307
+ [(path / x).unlink() for x in txt if (path / x).exists()] # remove existing
1308
+
1309
+ print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
1310
+ for i, img in tqdm(zip(indices, files), total=n):
1311
+ if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
1312
+ with open(path / txt[i], 'a') as f:
1313
+ f.write(str(img) + '\n') # add image to txt file
1314
+
1315
+
1316
+ def load_segmentations(self, index):
1317
+ key = '/work/handsomejw66/coco17/' + self.img_files[index]
1318
+ #print(key)
1319
+ # /work/handsomejw66/coco17/
1320
+ return self.segs[key]
utils/general.py ADDED
@@ -0,0 +1,790 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOR general utils
2
+
3
+ import glob
4
+ import logging
5
+ import math
6
+ import os
7
+ import platform
8
+ import random
9
+ import re
10
+ import subprocess
11
+ import time
12
+ from pathlib import Path
13
+
14
+ import cv2
15
+ import numpy as np
16
+ import pandas as pd
17
+ import torch
18
+ import torchvision
19
+ import yaml
20
+
21
+ from utils.google_utils import gsutil_getsize
22
+ from utils.metrics import fitness
23
+ from utils.torch_utils import init_torch_seeds
24
+
25
+ # Settings
26
+ torch.set_printoptions(linewidth=320, precision=5, profile='long')
27
+ np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
28
+ pd.options.display.max_columns = 10
29
+ cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
30
+ os.environ['NUMEXPR_MAX_THREADS'] = str(min(os.cpu_count(), 8)) # NumExpr max threads
31
+
32
+
33
+ def set_logging(rank=-1):
34
+ logging.basicConfig(
35
+ format="%(message)s",
36
+ level=logging.INFO if rank in [-1, 0] else logging.WARN)
37
+
38
+
39
+ def init_seeds(seed=0):
40
+ # Initialize random number generator (RNG) seeds
41
+ random.seed(seed)
42
+ np.random.seed(seed)
43
+ init_torch_seeds(seed)
44
+
45
+
46
+ def get_latest_run(search_dir='.'):
47
+ # Return path to most recent 'last.pt' in /runs (i.e. to --resume from)
48
+ last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)
49
+ return max(last_list, key=os.path.getctime) if last_list else ''
50
+
51
+
52
+ def isdocker():
53
+ # Is environment a Docker container
54
+ return Path('/workspace').exists() # or Path('/.dockerenv').exists()
55
+
56
+
57
+ def emojis(str=''):
58
+ # Return platform-dependent emoji-safe version of string
59
+ return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str
60
+
61
+
62
+ def check_online():
63
+ # Check internet connectivity
64
+ import socket
65
+ try:
66
+ socket.create_connection(("1.1.1.1", 443), 5) # check host accesability
67
+ return True
68
+ except OSError:
69
+ return False
70
+
71
+
72
+ def check_git_status():
73
+ # Recommend 'git pull' if code is out of date
74
+ print(colorstr('github: '), end='')
75
+ try:
76
+ assert Path('.git').exists(), 'skipping check (not a git repository)'
77
+ assert not isdocker(), 'skipping check (Docker image)'
78
+ assert check_online(), 'skipping check (offline)'
79
+
80
+ cmd = 'git fetch && git config --get remote.origin.url'
81
+ url = subprocess.check_output(cmd, shell=True).decode().strip().rstrip('.git') # github repo url
82
+ branch = subprocess.check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out
83
+ n = int(subprocess.check_output(f'git rev-list {branch}..origin/master --count', shell=True)) # commits behind
84
+ if n > 0:
85
+ s = f"⚠️ WARNING: code is out of date by {n} commit{'s' * (n > 1)}. " \
86
+ f"Use 'git pull' to update or 'git clone {url}' to download latest."
87
+ else:
88
+ s = f'up to date with {url} ✅'
89
+ print(emojis(s)) # emoji-safe
90
+ except Exception as e:
91
+ print(e)
92
+
93
+
94
+ def check_requirements(requirements='requirements.txt', exclude=()):
95
+ # Check installed dependencies meet requirements (pass *.txt file or list of packages)
96
+ import pkg_resources as pkg
97
+ prefix = colorstr('red', 'bold', 'requirements:')
98
+ if isinstance(requirements, (str, Path)): # requirements.txt file
99
+ file = Path(requirements)
100
+ if not file.exists():
101
+ print(f"{prefix} {file.resolve()} not found, check failed.")
102
+ return
103
+ requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(file.open()) if x.name not in exclude]
104
+ else: # list or tuple of packages
105
+ requirements = [x for x in requirements if x not in exclude]
106
+
107
+ n = 0 # number of packages updates
108
+ for r in requirements:
109
+ try:
110
+ pkg.require(r)
111
+ except Exception as e: # DistributionNotFound or VersionConflict if requirements not met
112
+ n += 1
113
+ print(f"{prefix} {e.req} not found and is required by YOLOR, attempting auto-update...")
114
+ print(subprocess.check_output(f"pip install '{e.req}'", shell=True).decode())
115
+
116
+ if n: # if packages updated
117
+ source = file.resolve() if 'file' in locals() else requirements
118
+ s = f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" \
119
+ f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n"
120
+ print(emojis(s)) # emoji-safe
121
+
122
+
123
+ def check_img_size(img_size, s=32):
124
+ # Verify img_size is a multiple of stride s
125
+ new_size = make_divisible(img_size, int(s)) # ceil gs-multiple
126
+ if new_size != img_size:
127
+ print('WARNING: --img-size %g must be multiple of max stride %g, updating to %g' % (img_size, s, new_size))
128
+ return new_size
129
+
130
+
131
+ def check_imshow():
132
+ # Check if environment supports image displays
133
+ try:
134
+ assert not isdocker(), 'cv2.imshow() is disabled in Docker environments'
135
+ cv2.imshow('test', np.zeros((1, 1, 3)))
136
+ cv2.waitKey(1)
137
+ cv2.destroyAllWindows()
138
+ cv2.waitKey(1)
139
+ return True
140
+ except Exception as e:
141
+ print(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}')
142
+ return False
143
+
144
+
145
+ def check_file(file):
146
+ # Search for file if not found
147
+ if Path(file).is_file() or file == '':
148
+ return file
149
+ else:
150
+ files = glob.glob('./**/' + file, recursive=True) # find file
151
+ assert len(files), f'File Not Found: {file}' # assert file was found
152
+ assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique
153
+ return files[0] # return file
154
+
155
+
156
+ def check_dataset(dict):
157
+ # Download dataset if not found locally
158
+ val, s = dict.get('val'), dict.get('download')
159
+ if val and len(val):
160
+ val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path
161
+ if not all(x.exists() for x in val):
162
+ print('\nWARNING: Dataset not found, nonexistent paths: %s' % [str(x) for x in val if not x.exists()])
163
+ if s and len(s): # download script
164
+ print('Downloading %s ...' % s)
165
+ if s.startswith('http') and s.endswith('.zip'): # URL
166
+ f = Path(s).name # filename
167
+ torch.hub.download_url_to_file(s, f)
168
+ r = os.system('unzip -q %s -d ../ && rm %s' % (f, f)) # unzip
169
+ else: # bash script
170
+ r = os.system(s)
171
+ print('Dataset autodownload %s\n' % ('success' if r == 0 else 'failure')) # analyze return value
172
+ else:
173
+ raise Exception('Dataset not found.')
174
+
175
+
176
+ def make_divisible(x, divisor):
177
+ # Returns x evenly divisible by divisor
178
+ return math.ceil(x / divisor) * divisor
179
+
180
+
181
+ def clean_str(s):
182
+ # Cleans a string by replacing special characters with underscore _
183
+ return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s)
184
+
185
+
186
+ def one_cycle(y1=0.0, y2=1.0, steps=100):
187
+ # lambda function for sinusoidal ramp from y1 to y2
188
+ return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1
189
+
190
+
191
+ def colorstr(*input):
192
+ # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')
193
+ *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string
194
+ colors = {'black': '\033[30m', # basic colors
195
+ 'red': '\033[31m',
196
+ 'green': '\033[32m',
197
+ 'yellow': '\033[33m',
198
+ 'blue': '\033[34m',
199
+ 'magenta': '\033[35m',
200
+ 'cyan': '\033[36m',
201
+ 'white': '\033[37m',
202
+ 'bright_black': '\033[90m', # bright colors
203
+ 'bright_red': '\033[91m',
204
+ 'bright_green': '\033[92m',
205
+ 'bright_yellow': '\033[93m',
206
+ 'bright_blue': '\033[94m',
207
+ 'bright_magenta': '\033[95m',
208
+ 'bright_cyan': '\033[96m',
209
+ 'bright_white': '\033[97m',
210
+ 'end': '\033[0m', # misc
211
+ 'bold': '\033[1m',
212
+ 'underline': '\033[4m'}
213
+ return ''.join(colors[x] for x in args) + f'{string}' + colors['end']
214
+
215
+
216
+ def labels_to_class_weights(labels, nc=80):
217
+ # Get class weights (inverse frequency) from training labels
218
+ if labels[0] is None: # no labels loaded
219
+ return torch.Tensor()
220
+
221
+ labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
222
+ classes = labels[:, 0].astype(np.int) # labels = [class xywh]
223
+ weights = np.bincount(classes, minlength=nc) # occurrences per class
224
+
225
+ # Prepend gridpoint count (for uCE training)
226
+ # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
227
+ # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
228
+
229
+ weights[weights == 0] = 1 # replace empty bins with 1
230
+ weights = 1 / weights # number of targets per class
231
+ weights /= weights.sum() # normalize
232
+ return torch.from_numpy(weights)
233
+
234
+
235
+ def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
236
+ # Produces image weights based on class_weights and image contents
237
+ class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels])
238
+ image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1)
239
+ # index = random.choices(range(n), weights=image_weights, k=1) # weight image sample
240
+ return image_weights
241
+
242
+
243
+ def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
244
+ # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
245
+ # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
246
+ # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
247
+ # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
248
+ # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
249
+ x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
250
+ 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
251
+ 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
252
+ return x
253
+
254
+
255
+ def xyxy2xywh(x):
256
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
257
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
258
+ y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
259
+ y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
260
+ y[:, 2] = x[:, 2] - x[:, 0] # width
261
+ y[:, 3] = x[:, 3] - x[:, 1] # height
262
+ return y
263
+
264
+
265
+ def xywh2xyxy(x):
266
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
267
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
268
+ y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
269
+ y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
270
+ y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
271
+ y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
272
+ return y
273
+
274
+
275
+ def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
276
+ # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
277
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
278
+ y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw # top left x
279
+ y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh # top left y
280
+ y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw # bottom right x
281
+ y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh # bottom right y
282
+ return y
283
+
284
+
285
+ def xyn2xy(x, w=640, h=640, padw=0, padh=0):
286
+ # Convert normalized segments into pixel segments, shape (n,2)
287
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
288
+ y[:, 0] = w * x[:, 0] + padw # top left x
289
+ y[:, 1] = h * x[:, 1] + padh # top left y
290
+ return y
291
+
292
+
293
+ def segment2box(segment, width=640, height=640):
294
+ # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)
295
+ x, y = segment.T # segment xy
296
+ inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)
297
+ x, y, = x[inside], y[inside]
298
+ return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy
299
+
300
+
301
+ def segments2boxes(segments):
302
+ # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)
303
+ boxes = []
304
+ for s in segments:
305
+ x, y = s.T # segment xy
306
+ boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy
307
+ return xyxy2xywh(np.array(boxes)) # cls, xywh
308
+
309
+
310
+ def resample_segments(segments, n=1000):
311
+ # Up-sample an (n,2) segment
312
+ for i, s in enumerate(segments):
313
+ x = np.linspace(0, len(s) - 1, n)
314
+ xp = np.arange(len(s))
315
+ segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy
316
+ return segments
317
+
318
+
319
+ def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
320
+ # Rescale coords (xyxy) from img1_shape to img0_shape
321
+ if ratio_pad is None: # calculate from img0_shape
322
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
323
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
324
+ else:
325
+ gain = ratio_pad[0][0]
326
+ pad = ratio_pad[1]
327
+
328
+ coords[:, [0, 2]] -= pad[0] # x padding
329
+ coords[:, [1, 3]] -= pad[1] # y padding
330
+ coords[:, :4] /= gain
331
+ clip_coords(coords, img0_shape)
332
+ return coords
333
+
334
+
335
+ def clip_coords(boxes, img_shape):
336
+ # Clip bounding xyxy bounding boxes to image shape (height, width)
337
+ boxes[:, 0].clamp_(0, img_shape[1]) # x1
338
+ boxes[:, 1].clamp_(0, img_shape[0]) # y1
339
+ boxes[:, 2].clamp_(0, img_shape[1]) # x2
340
+ boxes[:, 3].clamp_(0, img_shape[0]) # y2
341
+
342
+
343
+ def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
344
+ # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
345
+ box2 = box2.T
346
+
347
+ # Get the coordinates of bounding boxes
348
+ if x1y1x2y2: # x1, y1, x2, y2 = box1
349
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
350
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
351
+ else: # transform from xywh to xyxy
352
+ b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
353
+ b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
354
+ b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
355
+ b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
356
+
357
+ # Intersection area
358
+ inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
359
+ (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
360
+
361
+ # Union Area
362
+ w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
363
+ w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
364
+ union = w1 * h1 + w2 * h2 - inter + eps
365
+
366
+ iou = inter / union
367
+
368
+ if GIoU or DIoU or CIoU:
369
+ cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
370
+ ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
371
+ if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
372
+ c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
373
+ rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 +
374
+ (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared
375
+ if DIoU:
376
+ return iou - rho2 / c2 # DIoU
377
+ elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
378
+ v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
379
+ with torch.no_grad():
380
+ alpha = v / (v - iou + (1 + eps))
381
+ return iou - (rho2 / c2 + v * alpha) # CIoU
382
+ else: # GIoU https://arxiv.org/pdf/1902.09630.pdf
383
+ c_area = cw * ch + eps # convex area
384
+ return iou - (c_area - union) / c_area # GIoU
385
+ else:
386
+ return iou # IoU
387
+
388
+
389
+
390
+
391
+ def bbox_alpha_iou(box1, box2, x1y1x2y2=False, GIoU=False, DIoU=False, CIoU=False, alpha=2, eps=1e-9):
392
+ # Returns tsqrt_he IoU of box1 to box2. box1 is 4, box2 is nx4
393
+ box2 = box2.T
394
+
395
+ # Get the coordinates of bounding boxes
396
+ if x1y1x2y2: # x1, y1, x2, y2 = box1
397
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
398
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
399
+ else: # transform from xywh to xyxy
400
+ b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
401
+ b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
402
+ b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
403
+ b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
404
+
405
+ # Intersection area
406
+ inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
407
+ (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
408
+
409
+ # Union Area
410
+ w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
411
+ w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
412
+ union = w1 * h1 + w2 * h2 - inter + eps
413
+
414
+ # change iou into pow(iou+eps)
415
+ # iou = inter / union
416
+ iou = torch.pow(inter/union + eps, alpha)
417
+ # beta = 2 * alpha
418
+ if GIoU or DIoU or CIoU:
419
+ cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
420
+ ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
421
+ if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
422
+ c2 = (cw ** 2 + ch ** 2) ** alpha + eps # convex diagonal
423
+ rho_x = torch.abs(b2_x1 + b2_x2 - b1_x1 - b1_x2)
424
+ rho_y = torch.abs(b2_y1 + b2_y2 - b1_y1 - b1_y2)
425
+ rho2 = ((rho_x ** 2 + rho_y ** 2) / 4) ** alpha # center distance
426
+ if DIoU:
427
+ return iou - rho2 / c2 # DIoU
428
+ elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
429
+ v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
430
+ with torch.no_grad():
431
+ alpha_ciou = v / ((1 + eps) - inter / union + v)
432
+ # return iou - (rho2 / c2 + v * alpha_ciou) # CIoU
433
+ return iou - (rho2 / c2 + torch.pow(v * alpha_ciou + eps, alpha)) # CIoU
434
+ else: # GIoU https://arxiv.org/pdf/1902.09630.pdf
435
+ # c_area = cw * ch + eps # convex area
436
+ # return iou - (c_area - union) / c_area # GIoU
437
+ c_area = torch.max(cw * ch + eps, union) # convex area
438
+ return iou - torch.pow((c_area - union) / c_area + eps, alpha) # GIoU
439
+ else:
440
+ return iou # torch.log(iou+eps) or iou
441
+
442
+
443
+ def box_iou(box1, box2):
444
+ # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
445
+ """
446
+ Return intersection-over-union (Jaccard index) of boxes.
447
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
448
+ Arguments:
449
+ box1 (Tensor[N, 4])
450
+ box2 (Tensor[M, 4])
451
+ Returns:
452
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
453
+ IoU values for every element in boxes1 and boxes2
454
+ """
455
+
456
+ def box_area(box):
457
+ # box = 4xn
458
+ return (box[2] - box[0]) * (box[3] - box[1])
459
+
460
+ area1 = box_area(box1.T)
461
+ area2 = box_area(box2.T)
462
+
463
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
464
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
465
+ return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
466
+
467
+
468
+ def wh_iou(wh1, wh2):
469
+ # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
470
+ wh1 = wh1[:, None] # [N,1,2]
471
+ wh2 = wh2[None] # [1,M,2]
472
+ inter = torch.min(wh1, wh2).prod(2) # [N,M]
473
+ return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter)
474
+
475
+
476
+ def box_giou(box1, box2):
477
+ """
478
+ Return generalized intersection-over-union (Jaccard index) between two sets of boxes.
479
+ Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
480
+ ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
481
+ Args:
482
+ boxes1 (Tensor[N, 4]): first set of boxes
483
+ boxes2 (Tensor[M, 4]): second set of boxes
484
+ Returns:
485
+ Tensor[N, M]: the NxM matrix containing the pairwise generalized IoU values
486
+ for every element in boxes1 and boxes2
487
+ """
488
+
489
+ def box_area(box):
490
+ # box = 4xn
491
+ return (box[2] - box[0]) * (box[3] - box[1])
492
+
493
+ area1 = box_area(box1.T)
494
+ area2 = box_area(box2.T)
495
+
496
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
497
+ union = (area1[:, None] + area2 - inter)
498
+
499
+ iou = inter / union
500
+
501
+ lti = torch.min(box1[:, None, :2], box2[:, :2])
502
+ rbi = torch.max(box1[:, None, 2:], box2[:, 2:])
503
+
504
+ whi = (rbi - lti).clamp(min=0) # [N,M,2]
505
+ areai = whi[:, :, 0] * whi[:, :, 1]
506
+
507
+ return iou - (areai - union) / areai
508
+
509
+
510
+ def box_ciou(box1, box2, eps: float = 1e-7):
511
+ """
512
+ Return complete intersection-over-union (Jaccard index) between two sets of boxes.
513
+ Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
514
+ ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
515
+ Args:
516
+ boxes1 (Tensor[N, 4]): first set of boxes
517
+ boxes2 (Tensor[M, 4]): second set of boxes
518
+ eps (float, optional): small number to prevent division by zero. Default: 1e-7
519
+ Returns:
520
+ Tensor[N, M]: the NxM matrix containing the pairwise complete IoU values
521
+ for every element in boxes1 and boxes2
522
+ """
523
+
524
+ def box_area(box):
525
+ # box = 4xn
526
+ return (box[2] - box[0]) * (box[3] - box[1])
527
+
528
+ area1 = box_area(box1.T)
529
+ area2 = box_area(box2.T)
530
+
531
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
532
+ union = (area1[:, None] + area2 - inter)
533
+
534
+ iou = inter / union
535
+
536
+ lti = torch.min(box1[:, None, :2], box2[:, :2])
537
+ rbi = torch.max(box1[:, None, 2:], box2[:, 2:])
538
+
539
+ whi = (rbi - lti).clamp(min=0) # [N,M,2]
540
+ diagonal_distance_squared = (whi[:, :, 0] ** 2) + (whi[:, :, 1] ** 2) + eps
541
+
542
+ # centers of boxes
543
+ x_p = (box1[:, None, 0] + box1[:, None, 2]) / 2
544
+ y_p = (box1[:, None, 1] + box1[:, None, 3]) / 2
545
+ x_g = (box2[:, 0] + box2[:, 2]) / 2
546
+ y_g = (box2[:, 1] + box2[:, 3]) / 2
547
+ # The distance between boxes' centers squared.
548
+ centers_distance_squared = (x_p - x_g) ** 2 + (y_p - y_g) ** 2
549
+
550
+ w_pred = box1[:, None, 2] - box1[:, None, 0]
551
+ h_pred = box1[:, None, 3] - box1[:, None, 1]
552
+
553
+ w_gt = box2[:, 2] - box2[:, 0]
554
+ h_gt = box2[:, 3] - box2[:, 1]
555
+
556
+ v = (4 / (torch.pi ** 2)) * torch.pow((torch.atan(w_gt / h_gt) - torch.atan(w_pred / h_pred)), 2)
557
+ with torch.no_grad():
558
+ alpha = v / (1 - iou + v + eps)
559
+ return iou - (centers_distance_squared / diagonal_distance_squared) - alpha * v
560
+
561
+
562
+ def box_diou(box1, box2, eps: float = 1e-7):
563
+ """
564
+ Return distance intersection-over-union (Jaccard index) between two sets of boxes.
565
+ Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
566
+ ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
567
+ Args:
568
+ boxes1 (Tensor[N, 4]): first set of boxes
569
+ boxes2 (Tensor[M, 4]): second set of boxes
570
+ eps (float, optional): small number to prevent division by zero. Default: 1e-7
571
+ Returns:
572
+ Tensor[N, M]: the NxM matrix containing the pairwise distance IoU values
573
+ for every element in boxes1 and boxes2
574
+ """
575
+
576
+ def box_area(box):
577
+ # box = 4xn
578
+ return (box[2] - box[0]) * (box[3] - box[1])
579
+
580
+ area1 = box_area(box1.T)
581
+ area2 = box_area(box2.T)
582
+
583
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
584
+ union = (area1[:, None] + area2 - inter)
585
+
586
+ iou = inter / union
587
+
588
+ lti = torch.min(box1[:, None, :2], box2[:, :2])
589
+ rbi = torch.max(box1[:, None, 2:], box2[:, 2:])
590
+
591
+ whi = (rbi - lti).clamp(min=0) # [N,M,2]
592
+ diagonal_distance_squared = (whi[:, :, 0] ** 2) + (whi[:, :, 1] ** 2) + eps
593
+
594
+ # centers of boxes
595
+ x_p = (box1[:, None, 0] + box1[:, None, 2]) / 2
596
+ y_p = (box1[:, None, 1] + box1[:, None, 3]) / 2
597
+ x_g = (box2[:, 0] + box2[:, 2]) / 2
598
+ y_g = (box2[:, 1] + box2[:, 3]) / 2
599
+ # The distance between boxes' centers squared.
600
+ centers_distance_squared = (x_p - x_g) ** 2 + (y_p - y_g) ** 2
601
+
602
+ # The distance IoU is the IoU penalized by a normalized
603
+ # distance between boxes' centers squared.
604
+ return iou - (centers_distance_squared / diagonal_distance_squared)
605
+
606
+
607
+ def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,
608
+ labels=()):
609
+ """Runs Non-Maximum Suppression (NMS) on inference results
610
+
611
+ Returns:
612
+ list of detections, on (n,6) tensor per image [xyxy, conf, cls]
613
+ """
614
+
615
+ nc = prediction.shape[2] - 5 # number of classes
616
+ xc = prediction[..., 4] > conf_thres # candidates
617
+
618
+ # Settings
619
+ min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
620
+ max_det = 300 # maximum number of detections per image
621
+ max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
622
+ time_limit = 10.0 # seconds to quit after
623
+ redundant = True # require redundant detections
624
+ multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
625
+ merge = False # use merge-NMS
626
+
627
+ t = time.time()
628
+ output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]
629
+ for xi, x in enumerate(prediction): # image index, image inference
630
+ # Apply constraints
631
+ # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
632
+ x = x[xc[xi]] # confidence
633
+
634
+ # Cat apriori labels if autolabelling
635
+ if labels and len(labels[xi]):
636
+ l = labels[xi]
637
+ v = torch.zeros((len(l), nc + 5), device=x.device)
638
+ v[:, :4] = l[:, 1:5] # box
639
+ v[:, 4] = 1.0 # conf
640
+ v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls
641
+ x = torch.cat((x, v), 0)
642
+
643
+ # If none remain process next image
644
+ if not x.shape[0]:
645
+ continue
646
+
647
+ # Compute conf
648
+ x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
649
+
650
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
651
+ box = xywh2xyxy(x[:, :4])
652
+
653
+ # Detections matrix nx6 (xyxy, conf, cls)
654
+ if multi_label:
655
+ i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
656
+ x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
657
+ else: # best class only
658
+ conf, j = x[:, 5:].max(1, keepdim=True)
659
+ x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
660
+
661
+ # Filter by class
662
+ if classes is not None:
663
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
664
+
665
+ # Apply finite constraint
666
+ # if not torch.isfinite(x).all():
667
+ # x = x[torch.isfinite(x).all(1)]
668
+
669
+ # Check shape
670
+ n = x.shape[0] # number of boxes
671
+ if not n: # no boxes
672
+ continue
673
+ elif n > max_nms: # excess boxes
674
+ x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence
675
+
676
+ # Batched NMS
677
+ c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
678
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
679
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
680
+ if i.shape[0] > max_det: # limit detections
681
+ i = i[:max_det]
682
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
683
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
684
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
685
+ weights = iou * scores[None] # box weights
686
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
687
+ if redundant:
688
+ i = i[iou.sum(1) > 1] # require redundancy
689
+
690
+ output[xi] = x[i]
691
+ if (time.time() - t) > time_limit:
692
+ print(f'WARNING: NMS time limit {time_limit}s exceeded')
693
+ break # time limit exceeded
694
+
695
+ return output
696
+
697
+
698
+ def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()
699
+ # Strip optimizer from 'f' to finalize training, optionally save as 's'
700
+ x = torch.load(f, map_location=torch.device('cpu'))
701
+ if x.get('ema'):
702
+ x['model'] = x['ema'] # replace model with ema
703
+ for k in 'optimizer', 'training_results', 'wandb_id', 'ema', 'updates': # keys
704
+ x[k] = None
705
+ x['epoch'] = -1
706
+ x['model'].half() # to FP16
707
+ for p in x['model'].parameters():
708
+ p.requires_grad = False
709
+ torch.save(x, s or f)
710
+ mb = os.path.getsize(s or f) / 1E6 # filesize
711
+ print(f"Optimizer stripped from {f},{(' saved as %s,' % s) if s else ''} {mb:.1f}MB")
712
+
713
+
714
+ def print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''):
715
+ # Print mutation results to evolve.txt (for use with train.py --evolve)
716
+ a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys
717
+ b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values
718
+ c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)
719
+ print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c))
720
+
721
+ if bucket:
722
+ url = 'gs://%s/evolve.txt' % bucket
723
+ if gsutil_getsize(url) > (os.path.getsize('evolve.txt') if os.path.exists('evolve.txt') else 0):
724
+ os.system('gsutil cp %s .' % url) # download evolve.txt if larger than local
725
+
726
+ with open('evolve.txt', 'a') as f: # append result
727
+ f.write(c + b + '\n')
728
+ x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows
729
+ x = x[np.argsort(-fitness(x))] # sort
730
+ np.savetxt('evolve.txt', x, '%10.3g') # save sort by fitness
731
+
732
+ # Save yaml
733
+ for i, k in enumerate(hyp.keys()):
734
+ hyp[k] = float(x[0, i + 7])
735
+ with open(yaml_file, 'w') as f:
736
+ results = tuple(x[0, :7])
737
+ c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)
738
+ f.write('# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: ' % len(x) + c + '\n\n')
739
+ yaml.dump(hyp, f, sort_keys=False)
740
+
741
+ if bucket:
742
+ os.system('gsutil cp evolve.txt %s gs://%s' % (yaml_file, bucket)) # upload
743
+
744
+
745
+ def apply_classifier(x, model, img, im0):
746
+ # applies a second stage classifier to yolo outputs
747
+ im0 = [im0] if isinstance(im0, np.ndarray) else im0
748
+ for i, d in enumerate(x): # per image
749
+ if d is not None and len(d):
750
+ d = d.clone()
751
+
752
+ # Reshape and pad cutouts
753
+ b = xyxy2xywh(d[:, :4]) # boxes
754
+ b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square
755
+ b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad
756
+ d[:, :4] = xywh2xyxy(b).long()
757
+
758
+ # Rescale boxes from img_size to im0 size
759
+ scale_coords(img.shape[2:], d[:, :4], im0[i].shape)
760
+
761
+ # Classes
762
+ pred_cls1 = d[:, 5].long()
763
+ ims = []
764
+ for j, a in enumerate(d): # per item
765
+ cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
766
+ im = cv2.resize(cutout, (224, 224)) # BGR
767
+ # cv2.imwrite('test%i.jpg' % j, cutout)
768
+
769
+ im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
770
+ im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32
771
+ im /= 255.0 # 0 - 255 to 0.0 - 1.0
772
+ ims.append(im)
773
+
774
+ pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction
775
+ x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections
776
+
777
+ return x
778
+
779
+
780
+ def increment_path(path, exist_ok=True, sep=''):
781
+ # Increment path, i.e. runs/exp --> runs/exp{sep}0, runs/exp{sep}1 etc.
782
+ path = Path(path) # os-agnostic
783
+ if (path.exists() and exist_ok) or (not path.exists()):
784
+ return str(path)
785
+ else:
786
+ dirs = glob.glob(f"{path}{sep}*") # similar paths
787
+ matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs]
788
+ i = [int(m.groups()[0]) for m in matches if m] # indices
789
+ n = max(i) + 1 if i else 2 # increment number
790
+ return f"{path}{sep}{n}" # update path
utils/google_utils.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Google utils: https://cloud.google.com/storage/docs/reference/libraries
2
+
3
+ import os
4
+ import platform
5
+ import subprocess
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import requests
10
+ import torch
11
+
12
+
13
+ def gsutil_getsize(url=''):
14
+ # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
15
+ s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
16
+ return eval(s.split(' ')[0]) if len(s) else 0 # bytes
17
+
18
+
19
+ def attempt_download(file, repo='WongKinYiu/yolov6'):
20
+ # Attempt file download if does not exist
21
+ file = Path(str(file).strip().replace("'", '').lower())
22
+
23
+ if not file.exists():
24
+ try:
25
+ response = requests.get(f'https://api.github.com/repos/{repo}/releases/weights').json() # github api
26
+ assets = [x['name'] for x in response['assets']] # release assets
27
+ tag = response['tag_name'] # i.e. 'v1.0'
28
+ except: # fallback plan
29
+ assets = ['yolov6.pt']
30
+ tag = subprocess.check_output('git tag', shell=True).decode().split()[-1]
31
+
32
+ name = file.name
33
+ if name in assets:
34
+ msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/'
35
+ redundant = False # second download option
36
+ try: # GitHub
37
+ url = f'https://github.com/{repo}/releases/download/{tag}/{name}'
38
+ print(f'Downloading {url} to {file}...')
39
+ torch.hub.download_url_to_file(url, file)
40
+ assert file.exists() and file.stat().st_size > 1E6 # check
41
+ except Exception as e: # GCP
42
+ print(f'Download error: {e}')
43
+ assert redundant, 'No secondary mirror'
44
+ url = f'https://storage.googleapis.com/{repo}/ckpt/{name}'
45
+ print(f'Downloading {url} to {file}...')
46
+ os.system(f'curl -L {url} -o {file}') # torch.hub.download_url_to_file(url, weights)
47
+ finally:
48
+ if not file.exists() or file.stat().st_size < 1E6: # check
49
+ file.unlink(missing_ok=True) # remove partial downloads
50
+ print(f'ERROR: Download failure: {msg}')
51
+ print('')
52
+ return
53
+
54
+
55
+ def gdrive_download(id='', file='tmp.zip'):
56
+ # Downloads a file from Google Drive. from yolov6.utils.google_utils import *; gdrive_download()
57
+ t = time.time()
58
+ file = Path(file)
59
+ cookie = Path('cookie') # gdrive cookie
60
+ print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
61
+ file.unlink(missing_ok=True) # remove existing file
62
+ cookie.unlink(missing_ok=True) # remove existing cookie
63
+
64
+ # Attempt file download
65
+ out = "NUL" if platform.system() == "Windows" else "/dev/null"
66
+ os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
67
+ if os.path.exists('cookie'): # large file
68
+ s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
69
+ else: # small file
70
+ s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
71
+ r = os.system(s) # execute, capture return
72
+ cookie.unlink(missing_ok=True) # remove existing cookie
73
+
74
+ # Error check
75
+ if r != 0:
76
+ file.unlink(missing_ok=True) # remove partial
77
+ print('Download error ') # raise Exception('Download error')
78
+ return r
79
+
80
+ # Unzip if archive
81
+ if file.suffix == '.zip':
82
+ print('unzipping... ', end='')
83
+ os.system(f'unzip -q {file}') # unzip
84
+ file.unlink() # remove zip to free space
85
+
86
+ print(f'Done ({time.time() - t:.1f}s)')
87
+ return r
88
+
89
+
90
+ def get_token(cookie="./cookie"):
91
+ with open(cookie) as f:
92
+ for line in f:
93
+ if "download" in line:
94
+ return line.split()[-1]
95
+ return ""
96
+
97
+ # def upload_blob(bucket_name, source_file_name, destination_blob_name):
98
+ # # Uploads a file to a bucket
99
+ # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
100
+ #
101
+ # storage_client = storage.Client()
102
+ # bucket = storage_client.get_bucket(bucket_name)
103
+ # blob = bucket.blob(destination_blob_name)
104
+ #
105
+ # blob.upload_from_filename(source_file_name)
106
+ #
107
+ # print('File {} uploaded to {}.'.format(
108
+ # source_file_name,
109
+ # destination_blob_name))
110
+ #
111
+ #
112
+ # def download_blob(bucket_name, source_blob_name, destination_file_name):
113
+ # # Uploads a blob from a bucket
114
+ # storage_client = storage.Client()
115
+ # bucket = storage_client.get_bucket(bucket_name)
116
+ # blob = bucket.blob(source_blob_name)
117
+ #
118
+ # blob.download_to_filename(destination_file_name)
119
+ #
120
+ # print('Blob {} downloaded to {}.'.format(
121
+ # source_blob_name,
122
+ # destination_file_name))
utils/loss.py ADDED
@@ -0,0 +1,1157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Loss functions
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ from utils.general import bbox_iou, bbox_alpha_iou, box_iou, box_giou, box_diou, box_ciou, xywh2xyxy
8
+ from utils.torch_utils import is_parallel
9
+
10
+
11
+ def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
12
+ # return positive, negative label smoothing BCE targets
13
+ return 1.0 - 0.5 * eps, 0.5 * eps
14
+
15
+
16
+ class BCEBlurWithLogitsLoss(nn.Module):
17
+ # BCEwithLogitLoss() with reduced missing label effects.
18
+ def __init__(self, alpha=0.05):
19
+ super(BCEBlurWithLogitsLoss, self).__init__()
20
+ self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
21
+ self.alpha = alpha
22
+
23
+ def forward(self, pred, true):
24
+ loss = self.loss_fcn(pred, true)
25
+ pred = torch.sigmoid(pred) # prob from logits
26
+ dx = pred - true # reduce only missing label effects
27
+ # dx = (pred - true).abs() # reduce missing label and false label effects
28
+ alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
29
+ loss *= alpha_factor
30
+ return loss.mean()
31
+
32
+
33
+ class SigmoidBin(nn.Module):
34
+ stride = None # strides computed during build
35
+ export = False # onnx export
36
+
37
+ def __init__(self, bin_count=10, min=0.0, max=1.0, reg_scale = 2.0, use_loss_regression=True, use_fw_regression=True, BCE_weight=1.0, smooth_eps=0.0):
38
+ super(SigmoidBin, self).__init__()
39
+
40
+ self.bin_count = bin_count
41
+ self.length = bin_count + 1
42
+ self.min = min
43
+ self.max = max
44
+ self.scale = float(max - min)
45
+ self.shift = self.scale / 2.0
46
+
47
+ self.use_loss_regression = use_loss_regression
48
+ self.use_fw_regression = use_fw_regression
49
+ self.reg_scale = reg_scale
50
+ self.BCE_weight = BCE_weight
51
+
52
+ start = min + (self.scale/2.0) / self.bin_count
53
+ end = max - (self.scale/2.0) / self.bin_count
54
+ step = self.scale / self.bin_count
55
+ self.step = step
56
+ #print(f" start = {start}, end = {end}, step = {step} ")
57
+
58
+ bins = torch.range(start, end + 0.0001, step).float()
59
+ self.register_buffer('bins', bins)
60
+
61
+
62
+ self.cp = 1.0 - 0.5 * smooth_eps
63
+ self.cn = 0.5 * smooth_eps
64
+
65
+ self.BCEbins = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([BCE_weight]))
66
+ self.MSELoss = nn.MSELoss()
67
+
68
+ def get_length(self):
69
+ return self.length
70
+
71
+ def forward(self, pred):
72
+ assert pred.shape[-1] == self.length, 'pred.shape[-1]=%d is not equal to self.length=%d' % (pred.shape[-1], self.length)
73
+
74
+ pred_reg = (pred[..., 0] * self.reg_scale - self.reg_scale/2.0) * self.step
75
+ pred_bin = pred[..., 1:(1+self.bin_count)]
76
+
77
+ _, bin_idx = torch.max(pred_bin, dim=-1)
78
+ bin_bias = self.bins[bin_idx]
79
+
80
+ if self.use_fw_regression:
81
+ result = pred_reg + bin_bias
82
+ else:
83
+ result = bin_bias
84
+ result = result.clamp(min=self.min, max=self.max)
85
+
86
+ return result
87
+
88
+
89
+ def training_loss(self, pred, target):
90
+ assert pred.shape[-1] == self.length, 'pred.shape[-1]=%d is not equal to self.length=%d' % (pred.shape[-1], self.length)
91
+ assert pred.shape[0] == target.shape[0], 'pred.shape=%d is not equal to the target.shape=%d' % (pred.shape[0], target.shape[0])
92
+ device = pred.device
93
+
94
+ pred_reg = (pred[..., 0].sigmoid() * self.reg_scale - self.reg_scale/2.0) * self.step
95
+ pred_bin = pred[..., 1:(1+self.bin_count)]
96
+
97
+ diff_bin_target = torch.abs(target[..., None] - self.bins)
98
+ _, bin_idx = torch.min(diff_bin_target, dim=-1)
99
+
100
+ bin_bias = self.bins[bin_idx]
101
+ bin_bias.requires_grad = False
102
+ result = pred_reg + bin_bias
103
+
104
+ target_bins = torch.full_like(pred_bin, self.cn, device=device) # targets
105
+ n = pred.shape[0]
106
+ target_bins[range(n), bin_idx] = self.cp
107
+
108
+ loss_bin = self.BCEbins(pred_bin, target_bins) # BCE
109
+
110
+ if self.use_loss_regression:
111
+ loss_regression = self.MSELoss(result, target) # MSE
112
+ loss = loss_bin + loss_regression
113
+ else:
114
+ loss = loss_bin
115
+
116
+ out_result = result.clamp(min=self.min, max=self.max)
117
+
118
+ return loss, out_result
119
+
120
+
121
+ class FocalLoss(nn.Module):
122
+ # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
123
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
124
+ super(FocalLoss, self).__init__()
125
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
126
+ self.gamma = gamma
127
+ self.alpha = alpha
128
+ self.reduction = loss_fcn.reduction
129
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
130
+
131
+ def forward(self, pred, true):
132
+ loss = self.loss_fcn(pred, true)
133
+ # p_t = torch.exp(-loss)
134
+ # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
135
+
136
+ # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
137
+ pred_prob = torch.sigmoid(pred) # prob from logits
138
+ p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
139
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
140
+ modulating_factor = (1.0 - p_t) ** self.gamma
141
+ loss *= alpha_factor * modulating_factor
142
+
143
+ if self.reduction == 'mean':
144
+ return loss.mean()
145
+ elif self.reduction == 'sum':
146
+ return loss.sum()
147
+ else: # 'none'
148
+ return loss
149
+
150
+
151
+ class QFocalLoss(nn.Module):
152
+ # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
153
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
154
+ super(QFocalLoss, self).__init__()
155
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
156
+ self.gamma = gamma
157
+ self.alpha = alpha
158
+ self.reduction = loss_fcn.reduction
159
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
160
+
161
+ def forward(self, pred, true):
162
+ loss = self.loss_fcn(pred, true)
163
+
164
+ pred_prob = torch.sigmoid(pred) # prob from logits
165
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
166
+ modulating_factor = torch.abs(true - pred_prob) ** self.gamma
167
+ loss *= alpha_factor * modulating_factor
168
+
169
+ if self.reduction == 'mean':
170
+ return loss.mean()
171
+ elif self.reduction == 'sum':
172
+ return loss.sum()
173
+ else: # 'none'
174
+ return loss
175
+
176
+ class RankSort(torch.autograd.Function):
177
+ @staticmethod
178
+ def forward(ctx, logits, targets, delta_RS=0.50, eps=1e-10):
179
+
180
+ classification_grads=torch.zeros(logits.shape).cuda()
181
+
182
+ #Filter fg logits
183
+ fg_labels = (targets > 0.)
184
+ fg_logits = logits[fg_labels]
185
+ fg_targets = targets[fg_labels]
186
+ fg_num = len(fg_logits)
187
+
188
+ #Do not use bg with scores less than minimum fg logit
189
+ #since changing its score does not have an effect on precision
190
+ threshold_logit = torch.min(fg_logits)-delta_RS
191
+ relevant_bg_labels=((targets==0) & (logits>=threshold_logit))
192
+
193
+ relevant_bg_logits = logits[relevant_bg_labels]
194
+ relevant_bg_grad=torch.zeros(len(relevant_bg_logits)).cuda()
195
+ sorting_error=torch.zeros(fg_num).cuda()
196
+ ranking_error=torch.zeros(fg_num).cuda()
197
+ fg_grad=torch.zeros(fg_num).cuda()
198
+
199
+ #sort the fg logits
200
+ order=torch.argsort(fg_logits)
201
+ #Loops over each positive following the order
202
+ for ii in order:
203
+ # Difference Transforms (x_ij)
204
+ fg_relations=fg_logits-fg_logits[ii]
205
+ bg_relations=relevant_bg_logits-fg_logits[ii]
206
+
207
+ if delta_RS > 0:
208
+ fg_relations=torch.clamp(fg_relations/(2*delta_RS)+0.5,min=0,max=1)
209
+ bg_relations=torch.clamp(bg_relations/(2*delta_RS)+0.5,min=0,max=1)
210
+ else:
211
+ fg_relations = (fg_relations >= 0).float()
212
+ bg_relations = (bg_relations >= 0).float()
213
+
214
+ # Rank of ii among pos and false positive number (bg with larger scores)
215
+ rank_pos=torch.sum(fg_relations)
216
+ FP_num=torch.sum(bg_relations)
217
+
218
+ # Rank of ii among all examples
219
+ rank=rank_pos+FP_num
220
+
221
+ # Ranking error of example ii. target_ranking_error is always 0. (Eq. 7)
222
+ ranking_error[ii]=FP_num/rank
223
+
224
+ # Current sorting error of example ii. (Eq. 7)
225
+ current_sorting_error = torch.sum(fg_relations*(1-fg_targets))/rank_pos
226
+
227
+ #Find examples in the target sorted order for example ii
228
+ iou_relations = (fg_targets >= fg_targets[ii])
229
+ target_sorted_order = iou_relations * fg_relations
230
+
231
+ #The rank of ii among positives in sorted order
232
+ rank_pos_target = torch.sum(target_sorted_order)
233
+
234
+ #Compute target sorting error. (Eq. 8)
235
+ #Since target ranking error is 0, this is also total target error
236
+ target_sorting_error= torch.sum(target_sorted_order*(1-fg_targets))/rank_pos_target
237
+
238
+ #Compute sorting error on example ii
239
+ sorting_error[ii] = current_sorting_error - target_sorting_error
240
+
241
+ #Identity Update for Ranking Error
242
+ if FP_num > eps:
243
+ #For ii the update is the ranking error
244
+ fg_grad[ii] -= ranking_error[ii]
245
+ #For negatives, distribute error via ranking pmf (i.e. bg_relations/FP_num)
246
+ relevant_bg_grad += (bg_relations*(ranking_error[ii]/FP_num))
247
+
248
+ #Find the positives that are misranked (the cause of the error)
249
+ #These are the ones with smaller IoU but larger logits
250
+ missorted_examples = (~ iou_relations) * fg_relations
251
+
252
+ #Denominotor of sorting pmf
253
+ sorting_pmf_denom = torch.sum(missorted_examples)
254
+
255
+ #Identity Update for Sorting Error
256
+ if sorting_pmf_denom > eps:
257
+ #For ii the update is the sorting error
258
+ fg_grad[ii] -= sorting_error[ii]
259
+ #For positives, distribute error via sorting pmf (i.e. missorted_examples/sorting_pmf_denom)
260
+ fg_grad += (missorted_examples*(sorting_error[ii]/sorting_pmf_denom))
261
+
262
+ #Normalize gradients by number of positives
263
+ classification_grads[fg_labels]= (fg_grad/fg_num)
264
+ classification_grads[relevant_bg_labels]= (relevant_bg_grad/fg_num)
265
+
266
+ ctx.save_for_backward(classification_grads)
267
+
268
+ return ranking_error.mean(), sorting_error.mean()
269
+
270
+ @staticmethod
271
+ def backward(ctx, out_grad1, out_grad2):
272
+ g1, =ctx.saved_tensors
273
+ return g1*out_grad1, None, None, None
274
+
275
+ class aLRPLoss(torch.autograd.Function):
276
+ @staticmethod
277
+ def forward(ctx, logits, targets, regression_losses, delta=1., eps=1e-5):
278
+ classification_grads=torch.zeros(logits.shape).cuda()
279
+
280
+ #Filter fg logits
281
+ fg_labels = (targets == 1)
282
+ fg_logits = logits[fg_labels]
283
+ fg_num = len(fg_logits)
284
+
285
+ #Do not use bg with scores less than minimum fg logit
286
+ #since changing its score does not have an effect on precision
287
+ threshold_logit = torch.min(fg_logits)-delta
288
+
289
+ #Get valid bg logits
290
+ relevant_bg_labels=((targets==0)&(logits>=threshold_logit))
291
+ relevant_bg_logits=logits[relevant_bg_labels]
292
+ relevant_bg_grad=torch.zeros(len(relevant_bg_logits)).cuda()
293
+ rank=torch.zeros(fg_num).cuda()
294
+ prec=torch.zeros(fg_num).cuda()
295
+ fg_grad=torch.zeros(fg_num).cuda()
296
+
297
+ max_prec=0
298
+ #sort the fg logits
299
+ order=torch.argsort(fg_logits)
300
+ #Loops over each positive following the order
301
+ for ii in order:
302
+ #x_ij s as score differences with fgs
303
+ fg_relations=fg_logits-fg_logits[ii]
304
+ #Apply piecewise linear function and determine relations with fgs
305
+ fg_relations=torch.clamp(fg_relations/(2*delta)+0.5,min=0,max=1)
306
+ #Discard i=j in the summation in rank_pos
307
+ fg_relations[ii]=0
308
+
309
+ #x_ij s as score differences with bgs
310
+ bg_relations=relevant_bg_logits-fg_logits[ii]
311
+ #Apply piecewise linear function and determine relations with bgs
312
+ bg_relations=torch.clamp(bg_relations/(2*delta)+0.5,min=0,max=1)
313
+
314
+ #Compute the rank of the example within fgs and number of bgs with larger scores
315
+ rank_pos=1+torch.sum(fg_relations)
316
+ FP_num=torch.sum(bg_relations)
317
+ #Store the total since it is normalizer also for aLRP Regression error
318
+ rank[ii]=rank_pos+FP_num
319
+
320
+ #Compute precision for this example to compute classification loss
321
+ prec[ii]=rank_pos/rank[ii]
322
+ #For stability, set eps to a infinitesmall value (e.g. 1e-6), then compute grads
323
+ if FP_num > eps:
324
+ fg_grad[ii] = -(torch.sum(fg_relations*regression_losses)+FP_num)/rank[ii]
325
+ relevant_bg_grad += (bg_relations*(-fg_grad[ii]/FP_num))
326
+
327
+ #aLRP with grad formulation fg gradient
328
+ classification_grads[fg_labels]= fg_grad
329
+ #aLRP with grad formulation bg gradient
330
+ classification_grads[relevant_bg_labels]= relevant_bg_grad
331
+
332
+ classification_grads /= (fg_num)
333
+
334
+ cls_loss=1-prec.mean()
335
+ ctx.save_for_backward(classification_grads)
336
+
337
+ return cls_loss, rank, order
338
+
339
+ @staticmethod
340
+ def backward(ctx, out_grad1, out_grad2, out_grad3):
341
+ g1, =ctx.saved_tensors
342
+ return g1*out_grad1, None, None, None, None
343
+
344
+
345
+ class APLoss(torch.autograd.Function):
346
+ @staticmethod
347
+ def forward(ctx, logits, targets, delta=1.):
348
+ classification_grads=torch.zeros(logits.shape).cuda()
349
+
350
+ #Filter fg logits
351
+ fg_labels = (targets == 1)
352
+ fg_logits = logits[fg_labels]
353
+ fg_num = len(fg_logits)
354
+
355
+ #Do not use bg with scores less than minimum fg logit
356
+ #since changing its score does not have an effect on precision
357
+ threshold_logit = torch.min(fg_logits)-delta
358
+
359
+ #Get valid bg logits
360
+ relevant_bg_labels=((targets==0)&(logits>=threshold_logit))
361
+ relevant_bg_logits=logits[relevant_bg_labels]
362
+ relevant_bg_grad=torch.zeros(len(relevant_bg_logits)).cuda()
363
+ rank=torch.zeros(fg_num).cuda()
364
+ prec=torch.zeros(fg_num).cuda()
365
+ fg_grad=torch.zeros(fg_num).cuda()
366
+
367
+ max_prec=0
368
+ #sort the fg logits
369
+ order=torch.argsort(fg_logits)
370
+ #Loops over each positive following the order
371
+ for ii in order:
372
+ #x_ij s as score differences with fgs
373
+ fg_relations=fg_logits-fg_logits[ii]
374
+ #Apply piecewise linear function and determine relations with fgs
375
+ fg_relations=torch.clamp(fg_relations/(2*delta)+0.5,min=0,max=1)
376
+ #Discard i=j in the summation in rank_pos
377
+ fg_relations[ii]=0
378
+
379
+ #x_ij s as score differences with bgs
380
+ bg_relations=relevant_bg_logits-fg_logits[ii]
381
+ #Apply piecewise linear function and determine relations with bgs
382
+ bg_relations=torch.clamp(bg_relations/(2*delta)+0.5,min=0,max=1)
383
+
384
+ #Compute the rank of the example within fgs and number of bgs with larger scores
385
+ rank_pos=1+torch.sum(fg_relations)
386
+ FP_num=torch.sum(bg_relations)
387
+ #Store the total since it is normalizer also for aLRP Regression error
388
+ rank[ii]=rank_pos+FP_num
389
+
390
+ #Compute precision for this example
391
+ current_prec=rank_pos/rank[ii]
392
+
393
+ #Compute interpolated AP and store gradients for relevant bg examples
394
+ if (max_prec<=current_prec):
395
+ max_prec=current_prec
396
+ relevant_bg_grad += (bg_relations/rank[ii])
397
+ else:
398
+ relevant_bg_grad += (bg_relations/rank[ii])*(((1-max_prec)/(1-current_prec)))
399
+
400
+ #Store fg gradients
401
+ fg_grad[ii]=-(1-max_prec)
402
+ prec[ii]=max_prec
403
+
404
+ #aLRP with grad formulation fg gradient
405
+ classification_grads[fg_labels]= fg_grad
406
+ #aLRP with grad formulation bg gradient
407
+ classification_grads[relevant_bg_labels]= relevant_bg_grad
408
+
409
+ classification_grads /= fg_num
410
+
411
+ cls_loss=1-prec.mean()
412
+ ctx.save_for_backward(classification_grads)
413
+
414
+ return cls_loss
415
+
416
+ @staticmethod
417
+ def backward(ctx, out_grad1):
418
+ g1, =ctx.saved_tensors
419
+ return g1*out_grad1, None, None
420
+
421
+
422
+ class ComputeLoss:
423
+ # Compute losses
424
+ def __init__(self, model, autobalance=False):
425
+ super(ComputeLoss, self).__init__()
426
+ device = next(model.parameters()).device # get model device
427
+ h = model.hyp # hyperparameters
428
+
429
+ # Define criteria
430
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
431
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
432
+
433
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
434
+ self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
435
+
436
+ # Focal loss
437
+ g = h['fl_gamma'] # focal loss gamma
438
+ if g > 0:
439
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
440
+
441
+ det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
442
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7
443
+ #self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.1, .05]) # P3-P7
444
+ #self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.5, 0.4, .1]) # P3-P7
445
+ self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
446
+ self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance
447
+ for k in 'na', 'nc', 'nl', 'anchors':
448
+ setattr(self, k, getattr(det, k))
449
+
450
+ def __call__(self, p, targets): # predictions, targets, model
451
+ device = targets.device
452
+ lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
453
+ tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
454
+
455
+ # Losses
456
+ for i, pi in enumerate(p): # layer index, layer predictions
457
+ b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
458
+ tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
459
+
460
+ n = b.shape[0] # number of targets
461
+ if n:
462
+ ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
463
+
464
+ # Regression
465
+ pxy = ps[:, :2].sigmoid() * 2. - 0.5
466
+ pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
467
+ pbox = torch.cat((pxy, pwh), 1) # predicted box
468
+ iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)
469
+ lbox += (1.0 - iou).mean() # iou loss
470
+
471
+ # Objectness
472
+ tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
473
+
474
+ # Classification
475
+ if self.nc > 1: # cls loss (only if multiple classes)
476
+ t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets
477
+ t[range(n), tcls[i]] = self.cp
478
+ #t[t==self.cp] = iou.detach().clamp(0).type(t.dtype)
479
+ lcls += self.BCEcls(ps[:, 5:], t) # BCE
480
+
481
+ # Append targets to text file
482
+ # with open('targets.txt', 'a') as file:
483
+ # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
484
+
485
+ obji = self.BCEobj(pi[..., 4], tobj)
486
+ lobj += obji * self.balance[i] # obj loss
487
+ if self.autobalance:
488
+ self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
489
+
490
+ if self.autobalance:
491
+ self.balance = [x / self.balance[self.ssi] for x in self.balance]
492
+ lbox *= self.hyp['box']
493
+ lobj *= self.hyp['obj']
494
+ lcls *= self.hyp['cls']
495
+ bs = tobj.shape[0] # batch size
496
+
497
+ loss = lbox + lobj + lcls
498
+ return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
499
+
500
+ def build_targets(self, p, targets):
501
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
502
+ na, nt = self.na, targets.shape[0] # number of anchors, targets
503
+ tcls, tbox, indices, anch = [], [], [], []
504
+ gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
505
+ ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
506
+ targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
507
+
508
+ g = 0.5 # bias
509
+ off = torch.tensor([[0, 0],
510
+ [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
511
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
512
+ ], device=targets.device).float() * g # offsets
513
+
514
+ for i in range(self.nl):
515
+ anchors = self.anchors[i]
516
+ gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
517
+
518
+ # Match targets to anchors
519
+ t = targets * gain
520
+ if nt:
521
+ # Matches
522
+ r = t[:, :, 4:6] / anchors[:, None] # wh ratio
523
+ j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
524
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
525
+ t = t[j] # filter
526
+
527
+ # Offsets
528
+ gxy = t[:, 2:4] # grid xy
529
+ gxi = gain[[2, 3]] - gxy # inverse
530
+ j, k = ((gxy % 1. < g) & (gxy > 1.)).T
531
+ l, m = ((gxi % 1. < g) & (gxi > 1.)).T
532
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
533
+ t = t.repeat((5, 1, 1))[j]
534
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
535
+ else:
536
+ t = targets[0]
537
+ offsets = 0
538
+
539
+ # Define
540
+ b, c = t[:, :2].long().T # image, class
541
+ gxy = t[:, 2:4] # grid xy
542
+ gwh = t[:, 4:6] # grid wh
543
+ gij = (gxy - offsets).long()
544
+ gi, gj = gij.T # grid xy indices
545
+
546
+ # Append
547
+ a = t[:, 6].long() # anchor indices
548
+ indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
549
+ tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
550
+ anch.append(anchors[a]) # anchors
551
+ tcls.append(c) # class
552
+
553
+ return tcls, tbox, indices, anch
554
+
555
+
556
+ class ComputeLossOTA:
557
+ # Compute losses
558
+ def __init__(self, model, autobalance=False):
559
+ super(ComputeLossOTA, self).__init__()
560
+ device = next(model.parameters()).device # get model device
561
+ h = model.hyp # hyperparameters
562
+
563
+ # Define criteria
564
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
565
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
566
+
567
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
568
+ self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
569
+
570
+ # Focal loss
571
+ g = h['fl_gamma'] # focal loss gamma
572
+ if g > 0:
573
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
574
+
575
+ det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
576
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7
577
+ self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
578
+ self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance
579
+ for k in 'na', 'nc', 'nl', 'anchors', 'stride':
580
+ setattr(self, k, getattr(det, k))
581
+
582
+ def __call__(self, p, targets, imgs): # predictions, targets, model
583
+ device = targets.device
584
+ lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
585
+ bs, as_, gjs, gis, targets, anchors = self.build_targets(p, targets, imgs)
586
+ pre_gen_gains = [torch.tensor(pp.shape, device=device)[[3, 2, 3, 2]] for pp in p]
587
+
588
+
589
+ # Losses
590
+ for i, pi in enumerate(p): # layer index, layer predictions
591
+ b, a, gj, gi = bs[i], as_[i], gjs[i], gis[i] # image, anchor, gridy, gridx
592
+ tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
593
+
594
+ n = b.shape[0] # number of targets
595
+ if n:
596
+ ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
597
+
598
+ # Regression
599
+ grid = torch.stack([gi, gj], dim=1)
600
+ pxy = ps[:, :2].sigmoid() * 2. - 0.5
601
+ #pxy = ps[:, :2].sigmoid() * 3. - 1.
602
+ pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
603
+ pbox = torch.cat((pxy, pwh), 1) # predicted box
604
+ selected_tbox = targets[i][:, 2:6] * pre_gen_gains[i]
605
+ selected_tbox[:, :2] -= grid
606
+ iou = bbox_iou(pbox.T, selected_tbox, x1y1x2y2=False, CIoU=True) # iou(prediction, target)
607
+ lbox += (1.0 - iou).mean() # iou loss
608
+
609
+ # Objectness
610
+ tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
611
+
612
+ # Classification
613
+ selected_tcls = targets[i][:, 1].long()
614
+ if self.nc > 1: # cls loss (only if multiple classes)
615
+ t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets
616
+ t[range(n), selected_tcls] = self.cp
617
+ lcls += self.BCEcls(ps[:, 5:], t) # BCE
618
+
619
+ # Append targets to text file
620
+ # with open('targets.txt', 'a') as file:
621
+ # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
622
+
623
+ obji = self.BCEobj(pi[..., 4], tobj)
624
+ lobj += obji * self.balance[i] # obj loss
625
+ if self.autobalance:
626
+ self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
627
+
628
+ if self.autobalance:
629
+ self.balance = [x / self.balance[self.ssi] for x in self.balance]
630
+ lbox *= self.hyp['box']
631
+ lobj *= self.hyp['obj']
632
+ lcls *= self.hyp['cls']
633
+ bs = tobj.shape[0] # batch size
634
+
635
+ loss = lbox + lobj + lcls
636
+ return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
637
+
638
+ def build_targets(self, p, targets, imgs):
639
+
640
+ #indices, anch = self.find_positive(p, targets)
641
+ indices, anch = self.find_3_positive(p, targets)
642
+ #indices, anch = self.find_4_positive(p, targets)
643
+ #indices, anch = self.find_5_positive(p, targets)
644
+ #indices, anch = self.find_9_positive(p, targets)
645
+
646
+ matching_bs = [[] for pp in p]
647
+ matching_as = [[] for pp in p]
648
+ matching_gjs = [[] for pp in p]
649
+ matching_gis = [[] for pp in p]
650
+ matching_targets = [[] for pp in p]
651
+ matching_anchs = [[] for pp in p]
652
+
653
+ nl = len(p)
654
+
655
+ for batch_idx in range(p[0].shape[0]):
656
+
657
+ b_idx = targets[:, 0]==batch_idx
658
+ this_target = targets[b_idx]
659
+ if this_target.shape[0] == 0:
660
+ continue
661
+
662
+ txywh = this_target[:, 2:6] * imgs[batch_idx].shape[1]
663
+ txyxy = xywh2xyxy(txywh)
664
+
665
+ pxyxys = []
666
+ p_cls = []
667
+ p_obj = []
668
+ from_which_layer = []
669
+ all_b = []
670
+ all_a = []
671
+ all_gj = []
672
+ all_gi = []
673
+ all_anch = []
674
+
675
+ for i, pi in enumerate(p):
676
+
677
+ b, a, gj, gi = indices[i]
678
+ idx = (b == batch_idx)
679
+ b, a, gj, gi = b[idx], a[idx], gj[idx], gi[idx]
680
+ all_b.append(b)
681
+ all_a.append(a)
682
+ all_gj.append(gj)
683
+ all_gi.append(gi)
684
+ all_anch.append(anch[i][idx])
685
+ from_which_layer.append(torch.ones(size=(len(b),)) * i)
686
+
687
+ fg_pred = pi[b, a, gj, gi]
688
+ p_obj.append(fg_pred[:, 4:5])
689
+ p_cls.append(fg_pred[:, 5:])
690
+
691
+ grid = torch.stack([gi, gj], dim=1)
692
+ pxy = (fg_pred[:, :2].sigmoid() * 2. - 0.5 + grid) * self.stride[i] #/ 8.
693
+ #pxy = (fg_pred[:, :2].sigmoid() * 3. - 1. + grid) * self.stride[i]
694
+ pwh = (fg_pred[:, 2:4].sigmoid() * 2) ** 2 * anch[i][idx] * self.stride[i] #/ 8.
695
+ pxywh = torch.cat([pxy, pwh], dim=-1)
696
+ pxyxy = xywh2xyxy(pxywh)
697
+ pxyxys.append(pxyxy)
698
+
699
+ pxyxys = torch.cat(pxyxys, dim=0)
700
+ if pxyxys.shape[0] == 0:
701
+ continue
702
+ p_obj = torch.cat(p_obj, dim=0)
703
+ p_cls = torch.cat(p_cls, dim=0)
704
+ from_which_layer = torch.cat(from_which_layer, dim=0)
705
+ all_b = torch.cat(all_b, dim=0)
706
+ all_a = torch.cat(all_a, dim=0)
707
+ all_gj = torch.cat(all_gj, dim=0)
708
+ all_gi = torch.cat(all_gi, dim=0)
709
+ all_anch = torch.cat(all_anch, dim=0)
710
+
711
+ pair_wise_iou = box_iou(txyxy, pxyxys)
712
+
713
+ pair_wise_iou_loss = -torch.log(pair_wise_iou + 1e-8)
714
+
715
+ top_k, _ = torch.topk(pair_wise_iou, min(10, pair_wise_iou.shape[1]), dim=1)
716
+ dynamic_ks = torch.clamp(top_k.sum(1).int(), min=1)
717
+
718
+ gt_cls_per_image = (
719
+ F.one_hot(this_target[:, 1].to(torch.int64), self.nc)
720
+ .float()
721
+ .unsqueeze(1)
722
+ .repeat(1, pxyxys.shape[0], 1)
723
+ )
724
+
725
+ num_gt = this_target.shape[0]
726
+ cls_preds_ = (
727
+ p_cls.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
728
+ * p_obj.unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
729
+ )
730
+
731
+ y = cls_preds_.sqrt_()
732
+ pair_wise_cls_loss = F.binary_cross_entropy_with_logits(
733
+ torch.log(y/(1-y)) , gt_cls_per_image, reduction="none"
734
+ ).sum(-1)
735
+ del cls_preds_
736
+
737
+ cost = (
738
+ pair_wise_cls_loss
739
+ + 3.0 * pair_wise_iou_loss
740
+ )
741
+
742
+ matching_matrix = torch.zeros_like(cost)
743
+
744
+ for gt_idx in range(num_gt):
745
+ _, pos_idx = torch.topk(
746
+ cost[gt_idx], k=dynamic_ks[gt_idx].item(), largest=False
747
+ )
748
+ matching_matrix[gt_idx][pos_idx] = 1.0
749
+
750
+ del top_k, dynamic_ks
751
+ anchor_matching_gt = matching_matrix.sum(0)
752
+ if (anchor_matching_gt > 1).sum() > 0:
753
+ _, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)
754
+ matching_matrix[:, anchor_matching_gt > 1] *= 0.0
755
+ matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1.0
756
+ fg_mask_inboxes = matching_matrix.sum(0) > 0.0
757
+ matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)
758
+
759
+ from_which_layer = from_which_layer[fg_mask_inboxes]
760
+ all_b = all_b[fg_mask_inboxes]
761
+ all_a = all_a[fg_mask_inboxes]
762
+ all_gj = all_gj[fg_mask_inboxes]
763
+ all_gi = all_gi[fg_mask_inboxes]
764
+ all_anch = all_anch[fg_mask_inboxes]
765
+
766
+ this_target = this_target[matched_gt_inds]
767
+
768
+ for i in range(nl):
769
+ layer_idx = from_which_layer == i
770
+ matching_bs[i].append(all_b[layer_idx])
771
+ matching_as[i].append(all_a[layer_idx])
772
+ matching_gjs[i].append(all_gj[layer_idx])
773
+ matching_gis[i].append(all_gi[layer_idx])
774
+ matching_targets[i].append(this_target[layer_idx])
775
+ matching_anchs[i].append(all_anch[layer_idx])
776
+
777
+ for i in range(nl):
778
+ matching_bs[i] = torch.cat(matching_bs[i], dim=0)
779
+ matching_as[i] = torch.cat(matching_as[i], dim=0)
780
+ matching_gjs[i] = torch.cat(matching_gjs[i], dim=0)
781
+ matching_gis[i] = torch.cat(matching_gis[i], dim=0)
782
+ matching_targets[i] = torch.cat(matching_targets[i], dim=0)
783
+ matching_anchs[i] = torch.cat(matching_anchs[i], dim=0)
784
+
785
+ return matching_bs, matching_as, matching_gjs, matching_gis, matching_targets, matching_anchs
786
+
787
+ def find_3_positive(self, p, targets):
788
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
789
+ na, nt = self.na, targets.shape[0] # number of anchors, targets
790
+ indices, anch = [], []
791
+ gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
792
+ ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
793
+ targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
794
+
795
+ g = 0.5 # bias
796
+ off = torch.tensor([[0, 0],
797
+ [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
798
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
799
+ ], device=targets.device).float() * g # offsets
800
+
801
+ for i in range(self.nl):
802
+ anchors = self.anchors[i]
803
+ gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
804
+
805
+ # Match targets to anchors
806
+ t = targets * gain
807
+ if nt:
808
+ # Matches
809
+ r = t[:, :, 4:6] / anchors[:, None] # wh ratio
810
+ j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
811
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
812
+ t = t[j] # filter
813
+
814
+ # Offsets
815
+ gxy = t[:, 2:4] # grid xy
816
+ gxi = gain[[2, 3]] - gxy # inverse
817
+ j, k = ((gxy % 1. < g) & (gxy > 1.)).T
818
+ l, m = ((gxi % 1. < g) & (gxi > 1.)).T
819
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
820
+ t = t.repeat((5, 1, 1))[j]
821
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
822
+ else:
823
+ t = targets[0]
824
+ offsets = 0
825
+
826
+ # Define
827
+ b, c = t[:, :2].long().T # image, class
828
+ gxy = t[:, 2:4] # grid xy
829
+ gwh = t[:, 4:6] # grid wh
830
+ gij = (gxy - offsets).long()
831
+ gi, gj = gij.T # grid xy indices
832
+
833
+ # Append
834
+ a = t[:, 6].long() # anchor indices
835
+ indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
836
+ anch.append(anchors[a]) # anchors
837
+
838
+ return indices, anch
839
+
840
+
841
+ class ComputeLossBinOTA:
842
+ # Compute losses
843
+ def __init__(self, model, autobalance=False):
844
+ super(ComputeLossBinOTA, self).__init__()
845
+ device = next(model.parameters()).device # get model device
846
+ h = model.hyp # hyperparameters
847
+
848
+ # Define criteria
849
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
850
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
851
+ #MSEangle = nn.MSELoss().to(device)
852
+
853
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
854
+ self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
855
+
856
+ # Focal loss
857
+ g = h['fl_gamma'] # focal loss gamma
858
+ if g > 0:
859
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
860
+
861
+ det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
862
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7
863
+ self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
864
+ self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance
865
+ for k in 'na', 'nc', 'nl', 'anchors', 'stride', 'bin_count':
866
+ setattr(self, k, getattr(det, k))
867
+
868
+ #xy_bin_sigmoid = SigmoidBin(bin_count=11, min=-0.5, max=1.5, use_loss_regression=False).to(device)
869
+ wh_bin_sigmoid = SigmoidBin(bin_count=self.bin_count, min=0.0, max=4.0, use_loss_regression=False).to(device)
870
+ #angle_bin_sigmoid = SigmoidBin(bin_count=31, min=-1.1, max=1.1, use_loss_regression=False).to(device)
871
+ self.wh_bin_sigmoid = wh_bin_sigmoid
872
+
873
+ def __call__(self, p, targets, imgs): # predictions, targets, model
874
+ device = targets.device
875
+ lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
876
+ bs, as_, gjs, gis, targets, anchors = self.build_targets(p, targets, imgs)
877
+ pre_gen_gains = [torch.tensor(pp.shape, device=device)[[3, 2, 3, 2]] for pp in p]
878
+
879
+
880
+ # Losses
881
+ for i, pi in enumerate(p): # layer index, layer predictions
882
+ b, a, gj, gi = bs[i], as_[i], gjs[i], gis[i] # image, anchor, gridy, gridx
883
+ tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
884
+
885
+ obj_idx = self.wh_bin_sigmoid.get_length()*2 + 2 # x,y, w-bce, h-bce # xy_bin_sigmoid.get_length()*2
886
+
887
+ n = b.shape[0] # number of targets
888
+ if n:
889
+ ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
890
+
891
+ # Regression
892
+ grid = torch.stack([gi, gj], dim=1)
893
+ selected_tbox = targets[i][:, 2:6] * pre_gen_gains[i]
894
+ selected_tbox[:, :2] -= grid
895
+
896
+ #pxy = ps[:, :2].sigmoid() * 2. - 0.5
897
+ ##pxy = ps[:, :2].sigmoid() * 3. - 1.
898
+ #pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
899
+ #pbox = torch.cat((pxy, pwh), 1) # predicted box
900
+
901
+ #x_loss, px = xy_bin_sigmoid.training_loss(ps[..., 0:12], tbox[i][..., 0])
902
+ #y_loss, py = xy_bin_sigmoid.training_loss(ps[..., 12:24], tbox[i][..., 1])
903
+ w_loss, pw = self.wh_bin_sigmoid.training_loss(ps[..., 2:(3+self.bin_count)], selected_tbox[..., 2] / anchors[i][..., 0])
904
+ h_loss, ph = self.wh_bin_sigmoid.training_loss(ps[..., (3+self.bin_count):obj_idx], selected_tbox[..., 3] / anchors[i][..., 1])
905
+
906
+ pw *= anchors[i][..., 0]
907
+ ph *= anchors[i][..., 1]
908
+
909
+ px = ps[:, 0].sigmoid() * 2. - 0.5
910
+ py = ps[:, 1].sigmoid() * 2. - 0.5
911
+
912
+ lbox += w_loss + h_loss # + x_loss + y_loss
913
+
914
+ #print(f"\n px = {px.shape}, py = {py.shape}, pw = {pw.shape}, ph = {ph.shape} \n")
915
+
916
+ pbox = torch.cat((px.unsqueeze(1), py.unsqueeze(1), pw.unsqueeze(1), ph.unsqueeze(1)), 1).to(device) # predicted box
917
+
918
+
919
+
920
+
921
+ iou = bbox_iou(pbox.T, selected_tbox, x1y1x2y2=False, CIoU=True) # iou(prediction, target)
922
+ lbox += (1.0 - iou).mean() # iou loss
923
+
924
+ # Objectness
925
+ tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
926
+
927
+ # Classification
928
+ selected_tcls = targets[i][:, 1].long()
929
+ if self.nc > 1: # cls loss (only if multiple classes)
930
+ t = torch.full_like(ps[:, (1+obj_idx):], self.cn, device=device) # targets
931
+ t[range(n), selected_tcls] = self.cp
932
+ lcls += self.BCEcls(ps[:, (1+obj_idx):], t) # BCE
933
+
934
+ # Append targets to text file
935
+ # with open('targets.txt', 'a') as file:
936
+ # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
937
+
938
+ obji = self.BCEobj(pi[..., obj_idx], tobj)
939
+ lobj += obji * self.balance[i] # obj loss
940
+ if self.autobalance:
941
+ self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
942
+
943
+ if self.autobalance:
944
+ self.balance = [x / self.balance[self.ssi] for x in self.balance]
945
+ lbox *= self.hyp['box']
946
+ lobj *= self.hyp['obj']
947
+ lcls *= self.hyp['cls']
948
+ bs = tobj.shape[0] # batch size
949
+
950
+ loss = lbox + lobj + lcls
951
+ return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
952
+
953
+ def build_targets(self, p, targets, imgs):
954
+
955
+ #indices, anch = self.find_positive(p, targets)
956
+ indices, anch = self.find_3_positive(p, targets)
957
+ #indices, anch = self.find_4_positive(p, targets)
958
+ #indices, anch = self.find_5_positive(p, targets)
959
+ #indices, anch = self.find_9_positive(p, targets)
960
+
961
+ matching_bs = [[] for pp in p]
962
+ matching_as = [[] for pp in p]
963
+ matching_gjs = [[] for pp in p]
964
+ matching_gis = [[] for pp in p]
965
+ matching_targets = [[] for pp in p]
966
+ matching_anchs = [[] for pp in p]
967
+
968
+ nl = len(p)
969
+
970
+ for batch_idx in range(p[0].shape[0]):
971
+
972
+ b_idx = targets[:, 0]==batch_idx
973
+ this_target = targets[b_idx]
974
+ if this_target.shape[0] == 0:
975
+ continue
976
+
977
+ txywh = this_target[:, 2:6] * imgs[batch_idx].shape[1]
978
+ txyxy = xywh2xyxy(txywh)
979
+
980
+ pxyxys = []
981
+ p_cls = []
982
+ p_obj = []
983
+ from_which_layer = []
984
+ all_b = []
985
+ all_a = []
986
+ all_gj = []
987
+ all_gi = []
988
+ all_anch = []
989
+
990
+ for i, pi in enumerate(p):
991
+
992
+ obj_idx = self.wh_bin_sigmoid.get_length()*2 + 2
993
+
994
+ b, a, gj, gi = indices[i]
995
+ idx = (b == batch_idx)
996
+ b, a, gj, gi = b[idx], a[idx], gj[idx], gi[idx]
997
+ all_b.append(b)
998
+ all_a.append(a)
999
+ all_gj.append(gj)
1000
+ all_gi.append(gi)
1001
+ all_anch.append(anch[i][idx])
1002
+ from_which_layer.append(torch.ones(size=(len(b),)) * i)
1003
+
1004
+ fg_pred = pi[b, a, gj, gi]
1005
+ p_obj.append(fg_pred[:, obj_idx:(obj_idx+1)])
1006
+ p_cls.append(fg_pred[:, (obj_idx+1):])
1007
+
1008
+ grid = torch.stack([gi, gj], dim=1)
1009
+ pxy = (fg_pred[:, :2].sigmoid() * 2. - 0.5 + grid) * self.stride[i] #/ 8.
1010
+ #pwh = (fg_pred[:, 2:4].sigmoid() * 2) ** 2 * anch[i][idx] * self.stride[i] #/ 8.
1011
+ pw = self.wh_bin_sigmoid.forward(fg_pred[..., 2:(3+self.bin_count)].sigmoid()) * anch[i][idx][:, 0] * self.stride[i]
1012
+ ph = self.wh_bin_sigmoid.forward(fg_pred[..., (3+self.bin_count):obj_idx].sigmoid()) * anch[i][idx][:, 1] * self.stride[i]
1013
+
1014
+ pxywh = torch.cat([pxy, pw.unsqueeze(1), ph.unsqueeze(1)], dim=-1)
1015
+ pxyxy = xywh2xyxy(pxywh)
1016
+ pxyxys.append(pxyxy)
1017
+
1018
+ pxyxys = torch.cat(pxyxys, dim=0)
1019
+ if pxyxys.shape[0] == 0:
1020
+ continue
1021
+ p_obj = torch.cat(p_obj, dim=0)
1022
+ p_cls = torch.cat(p_cls, dim=0)
1023
+ from_which_layer = torch.cat(from_which_layer, dim=0)
1024
+ all_b = torch.cat(all_b, dim=0)
1025
+ all_a = torch.cat(all_a, dim=0)
1026
+ all_gj = torch.cat(all_gj, dim=0)
1027
+ all_gi = torch.cat(all_gi, dim=0)
1028
+ all_anch = torch.cat(all_anch, dim=0)
1029
+
1030
+ pair_wise_iou = box_iou(txyxy, pxyxys)
1031
+
1032
+ pair_wise_iou_loss = -torch.log(pair_wise_iou + 1e-8)
1033
+
1034
+ top_k, _ = torch.topk(pair_wise_iou, min(10, pair_wise_iou.shape[1]), dim=1)
1035
+ dynamic_ks = torch.clamp(top_k.sum(1).int(), min=1)
1036
+
1037
+ gt_cls_per_image = (
1038
+ F.one_hot(this_target[:, 1].to(torch.int64), self.nc)
1039
+ .float()
1040
+ .unsqueeze(1)
1041
+ .repeat(1, pxyxys.shape[0], 1)
1042
+ )
1043
+
1044
+ num_gt = this_target.shape[0]
1045
+ cls_preds_ = (
1046
+ p_cls.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
1047
+ * p_obj.unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
1048
+ )
1049
+
1050
+ y = cls_preds_.sqrt_()
1051
+ pair_wise_cls_loss = F.binary_cross_entropy_with_logits(
1052
+ torch.log(y/(1-y)) , gt_cls_per_image, reduction="none"
1053
+ ).sum(-1)
1054
+ del cls_preds_
1055
+
1056
+ cost = (
1057
+ pair_wise_cls_loss
1058
+ + 3.0 * pair_wise_iou_loss
1059
+ )
1060
+
1061
+ matching_matrix = torch.zeros_like(cost)
1062
+
1063
+ for gt_idx in range(num_gt):
1064
+ _, pos_idx = torch.topk(
1065
+ cost[gt_idx], k=dynamic_ks[gt_idx].item(), largest=False
1066
+ )
1067
+ matching_matrix[gt_idx][pos_idx] = 1.0
1068
+
1069
+ del top_k, dynamic_ks
1070
+ anchor_matching_gt = matching_matrix.sum(0)
1071
+ if (anchor_matching_gt > 1).sum() > 0:
1072
+ _, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)
1073
+ matching_matrix[:, anchor_matching_gt > 1] *= 0.0
1074
+ matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1.0
1075
+ fg_mask_inboxes = matching_matrix.sum(0) > 0.0
1076
+ matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)
1077
+
1078
+ from_which_layer = from_which_layer[fg_mask_inboxes]
1079
+ all_b = all_b[fg_mask_inboxes]
1080
+ all_a = all_a[fg_mask_inboxes]
1081
+ all_gj = all_gj[fg_mask_inboxes]
1082
+ all_gi = all_gi[fg_mask_inboxes]
1083
+ all_anch = all_anch[fg_mask_inboxes]
1084
+
1085
+ this_target = this_target[matched_gt_inds]
1086
+
1087
+ for i in range(nl):
1088
+ layer_idx = from_which_layer == i
1089
+ matching_bs[i].append(all_b[layer_idx])
1090
+ matching_as[i].append(all_a[layer_idx])
1091
+ matching_gjs[i].append(all_gj[layer_idx])
1092
+ matching_gis[i].append(all_gi[layer_idx])
1093
+ matching_targets[i].append(this_target[layer_idx])
1094
+ matching_anchs[i].append(all_anch[layer_idx])
1095
+
1096
+ for i in range(nl):
1097
+ matching_bs[i] = torch.cat(matching_bs[i], dim=0)
1098
+ matching_as[i] = torch.cat(matching_as[i], dim=0)
1099
+ matching_gjs[i] = torch.cat(matching_gjs[i], dim=0)
1100
+ matching_gis[i] = torch.cat(matching_gis[i], dim=0)
1101
+ matching_targets[i] = torch.cat(matching_targets[i], dim=0)
1102
+ matching_anchs[i] = torch.cat(matching_anchs[i], dim=0)
1103
+
1104
+ return matching_bs, matching_as, matching_gjs, matching_gis, matching_targets, matching_anchs
1105
+
1106
+ def find_3_positive(self, p, targets):
1107
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
1108
+ na, nt = self.na, targets.shape[0] # number of anchors, targets
1109
+ indices, anch = [], []
1110
+ gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
1111
+ ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
1112
+ targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
1113
+
1114
+ g = 0.5 # bias
1115
+ off = torch.tensor([[0, 0],
1116
+ [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
1117
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
1118
+ ], device=targets.device).float() * g # offsets
1119
+
1120
+ for i in range(self.nl):
1121
+ anchors = self.anchors[i]
1122
+ gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
1123
+
1124
+ # Match targets to anchors
1125
+ t = targets * gain
1126
+ if nt:
1127
+ # Matches
1128
+ r = t[:, :, 4:6] / anchors[:, None] # wh ratio
1129
+ j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
1130
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
1131
+ t = t[j] # filter
1132
+
1133
+ # Offsets
1134
+ gxy = t[:, 2:4] # grid xy
1135
+ gxi = gain[[2, 3]] - gxy # inverse
1136
+ j, k = ((gxy % 1. < g) & (gxy > 1.)).T
1137
+ l, m = ((gxi % 1. < g) & (gxi > 1.)).T
1138
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
1139
+ t = t.repeat((5, 1, 1))[j]
1140
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
1141
+ else:
1142
+ t = targets[0]
1143
+ offsets = 0
1144
+
1145
+ # Define
1146
+ b, c = t[:, :2].long().T # image, class
1147
+ gxy = t[:, 2:4] # grid xy
1148
+ gwh = t[:, 4:6] # grid wh
1149
+ gij = (gxy - offsets).long()
1150
+ gi, gj = gij.T # grid xy indices
1151
+
1152
+ # Append
1153
+ a = t[:, 6].long() # anchor indices
1154
+ indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
1155
+ anch.append(anchors[a]) # anchors
1156
+
1157
+ return indices, anch
utils/metrics.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model validation metrics
2
+
3
+ from pathlib import Path
4
+
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ import torch
8
+
9
+ from . import general
10
+
11
+
12
+ def fitness(x):
13
+ # Model fitness as a weighted combination of metrics
14
+ w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
15
+ return (x[:, :4] * w).sum(1)
16
+
17
+
18
+ def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()):
19
+ """ Compute the average precision, given the recall and precision curves.
20
+ Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
21
+ # Arguments
22
+ tp: True positives (nparray, nx1 or nx10).
23
+ conf: Objectness value from 0-1 (nparray).
24
+ pred_cls: Predicted object classes (nparray).
25
+ target_cls: True object classes (nparray).
26
+ plot: Plot precision-recall curve at mAP@0.5
27
+ save_dir: Plot save directory
28
+ # Returns
29
+ The average precision as computed in py-faster-rcnn.
30
+ """
31
+
32
+ # Sort by objectness
33
+ i = np.argsort(-conf)
34
+ tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
35
+
36
+ # Find unique classes
37
+ unique_classes = np.unique(target_cls)
38
+ nc = unique_classes.shape[0] # number of classes, number of detections
39
+
40
+ # Create Precision-Recall curve and compute AP for each class
41
+ px, py = np.linspace(0, 1, 1000), [] # for plotting
42
+ ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
43
+ for ci, c in enumerate(unique_classes):
44
+ i = pred_cls == c
45
+ n_l = (target_cls == c).sum() # number of labels
46
+ n_p = i.sum() # number of predictions
47
+
48
+ if n_p == 0 or n_l == 0:
49
+ continue
50
+ else:
51
+ # Accumulate FPs and TPs
52
+ fpc = (1 - tp[i]).cumsum(0)
53
+ tpc = tp[i].cumsum(0)
54
+
55
+ # Recall
56
+ recall = tpc / (n_l + 1e-16) # recall curve
57
+ r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
58
+
59
+ # Precision
60
+ precision = tpc / (tpc + fpc) # precision curve
61
+ p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
62
+
63
+ # AP from recall-precision curve
64
+ for j in range(tp.shape[1]):
65
+ ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
66
+ if plot and j == 0:
67
+ py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
68
+
69
+ # Compute F1 (harmonic mean of precision and recall)
70
+ f1 = 2 * p * r / (p + r + 1e-16)
71
+ if plot:
72
+ plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
73
+ plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
74
+ plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
75
+ plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')
76
+
77
+ i = f1.mean(0).argmax() # max F1 index
78
+ return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32')
79
+
80
+
81
+ def compute_ap(recall, precision):
82
+ """ Compute the average precision, given the recall and precision curves
83
+ # Arguments
84
+ recall: The recall curve (list)
85
+ precision: The precision curve (list)
86
+ # Returns
87
+ Average precision, precision curve, recall curve
88
+ """
89
+
90
+ # Append sentinel values to beginning and end
91
+ mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01]))
92
+ mpre = np.concatenate(([1.], precision, [0.]))
93
+
94
+ # Compute the precision envelope
95
+ mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
96
+
97
+ # Integrate area under curve
98
+ method = 'interp' # methods: 'continuous', 'interp'
99
+ if method == 'interp':
100
+ x = np.linspace(0, 1, 101) # 101-point interp (COCO)
101
+ ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
102
+ else: # 'continuous'
103
+ i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
104
+ ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
105
+
106
+ return ap, mpre, mrec
107
+
108
+
109
+ class ConfusionMatrix:
110
+ # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
111
+ def __init__(self, nc, conf=0.25, iou_thres=0.45):
112
+ self.matrix = np.zeros((nc + 1, nc + 1))
113
+ self.nc = nc # number of classes
114
+ self.conf = conf
115
+ self.iou_thres = iou_thres
116
+
117
+ def process_batch(self, detections, labels):
118
+ """
119
+ Return intersection-over-union (Jaccard index) of boxes.
120
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
121
+ Arguments:
122
+ detections (Array[N, 6]), x1, y1, x2, y2, conf, class
123
+ labels (Array[M, 5]), class, x1, y1, x2, y2
124
+ Returns:
125
+ None, updates confusion matrix accordingly
126
+ """
127
+ detections = detections[detections[:, 4] > self.conf]
128
+ gt_classes = labels[:, 0].int()
129
+ detection_classes = detections[:, 5].int()
130
+ iou = general.box_iou(labels[:, 1:], detections[:, :4])
131
+
132
+ x = torch.where(iou > self.iou_thres)
133
+ if x[0].shape[0]:
134
+ matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
135
+ if x[0].shape[0] > 1:
136
+ matches = matches[matches[:, 2].argsort()[::-1]]
137
+ matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
138
+ matches = matches[matches[:, 2].argsort()[::-1]]
139
+ matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
140
+ else:
141
+ matches = np.zeros((0, 3))
142
+
143
+ n = matches.shape[0] > 0
144
+ m0, m1, _ = matches.transpose().astype(np.int16)
145
+ for i, gc in enumerate(gt_classes):
146
+ j = m0 == i
147
+ if n and sum(j) == 1:
148
+ self.matrix[gc, detection_classes[m1[j]]] += 1 # correct
149
+ else:
150
+ self.matrix[self.nc, gc] += 1 # background FP
151
+
152
+ if n:
153
+ for i, dc in enumerate(detection_classes):
154
+ if not any(m1 == i):
155
+ self.matrix[dc, self.nc] += 1 # background FN
156
+
157
+ def matrix(self):
158
+ return self.matrix
159
+
160
+ def plot(self, save_dir='', names=()):
161
+ try:
162
+ import seaborn as sn
163
+
164
+ array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize
165
+ array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
166
+
167
+ fig = plt.figure(figsize=(12, 9), tight_layout=True)
168
+ sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size
169
+ labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels
170
+ sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True,
171
+ xticklabels=names + ['background FP'] if labels else "auto",
172
+ yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))
173
+ fig.axes[0].set_xlabel('True')
174
+ fig.axes[0].set_ylabel('Predicted')
175
+ fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
176
+ except Exception as e:
177
+ pass
178
+
179
+ def print(self):
180
+ for i in range(self.nc + 1):
181
+ print(' '.join(map(str, self.matrix[i])))
182
+
183
+
184
+ # Plots ----------------------------------------------------------------------------------------------------------------
185
+
186
+ def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):
187
+ # Precision-recall curve
188
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
189
+ py = np.stack(py, axis=1)
190
+
191
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
192
+ for i, y in enumerate(py.T):
193
+ ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
194
+ else:
195
+ ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
196
+
197
+ ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
198
+ ax.set_xlabel('Recall')
199
+ ax.set_ylabel('Precision')
200
+ ax.set_xlim(0, 1)
201
+ ax.set_ylim(0, 1)
202
+ plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
203
+ fig.savefig(Path(save_dir), dpi=250)
204
+
205
+
206
+ def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):
207
+ # Metric-confidence curve
208
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
209
+
210
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
211
+ for i, y in enumerate(py):
212
+ ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
213
+ else:
214
+ ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
215
+
216
+ y = py.mean(0)
217
+ ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
218
+ ax.set_xlabel(xlabel)
219
+ ax.set_ylabel(ylabel)
220
+ ax.set_xlim(0, 1)
221
+ ax.set_ylim(0, 1)
222
+ plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
223
+ fig.savefig(Path(save_dir), dpi=250)
utils/plots.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Plotting utils
2
+
3
+ import glob
4
+ import math
5
+ import os
6
+ import random
7
+ from copy import copy
8
+ from pathlib import Path
9
+
10
+ import cv2
11
+ import matplotlib
12
+ import matplotlib.pyplot as plt
13
+ import numpy as np
14
+ import pandas as pd
15
+ import seaborn as sns
16
+ import torch
17
+ import yaml
18
+ from PIL import Image, ImageDraw, ImageFont
19
+ from scipy.signal import butter, filtfilt
20
+
21
+ from utils.general import xywh2xyxy, xyxy2xywh
22
+ from utils.metrics import fitness
23
+
24
+ # Settings
25
+ matplotlib.rc('font', **{'size': 11})
26
+ matplotlib.use('Agg') # for writing to files only
27
+
28
+
29
+ def color_list():
30
+ # Return first 10 plt colors as (r,g,b) https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb
31
+ def hex2rgb(h):
32
+ return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
33
+
34
+ return [hex2rgb(h) for h in matplotlib.colors.TABLEAU_COLORS.values()] # or BASE_ (8), CSS4_ (148), XKCD_ (949)
35
+
36
+
37
+ def hist2d(x, y, n=100):
38
+ # 2d histogram used in labels.png and evolve.png
39
+ xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
40
+ hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
41
+ xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
42
+ yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
43
+ return np.log(hist[xidx, yidx])
44
+
45
+
46
+ def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
47
+ # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
48
+ def butter_lowpass(cutoff, fs, order):
49
+ nyq = 0.5 * fs
50
+ normal_cutoff = cutoff / nyq
51
+ return butter(order, normal_cutoff, btype='low', analog=False)
52
+
53
+ b, a = butter_lowpass(cutoff, fs, order=order)
54
+ return filtfilt(b, a, data) # forward-backward filter
55
+
56
+
57
+ def plot_one_box(x, img, color=None, label=None, line_thickness=3):
58
+ # Plots one bounding box on image img
59
+ tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness
60
+ color = color or [random.randint(0, 255) for _ in range(3)]
61
+ c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
62
+ cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
63
+ if label:
64
+ tf = max(tl - 1, 1) # font thickness
65
+ t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
66
+ c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
67
+ cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled
68
+ cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
69
+
70
+
71
+ def plot_one_box_PIL(box, img, color=None, label=None, line_thickness=None):
72
+ img = Image.fromarray(img)
73
+ draw = ImageDraw.Draw(img)
74
+ line_thickness = line_thickness or max(int(min(img.size) / 200), 2)
75
+ draw.rectangle(box, width=line_thickness, outline=tuple(color)) # plot
76
+ if label:
77
+ fontsize = max(round(max(img.size) / 40), 12)
78
+ font = ImageFont.truetype("Arial.ttf", fontsize)
79
+ txt_width, txt_height = font.getsize(label)
80
+ draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=tuple(color))
81
+ draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font)
82
+ return np.asarray(img)
83
+
84
+
85
+ def plot_wh_methods(): # from utils.plots import *; plot_wh_methods()
86
+ # Compares the two methods for width-height anchor multiplication
87
+ # https://github.com/ultralytics/yolov3/issues/168
88
+ x = np.arange(-4.0, 4.0, .1)
89
+ ya = np.exp(x)
90
+ yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
91
+
92
+ fig = plt.figure(figsize=(6, 3), tight_layout=True)
93
+ plt.plot(x, ya, '.-', label='YOLOv3')
94
+ plt.plot(x, yb ** 2, '.-', label='YOLOR ^2')
95
+ plt.plot(x, yb ** 1.6, '.-', label='YOLOR ^1.6')
96
+ plt.xlim(left=-4, right=4)
97
+ plt.ylim(bottom=0, top=6)
98
+ plt.xlabel('input')
99
+ plt.ylabel('output')
100
+ plt.grid()
101
+ plt.legend()
102
+ fig.savefig('comparison.png', dpi=200)
103
+
104
+
105
+ def output_to_target(output):
106
+ # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
107
+ targets = []
108
+ for i, o in enumerate(output):
109
+ for *box, conf, cls in o.cpu().numpy():
110
+ targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
111
+ return np.array(targets)
112
+
113
+
114
+ def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
115
+ # Plot image grid with labels
116
+
117
+ if isinstance(images, torch.Tensor):
118
+ images = images.cpu().float().numpy()
119
+ if isinstance(targets, torch.Tensor):
120
+ targets = targets.cpu().numpy()
121
+
122
+ # un-normalise
123
+ if np.max(images[0]) <= 1:
124
+ images *= 255
125
+
126
+ tl = 3 # line thickness
127
+ tf = max(tl - 1, 1) # font thickness
128
+ bs, _, h, w = images.shape # batch size, _, height, width
129
+ bs = min(bs, max_subplots) # limit plot images
130
+ ns = np.ceil(bs ** 0.5) # number of subplots (square)
131
+
132
+ # Check if we should resize
133
+ scale_factor = max_size / max(h, w)
134
+ if scale_factor < 1:
135
+ h = math.ceil(scale_factor * h)
136
+ w = math.ceil(scale_factor * w)
137
+
138
+ colors = color_list() # list of colors
139
+ mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
140
+ for i, img in enumerate(images):
141
+ if i == max_subplots: # if last batch has fewer images than we expect
142
+ break
143
+
144
+ block_x = int(w * (i // ns))
145
+ block_y = int(h * (i % ns))
146
+
147
+ img = img.transpose(1, 2, 0)
148
+ if scale_factor < 1:
149
+ img = cv2.resize(img, (w, h))
150
+
151
+ mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
152
+ if len(targets) > 0:
153
+ image_targets = targets[targets[:, 0] == i]
154
+ boxes = xywh2xyxy(image_targets[:, 2:6]).T
155
+ classes = image_targets[:, 1].astype('int')
156
+ labels = image_targets.shape[1] == 6 # labels if no conf column
157
+ conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred)
158
+
159
+ if boxes.shape[1]:
160
+ if boxes.max() <= 1.01: # if normalized with tolerance 0.01
161
+ boxes[[0, 2]] *= w # scale to pixels
162
+ boxes[[1, 3]] *= h
163
+ elif scale_factor < 1: # absolute coords need scale if image scales
164
+ boxes *= scale_factor
165
+ boxes[[0, 2]] += block_x
166
+ boxes[[1, 3]] += block_y
167
+ for j, box in enumerate(boxes.T):
168
+ cls = int(classes[j])
169
+ color = colors[cls % len(colors)]
170
+ cls = names[cls] if names else cls
171
+ if labels or conf[j] > 0.25: # 0.25 conf thresh
172
+ label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])
173
+ plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)
174
+
175
+ # Draw image filename labels
176
+ if paths:
177
+ label = Path(paths[i]).name[:40] # trim to 40 char
178
+ t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
179
+ cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
180
+ lineType=cv2.LINE_AA)
181
+
182
+ # Image border
183
+ cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
184
+
185
+ if fname:
186
+ r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size
187
+ mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)
188
+ # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save
189
+ Image.fromarray(mosaic).save(fname) # PIL save
190
+ return mosaic
191
+
192
+
193
+ def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
194
+ # Plot LR simulating training for full epochs
195
+ optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
196
+ y = []
197
+ for _ in range(epochs):
198
+ scheduler.step()
199
+ y.append(optimizer.param_groups[0]['lr'])
200
+ plt.plot(y, '.-', label='LR')
201
+ plt.xlabel('epoch')
202
+ plt.ylabel('LR')
203
+ plt.grid()
204
+ plt.xlim(0, epochs)
205
+ plt.ylim(0)
206
+ plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
207
+ plt.close()
208
+
209
+
210
+ def plot_test_txt(): # from utils.plots import *; plot_test()
211
+ # Plot test.txt histograms
212
+ x = np.loadtxt('test.txt', dtype=np.float32)
213
+ box = xyxy2xywh(x[:, :4])
214
+ cx, cy = box[:, 0], box[:, 1]
215
+
216
+ fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
217
+ ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
218
+ ax.set_aspect('equal')
219
+ plt.savefig('hist2d.png', dpi=300)
220
+
221
+ fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
222
+ ax[0].hist(cx, bins=600)
223
+ ax[1].hist(cy, bins=600)
224
+ plt.savefig('hist1d.png', dpi=200)
225
+
226
+
227
+ def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
228
+ # Plot targets.txt histograms
229
+ x = np.loadtxt('targets.txt', dtype=np.float32).T
230
+ s = ['x targets', 'y targets', 'width targets', 'height targets']
231
+ fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
232
+ ax = ax.ravel()
233
+ for i in range(4):
234
+ ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
235
+ ax[i].legend()
236
+ ax[i].set_title(s[i])
237
+ plt.savefig('targets.jpg', dpi=200)
238
+
239
+
240
+ def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt()
241
+ # Plot study.txt generated by test.py
242
+ fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)
243
+ # ax = ax.ravel()
244
+
245
+ fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
246
+ # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolor-p6', 'yolor-w6', 'yolor-e6', 'yolor-d6']]:
247
+ for f in sorted(Path(path).glob('study*.txt')):
248
+ y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
249
+ x = np.arange(y.shape[1]) if x is None else np.array(x)
250
+ s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)']
251
+ # for i in range(7):
252
+ # ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
253
+ # ax[i].set_title(s[i])
254
+
255
+ j = y[3].argmax() + 1
256
+ ax2.plot(y[6, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8,
257
+ label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
258
+
259
+ ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
260
+ 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
261
+
262
+ ax2.grid(alpha=0.2)
263
+ ax2.set_yticks(np.arange(20, 60, 5))
264
+ ax2.set_xlim(0, 57)
265
+ ax2.set_ylim(30, 55)
266
+ ax2.set_xlabel('GPU Speed (ms/img)')
267
+ ax2.set_ylabel('COCO AP val')
268
+ ax2.legend(loc='lower right')
269
+ plt.savefig(str(Path(path).name) + '.png', dpi=300)
270
+
271
+
272
+ def plot_labels(labels, names=(), save_dir=Path(''), loggers=None):
273
+ # plot dataset labels
274
+ print('Plotting labels... ')
275
+ c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
276
+ nc = int(c.max() + 1) # number of classes
277
+ colors = color_list()
278
+ x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
279
+
280
+ # seaborn correlogram
281
+ sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
282
+ plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
283
+ plt.close()
284
+
285
+ # matplotlib labels
286
+ matplotlib.use('svg') # faster
287
+ ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
288
+ ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
289
+ ax[0].set_ylabel('instances')
290
+ if 0 < len(names) < 30:
291
+ ax[0].set_xticks(range(len(names)))
292
+ ax[0].set_xticklabels(names, rotation=90, fontsize=10)
293
+ else:
294
+ ax[0].set_xlabel('classes')
295
+ sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
296
+ sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
297
+
298
+ # rectangles
299
+ labels[:, 1:3] = 0.5 # center
300
+ labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
301
+ img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
302
+ for cls, *box in labels[:1000]:
303
+ ImageDraw.Draw(img).rectangle(box, width=1, outline=colors[int(cls) % 10]) # plot
304
+ ax[1].imshow(img)
305
+ ax[1].axis('off')
306
+
307
+ for a in [0, 1, 2, 3]:
308
+ for s in ['top', 'right', 'left', 'bottom']:
309
+ ax[a].spines[s].set_visible(False)
310
+
311
+ plt.savefig(save_dir / 'labels.jpg', dpi=200)
312
+ matplotlib.use('Agg')
313
+ plt.close()
314
+
315
+ # loggers
316
+ for k, v in loggers.items() or {}:
317
+ if k == 'wandb' and v:
318
+ v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False)
319
+
320
+
321
+ def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution()
322
+ # Plot hyperparameter evolution results in evolve.txt
323
+ with open(yaml_file) as f:
324
+ hyp = yaml.load(f, Loader=yaml.SafeLoader)
325
+ x = np.loadtxt('evolve.txt', ndmin=2)
326
+ f = fitness(x)
327
+ # weights = (f - f.min()) ** 2 # for weighted results
328
+ plt.figure(figsize=(10, 12), tight_layout=True)
329
+ matplotlib.rc('font', **{'size': 8})
330
+ for i, (k, v) in enumerate(hyp.items()):
331
+ y = x[:, i + 7]
332
+ # mu = (y * weights).sum() / weights.sum() # best weighted result
333
+ mu = y[f.argmax()] # best single result
334
+ plt.subplot(6, 5, i + 1)
335
+ plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
336
+ plt.plot(mu, f.max(), 'k+', markersize=15)
337
+ plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
338
+ if i % 5 != 0:
339
+ plt.yticks([])
340
+ print('%15s: %.3g' % (k, mu))
341
+ plt.savefig('evolve.png', dpi=200)
342
+ print('\nPlot saved as evolve.png')
343
+
344
+
345
+ def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
346
+ # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
347
+ ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
348
+ s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
349
+ files = list(Path(save_dir).glob('frames*.txt'))
350
+ for fi, f in enumerate(files):
351
+ try:
352
+ results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
353
+ n = results.shape[1] # number of rows
354
+ x = np.arange(start, min(stop, n) if stop else n)
355
+ results = results[:, x]
356
+ t = (results[0] - results[0].min()) # set t0=0s
357
+ results[0] = x
358
+ for i, a in enumerate(ax):
359
+ if i < len(results):
360
+ label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
361
+ a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
362
+ a.set_title(s[i])
363
+ a.set_xlabel('time (s)')
364
+ # if fi == len(files) - 1:
365
+ # a.set_ylim(bottom=0)
366
+ for side in ['top', 'right']:
367
+ a.spines[side].set_visible(False)
368
+ else:
369
+ a.remove()
370
+ except Exception as e:
371
+ print('Warning: Plotting error for %s; %s' % (f, e))
372
+
373
+ ax[1].legend()
374
+ plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
375
+
376
+
377
+ def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay()
378
+ # Plot training 'results*.txt', overlaying train and val losses
379
+ s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends
380
+ t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
381
+ for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
382
+ results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
383
+ n = results.shape[1] # number of rows
384
+ x = range(start, min(stop, n) if stop else n)
385
+ fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
386
+ ax = ax.ravel()
387
+ for i in range(5):
388
+ for j in [i, i + 5]:
389
+ y = results[j, x]
390
+ ax[i].plot(x, y, marker='.', label=s[j])
391
+ # y_smooth = butter_lowpass_filtfilt(y)
392
+ # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
393
+
394
+ ax[i].set_title(t[i])
395
+ ax[i].legend()
396
+ ax[i].set_ylabel(f) if i == 0 else None # add filename
397
+ fig.savefig(f.replace('.txt', '.png'), dpi=200)
398
+
399
+
400
+ def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):
401
+ # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')
402
+ fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
403
+ ax = ax.ravel()
404
+ s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',
405
+ 'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95']
406
+ if bucket:
407
+ # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
408
+ files = ['results%g.txt' % x for x in id]
409
+ c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)
410
+ os.system(c)
411
+ else:
412
+ files = list(Path(save_dir).glob('results*.txt'))
413
+ assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)
414
+ for fi, f in enumerate(files):
415
+ try:
416
+ results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
417
+ n = results.shape[1] # number of rows
418
+ x = range(start, min(stop, n) if stop else n)
419
+ for i in range(10):
420
+ y = results[i, x]
421
+ if i in [0, 1, 2, 5, 6, 7]:
422
+ y[y == 0] = np.nan # don't show zero loss values
423
+ # y /= y[0] # normalize
424
+ label = labels[fi] if len(labels) else f.stem
425
+ ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)
426
+ ax[i].set_title(s[i])
427
+ # if i in [5, 6, 7]: # share train and val loss y axes
428
+ # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
429
+ except Exception as e:
430
+ print('Warning: Plotting error for %s; %s' % (f, e))
431
+
432
+ ax[1].legend()
433
+ fig.savefig(Path(save_dir) / 'results.png', dpi=200)
utils/torch_utils.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOR PyTorch utils
2
+
3
+ import datetime
4
+ import logging
5
+ import math
6
+ import os
7
+ import platform
8
+ import subprocess
9
+ import time
10
+ from contextlib import contextmanager
11
+ from copy import deepcopy
12
+ from pathlib import Path
13
+
14
+ import torch
15
+ import torch.backends.cudnn as cudnn
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ import torchvision
19
+
20
+ try:
21
+ import thop # for FLOPS computation
22
+ except ImportError:
23
+ thop = None
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ @contextmanager
28
+ def torch_distributed_zero_first(local_rank: int):
29
+ """
30
+ Decorator to make all processes in distributed training wait for each local_master to do something.
31
+ """
32
+ if local_rank not in [-1, 0]:
33
+ torch.distributed.barrier()
34
+ yield
35
+ if local_rank == 0:
36
+ torch.distributed.barrier()
37
+
38
+
39
+ def init_torch_seeds(seed=0):
40
+ # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
41
+ torch.manual_seed(seed)
42
+ if seed == 0: # slower, more reproducible
43
+ cudnn.benchmark, cudnn.deterministic = False, True
44
+ else: # faster, less reproducible
45
+ cudnn.benchmark, cudnn.deterministic = True, False
46
+
47
+
48
+ def date_modified(path=__file__):
49
+ # return human-readable file modification date, i.e. '2021-3-26'
50
+ t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime)
51
+ return f'{t.year}-{t.month}-{t.day}'
52
+
53
+
54
+ def git_describe(path=Path(__file__).parent): # path must be a directory
55
+ # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
56
+ s = f'git -C {path} describe --tags --long --always'
57
+ try:
58
+ return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1]
59
+ except subprocess.CalledProcessError as e:
60
+ return '' # not a git repository
61
+
62
+
63
+ def select_device(device='', batch_size=None):
64
+ # device = 'cpu' or '0' or '0,1,2,3'
65
+ s = f'YOLOR 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string
66
+ cpu = device.lower() == 'cpu'
67
+ if cpu:
68
+ os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
69
+ elif device: # non-cpu device requested
70
+ os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
71
+ assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability
72
+
73
+ cuda = not cpu and torch.cuda.is_available()
74
+ if cuda:
75
+ n = torch.cuda.device_count()
76
+ if n > 1 and batch_size: # check that batch_size is compatible with device_count
77
+ assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
78
+ space = ' ' * len(s)
79
+ for i, d in enumerate(device.split(',') if device else range(n)):
80
+ p = torch.cuda.get_device_properties(i)
81
+ s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB
82
+ else:
83
+ s += 'CPU\n'
84
+
85
+ logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
86
+ return torch.device('cuda:0' if cuda else 'cpu')
87
+
88
+
89
+ def time_synchronized():
90
+ # pytorch-accurate time
91
+ if torch.cuda.is_available():
92
+ torch.cuda.synchronize()
93
+ return time.time()
94
+
95
+
96
+ def profile(x, ops, n=100, device=None):
97
+ # profile a pytorch module or list of modules. Example usage:
98
+ # x = torch.randn(16, 3, 640, 640) # input
99
+ # m1 = lambda x: x * torch.sigmoid(x)
100
+ # m2 = nn.SiLU()
101
+ # profile(x, [m1, m2], n=100) # profile speed over 100 iterations
102
+
103
+ device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
104
+ x = x.to(device)
105
+ x.requires_grad = True
106
+ print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '')
107
+ print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}")
108
+ for m in ops if isinstance(ops, list) else [ops]:
109
+ m = m.to(device) if hasattr(m, 'to') else m # device
110
+ m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type
111
+ dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward
112
+ try:
113
+ flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS
114
+ except:
115
+ flops = 0
116
+
117
+ for _ in range(n):
118
+ t[0] = time_synchronized()
119
+ y = m(x)
120
+ t[1] = time_synchronized()
121
+ try:
122
+ _ = y.sum().backward()
123
+ t[2] = time_synchronized()
124
+ except: # no backward method
125
+ t[2] = float('nan')
126
+ dtf += (t[1] - t[0]) * 1000 / n # ms per op forward
127
+ dtb += (t[2] - t[1]) * 1000 / n # ms per op backward
128
+
129
+ s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list'
130
+ s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list'
131
+ p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters
132
+ print(f'{p:12}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}')
133
+
134
+
135
+ def is_parallel(model):
136
+ return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
137
+
138
+
139
+ def intersect_dicts(da, db, exclude=()):
140
+ # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
141
+ return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
142
+
143
+
144
+ def initialize_weights(model):
145
+ for m in model.modules():
146
+ t = type(m)
147
+ if t is nn.Conv2d:
148
+ pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
149
+ elif t is nn.BatchNorm2d:
150
+ m.eps = 1e-3
151
+ m.momentum = 0.03
152
+ elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
153
+ m.inplace = True
154
+
155
+
156
+ def find_modules(model, mclass=nn.Conv2d):
157
+ # Finds layer indices matching module class 'mclass'
158
+ return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
159
+
160
+
161
+ def sparsity(model):
162
+ # Return global model sparsity
163
+ a, b = 0., 0.
164
+ for p in model.parameters():
165
+ a += p.numel()
166
+ b += (p == 0).sum()
167
+ return b / a
168
+
169
+
170
+ def prune(model, amount=0.3):
171
+ # Prune model to requested global sparsity
172
+ import torch.nn.utils.prune as prune
173
+ print('Pruning model... ', end='')
174
+ for name, m in model.named_modules():
175
+ if isinstance(m, nn.Conv2d):
176
+ prune.l1_unstructured(m, name='weight', amount=amount) # prune
177
+ prune.remove(m, 'weight') # make permanent
178
+ print(' %.3g global sparsity' % sparsity(model))
179
+
180
+
181
+ def fuse_conv_and_bn(conv, bn):
182
+ # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
183
+ fusedconv = nn.Conv2d(conv.in_channels,
184
+ conv.out_channels,
185
+ kernel_size=conv.kernel_size,
186
+ stride=conv.stride,
187
+ padding=conv.padding,
188
+ groups=conv.groups,
189
+ bias=True).requires_grad_(False).to(conv.weight.device)
190
+
191
+ # prepare filters
192
+ w_conv = conv.weight.clone().view(conv.out_channels, -1)
193
+ w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
194
+ fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
195
+
196
+ # prepare spatial bias
197
+ b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
198
+ b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
199
+ fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
200
+
201
+ return fusedconv
202
+
203
+
204
+ def model_info(model, verbose=False, img_size=640):
205
+ # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
206
+ n_p = sum(x.numel() for x in model.parameters()) # number parameters
207
+ n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
208
+ if verbose:
209
+ print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
210
+ for i, (name, p) in enumerate(model.named_parameters()):
211
+ name = name.replace('module_list.', '')
212
+ print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
213
+ (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
214
+
215
+ try: # FLOPS
216
+ from thop import profile
217
+ stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32
218
+ img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input
219
+ flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS
220
+ img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float
221
+ fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS
222
+ except (ImportError, Exception):
223
+ fs = ''
224
+
225
+ logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
226
+
227
+
228
+ def load_classifier(name='resnet101', n=2):
229
+ # Loads a pretrained model reshaped to n-class output
230
+ model = torchvision.models.__dict__[name](pretrained=True)
231
+
232
+ # ResNet model properties
233
+ # input_size = [3, 224, 224]
234
+ # input_space = 'RGB'
235
+ # input_range = [0, 1]
236
+ # mean = [0.485, 0.456, 0.406]
237
+ # std = [0.229, 0.224, 0.225]
238
+
239
+ # Reshape output to n classes
240
+ filters = model.fc.weight.shape[1]
241
+ model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
242
+ model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
243
+ model.fc.out_features = n
244
+ return model
245
+
246
+
247
+ def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
248
+ # scales img(bs,3,y,x) by ratio constrained to gs-multiple
249
+ if ratio == 1.0:
250
+ return img
251
+ else:
252
+ h, w = img.shape[2:]
253
+ s = (int(h * ratio), int(w * ratio)) # new size
254
+ img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
255
+ if not same_shape: # pad/crop img
256
+ h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
257
+ return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
258
+
259
+
260
+ def copy_attr(a, b, include=(), exclude=()):
261
+ # Copy attributes from b to a, options to only include [...] and to exclude [...]
262
+ for k, v in b.__dict__.items():
263
+ if (len(include) and k not in include) or k.startswith('_') or k in exclude:
264
+ continue
265
+ else:
266
+ setattr(a, k, v)
267
+
268
+
269
+ class ModelEMA:
270
+ """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
271
+ Keep a moving average of everything in the model state_dict (parameters and buffers).
272
+ This is intended to allow functionality like
273
+ https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
274
+ A smoothed version of the weights is necessary for some training schemes to perform well.
275
+ This class is sensitive where it is initialized in the sequence of model init,
276
+ GPU assignment and distributed training wrappers.
277
+ """
278
+
279
+ def __init__(self, model, decay=0.9999, updates=0):
280
+ # Create EMA
281
+ self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA
282
+ # if next(model.parameters()).device.type != 'cpu':
283
+ # self.ema.half() # FP16 EMA
284
+ self.updates = updates # number of EMA updates
285
+ self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
286
+ for p in self.ema.parameters():
287
+ p.requires_grad_(False)
288
+
289
+ def update(self, model):
290
+ # Update EMA parameters
291
+ with torch.no_grad():
292
+ self.updates += 1
293
+ d = self.decay(self.updates)
294
+
295
+ msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict
296
+ for k, v in self.ema.state_dict().items():
297
+ if v.dtype.is_floating_point:
298
+ v *= d
299
+ v += (1. - d) * msd[k].detach()
300
+
301
+ def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
302
+ # Update EMA attributes
303
+ copy_attr(self.ema, model, include, exclude)
304
+
305
+
306
+ class BatchNormXd(torch.nn.modules.batchnorm._BatchNorm):
307
+ def _check_input_dim(self, input):
308
+ # The only difference between BatchNorm1d, BatchNorm2d, BatchNorm3d, etc
309
+ # is this method that is overwritten by the sub-class
310
+ # This original goal of this method was for tensor sanity checks
311
+ # If you're ok bypassing those sanity checks (eg. if you trust your inference
312
+ # to provide the right dimensional inputs), then you can just use this method
313
+ # for easy conversion from SyncBatchNorm
314
+ # (unfortunately, SyncBatchNorm does not store the original class - if it did
315
+ # we could return the one that was originally created)
316
+ return
317
+
318
+ def revert_sync_batchnorm(module):
319
+ # this is very similar to the function that it is trying to revert:
320
+ # https://github.com/pytorch/pytorch/blob/c8b3686a3e4ba63dc59e5dcfe5db3430df256833/torch/nn/modules/batchnorm.py#L679
321
+ module_output = module
322
+ if isinstance(module, torch.nn.modules.batchnorm.SyncBatchNorm):
323
+ new_cls = BatchNormXd
324
+ module_output = BatchNormXd(module.num_features,
325
+ module.eps, module.momentum,
326
+ module.affine,
327
+ module.track_running_stats)
328
+ if module.affine:
329
+ with torch.no_grad():
330
+ module_output.weight = module.weight
331
+ module_output.bias = module.bias
332
+ module_output.running_mean = module.running_mean
333
+ module_output.running_var = module.running_var
334
+ module_output.num_batches_tracked = module.num_batches_tracked
335
+ if hasattr(module, "qconfig"):
336
+ module_output.qconfig = module.qconfig
337
+ for name, child in module.named_children():
338
+ module_output.add_module(name, revert_sync_batchnorm(child))
339
+ del module
340
+ return module_output
341
+
342
+
343
+ class TracedModel(nn.Module):
344
+
345
+ def __init__(self, model=None, device=None, img_size=(640,640)):
346
+ super(TracedModel, self).__init__()
347
+
348
+ print(" Convert model to Traced-model... ")
349
+ self.stride = model.stride
350
+ self.names = model.names
351
+ self.model = model
352
+
353
+ self.model = revert_sync_batchnorm(self.model)
354
+ self.model.to('cpu')
355
+ self.model.eval()
356
+
357
+ self.detect_layer = self.model.model[-1]
358
+ self.model.traced = True
359
+
360
+ rand_example = torch.rand(1, 3, img_size, img_size)
361
+
362
+ traced_script_module = torch.jit.trace(self.model, rand_example, strict=False)
363
+ #traced_script_module = torch.jit.script(self.model)
364
+ traced_script_module.save("traced_model.pt")
365
+ print(" traced_script_module saved! ")
366
+ self.model = traced_script_module
367
+ self.model.to(device)
368
+ self.detect_layer.to(device)
369
+ print(" model is traced! \n")
370
+
371
+ def forward(self, x, augment=False, profile=False):
372
+ out = self.model(x)
373
+ out = self.detect_layer(out)
374
+ return out