EntropyDrop commited on
Commit
76d7a6e
·
verified ·
1 Parent(s): f02dec9

Release SKING_DDJ_v101c portable inference bundle

Browse files

Publish the privacy-reviewed v101 production parser as SKING_DDJ_v101c. The bundle includes tensor-identical parser and foreground weights in sanitized checkpoints, pinned offline dependencies, UV mappings, source code, portable inference, checksums, and license notices. Optimizer state, server paths, deployment records, backups, user inputs, and regression image galleries are excluded. Portability checks pass with exact alpha and visible RGB error at most 1/255. Existing releases are preserved.

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. README.md +6 -0
  3. SKING_DDJ_v101c/LICENSE +661 -0
  4. SKING_DDJ_v101c/README.md +64 -0
  5. SKING_DDJ_v101c/THIRD_PARTY_NOTICES.md +7 -0
  6. SKING_DDJ_v101c/foreground.pt +3 -0
  7. SKING_DDJ_v101c/foreground_base/BiRefNet_config.py +11 -0
  8. SKING_DDJ_v101c/foreground_base/birefnet.py +2249 -0
  9. SKING_DDJ_v101c/foreground_base/config.json +20 -0
  10. SKING_DDJ_v101c/foreground_base/model.safetensors +3 -0
  11. SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/refs/main +1 -0
  12. SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/config.json +12 -0
  13. SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/model.safetensors +3 -0
  14. SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/preprocessor_config.json +24 -0
  15. SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/special_tokens_map.json +34 -0
  16. SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.json +3 -0
  17. SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.model +3 -0
  18. SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer_config.json +2020 -0
  19. SKING_DDJ_v101c/hf_cache/modules/__init__.py +0 -0
  20. SKING_DDJ_v101c/hf_cache/modules/transformers_modules/__init__.py +0 -0
  21. SKING_DDJ_v101c/hf_cache/modules/transformers_modules/foreground_base/BiRefNet_config.py +11 -0
  22. SKING_DDJ_v101c/hf_cache/modules/transformers_modules/foreground_base/__init__.py +0 -0
  23. SKING_DDJ_v101c/hf_cache/modules/transformers_modules/foreground_base/birefnet.py +2249 -0
  24. SKING_DDJ_v101c/infer.py +214 -0
  25. SKING_DDJ_v101c/licenses/BiRefNet_LICENSE.txt +21 -0
  26. SKING_DDJ_v101c/licenses/SigLIP2_LICENSE.txt +201 -0
  27. SKING_DDJ_v101c/licenses/sources.json +14 -0
  28. SKING_DDJ_v101c/mappings_256x512/back_left_mapping.pt +3 -0
  29. SKING_DDJ_v101c/mappings_256x512/back_left_overlay_mapping.pt +3 -0
  30. SKING_DDJ_v101c/mappings_256x512/back_right_mapping.pt +3 -0
  31. SKING_DDJ_v101c/mappings_256x512/back_right_overlay_mapping.pt +3 -0
  32. SKING_DDJ_v101c/mappings_256x512/front_left_mapping.pt +3 -0
  33. SKING_DDJ_v101c/mappings_256x512/front_left_overlay_mapping.pt +3 -0
  34. SKING_DDJ_v101c/mappings_256x512/front_right_mapping.pt +3 -0
  35. SKING_DDJ_v101c/mappings_256x512/front_right_overlay_mapping.pt +3 -0
  36. SKING_DDJ_v101c/mappings_256x512/static_back_mapping.pt +3 -0
  37. SKING_DDJ_v101c/mappings_256x512/static_front_mapping.pt +3 -0
  38. SKING_DDJ_v101c/mappings_256x512/walk_back_base_layer_ortho_mapping.pt +3 -0
  39. SKING_DDJ_v101c/mappings_256x512/walk_back_both_layer_ortho_mapping.pt +3 -0
  40. SKING_DDJ_v101c/mappings_256x512/walk_front_base_layer_ortho_mapping.pt +3 -0
  41. SKING_DDJ_v101c/mappings_256x512/walk_front_both_layer_ortho_mapping.pt +3 -0
  42. SKING_DDJ_v101c/parser.pt +3 -0
  43. SKING_DDJ_v101c/pipeline.json +79 -0
  44. SKING_DDJ_v101c/release.json +142 -0
  45. SKING_DDJ_v101c/runtime/LICENSE +661 -0
  46. SKING_DDJ_v101c/runtime/dense_uv_parser/__init__.py +2 -0
  47. SKING_DDJ_v101c/runtime/dense_uv_parser/accessories.py +199 -0
  48. SKING_DDJ_v101c/runtime/dense_uv_parser/accessory_data.py +148 -0
  49. SKING_DDJ_v101c/runtime/dense_uv_parser/accessory_pipeline.py +89 -0
  50. SKING_DDJ_v101c/runtime/dense_uv_parser/accessory_regression.py +73 -0
.gitattributes CHANGED
@@ -36,3 +36,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
36
  *.jpg filter=lfs diff=lfs merge=lfs -text
37
  *.jpeg filter=lfs diff=lfs merge=lfs -text
38
  SKING_DDJ_v104/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.json filter=lfs diff=lfs merge=lfs -text
 
 
36
  *.jpg filter=lfs diff=lfs merge=lfs -text
37
  *.jpeg filter=lfs diff=lfs merge=lfs -text
38
  SKING_DDJ_v104/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.json filter=lfs diff=lfs merge=lfs -text
39
+ SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -10,6 +10,12 @@ tags:
10
 
11
  **Sking** is an image-to-Minecraft-skin generation model designed to transform character images, portraits, avatars, or concept art into Minecraft-style skin textures. Given a reference image, the model learns to preserve key visual features such as clothing, colors, hairstyle, and character identity while adapting them into the compact pixel-art structure used by Minecraft skins.
12
 
 
 
 
 
 
 
13
  ## SKING_DDJ_v104 — production UV release (2026-09-08)
14
 
15
  The full v104 render-to-UV bundle is available in [`SKING_DDJ_v104/`](SKING_DDJ_v104). It includes the dense UV parser, trained foreground model, BiRefNet and SigLIP2 dependencies, pinned runtime, UV mappings, and a portable inference launcher. It produces a 64×64 RGBA Minecraft skin from the combined front/back edited render.
 
10
 
11
  **Sking** is an image-to-Minecraft-skin generation model designed to transform character images, portraits, avatars, or concept art into Minecraft-style skin textures. Given a reference image, the model learns to preserve key visual features such as clothing, colors, hairstyle, and character identity while adapting them into the compact pixel-art structure used by Minecraft skins.
12
 
13
+ ## SKING_DDJ_v101c — recommended production UV release (2026-09-16)
14
+
15
+ The portable v101c render-to-UV bundle is available in [`SKING_DDJ_v101c/`](SKING_DDJ_v101c). It contains privacy-sanitized inference checkpoints with tensor weights identical to the deployed v101 crown-geometry release, the trained foreground model, pinned offline dependencies, UV mappings, source code, checksums, and a portable launcher.
16
+
17
+ See the [v101c download and inference instructions](SKING_DDJ_v101c/README.md). Download the complete directory rather than only `parser.pt`. The older v104 release remains available below for reproducibility.
18
+
19
  ## SKING_DDJ_v104 — production UV release (2026-09-08)
20
 
21
  The full v104 render-to-UV bundle is available in [`SKING_DDJ_v104/`](SKING_DDJ_v104). It includes the dense UV parser, trained foreground model, BiRefNet and SigLIP2 dependencies, pinned runtime, UV mappings, and a portable inference launcher. It produces a 64×64 RGBA Minecraft skin from the combined front/back edited render.
SKING_DDJ_v101c/LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
SKING_DDJ_v101c/README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SKING_DDJ_v101c
2
+
3
+ Portable open-source package of the v101 production render-to-UV pipeline, published as `SKING_DDJ_v101c`. It converts a square combined front/back Minecraft character render into a 64×64 RGBA skin with inner and outer layers. The left view is `front_left` and the right view is `back_left`, following the Sking edited-render layout. Creating that edited render is a separate upstream stage.
4
+
5
+ The parser tensor weights, foreground decoder tensor weights, pipeline behavior, and runtime are derived from the deployed v101 crown-geometry release (`crown_geometry_20260906`, source commit `28f548a5be37868022cfbafaddbe095895e18210`). The public checkpoints were repacked to remove optimizer state, private filesystem paths, and development-only manifests. Tensor equality and inference outputs were verified against the deployed release.
6
+
7
+ ## Contents
8
+
9
+ | Path | Purpose |
10
+ | --- | --- |
11
+ | `parser.pt` | Sanitized v101c dense UV parser checkpoint |
12
+ | `foreground.pt` | Sanitized trained Minecraft foreground decoder checkpoint |
13
+ | `pipeline.json` | Inference configuration with development-only path metadata removed |
14
+ | `foreground_base/` | BiRefNet base model and implementation |
15
+ | `hf_cache/` | Pinned SigLIP2 model and tokenizer for offline inference |
16
+ | `runtime/` | Matching inference and training source snapshot, without private test images |
17
+ | `mappings_256x512/` | UV mapping tensors used by production |
18
+ | `infer.py` | Portable foreground + parser + final inpainting launcher |
19
+ | `release.json` | Checksums, source artifact identities, and sanitization record |
20
+ | `tested_environments.json` | Dependency versions used for verification |
21
+
22
+ Download the complete directory. `parser.pt` by itself is insufficient to reproduce the full pipeline.
23
+
24
+ ## Download
25
+
26
+ ```python
27
+ from huggingface_hub import snapshot_download
28
+
29
+ snapshot_download(
30
+ repo_id="EntropyDrop/Sking",
31
+ allow_patterns=["SKING_DDJ_v101c/*"],
32
+ local_dir="./Sking",
33
+ )
34
+ ```
35
+
36
+ For repeatable deployments, pass the release commit hash as `revision` instead of following the repository's moving `main` branch.
37
+
38
+ ## Run
39
+
40
+ Use Linux with an NVIDIA CUDA GPU and Python 3.12. The parser environment needs PyTorch/torchvision, NumPy, Pillow, Transformers, timm, einops, SciPy, OpenCV, SentencePiece, safetensors and accelerate. The foreground environment also uses kornia. Install a CUDA-compatible PyTorch build before the remaining dependencies. The two options below may point to the same interpreter if it contains both dependency sets.
41
+
42
+ ```bash
43
+ python ./Sking/SKING_DDJ_v101c/infer.py --verify-only
44
+
45
+ /path/to/parser-env/bin/python ./Sking/SKING_DDJ_v101c/infer.py \
46
+ --parser-python /path/to/parser-env/bin/python \
47
+ --foreground-python /path/to/foreground-env/bin/python \
48
+ --input ./character_edited.png \
49
+ --output ./character_result_v101c.png
50
+ ```
51
+
52
+ Input must be an even square image between 256 and 4096 pixels wide, containing the two expected views side by side. The launcher verifies every bundled file, runs the trained foreground model, executes the pinned parser and postprocessing pipeline, validates output provenance, and writes the final 64×64 RGBA PNG. Model inference uses the included Hugging Face cache in offline mode.
53
+
54
+ ## Validation and limits
55
+
56
+ Eight fresh samples were selected across the historical v54, v61, and v66 data groups, excluding the deployment fixtures. Public-package outputs had exact alpha on all eight samples and visible RGB differences of at most 1/255 from the historical v101 results. A separate six-case deployment suite covering eyes, hair, beard, crown, hat, and glasses met the same threshold.
57
+
58
+ The repacked parser and foreground checkpoints were checked tensor-by-tensor against production. The public package contains no optimizer states, credentials, server paths, user inputs, deployment records, backup directories, or historical regression image galleries.
59
+
60
+ Semantic errors can still occur, and the model assumes the expected edited-render layout.
61
+
62
+ ## License and upstream components
63
+
64
+ Sking is licensed under AGPL-3.0; see `LICENSE`. BiRefNet and SigLIP2 retain their own licenses and attribution. See `THIRD_PARTY_NOTICES.md` and `licenses/` for pinned upstream revisions and license texts.
SKING_DDJ_v101c/THIRD_PARTY_NOTICES.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Third-party components
2
+
3
+ - `foreground_base/`: [ZhengPeng7/BiRefNet](https://huggingface.co/ZhengPeng7/BiRefNet/tree/6a62b7dcfa18a3829087877fb16c8006831e4220), MIT. License: `licenses/BiRefNet_LICENSE.txt`.
4
+ - `hf_cache/hub/models--google--siglip2-base-patch16-224/`: [google/siglip2-base-patch16-224](https://huggingface.co/google/siglip2-base-patch16-224/tree/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2), Apache-2.0. License: `licenses/SigLIP2_LICENSE.txt` (Google Big Vision repository).
5
+ - Sking weights, inference/runtime code and UV mappings are provided under the repository AGPL-3.0 license; third-party components retain their respective licenses.
6
+
7
+ Upstream license retrieval URLs and SHA-256 hashes are recorded in `licenses/sources.json`.
SKING_DDJ_v101c/foreground.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f00c1abbf736d54fcda6800ec6046817456ef9fbc45bb67bc1e6d759cfb45331
3
+ size 100142558
SKING_DDJ_v101c/foreground_base/BiRefNet_config.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class BiRefNetConfig(PretrainedConfig):
4
+ model_type = "SegformerForSemanticSegmentation"
5
+ def __init__(
6
+ self,
7
+ bb_pretrained=False,
8
+ **kwargs
9
+ ):
10
+ self.bb_pretrained = bb_pretrained
11
+ super().__init__(**kwargs)
SKING_DDJ_v101c/foreground_base/birefnet.py ADDED
@@ -0,0 +1,2249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### config.py
2
+
3
+ import os
4
+ import math
5
+ from transformers import PretrainedConfig
6
+
7
+
8
+ class Config(PretrainedConfig):
9
+ def __init__(self) -> None:
10
+ # PATH settings
11
+ self.sys_home_dir = os.path.expanduser('~') # Make up your file system as: SYS_HOME_DIR/codes/dis/BiRefNet, SYS_HOME_DIR/datasets/dis/xx, SYS_HOME_DIR/weights/xx
12
+
13
+ # TASK settings
14
+ self.task = ['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'][0]
15
+ self.training_set = {
16
+ 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0],
17
+ 'COD': 'TR-COD10K+TR-CAMO',
18
+ 'HRSOD': ['TR-DUTS', 'TR-HRSOD', 'TR-UHRSD', 'TR-DUTS+TR-HRSOD', 'TR-DUTS+TR-UHRSD', 'TR-HRSOD+TR-UHRSD', 'TR-DUTS+TR-HRSOD+TR-UHRSD'][5],
19
+ 'DIS5K+HRSOD+HRS10K': 'DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4+DIS-TR+TE-HRS10K+TE-HRSOD+TE-UHRSD+TR-HRS10K+TR-HRSOD+TR-UHRSD', # leave DIS-VD for evaluation.
20
+ 'P3M-10k': 'TR-P3M-10k',
21
+ }[self.task]
22
+ self.prompt4loc = ['dense', 'sparse'][0]
23
+
24
+ # Faster-Training settings
25
+ self.load_all = True
26
+ self.compile = True # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch.
27
+ # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting.
28
+ # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607.
29
+ # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training.
30
+ self.precisionHigh = True
31
+
32
+ # MODEL settings
33
+ self.ms_supervision = True
34
+ self.out_ref = self.ms_supervision and True
35
+ self.dec_ipt = True
36
+ self.dec_ipt_split = True
37
+ self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder
38
+ self.mul_scl_ipt = ['', 'add', 'cat'][2]
39
+ self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2]
40
+ self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1]
41
+ self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0]
42
+
43
+ # TRAINING settings
44
+ self.batch_size = 4
45
+ self.IoU_finetune_last_epochs = [
46
+ 0,
47
+ {
48
+ 'DIS5K': -50,
49
+ 'COD': -20,
50
+ 'HRSOD': -20,
51
+ 'DIS5K+HRSOD+HRS10K': -20,
52
+ 'P3M-10k': -20,
53
+ }[self.task]
54
+ ][1] # choose 0 to skip
55
+ self.lr = (1e-4 if 'DIS5K' in self.task else 1e-5) * math.sqrt(self.batch_size / 4) # DIS needs high lr to converge faster. Adapt the lr linearly
56
+ self.size = 1024
57
+ self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader
58
+
59
+ # Backbone settings
60
+ self.bb = [
61
+ 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2
62
+ 'swin_v1_t', 'swin_v1_s', # 3, 4
63
+ 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs4
64
+ 'pvt_v2_b0', 'pvt_v2_b1', # 7, 8
65
+ 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5
66
+ ][6]
67
+ self.lateral_channels_in_collection = {
68
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
69
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
70
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
71
+ 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96],
72
+ 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64],
73
+ }[self.bb]
74
+ if self.mul_scl_ipt == 'cat':
75
+ self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection]
76
+ self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []
77
+
78
+ # MODEL settings - inactive
79
+ self.lat_blk = ['BasicLatBlk'][0]
80
+ self.dec_channels_inter = ['fixed', 'adap'][0]
81
+ self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0]
82
+ self.progressive_ref = self.refine and True
83
+ self.ender = self.progressive_ref and False
84
+ self.scale = self.progressive_ref and 2
85
+ self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`.
86
+ self.refine_iteration = 1
87
+ self.freeze_bb = False
88
+ self.model = [
89
+ 'BiRefNet',
90
+ ][0]
91
+ if self.dec_blk == 'HierarAttDecBlk':
92
+ self.batch_size = 2 ** [0, 1, 2, 3, 4][2]
93
+
94
+ # TRAINING settings - inactive
95
+ self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4]
96
+ self.optimizer = ['Adam', 'AdamW'][1]
97
+ self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch.
98
+ self.lr_decay_rate = 0.5
99
+ # Loss
100
+ self.lambdas_pix_last = {
101
+ # not 0 means opening this loss
102
+ # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30
103
+ 'bce': 30 * 1, # high performance
104
+ 'iou': 0.5 * 1, # 0 / 255
105
+ 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64)
106
+ 'mse': 150 * 0, # can smooth the saliency map
107
+ 'triplet': 3 * 0,
108
+ 'reg': 100 * 0,
109
+ 'ssim': 10 * 1, # help contours,
110
+ 'cnt': 5 * 0, # help contours
111
+ 'structure': 5 * 0, # structure loss from codes of MVANet. A little improvement on DIS-TE[1,2,3], a bit more decrease on DIS-TE4.
112
+ }
113
+ self.lambdas_cls = {
114
+ 'ce': 5.0
115
+ }
116
+ # Adv
117
+ self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training
118
+ self.lambda_adv_d = 3. * (self.lambda_adv_g > 0)
119
+
120
+ # PATH settings - inactive
121
+ self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis')
122
+ self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights')
123
+ self.weights = {
124
+ 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'),
125
+ 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]),
126
+ 'swin_v1_b': os.path.join(self.weights_root_dir, ['swin_base_patch4_window12_384_22kto1k.pth', 'swin_base_patch4_window12_384_22k.pth'][0]),
127
+ 'swin_v1_l': os.path.join(self.weights_root_dir, ['swin_large_patch4_window12_384_22kto1k.pth', 'swin_large_patch4_window12_384_22k.pth'][0]),
128
+ 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]),
129
+ 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]),
130
+ 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]),
131
+ 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]),
132
+ }
133
+
134
+ # Callbacks - inactive
135
+ self.verbose_eval = True
136
+ self.only_S_MAE = False
137
+ self.use_fp16 = False # Bugs. It may cause nan in training.
138
+ self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs
139
+
140
+ # others
141
+ self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')
142
+
143
+ self.batch_size_valid = 1
144
+ self.rand_seed = 7
145
+ # run_sh_file = [f for f in os.listdir('.') if 'train.sh' == f] + [os.path.join('..', f) for f in os.listdir('..') if 'train.sh' == f]
146
+ # with open(run_sh_file[0], 'r') as f:
147
+ # lines = f.readlines()
148
+ # self.save_last = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'val_last=' in l][0].split('val_last=')[-1].split()[0])
149
+ # self.save_step = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'step=' in l][0].split('step=')[-1].split()[0])
150
+ # self.val_step = [0, self.save_step][0]
151
+
152
+ def print_task(self) -> None:
153
+ # Return task for choosing settings in shell scripts.
154
+ print(self.task)
155
+
156
+
157
+
158
+ ### models/backbones/pvt_v2.py
159
+
160
+ import torch
161
+ import torch.nn as nn
162
+ from functools import partial
163
+
164
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
165
+ from timm.models.registry import register_model
166
+
167
+ import math
168
+
169
+ # from config import Config
170
+
171
+ # config = Config()
172
+
173
+ class Mlp(nn.Module):
174
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
175
+ super().__init__()
176
+ out_features = out_features or in_features
177
+ hidden_features = hidden_features or in_features
178
+ self.fc1 = nn.Linear(in_features, hidden_features)
179
+ self.dwconv = DWConv(hidden_features)
180
+ self.act = act_layer()
181
+ self.fc2 = nn.Linear(hidden_features, out_features)
182
+ self.drop = nn.Dropout(drop)
183
+
184
+ self.apply(self._init_weights)
185
+
186
+ def _init_weights(self, m):
187
+ if isinstance(m, nn.Linear):
188
+ trunc_normal_(m.weight, std=.02)
189
+ if isinstance(m, nn.Linear) and m.bias is not None:
190
+ nn.init.constant_(m.bias, 0)
191
+ elif isinstance(m, nn.LayerNorm):
192
+ nn.init.constant_(m.bias, 0)
193
+ nn.init.constant_(m.weight, 1.0)
194
+ elif isinstance(m, nn.Conv2d):
195
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
196
+ fan_out //= m.groups
197
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
198
+ if m.bias is not None:
199
+ m.bias.data.zero_()
200
+
201
+ def forward(self, x, H, W):
202
+ x = self.fc1(x)
203
+ x = self.dwconv(x, H, W)
204
+ x = self.act(x)
205
+ x = self.drop(x)
206
+ x = self.fc2(x)
207
+ x = self.drop(x)
208
+ return x
209
+
210
+
211
+ class Attention(nn.Module):
212
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
213
+ super().__init__()
214
+ assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
215
+
216
+ self.dim = dim
217
+ self.num_heads = num_heads
218
+ head_dim = dim // num_heads
219
+ self.scale = qk_scale or head_dim ** -0.5
220
+
221
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
222
+ self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
223
+ self.attn_drop_prob = attn_drop
224
+ self.attn_drop = nn.Dropout(attn_drop)
225
+ self.proj = nn.Linear(dim, dim)
226
+ self.proj_drop = nn.Dropout(proj_drop)
227
+
228
+ self.sr_ratio = sr_ratio
229
+ if sr_ratio > 1:
230
+ self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
231
+ self.norm = nn.LayerNorm(dim)
232
+
233
+ self.apply(self._init_weights)
234
+
235
+ def _init_weights(self, m):
236
+ if isinstance(m, nn.Linear):
237
+ trunc_normal_(m.weight, std=.02)
238
+ if isinstance(m, nn.Linear) and m.bias is not None:
239
+ nn.init.constant_(m.bias, 0)
240
+ elif isinstance(m, nn.LayerNorm):
241
+ nn.init.constant_(m.bias, 0)
242
+ nn.init.constant_(m.weight, 1.0)
243
+ elif isinstance(m, nn.Conv2d):
244
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
245
+ fan_out //= m.groups
246
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
247
+ if m.bias is not None:
248
+ m.bias.data.zero_()
249
+
250
+ def forward(self, x, H, W):
251
+ B, N, C = x.shape
252
+ q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
253
+
254
+ if self.sr_ratio > 1:
255
+ x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
256
+ x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
257
+ x_ = self.norm(x_)
258
+ kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
259
+ else:
260
+ kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
261
+ k, v = kv[0], kv[1]
262
+
263
+ if config.SDPA_enabled:
264
+ x = torch.nn.functional.scaled_dot_product_attention(
265
+ q, k, v,
266
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
267
+ ).transpose(1, 2).reshape(B, N, C)
268
+ else:
269
+ attn = (q @ k.transpose(-2, -1)) * self.scale
270
+ attn = attn.softmax(dim=-1)
271
+ attn = self.attn_drop(attn)
272
+
273
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
274
+ x = self.proj(x)
275
+ x = self.proj_drop(x)
276
+
277
+ return x
278
+
279
+
280
+ class Block(nn.Module):
281
+
282
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
283
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
284
+ super().__init__()
285
+ self.norm1 = norm_layer(dim)
286
+ self.attn = Attention(
287
+ dim,
288
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
289
+ attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
290
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
291
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
292
+ self.norm2 = norm_layer(dim)
293
+ mlp_hidden_dim = int(dim * mlp_ratio)
294
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
295
+
296
+ self.apply(self._init_weights)
297
+
298
+ def _init_weights(self, m):
299
+ if isinstance(m, nn.Linear):
300
+ trunc_normal_(m.weight, std=.02)
301
+ if isinstance(m, nn.Linear) and m.bias is not None:
302
+ nn.init.constant_(m.bias, 0)
303
+ elif isinstance(m, nn.LayerNorm):
304
+ nn.init.constant_(m.bias, 0)
305
+ nn.init.constant_(m.weight, 1.0)
306
+ elif isinstance(m, nn.Conv2d):
307
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
308
+ fan_out //= m.groups
309
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
310
+ if m.bias is not None:
311
+ m.bias.data.zero_()
312
+
313
+ def forward(self, x, H, W):
314
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
315
+ x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
316
+
317
+ return x
318
+
319
+
320
+ class OverlapPatchEmbed(nn.Module):
321
+ """ Image to Patch Embedding
322
+ """
323
+
324
+ def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768):
325
+ super().__init__()
326
+ img_size = to_2tuple(img_size)
327
+ patch_size = to_2tuple(patch_size)
328
+
329
+ self.img_size = img_size
330
+ self.patch_size = patch_size
331
+ self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
332
+ self.num_patches = self.H * self.W
333
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride,
334
+ padding=(patch_size[0] // 2, patch_size[1] // 2))
335
+ self.norm = nn.LayerNorm(embed_dim)
336
+
337
+ self.apply(self._init_weights)
338
+
339
+ def _init_weights(self, m):
340
+ if isinstance(m, nn.Linear):
341
+ trunc_normal_(m.weight, std=.02)
342
+ if isinstance(m, nn.Linear) and m.bias is not None:
343
+ nn.init.constant_(m.bias, 0)
344
+ elif isinstance(m, nn.LayerNorm):
345
+ nn.init.constant_(m.bias, 0)
346
+ nn.init.constant_(m.weight, 1.0)
347
+ elif isinstance(m, nn.Conv2d):
348
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
349
+ fan_out //= m.groups
350
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
351
+ if m.bias is not None:
352
+ m.bias.data.zero_()
353
+
354
+ def forward(self, x):
355
+ x = self.proj(x)
356
+ _, _, H, W = x.shape
357
+ x = x.flatten(2).transpose(1, 2)
358
+ x = self.norm(x)
359
+
360
+ return x, H, W
361
+
362
+
363
+ class PyramidVisionTransformerImpr(nn.Module):
364
+ def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512],
365
+ num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,
366
+ attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
367
+ depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):
368
+ super().__init__()
369
+ self.num_classes = num_classes
370
+ self.depths = depths
371
+
372
+ # patch_embed
373
+ self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels,
374
+ embed_dim=embed_dims[0])
375
+ self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0],
376
+ embed_dim=embed_dims[1])
377
+ self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1],
378
+ embed_dim=embed_dims[2])
379
+ self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2],
380
+ embed_dim=embed_dims[3])
381
+
382
+ # transformer encoder
383
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
384
+ cur = 0
385
+ self.block1 = nn.ModuleList([Block(
386
+ dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,
387
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
388
+ sr_ratio=sr_ratios[0])
389
+ for i in range(depths[0])])
390
+ self.norm1 = norm_layer(embed_dims[0])
391
+
392
+ cur += depths[0]
393
+ self.block2 = nn.ModuleList([Block(
394
+ dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,
395
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
396
+ sr_ratio=sr_ratios[1])
397
+ for i in range(depths[1])])
398
+ self.norm2 = norm_layer(embed_dims[1])
399
+
400
+ cur += depths[1]
401
+ self.block3 = nn.ModuleList([Block(
402
+ dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,
403
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
404
+ sr_ratio=sr_ratios[2])
405
+ for i in range(depths[2])])
406
+ self.norm3 = norm_layer(embed_dims[2])
407
+
408
+ cur += depths[2]
409
+ self.block4 = nn.ModuleList([Block(
410
+ dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,
411
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
412
+ sr_ratio=sr_ratios[3])
413
+ for i in range(depths[3])])
414
+ self.norm4 = norm_layer(embed_dims[3])
415
+
416
+ # classification head
417
+ # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
418
+
419
+ self.apply(self._init_weights)
420
+
421
+ def _init_weights(self, m):
422
+ if isinstance(m, nn.Linear):
423
+ trunc_normal_(m.weight, std=.02)
424
+ if isinstance(m, nn.Linear) and m.bias is not None:
425
+ nn.init.constant_(m.bias, 0)
426
+ elif isinstance(m, nn.LayerNorm):
427
+ nn.init.constant_(m.bias, 0)
428
+ nn.init.constant_(m.weight, 1.0)
429
+ elif isinstance(m, nn.Conv2d):
430
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
431
+ fan_out //= m.groups
432
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
433
+ if m.bias is not None:
434
+ m.bias.data.zero_()
435
+
436
+ def init_weights(self, pretrained=None):
437
+ if isinstance(pretrained, str):
438
+ logger = 1
439
+ #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
440
+
441
+ def reset_drop_path(self, drop_path_rate):
442
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
443
+ cur = 0
444
+ for i in range(self.depths[0]):
445
+ self.block1[i].drop_path.drop_prob = dpr[cur + i]
446
+
447
+ cur += self.depths[0]
448
+ for i in range(self.depths[1]):
449
+ self.block2[i].drop_path.drop_prob = dpr[cur + i]
450
+
451
+ cur += self.depths[1]
452
+ for i in range(self.depths[2]):
453
+ self.block3[i].drop_path.drop_prob = dpr[cur + i]
454
+
455
+ cur += self.depths[2]
456
+ for i in range(self.depths[3]):
457
+ self.block4[i].drop_path.drop_prob = dpr[cur + i]
458
+
459
+ def freeze_patch_emb(self):
460
+ self.patch_embed1.requires_grad = False
461
+
462
+ @torch.jit.ignore
463
+ def no_weight_decay(self):
464
+ return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
465
+
466
+ def get_classifier(self):
467
+ return self.head
468
+
469
+ def reset_classifier(self, num_classes, global_pool=''):
470
+ self.num_classes = num_classes
471
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
472
+
473
+ def forward_features(self, x):
474
+ B = x.shape[0]
475
+ outs = []
476
+
477
+ # stage 1
478
+ x, H, W = self.patch_embed1(x)
479
+ for i, blk in enumerate(self.block1):
480
+ x = blk(x, H, W)
481
+ x = self.norm1(x)
482
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
483
+ outs.append(x)
484
+
485
+ # stage 2
486
+ x, H, W = self.patch_embed2(x)
487
+ for i, blk in enumerate(self.block2):
488
+ x = blk(x, H, W)
489
+ x = self.norm2(x)
490
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
491
+ outs.append(x)
492
+
493
+ # stage 3
494
+ x, H, W = self.patch_embed3(x)
495
+ for i, blk in enumerate(self.block3):
496
+ x = blk(x, H, W)
497
+ x = self.norm3(x)
498
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
499
+ outs.append(x)
500
+
501
+ # stage 4
502
+ x, H, W = self.patch_embed4(x)
503
+ for i, blk in enumerate(self.block4):
504
+ x = blk(x, H, W)
505
+ x = self.norm4(x)
506
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
507
+ outs.append(x)
508
+
509
+ return outs
510
+
511
+ # return x.mean(dim=1)
512
+
513
+ def forward(self, x):
514
+ x = self.forward_features(x)
515
+ # x = self.head(x)
516
+
517
+ return x
518
+
519
+
520
+ class DWConv(nn.Module):
521
+ def __init__(self, dim=768):
522
+ super(DWConv, self).__init__()
523
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
524
+
525
+ def forward(self, x, H, W):
526
+ B, N, C = x.shape
527
+ x = x.transpose(1, 2).view(B, C, H, W).contiguous()
528
+ x = self.dwconv(x)
529
+ x = x.flatten(2).transpose(1, 2)
530
+
531
+ return x
532
+
533
+
534
+ def _conv_filter(state_dict, patch_size=16):
535
+ """ convert patch embedding weight from manual patchify + linear proj to conv"""
536
+ out_dict = {}
537
+ for k, v in state_dict.items():
538
+ if 'patch_embed.proj.weight' in k:
539
+ v = v.reshape((v.shape[0], 3, patch_size, patch_size))
540
+ out_dict[k] = v
541
+
542
+ return out_dict
543
+
544
+
545
+ ## @register_model
546
+ class pvt_v2_b0(PyramidVisionTransformerImpr):
547
+ def __init__(self, **kwargs):
548
+ super(pvt_v2_b0, self).__init__(
549
+ patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
550
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
551
+ drop_rate=0.0, drop_path_rate=0.1)
552
+
553
+
554
+
555
+ ## @register_model
556
+ class pvt_v2_b1(PyramidVisionTransformerImpr):
557
+ def __init__(self, **kwargs):
558
+ super(pvt_v2_b1, self).__init__(
559
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
560
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
561
+ drop_rate=0.0, drop_path_rate=0.1)
562
+
563
+ ## @register_model
564
+ class pvt_v2_b2(PyramidVisionTransformerImpr):
565
+ def __init__(self, in_channels=3, **kwargs):
566
+ super(pvt_v2_b2, self).__init__(
567
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
568
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],
569
+ drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)
570
+
571
+ ## @register_model
572
+ class pvt_v2_b3(PyramidVisionTransformerImpr):
573
+ def __init__(self, **kwargs):
574
+ super(pvt_v2_b3, self).__init__(
575
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
576
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],
577
+ drop_rate=0.0, drop_path_rate=0.1)
578
+
579
+ ## @register_model
580
+ class pvt_v2_b4(PyramidVisionTransformerImpr):
581
+ def __init__(self, **kwargs):
582
+ super(pvt_v2_b4, self).__init__(
583
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
584
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],
585
+ drop_rate=0.0, drop_path_rate=0.1)
586
+
587
+
588
+ ## @register_model
589
+ class pvt_v2_b5(PyramidVisionTransformerImpr):
590
+ def __init__(self, **kwargs):
591
+ super(pvt_v2_b5, self).__init__(
592
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
593
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],
594
+ drop_rate=0.0, drop_path_rate=0.1)
595
+
596
+
597
+
598
+ ### models/backbones/swin_v1.py
599
+
600
+ # --------------------------------------------------------
601
+ # Swin Transformer
602
+ # Copyright (c) 2021 Microsoft
603
+ # Licensed under The MIT License [see LICENSE for details]
604
+ # Written by Ze Liu, Yutong Lin, Yixuan Wei
605
+ # --------------------------------------------------------
606
+
607
+ import torch
608
+ import torch.nn as nn
609
+ import torch.nn.functional as F
610
+ import torch.utils.checkpoint as checkpoint
611
+ import numpy as np
612
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
613
+
614
+ # from config import Config
615
+
616
+
617
+ # config = Config()
618
+
619
+
620
+ class Mlp(nn.Module):
621
+ """ Multilayer perceptron."""
622
+
623
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
624
+ super().__init__()
625
+ out_features = out_features or in_features
626
+ hidden_features = hidden_features or in_features
627
+ self.fc1 = nn.Linear(in_features, hidden_features)
628
+ self.act = act_layer()
629
+ self.fc2 = nn.Linear(hidden_features, out_features)
630
+ self.drop = nn.Dropout(drop)
631
+
632
+ def forward(self, x):
633
+ x = self.fc1(x)
634
+ x = self.act(x)
635
+ x = self.drop(x)
636
+ x = self.fc2(x)
637
+ x = self.drop(x)
638
+ return x
639
+
640
+
641
+ def window_partition(x, window_size):
642
+ """
643
+ Args:
644
+ x: (B, H, W, C)
645
+ window_size (int): window size
646
+
647
+ Returns:
648
+ windows: (num_windows*B, window_size, window_size, C)
649
+ """
650
+ B, H, W, C = x.shape
651
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
652
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
653
+ return windows
654
+
655
+
656
+ def window_reverse(windows, window_size, H, W):
657
+ """
658
+ Args:
659
+ windows: (num_windows*B, window_size, window_size, C)
660
+ window_size (int): Window size
661
+ H (int): Height of image
662
+ W (int): Width of image
663
+
664
+ Returns:
665
+ x: (B, H, W, C)
666
+ """
667
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
668
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
669
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
670
+ return x
671
+
672
+
673
+ class WindowAttention(nn.Module):
674
+ """ Window based multi-head self attention (W-MSA) module with relative position bias.
675
+ It supports both of shifted and non-shifted window.
676
+
677
+ Args:
678
+ dim (int): Number of input channels.
679
+ window_size (tuple[int]): The height and width of the window.
680
+ num_heads (int): Number of attention heads.
681
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
682
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
683
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
684
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
685
+ """
686
+
687
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
688
+
689
+ super().__init__()
690
+ self.dim = dim
691
+ self.window_size = window_size # Wh, Ww
692
+ self.num_heads = num_heads
693
+ head_dim = dim // num_heads
694
+ self.scale = qk_scale or head_dim ** -0.5
695
+
696
+ # define a parameter table of relative position bias
697
+ self.relative_position_bias_table = nn.Parameter(
698
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
699
+
700
+ # get pair-wise relative position index for each token inside the window
701
+ coords_h = torch.arange(self.window_size[0])
702
+ coords_w = torch.arange(self.window_size[1])
703
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww
704
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
705
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
706
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
707
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
708
+ relative_coords[:, :, 1] += self.window_size[1] - 1
709
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
710
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
711
+ self.register_buffer("relative_position_index", relative_position_index)
712
+
713
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
714
+ self.attn_drop_prob = attn_drop
715
+ self.attn_drop = nn.Dropout(attn_drop)
716
+ self.proj = nn.Linear(dim, dim)
717
+ self.proj_drop = nn.Dropout(proj_drop)
718
+
719
+ trunc_normal_(self.relative_position_bias_table, std=.02)
720
+ self.softmax = nn.Softmax(dim=-1)
721
+
722
+ def forward(self, x, mask=None):
723
+ """ Forward function.
724
+
725
+ Args:
726
+ x: input features with shape of (num_windows*B, N, C)
727
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
728
+ """
729
+ B_, N, C = x.shape
730
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
731
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
732
+
733
+ q = q * self.scale
734
+
735
+ if config.SDPA_enabled:
736
+ x = torch.nn.functional.scaled_dot_product_attention(
737
+ q, k, v,
738
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
739
+ ).transpose(1, 2).reshape(B_, N, C)
740
+ else:
741
+ attn = (q @ k.transpose(-2, -1))
742
+
743
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
744
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
745
+ ) # Wh*Ww, Wh*Ww, nH
746
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
747
+ attn = attn + relative_position_bias.unsqueeze(0)
748
+
749
+ if mask is not None:
750
+ nW = mask.shape[0]
751
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
752
+ attn = attn.view(-1, self.num_heads, N, N)
753
+ attn = self.softmax(attn)
754
+ else:
755
+ attn = self.softmax(attn)
756
+
757
+ attn = self.attn_drop(attn)
758
+
759
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
760
+ x = self.proj(x)
761
+ x = self.proj_drop(x)
762
+ return x
763
+
764
+
765
+ class SwinTransformerBlock(nn.Module):
766
+ """ Swin Transformer Block.
767
+
768
+ Args:
769
+ dim (int): Number of input channels.
770
+ num_heads (int): Number of attention heads.
771
+ window_size (int): Window size.
772
+ shift_size (int): Shift size for SW-MSA.
773
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
774
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
775
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
776
+ drop (float, optional): Dropout rate. Default: 0.0
777
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
778
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
779
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
780
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
781
+ """
782
+
783
+ def __init__(self, dim, num_heads, window_size=7, shift_size=0,
784
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
785
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm):
786
+ super().__init__()
787
+ self.dim = dim
788
+ self.num_heads = num_heads
789
+ self.window_size = window_size
790
+ self.shift_size = shift_size
791
+ self.mlp_ratio = mlp_ratio
792
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
793
+
794
+ self.norm1 = norm_layer(dim)
795
+ self.attn = WindowAttention(
796
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
797
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
798
+
799
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
800
+ self.norm2 = norm_layer(dim)
801
+ mlp_hidden_dim = int(dim * mlp_ratio)
802
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
803
+
804
+ self.H = None
805
+ self.W = None
806
+
807
+ def forward(self, x, mask_matrix):
808
+ """ Forward function.
809
+
810
+ Args:
811
+ x: Input feature, tensor size (B, H*W, C).
812
+ H, W: Spatial resolution of the input feature.
813
+ mask_matrix: Attention mask for cyclic shift.
814
+ """
815
+ B, L, C = x.shape
816
+ H, W = self.H, self.W
817
+ assert L == H * W, "input feature has wrong size"
818
+
819
+ shortcut = x
820
+ x = self.norm1(x)
821
+ x = x.view(B, H, W, C)
822
+
823
+ # pad feature maps to multiples of window size
824
+ pad_l = pad_t = 0
825
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
826
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
827
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
828
+ _, Hp, Wp, _ = x.shape
829
+
830
+ # cyclic shift
831
+ if self.shift_size > 0:
832
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
833
+ attn_mask = mask_matrix
834
+ else:
835
+ shifted_x = x
836
+ attn_mask = None
837
+
838
+ # partition windows
839
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
840
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
841
+
842
+ # W-MSA/SW-MSA
843
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
844
+
845
+ # merge windows
846
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
847
+ shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
848
+
849
+ # reverse cyclic shift
850
+ if self.shift_size > 0:
851
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
852
+ else:
853
+ x = shifted_x
854
+
855
+ if pad_r > 0 or pad_b > 0:
856
+ x = x[:, :H, :W, :].contiguous()
857
+
858
+ x = x.view(B, H * W, C)
859
+
860
+ # FFN
861
+ x = shortcut + self.drop_path(x)
862
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
863
+
864
+ return x
865
+
866
+
867
+ class PatchMerging(nn.Module):
868
+ """ Patch Merging Layer
869
+
870
+ Args:
871
+ dim (int): Number of input channels.
872
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
873
+ """
874
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
875
+ super().__init__()
876
+ self.dim = dim
877
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
878
+ self.norm = norm_layer(4 * dim)
879
+
880
+ def forward(self, x, H, W):
881
+ """ Forward function.
882
+
883
+ Args:
884
+ x: Input feature, tensor size (B, H*W, C).
885
+ H, W: Spatial resolution of the input feature.
886
+ """
887
+ B, L, C = x.shape
888
+ assert L == H * W, "input feature has wrong size"
889
+
890
+ x = x.view(B, H, W, C)
891
+
892
+ # padding
893
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
894
+ if pad_input:
895
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
896
+
897
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
898
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
899
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
900
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
901
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
902
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
903
+
904
+ x = self.norm(x)
905
+ x = self.reduction(x)
906
+
907
+ return x
908
+
909
+
910
+ class BasicLayer(nn.Module):
911
+ """ A basic Swin Transformer layer for one stage.
912
+
913
+ Args:
914
+ dim (int): Number of feature channels
915
+ depth (int): Depths of this stage.
916
+ num_heads (int): Number of attention head.
917
+ window_size (int): Local window size. Default: 7.
918
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
919
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
920
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
921
+ drop (float, optional): Dropout rate. Default: 0.0
922
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
923
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
924
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
925
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
926
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
927
+ """
928
+
929
+ def __init__(self,
930
+ dim,
931
+ depth,
932
+ num_heads,
933
+ window_size=7,
934
+ mlp_ratio=4.,
935
+ qkv_bias=True,
936
+ qk_scale=None,
937
+ drop=0.,
938
+ attn_drop=0.,
939
+ drop_path=0.,
940
+ norm_layer=nn.LayerNorm,
941
+ downsample=None,
942
+ use_checkpoint=False):
943
+ super().__init__()
944
+ self.window_size = window_size
945
+ self.shift_size = window_size // 2
946
+ self.depth = depth
947
+ self.use_checkpoint = use_checkpoint
948
+
949
+ # build blocks
950
+ self.blocks = nn.ModuleList([
951
+ SwinTransformerBlock(
952
+ dim=dim,
953
+ num_heads=num_heads,
954
+ window_size=window_size,
955
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
956
+ mlp_ratio=mlp_ratio,
957
+ qkv_bias=qkv_bias,
958
+ qk_scale=qk_scale,
959
+ drop=drop,
960
+ attn_drop=attn_drop,
961
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
962
+ norm_layer=norm_layer)
963
+ for i in range(depth)])
964
+
965
+ # patch merging layer
966
+ if downsample is not None:
967
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
968
+ else:
969
+ self.downsample = None
970
+
971
+ def forward(self, x, H, W):
972
+ """ Forward function.
973
+
974
+ Args:
975
+ x: Input feature, tensor size (B, H*W, C).
976
+ H, W: Spatial resolution of the input feature.
977
+ """
978
+
979
+ # calculate attention mask for SW-MSA
980
+ # Turn int to torch.tensor for the compatiability with torch.compile in PyTorch 2.5.
981
+ Hp = torch.ceil(torch.tensor(H) / self.window_size).to(torch.int64) * self.window_size
982
+ Wp = torch.ceil(torch.tensor(W) / self.window_size).to(torch.int64) * self.window_size
983
+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
984
+ h_slices = (slice(0, -self.window_size),
985
+ slice(-self.window_size, -self.shift_size),
986
+ slice(-self.shift_size, None))
987
+ w_slices = (slice(0, -self.window_size),
988
+ slice(-self.window_size, -self.shift_size),
989
+ slice(-self.shift_size, None))
990
+ cnt = 0
991
+ for h in h_slices:
992
+ for w in w_slices:
993
+ img_mask[:, h, w, :] = cnt
994
+ cnt += 1
995
+
996
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
997
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
998
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
999
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)).to(x.dtype)
1000
+
1001
+ for blk in self.blocks:
1002
+ blk.H, blk.W = H, W
1003
+ if self.use_checkpoint:
1004
+ x = checkpoint.checkpoint(blk, x, attn_mask)
1005
+ else:
1006
+ x = blk(x, attn_mask)
1007
+ if self.downsample is not None:
1008
+ x_down = self.downsample(x, H, W)
1009
+ Wh, Ww = (H + 1) // 2, (W + 1) // 2
1010
+ return x, H, W, x_down, Wh, Ww
1011
+ else:
1012
+ return x, H, W, x, H, W
1013
+
1014
+
1015
+ class PatchEmbed(nn.Module):
1016
+ """ Image to Patch Embedding
1017
+
1018
+ Args:
1019
+ patch_size (int): Patch token size. Default: 4.
1020
+ in_channels (int): Number of input image channels. Default: 3.
1021
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1022
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
1023
+ """
1024
+
1025
+ def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None):
1026
+ super().__init__()
1027
+ patch_size = to_2tuple(patch_size)
1028
+ self.patch_size = patch_size
1029
+
1030
+ self.in_channels = in_channels
1031
+ self.embed_dim = embed_dim
1032
+
1033
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
1034
+ if norm_layer is not None:
1035
+ self.norm = norm_layer(embed_dim)
1036
+ else:
1037
+ self.norm = None
1038
+
1039
+ def forward(self, x):
1040
+ """Forward function."""
1041
+ # padding
1042
+ _, _, H, W = x.size()
1043
+ if W % self.patch_size[1] != 0:
1044
+ x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
1045
+ if H % self.patch_size[0] != 0:
1046
+ x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
1047
+
1048
+ x = self.proj(x) # B C Wh Ww
1049
+ if self.norm is not None:
1050
+ Wh, Ww = x.size(2), x.size(3)
1051
+ x = x.flatten(2).transpose(1, 2)
1052
+ x = self.norm(x)
1053
+ x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
1054
+
1055
+ return x
1056
+
1057
+
1058
+ class SwinTransformer(nn.Module):
1059
+ """ Swin Transformer backbone.
1060
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
1061
+ https://arxiv.org/pdf/2103.14030
1062
+
1063
+ Args:
1064
+ pretrain_img_size (int): Input image size for training the pretrained model,
1065
+ used in absolute postion embedding. Default 224.
1066
+ patch_size (int | tuple(int)): Patch size. Default: 4.
1067
+ in_channels (int): Number of input image channels. Default: 3.
1068
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1069
+ depths (tuple[int]): Depths of each Swin Transformer stage.
1070
+ num_heads (tuple[int]): Number of attention head of each stage.
1071
+ window_size (int): Window size. Default: 7.
1072
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
1073
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
1074
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
1075
+ drop_rate (float): Dropout rate.
1076
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
1077
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
1078
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
1079
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
1080
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True.
1081
+ out_indices (Sequence[int]): Output from which stages.
1082
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
1083
+ -1 means not freezing any parameters.
1084
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
1085
+ """
1086
+
1087
+ def __init__(self,
1088
+ pretrain_img_size=224,
1089
+ patch_size=4,
1090
+ in_channels=3,
1091
+ embed_dim=96,
1092
+ depths=[2, 2, 6, 2],
1093
+ num_heads=[3, 6, 12, 24],
1094
+ window_size=7,
1095
+ mlp_ratio=4.,
1096
+ qkv_bias=True,
1097
+ qk_scale=None,
1098
+ drop_rate=0.,
1099
+ attn_drop_rate=0.,
1100
+ drop_path_rate=0.2,
1101
+ norm_layer=nn.LayerNorm,
1102
+ ape=False,
1103
+ patch_norm=True,
1104
+ out_indices=(0, 1, 2, 3),
1105
+ frozen_stages=-1,
1106
+ use_checkpoint=False):
1107
+ super().__init__()
1108
+
1109
+ self.pretrain_img_size = pretrain_img_size
1110
+ self.num_layers = len(depths)
1111
+ self.embed_dim = embed_dim
1112
+ self.ape = ape
1113
+ self.patch_norm = patch_norm
1114
+ self.out_indices = out_indices
1115
+ self.frozen_stages = frozen_stages
1116
+
1117
+ # split image into non-overlapping patches
1118
+ self.patch_embed = PatchEmbed(
1119
+ patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim,
1120
+ norm_layer=norm_layer if self.patch_norm else None)
1121
+
1122
+ # absolute position embedding
1123
+ if self.ape:
1124
+ pretrain_img_size = to_2tuple(pretrain_img_size)
1125
+ patch_size = to_2tuple(patch_size)
1126
+ patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
1127
+
1128
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))
1129
+ trunc_normal_(self.absolute_pos_embed, std=.02)
1130
+
1131
+ self.pos_drop = nn.Dropout(p=drop_rate)
1132
+
1133
+ # stochastic depth
1134
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
1135
+
1136
+ # build layers
1137
+ self.layers = nn.ModuleList()
1138
+ for i_layer in range(self.num_layers):
1139
+ layer = BasicLayer(
1140
+ dim=int(embed_dim * 2 ** i_layer),
1141
+ depth=depths[i_layer],
1142
+ num_heads=num_heads[i_layer],
1143
+ window_size=window_size,
1144
+ mlp_ratio=mlp_ratio,
1145
+ qkv_bias=qkv_bias,
1146
+ qk_scale=qk_scale,
1147
+ drop=drop_rate,
1148
+ attn_drop=attn_drop_rate,
1149
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
1150
+ norm_layer=norm_layer,
1151
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
1152
+ use_checkpoint=use_checkpoint)
1153
+ self.layers.append(layer)
1154
+
1155
+ num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
1156
+ self.num_features = num_features
1157
+
1158
+ # add a norm layer for each output
1159
+ for i_layer in out_indices:
1160
+ layer = norm_layer(num_features[i_layer])
1161
+ layer_name = f'norm{i_layer}'
1162
+ self.add_module(layer_name, layer)
1163
+
1164
+ self._freeze_stages()
1165
+
1166
+ def _freeze_stages(self):
1167
+ if self.frozen_stages >= 0:
1168
+ self.patch_embed.eval()
1169
+ for param in self.patch_embed.parameters():
1170
+ param.requires_grad = False
1171
+
1172
+ if self.frozen_stages >= 1 and self.ape:
1173
+ self.absolute_pos_embed.requires_grad = False
1174
+
1175
+ if self.frozen_stages >= 2:
1176
+ self.pos_drop.eval()
1177
+ for i in range(0, self.frozen_stages - 1):
1178
+ m = self.layers[i]
1179
+ m.eval()
1180
+ for param in m.parameters():
1181
+ param.requires_grad = False
1182
+
1183
+
1184
+ def forward(self, x):
1185
+ """Forward function."""
1186
+ x = self.patch_embed(x)
1187
+
1188
+ Wh, Ww = x.size(2), x.size(3)
1189
+ if self.ape:
1190
+ # interpolate the position embedding to the corresponding size
1191
+ absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')
1192
+ x = (x + absolute_pos_embed) # B Wh*Ww C
1193
+
1194
+ outs = []#x.contiguous()]
1195
+ x = x.flatten(2).transpose(1, 2)
1196
+ x = self.pos_drop(x)
1197
+ for i in range(self.num_layers):
1198
+ layer = self.layers[i]
1199
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
1200
+
1201
+ if i in self.out_indices:
1202
+ norm_layer = getattr(self, f'norm{i}')
1203
+ x_out = norm_layer(x_out)
1204
+
1205
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
1206
+ outs.append(out)
1207
+
1208
+ return tuple(outs)
1209
+
1210
+ def train(self, mode=True):
1211
+ """Convert the model into training mode while keep layers freezed."""
1212
+ super(SwinTransformer, self).train(mode)
1213
+ self._freeze_stages()
1214
+
1215
+ def swin_v1_t():
1216
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7)
1217
+ return model
1218
+
1219
+ def swin_v1_s():
1220
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7)
1221
+ return model
1222
+
1223
+ def swin_v1_b():
1224
+ model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12)
1225
+ return model
1226
+
1227
+ def swin_v1_l():
1228
+ model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12)
1229
+ return model
1230
+
1231
+
1232
+
1233
+ ### models/modules/deform_conv.py
1234
+
1235
+ import torch
1236
+ import torch.nn as nn
1237
+ from torchvision.ops import deform_conv2d
1238
+
1239
+
1240
+ class DeformableConv2d(nn.Module):
1241
+ def __init__(self,
1242
+ in_channels,
1243
+ out_channels,
1244
+ kernel_size=3,
1245
+ stride=1,
1246
+ padding=1,
1247
+ bias=False):
1248
+
1249
+ super(DeformableConv2d, self).__init__()
1250
+
1251
+ assert type(kernel_size) == tuple or type(kernel_size) == int
1252
+
1253
+ kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size)
1254
+ self.stride = stride if type(stride) == tuple else (stride, stride)
1255
+ self.padding = padding
1256
+
1257
+ self.offset_conv = nn.Conv2d(in_channels,
1258
+ 2 * kernel_size[0] * kernel_size[1],
1259
+ kernel_size=kernel_size,
1260
+ stride=stride,
1261
+ padding=self.padding,
1262
+ bias=True)
1263
+
1264
+ nn.init.constant_(self.offset_conv.weight, 0.)
1265
+ nn.init.constant_(self.offset_conv.bias, 0.)
1266
+
1267
+ self.modulator_conv = nn.Conv2d(in_channels,
1268
+ 1 * kernel_size[0] * kernel_size[1],
1269
+ kernel_size=kernel_size,
1270
+ stride=stride,
1271
+ padding=self.padding,
1272
+ bias=True)
1273
+
1274
+ nn.init.constant_(self.modulator_conv.weight, 0.)
1275
+ nn.init.constant_(self.modulator_conv.bias, 0.)
1276
+
1277
+ self.regular_conv = nn.Conv2d(in_channels,
1278
+ out_channels=out_channels,
1279
+ kernel_size=kernel_size,
1280
+ stride=stride,
1281
+ padding=self.padding,
1282
+ bias=bias)
1283
+
1284
+ def forward(self, x):
1285
+ #h, w = x.shape[2:]
1286
+ #max_offset = max(h, w)/4.
1287
+
1288
+ offset = self.offset_conv(x)#.clamp(-max_offset, max_offset)
1289
+ modulator = 2. * torch.sigmoid(self.modulator_conv(x))
1290
+
1291
+ x = deform_conv2d(
1292
+ input=x,
1293
+ offset=offset,
1294
+ weight=self.regular_conv.weight,
1295
+ bias=self.regular_conv.bias,
1296
+ padding=self.padding,
1297
+ mask=modulator,
1298
+ stride=self.stride,
1299
+ )
1300
+ return x
1301
+
1302
+
1303
+
1304
+
1305
+ ### utils.py
1306
+
1307
+ import torch.nn as nn
1308
+
1309
+
1310
+ def build_act_layer(act_layer):
1311
+ if act_layer == 'ReLU':
1312
+ return nn.ReLU(inplace=True)
1313
+ elif act_layer == 'SiLU':
1314
+ return nn.SiLU(inplace=True)
1315
+ elif act_layer == 'GELU':
1316
+ return nn.GELU()
1317
+
1318
+ raise NotImplementedError(f'build_act_layer does not support {act_layer}')
1319
+
1320
+
1321
+ def build_norm_layer(dim,
1322
+ norm_layer,
1323
+ in_format='channels_last',
1324
+ out_format='channels_last',
1325
+ eps=1e-6):
1326
+ layers = []
1327
+ if norm_layer == 'BN':
1328
+ if in_format == 'channels_last':
1329
+ layers.append(to_channels_first())
1330
+ layers.append(nn.BatchNorm2d(dim))
1331
+ if out_format == 'channels_last':
1332
+ layers.append(to_channels_last())
1333
+ elif norm_layer == 'LN':
1334
+ if in_format == 'channels_first':
1335
+ layers.append(to_channels_last())
1336
+ layers.append(nn.LayerNorm(dim, eps=eps))
1337
+ if out_format == 'channels_first':
1338
+ layers.append(to_channels_first())
1339
+ else:
1340
+ raise NotImplementedError(
1341
+ f'build_norm_layer does not support {norm_layer}')
1342
+ return nn.Sequential(*layers)
1343
+
1344
+
1345
+ class to_channels_first(nn.Module):
1346
+
1347
+ def __init__(self):
1348
+ super().__init__()
1349
+
1350
+ def forward(self, x):
1351
+ return x.permute(0, 3, 1, 2)
1352
+
1353
+
1354
+ class to_channels_last(nn.Module):
1355
+
1356
+ def __init__(self):
1357
+ super().__init__()
1358
+
1359
+ def forward(self, x):
1360
+ return x.permute(0, 2, 3, 1)
1361
+
1362
+
1363
+
1364
+ ### dataset.py
1365
+
1366
+ _class_labels_TR_sorted = (
1367
+ 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, '
1368
+ 'BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, '
1369
+ 'CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, '
1370
+ 'Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, '
1371
+ 'Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, '
1372
+ 'Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, '
1373
+ 'KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, '
1374
+ 'Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, '
1375
+ 'OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, '
1376
+ 'RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, '
1377
+ 'ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, '
1378
+ 'Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, '
1379
+ 'TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, '
1380
+ 'UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht'
1381
+ )
1382
+ class_labels_TR_sorted = _class_labels_TR_sorted.split(', ')
1383
+
1384
+
1385
+ ### models/backbones/build_backbones.py
1386
+
1387
+ import torch
1388
+ import torch.nn as nn
1389
+ from collections import OrderedDict
1390
+ from torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights
1391
+ # from models.pvt_v2 import pvt_v2_b0, pvt_v2_b1, pvt_v2_b2, pvt_v2_b5
1392
+ # from models.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l
1393
+ # from config import Config
1394
+
1395
+
1396
+ config = Config()
1397
+
1398
+ def build_backbone(bb_name, pretrained=True, params_settings=''):
1399
+ if bb_name == 'vgg16':
1400
+ bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0]
1401
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]}))
1402
+ elif bb_name == 'vgg16bn':
1403
+ bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0]
1404
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]}))
1405
+ elif bb_name == 'resnet50':
1406
+ bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children())
1407
+ bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]}))
1408
+ else:
1409
+ bb = eval('{}({})'.format(bb_name, params_settings))
1410
+ if pretrained:
1411
+ bb = load_weights(bb, bb_name)
1412
+ return bb
1413
+
1414
+ def load_weights(model, model_name):
1415
+ save_model = torch.load(config.weights[model_name], map_location='cpu')
1416
+ model_dict = model.state_dict()
1417
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model.items() if k in model_dict.keys()}
1418
+ # to ignore the weights with mismatched size when I modify the backbone itself.
1419
+ if not state_dict:
1420
+ save_model_keys = list(save_model.keys())
1421
+ sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None
1422
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model[sub_item].items() if k in model_dict.keys()}
1423
+ if not state_dict or not sub_item:
1424
+ print('Weights are not successully loaded. Check the state dict of weights file.')
1425
+ return None
1426
+ else:
1427
+ print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item))
1428
+ model_dict.update(state_dict)
1429
+ model.load_state_dict(model_dict)
1430
+ return model
1431
+
1432
+
1433
+
1434
+ ### models/modules/decoder_blocks.py
1435
+
1436
+ import torch
1437
+ import torch.nn as nn
1438
+ # from models.aspp import ASPP, ASPPDeformable
1439
+ # from config import Config
1440
+
1441
+
1442
+ # config = Config()
1443
+
1444
+
1445
+ class BasicDecBlk(nn.Module):
1446
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1447
+ super(BasicDecBlk, self).__init__()
1448
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1449
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1450
+ self.relu_in = nn.ReLU(inplace=True)
1451
+ if config.dec_att == 'ASPP':
1452
+ self.dec_att = ASPP(in_channels=inter_channels)
1453
+ elif config.dec_att == 'ASPPDeformable':
1454
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1455
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1456
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1457
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1458
+
1459
+ def forward(self, x):
1460
+ x = self.conv_in(x)
1461
+ x = self.bn_in(x)
1462
+ x = self.relu_in(x)
1463
+ if hasattr(self, 'dec_att'):
1464
+ x = self.dec_att(x)
1465
+ x = self.conv_out(x)
1466
+ x = self.bn_out(x)
1467
+ return x
1468
+
1469
+
1470
+ class ResBlk(nn.Module):
1471
+ def __init__(self, in_channels=64, out_channels=None, inter_channels=64):
1472
+ super(ResBlk, self).__init__()
1473
+ if out_channels is None:
1474
+ out_channels = in_channels
1475
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1476
+
1477
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1478
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1479
+ self.relu_in = nn.ReLU(inplace=True)
1480
+
1481
+ if config.dec_att == 'ASPP':
1482
+ self.dec_att = ASPP(in_channels=inter_channels)
1483
+ elif config.dec_att == 'ASPPDeformable':
1484
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1485
+
1486
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1487
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1488
+
1489
+ self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1490
+
1491
+ def forward(self, x):
1492
+ _x = self.conv_resi(x)
1493
+ x = self.conv_in(x)
1494
+ x = self.bn_in(x)
1495
+ x = self.relu_in(x)
1496
+ if hasattr(self, 'dec_att'):
1497
+ x = self.dec_att(x)
1498
+ x = self.conv_out(x)
1499
+ x = self.bn_out(x)
1500
+ return x + _x
1501
+
1502
+
1503
+
1504
+ ### models/modules/lateral_blocks.py
1505
+
1506
+ import numpy as np
1507
+ import torch
1508
+ import torch.nn as nn
1509
+ import torch.nn.functional as F
1510
+ from functools import partial
1511
+
1512
+ # from config import Config
1513
+
1514
+
1515
+ # config = Config()
1516
+
1517
+
1518
+ class BasicLatBlk(nn.Module):
1519
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1520
+ super(BasicLatBlk, self).__init__()
1521
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1522
+ self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1523
+
1524
+ def forward(self, x):
1525
+ x = self.conv(x)
1526
+ return x
1527
+
1528
+
1529
+
1530
+ ### models/modules/aspp.py
1531
+
1532
+ import torch
1533
+ import torch.nn as nn
1534
+ import torch.nn.functional as F
1535
+ # from models.deform_conv import DeformableConv2d
1536
+ # from config import Config
1537
+
1538
+
1539
+ # config = Config()
1540
+
1541
+
1542
+ class _ASPPModule(nn.Module):
1543
+ def __init__(self, in_channels, planes, kernel_size, padding, dilation):
1544
+ super(_ASPPModule, self).__init__()
1545
+ self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size,
1546
+ stride=1, padding=padding, dilation=dilation, bias=False)
1547
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1548
+ self.relu = nn.ReLU(inplace=True)
1549
+
1550
+ def forward(self, x):
1551
+ x = self.atrous_conv(x)
1552
+ x = self.bn(x)
1553
+
1554
+ return self.relu(x)
1555
+
1556
+
1557
+ class ASPP(nn.Module):
1558
+ def __init__(self, in_channels=64, out_channels=None, output_stride=16):
1559
+ super(ASPP, self).__init__()
1560
+ self.down_scale = 1
1561
+ if out_channels is None:
1562
+ out_channels = in_channels
1563
+ self.in_channelster = 256 // self.down_scale
1564
+ if output_stride == 16:
1565
+ dilations = [1, 6, 12, 18]
1566
+ elif output_stride == 8:
1567
+ dilations = [1, 12, 24, 36]
1568
+ else:
1569
+ raise NotImplementedError
1570
+
1571
+ self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0])
1572
+ self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1])
1573
+ self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2])
1574
+ self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3])
1575
+
1576
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1577
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1578
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1579
+ nn.ReLU(inplace=True))
1580
+ self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False)
1581
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1582
+ self.relu = nn.ReLU(inplace=True)
1583
+ self.dropout = nn.Dropout(0.5)
1584
+
1585
+ def forward(self, x):
1586
+ x1 = self.aspp1(x)
1587
+ x2 = self.aspp2(x)
1588
+ x3 = self.aspp3(x)
1589
+ x4 = self.aspp4(x)
1590
+ x5 = self.global_avg_pool(x)
1591
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1592
+ x = torch.cat((x1, x2, x3, x4, x5), dim=1)
1593
+
1594
+ x = self.conv1(x)
1595
+ x = self.bn1(x)
1596
+ x = self.relu(x)
1597
+
1598
+ return self.dropout(x)
1599
+
1600
+
1601
+ ##################### Deformable
1602
+ class _ASPPModuleDeformable(nn.Module):
1603
+ def __init__(self, in_channels, planes, kernel_size, padding):
1604
+ super(_ASPPModuleDeformable, self).__init__()
1605
+ self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size,
1606
+ stride=1, padding=padding, bias=False)
1607
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1608
+ self.relu = nn.ReLU(inplace=True)
1609
+
1610
+ def forward(self, x):
1611
+ x = self.atrous_conv(x)
1612
+ x = self.bn(x)
1613
+
1614
+ return self.relu(x)
1615
+
1616
+
1617
+ class ASPPDeformable(nn.Module):
1618
+ def __init__(self, in_channels, out_channels=None, parallel_block_sizes=[1, 3, 7]):
1619
+ super(ASPPDeformable, self).__init__()
1620
+ self.down_scale = 1
1621
+ if out_channels is None:
1622
+ out_channels = in_channels
1623
+ self.in_channelster = 256 // self.down_scale
1624
+
1625
+ self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0)
1626
+ self.aspp_deforms = nn.ModuleList([
1627
+ _ASPPModuleDeformable(in_channels, self.in_channelster, conv_size, padding=int(conv_size//2)) for conv_size in parallel_block_sizes
1628
+ ])
1629
+
1630
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1631
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1632
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1633
+ nn.ReLU(inplace=True))
1634
+ self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False)
1635
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1636
+ self.relu = nn.ReLU(inplace=True)
1637
+ self.dropout = nn.Dropout(0.5)
1638
+
1639
+ def forward(self, x):
1640
+ x1 = self.aspp1(x)
1641
+ x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms]
1642
+ x5 = self.global_avg_pool(x)
1643
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1644
+ x = torch.cat((x1, *x_aspp_deforms, x5), dim=1)
1645
+
1646
+ x = self.conv1(x)
1647
+ x = self.bn1(x)
1648
+ x = self.relu(x)
1649
+
1650
+ return self.dropout(x)
1651
+
1652
+
1653
+
1654
+ ### models/refinement/refiner.py
1655
+
1656
+ import torch
1657
+ import torch.nn as nn
1658
+ from collections import OrderedDict
1659
+ import torch
1660
+ import torch.nn as nn
1661
+ import torch.nn.functional as F
1662
+ from torchvision.models import vgg16, vgg16_bn
1663
+ from torchvision.models import resnet50
1664
+
1665
+ # from config import Config
1666
+ # from dataset import class_labels_TR_sorted
1667
+ # from models.build_backbone import build_backbone
1668
+ # from models.decoder_blocks import BasicDecBlk
1669
+ # from models.lateral_blocks import BasicLatBlk
1670
+ # from models.ing import *
1671
+ # from models.stem_layer import StemLayer
1672
+
1673
+
1674
+ class RefinerPVTInChannels4(nn.Module):
1675
+ def __init__(self, in_channels=3+1):
1676
+ super(RefinerPVTInChannels4, self).__init__()
1677
+ self.config = Config()
1678
+ self.epoch = 1
1679
+ self.bb = build_backbone(self.config.bb, params_settings='in_channels=4')
1680
+
1681
+ lateral_channels_in_collection = {
1682
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1683
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1684
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1685
+ }
1686
+ channels = lateral_channels_in_collection[self.config.bb]
1687
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1688
+
1689
+ self.decoder = Decoder(channels)
1690
+
1691
+ if 0:
1692
+ for key, value in self.named_parameters():
1693
+ if 'bb.' in key:
1694
+ value.requires_grad = False
1695
+
1696
+ def forward(self, x):
1697
+ if isinstance(x, list):
1698
+ x = torch.cat(x, dim=1)
1699
+ ########## Encoder ##########
1700
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1701
+ x1 = self.bb.conv1(x)
1702
+ x2 = self.bb.conv2(x1)
1703
+ x3 = self.bb.conv3(x2)
1704
+ x4 = self.bb.conv4(x3)
1705
+ else:
1706
+ x1, x2, x3, x4 = self.bb(x)
1707
+
1708
+ x4 = self.squeeze_module(x4)
1709
+
1710
+ ########## Decoder ##########
1711
+
1712
+ features = [x, x1, x2, x3, x4]
1713
+ scaled_preds = self.decoder(features)
1714
+
1715
+ return scaled_preds
1716
+
1717
+
1718
+ class Refiner(nn.Module):
1719
+ def __init__(self, in_channels=3+1):
1720
+ super(Refiner, self).__init__()
1721
+ self.config = Config()
1722
+ self.epoch = 1
1723
+ self.stem_layer = StemLayer(in_channels=in_channels, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
1724
+ self.bb = build_backbone(self.config.bb)
1725
+
1726
+ lateral_channels_in_collection = {
1727
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1728
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1729
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1730
+ }
1731
+ channels = lateral_channels_in_collection[self.config.bb]
1732
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1733
+
1734
+ self.decoder = Decoder(channels)
1735
+
1736
+ if 0:
1737
+ for key, value in self.named_parameters():
1738
+ if 'bb.' in key:
1739
+ value.requires_grad = False
1740
+
1741
+ def forward(self, x):
1742
+ if isinstance(x, list):
1743
+ x = torch.cat(x, dim=1)
1744
+ x = self.stem_layer(x)
1745
+ ########## Encoder ##########
1746
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1747
+ x1 = self.bb.conv1(x)
1748
+ x2 = self.bb.conv2(x1)
1749
+ x3 = self.bb.conv3(x2)
1750
+ x4 = self.bb.conv4(x3)
1751
+ else:
1752
+ x1, x2, x3, x4 = self.bb(x)
1753
+
1754
+ x4 = self.squeeze_module(x4)
1755
+
1756
+ ########## Decoder ##########
1757
+
1758
+ features = [x, x1, x2, x3, x4]
1759
+ scaled_preds = self.decoder(features)
1760
+
1761
+ return scaled_preds
1762
+
1763
+
1764
+ class Decoder(nn.Module):
1765
+ def __init__(self, channels):
1766
+ super(Decoder, self).__init__()
1767
+ self.config = Config()
1768
+ DecoderBlock = eval('BasicDecBlk')
1769
+ LateralBlock = eval('BasicLatBlk')
1770
+
1771
+ self.decoder_block4 = DecoderBlock(channels[0], channels[1])
1772
+ self.decoder_block3 = DecoderBlock(channels[1], channels[2])
1773
+ self.decoder_block2 = DecoderBlock(channels[2], channels[3])
1774
+ self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2)
1775
+
1776
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
1777
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
1778
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
1779
+
1780
+ if self.config.ms_supervision:
1781
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
1782
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
1783
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
1784
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0))
1785
+
1786
+ def forward(self, features):
1787
+ x, x1, x2, x3, x4 = features
1788
+ outs = []
1789
+ p4 = self.decoder_block4(x4)
1790
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
1791
+ _p3 = _p4 + self.lateral_block4(x3)
1792
+
1793
+ p3 = self.decoder_block3(_p3)
1794
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
1795
+ _p2 = _p3 + self.lateral_block3(x2)
1796
+
1797
+ p2 = self.decoder_block2(_p2)
1798
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
1799
+ _p1 = _p2 + self.lateral_block2(x1)
1800
+
1801
+ _p1 = self.decoder_block1(_p1)
1802
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
1803
+ p1_out = self.conv_out1(_p1)
1804
+
1805
+ if self.config.ms_supervision:
1806
+ outs.append(self.conv_ms_spvn_4(p4))
1807
+ outs.append(self.conv_ms_spvn_3(p3))
1808
+ outs.append(self.conv_ms_spvn_2(p2))
1809
+ outs.append(p1_out)
1810
+ return outs
1811
+
1812
+
1813
+ class RefUNet(nn.Module):
1814
+ # Refinement
1815
+ def __init__(self, in_channels=3+1):
1816
+ super(RefUNet, self).__init__()
1817
+ self.encoder_1 = nn.Sequential(
1818
+ nn.Conv2d(in_channels, 64, 3, 1, 1),
1819
+ nn.Conv2d(64, 64, 3, 1, 1),
1820
+ nn.BatchNorm2d(64),
1821
+ nn.ReLU(inplace=True)
1822
+ )
1823
+
1824
+ self.encoder_2 = nn.Sequential(
1825
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1826
+ nn.Conv2d(64, 64, 3, 1, 1),
1827
+ nn.BatchNorm2d(64),
1828
+ nn.ReLU(inplace=True)
1829
+ )
1830
+
1831
+ self.encoder_3 = nn.Sequential(
1832
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1833
+ nn.Conv2d(64, 64, 3, 1, 1),
1834
+ nn.BatchNorm2d(64),
1835
+ nn.ReLU(inplace=True)
1836
+ )
1837
+
1838
+ self.encoder_4 = nn.Sequential(
1839
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1840
+ nn.Conv2d(64, 64, 3, 1, 1),
1841
+ nn.BatchNorm2d(64),
1842
+ nn.ReLU(inplace=True)
1843
+ )
1844
+
1845
+ self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True)
1846
+ #####
1847
+ self.decoder_5 = nn.Sequential(
1848
+ nn.Conv2d(64, 64, 3, 1, 1),
1849
+ nn.BatchNorm2d(64),
1850
+ nn.ReLU(inplace=True)
1851
+ )
1852
+ #####
1853
+ self.decoder_4 = nn.Sequential(
1854
+ nn.Conv2d(128, 64, 3, 1, 1),
1855
+ nn.BatchNorm2d(64),
1856
+ nn.ReLU(inplace=True)
1857
+ )
1858
+
1859
+ self.decoder_3 = nn.Sequential(
1860
+ nn.Conv2d(128, 64, 3, 1, 1),
1861
+ nn.BatchNorm2d(64),
1862
+ nn.ReLU(inplace=True)
1863
+ )
1864
+
1865
+ self.decoder_2 = nn.Sequential(
1866
+ nn.Conv2d(128, 64, 3, 1, 1),
1867
+ nn.BatchNorm2d(64),
1868
+ nn.ReLU(inplace=True)
1869
+ )
1870
+
1871
+ self.decoder_1 = nn.Sequential(
1872
+ nn.Conv2d(128, 64, 3, 1, 1),
1873
+ nn.BatchNorm2d(64),
1874
+ nn.ReLU(inplace=True)
1875
+ )
1876
+
1877
+ self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1)
1878
+
1879
+ self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
1880
+
1881
+ def forward(self, x):
1882
+ outs = []
1883
+ if isinstance(x, list):
1884
+ x = torch.cat(x, dim=1)
1885
+ hx = x
1886
+
1887
+ hx1 = self.encoder_1(hx)
1888
+ hx2 = self.encoder_2(hx1)
1889
+ hx3 = self.encoder_3(hx2)
1890
+ hx4 = self.encoder_4(hx3)
1891
+
1892
+ hx = self.decoder_5(self.pool4(hx4))
1893
+ hx = torch.cat((self.upscore2(hx), hx4), 1)
1894
+
1895
+ d4 = self.decoder_4(hx)
1896
+ hx = torch.cat((self.upscore2(d4), hx3), 1)
1897
+
1898
+ d3 = self.decoder_3(hx)
1899
+ hx = torch.cat((self.upscore2(d3), hx2), 1)
1900
+
1901
+ d2 = self.decoder_2(hx)
1902
+ hx = torch.cat((self.upscore2(d2), hx1), 1)
1903
+
1904
+ d1 = self.decoder_1(hx)
1905
+
1906
+ x = self.conv_d0(d1)
1907
+ outs.append(x)
1908
+ return outs
1909
+
1910
+
1911
+
1912
+ ### models/stem_layer.py
1913
+
1914
+ import torch.nn as nn
1915
+ # from utils import build_act_layer, build_norm_layer
1916
+
1917
+
1918
+ class StemLayer(nn.Module):
1919
+ r""" Stem layer of InternImage
1920
+ Args:
1921
+ in_channels (int): number of input channels
1922
+ out_channels (int): number of output channels
1923
+ act_layer (str): activation layer
1924
+ norm_layer (str): normalization layer
1925
+ """
1926
+
1927
+ def __init__(self,
1928
+ in_channels=3+1,
1929
+ inter_channels=48,
1930
+ out_channels=96,
1931
+ act_layer='GELU',
1932
+ norm_layer='BN'):
1933
+ super().__init__()
1934
+ self.conv1 = nn.Conv2d(in_channels,
1935
+ inter_channels,
1936
+ kernel_size=3,
1937
+ stride=1,
1938
+ padding=1)
1939
+ self.norm1 = build_norm_layer(
1940
+ inter_channels, norm_layer, 'channels_first', 'channels_first'
1941
+ )
1942
+ self.act = build_act_layer(act_layer)
1943
+ self.conv2 = nn.Conv2d(inter_channels,
1944
+ out_channels,
1945
+ kernel_size=3,
1946
+ stride=1,
1947
+ padding=1)
1948
+ self.norm2 = build_norm_layer(
1949
+ out_channels, norm_layer, 'channels_first', 'channels_first'
1950
+ )
1951
+
1952
+ def forward(self, x):
1953
+ x = self.conv1(x)
1954
+ x = self.norm1(x)
1955
+ x = self.act(x)
1956
+ x = self.conv2(x)
1957
+ x = self.norm2(x)
1958
+ return x
1959
+
1960
+
1961
+ ### models/birefnet.py
1962
+
1963
+ import torch
1964
+ import torch.nn as nn
1965
+ import torch.nn.functional as F
1966
+ from kornia.filters import laplacian
1967
+ from transformers import PreTrainedModel
1968
+ from einops import rearrange
1969
+
1970
+ # from config import Config
1971
+ # from dataset import class_labels_TR_sorted
1972
+ # from models.build_backbone import build_backbone
1973
+ # from models.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk
1974
+ # from models.lateral_blocks import BasicLatBlk
1975
+ # from models.aspp import ASPP, ASPPDeformable
1976
+ # from models.ing import *
1977
+ # from models.refiner import Refiner, RefinerPVTInChannels4, RefUNet
1978
+ # from models.stem_layer import StemLayer
1979
+ from .BiRefNet_config import BiRefNetConfig
1980
+
1981
+
1982
+ def image2patches(image, grid_h=2, grid_w=2, patch_ref=None, transformation='b c (hg h) (wg w) -> (b hg wg) c h w'):
1983
+ if patch_ref is not None:
1984
+ grid_h, grid_w = image.shape[-2] // patch_ref.shape[-2], image.shape[-1] // patch_ref.shape[-1]
1985
+ patches = rearrange(image, transformation, hg=grid_h, wg=grid_w)
1986
+ return patches
1987
+
1988
+ def patches2image(patches, grid_h=2, grid_w=2, patch_ref=None, transformation='(b hg wg) c h w -> b c (hg h) (wg w)'):
1989
+ if patch_ref is not None:
1990
+ grid_h, grid_w = patch_ref.shape[-2] // patches[0].shape[-2], patch_ref.shape[-1] // patches[0].shape[-1]
1991
+ image = rearrange(patches, transformation, hg=grid_h, wg=grid_w)
1992
+ return image
1993
+
1994
+ class BiRefNet(
1995
+ PreTrainedModel
1996
+ ):
1997
+ config_class = BiRefNetConfig
1998
+ def __init__(self, bb_pretrained=True, config=BiRefNetConfig()):
1999
+ super(BiRefNet, self).__init__(config)
2000
+ bb_pretrained = config.bb_pretrained
2001
+ self.config = Config()
2002
+ self.epoch = 1
2003
+ self.bb = build_backbone(self.config.bb, pretrained=bb_pretrained)
2004
+
2005
+ channels = self.config.lateral_channels_in_collection
2006
+
2007
+ if self.config.auxiliary_classification:
2008
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
2009
+ self.cls_head = nn.Sequential(
2010
+ nn.Linear(channels[0], len(class_labels_TR_sorted))
2011
+ )
2012
+
2013
+ if self.config.squeeze_block:
2014
+ self.squeeze_module = nn.Sequential(*[
2015
+ eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0])
2016
+ for _ in range(eval(self.config.squeeze_block.split('_x')[1]))
2017
+ ])
2018
+
2019
+ self.decoder = Decoder(channels)
2020
+
2021
+ if self.config.ender:
2022
+ self.dec_end = nn.Sequential(
2023
+ nn.Conv2d(1, 16, 3, 1, 1),
2024
+ nn.Conv2d(16, 1, 3, 1, 1),
2025
+ nn.ReLU(inplace=True),
2026
+ )
2027
+
2028
+ # refine patch-level segmentation
2029
+ if self.config.refine:
2030
+ if self.config.refine == 'itself':
2031
+ self.stem_layer = StemLayer(in_channels=3+1, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
2032
+ else:
2033
+ self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1'))
2034
+
2035
+ if self.config.freeze_bb:
2036
+ # Freeze the backbone...
2037
+ print(self.named_parameters())
2038
+ for key, value in self.named_parameters():
2039
+ if 'bb.' in key and 'refiner.' not in key:
2040
+ value.requires_grad = False
2041
+
2042
+ def forward_enc(self, x):
2043
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
2044
+ x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3)
2045
+ else:
2046
+ x1, x2, x3, x4 = self.bb(x)
2047
+ if self.config.mul_scl_ipt == 'cat':
2048
+ B, C, H, W = x.shape
2049
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2050
+ x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2051
+ x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2052
+ x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2053
+ x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2054
+ elif self.config.mul_scl_ipt == 'add':
2055
+ B, C, H, W = x.shape
2056
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2057
+ x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)
2058
+ x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)
2059
+ x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)
2060
+ x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)
2061
+ class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None
2062
+ if self.config.cxt:
2063
+ x4 = torch.cat(
2064
+ (
2065
+ *[
2066
+ F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True),
2067
+ F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True),
2068
+ F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True),
2069
+ ][-len(self.config.cxt):],
2070
+ x4
2071
+ ),
2072
+ dim=1
2073
+ )
2074
+ return (x1, x2, x3, x4), class_preds
2075
+
2076
+ def forward_ori(self, x):
2077
+ ########## Encoder ##########
2078
+ (x1, x2, x3, x4), class_preds = self.forward_enc(x)
2079
+ if self.config.squeeze_block:
2080
+ x4 = self.squeeze_module(x4)
2081
+ ########## Decoder ##########
2082
+ features = [x, x1, x2, x3, x4]
2083
+ if self.training and self.config.out_ref:
2084
+ features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5))
2085
+ scaled_preds = self.decoder(features)
2086
+ return scaled_preds, class_preds
2087
+
2088
+ def forward(self, x):
2089
+ scaled_preds, class_preds = self.forward_ori(x)
2090
+ class_preds_lst = [class_preds]
2091
+ return [scaled_preds, class_preds_lst] if self.training else scaled_preds
2092
+
2093
+
2094
+ class Decoder(nn.Module):
2095
+ def __init__(self, channels):
2096
+ super(Decoder, self).__init__()
2097
+ self.config = Config()
2098
+ DecoderBlock = eval(self.config.dec_blk)
2099
+ LateralBlock = eval(self.config.lat_blk)
2100
+
2101
+ if self.config.dec_ipt:
2102
+ self.split = self.config.dec_ipt_split
2103
+ N_dec_ipt = 64
2104
+ DBlock = SimpleConvs
2105
+ ic = 64
2106
+ ipt_cha_opt = 1
2107
+ self.ipt_blk5 = DBlock(2**10*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2108
+ self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2109
+ self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic)
2110
+ self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic)
2111
+ self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic)
2112
+ else:
2113
+ self.split = None
2114
+
2115
+ self.decoder_block4 = DecoderBlock(channels[0]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[1])
2116
+ self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2])
2117
+ self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3])
2118
+ self.decoder_block1 = DecoderBlock(channels[3]+([N_dec_ipt, channels[2]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]//2)
2119
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2+([N_dec_ipt, channels[3]//8][ipt_cha_opt] if self.config.dec_ipt else 0), 1, 1, 1, 0))
2120
+
2121
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
2122
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
2123
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
2124
+
2125
+ if self.config.ms_supervision:
2126
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
2127
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
2128
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
2129
+
2130
+ if self.config.out_ref:
2131
+ _N = 16
2132
+ self.gdt_convs_4 = nn.Sequential(nn.Conv2d(channels[1], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2133
+ self.gdt_convs_3 = nn.Sequential(nn.Conv2d(channels[2], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2134
+ self.gdt_convs_2 = nn.Sequential(nn.Conv2d(channels[3], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2135
+
2136
+ self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2137
+ self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2138
+ self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2139
+
2140
+ self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2141
+ self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2142
+ self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2143
+
2144
+ def forward(self, features):
2145
+ if self.training and self.config.out_ref:
2146
+ outs_gdt_pred = []
2147
+ outs_gdt_label = []
2148
+ x, x1, x2, x3, x4, gdt_gt = features
2149
+ else:
2150
+ x, x1, x2, x3, x4 = features
2151
+ outs = []
2152
+
2153
+ if self.config.dec_ipt:
2154
+ patches_batch = image2patches(x, patch_ref=x4, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2155
+ x4 = torch.cat((x4, self.ipt_blk5(F.interpolate(patches_batch, size=x4.shape[2:], mode='bilinear', align_corners=True))), 1)
2156
+ p4 = self.decoder_block4(x4)
2157
+ m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision and self.training else None
2158
+ if self.config.out_ref:
2159
+ p4_gdt = self.gdt_convs_4(p4)
2160
+ if self.training:
2161
+ # >> GT:
2162
+ m4_dia = m4
2163
+ gdt_label_main_4 = gdt_gt * F.interpolate(m4_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2164
+ outs_gdt_label.append(gdt_label_main_4)
2165
+ # >> Pred:
2166
+ gdt_pred_4 = self.gdt_convs_pred_4(p4_gdt)
2167
+ outs_gdt_pred.append(gdt_pred_4)
2168
+ gdt_attn_4 = self.gdt_convs_attn_4(p4_gdt).sigmoid()
2169
+ # >> Finally:
2170
+ p4 = p4 * gdt_attn_4
2171
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
2172
+ _p3 = _p4 + self.lateral_block4(x3)
2173
+
2174
+ if self.config.dec_ipt:
2175
+ patches_batch = image2patches(x, patch_ref=_p3, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2176
+ _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1)
2177
+ p3 = self.decoder_block3(_p3)
2178
+ m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision and self.training else None
2179
+ if self.config.out_ref:
2180
+ p3_gdt = self.gdt_convs_3(p3)
2181
+ if self.training:
2182
+ # >> GT:
2183
+ # m3 --dilation--> m3_dia
2184
+ # G_3^gt * m3_dia --> G_3^m, which is the label of gradient
2185
+ m3_dia = m3
2186
+ gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2187
+ outs_gdt_label.append(gdt_label_main_3)
2188
+ # >> Pred:
2189
+ # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx
2190
+ # F_3^G --sigmoid--> A_3^G
2191
+ gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt)
2192
+ outs_gdt_pred.append(gdt_pred_3)
2193
+ gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid()
2194
+ # >> Finally:
2195
+ # p3 = p3 * A_3^G
2196
+ p3 = p3 * gdt_attn_3
2197
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
2198
+ _p2 = _p3 + self.lateral_block3(x2)
2199
+
2200
+ if self.config.dec_ipt:
2201
+ patches_batch = image2patches(x, patch_ref=_p2, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2202
+ _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1)
2203
+ p2 = self.decoder_block2(_p2)
2204
+ m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision and self.training else None
2205
+ if self.config.out_ref:
2206
+ p2_gdt = self.gdt_convs_2(p2)
2207
+ if self.training:
2208
+ # >> GT:
2209
+ m2_dia = m2
2210
+ gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2211
+ outs_gdt_label.append(gdt_label_main_2)
2212
+ # >> Pred:
2213
+ gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt)
2214
+ outs_gdt_pred.append(gdt_pred_2)
2215
+ gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid()
2216
+ # >> Finally:
2217
+ p2 = p2 * gdt_attn_2
2218
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
2219
+ _p1 = _p2 + self.lateral_block2(x1)
2220
+
2221
+ if self.config.dec_ipt:
2222
+ patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2223
+ _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1)
2224
+ _p1 = self.decoder_block1(_p1)
2225
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
2226
+
2227
+ if self.config.dec_ipt:
2228
+ patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2229
+ _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1)
2230
+ p1_out = self.conv_out1(_p1)
2231
+
2232
+ if self.config.ms_supervision and self.training:
2233
+ outs.append(m4)
2234
+ outs.append(m3)
2235
+ outs.append(m2)
2236
+ outs.append(p1_out)
2237
+ return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs)
2238
+
2239
+
2240
+ class SimpleConvs(nn.Module):
2241
+ def __init__(
2242
+ self, in_channels: int, out_channels: int, inter_channels=64
2243
+ ) -> None:
2244
+ super().__init__()
2245
+ self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1)
2246
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)
2247
+
2248
+ def forward(self, x):
2249
+ return self.conv_out(self.conv1(x))
SKING_DDJ_v101c/foreground_base/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "ZhengPeng7/BiRefNet",
3
+ "architectures": [
4
+ "BiRefNet"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "BiRefNet_config.BiRefNetConfig",
8
+ "AutoModelForImageSegmentation": "birefnet.BiRefNet"
9
+ },
10
+ "custom_pipelines": {
11
+ "image-segmentation": {
12
+ "pt": [
13
+ "AutoModelForImageSegmentation"
14
+ ],
15
+ "tf": [],
16
+ "type": "image"
17
+ }
18
+ },
19
+ "bb_pretrained": false
20
+ }
SKING_DDJ_v101c/foreground_base/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ab37426bf4de0567af6b5d21b16151357149139362e6e8992021b8ce356a154
3
+ size 444473596
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/refs/main ADDED
@@ -0,0 +1 @@
 
 
1
+ 75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "initializer_factor": 1.0,
3
+ "model_type": "siglip",
4
+ "text_config": {
5
+ "model_type": "siglip_text_model",
6
+ "vocab_size": 256000
7
+ },
8
+ "transformers_version": "4.49.0.dev0",
9
+ "vision_config": {
10
+ "model_type": "siglip_vision_model"
11
+ }
12
+ }
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:612923381c76ec5a9bed335d1c48827e3f2e506ac31b044b63b2031fadee6a0b
3
+ size 1500800904
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/preprocessor_config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_convert_rgb": null,
3
+ "do_normalize": true,
4
+ "do_rescale": true,
5
+ "do_resize": true,
6
+ "image_mean": [
7
+ 0.5,
8
+ 0.5,
9
+ 0.5
10
+ ],
11
+ "image_processor_type": "SiglipImageProcessor",
12
+ "image_std": [
13
+ 0.5,
14
+ 0.5,
15
+ 0.5
16
+ ],
17
+ "processor_class": "SiglipProcessor",
18
+ "resample": 2,
19
+ "rescale_factor": 0.00392156862745098,
20
+ "size": {
21
+ "height": 224,
22
+ "width": 224
23
+ }
24
+ }
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/special_tokens_map.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<start_of_turn>",
4
+ "<end_of_turn>"
5
+ ],
6
+ "bos_token": {
7
+ "content": "<bos>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "eos_token": {
14
+ "content": "<eos>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ },
20
+ "pad_token": {
21
+ "content": "<pad>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ },
27
+ "unk_token": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false
33
+ }
34
+ }
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb9140fae3ac5122c972d37adf83e1248471a38147ad76f8215c8872c6fd8322
3
+ size 34363039
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2
3
+ size 4241003
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer_config.json ADDED
@@ -0,0 +1,2020 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": true,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<pad>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<eos>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "<bos>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "3": {
30
+ "content": "<unk>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "4": {
38
+ "content": "<mask>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": false
44
+ },
45
+ "5": {
46
+ "content": "<2mass>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": false
52
+ },
53
+ "6": {
54
+ "content": "[@BOS@]",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": false
60
+ },
61
+ "7": {
62
+ "content": "<unused0>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": false
68
+ },
69
+ "8": {
70
+ "content": "<unused1>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": false
76
+ },
77
+ "9": {
78
+ "content": "<unused2>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": false
84
+ },
85
+ "10": {
86
+ "content": "<unused3>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": false
92
+ },
93
+ "11": {
94
+ "content": "<unused4>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": false
100
+ },
101
+ "12": {
102
+ "content": "<unused5>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": false
108
+ },
109
+ "13": {
110
+ "content": "<unused6>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": false
116
+ },
117
+ "14": {
118
+ "content": "<unused7>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "15": {
126
+ "content": "<unused8>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "16": {
134
+ "content": "<unused9>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "17": {
142
+ "content": "<unused10>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "18": {
150
+ "content": "<unused11>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "19": {
158
+ "content": "<unused12>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "20": {
166
+ "content": "<unused13>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "21": {
174
+ "content": "<unused14>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "22": {
182
+ "content": "<unused15>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "23": {
190
+ "content": "<unused16>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "24": {
198
+ "content": "<unused17>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "25": {
206
+ "content": "<unused18>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ },
213
+ "26": {
214
+ "content": "<unused19>",
215
+ "lstrip": false,
216
+ "normalized": false,
217
+ "rstrip": false,
218
+ "single_word": false,
219
+ "special": false
220
+ },
221
+ "27": {
222
+ "content": "<unused20>",
223
+ "lstrip": false,
224
+ "normalized": false,
225
+ "rstrip": false,
226
+ "single_word": false,
227
+ "special": false
228
+ },
229
+ "28": {
230
+ "content": "<unused21>",
231
+ "lstrip": false,
232
+ "normalized": false,
233
+ "rstrip": false,
234
+ "single_word": false,
235
+ "special": false
236
+ },
237
+ "29": {
238
+ "content": "<unused22>",
239
+ "lstrip": false,
240
+ "normalized": false,
241
+ "rstrip": false,
242
+ "single_word": false,
243
+ "special": false
244
+ },
245
+ "30": {
246
+ "content": "<unused23>",
247
+ "lstrip": false,
248
+ "normalized": false,
249
+ "rstrip": false,
250
+ "single_word": false,
251
+ "special": false
252
+ },
253
+ "31": {
254
+ "content": "<unused24>",
255
+ "lstrip": false,
256
+ "normalized": false,
257
+ "rstrip": false,
258
+ "single_word": false,
259
+ "special": false
260
+ },
261
+ "32": {
262
+ "content": "<unused25>",
263
+ "lstrip": false,
264
+ "normalized": false,
265
+ "rstrip": false,
266
+ "single_word": false,
267
+ "special": false
268
+ },
269
+ "33": {
270
+ "content": "<unused26>",
271
+ "lstrip": false,
272
+ "normalized": false,
273
+ "rstrip": false,
274
+ "single_word": false,
275
+ "special": false
276
+ },
277
+ "34": {
278
+ "content": "<unused27>",
279
+ "lstrip": false,
280
+ "normalized": false,
281
+ "rstrip": false,
282
+ "single_word": false,
283
+ "special": false
284
+ },
285
+ "35": {
286
+ "content": "<unused28>",
287
+ "lstrip": false,
288
+ "normalized": false,
289
+ "rstrip": false,
290
+ "single_word": false,
291
+ "special": false
292
+ },
293
+ "36": {
294
+ "content": "<unused29>",
295
+ "lstrip": false,
296
+ "normalized": false,
297
+ "rstrip": false,
298
+ "single_word": false,
299
+ "special": false
300
+ },
301
+ "37": {
302
+ "content": "<unused30>",
303
+ "lstrip": false,
304
+ "normalized": false,
305
+ "rstrip": false,
306
+ "single_word": false,
307
+ "special": false
308
+ },
309
+ "38": {
310
+ "content": "<unused31>",
311
+ "lstrip": false,
312
+ "normalized": false,
313
+ "rstrip": false,
314
+ "single_word": false,
315
+ "special": false
316
+ },
317
+ "39": {
318
+ "content": "<unused32>",
319
+ "lstrip": false,
320
+ "normalized": false,
321
+ "rstrip": false,
322
+ "single_word": false,
323
+ "special": false
324
+ },
325
+ "40": {
326
+ "content": "<unused33>",
327
+ "lstrip": false,
328
+ "normalized": false,
329
+ "rstrip": false,
330
+ "single_word": false,
331
+ "special": false
332
+ },
333
+ "41": {
334
+ "content": "<unused34>",
335
+ "lstrip": false,
336
+ "normalized": false,
337
+ "rstrip": false,
338
+ "single_word": false,
339
+ "special": false
340
+ },
341
+ "42": {
342
+ "content": "<unused35>",
343
+ "lstrip": false,
344
+ "normalized": false,
345
+ "rstrip": false,
346
+ "single_word": false,
347
+ "special": false
348
+ },
349
+ "43": {
350
+ "content": "<unused36>",
351
+ "lstrip": false,
352
+ "normalized": false,
353
+ "rstrip": false,
354
+ "single_word": false,
355
+ "special": false
356
+ },
357
+ "44": {
358
+ "content": "<unused37>",
359
+ "lstrip": false,
360
+ "normalized": false,
361
+ "rstrip": false,
362
+ "single_word": false,
363
+ "special": false
364
+ },
365
+ "45": {
366
+ "content": "<unused38>",
367
+ "lstrip": false,
368
+ "normalized": false,
369
+ "rstrip": false,
370
+ "single_word": false,
371
+ "special": false
372
+ },
373
+ "46": {
374
+ "content": "<unused39>",
375
+ "lstrip": false,
376
+ "normalized": false,
377
+ "rstrip": false,
378
+ "single_word": false,
379
+ "special": false
380
+ },
381
+ "47": {
382
+ "content": "<unused40>",
383
+ "lstrip": false,
384
+ "normalized": false,
385
+ "rstrip": false,
386
+ "single_word": false,
387
+ "special": false
388
+ },
389
+ "48": {
390
+ "content": "<unused41>",
391
+ "lstrip": false,
392
+ "normalized": false,
393
+ "rstrip": false,
394
+ "single_word": false,
395
+ "special": false
396
+ },
397
+ "49": {
398
+ "content": "<unused42>",
399
+ "lstrip": false,
400
+ "normalized": false,
401
+ "rstrip": false,
402
+ "single_word": false,
403
+ "special": false
404
+ },
405
+ "50": {
406
+ "content": "<unused43>",
407
+ "lstrip": false,
408
+ "normalized": false,
409
+ "rstrip": false,
410
+ "single_word": false,
411
+ "special": false
412
+ },
413
+ "51": {
414
+ "content": "<unused44>",
415
+ "lstrip": false,
416
+ "normalized": false,
417
+ "rstrip": false,
418
+ "single_word": false,
419
+ "special": false
420
+ },
421
+ "52": {
422
+ "content": "<unused45>",
423
+ "lstrip": false,
424
+ "normalized": false,
425
+ "rstrip": false,
426
+ "single_word": false,
427
+ "special": false
428
+ },
429
+ "53": {
430
+ "content": "<unused46>",
431
+ "lstrip": false,
432
+ "normalized": false,
433
+ "rstrip": false,
434
+ "single_word": false,
435
+ "special": false
436
+ },
437
+ "54": {
438
+ "content": "<unused47>",
439
+ "lstrip": false,
440
+ "normalized": false,
441
+ "rstrip": false,
442
+ "single_word": false,
443
+ "special": false
444
+ },
445
+ "55": {
446
+ "content": "<unused48>",
447
+ "lstrip": false,
448
+ "normalized": false,
449
+ "rstrip": false,
450
+ "single_word": false,
451
+ "special": false
452
+ },
453
+ "56": {
454
+ "content": "<unused49>",
455
+ "lstrip": false,
456
+ "normalized": false,
457
+ "rstrip": false,
458
+ "single_word": false,
459
+ "special": false
460
+ },
461
+ "57": {
462
+ "content": "<unused50>",
463
+ "lstrip": false,
464
+ "normalized": false,
465
+ "rstrip": false,
466
+ "single_word": false,
467
+ "special": false
468
+ },
469
+ "58": {
470
+ "content": "<unused51>",
471
+ "lstrip": false,
472
+ "normalized": false,
473
+ "rstrip": false,
474
+ "single_word": false,
475
+ "special": false
476
+ },
477
+ "59": {
478
+ "content": "<unused52>",
479
+ "lstrip": false,
480
+ "normalized": false,
481
+ "rstrip": false,
482
+ "single_word": false,
483
+ "special": false
484
+ },
485
+ "60": {
486
+ "content": "<unused53>",
487
+ "lstrip": false,
488
+ "normalized": false,
489
+ "rstrip": false,
490
+ "single_word": false,
491
+ "special": false
492
+ },
493
+ "61": {
494
+ "content": "<unused54>",
495
+ "lstrip": false,
496
+ "normalized": false,
497
+ "rstrip": false,
498
+ "single_word": false,
499
+ "special": false
500
+ },
501
+ "62": {
502
+ "content": "<unused55>",
503
+ "lstrip": false,
504
+ "normalized": false,
505
+ "rstrip": false,
506
+ "single_word": false,
507
+ "special": false
508
+ },
509
+ "63": {
510
+ "content": "<unused56>",
511
+ "lstrip": false,
512
+ "normalized": false,
513
+ "rstrip": false,
514
+ "single_word": false,
515
+ "special": false
516
+ },
517
+ "64": {
518
+ "content": "<unused57>",
519
+ "lstrip": false,
520
+ "normalized": false,
521
+ "rstrip": false,
522
+ "single_word": false,
523
+ "special": false
524
+ },
525
+ "65": {
526
+ "content": "<unused58>",
527
+ "lstrip": false,
528
+ "normalized": false,
529
+ "rstrip": false,
530
+ "single_word": false,
531
+ "special": false
532
+ },
533
+ "66": {
534
+ "content": "<unused59>",
535
+ "lstrip": false,
536
+ "normalized": false,
537
+ "rstrip": false,
538
+ "single_word": false,
539
+ "special": false
540
+ },
541
+ "67": {
542
+ "content": "<unused60>",
543
+ "lstrip": false,
544
+ "normalized": false,
545
+ "rstrip": false,
546
+ "single_word": false,
547
+ "special": false
548
+ },
549
+ "68": {
550
+ "content": "<unused61>",
551
+ "lstrip": false,
552
+ "normalized": false,
553
+ "rstrip": false,
554
+ "single_word": false,
555
+ "special": false
556
+ },
557
+ "69": {
558
+ "content": "<unused62>",
559
+ "lstrip": false,
560
+ "normalized": false,
561
+ "rstrip": false,
562
+ "single_word": false,
563
+ "special": false
564
+ },
565
+ "70": {
566
+ "content": "<unused63>",
567
+ "lstrip": false,
568
+ "normalized": false,
569
+ "rstrip": false,
570
+ "single_word": false,
571
+ "special": false
572
+ },
573
+ "71": {
574
+ "content": "<unused64>",
575
+ "lstrip": false,
576
+ "normalized": false,
577
+ "rstrip": false,
578
+ "single_word": false,
579
+ "special": false
580
+ },
581
+ "72": {
582
+ "content": "<unused65>",
583
+ "lstrip": false,
584
+ "normalized": false,
585
+ "rstrip": false,
586
+ "single_word": false,
587
+ "special": false
588
+ },
589
+ "73": {
590
+ "content": "<unused66>",
591
+ "lstrip": false,
592
+ "normalized": false,
593
+ "rstrip": false,
594
+ "single_word": false,
595
+ "special": false
596
+ },
597
+ "74": {
598
+ "content": "<unused67>",
599
+ "lstrip": false,
600
+ "normalized": false,
601
+ "rstrip": false,
602
+ "single_word": false,
603
+ "special": false
604
+ },
605
+ "75": {
606
+ "content": "<unused68>",
607
+ "lstrip": false,
608
+ "normalized": false,
609
+ "rstrip": false,
610
+ "single_word": false,
611
+ "special": false
612
+ },
613
+ "76": {
614
+ "content": "<unused69>",
615
+ "lstrip": false,
616
+ "normalized": false,
617
+ "rstrip": false,
618
+ "single_word": false,
619
+ "special": false
620
+ },
621
+ "77": {
622
+ "content": "<unused70>",
623
+ "lstrip": false,
624
+ "normalized": false,
625
+ "rstrip": false,
626
+ "single_word": false,
627
+ "special": false
628
+ },
629
+ "78": {
630
+ "content": "<unused71>",
631
+ "lstrip": false,
632
+ "normalized": false,
633
+ "rstrip": false,
634
+ "single_word": false,
635
+ "special": false
636
+ },
637
+ "79": {
638
+ "content": "<unused72>",
639
+ "lstrip": false,
640
+ "normalized": false,
641
+ "rstrip": false,
642
+ "single_word": false,
643
+ "special": false
644
+ },
645
+ "80": {
646
+ "content": "<unused73>",
647
+ "lstrip": false,
648
+ "normalized": false,
649
+ "rstrip": false,
650
+ "single_word": false,
651
+ "special": false
652
+ },
653
+ "81": {
654
+ "content": "<unused74>",
655
+ "lstrip": false,
656
+ "normalized": false,
657
+ "rstrip": false,
658
+ "single_word": false,
659
+ "special": false
660
+ },
661
+ "82": {
662
+ "content": "<unused75>",
663
+ "lstrip": false,
664
+ "normalized": false,
665
+ "rstrip": false,
666
+ "single_word": false,
667
+ "special": false
668
+ },
669
+ "83": {
670
+ "content": "<unused76>",
671
+ "lstrip": false,
672
+ "normalized": false,
673
+ "rstrip": false,
674
+ "single_word": false,
675
+ "special": false
676
+ },
677
+ "84": {
678
+ "content": "<unused77>",
679
+ "lstrip": false,
680
+ "normalized": false,
681
+ "rstrip": false,
682
+ "single_word": false,
683
+ "special": false
684
+ },
685
+ "85": {
686
+ "content": "<unused78>",
687
+ "lstrip": false,
688
+ "normalized": false,
689
+ "rstrip": false,
690
+ "single_word": false,
691
+ "special": false
692
+ },
693
+ "86": {
694
+ "content": "<unused79>",
695
+ "lstrip": false,
696
+ "normalized": false,
697
+ "rstrip": false,
698
+ "single_word": false,
699
+ "special": false
700
+ },
701
+ "87": {
702
+ "content": "<unused80>",
703
+ "lstrip": false,
704
+ "normalized": false,
705
+ "rstrip": false,
706
+ "single_word": false,
707
+ "special": false
708
+ },
709
+ "88": {
710
+ "content": "<unused81>",
711
+ "lstrip": false,
712
+ "normalized": false,
713
+ "rstrip": false,
714
+ "single_word": false,
715
+ "special": false
716
+ },
717
+ "89": {
718
+ "content": "<unused82>",
719
+ "lstrip": false,
720
+ "normalized": false,
721
+ "rstrip": false,
722
+ "single_word": false,
723
+ "special": false
724
+ },
725
+ "90": {
726
+ "content": "<unused83>",
727
+ "lstrip": false,
728
+ "normalized": false,
729
+ "rstrip": false,
730
+ "single_word": false,
731
+ "special": false
732
+ },
733
+ "91": {
734
+ "content": "<unused84>",
735
+ "lstrip": false,
736
+ "normalized": false,
737
+ "rstrip": false,
738
+ "single_word": false,
739
+ "special": false
740
+ },
741
+ "92": {
742
+ "content": "<unused85>",
743
+ "lstrip": false,
744
+ "normalized": false,
745
+ "rstrip": false,
746
+ "single_word": false,
747
+ "special": false
748
+ },
749
+ "93": {
750
+ "content": "<unused86>",
751
+ "lstrip": false,
752
+ "normalized": false,
753
+ "rstrip": false,
754
+ "single_word": false,
755
+ "special": false
756
+ },
757
+ "94": {
758
+ "content": "<unused87>",
759
+ "lstrip": false,
760
+ "normalized": false,
761
+ "rstrip": false,
762
+ "single_word": false,
763
+ "special": false
764
+ },
765
+ "95": {
766
+ "content": "<unused88>",
767
+ "lstrip": false,
768
+ "normalized": false,
769
+ "rstrip": false,
770
+ "single_word": false,
771
+ "special": false
772
+ },
773
+ "96": {
774
+ "content": "<unused89>",
775
+ "lstrip": false,
776
+ "normalized": false,
777
+ "rstrip": false,
778
+ "single_word": false,
779
+ "special": false
780
+ },
781
+ "97": {
782
+ "content": "<unused90>",
783
+ "lstrip": false,
784
+ "normalized": false,
785
+ "rstrip": false,
786
+ "single_word": false,
787
+ "special": false
788
+ },
789
+ "98": {
790
+ "content": "<unused91>",
791
+ "lstrip": false,
792
+ "normalized": false,
793
+ "rstrip": false,
794
+ "single_word": false,
795
+ "special": false
796
+ },
797
+ "99": {
798
+ "content": "<unused92>",
799
+ "lstrip": false,
800
+ "normalized": false,
801
+ "rstrip": false,
802
+ "single_word": false,
803
+ "special": false
804
+ },
805
+ "100": {
806
+ "content": "<unused93>",
807
+ "lstrip": false,
808
+ "normalized": false,
809
+ "rstrip": false,
810
+ "single_word": false,
811
+ "special": false
812
+ },
813
+ "101": {
814
+ "content": "<unused94>",
815
+ "lstrip": false,
816
+ "normalized": false,
817
+ "rstrip": false,
818
+ "single_word": false,
819
+ "special": false
820
+ },
821
+ "102": {
822
+ "content": "<unused95>",
823
+ "lstrip": false,
824
+ "normalized": false,
825
+ "rstrip": false,
826
+ "single_word": false,
827
+ "special": false
828
+ },
829
+ "103": {
830
+ "content": "<unused96>",
831
+ "lstrip": false,
832
+ "normalized": false,
833
+ "rstrip": false,
834
+ "single_word": false,
835
+ "special": false
836
+ },
837
+ "104": {
838
+ "content": "<unused97>",
839
+ "lstrip": false,
840
+ "normalized": false,
841
+ "rstrip": false,
842
+ "single_word": false,
843
+ "special": false
844
+ },
845
+ "105": {
846
+ "content": "<unused98>",
847
+ "lstrip": false,
848
+ "normalized": false,
849
+ "rstrip": false,
850
+ "single_word": false,
851
+ "special": false
852
+ },
853
+ "106": {
854
+ "content": "<start_of_turn>",
855
+ "lstrip": false,
856
+ "normalized": false,
857
+ "rstrip": false,
858
+ "single_word": false,
859
+ "special": true
860
+ },
861
+ "107": {
862
+ "content": "<end_of_turn>",
863
+ "lstrip": false,
864
+ "normalized": false,
865
+ "rstrip": false,
866
+ "single_word": false,
867
+ "special": true
868
+ },
869
+ "108": {
870
+ "content": "\n",
871
+ "lstrip": false,
872
+ "normalized": false,
873
+ "rstrip": false,
874
+ "single_word": false,
875
+ "special": false
876
+ },
877
+ "109": {
878
+ "content": "\n\n",
879
+ "lstrip": false,
880
+ "normalized": false,
881
+ "rstrip": false,
882
+ "single_word": false,
883
+ "special": false
884
+ },
885
+ "110": {
886
+ "content": "\n\n\n",
887
+ "lstrip": false,
888
+ "normalized": false,
889
+ "rstrip": false,
890
+ "single_word": false,
891
+ "special": false
892
+ },
893
+ "111": {
894
+ "content": "\n\n\n\n",
895
+ "lstrip": false,
896
+ "normalized": false,
897
+ "rstrip": false,
898
+ "single_word": false,
899
+ "special": false
900
+ },
901
+ "112": {
902
+ "content": "\n\n\n\n\n",
903
+ "lstrip": false,
904
+ "normalized": false,
905
+ "rstrip": false,
906
+ "single_word": false,
907
+ "special": false
908
+ },
909
+ "113": {
910
+ "content": "\n\n\n\n\n\n",
911
+ "lstrip": false,
912
+ "normalized": false,
913
+ "rstrip": false,
914
+ "single_word": false,
915
+ "special": false
916
+ },
917
+ "114": {
918
+ "content": "\n\n\n\n\n\n\n",
919
+ "lstrip": false,
920
+ "normalized": false,
921
+ "rstrip": false,
922
+ "single_word": false,
923
+ "special": false
924
+ },
925
+ "115": {
926
+ "content": "\n\n\n\n\n\n\n\n",
927
+ "lstrip": false,
928
+ "normalized": false,
929
+ "rstrip": false,
930
+ "single_word": false,
931
+ "special": false
932
+ },
933
+ "116": {
934
+ "content": "\n\n\n\n\n\n\n\n\n",
935
+ "lstrip": false,
936
+ "normalized": false,
937
+ "rstrip": false,
938
+ "single_word": false,
939
+ "special": false
940
+ },
941
+ "117": {
942
+ "content": "\n\n\n\n\n\n\n\n\n\n",
943
+ "lstrip": false,
944
+ "normalized": false,
945
+ "rstrip": false,
946
+ "single_word": false,
947
+ "special": false
948
+ },
949
+ "118": {
950
+ "content": "\n\n\n\n\n\n\n\n\n\n\n",
951
+ "lstrip": false,
952
+ "normalized": false,
953
+ "rstrip": false,
954
+ "single_word": false,
955
+ "special": false
956
+ },
957
+ "119": {
958
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n",
959
+ "lstrip": false,
960
+ "normalized": false,
961
+ "rstrip": false,
962
+ "single_word": false,
963
+ "special": false
964
+ },
965
+ "120": {
966
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n",
967
+ "lstrip": false,
968
+ "normalized": false,
969
+ "rstrip": false,
970
+ "single_word": false,
971
+ "special": false
972
+ },
973
+ "121": {
974
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
975
+ "lstrip": false,
976
+ "normalized": false,
977
+ "rstrip": false,
978
+ "single_word": false,
979
+ "special": false
980
+ },
981
+ "122": {
982
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
983
+ "lstrip": false,
984
+ "normalized": false,
985
+ "rstrip": false,
986
+ "single_word": false,
987
+ "special": false
988
+ },
989
+ "123": {
990
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
991
+ "lstrip": false,
992
+ "normalized": false,
993
+ "rstrip": false,
994
+ "single_word": false,
995
+ "special": false
996
+ },
997
+ "124": {
998
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
999
+ "lstrip": false,
1000
+ "normalized": false,
1001
+ "rstrip": false,
1002
+ "single_word": false,
1003
+ "special": false
1004
+ },
1005
+ "125": {
1006
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1007
+ "lstrip": false,
1008
+ "normalized": false,
1009
+ "rstrip": false,
1010
+ "single_word": false,
1011
+ "special": false
1012
+ },
1013
+ "126": {
1014
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1015
+ "lstrip": false,
1016
+ "normalized": false,
1017
+ "rstrip": false,
1018
+ "single_word": false,
1019
+ "special": false
1020
+ },
1021
+ "127": {
1022
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1023
+ "lstrip": false,
1024
+ "normalized": false,
1025
+ "rstrip": false,
1026
+ "single_word": false,
1027
+ "special": false
1028
+ },
1029
+ "128": {
1030
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1031
+ "lstrip": false,
1032
+ "normalized": false,
1033
+ "rstrip": false,
1034
+ "single_word": false,
1035
+ "special": false
1036
+ },
1037
+ "129": {
1038
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1039
+ "lstrip": false,
1040
+ "normalized": false,
1041
+ "rstrip": false,
1042
+ "single_word": false,
1043
+ "special": false
1044
+ },
1045
+ "130": {
1046
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1047
+ "lstrip": false,
1048
+ "normalized": false,
1049
+ "rstrip": false,
1050
+ "single_word": false,
1051
+ "special": false
1052
+ },
1053
+ "131": {
1054
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1055
+ "lstrip": false,
1056
+ "normalized": false,
1057
+ "rstrip": false,
1058
+ "single_word": false,
1059
+ "special": false
1060
+ },
1061
+ "132": {
1062
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1063
+ "lstrip": false,
1064
+ "normalized": false,
1065
+ "rstrip": false,
1066
+ "single_word": false,
1067
+ "special": false
1068
+ },
1069
+ "133": {
1070
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1071
+ "lstrip": false,
1072
+ "normalized": false,
1073
+ "rstrip": false,
1074
+ "single_word": false,
1075
+ "special": false
1076
+ },
1077
+ "134": {
1078
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1079
+ "lstrip": false,
1080
+ "normalized": false,
1081
+ "rstrip": false,
1082
+ "single_word": false,
1083
+ "special": false
1084
+ },
1085
+ "135": {
1086
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1087
+ "lstrip": false,
1088
+ "normalized": false,
1089
+ "rstrip": false,
1090
+ "single_word": false,
1091
+ "special": false
1092
+ },
1093
+ "136": {
1094
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1095
+ "lstrip": false,
1096
+ "normalized": false,
1097
+ "rstrip": false,
1098
+ "single_word": false,
1099
+ "special": false
1100
+ },
1101
+ "137": {
1102
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1103
+ "lstrip": false,
1104
+ "normalized": false,
1105
+ "rstrip": false,
1106
+ "single_word": false,
1107
+ "special": false
1108
+ },
1109
+ "138": {
1110
+ "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1111
+ "lstrip": false,
1112
+ "normalized": false,
1113
+ "rstrip": false,
1114
+ "single_word": false,
1115
+ "special": false
1116
+ },
1117
+ "139": {
1118
+ "content": "▁▁",
1119
+ "lstrip": false,
1120
+ "normalized": false,
1121
+ "rstrip": false,
1122
+ "single_word": false,
1123
+ "special": false
1124
+ },
1125
+ "140": {
1126
+ "content": "▁▁▁",
1127
+ "lstrip": false,
1128
+ "normalized": false,
1129
+ "rstrip": false,
1130
+ "single_word": false,
1131
+ "special": false
1132
+ },
1133
+ "141": {
1134
+ "content": "▁▁▁▁",
1135
+ "lstrip": false,
1136
+ "normalized": false,
1137
+ "rstrip": false,
1138
+ "single_word": false,
1139
+ "special": false
1140
+ },
1141
+ "142": {
1142
+ "content": "▁▁▁▁▁",
1143
+ "lstrip": false,
1144
+ "normalized": false,
1145
+ "rstrip": false,
1146
+ "single_word": false,
1147
+ "special": false
1148
+ },
1149
+ "143": {
1150
+ "content": "▁▁▁▁▁▁",
1151
+ "lstrip": false,
1152
+ "normalized": false,
1153
+ "rstrip": false,
1154
+ "single_word": false,
1155
+ "special": false
1156
+ },
1157
+ "144": {
1158
+ "content": "▁▁▁▁▁▁▁",
1159
+ "lstrip": false,
1160
+ "normalized": false,
1161
+ "rstrip": false,
1162
+ "single_word": false,
1163
+ "special": false
1164
+ },
1165
+ "145": {
1166
+ "content": "▁▁▁▁▁▁▁▁",
1167
+ "lstrip": false,
1168
+ "normalized": false,
1169
+ "rstrip": false,
1170
+ "single_word": false,
1171
+ "special": false
1172
+ },
1173
+ "146": {
1174
+ "content": "▁▁▁▁▁▁▁▁▁",
1175
+ "lstrip": false,
1176
+ "normalized": false,
1177
+ "rstrip": false,
1178
+ "single_word": false,
1179
+ "special": false
1180
+ },
1181
+ "147": {
1182
+ "content": "▁▁▁▁▁▁▁▁▁▁",
1183
+ "lstrip": false,
1184
+ "normalized": false,
1185
+ "rstrip": false,
1186
+ "single_word": false,
1187
+ "special": false
1188
+ },
1189
+ "148": {
1190
+ "content": "▁▁▁▁▁▁▁▁▁▁▁",
1191
+ "lstrip": false,
1192
+ "normalized": false,
1193
+ "rstrip": false,
1194
+ "single_word": false,
1195
+ "special": false
1196
+ },
1197
+ "149": {
1198
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁",
1199
+ "lstrip": false,
1200
+ "normalized": false,
1201
+ "rstrip": false,
1202
+ "single_word": false,
1203
+ "special": false
1204
+ },
1205
+ "150": {
1206
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁",
1207
+ "lstrip": false,
1208
+ "normalized": false,
1209
+ "rstrip": false,
1210
+ "single_word": false,
1211
+ "special": false
1212
+ },
1213
+ "151": {
1214
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1215
+ "lstrip": false,
1216
+ "normalized": false,
1217
+ "rstrip": false,
1218
+ "single_word": false,
1219
+ "special": false
1220
+ },
1221
+ "152": {
1222
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1223
+ "lstrip": false,
1224
+ "normalized": false,
1225
+ "rstrip": false,
1226
+ "single_word": false,
1227
+ "special": false
1228
+ },
1229
+ "153": {
1230
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1231
+ "lstrip": false,
1232
+ "normalized": false,
1233
+ "rstrip": false,
1234
+ "single_word": false,
1235
+ "special": false
1236
+ },
1237
+ "154": {
1238
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1239
+ "lstrip": false,
1240
+ "normalized": false,
1241
+ "rstrip": false,
1242
+ "single_word": false,
1243
+ "special": false
1244
+ },
1245
+ "155": {
1246
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1247
+ "lstrip": false,
1248
+ "normalized": false,
1249
+ "rstrip": false,
1250
+ "single_word": false,
1251
+ "special": false
1252
+ },
1253
+ "156": {
1254
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1255
+ "lstrip": false,
1256
+ "normalized": false,
1257
+ "rstrip": false,
1258
+ "single_word": false,
1259
+ "special": false
1260
+ },
1261
+ "157": {
1262
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1263
+ "lstrip": false,
1264
+ "normalized": false,
1265
+ "rstrip": false,
1266
+ "single_word": false,
1267
+ "special": false
1268
+ },
1269
+ "158": {
1270
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1271
+ "lstrip": false,
1272
+ "normalized": false,
1273
+ "rstrip": false,
1274
+ "single_word": false,
1275
+ "special": false
1276
+ },
1277
+ "159": {
1278
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1279
+ "lstrip": false,
1280
+ "normalized": false,
1281
+ "rstrip": false,
1282
+ "single_word": false,
1283
+ "special": false
1284
+ },
1285
+ "160": {
1286
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1287
+ "lstrip": false,
1288
+ "normalized": false,
1289
+ "rstrip": false,
1290
+ "single_word": false,
1291
+ "special": false
1292
+ },
1293
+ "161": {
1294
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1295
+ "lstrip": false,
1296
+ "normalized": false,
1297
+ "rstrip": false,
1298
+ "single_word": false,
1299
+ "special": false
1300
+ },
1301
+ "162": {
1302
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1303
+ "lstrip": false,
1304
+ "normalized": false,
1305
+ "rstrip": false,
1306
+ "single_word": false,
1307
+ "special": false
1308
+ },
1309
+ "163": {
1310
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1311
+ "lstrip": false,
1312
+ "normalized": false,
1313
+ "rstrip": false,
1314
+ "single_word": false,
1315
+ "special": false
1316
+ },
1317
+ "164": {
1318
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1319
+ "lstrip": false,
1320
+ "normalized": false,
1321
+ "rstrip": false,
1322
+ "single_word": false,
1323
+ "special": false
1324
+ },
1325
+ "165": {
1326
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1327
+ "lstrip": false,
1328
+ "normalized": false,
1329
+ "rstrip": false,
1330
+ "single_word": false,
1331
+ "special": false
1332
+ },
1333
+ "166": {
1334
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1335
+ "lstrip": false,
1336
+ "normalized": false,
1337
+ "rstrip": false,
1338
+ "single_word": false,
1339
+ "special": false
1340
+ },
1341
+ "167": {
1342
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1343
+ "lstrip": false,
1344
+ "normalized": false,
1345
+ "rstrip": false,
1346
+ "single_word": false,
1347
+ "special": false
1348
+ },
1349
+ "168": {
1350
+ "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
1351
+ "lstrip": false,
1352
+ "normalized": false,
1353
+ "rstrip": false,
1354
+ "single_word": false,
1355
+ "special": false
1356
+ },
1357
+ "169": {
1358
+ "content": "<table>",
1359
+ "lstrip": false,
1360
+ "normalized": false,
1361
+ "rstrip": false,
1362
+ "single_word": false,
1363
+ "special": false
1364
+ },
1365
+ "170": {
1366
+ "content": "<caption>",
1367
+ "lstrip": false,
1368
+ "normalized": false,
1369
+ "rstrip": false,
1370
+ "single_word": false,
1371
+ "special": false
1372
+ },
1373
+ "171": {
1374
+ "content": "<thead>",
1375
+ "lstrip": false,
1376
+ "normalized": false,
1377
+ "rstrip": false,
1378
+ "single_word": false,
1379
+ "special": false
1380
+ },
1381
+ "172": {
1382
+ "content": "<tbody>",
1383
+ "lstrip": false,
1384
+ "normalized": false,
1385
+ "rstrip": false,
1386
+ "single_word": false,
1387
+ "special": false
1388
+ },
1389
+ "173": {
1390
+ "content": "<tfoot>",
1391
+ "lstrip": false,
1392
+ "normalized": false,
1393
+ "rstrip": false,
1394
+ "single_word": false,
1395
+ "special": false
1396
+ },
1397
+ "174": {
1398
+ "content": "<tr>",
1399
+ "lstrip": false,
1400
+ "normalized": false,
1401
+ "rstrip": false,
1402
+ "single_word": false,
1403
+ "special": false
1404
+ },
1405
+ "175": {
1406
+ "content": "<th>",
1407
+ "lstrip": false,
1408
+ "normalized": false,
1409
+ "rstrip": false,
1410
+ "single_word": false,
1411
+ "special": false
1412
+ },
1413
+ "176": {
1414
+ "content": "<td>",
1415
+ "lstrip": false,
1416
+ "normalized": false,
1417
+ "rstrip": false,
1418
+ "single_word": false,
1419
+ "special": false
1420
+ },
1421
+ "177": {
1422
+ "content": "</table>",
1423
+ "lstrip": false,
1424
+ "normalized": false,
1425
+ "rstrip": false,
1426
+ "single_word": false,
1427
+ "special": false
1428
+ },
1429
+ "178": {
1430
+ "content": "</caption>",
1431
+ "lstrip": false,
1432
+ "normalized": false,
1433
+ "rstrip": false,
1434
+ "single_word": false,
1435
+ "special": false
1436
+ },
1437
+ "179": {
1438
+ "content": "</thead>",
1439
+ "lstrip": false,
1440
+ "normalized": false,
1441
+ "rstrip": false,
1442
+ "single_word": false,
1443
+ "special": false
1444
+ },
1445
+ "180": {
1446
+ "content": "</tbody>",
1447
+ "lstrip": false,
1448
+ "normalized": false,
1449
+ "rstrip": false,
1450
+ "single_word": false,
1451
+ "special": false
1452
+ },
1453
+ "181": {
1454
+ "content": "</tfoot>",
1455
+ "lstrip": false,
1456
+ "normalized": false,
1457
+ "rstrip": false,
1458
+ "single_word": false,
1459
+ "special": false
1460
+ },
1461
+ "182": {
1462
+ "content": "</tr>",
1463
+ "lstrip": false,
1464
+ "normalized": false,
1465
+ "rstrip": false,
1466
+ "single_word": false,
1467
+ "special": false
1468
+ },
1469
+ "183": {
1470
+ "content": "</th>",
1471
+ "lstrip": false,
1472
+ "normalized": false,
1473
+ "rstrip": false,
1474
+ "single_word": false,
1475
+ "special": false
1476
+ },
1477
+ "184": {
1478
+ "content": "</td>",
1479
+ "lstrip": false,
1480
+ "normalized": false,
1481
+ "rstrip": false,
1482
+ "single_word": false,
1483
+ "special": false
1484
+ },
1485
+ "185": {
1486
+ "content": "<h1>",
1487
+ "lstrip": false,
1488
+ "normalized": false,
1489
+ "rstrip": false,
1490
+ "single_word": false,
1491
+ "special": false
1492
+ },
1493
+ "186": {
1494
+ "content": "<h2>",
1495
+ "lstrip": false,
1496
+ "normalized": false,
1497
+ "rstrip": false,
1498
+ "single_word": false,
1499
+ "special": false
1500
+ },
1501
+ "187": {
1502
+ "content": "<h3>",
1503
+ "lstrip": false,
1504
+ "normalized": false,
1505
+ "rstrip": false,
1506
+ "single_word": false,
1507
+ "special": false
1508
+ },
1509
+ "188": {
1510
+ "content": "<h4>",
1511
+ "lstrip": false,
1512
+ "normalized": false,
1513
+ "rstrip": false,
1514
+ "single_word": false,
1515
+ "special": false
1516
+ },
1517
+ "189": {
1518
+ "content": "<h5>",
1519
+ "lstrip": false,
1520
+ "normalized": false,
1521
+ "rstrip": false,
1522
+ "single_word": false,
1523
+ "special": false
1524
+ },
1525
+ "190": {
1526
+ "content": "<h6>",
1527
+ "lstrip": false,
1528
+ "normalized": false,
1529
+ "rstrip": false,
1530
+ "single_word": false,
1531
+ "special": false
1532
+ },
1533
+ "191": {
1534
+ "content": "<blockquote>",
1535
+ "lstrip": false,
1536
+ "normalized": false,
1537
+ "rstrip": false,
1538
+ "single_word": false,
1539
+ "special": false
1540
+ },
1541
+ "192": {
1542
+ "content": "</h1>",
1543
+ "lstrip": false,
1544
+ "normalized": false,
1545
+ "rstrip": false,
1546
+ "single_word": false,
1547
+ "special": false
1548
+ },
1549
+ "193": {
1550
+ "content": "</h2>",
1551
+ "lstrip": false,
1552
+ "normalized": false,
1553
+ "rstrip": false,
1554
+ "single_word": false,
1555
+ "special": false
1556
+ },
1557
+ "194": {
1558
+ "content": "</h3>",
1559
+ "lstrip": false,
1560
+ "normalized": false,
1561
+ "rstrip": false,
1562
+ "single_word": false,
1563
+ "special": false
1564
+ },
1565
+ "195": {
1566
+ "content": "</h4>",
1567
+ "lstrip": false,
1568
+ "normalized": false,
1569
+ "rstrip": false,
1570
+ "single_word": false,
1571
+ "special": false
1572
+ },
1573
+ "196": {
1574
+ "content": "</h5>",
1575
+ "lstrip": false,
1576
+ "normalized": false,
1577
+ "rstrip": false,
1578
+ "single_word": false,
1579
+ "special": false
1580
+ },
1581
+ "197": {
1582
+ "content": "</h6>",
1583
+ "lstrip": false,
1584
+ "normalized": false,
1585
+ "rstrip": false,
1586
+ "single_word": false,
1587
+ "special": false
1588
+ },
1589
+ "198": {
1590
+ "content": "</blockquote>",
1591
+ "lstrip": false,
1592
+ "normalized": false,
1593
+ "rstrip": false,
1594
+ "single_word": false,
1595
+ "special": false
1596
+ },
1597
+ "199": {
1598
+ "content": "<strong>",
1599
+ "lstrip": false,
1600
+ "normalized": false,
1601
+ "rstrip": false,
1602
+ "single_word": false,
1603
+ "special": false
1604
+ },
1605
+ "200": {
1606
+ "content": "<em>",
1607
+ "lstrip": false,
1608
+ "normalized": false,
1609
+ "rstrip": false,
1610
+ "single_word": false,
1611
+ "special": false
1612
+ },
1613
+ "201": {
1614
+ "content": "<b>",
1615
+ "lstrip": false,
1616
+ "normalized": false,
1617
+ "rstrip": false,
1618
+ "single_word": false,
1619
+ "special": false
1620
+ },
1621
+ "202": {
1622
+ "content": "<i>",
1623
+ "lstrip": false,
1624
+ "normalized": false,
1625
+ "rstrip": false,
1626
+ "single_word": false,
1627
+ "special": false
1628
+ },
1629
+ "203": {
1630
+ "content": "<u>",
1631
+ "lstrip": false,
1632
+ "normalized": false,
1633
+ "rstrip": false,
1634
+ "single_word": false,
1635
+ "special": false
1636
+ },
1637
+ "204": {
1638
+ "content": "<s>",
1639
+ "lstrip": false,
1640
+ "normalized": false,
1641
+ "rstrip": false,
1642
+ "single_word": false,
1643
+ "special": false
1644
+ },
1645
+ "205": {
1646
+ "content": "<sub>",
1647
+ "lstrip": false,
1648
+ "normalized": false,
1649
+ "rstrip": false,
1650
+ "single_word": false,
1651
+ "special": false
1652
+ },
1653
+ "206": {
1654
+ "content": "<sup>",
1655
+ "lstrip": false,
1656
+ "normalized": false,
1657
+ "rstrip": false,
1658
+ "single_word": false,
1659
+ "special": false
1660
+ },
1661
+ "207": {
1662
+ "content": "<code>",
1663
+ "lstrip": false,
1664
+ "normalized": false,
1665
+ "rstrip": false,
1666
+ "single_word": false,
1667
+ "special": false
1668
+ },
1669
+ "208": {
1670
+ "content": "</strong>",
1671
+ "lstrip": false,
1672
+ "normalized": false,
1673
+ "rstrip": false,
1674
+ "single_word": false,
1675
+ "special": false
1676
+ },
1677
+ "209": {
1678
+ "content": "</em>",
1679
+ "lstrip": false,
1680
+ "normalized": false,
1681
+ "rstrip": false,
1682
+ "single_word": false,
1683
+ "special": false
1684
+ },
1685
+ "210": {
1686
+ "content": "</b>",
1687
+ "lstrip": false,
1688
+ "normalized": false,
1689
+ "rstrip": false,
1690
+ "single_word": false,
1691
+ "special": false
1692
+ },
1693
+ "211": {
1694
+ "content": "</i>",
1695
+ "lstrip": false,
1696
+ "normalized": false,
1697
+ "rstrip": false,
1698
+ "single_word": false,
1699
+ "special": false
1700
+ },
1701
+ "212": {
1702
+ "content": "</u>",
1703
+ "lstrip": false,
1704
+ "normalized": false,
1705
+ "rstrip": false,
1706
+ "single_word": false,
1707
+ "special": false
1708
+ },
1709
+ "213": {
1710
+ "content": "</s>",
1711
+ "lstrip": false,
1712
+ "normalized": false,
1713
+ "rstrip": false,
1714
+ "single_word": false,
1715
+ "special": false
1716
+ },
1717
+ "214": {
1718
+ "content": "</sub>",
1719
+ "lstrip": false,
1720
+ "normalized": false,
1721
+ "rstrip": false,
1722
+ "single_word": false,
1723
+ "special": false
1724
+ },
1725
+ "215": {
1726
+ "content": "</sup>",
1727
+ "lstrip": false,
1728
+ "normalized": false,
1729
+ "rstrip": false,
1730
+ "single_word": false,
1731
+ "special": false
1732
+ },
1733
+ "216": {
1734
+ "content": "</code>",
1735
+ "lstrip": false,
1736
+ "normalized": false,
1737
+ "rstrip": false,
1738
+ "single_word": false,
1739
+ "special": false
1740
+ },
1741
+ "255968": {
1742
+ "content": "[toxicity=0]",
1743
+ "lstrip": false,
1744
+ "normalized": false,
1745
+ "rstrip": false,
1746
+ "single_word": false,
1747
+ "special": false
1748
+ },
1749
+ "255969": {
1750
+ "content": "\t\t",
1751
+ "lstrip": false,
1752
+ "normalized": false,
1753
+ "rstrip": false,
1754
+ "single_word": false,
1755
+ "special": false
1756
+ },
1757
+ "255970": {
1758
+ "content": "\t\t\t",
1759
+ "lstrip": false,
1760
+ "normalized": false,
1761
+ "rstrip": false,
1762
+ "single_word": false,
1763
+ "special": false
1764
+ },
1765
+ "255971": {
1766
+ "content": "\t\t\t\t",
1767
+ "lstrip": false,
1768
+ "normalized": false,
1769
+ "rstrip": false,
1770
+ "single_word": false,
1771
+ "special": false
1772
+ },
1773
+ "255972": {
1774
+ "content": "\t\t\t\t\t",
1775
+ "lstrip": false,
1776
+ "normalized": false,
1777
+ "rstrip": false,
1778
+ "single_word": false,
1779
+ "special": false
1780
+ },
1781
+ "255973": {
1782
+ "content": "\t\t\t\t\t\t",
1783
+ "lstrip": false,
1784
+ "normalized": false,
1785
+ "rstrip": false,
1786
+ "single_word": false,
1787
+ "special": false
1788
+ },
1789
+ "255974": {
1790
+ "content": "\t\t\t\t\t\t\t",
1791
+ "lstrip": false,
1792
+ "normalized": false,
1793
+ "rstrip": false,
1794
+ "single_word": false,
1795
+ "special": false
1796
+ },
1797
+ "255975": {
1798
+ "content": "\t\t\t\t\t\t\t\t",
1799
+ "lstrip": false,
1800
+ "normalized": false,
1801
+ "rstrip": false,
1802
+ "single_word": false,
1803
+ "special": false
1804
+ },
1805
+ "255976": {
1806
+ "content": "\t\t\t\t\t\t\t\t\t",
1807
+ "lstrip": false,
1808
+ "normalized": false,
1809
+ "rstrip": false,
1810
+ "single_word": false,
1811
+ "special": false
1812
+ },
1813
+ "255977": {
1814
+ "content": "\t\t\t\t\t\t\t\t\t\t",
1815
+ "lstrip": false,
1816
+ "normalized": false,
1817
+ "rstrip": false,
1818
+ "single_word": false,
1819
+ "special": false
1820
+ },
1821
+ "255978": {
1822
+ "content": "\t\t\t\t\t\t\t\t\t\t\t",
1823
+ "lstrip": false,
1824
+ "normalized": false,
1825
+ "rstrip": false,
1826
+ "single_word": false,
1827
+ "special": false
1828
+ },
1829
+ "255979": {
1830
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t",
1831
+ "lstrip": false,
1832
+ "normalized": false,
1833
+ "rstrip": false,
1834
+ "single_word": false,
1835
+ "special": false
1836
+ },
1837
+ "255980": {
1838
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t",
1839
+ "lstrip": false,
1840
+ "normalized": false,
1841
+ "rstrip": false,
1842
+ "single_word": false,
1843
+ "special": false
1844
+ },
1845
+ "255981": {
1846
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1847
+ "lstrip": false,
1848
+ "normalized": false,
1849
+ "rstrip": false,
1850
+ "single_word": false,
1851
+ "special": false
1852
+ },
1853
+ "255982": {
1854
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1855
+ "lstrip": false,
1856
+ "normalized": false,
1857
+ "rstrip": false,
1858
+ "single_word": false,
1859
+ "special": false
1860
+ },
1861
+ "255983": {
1862
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1863
+ "lstrip": false,
1864
+ "normalized": false,
1865
+ "rstrip": false,
1866
+ "single_word": false,
1867
+ "special": false
1868
+ },
1869
+ "255984": {
1870
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1871
+ "lstrip": false,
1872
+ "normalized": false,
1873
+ "rstrip": false,
1874
+ "single_word": false,
1875
+ "special": false
1876
+ },
1877
+ "255985": {
1878
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1879
+ "lstrip": false,
1880
+ "normalized": false,
1881
+ "rstrip": false,
1882
+ "single_word": false,
1883
+ "special": false
1884
+ },
1885
+ "255986": {
1886
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1887
+ "lstrip": false,
1888
+ "normalized": false,
1889
+ "rstrip": false,
1890
+ "single_word": false,
1891
+ "special": false
1892
+ },
1893
+ "255987": {
1894
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1895
+ "lstrip": false,
1896
+ "normalized": false,
1897
+ "rstrip": false,
1898
+ "single_word": false,
1899
+ "special": false
1900
+ },
1901
+ "255988": {
1902
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1903
+ "lstrip": false,
1904
+ "normalized": false,
1905
+ "rstrip": false,
1906
+ "single_word": false,
1907
+ "special": false
1908
+ },
1909
+ "255989": {
1910
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1911
+ "lstrip": false,
1912
+ "normalized": false,
1913
+ "rstrip": false,
1914
+ "single_word": false,
1915
+ "special": false
1916
+ },
1917
+ "255990": {
1918
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1919
+ "lstrip": false,
1920
+ "normalized": false,
1921
+ "rstrip": false,
1922
+ "single_word": false,
1923
+ "special": false
1924
+ },
1925
+ "255991": {
1926
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1927
+ "lstrip": false,
1928
+ "normalized": false,
1929
+ "rstrip": false,
1930
+ "single_word": false,
1931
+ "special": false
1932
+ },
1933
+ "255992": {
1934
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1935
+ "lstrip": false,
1936
+ "normalized": false,
1937
+ "rstrip": false,
1938
+ "single_word": false,
1939
+ "special": false
1940
+ },
1941
+ "255993": {
1942
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1943
+ "lstrip": false,
1944
+ "normalized": false,
1945
+ "rstrip": false,
1946
+ "single_word": false,
1947
+ "special": false
1948
+ },
1949
+ "255994": {
1950
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1951
+ "lstrip": false,
1952
+ "normalized": false,
1953
+ "rstrip": false,
1954
+ "single_word": false,
1955
+ "special": false
1956
+ },
1957
+ "255995": {
1958
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1959
+ "lstrip": false,
1960
+ "normalized": false,
1961
+ "rstrip": false,
1962
+ "single_word": false,
1963
+ "special": false
1964
+ },
1965
+ "255996": {
1966
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1967
+ "lstrip": false,
1968
+ "normalized": false,
1969
+ "rstrip": false,
1970
+ "single_word": false,
1971
+ "special": false
1972
+ },
1973
+ "255997": {
1974
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1975
+ "lstrip": false,
1976
+ "normalized": false,
1977
+ "rstrip": false,
1978
+ "single_word": false,
1979
+ "special": false
1980
+ },
1981
+ "255998": {
1982
+ "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
1983
+ "lstrip": false,
1984
+ "normalized": false,
1985
+ "rstrip": false,
1986
+ "single_word": false,
1987
+ "special": false
1988
+ },
1989
+ "255999": {
1990
+ "content": "<unused99>",
1991
+ "lstrip": false,
1992
+ "normalized": false,
1993
+ "rstrip": false,
1994
+ "single_word": false,
1995
+ "special": false
1996
+ }
1997
+ },
1998
+ "additional_special_tokens": [
1999
+ "<start_of_turn>",
2000
+ "<end_of_turn>"
2001
+ ],
2002
+ "bos_token": "<bos>",
2003
+ "chat_template": "{{ bos_token }}{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '<start_of_turn>' + role + '\n' + message['content'] | trim + '<end_of_turn>\n' }}{% endfor %}{% if add_generation_prompt %}{{'<start_of_turn>model\n'}}{% endif %}",
2004
+ "clean_up_tokenization_spaces": false,
2005
+ "do_lower_case": true,
2006
+ "eos_token": "<eos>",
2007
+ "extra_special_tokens": {},
2008
+ "model_input_names": [
2009
+ "input_ids"
2010
+ ],
2011
+ "model_max_length": 1000000000000000019884624838656,
2012
+ "pad_token": "<pad>",
2013
+ "padding_side": "right",
2014
+ "processor_class": "SiglipProcessor",
2015
+ "sp_model_kwargs": {},
2016
+ "spaces_between_special_tokens": false,
2017
+ "tokenizer_class": "GemmaTokenizer",
2018
+ "unk_token": "<unk>",
2019
+ "use_default_system_prompt": false
2020
+ }
SKING_DDJ_v101c/hf_cache/modules/__init__.py ADDED
File without changes
SKING_DDJ_v101c/hf_cache/modules/transformers_modules/__init__.py ADDED
File without changes
SKING_DDJ_v101c/hf_cache/modules/transformers_modules/foreground_base/BiRefNet_config.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class BiRefNetConfig(PretrainedConfig):
4
+ model_type = "SegformerForSemanticSegmentation"
5
+ def __init__(
6
+ self,
7
+ bb_pretrained=False,
8
+ **kwargs
9
+ ):
10
+ self.bb_pretrained = bb_pretrained
11
+ super().__init__(**kwargs)
SKING_DDJ_v101c/hf_cache/modules/transformers_modules/foreground_base/__init__.py ADDED
File without changes
SKING_DDJ_v101c/hf_cache/modules/transformers_modules/foreground_base/birefnet.py ADDED
@@ -0,0 +1,2249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### config.py
2
+
3
+ import os
4
+ import math
5
+ from transformers import PretrainedConfig
6
+
7
+
8
+ class Config(PretrainedConfig):
9
+ def __init__(self) -> None:
10
+ # PATH settings
11
+ self.sys_home_dir = os.path.expanduser('~') # Make up your file system as: SYS_HOME_DIR/codes/dis/BiRefNet, SYS_HOME_DIR/datasets/dis/xx, SYS_HOME_DIR/weights/xx
12
+
13
+ # TASK settings
14
+ self.task = ['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'][0]
15
+ self.training_set = {
16
+ 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0],
17
+ 'COD': 'TR-COD10K+TR-CAMO',
18
+ 'HRSOD': ['TR-DUTS', 'TR-HRSOD', 'TR-UHRSD', 'TR-DUTS+TR-HRSOD', 'TR-DUTS+TR-UHRSD', 'TR-HRSOD+TR-UHRSD', 'TR-DUTS+TR-HRSOD+TR-UHRSD'][5],
19
+ 'DIS5K+HRSOD+HRS10K': 'DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4+DIS-TR+TE-HRS10K+TE-HRSOD+TE-UHRSD+TR-HRS10K+TR-HRSOD+TR-UHRSD', # leave DIS-VD for evaluation.
20
+ 'P3M-10k': 'TR-P3M-10k',
21
+ }[self.task]
22
+ self.prompt4loc = ['dense', 'sparse'][0]
23
+
24
+ # Faster-Training settings
25
+ self.load_all = True
26
+ self.compile = True # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch.
27
+ # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting.
28
+ # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607.
29
+ # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training.
30
+ self.precisionHigh = True
31
+
32
+ # MODEL settings
33
+ self.ms_supervision = True
34
+ self.out_ref = self.ms_supervision and True
35
+ self.dec_ipt = True
36
+ self.dec_ipt_split = True
37
+ self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder
38
+ self.mul_scl_ipt = ['', 'add', 'cat'][2]
39
+ self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2]
40
+ self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1]
41
+ self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0]
42
+
43
+ # TRAINING settings
44
+ self.batch_size = 4
45
+ self.IoU_finetune_last_epochs = [
46
+ 0,
47
+ {
48
+ 'DIS5K': -50,
49
+ 'COD': -20,
50
+ 'HRSOD': -20,
51
+ 'DIS5K+HRSOD+HRS10K': -20,
52
+ 'P3M-10k': -20,
53
+ }[self.task]
54
+ ][1] # choose 0 to skip
55
+ self.lr = (1e-4 if 'DIS5K' in self.task else 1e-5) * math.sqrt(self.batch_size / 4) # DIS needs high lr to converge faster. Adapt the lr linearly
56
+ self.size = 1024
57
+ self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader
58
+
59
+ # Backbone settings
60
+ self.bb = [
61
+ 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2
62
+ 'swin_v1_t', 'swin_v1_s', # 3, 4
63
+ 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs4
64
+ 'pvt_v2_b0', 'pvt_v2_b1', # 7, 8
65
+ 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5
66
+ ][6]
67
+ self.lateral_channels_in_collection = {
68
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
69
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
70
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
71
+ 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96],
72
+ 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64],
73
+ }[self.bb]
74
+ if self.mul_scl_ipt == 'cat':
75
+ self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection]
76
+ self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []
77
+
78
+ # MODEL settings - inactive
79
+ self.lat_blk = ['BasicLatBlk'][0]
80
+ self.dec_channels_inter = ['fixed', 'adap'][0]
81
+ self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0]
82
+ self.progressive_ref = self.refine and True
83
+ self.ender = self.progressive_ref and False
84
+ self.scale = self.progressive_ref and 2
85
+ self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`.
86
+ self.refine_iteration = 1
87
+ self.freeze_bb = False
88
+ self.model = [
89
+ 'BiRefNet',
90
+ ][0]
91
+ if self.dec_blk == 'HierarAttDecBlk':
92
+ self.batch_size = 2 ** [0, 1, 2, 3, 4][2]
93
+
94
+ # TRAINING settings - inactive
95
+ self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4]
96
+ self.optimizer = ['Adam', 'AdamW'][1]
97
+ self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch.
98
+ self.lr_decay_rate = 0.5
99
+ # Loss
100
+ self.lambdas_pix_last = {
101
+ # not 0 means opening this loss
102
+ # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30
103
+ 'bce': 30 * 1, # high performance
104
+ 'iou': 0.5 * 1, # 0 / 255
105
+ 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64)
106
+ 'mse': 150 * 0, # can smooth the saliency map
107
+ 'triplet': 3 * 0,
108
+ 'reg': 100 * 0,
109
+ 'ssim': 10 * 1, # help contours,
110
+ 'cnt': 5 * 0, # help contours
111
+ 'structure': 5 * 0, # structure loss from codes of MVANet. A little improvement on DIS-TE[1,2,3], a bit more decrease on DIS-TE4.
112
+ }
113
+ self.lambdas_cls = {
114
+ 'ce': 5.0
115
+ }
116
+ # Adv
117
+ self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training
118
+ self.lambda_adv_d = 3. * (self.lambda_adv_g > 0)
119
+
120
+ # PATH settings - inactive
121
+ self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis')
122
+ self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights')
123
+ self.weights = {
124
+ 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'),
125
+ 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]),
126
+ 'swin_v1_b': os.path.join(self.weights_root_dir, ['swin_base_patch4_window12_384_22kto1k.pth', 'swin_base_patch4_window12_384_22k.pth'][0]),
127
+ 'swin_v1_l': os.path.join(self.weights_root_dir, ['swin_large_patch4_window12_384_22kto1k.pth', 'swin_large_patch4_window12_384_22k.pth'][0]),
128
+ 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]),
129
+ 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]),
130
+ 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]),
131
+ 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]),
132
+ }
133
+
134
+ # Callbacks - inactive
135
+ self.verbose_eval = True
136
+ self.only_S_MAE = False
137
+ self.use_fp16 = False # Bugs. It may cause nan in training.
138
+ self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs
139
+
140
+ # others
141
+ self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')
142
+
143
+ self.batch_size_valid = 1
144
+ self.rand_seed = 7
145
+ # run_sh_file = [f for f in os.listdir('.') if 'train.sh' == f] + [os.path.join('..', f) for f in os.listdir('..') if 'train.sh' == f]
146
+ # with open(run_sh_file[0], 'r') as f:
147
+ # lines = f.readlines()
148
+ # self.save_last = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'val_last=' in l][0].split('val_last=')[-1].split()[0])
149
+ # self.save_step = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'step=' in l][0].split('step=')[-1].split()[0])
150
+ # self.val_step = [0, self.save_step][0]
151
+
152
+ def print_task(self) -> None:
153
+ # Return task for choosing settings in shell scripts.
154
+ print(self.task)
155
+
156
+
157
+
158
+ ### models/backbones/pvt_v2.py
159
+
160
+ import torch
161
+ import torch.nn as nn
162
+ from functools import partial
163
+
164
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
165
+ from timm.models.registry import register_model
166
+
167
+ import math
168
+
169
+ # from config import Config
170
+
171
+ # config = Config()
172
+
173
+ class Mlp(nn.Module):
174
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
175
+ super().__init__()
176
+ out_features = out_features or in_features
177
+ hidden_features = hidden_features or in_features
178
+ self.fc1 = nn.Linear(in_features, hidden_features)
179
+ self.dwconv = DWConv(hidden_features)
180
+ self.act = act_layer()
181
+ self.fc2 = nn.Linear(hidden_features, out_features)
182
+ self.drop = nn.Dropout(drop)
183
+
184
+ self.apply(self._init_weights)
185
+
186
+ def _init_weights(self, m):
187
+ if isinstance(m, nn.Linear):
188
+ trunc_normal_(m.weight, std=.02)
189
+ if isinstance(m, nn.Linear) and m.bias is not None:
190
+ nn.init.constant_(m.bias, 0)
191
+ elif isinstance(m, nn.LayerNorm):
192
+ nn.init.constant_(m.bias, 0)
193
+ nn.init.constant_(m.weight, 1.0)
194
+ elif isinstance(m, nn.Conv2d):
195
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
196
+ fan_out //= m.groups
197
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
198
+ if m.bias is not None:
199
+ m.bias.data.zero_()
200
+
201
+ def forward(self, x, H, W):
202
+ x = self.fc1(x)
203
+ x = self.dwconv(x, H, W)
204
+ x = self.act(x)
205
+ x = self.drop(x)
206
+ x = self.fc2(x)
207
+ x = self.drop(x)
208
+ return x
209
+
210
+
211
+ class Attention(nn.Module):
212
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
213
+ super().__init__()
214
+ assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
215
+
216
+ self.dim = dim
217
+ self.num_heads = num_heads
218
+ head_dim = dim // num_heads
219
+ self.scale = qk_scale or head_dim ** -0.5
220
+
221
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
222
+ self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
223
+ self.attn_drop_prob = attn_drop
224
+ self.attn_drop = nn.Dropout(attn_drop)
225
+ self.proj = nn.Linear(dim, dim)
226
+ self.proj_drop = nn.Dropout(proj_drop)
227
+
228
+ self.sr_ratio = sr_ratio
229
+ if sr_ratio > 1:
230
+ self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
231
+ self.norm = nn.LayerNorm(dim)
232
+
233
+ self.apply(self._init_weights)
234
+
235
+ def _init_weights(self, m):
236
+ if isinstance(m, nn.Linear):
237
+ trunc_normal_(m.weight, std=.02)
238
+ if isinstance(m, nn.Linear) and m.bias is not None:
239
+ nn.init.constant_(m.bias, 0)
240
+ elif isinstance(m, nn.LayerNorm):
241
+ nn.init.constant_(m.bias, 0)
242
+ nn.init.constant_(m.weight, 1.0)
243
+ elif isinstance(m, nn.Conv2d):
244
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
245
+ fan_out //= m.groups
246
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
247
+ if m.bias is not None:
248
+ m.bias.data.zero_()
249
+
250
+ def forward(self, x, H, W):
251
+ B, N, C = x.shape
252
+ q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
253
+
254
+ if self.sr_ratio > 1:
255
+ x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
256
+ x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
257
+ x_ = self.norm(x_)
258
+ kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
259
+ else:
260
+ kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
261
+ k, v = kv[0], kv[1]
262
+
263
+ if config.SDPA_enabled:
264
+ x = torch.nn.functional.scaled_dot_product_attention(
265
+ q, k, v,
266
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
267
+ ).transpose(1, 2).reshape(B, N, C)
268
+ else:
269
+ attn = (q @ k.transpose(-2, -1)) * self.scale
270
+ attn = attn.softmax(dim=-1)
271
+ attn = self.attn_drop(attn)
272
+
273
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
274
+ x = self.proj(x)
275
+ x = self.proj_drop(x)
276
+
277
+ return x
278
+
279
+
280
+ class Block(nn.Module):
281
+
282
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
283
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
284
+ super().__init__()
285
+ self.norm1 = norm_layer(dim)
286
+ self.attn = Attention(
287
+ dim,
288
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
289
+ attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
290
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
291
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
292
+ self.norm2 = norm_layer(dim)
293
+ mlp_hidden_dim = int(dim * mlp_ratio)
294
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
295
+
296
+ self.apply(self._init_weights)
297
+
298
+ def _init_weights(self, m):
299
+ if isinstance(m, nn.Linear):
300
+ trunc_normal_(m.weight, std=.02)
301
+ if isinstance(m, nn.Linear) and m.bias is not None:
302
+ nn.init.constant_(m.bias, 0)
303
+ elif isinstance(m, nn.LayerNorm):
304
+ nn.init.constant_(m.bias, 0)
305
+ nn.init.constant_(m.weight, 1.0)
306
+ elif isinstance(m, nn.Conv2d):
307
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
308
+ fan_out //= m.groups
309
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
310
+ if m.bias is not None:
311
+ m.bias.data.zero_()
312
+
313
+ def forward(self, x, H, W):
314
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
315
+ x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
316
+
317
+ return x
318
+
319
+
320
+ class OverlapPatchEmbed(nn.Module):
321
+ """ Image to Patch Embedding
322
+ """
323
+
324
+ def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768):
325
+ super().__init__()
326
+ img_size = to_2tuple(img_size)
327
+ patch_size = to_2tuple(patch_size)
328
+
329
+ self.img_size = img_size
330
+ self.patch_size = patch_size
331
+ self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
332
+ self.num_patches = self.H * self.W
333
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride,
334
+ padding=(patch_size[0] // 2, patch_size[1] // 2))
335
+ self.norm = nn.LayerNorm(embed_dim)
336
+
337
+ self.apply(self._init_weights)
338
+
339
+ def _init_weights(self, m):
340
+ if isinstance(m, nn.Linear):
341
+ trunc_normal_(m.weight, std=.02)
342
+ if isinstance(m, nn.Linear) and m.bias is not None:
343
+ nn.init.constant_(m.bias, 0)
344
+ elif isinstance(m, nn.LayerNorm):
345
+ nn.init.constant_(m.bias, 0)
346
+ nn.init.constant_(m.weight, 1.0)
347
+ elif isinstance(m, nn.Conv2d):
348
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
349
+ fan_out //= m.groups
350
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
351
+ if m.bias is not None:
352
+ m.bias.data.zero_()
353
+
354
+ def forward(self, x):
355
+ x = self.proj(x)
356
+ _, _, H, W = x.shape
357
+ x = x.flatten(2).transpose(1, 2)
358
+ x = self.norm(x)
359
+
360
+ return x, H, W
361
+
362
+
363
+ class PyramidVisionTransformerImpr(nn.Module):
364
+ def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512],
365
+ num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,
366
+ attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
367
+ depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):
368
+ super().__init__()
369
+ self.num_classes = num_classes
370
+ self.depths = depths
371
+
372
+ # patch_embed
373
+ self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels,
374
+ embed_dim=embed_dims[0])
375
+ self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0],
376
+ embed_dim=embed_dims[1])
377
+ self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1],
378
+ embed_dim=embed_dims[2])
379
+ self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2],
380
+ embed_dim=embed_dims[3])
381
+
382
+ # transformer encoder
383
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
384
+ cur = 0
385
+ self.block1 = nn.ModuleList([Block(
386
+ dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,
387
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
388
+ sr_ratio=sr_ratios[0])
389
+ for i in range(depths[0])])
390
+ self.norm1 = norm_layer(embed_dims[0])
391
+
392
+ cur += depths[0]
393
+ self.block2 = nn.ModuleList([Block(
394
+ dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,
395
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
396
+ sr_ratio=sr_ratios[1])
397
+ for i in range(depths[1])])
398
+ self.norm2 = norm_layer(embed_dims[1])
399
+
400
+ cur += depths[1]
401
+ self.block3 = nn.ModuleList([Block(
402
+ dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,
403
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
404
+ sr_ratio=sr_ratios[2])
405
+ for i in range(depths[2])])
406
+ self.norm3 = norm_layer(embed_dims[2])
407
+
408
+ cur += depths[2]
409
+ self.block4 = nn.ModuleList([Block(
410
+ dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,
411
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
412
+ sr_ratio=sr_ratios[3])
413
+ for i in range(depths[3])])
414
+ self.norm4 = norm_layer(embed_dims[3])
415
+
416
+ # classification head
417
+ # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
418
+
419
+ self.apply(self._init_weights)
420
+
421
+ def _init_weights(self, m):
422
+ if isinstance(m, nn.Linear):
423
+ trunc_normal_(m.weight, std=.02)
424
+ if isinstance(m, nn.Linear) and m.bias is not None:
425
+ nn.init.constant_(m.bias, 0)
426
+ elif isinstance(m, nn.LayerNorm):
427
+ nn.init.constant_(m.bias, 0)
428
+ nn.init.constant_(m.weight, 1.0)
429
+ elif isinstance(m, nn.Conv2d):
430
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
431
+ fan_out //= m.groups
432
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
433
+ if m.bias is not None:
434
+ m.bias.data.zero_()
435
+
436
+ def init_weights(self, pretrained=None):
437
+ if isinstance(pretrained, str):
438
+ logger = 1
439
+ #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
440
+
441
+ def reset_drop_path(self, drop_path_rate):
442
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
443
+ cur = 0
444
+ for i in range(self.depths[0]):
445
+ self.block1[i].drop_path.drop_prob = dpr[cur + i]
446
+
447
+ cur += self.depths[0]
448
+ for i in range(self.depths[1]):
449
+ self.block2[i].drop_path.drop_prob = dpr[cur + i]
450
+
451
+ cur += self.depths[1]
452
+ for i in range(self.depths[2]):
453
+ self.block3[i].drop_path.drop_prob = dpr[cur + i]
454
+
455
+ cur += self.depths[2]
456
+ for i in range(self.depths[3]):
457
+ self.block4[i].drop_path.drop_prob = dpr[cur + i]
458
+
459
+ def freeze_patch_emb(self):
460
+ self.patch_embed1.requires_grad = False
461
+
462
+ @torch.jit.ignore
463
+ def no_weight_decay(self):
464
+ return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
465
+
466
+ def get_classifier(self):
467
+ return self.head
468
+
469
+ def reset_classifier(self, num_classes, global_pool=''):
470
+ self.num_classes = num_classes
471
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
472
+
473
+ def forward_features(self, x):
474
+ B = x.shape[0]
475
+ outs = []
476
+
477
+ # stage 1
478
+ x, H, W = self.patch_embed1(x)
479
+ for i, blk in enumerate(self.block1):
480
+ x = blk(x, H, W)
481
+ x = self.norm1(x)
482
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
483
+ outs.append(x)
484
+
485
+ # stage 2
486
+ x, H, W = self.patch_embed2(x)
487
+ for i, blk in enumerate(self.block2):
488
+ x = blk(x, H, W)
489
+ x = self.norm2(x)
490
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
491
+ outs.append(x)
492
+
493
+ # stage 3
494
+ x, H, W = self.patch_embed3(x)
495
+ for i, blk in enumerate(self.block3):
496
+ x = blk(x, H, W)
497
+ x = self.norm3(x)
498
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
499
+ outs.append(x)
500
+
501
+ # stage 4
502
+ x, H, W = self.patch_embed4(x)
503
+ for i, blk in enumerate(self.block4):
504
+ x = blk(x, H, W)
505
+ x = self.norm4(x)
506
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
507
+ outs.append(x)
508
+
509
+ return outs
510
+
511
+ # return x.mean(dim=1)
512
+
513
+ def forward(self, x):
514
+ x = self.forward_features(x)
515
+ # x = self.head(x)
516
+
517
+ return x
518
+
519
+
520
+ class DWConv(nn.Module):
521
+ def __init__(self, dim=768):
522
+ super(DWConv, self).__init__()
523
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
524
+
525
+ def forward(self, x, H, W):
526
+ B, N, C = x.shape
527
+ x = x.transpose(1, 2).view(B, C, H, W).contiguous()
528
+ x = self.dwconv(x)
529
+ x = x.flatten(2).transpose(1, 2)
530
+
531
+ return x
532
+
533
+
534
+ def _conv_filter(state_dict, patch_size=16):
535
+ """ convert patch embedding weight from manual patchify + linear proj to conv"""
536
+ out_dict = {}
537
+ for k, v in state_dict.items():
538
+ if 'patch_embed.proj.weight' in k:
539
+ v = v.reshape((v.shape[0], 3, patch_size, patch_size))
540
+ out_dict[k] = v
541
+
542
+ return out_dict
543
+
544
+
545
+ ## @register_model
546
+ class pvt_v2_b0(PyramidVisionTransformerImpr):
547
+ def __init__(self, **kwargs):
548
+ super(pvt_v2_b0, self).__init__(
549
+ patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
550
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
551
+ drop_rate=0.0, drop_path_rate=0.1)
552
+
553
+
554
+
555
+ ## @register_model
556
+ class pvt_v2_b1(PyramidVisionTransformerImpr):
557
+ def __init__(self, **kwargs):
558
+ super(pvt_v2_b1, self).__init__(
559
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
560
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
561
+ drop_rate=0.0, drop_path_rate=0.1)
562
+
563
+ ## @register_model
564
+ class pvt_v2_b2(PyramidVisionTransformerImpr):
565
+ def __init__(self, in_channels=3, **kwargs):
566
+ super(pvt_v2_b2, self).__init__(
567
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
568
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],
569
+ drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)
570
+
571
+ ## @register_model
572
+ class pvt_v2_b3(PyramidVisionTransformerImpr):
573
+ def __init__(self, **kwargs):
574
+ super(pvt_v2_b3, self).__init__(
575
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
576
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],
577
+ drop_rate=0.0, drop_path_rate=0.1)
578
+
579
+ ## @register_model
580
+ class pvt_v2_b4(PyramidVisionTransformerImpr):
581
+ def __init__(self, **kwargs):
582
+ super(pvt_v2_b4, self).__init__(
583
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
584
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],
585
+ drop_rate=0.0, drop_path_rate=0.1)
586
+
587
+
588
+ ## @register_model
589
+ class pvt_v2_b5(PyramidVisionTransformerImpr):
590
+ def __init__(self, **kwargs):
591
+ super(pvt_v2_b5, self).__init__(
592
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
593
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],
594
+ drop_rate=0.0, drop_path_rate=0.1)
595
+
596
+
597
+
598
+ ### models/backbones/swin_v1.py
599
+
600
+ # --------------------------------------------------------
601
+ # Swin Transformer
602
+ # Copyright (c) 2021 Microsoft
603
+ # Licensed under The MIT License [see LICENSE for details]
604
+ # Written by Ze Liu, Yutong Lin, Yixuan Wei
605
+ # --------------------------------------------------------
606
+
607
+ import torch
608
+ import torch.nn as nn
609
+ import torch.nn.functional as F
610
+ import torch.utils.checkpoint as checkpoint
611
+ import numpy as np
612
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
613
+
614
+ # from config import Config
615
+
616
+
617
+ # config = Config()
618
+
619
+
620
+ class Mlp(nn.Module):
621
+ """ Multilayer perceptron."""
622
+
623
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
624
+ super().__init__()
625
+ out_features = out_features or in_features
626
+ hidden_features = hidden_features or in_features
627
+ self.fc1 = nn.Linear(in_features, hidden_features)
628
+ self.act = act_layer()
629
+ self.fc2 = nn.Linear(hidden_features, out_features)
630
+ self.drop = nn.Dropout(drop)
631
+
632
+ def forward(self, x):
633
+ x = self.fc1(x)
634
+ x = self.act(x)
635
+ x = self.drop(x)
636
+ x = self.fc2(x)
637
+ x = self.drop(x)
638
+ return x
639
+
640
+
641
+ def window_partition(x, window_size):
642
+ """
643
+ Args:
644
+ x: (B, H, W, C)
645
+ window_size (int): window size
646
+
647
+ Returns:
648
+ windows: (num_windows*B, window_size, window_size, C)
649
+ """
650
+ B, H, W, C = x.shape
651
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
652
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
653
+ return windows
654
+
655
+
656
+ def window_reverse(windows, window_size, H, W):
657
+ """
658
+ Args:
659
+ windows: (num_windows*B, window_size, window_size, C)
660
+ window_size (int): Window size
661
+ H (int): Height of image
662
+ W (int): Width of image
663
+
664
+ Returns:
665
+ x: (B, H, W, C)
666
+ """
667
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
668
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
669
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
670
+ return x
671
+
672
+
673
+ class WindowAttention(nn.Module):
674
+ """ Window based multi-head self attention (W-MSA) module with relative position bias.
675
+ It supports both of shifted and non-shifted window.
676
+
677
+ Args:
678
+ dim (int): Number of input channels.
679
+ window_size (tuple[int]): The height and width of the window.
680
+ num_heads (int): Number of attention heads.
681
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
682
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
683
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
684
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
685
+ """
686
+
687
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
688
+
689
+ super().__init__()
690
+ self.dim = dim
691
+ self.window_size = window_size # Wh, Ww
692
+ self.num_heads = num_heads
693
+ head_dim = dim // num_heads
694
+ self.scale = qk_scale or head_dim ** -0.5
695
+
696
+ # define a parameter table of relative position bias
697
+ self.relative_position_bias_table = nn.Parameter(
698
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
699
+
700
+ # get pair-wise relative position index for each token inside the window
701
+ coords_h = torch.arange(self.window_size[0])
702
+ coords_w = torch.arange(self.window_size[1])
703
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww
704
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
705
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
706
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
707
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
708
+ relative_coords[:, :, 1] += self.window_size[1] - 1
709
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
710
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
711
+ self.register_buffer("relative_position_index", relative_position_index)
712
+
713
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
714
+ self.attn_drop_prob = attn_drop
715
+ self.attn_drop = nn.Dropout(attn_drop)
716
+ self.proj = nn.Linear(dim, dim)
717
+ self.proj_drop = nn.Dropout(proj_drop)
718
+
719
+ trunc_normal_(self.relative_position_bias_table, std=.02)
720
+ self.softmax = nn.Softmax(dim=-1)
721
+
722
+ def forward(self, x, mask=None):
723
+ """ Forward function.
724
+
725
+ Args:
726
+ x: input features with shape of (num_windows*B, N, C)
727
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
728
+ """
729
+ B_, N, C = x.shape
730
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
731
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
732
+
733
+ q = q * self.scale
734
+
735
+ if config.SDPA_enabled:
736
+ x = torch.nn.functional.scaled_dot_product_attention(
737
+ q, k, v,
738
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
739
+ ).transpose(1, 2).reshape(B_, N, C)
740
+ else:
741
+ attn = (q @ k.transpose(-2, -1))
742
+
743
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
744
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
745
+ ) # Wh*Ww, Wh*Ww, nH
746
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
747
+ attn = attn + relative_position_bias.unsqueeze(0)
748
+
749
+ if mask is not None:
750
+ nW = mask.shape[0]
751
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
752
+ attn = attn.view(-1, self.num_heads, N, N)
753
+ attn = self.softmax(attn)
754
+ else:
755
+ attn = self.softmax(attn)
756
+
757
+ attn = self.attn_drop(attn)
758
+
759
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
760
+ x = self.proj(x)
761
+ x = self.proj_drop(x)
762
+ return x
763
+
764
+
765
+ class SwinTransformerBlock(nn.Module):
766
+ """ Swin Transformer Block.
767
+
768
+ Args:
769
+ dim (int): Number of input channels.
770
+ num_heads (int): Number of attention heads.
771
+ window_size (int): Window size.
772
+ shift_size (int): Shift size for SW-MSA.
773
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
774
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
775
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
776
+ drop (float, optional): Dropout rate. Default: 0.0
777
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
778
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
779
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
780
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
781
+ """
782
+
783
+ def __init__(self, dim, num_heads, window_size=7, shift_size=0,
784
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
785
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm):
786
+ super().__init__()
787
+ self.dim = dim
788
+ self.num_heads = num_heads
789
+ self.window_size = window_size
790
+ self.shift_size = shift_size
791
+ self.mlp_ratio = mlp_ratio
792
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
793
+
794
+ self.norm1 = norm_layer(dim)
795
+ self.attn = WindowAttention(
796
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
797
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
798
+
799
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
800
+ self.norm2 = norm_layer(dim)
801
+ mlp_hidden_dim = int(dim * mlp_ratio)
802
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
803
+
804
+ self.H = None
805
+ self.W = None
806
+
807
+ def forward(self, x, mask_matrix):
808
+ """ Forward function.
809
+
810
+ Args:
811
+ x: Input feature, tensor size (B, H*W, C).
812
+ H, W: Spatial resolution of the input feature.
813
+ mask_matrix: Attention mask for cyclic shift.
814
+ """
815
+ B, L, C = x.shape
816
+ H, W = self.H, self.W
817
+ assert L == H * W, "input feature has wrong size"
818
+
819
+ shortcut = x
820
+ x = self.norm1(x)
821
+ x = x.view(B, H, W, C)
822
+
823
+ # pad feature maps to multiples of window size
824
+ pad_l = pad_t = 0
825
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
826
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
827
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
828
+ _, Hp, Wp, _ = x.shape
829
+
830
+ # cyclic shift
831
+ if self.shift_size > 0:
832
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
833
+ attn_mask = mask_matrix
834
+ else:
835
+ shifted_x = x
836
+ attn_mask = None
837
+
838
+ # partition windows
839
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
840
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
841
+
842
+ # W-MSA/SW-MSA
843
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
844
+
845
+ # merge windows
846
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
847
+ shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
848
+
849
+ # reverse cyclic shift
850
+ if self.shift_size > 0:
851
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
852
+ else:
853
+ x = shifted_x
854
+
855
+ if pad_r > 0 or pad_b > 0:
856
+ x = x[:, :H, :W, :].contiguous()
857
+
858
+ x = x.view(B, H * W, C)
859
+
860
+ # FFN
861
+ x = shortcut + self.drop_path(x)
862
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
863
+
864
+ return x
865
+
866
+
867
+ class PatchMerging(nn.Module):
868
+ """ Patch Merging Layer
869
+
870
+ Args:
871
+ dim (int): Number of input channels.
872
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
873
+ """
874
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
875
+ super().__init__()
876
+ self.dim = dim
877
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
878
+ self.norm = norm_layer(4 * dim)
879
+
880
+ def forward(self, x, H, W):
881
+ """ Forward function.
882
+
883
+ Args:
884
+ x: Input feature, tensor size (B, H*W, C).
885
+ H, W: Spatial resolution of the input feature.
886
+ """
887
+ B, L, C = x.shape
888
+ assert L == H * W, "input feature has wrong size"
889
+
890
+ x = x.view(B, H, W, C)
891
+
892
+ # padding
893
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
894
+ if pad_input:
895
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
896
+
897
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
898
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
899
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
900
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
901
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
902
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
903
+
904
+ x = self.norm(x)
905
+ x = self.reduction(x)
906
+
907
+ return x
908
+
909
+
910
+ class BasicLayer(nn.Module):
911
+ """ A basic Swin Transformer layer for one stage.
912
+
913
+ Args:
914
+ dim (int): Number of feature channels
915
+ depth (int): Depths of this stage.
916
+ num_heads (int): Number of attention head.
917
+ window_size (int): Local window size. Default: 7.
918
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
919
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
920
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
921
+ drop (float, optional): Dropout rate. Default: 0.0
922
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
923
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
924
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
925
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
926
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
927
+ """
928
+
929
+ def __init__(self,
930
+ dim,
931
+ depth,
932
+ num_heads,
933
+ window_size=7,
934
+ mlp_ratio=4.,
935
+ qkv_bias=True,
936
+ qk_scale=None,
937
+ drop=0.,
938
+ attn_drop=0.,
939
+ drop_path=0.,
940
+ norm_layer=nn.LayerNorm,
941
+ downsample=None,
942
+ use_checkpoint=False):
943
+ super().__init__()
944
+ self.window_size = window_size
945
+ self.shift_size = window_size // 2
946
+ self.depth = depth
947
+ self.use_checkpoint = use_checkpoint
948
+
949
+ # build blocks
950
+ self.blocks = nn.ModuleList([
951
+ SwinTransformerBlock(
952
+ dim=dim,
953
+ num_heads=num_heads,
954
+ window_size=window_size,
955
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
956
+ mlp_ratio=mlp_ratio,
957
+ qkv_bias=qkv_bias,
958
+ qk_scale=qk_scale,
959
+ drop=drop,
960
+ attn_drop=attn_drop,
961
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
962
+ norm_layer=norm_layer)
963
+ for i in range(depth)])
964
+
965
+ # patch merging layer
966
+ if downsample is not None:
967
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
968
+ else:
969
+ self.downsample = None
970
+
971
+ def forward(self, x, H, W):
972
+ """ Forward function.
973
+
974
+ Args:
975
+ x: Input feature, tensor size (B, H*W, C).
976
+ H, W: Spatial resolution of the input feature.
977
+ """
978
+
979
+ # calculate attention mask for SW-MSA
980
+ # Turn int to torch.tensor for the compatiability with torch.compile in PyTorch 2.5.
981
+ Hp = torch.ceil(torch.tensor(H) / self.window_size).to(torch.int64) * self.window_size
982
+ Wp = torch.ceil(torch.tensor(W) / self.window_size).to(torch.int64) * self.window_size
983
+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
984
+ h_slices = (slice(0, -self.window_size),
985
+ slice(-self.window_size, -self.shift_size),
986
+ slice(-self.shift_size, None))
987
+ w_slices = (slice(0, -self.window_size),
988
+ slice(-self.window_size, -self.shift_size),
989
+ slice(-self.shift_size, None))
990
+ cnt = 0
991
+ for h in h_slices:
992
+ for w in w_slices:
993
+ img_mask[:, h, w, :] = cnt
994
+ cnt += 1
995
+
996
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
997
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
998
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
999
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)).to(x.dtype)
1000
+
1001
+ for blk in self.blocks:
1002
+ blk.H, blk.W = H, W
1003
+ if self.use_checkpoint:
1004
+ x = checkpoint.checkpoint(blk, x, attn_mask)
1005
+ else:
1006
+ x = blk(x, attn_mask)
1007
+ if self.downsample is not None:
1008
+ x_down = self.downsample(x, H, W)
1009
+ Wh, Ww = (H + 1) // 2, (W + 1) // 2
1010
+ return x, H, W, x_down, Wh, Ww
1011
+ else:
1012
+ return x, H, W, x, H, W
1013
+
1014
+
1015
+ class PatchEmbed(nn.Module):
1016
+ """ Image to Patch Embedding
1017
+
1018
+ Args:
1019
+ patch_size (int): Patch token size. Default: 4.
1020
+ in_channels (int): Number of input image channels. Default: 3.
1021
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1022
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
1023
+ """
1024
+
1025
+ def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None):
1026
+ super().__init__()
1027
+ patch_size = to_2tuple(patch_size)
1028
+ self.patch_size = patch_size
1029
+
1030
+ self.in_channels = in_channels
1031
+ self.embed_dim = embed_dim
1032
+
1033
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
1034
+ if norm_layer is not None:
1035
+ self.norm = norm_layer(embed_dim)
1036
+ else:
1037
+ self.norm = None
1038
+
1039
+ def forward(self, x):
1040
+ """Forward function."""
1041
+ # padding
1042
+ _, _, H, W = x.size()
1043
+ if W % self.patch_size[1] != 0:
1044
+ x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
1045
+ if H % self.patch_size[0] != 0:
1046
+ x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
1047
+
1048
+ x = self.proj(x) # B C Wh Ww
1049
+ if self.norm is not None:
1050
+ Wh, Ww = x.size(2), x.size(3)
1051
+ x = x.flatten(2).transpose(1, 2)
1052
+ x = self.norm(x)
1053
+ x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
1054
+
1055
+ return x
1056
+
1057
+
1058
+ class SwinTransformer(nn.Module):
1059
+ """ Swin Transformer backbone.
1060
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
1061
+ https://arxiv.org/pdf/2103.14030
1062
+
1063
+ Args:
1064
+ pretrain_img_size (int): Input image size for training the pretrained model,
1065
+ used in absolute postion embedding. Default 224.
1066
+ patch_size (int | tuple(int)): Patch size. Default: 4.
1067
+ in_channels (int): Number of input image channels. Default: 3.
1068
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1069
+ depths (tuple[int]): Depths of each Swin Transformer stage.
1070
+ num_heads (tuple[int]): Number of attention head of each stage.
1071
+ window_size (int): Window size. Default: 7.
1072
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
1073
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
1074
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
1075
+ drop_rate (float): Dropout rate.
1076
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
1077
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
1078
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
1079
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
1080
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True.
1081
+ out_indices (Sequence[int]): Output from which stages.
1082
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
1083
+ -1 means not freezing any parameters.
1084
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
1085
+ """
1086
+
1087
+ def __init__(self,
1088
+ pretrain_img_size=224,
1089
+ patch_size=4,
1090
+ in_channels=3,
1091
+ embed_dim=96,
1092
+ depths=[2, 2, 6, 2],
1093
+ num_heads=[3, 6, 12, 24],
1094
+ window_size=7,
1095
+ mlp_ratio=4.,
1096
+ qkv_bias=True,
1097
+ qk_scale=None,
1098
+ drop_rate=0.,
1099
+ attn_drop_rate=0.,
1100
+ drop_path_rate=0.2,
1101
+ norm_layer=nn.LayerNorm,
1102
+ ape=False,
1103
+ patch_norm=True,
1104
+ out_indices=(0, 1, 2, 3),
1105
+ frozen_stages=-1,
1106
+ use_checkpoint=False):
1107
+ super().__init__()
1108
+
1109
+ self.pretrain_img_size = pretrain_img_size
1110
+ self.num_layers = len(depths)
1111
+ self.embed_dim = embed_dim
1112
+ self.ape = ape
1113
+ self.patch_norm = patch_norm
1114
+ self.out_indices = out_indices
1115
+ self.frozen_stages = frozen_stages
1116
+
1117
+ # split image into non-overlapping patches
1118
+ self.patch_embed = PatchEmbed(
1119
+ patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim,
1120
+ norm_layer=norm_layer if self.patch_norm else None)
1121
+
1122
+ # absolute position embedding
1123
+ if self.ape:
1124
+ pretrain_img_size = to_2tuple(pretrain_img_size)
1125
+ patch_size = to_2tuple(patch_size)
1126
+ patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
1127
+
1128
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))
1129
+ trunc_normal_(self.absolute_pos_embed, std=.02)
1130
+
1131
+ self.pos_drop = nn.Dropout(p=drop_rate)
1132
+
1133
+ # stochastic depth
1134
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
1135
+
1136
+ # build layers
1137
+ self.layers = nn.ModuleList()
1138
+ for i_layer in range(self.num_layers):
1139
+ layer = BasicLayer(
1140
+ dim=int(embed_dim * 2 ** i_layer),
1141
+ depth=depths[i_layer],
1142
+ num_heads=num_heads[i_layer],
1143
+ window_size=window_size,
1144
+ mlp_ratio=mlp_ratio,
1145
+ qkv_bias=qkv_bias,
1146
+ qk_scale=qk_scale,
1147
+ drop=drop_rate,
1148
+ attn_drop=attn_drop_rate,
1149
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
1150
+ norm_layer=norm_layer,
1151
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
1152
+ use_checkpoint=use_checkpoint)
1153
+ self.layers.append(layer)
1154
+
1155
+ num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
1156
+ self.num_features = num_features
1157
+
1158
+ # add a norm layer for each output
1159
+ for i_layer in out_indices:
1160
+ layer = norm_layer(num_features[i_layer])
1161
+ layer_name = f'norm{i_layer}'
1162
+ self.add_module(layer_name, layer)
1163
+
1164
+ self._freeze_stages()
1165
+
1166
+ def _freeze_stages(self):
1167
+ if self.frozen_stages >= 0:
1168
+ self.patch_embed.eval()
1169
+ for param in self.patch_embed.parameters():
1170
+ param.requires_grad = False
1171
+
1172
+ if self.frozen_stages >= 1 and self.ape:
1173
+ self.absolute_pos_embed.requires_grad = False
1174
+
1175
+ if self.frozen_stages >= 2:
1176
+ self.pos_drop.eval()
1177
+ for i in range(0, self.frozen_stages - 1):
1178
+ m = self.layers[i]
1179
+ m.eval()
1180
+ for param in m.parameters():
1181
+ param.requires_grad = False
1182
+
1183
+
1184
+ def forward(self, x):
1185
+ """Forward function."""
1186
+ x = self.patch_embed(x)
1187
+
1188
+ Wh, Ww = x.size(2), x.size(3)
1189
+ if self.ape:
1190
+ # interpolate the position embedding to the corresponding size
1191
+ absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')
1192
+ x = (x + absolute_pos_embed) # B Wh*Ww C
1193
+
1194
+ outs = []#x.contiguous()]
1195
+ x = x.flatten(2).transpose(1, 2)
1196
+ x = self.pos_drop(x)
1197
+ for i in range(self.num_layers):
1198
+ layer = self.layers[i]
1199
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
1200
+
1201
+ if i in self.out_indices:
1202
+ norm_layer = getattr(self, f'norm{i}')
1203
+ x_out = norm_layer(x_out)
1204
+
1205
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
1206
+ outs.append(out)
1207
+
1208
+ return tuple(outs)
1209
+
1210
+ def train(self, mode=True):
1211
+ """Convert the model into training mode while keep layers freezed."""
1212
+ super(SwinTransformer, self).train(mode)
1213
+ self._freeze_stages()
1214
+
1215
+ def swin_v1_t():
1216
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7)
1217
+ return model
1218
+
1219
+ def swin_v1_s():
1220
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7)
1221
+ return model
1222
+
1223
+ def swin_v1_b():
1224
+ model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12)
1225
+ return model
1226
+
1227
+ def swin_v1_l():
1228
+ model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12)
1229
+ return model
1230
+
1231
+
1232
+
1233
+ ### models/modules/deform_conv.py
1234
+
1235
+ import torch
1236
+ import torch.nn as nn
1237
+ from torchvision.ops import deform_conv2d
1238
+
1239
+
1240
+ class DeformableConv2d(nn.Module):
1241
+ def __init__(self,
1242
+ in_channels,
1243
+ out_channels,
1244
+ kernel_size=3,
1245
+ stride=1,
1246
+ padding=1,
1247
+ bias=False):
1248
+
1249
+ super(DeformableConv2d, self).__init__()
1250
+
1251
+ assert type(kernel_size) == tuple or type(kernel_size) == int
1252
+
1253
+ kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size)
1254
+ self.stride = stride if type(stride) == tuple else (stride, stride)
1255
+ self.padding = padding
1256
+
1257
+ self.offset_conv = nn.Conv2d(in_channels,
1258
+ 2 * kernel_size[0] * kernel_size[1],
1259
+ kernel_size=kernel_size,
1260
+ stride=stride,
1261
+ padding=self.padding,
1262
+ bias=True)
1263
+
1264
+ nn.init.constant_(self.offset_conv.weight, 0.)
1265
+ nn.init.constant_(self.offset_conv.bias, 0.)
1266
+
1267
+ self.modulator_conv = nn.Conv2d(in_channels,
1268
+ 1 * kernel_size[0] * kernel_size[1],
1269
+ kernel_size=kernel_size,
1270
+ stride=stride,
1271
+ padding=self.padding,
1272
+ bias=True)
1273
+
1274
+ nn.init.constant_(self.modulator_conv.weight, 0.)
1275
+ nn.init.constant_(self.modulator_conv.bias, 0.)
1276
+
1277
+ self.regular_conv = nn.Conv2d(in_channels,
1278
+ out_channels=out_channels,
1279
+ kernel_size=kernel_size,
1280
+ stride=stride,
1281
+ padding=self.padding,
1282
+ bias=bias)
1283
+
1284
+ def forward(self, x):
1285
+ #h, w = x.shape[2:]
1286
+ #max_offset = max(h, w)/4.
1287
+
1288
+ offset = self.offset_conv(x)#.clamp(-max_offset, max_offset)
1289
+ modulator = 2. * torch.sigmoid(self.modulator_conv(x))
1290
+
1291
+ x = deform_conv2d(
1292
+ input=x,
1293
+ offset=offset,
1294
+ weight=self.regular_conv.weight,
1295
+ bias=self.regular_conv.bias,
1296
+ padding=self.padding,
1297
+ mask=modulator,
1298
+ stride=self.stride,
1299
+ )
1300
+ return x
1301
+
1302
+
1303
+
1304
+
1305
+ ### utils.py
1306
+
1307
+ import torch.nn as nn
1308
+
1309
+
1310
+ def build_act_layer(act_layer):
1311
+ if act_layer == 'ReLU':
1312
+ return nn.ReLU(inplace=True)
1313
+ elif act_layer == 'SiLU':
1314
+ return nn.SiLU(inplace=True)
1315
+ elif act_layer == 'GELU':
1316
+ return nn.GELU()
1317
+
1318
+ raise NotImplementedError(f'build_act_layer does not support {act_layer}')
1319
+
1320
+
1321
+ def build_norm_layer(dim,
1322
+ norm_layer,
1323
+ in_format='channels_last',
1324
+ out_format='channels_last',
1325
+ eps=1e-6):
1326
+ layers = []
1327
+ if norm_layer == 'BN':
1328
+ if in_format == 'channels_last':
1329
+ layers.append(to_channels_first())
1330
+ layers.append(nn.BatchNorm2d(dim))
1331
+ if out_format == 'channels_last':
1332
+ layers.append(to_channels_last())
1333
+ elif norm_layer == 'LN':
1334
+ if in_format == 'channels_first':
1335
+ layers.append(to_channels_last())
1336
+ layers.append(nn.LayerNorm(dim, eps=eps))
1337
+ if out_format == 'channels_first':
1338
+ layers.append(to_channels_first())
1339
+ else:
1340
+ raise NotImplementedError(
1341
+ f'build_norm_layer does not support {norm_layer}')
1342
+ return nn.Sequential(*layers)
1343
+
1344
+
1345
+ class to_channels_first(nn.Module):
1346
+
1347
+ def __init__(self):
1348
+ super().__init__()
1349
+
1350
+ def forward(self, x):
1351
+ return x.permute(0, 3, 1, 2)
1352
+
1353
+
1354
+ class to_channels_last(nn.Module):
1355
+
1356
+ def __init__(self):
1357
+ super().__init__()
1358
+
1359
+ def forward(self, x):
1360
+ return x.permute(0, 2, 3, 1)
1361
+
1362
+
1363
+
1364
+ ### dataset.py
1365
+
1366
+ _class_labels_TR_sorted = (
1367
+ 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, '
1368
+ 'BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, '
1369
+ 'CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, '
1370
+ 'Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, '
1371
+ 'Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, '
1372
+ 'Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, '
1373
+ 'KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, '
1374
+ 'Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, '
1375
+ 'OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, '
1376
+ 'RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, '
1377
+ 'ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, '
1378
+ 'Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, '
1379
+ 'TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, '
1380
+ 'UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht'
1381
+ )
1382
+ class_labels_TR_sorted = _class_labels_TR_sorted.split(', ')
1383
+
1384
+
1385
+ ### models/backbones/build_backbones.py
1386
+
1387
+ import torch
1388
+ import torch.nn as nn
1389
+ from collections import OrderedDict
1390
+ from torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights
1391
+ # from models.pvt_v2 import pvt_v2_b0, pvt_v2_b1, pvt_v2_b2, pvt_v2_b5
1392
+ # from models.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l
1393
+ # from config import Config
1394
+
1395
+
1396
+ config = Config()
1397
+
1398
+ def build_backbone(bb_name, pretrained=True, params_settings=''):
1399
+ if bb_name == 'vgg16':
1400
+ bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0]
1401
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]}))
1402
+ elif bb_name == 'vgg16bn':
1403
+ bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0]
1404
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]}))
1405
+ elif bb_name == 'resnet50':
1406
+ bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children())
1407
+ bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]}))
1408
+ else:
1409
+ bb = eval('{}({})'.format(bb_name, params_settings))
1410
+ if pretrained:
1411
+ bb = load_weights(bb, bb_name)
1412
+ return bb
1413
+
1414
+ def load_weights(model, model_name):
1415
+ save_model = torch.load(config.weights[model_name], map_location='cpu')
1416
+ model_dict = model.state_dict()
1417
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model.items() if k in model_dict.keys()}
1418
+ # to ignore the weights with mismatched size when I modify the backbone itself.
1419
+ if not state_dict:
1420
+ save_model_keys = list(save_model.keys())
1421
+ sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None
1422
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model[sub_item].items() if k in model_dict.keys()}
1423
+ if not state_dict or not sub_item:
1424
+ print('Weights are not successully loaded. Check the state dict of weights file.')
1425
+ return None
1426
+ else:
1427
+ print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item))
1428
+ model_dict.update(state_dict)
1429
+ model.load_state_dict(model_dict)
1430
+ return model
1431
+
1432
+
1433
+
1434
+ ### models/modules/decoder_blocks.py
1435
+
1436
+ import torch
1437
+ import torch.nn as nn
1438
+ # from models.aspp import ASPP, ASPPDeformable
1439
+ # from config import Config
1440
+
1441
+
1442
+ # config = Config()
1443
+
1444
+
1445
+ class BasicDecBlk(nn.Module):
1446
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1447
+ super(BasicDecBlk, self).__init__()
1448
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1449
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1450
+ self.relu_in = nn.ReLU(inplace=True)
1451
+ if config.dec_att == 'ASPP':
1452
+ self.dec_att = ASPP(in_channels=inter_channels)
1453
+ elif config.dec_att == 'ASPPDeformable':
1454
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1455
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1456
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1457
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1458
+
1459
+ def forward(self, x):
1460
+ x = self.conv_in(x)
1461
+ x = self.bn_in(x)
1462
+ x = self.relu_in(x)
1463
+ if hasattr(self, 'dec_att'):
1464
+ x = self.dec_att(x)
1465
+ x = self.conv_out(x)
1466
+ x = self.bn_out(x)
1467
+ return x
1468
+
1469
+
1470
+ class ResBlk(nn.Module):
1471
+ def __init__(self, in_channels=64, out_channels=None, inter_channels=64):
1472
+ super(ResBlk, self).__init__()
1473
+ if out_channels is None:
1474
+ out_channels = in_channels
1475
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1476
+
1477
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1478
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1479
+ self.relu_in = nn.ReLU(inplace=True)
1480
+
1481
+ if config.dec_att == 'ASPP':
1482
+ self.dec_att = ASPP(in_channels=inter_channels)
1483
+ elif config.dec_att == 'ASPPDeformable':
1484
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1485
+
1486
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1487
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1488
+
1489
+ self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1490
+
1491
+ def forward(self, x):
1492
+ _x = self.conv_resi(x)
1493
+ x = self.conv_in(x)
1494
+ x = self.bn_in(x)
1495
+ x = self.relu_in(x)
1496
+ if hasattr(self, 'dec_att'):
1497
+ x = self.dec_att(x)
1498
+ x = self.conv_out(x)
1499
+ x = self.bn_out(x)
1500
+ return x + _x
1501
+
1502
+
1503
+
1504
+ ### models/modules/lateral_blocks.py
1505
+
1506
+ import numpy as np
1507
+ import torch
1508
+ import torch.nn as nn
1509
+ import torch.nn.functional as F
1510
+ from functools import partial
1511
+
1512
+ # from config import Config
1513
+
1514
+
1515
+ # config = Config()
1516
+
1517
+
1518
+ class BasicLatBlk(nn.Module):
1519
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1520
+ super(BasicLatBlk, self).__init__()
1521
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1522
+ self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1523
+
1524
+ def forward(self, x):
1525
+ x = self.conv(x)
1526
+ return x
1527
+
1528
+
1529
+
1530
+ ### models/modules/aspp.py
1531
+
1532
+ import torch
1533
+ import torch.nn as nn
1534
+ import torch.nn.functional as F
1535
+ # from models.deform_conv import DeformableConv2d
1536
+ # from config import Config
1537
+
1538
+
1539
+ # config = Config()
1540
+
1541
+
1542
+ class _ASPPModule(nn.Module):
1543
+ def __init__(self, in_channels, planes, kernel_size, padding, dilation):
1544
+ super(_ASPPModule, self).__init__()
1545
+ self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size,
1546
+ stride=1, padding=padding, dilation=dilation, bias=False)
1547
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1548
+ self.relu = nn.ReLU(inplace=True)
1549
+
1550
+ def forward(self, x):
1551
+ x = self.atrous_conv(x)
1552
+ x = self.bn(x)
1553
+
1554
+ return self.relu(x)
1555
+
1556
+
1557
+ class ASPP(nn.Module):
1558
+ def __init__(self, in_channels=64, out_channels=None, output_stride=16):
1559
+ super(ASPP, self).__init__()
1560
+ self.down_scale = 1
1561
+ if out_channels is None:
1562
+ out_channels = in_channels
1563
+ self.in_channelster = 256 // self.down_scale
1564
+ if output_stride == 16:
1565
+ dilations = [1, 6, 12, 18]
1566
+ elif output_stride == 8:
1567
+ dilations = [1, 12, 24, 36]
1568
+ else:
1569
+ raise NotImplementedError
1570
+
1571
+ self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0])
1572
+ self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1])
1573
+ self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2])
1574
+ self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3])
1575
+
1576
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1577
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1578
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1579
+ nn.ReLU(inplace=True))
1580
+ self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False)
1581
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1582
+ self.relu = nn.ReLU(inplace=True)
1583
+ self.dropout = nn.Dropout(0.5)
1584
+
1585
+ def forward(self, x):
1586
+ x1 = self.aspp1(x)
1587
+ x2 = self.aspp2(x)
1588
+ x3 = self.aspp3(x)
1589
+ x4 = self.aspp4(x)
1590
+ x5 = self.global_avg_pool(x)
1591
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1592
+ x = torch.cat((x1, x2, x3, x4, x5), dim=1)
1593
+
1594
+ x = self.conv1(x)
1595
+ x = self.bn1(x)
1596
+ x = self.relu(x)
1597
+
1598
+ return self.dropout(x)
1599
+
1600
+
1601
+ ##################### Deformable
1602
+ class _ASPPModuleDeformable(nn.Module):
1603
+ def __init__(self, in_channels, planes, kernel_size, padding):
1604
+ super(_ASPPModuleDeformable, self).__init__()
1605
+ self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size,
1606
+ stride=1, padding=padding, bias=False)
1607
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1608
+ self.relu = nn.ReLU(inplace=True)
1609
+
1610
+ def forward(self, x):
1611
+ x = self.atrous_conv(x)
1612
+ x = self.bn(x)
1613
+
1614
+ return self.relu(x)
1615
+
1616
+
1617
+ class ASPPDeformable(nn.Module):
1618
+ def __init__(self, in_channels, out_channels=None, parallel_block_sizes=[1, 3, 7]):
1619
+ super(ASPPDeformable, self).__init__()
1620
+ self.down_scale = 1
1621
+ if out_channels is None:
1622
+ out_channels = in_channels
1623
+ self.in_channelster = 256 // self.down_scale
1624
+
1625
+ self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0)
1626
+ self.aspp_deforms = nn.ModuleList([
1627
+ _ASPPModuleDeformable(in_channels, self.in_channelster, conv_size, padding=int(conv_size//2)) for conv_size in parallel_block_sizes
1628
+ ])
1629
+
1630
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1631
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1632
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1633
+ nn.ReLU(inplace=True))
1634
+ self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False)
1635
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1636
+ self.relu = nn.ReLU(inplace=True)
1637
+ self.dropout = nn.Dropout(0.5)
1638
+
1639
+ def forward(self, x):
1640
+ x1 = self.aspp1(x)
1641
+ x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms]
1642
+ x5 = self.global_avg_pool(x)
1643
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1644
+ x = torch.cat((x1, *x_aspp_deforms, x5), dim=1)
1645
+
1646
+ x = self.conv1(x)
1647
+ x = self.bn1(x)
1648
+ x = self.relu(x)
1649
+
1650
+ return self.dropout(x)
1651
+
1652
+
1653
+
1654
+ ### models/refinement/refiner.py
1655
+
1656
+ import torch
1657
+ import torch.nn as nn
1658
+ from collections import OrderedDict
1659
+ import torch
1660
+ import torch.nn as nn
1661
+ import torch.nn.functional as F
1662
+ from torchvision.models import vgg16, vgg16_bn
1663
+ from torchvision.models import resnet50
1664
+
1665
+ # from config import Config
1666
+ # from dataset import class_labels_TR_sorted
1667
+ # from models.build_backbone import build_backbone
1668
+ # from models.decoder_blocks import BasicDecBlk
1669
+ # from models.lateral_blocks import BasicLatBlk
1670
+ # from models.ing import *
1671
+ # from models.stem_layer import StemLayer
1672
+
1673
+
1674
+ class RefinerPVTInChannels4(nn.Module):
1675
+ def __init__(self, in_channels=3+1):
1676
+ super(RefinerPVTInChannels4, self).__init__()
1677
+ self.config = Config()
1678
+ self.epoch = 1
1679
+ self.bb = build_backbone(self.config.bb, params_settings='in_channels=4')
1680
+
1681
+ lateral_channels_in_collection = {
1682
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1683
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1684
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1685
+ }
1686
+ channels = lateral_channels_in_collection[self.config.bb]
1687
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1688
+
1689
+ self.decoder = Decoder(channels)
1690
+
1691
+ if 0:
1692
+ for key, value in self.named_parameters():
1693
+ if 'bb.' in key:
1694
+ value.requires_grad = False
1695
+
1696
+ def forward(self, x):
1697
+ if isinstance(x, list):
1698
+ x = torch.cat(x, dim=1)
1699
+ ########## Encoder ##########
1700
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1701
+ x1 = self.bb.conv1(x)
1702
+ x2 = self.bb.conv2(x1)
1703
+ x3 = self.bb.conv3(x2)
1704
+ x4 = self.bb.conv4(x3)
1705
+ else:
1706
+ x1, x2, x3, x4 = self.bb(x)
1707
+
1708
+ x4 = self.squeeze_module(x4)
1709
+
1710
+ ########## Decoder ##########
1711
+
1712
+ features = [x, x1, x2, x3, x4]
1713
+ scaled_preds = self.decoder(features)
1714
+
1715
+ return scaled_preds
1716
+
1717
+
1718
+ class Refiner(nn.Module):
1719
+ def __init__(self, in_channels=3+1):
1720
+ super(Refiner, self).__init__()
1721
+ self.config = Config()
1722
+ self.epoch = 1
1723
+ self.stem_layer = StemLayer(in_channels=in_channels, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
1724
+ self.bb = build_backbone(self.config.bb)
1725
+
1726
+ lateral_channels_in_collection = {
1727
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1728
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1729
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1730
+ }
1731
+ channels = lateral_channels_in_collection[self.config.bb]
1732
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1733
+
1734
+ self.decoder = Decoder(channels)
1735
+
1736
+ if 0:
1737
+ for key, value in self.named_parameters():
1738
+ if 'bb.' in key:
1739
+ value.requires_grad = False
1740
+
1741
+ def forward(self, x):
1742
+ if isinstance(x, list):
1743
+ x = torch.cat(x, dim=1)
1744
+ x = self.stem_layer(x)
1745
+ ########## Encoder ##########
1746
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1747
+ x1 = self.bb.conv1(x)
1748
+ x2 = self.bb.conv2(x1)
1749
+ x3 = self.bb.conv3(x2)
1750
+ x4 = self.bb.conv4(x3)
1751
+ else:
1752
+ x1, x2, x3, x4 = self.bb(x)
1753
+
1754
+ x4 = self.squeeze_module(x4)
1755
+
1756
+ ########## Decoder ##########
1757
+
1758
+ features = [x, x1, x2, x3, x4]
1759
+ scaled_preds = self.decoder(features)
1760
+
1761
+ return scaled_preds
1762
+
1763
+
1764
+ class Decoder(nn.Module):
1765
+ def __init__(self, channels):
1766
+ super(Decoder, self).__init__()
1767
+ self.config = Config()
1768
+ DecoderBlock = eval('BasicDecBlk')
1769
+ LateralBlock = eval('BasicLatBlk')
1770
+
1771
+ self.decoder_block4 = DecoderBlock(channels[0], channels[1])
1772
+ self.decoder_block3 = DecoderBlock(channels[1], channels[2])
1773
+ self.decoder_block2 = DecoderBlock(channels[2], channels[3])
1774
+ self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2)
1775
+
1776
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
1777
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
1778
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
1779
+
1780
+ if self.config.ms_supervision:
1781
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
1782
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
1783
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
1784
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0))
1785
+
1786
+ def forward(self, features):
1787
+ x, x1, x2, x3, x4 = features
1788
+ outs = []
1789
+ p4 = self.decoder_block4(x4)
1790
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
1791
+ _p3 = _p4 + self.lateral_block4(x3)
1792
+
1793
+ p3 = self.decoder_block3(_p3)
1794
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
1795
+ _p2 = _p3 + self.lateral_block3(x2)
1796
+
1797
+ p2 = self.decoder_block2(_p2)
1798
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
1799
+ _p1 = _p2 + self.lateral_block2(x1)
1800
+
1801
+ _p1 = self.decoder_block1(_p1)
1802
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
1803
+ p1_out = self.conv_out1(_p1)
1804
+
1805
+ if self.config.ms_supervision:
1806
+ outs.append(self.conv_ms_spvn_4(p4))
1807
+ outs.append(self.conv_ms_spvn_3(p3))
1808
+ outs.append(self.conv_ms_spvn_2(p2))
1809
+ outs.append(p1_out)
1810
+ return outs
1811
+
1812
+
1813
+ class RefUNet(nn.Module):
1814
+ # Refinement
1815
+ def __init__(self, in_channels=3+1):
1816
+ super(RefUNet, self).__init__()
1817
+ self.encoder_1 = nn.Sequential(
1818
+ nn.Conv2d(in_channels, 64, 3, 1, 1),
1819
+ nn.Conv2d(64, 64, 3, 1, 1),
1820
+ nn.BatchNorm2d(64),
1821
+ nn.ReLU(inplace=True)
1822
+ )
1823
+
1824
+ self.encoder_2 = nn.Sequential(
1825
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1826
+ nn.Conv2d(64, 64, 3, 1, 1),
1827
+ nn.BatchNorm2d(64),
1828
+ nn.ReLU(inplace=True)
1829
+ )
1830
+
1831
+ self.encoder_3 = nn.Sequential(
1832
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1833
+ nn.Conv2d(64, 64, 3, 1, 1),
1834
+ nn.BatchNorm2d(64),
1835
+ nn.ReLU(inplace=True)
1836
+ )
1837
+
1838
+ self.encoder_4 = nn.Sequential(
1839
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1840
+ nn.Conv2d(64, 64, 3, 1, 1),
1841
+ nn.BatchNorm2d(64),
1842
+ nn.ReLU(inplace=True)
1843
+ )
1844
+
1845
+ self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True)
1846
+ #####
1847
+ self.decoder_5 = nn.Sequential(
1848
+ nn.Conv2d(64, 64, 3, 1, 1),
1849
+ nn.BatchNorm2d(64),
1850
+ nn.ReLU(inplace=True)
1851
+ )
1852
+ #####
1853
+ self.decoder_4 = nn.Sequential(
1854
+ nn.Conv2d(128, 64, 3, 1, 1),
1855
+ nn.BatchNorm2d(64),
1856
+ nn.ReLU(inplace=True)
1857
+ )
1858
+
1859
+ self.decoder_3 = nn.Sequential(
1860
+ nn.Conv2d(128, 64, 3, 1, 1),
1861
+ nn.BatchNorm2d(64),
1862
+ nn.ReLU(inplace=True)
1863
+ )
1864
+
1865
+ self.decoder_2 = nn.Sequential(
1866
+ nn.Conv2d(128, 64, 3, 1, 1),
1867
+ nn.BatchNorm2d(64),
1868
+ nn.ReLU(inplace=True)
1869
+ )
1870
+
1871
+ self.decoder_1 = nn.Sequential(
1872
+ nn.Conv2d(128, 64, 3, 1, 1),
1873
+ nn.BatchNorm2d(64),
1874
+ nn.ReLU(inplace=True)
1875
+ )
1876
+
1877
+ self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1)
1878
+
1879
+ self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
1880
+
1881
+ def forward(self, x):
1882
+ outs = []
1883
+ if isinstance(x, list):
1884
+ x = torch.cat(x, dim=1)
1885
+ hx = x
1886
+
1887
+ hx1 = self.encoder_1(hx)
1888
+ hx2 = self.encoder_2(hx1)
1889
+ hx3 = self.encoder_3(hx2)
1890
+ hx4 = self.encoder_4(hx3)
1891
+
1892
+ hx = self.decoder_5(self.pool4(hx4))
1893
+ hx = torch.cat((self.upscore2(hx), hx4), 1)
1894
+
1895
+ d4 = self.decoder_4(hx)
1896
+ hx = torch.cat((self.upscore2(d4), hx3), 1)
1897
+
1898
+ d3 = self.decoder_3(hx)
1899
+ hx = torch.cat((self.upscore2(d3), hx2), 1)
1900
+
1901
+ d2 = self.decoder_2(hx)
1902
+ hx = torch.cat((self.upscore2(d2), hx1), 1)
1903
+
1904
+ d1 = self.decoder_1(hx)
1905
+
1906
+ x = self.conv_d0(d1)
1907
+ outs.append(x)
1908
+ return outs
1909
+
1910
+
1911
+
1912
+ ### models/stem_layer.py
1913
+
1914
+ import torch.nn as nn
1915
+ # from utils import build_act_layer, build_norm_layer
1916
+
1917
+
1918
+ class StemLayer(nn.Module):
1919
+ r""" Stem layer of InternImage
1920
+ Args:
1921
+ in_channels (int): number of input channels
1922
+ out_channels (int): number of output channels
1923
+ act_layer (str): activation layer
1924
+ norm_layer (str): normalization layer
1925
+ """
1926
+
1927
+ def __init__(self,
1928
+ in_channels=3+1,
1929
+ inter_channels=48,
1930
+ out_channels=96,
1931
+ act_layer='GELU',
1932
+ norm_layer='BN'):
1933
+ super().__init__()
1934
+ self.conv1 = nn.Conv2d(in_channels,
1935
+ inter_channels,
1936
+ kernel_size=3,
1937
+ stride=1,
1938
+ padding=1)
1939
+ self.norm1 = build_norm_layer(
1940
+ inter_channels, norm_layer, 'channels_first', 'channels_first'
1941
+ )
1942
+ self.act = build_act_layer(act_layer)
1943
+ self.conv2 = nn.Conv2d(inter_channels,
1944
+ out_channels,
1945
+ kernel_size=3,
1946
+ stride=1,
1947
+ padding=1)
1948
+ self.norm2 = build_norm_layer(
1949
+ out_channels, norm_layer, 'channels_first', 'channels_first'
1950
+ )
1951
+
1952
+ def forward(self, x):
1953
+ x = self.conv1(x)
1954
+ x = self.norm1(x)
1955
+ x = self.act(x)
1956
+ x = self.conv2(x)
1957
+ x = self.norm2(x)
1958
+ return x
1959
+
1960
+
1961
+ ### models/birefnet.py
1962
+
1963
+ import torch
1964
+ import torch.nn as nn
1965
+ import torch.nn.functional as F
1966
+ from kornia.filters import laplacian
1967
+ from transformers import PreTrainedModel
1968
+ from einops import rearrange
1969
+
1970
+ # from config import Config
1971
+ # from dataset import class_labels_TR_sorted
1972
+ # from models.build_backbone import build_backbone
1973
+ # from models.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk
1974
+ # from models.lateral_blocks import BasicLatBlk
1975
+ # from models.aspp import ASPP, ASPPDeformable
1976
+ # from models.ing import *
1977
+ # from models.refiner import Refiner, RefinerPVTInChannels4, RefUNet
1978
+ # from models.stem_layer import StemLayer
1979
+ from .BiRefNet_config import BiRefNetConfig
1980
+
1981
+
1982
+ def image2patches(image, grid_h=2, grid_w=2, patch_ref=None, transformation='b c (hg h) (wg w) -> (b hg wg) c h w'):
1983
+ if patch_ref is not None:
1984
+ grid_h, grid_w = image.shape[-2] // patch_ref.shape[-2], image.shape[-1] // patch_ref.shape[-1]
1985
+ patches = rearrange(image, transformation, hg=grid_h, wg=grid_w)
1986
+ return patches
1987
+
1988
+ def patches2image(patches, grid_h=2, grid_w=2, patch_ref=None, transformation='(b hg wg) c h w -> b c (hg h) (wg w)'):
1989
+ if patch_ref is not None:
1990
+ grid_h, grid_w = patch_ref.shape[-2] // patches[0].shape[-2], patch_ref.shape[-1] // patches[0].shape[-1]
1991
+ image = rearrange(patches, transformation, hg=grid_h, wg=grid_w)
1992
+ return image
1993
+
1994
+ class BiRefNet(
1995
+ PreTrainedModel
1996
+ ):
1997
+ config_class = BiRefNetConfig
1998
+ def __init__(self, bb_pretrained=True, config=BiRefNetConfig()):
1999
+ super(BiRefNet, self).__init__(config)
2000
+ bb_pretrained = config.bb_pretrained
2001
+ self.config = Config()
2002
+ self.epoch = 1
2003
+ self.bb = build_backbone(self.config.bb, pretrained=bb_pretrained)
2004
+
2005
+ channels = self.config.lateral_channels_in_collection
2006
+
2007
+ if self.config.auxiliary_classification:
2008
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
2009
+ self.cls_head = nn.Sequential(
2010
+ nn.Linear(channels[0], len(class_labels_TR_sorted))
2011
+ )
2012
+
2013
+ if self.config.squeeze_block:
2014
+ self.squeeze_module = nn.Sequential(*[
2015
+ eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0])
2016
+ for _ in range(eval(self.config.squeeze_block.split('_x')[1]))
2017
+ ])
2018
+
2019
+ self.decoder = Decoder(channels)
2020
+
2021
+ if self.config.ender:
2022
+ self.dec_end = nn.Sequential(
2023
+ nn.Conv2d(1, 16, 3, 1, 1),
2024
+ nn.Conv2d(16, 1, 3, 1, 1),
2025
+ nn.ReLU(inplace=True),
2026
+ )
2027
+
2028
+ # refine patch-level segmentation
2029
+ if self.config.refine:
2030
+ if self.config.refine == 'itself':
2031
+ self.stem_layer = StemLayer(in_channels=3+1, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
2032
+ else:
2033
+ self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1'))
2034
+
2035
+ if self.config.freeze_bb:
2036
+ # Freeze the backbone...
2037
+ print(self.named_parameters())
2038
+ for key, value in self.named_parameters():
2039
+ if 'bb.' in key and 'refiner.' not in key:
2040
+ value.requires_grad = False
2041
+
2042
+ def forward_enc(self, x):
2043
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
2044
+ x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3)
2045
+ else:
2046
+ x1, x2, x3, x4 = self.bb(x)
2047
+ if self.config.mul_scl_ipt == 'cat':
2048
+ B, C, H, W = x.shape
2049
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2050
+ x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2051
+ x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2052
+ x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2053
+ x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2054
+ elif self.config.mul_scl_ipt == 'add':
2055
+ B, C, H, W = x.shape
2056
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2057
+ x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)
2058
+ x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)
2059
+ x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)
2060
+ x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)
2061
+ class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None
2062
+ if self.config.cxt:
2063
+ x4 = torch.cat(
2064
+ (
2065
+ *[
2066
+ F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True),
2067
+ F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True),
2068
+ F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True),
2069
+ ][-len(self.config.cxt):],
2070
+ x4
2071
+ ),
2072
+ dim=1
2073
+ )
2074
+ return (x1, x2, x3, x4), class_preds
2075
+
2076
+ def forward_ori(self, x):
2077
+ ########## Encoder ##########
2078
+ (x1, x2, x3, x4), class_preds = self.forward_enc(x)
2079
+ if self.config.squeeze_block:
2080
+ x4 = self.squeeze_module(x4)
2081
+ ########## Decoder ##########
2082
+ features = [x, x1, x2, x3, x4]
2083
+ if self.training and self.config.out_ref:
2084
+ features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5))
2085
+ scaled_preds = self.decoder(features)
2086
+ return scaled_preds, class_preds
2087
+
2088
+ def forward(self, x):
2089
+ scaled_preds, class_preds = self.forward_ori(x)
2090
+ class_preds_lst = [class_preds]
2091
+ return [scaled_preds, class_preds_lst] if self.training else scaled_preds
2092
+
2093
+
2094
+ class Decoder(nn.Module):
2095
+ def __init__(self, channels):
2096
+ super(Decoder, self).__init__()
2097
+ self.config = Config()
2098
+ DecoderBlock = eval(self.config.dec_blk)
2099
+ LateralBlock = eval(self.config.lat_blk)
2100
+
2101
+ if self.config.dec_ipt:
2102
+ self.split = self.config.dec_ipt_split
2103
+ N_dec_ipt = 64
2104
+ DBlock = SimpleConvs
2105
+ ic = 64
2106
+ ipt_cha_opt = 1
2107
+ self.ipt_blk5 = DBlock(2**10*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2108
+ self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2109
+ self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic)
2110
+ self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic)
2111
+ self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic)
2112
+ else:
2113
+ self.split = None
2114
+
2115
+ self.decoder_block4 = DecoderBlock(channels[0]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[1])
2116
+ self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2])
2117
+ self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3])
2118
+ self.decoder_block1 = DecoderBlock(channels[3]+([N_dec_ipt, channels[2]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]//2)
2119
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2+([N_dec_ipt, channels[3]//8][ipt_cha_opt] if self.config.dec_ipt else 0), 1, 1, 1, 0))
2120
+
2121
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
2122
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
2123
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
2124
+
2125
+ if self.config.ms_supervision:
2126
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
2127
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
2128
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
2129
+
2130
+ if self.config.out_ref:
2131
+ _N = 16
2132
+ self.gdt_convs_4 = nn.Sequential(nn.Conv2d(channels[1], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2133
+ self.gdt_convs_3 = nn.Sequential(nn.Conv2d(channels[2], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2134
+ self.gdt_convs_2 = nn.Sequential(nn.Conv2d(channels[3], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2135
+
2136
+ self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2137
+ self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2138
+ self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2139
+
2140
+ self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2141
+ self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2142
+ self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2143
+
2144
+ def forward(self, features):
2145
+ if self.training and self.config.out_ref:
2146
+ outs_gdt_pred = []
2147
+ outs_gdt_label = []
2148
+ x, x1, x2, x3, x4, gdt_gt = features
2149
+ else:
2150
+ x, x1, x2, x3, x4 = features
2151
+ outs = []
2152
+
2153
+ if self.config.dec_ipt:
2154
+ patches_batch = image2patches(x, patch_ref=x4, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2155
+ x4 = torch.cat((x4, self.ipt_blk5(F.interpolate(patches_batch, size=x4.shape[2:], mode='bilinear', align_corners=True))), 1)
2156
+ p4 = self.decoder_block4(x4)
2157
+ m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision and self.training else None
2158
+ if self.config.out_ref:
2159
+ p4_gdt = self.gdt_convs_4(p4)
2160
+ if self.training:
2161
+ # >> GT:
2162
+ m4_dia = m4
2163
+ gdt_label_main_4 = gdt_gt * F.interpolate(m4_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2164
+ outs_gdt_label.append(gdt_label_main_4)
2165
+ # >> Pred:
2166
+ gdt_pred_4 = self.gdt_convs_pred_4(p4_gdt)
2167
+ outs_gdt_pred.append(gdt_pred_4)
2168
+ gdt_attn_4 = self.gdt_convs_attn_4(p4_gdt).sigmoid()
2169
+ # >> Finally:
2170
+ p4 = p4 * gdt_attn_4
2171
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
2172
+ _p3 = _p4 + self.lateral_block4(x3)
2173
+
2174
+ if self.config.dec_ipt:
2175
+ patches_batch = image2patches(x, patch_ref=_p3, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2176
+ _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1)
2177
+ p3 = self.decoder_block3(_p3)
2178
+ m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision and self.training else None
2179
+ if self.config.out_ref:
2180
+ p3_gdt = self.gdt_convs_3(p3)
2181
+ if self.training:
2182
+ # >> GT:
2183
+ # m3 --dilation--> m3_dia
2184
+ # G_3^gt * m3_dia --> G_3^m, which is the label of gradient
2185
+ m3_dia = m3
2186
+ gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2187
+ outs_gdt_label.append(gdt_label_main_3)
2188
+ # >> Pred:
2189
+ # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx
2190
+ # F_3^G --sigmoid--> A_3^G
2191
+ gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt)
2192
+ outs_gdt_pred.append(gdt_pred_3)
2193
+ gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid()
2194
+ # >> Finally:
2195
+ # p3 = p3 * A_3^G
2196
+ p3 = p3 * gdt_attn_3
2197
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
2198
+ _p2 = _p3 + self.lateral_block3(x2)
2199
+
2200
+ if self.config.dec_ipt:
2201
+ patches_batch = image2patches(x, patch_ref=_p2, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2202
+ _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1)
2203
+ p2 = self.decoder_block2(_p2)
2204
+ m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision and self.training else None
2205
+ if self.config.out_ref:
2206
+ p2_gdt = self.gdt_convs_2(p2)
2207
+ if self.training:
2208
+ # >> GT:
2209
+ m2_dia = m2
2210
+ gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2211
+ outs_gdt_label.append(gdt_label_main_2)
2212
+ # >> Pred:
2213
+ gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt)
2214
+ outs_gdt_pred.append(gdt_pred_2)
2215
+ gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid()
2216
+ # >> Finally:
2217
+ p2 = p2 * gdt_attn_2
2218
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
2219
+ _p1 = _p2 + self.lateral_block2(x1)
2220
+
2221
+ if self.config.dec_ipt:
2222
+ patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2223
+ _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1)
2224
+ _p1 = self.decoder_block1(_p1)
2225
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
2226
+
2227
+ if self.config.dec_ipt:
2228
+ patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2229
+ _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1)
2230
+ p1_out = self.conv_out1(_p1)
2231
+
2232
+ if self.config.ms_supervision and self.training:
2233
+ outs.append(m4)
2234
+ outs.append(m3)
2235
+ outs.append(m2)
2236
+ outs.append(p1_out)
2237
+ return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs)
2238
+
2239
+
2240
+ class SimpleConvs(nn.Module):
2241
+ def __init__(
2242
+ self, in_channels: int, out_channels: int, inter_channels=64
2243
+ ) -> None:
2244
+ super().__init__()
2245
+ self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1)
2246
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)
2247
+
2248
+ def forward(self, x):
2249
+ return self.conv_out(self.conv1(x))
SKING_DDJ_v101c/infer.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Portable launcher for the sanitized SKING_DDJ_v101c inference bundle."""
2
+ import argparse
3
+ import hashlib
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import runpy
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+
13
+ ROOT = Path(__file__).resolve().parent
14
+
15
+
16
+ def sha(path):
17
+ digest = hashlib.sha256()
18
+ with Path(path).open("rb") as stream:
19
+ for block in iter(lambda: stream.read(4 * 1024 * 1024), b""):
20
+ digest.update(block)
21
+ return digest.hexdigest()
22
+
23
+
24
+ def verify():
25
+ release = json.loads((ROOT / "release.json").read_text())
26
+ if (
27
+ release["format"] != "sking-hf-bundle-v1"
28
+ or release["model_version"] != "SKING_DDJ_v101c"
29
+ ):
30
+ raise ValueError("Wrong release identity")
31
+ for name, expected in release["sha256"].items():
32
+ path = (ROOT / name).resolve()
33
+ if not path.is_relative_to(ROOT) or sha(path) != expected:
34
+ raise ValueError("Release integrity failure: " + name)
35
+ return release
36
+
37
+
38
+ def parser_stage(options):
39
+ sys.path.insert(0, str(ROOT / "runtime/dense_uv_parser"))
40
+ from run_local import bind_checkout
41
+
42
+ bind_checkout()
43
+ import SkingToolkit.dense_uv_parser.infer as parser_module
44
+
45
+ original = parser_module.load_parser
46
+
47
+ def load_portable(*args, **kwargs):
48
+ model, config = original(*args, **kwargs)
49
+ config = dict(config)
50
+ config["mappings_dir"] = str(ROOT / "mappings_256x512")
51
+ return model, config
52
+
53
+ parser_module.load_parser = load_portable
54
+ sys.argv = [
55
+ "batch_accessories",
56
+ "--checkpoint",
57
+ str(ROOT / "parser.pt"),
58
+ "--pipeline",
59
+ str(ROOT / "pipeline.json"),
60
+ "--output-dir",
61
+ str(options.output),
62
+ "--foreground-probabilities",
63
+ str(options.probability),
64
+ "--inputs",
65
+ str(options.input),
66
+ ]
67
+ runpy.run_module(
68
+ "SkingToolkit.dense_uv_parser.batch_accessories", run_name="__main__"
69
+ )
70
+
71
+
72
+ def main():
73
+ parser = argparse.ArgumentParser(description=__doc__)
74
+ parser.add_argument("--input", type=Path, help="Square combined front/back edited render")
75
+ parser.add_argument("--output", type=Path, help="Output 64x64 RGBA PNG")
76
+ parser.add_argument("--parser-python", default=sys.executable)
77
+ parser.add_argument("--foreground-python", default=sys.executable)
78
+ parser.add_argument("--verify-only", action="store_true")
79
+ parser.add_argument("--parser-stage", action="store_true", help=argparse.SUPPRESS)
80
+ parser.add_argument("--probability", type=Path, help=argparse.SUPPRESS)
81
+ options = parser.parse_args()
82
+ os.environ.update(
83
+ HF_HUB_OFFLINE="1",
84
+ HF_HOME=str(ROOT / "hf_cache"),
85
+ HF_HUB_CACHE=str(ROOT / "hf_cache/hub"),
86
+ HF_HUB_DISABLE_PROGRESS_BARS="1",
87
+ PYTHONDONTWRITEBYTECODE="1",
88
+ OMP_NUM_THREADS="4",
89
+ MKL_NUM_THREADS="4",
90
+ CUBLAS_WORKSPACE_CONFIG=":4096:8",
91
+ )
92
+ if options.parser_stage:
93
+ parser_stage(options)
94
+ return
95
+ release = verify()
96
+ if options.verify_only:
97
+ print(
98
+ json.dumps(
99
+ {
100
+ "verified_files": len(release["sha256"]),
101
+ "model_version": release["model_version"],
102
+ }
103
+ )
104
+ )
105
+ return
106
+ if options.input is None or options.output is None:
107
+ parser.error("--input and --output are required for inference")
108
+ options.input = options.input.resolve()
109
+ options.output = options.output.resolve()
110
+ if options.input == options.output:
111
+ parser.error("Input and output must be different files")
112
+ from PIL import Image
113
+
114
+ with Image.open(options.input) as source:
115
+ width, height = source.size
116
+ if width != height or width < 256 or width > 4096 or width % 2:
117
+ raise ValueError("Expected an even square combined render, 256 to 4096 pixels")
118
+ source.verify()
119
+ options.output.parent.mkdir(parents=True, exist_ok=True)
120
+ with tempfile.TemporaryDirectory(prefix="sking-v101c-") as directory:
121
+ work = Path(directory)
122
+ source_path = work / "input.png"
123
+ shutil.copyfile(options.input, source_path)
124
+ index = work / "foreground.json"
125
+ entry = ROOT / "runtime/dense_uv_parser/run_local.py"
126
+ subprocess.run(
127
+ [
128
+ options.foreground_python,
129
+ str(entry),
130
+ "foreground_provider",
131
+ "--checkpoint",
132
+ str(ROOT / "foreground.pt"),
133
+ "--model-dir",
134
+ str(ROOT / "foreground_base"),
135
+ "--output-dir",
136
+ str(work / "foreground"),
137
+ "--result-manifest",
138
+ str(index),
139
+ "--inputs",
140
+ str(source_path),
141
+ ],
142
+ check=True,
143
+ cwd=ROOT / "runtime",
144
+ )
145
+ probabilities = json.loads(index.read_text())["probabilities"]
146
+ if len(probabilities) != 1:
147
+ raise RuntimeError("Foreground stage did not return one result")
148
+ subprocess.run(
149
+ [
150
+ options.parser_python,
151
+ str(Path(__file__).resolve()),
152
+ "--parser-stage",
153
+ "--input",
154
+ str(source_path),
155
+ "--output",
156
+ str(work / "uv"),
157
+ "--probability",
158
+ probabilities[0],
159
+ ],
160
+ check=True,
161
+ cwd=ROOT / "runtime",
162
+ )
163
+ outputs = list((work / "uv").glob("*/manifest.json"))
164
+ if len(outputs) != 1:
165
+ raise RuntimeError("Parser did not return one result")
166
+ manifest = json.loads(outputs[0].read_text())
167
+ expected_sources = {
168
+ Path(name).name: digest
169
+ for name, digest in release["sha256"].items()
170
+ if Path(name).parent == Path("runtime/dense_uv_parser")
171
+ and name.endswith(".py")
172
+ }
173
+ if (
174
+ manifest.get("complete") is not True
175
+ or manifest.get("input_sha256") != sha(source_path)
176
+ or manifest.get("checkpoint_sha256") != release["sha256"]["parser.pt"]
177
+ or manifest.get("pipeline")
178
+ != json.loads((ROOT / "pipeline.json").read_text())
179
+ or manifest.get("source_sha256") != expected_sources
180
+ or manifest.get("foreground_provider", {}).get("adaptation_sha256")
181
+ != release["sha256"]["foreground.pt"]
182
+ or manifest.get("foreground_provider", {}).get("model_sha256")
183
+ != release["sha256"]["foreground_base/model.safetensors"]
184
+ ):
185
+ raise RuntimeError("Output provenance does not match this release")
186
+ result = outputs[0].parent / "pred_uv.png"
187
+ with Image.open(result) as uv:
188
+ if uv.size != (64, 64) or uv.mode != "RGBA" or not uv.getchannel("A").getbbox():
189
+ raise RuntimeError("Invalid UV output")
190
+ with tempfile.NamedTemporaryFile(
191
+ dir=options.output.parent,
192
+ prefix=".sking-v101c-",
193
+ suffix=".png",
194
+ delete=False,
195
+ ) as stream:
196
+ temporary = Path(stream.name)
197
+ stream.write(result.read_bytes())
198
+ try:
199
+ os.replace(temporary, options.output)
200
+ finally:
201
+ temporary.unlink(missing_ok=True)
202
+ print(
203
+ json.dumps(
204
+ {
205
+ "model_version": "SKING_DDJ_v101c",
206
+ "output": str(options.output),
207
+ "sha256": sha(options.output),
208
+ }
209
+ )
210
+ )
211
+
212
+
213
+ if __name__ == "__main__":
214
+ main()
SKING_DDJ_v101c/licenses/BiRefNet_LICENSE.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 ZhengPeng
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
SKING_DDJ_v101c/licenses/SigLIP2_LICENSE.txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
SKING_DDJ_v101c/licenses/sources.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "file": "BiRefNet_LICENSE.txt",
4
+ "url": "https://raw.githubusercontent.com/ZhengPeng7/BiRefNet/main/LICENSE",
5
+ "sha256": "92a7089e0915fc32bc40067560b398f1e6a7a5958abd7d04eda393629a5acefb",
6
+ "bytes": 1066
7
+ },
8
+ {
9
+ "file": "SigLIP2_LICENSE.txt",
10
+ "url": "https://raw.githubusercontent.com/google-research/big_vision/main/LICENSE",
11
+ "sha256": "43070e2d4e532684de521b885f385d0841030efa2b1a20bafb76133a5e1379c1",
12
+ "bytes": 11356
13
+ }
14
+ ]
SKING_DDJ_v101c/mappings_256x512/back_left_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4966dc30a35f7884dad1f37d4cf2b14bcf8fdfdbe34f3dbbec1ed2ebd31f9308
3
+ size 18878693
SKING_DDJ_v101c/mappings_256x512/back_left_overlay_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:66796f7e6f321f9bd1739fbd9f2110c6477d814cf9a98f968190a255b2e128e7
3
+ size 13373861
SKING_DDJ_v101c/mappings_256x512/back_right_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3baa16ca38e7b62f38d04c29746c72c5a3c05ca054d72300cda2c08b2645c4c8
3
+ size 18878709
SKING_DDJ_v101c/mappings_256x512/back_right_overlay_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:63e7dde6cfb22edebe4b45b1ebecaa9ee5679aca1be022e26fabdfc922c84fb8
3
+ size 13373877
SKING_DDJ_v101c/mappings_256x512/front_left_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f09e38516ed10a81c86939119d776353d795554093c699b10d89741ea78dce7f
3
+ size 18878709
SKING_DDJ_v101c/mappings_256x512/front_left_overlay_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56db06fe4bf215e06b6f9e8a7b81747e4e24483d770619660b26f555e5402f97
3
+ size 13373877
SKING_DDJ_v101c/mappings_256x512/front_right_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d9f32bdcbbd98ea6f75aaacc966d6553582d676c06154003dde1559d3f92f1f5
3
+ size 18878725
SKING_DDJ_v101c/mappings_256x512/front_right_overlay_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:138481fd6da1746f21dd90bb42f432a532fa79d73d60515d4558bda2cf56365d
3
+ size 13373893
SKING_DDJ_v101c/mappings_256x512/static_back_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14213de89eaac720fd83892033c5e42301e682ad37c678dd723619bf10982ca2
3
+ size 18878725
SKING_DDJ_v101c/mappings_256x512/static_front_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d42e32902fedb9af2bd0f34ae50d18107c3d2264e519beb3b4eb8619d8a0f703
3
+ size 18878741
SKING_DDJ_v101c/mappings_256x512/walk_back_base_layer_ortho_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9fdc06695caada150b071bc0632fb83a8fed04c6ae1135b25c9519077eddfdca
3
+ size 13374005
SKING_DDJ_v101c/mappings_256x512/walk_back_both_layer_ortho_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9dfe71bab556365f9e4a33c2eca9d1905806b4278d422adfcf58cb6678b65853
3
+ size 21501093
SKING_DDJ_v101c/mappings_256x512/walk_front_base_layer_ortho_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c406299c5bab60cc4b8d7afa59f833a41a693ba7b2efa7a819ee2828e4f4008b
3
+ size 13374021
SKING_DDJ_v101c/mappings_256x512/walk_front_both_layer_ortho_mapping.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84ad02344ba9777c18d0ec41004d6fed5211b8a1e5cffd62dcac43ba7e4f3148
3
+ size 21501111
SKING_DDJ_v101c/parser.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea3bd7d0e0d2eeb73d0bea68233412bf74ddc5ae8ddfb9a3a6957c381f1b2540
3
+ size 31771763
SKING_DDJ_v101c/pipeline.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "foreground_flood_tolerance": 0.09,
3
+ "foreground_background": "adaptive",
4
+ "routing": {
5
+ "views": [
6
+ "front_left",
7
+ "back_left"
8
+ ],
9
+ "group_size": 2,
10
+ "fg_threshold": 0.5,
11
+ "bg_color": [
12
+ 128,
13
+ 128,
14
+ 128
15
+ ],
16
+ "semantic_gate": true,
17
+ "affine_refine": false,
18
+ "affine_refine_translation_px": 0.0,
19
+ "affine_refine_scale": 0.0,
20
+ "route_confidence_threshold": 0.0,
21
+ "route_margin_threshold": 0.0,
22
+ "outer_route_confidence_threshold": 0.8,
23
+ "outer_route_margin_threshold": 0.55,
24
+ "outer_uv_min_coverage": 0.25,
25
+ "outer_uv_min_source_pixels": 30,
26
+ "outer_silhouette_consistency": true,
27
+ "outer_silhouette_min_coverage": 0.5,
28
+ "outer_silhouette_dilation": 0,
29
+ "outer_silhouette_min_pixels": 4,
30
+ "outer_geometry_rescue": true,
31
+ "outer_semantic_rescue": true,
32
+ "outer_semantic_presence_threshold": 0.8,
33
+ "outer_semantic_coverage_threshold": 0.2,
34
+ "outer_rescue_confidence_threshold": 0.6,
35
+ "outer_rescue_margin_threshold": 0.25,
36
+ "outer_rescue_min_coverage": 0.1,
37
+ "color_aggregation": "grid_mode",
38
+ "geometry_route_texel_consensus": true,
39
+ "geometry_route_texel_consensus_weight": 0.6,
40
+ "geometry_route_preserve_outer_confidence": 0.8,
41
+ "geometry_route_preserve_outer_margin": 0.35,
42
+ "geometry_route_consensus_outer_confidence": 0.7,
43
+ "geometry_route_consensus_outer_margin": 0.2,
44
+ "geometry_cross_view_outer_consistency": false,
45
+ "geometry_cross_view_outer_weight": 0.5,
46
+ "geometry_cross_view_outer_positive_confidence": 0.7,
47
+ "geometry_cross_view_outer_positive_margin": 0.2,
48
+ "geometry_cross_view_outer_negative_confidence": 0.7,
49
+ "geometry_cross_view_outer_negative_margin": 0.2,
50
+ "geometry_cross_view_outer_background_max_coverage": 0.25,
51
+ "geometry_cross_view_outer_min_views": 2,
52
+ "outer_uv_occupancy": false,
53
+ "outer_uv_occupancy_blend_weight": 0.0,
54
+ "outer_uv_occupancy_gate_threshold": 0.15,
55
+ "outer_uv_occupancy_rescue_threshold": 0.7,
56
+ "outer_uv_occupancy_rescue_route_threshold": 0.3,
57
+ "outer_uv_component_routing": false,
58
+ "outer_uv_component_seed_threshold": 0.8,
59
+ "outer_uv_component_grow_threshold": 0.5,
60
+ "outer_uv_component_min_size": 2,
61
+ "background_color_tolerance": 0.25,
62
+ "color_background_tolerance": 0.031372549,
63
+ "color_foreground_inset": 1,
64
+ "reject_semantic_fallback": true,
65
+ "include_rejected_context": false,
66
+ "include_confidence": false,
67
+ "head_color_separation_inset": 2
68
+ },
69
+ "accessory_route_threshold": 0.9,
70
+ "synthetic_alpha_foreground": true,
71
+ "head_material_refine_steps": 48,
72
+ "head_material_refine_mode": "isolated",
73
+ "headphone_routing_mode": "existing_uv",
74
+ "headphone_presence_threshold": 0.99,
75
+ "headphone_presence_consensus": true,
76
+ "head_semantic_inpaint": true,
77
+ "headwear_presence_threshold": 0.95,
78
+ "crown_top_geometry_mode": "rendered_semantics"
79
+ }
SKING_DDJ_v101c/release.json ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format": "sking-hf-bundle-v1",
3
+ "model_version": "SKING_DDJ_v101c",
4
+ "original_version": "v101",
5
+ "original_revision": "crown_geometry_20260906",
6
+ "source_code_commit": "28f548a5be37868022cfbafaddbe095895e18210",
7
+ "production_artifacts": {
8
+ "parser_sha256": "a8aa3d8cd51cc6fec28d7c525aa1b012976d7cb1206e8b00c707de76bfb205dc",
9
+ "foreground_sha256": "8585a698d38969e6e7562e9c7d8c5f0b5e934e8f0811cf5b8678fcf05734e732",
10
+ "pipeline_sha256": "3e14b98437eba9c5189a3344f560e7183f8daad44b9c40c55e15f7e0fda27685"
11
+ },
12
+ "sanitization": {
13
+ "pipeline_fields_removed": [
14
+ "foreground_cache",
15
+ "foreground_release",
16
+ "hat_development"
17
+ ],
18
+ "private_paths_removed": true,
19
+ "optimizer_states_removed": true,
20
+ "user_and_regression_images_excluded": true,
21
+ "parser_tensor_count": 386,
22
+ "foreground_tensor_count": 397,
23
+ "parser_metadata_paths_removed": 1,
24
+ "foreground_metadata_paths_removed": 3,
25
+ "optimizer_state_removed": {
26
+ "parser": false,
27
+ "foreground": true
28
+ },
29
+ "excluded_private_tests": [
30
+ "test_accessories.py",
31
+ "test_affine_routing.py",
32
+ "test_crown_geometry.py",
33
+ "test_foreground.py",
34
+ "test_headwear.py",
35
+ "test_matting_data.py",
36
+ "test_ownership.py",
37
+ "test_semantic_generalization.py",
38
+ "test_semantic_parser.py"
39
+ ],
40
+ "portable_path_adjustments": [
41
+ "batch_accessories.py",
42
+ "foreground_batch.py",
43
+ "released_inference.py"
44
+ ]
45
+ },
46
+ "validation": {
47
+ "historical_samples": 8,
48
+ "alpha_exact": 8,
49
+ "visible_rgb_max": 1,
50
+ "deployment_regression_samples": 6
51
+ },
52
+ "sha256": {
53
+ "LICENSE": "8486a10c4393cee1c25392769ddd3b2d6c242d6ec7928e1414efff7dfb2f07ef",
54
+ "README.md": "342c7e13ea8a7cad51d77bf999074168ea99db7a48e2c4cc6b7b78e80b362667",
55
+ "THIRD_PARTY_NOTICES.md": "58533726d4b29528a102039a8d1c6d42cf6c7b07b42dd9b026cf418348fc14af",
56
+ "foreground.pt": "f00c1abbf736d54fcda6800ec6046817456ef9fbc45bb67bc1e6d759cfb45331",
57
+ "foreground_base/BiRefNet_config.py": "e7b8c2a74f6cea6a59553d517f71d47f2c1d90e670a13416af17c25fe2f3dc52",
58
+ "foreground_base/birefnet.py": "a9566611aa07a6fbb68ddb6ac8e19e62c879a428fbfc2f44efa53d233f2e302f",
59
+ "foreground_base/config.json": "c97ea21569daf66b205491a4635147dd3bc42c7c168b89d7d75b53f67ef548ae",
60
+ "foreground_base/model.safetensors": "9ab37426bf4de0567af6b5d21b16151357149139362e6e8992021b8ce356a154",
61
+ "hf_cache/hub/models--google--siglip2-base-patch16-224/refs/main": "5adaedd88ee9835df44ae379db76ca2e0a84427d427f05d9b268f5556b02ff97",
62
+ "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/config.json": "fe8b5fe6d5734360678fd71c11c21e1ea3364bd8598d34295d9206335973ffd7",
63
+ "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/model.safetensors": "612923381c76ec5a9bed335d1c48827e3f2e506ac31b044b63b2031fadee6a0b",
64
+ "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/preprocessor_config.json": "9b36b57ebaf20f09bf4c22100ccc21877ea6bfe5aead0c00c59f8af8ccefacfc",
65
+ "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/special_tokens_map.json": "baec30ea10906f16adb8c18af7a34023002c1746542612b8b41c9f09e1351351",
66
+ "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.json": "cb9140fae3ac5122c972d37adf83e1248471a38147ad76f8215c8872c6fd8322",
67
+ "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.model": "61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2",
68
+ "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer_config.json": "14afe629fe4959b9e0d51e1852b8d9f7ad074f90a1a7125a4fcdd17f06e78fc8",
69
+ "hf_cache/modules/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
70
+ "hf_cache/modules/transformers_modules/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
71
+ "hf_cache/modules/transformers_modules/foreground_base/BiRefNet_config.py": "e7b8c2a74f6cea6a59553d517f71d47f2c1d90e670a13416af17c25fe2f3dc52",
72
+ "hf_cache/modules/transformers_modules/foreground_base/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
73
+ "hf_cache/modules/transformers_modules/foreground_base/birefnet.py": "a9566611aa07a6fbb68ddb6ac8e19e62c879a428fbfc2f44efa53d233f2e302f",
74
+ "infer.py": "4454b60fe21440cd8036cb7fdac54063d4b82a1636347c650475a59dcda45c29",
75
+ "licenses/BiRefNet_LICENSE.txt": "92a7089e0915fc32bc40067560b398f1e6a7a5958abd7d04eda393629a5acefb",
76
+ "licenses/SigLIP2_LICENSE.txt": "43070e2d4e532684de521b885f385d0841030efa2b1a20bafb76133a5e1379c1",
77
+ "licenses/sources.json": "61b376b10e8f5d18d7d99c0cb9db89f761e60d1b2ad5333b8408502d535c4218",
78
+ "mappings_256x512/back_left_mapping.pt": "4966dc30a35f7884dad1f37d4cf2b14bcf8fdfdbe34f3dbbec1ed2ebd31f9308",
79
+ "mappings_256x512/back_left_overlay_mapping.pt": "66796f7e6f321f9bd1739fbd9f2110c6477d814cf9a98f968190a255b2e128e7",
80
+ "mappings_256x512/back_right_mapping.pt": "3baa16ca38e7b62f38d04c29746c72c5a3c05ca054d72300cda2c08b2645c4c8",
81
+ "mappings_256x512/back_right_overlay_mapping.pt": "63e7dde6cfb22edebe4b45b1ebecaa9ee5679aca1be022e26fabdfc922c84fb8",
82
+ "mappings_256x512/front_left_mapping.pt": "f09e38516ed10a81c86939119d776353d795554093c699b10d89741ea78dce7f",
83
+ "mappings_256x512/front_left_overlay_mapping.pt": "56db06fe4bf215e06b6f9e8a7b81747e4e24483d770619660b26f555e5402f97",
84
+ "mappings_256x512/front_right_mapping.pt": "d9f32bdcbbd98ea6f75aaacc966d6553582d676c06154003dde1559d3f92f1f5",
85
+ "mappings_256x512/front_right_overlay_mapping.pt": "138481fd6da1746f21dd90bb42f432a532fa79d73d60515d4558bda2cf56365d",
86
+ "mappings_256x512/static_back_mapping.pt": "14213de89eaac720fd83892033c5e42301e682ad37c678dd723619bf10982ca2",
87
+ "mappings_256x512/static_front_mapping.pt": "d42e32902fedb9af2bd0f34ae50d18107c3d2264e519beb3b4eb8619d8a0f703",
88
+ "mappings_256x512/walk_back_base_layer_ortho_mapping.pt": "9fdc06695caada150b071bc0632fb83a8fed04c6ae1135b25c9519077eddfdca",
89
+ "mappings_256x512/walk_back_both_layer_ortho_mapping.pt": "9dfe71bab556365f9e4a33c2eca9d1905806b4278d422adfcf58cb6678b65853",
90
+ "mappings_256x512/walk_front_base_layer_ortho_mapping.pt": "c406299c5bab60cc4b8d7afa59f833a41a693ba7b2efa7a819ee2828e4f4008b",
91
+ "mappings_256x512/walk_front_both_layer_ortho_mapping.pt": "84ad02344ba9777c18d0ec41004d6fed5211b8a1e5cffd62dcac43ba7e4f3148",
92
+ "parser.pt": "ea3bd7d0e0d2eeb73d0bea68233412bf74ddc5ae8ddfb9a3a6957c381f1b2540",
93
+ "pipeline.json": "b3ecdcc8400621c21d3d03af249ffa8968b019184b1e82f478581b97ba49a394",
94
+ "runtime/LICENSE": "8486a10c4393cee1c25392769ddd3b2d6c242d6ec7928e1414efff7dfb2f07ef",
95
+ "runtime/dense_uv_parser/__init__.py": "044e6ec3019c5cf9175ddb7a5df3083630a491d01864837ee6139b01600c2ceb",
96
+ "runtime/dense_uv_parser/accessories.py": "5e1787c41640196e94b7a99576d269408f56c80406577cfd0b1afe23ccd8d014",
97
+ "runtime/dense_uv_parser/accessory_data.py": "7989807a1771b00df4d80cab9a7f3a0e80a8aa24546c729a9627919ffbab0728",
98
+ "runtime/dense_uv_parser/accessory_pipeline.py": "66f8927b310aed4b1dae1eedfb01c1493f8aa7f7bf25e646b662bbe3f40d7ca1",
99
+ "runtime/dense_uv_parser/accessory_regression.py": "9fa90be8bd6f3ba50438ec7abc394824a300270fa9dcdf3ad55968a5be73a238",
100
+ "runtime/dense_uv_parser/batch_accessories.py": "9800436d24e06e3856abf4e2325546c11ba2b5b97b55099693b3d77d088ae694",
101
+ "runtime/dense_uv_parser/cache_semantic_features.py": "9c439ba5a95c5a3f55c8114975872c4ad0eb38087f44f5d2f82e41d07b4a0961",
102
+ "runtime/dense_uv_parser/crown_geometry.py": "608a28c8223cb0ffb0882c3ff183b9a44a3f6d2987b660517548ca657cfca14a",
103
+ "runtime/dense_uv_parser/foreground.py": "6d488ef64135fd57cc661bcab531748bc242b4034b07b748bf61d34deba61db6",
104
+ "runtime/dense_uv_parser/foreground_acceptance.py": "d9c6b9367cc0a4333fe08832bf558a1738a0e533dab257a3be0a181481dfb2ed",
105
+ "runtime/dense_uv_parser/foreground_batch.py": "7d7917b61a3dd13a08a5afb181a9c43ad6d8973fb1e485d9503fe79d950730e4",
106
+ "runtime/dense_uv_parser/foreground_model.py": "96b1cf0a4944df39d3cb1e3c0cf490508e65306b8b2428fc64fdd6974ffb978a",
107
+ "runtime/dense_uv_parser/foreground_provider.py": "1970ad563d3e8aeb7df5e84fc5f4264353d4ceca80f362a13fba75f5cdbeaa5e",
108
+ "runtime/dense_uv_parser/head_inpainting.py": "076c8844db555f168599e06a77efa4ae4da48b9d34860a3a2cfdf1da3ccc0638",
109
+ "runtime/dense_uv_parser/headwear.py": "0e553177b9214fe6252df3dc9a0ae351c605c7d8127b1de976a04dda4ee5f09d",
110
+ "runtime/dense_uv_parser/headwear_data.py": "114f904bd0743206223cf98b71bb027513c2e81c62a1ca0540d5af441384a915",
111
+ "runtime/dense_uv_parser/infer.py": "819d6c78b4065b1835a5c39c152b2014adfabf7dfb0180e151b434293d1ae678",
112
+ "runtime/dense_uv_parser/losses.py": "87de937f9087284de4a84ce555229c5995ed582d91af99685a2861bc6e8b66f6",
113
+ "runtime/dense_uv_parser/material_refine.py": "c236307c541798ef7e232107a9da7d95b95866584c645551477bbce45eca7e18",
114
+ "runtime/dense_uv_parser/matting_data.py": "107db91d98bca7a02c7501b648860e75faf7ef32a89919f4cbcd107c479d0429",
115
+ "runtime/dense_uv_parser/model.py": "9729d3c97aa4c593e3891609f467563b037bf8dbc9dce597346b5b09bbc5b885",
116
+ "runtime/dense_uv_parser/ownership.py": "1f414be584390f0f853423f47af85cf0a5b6a40c1c4503a0e0b76557e70f1ee8",
117
+ "runtime/dense_uv_parser/ownership_data.py": "d4ff687cbbba2634aca13f4a9c02db8cf0479b3b2a1bcdc40e9bc501676c6ef1",
118
+ "runtime/dense_uv_parser/prepare_foreground_data.py": "13c03bc989b1c89bf2446147b6dd5ef6d0a72bde7e3f903045ef4c7e825c2e91",
119
+ "runtime/dense_uv_parser/released_inference.py": "3ca2f766ee6d89788973ef9d116b3b406e2e3556827efaef224d46e71b47cc48",
120
+ "runtime/dense_uv_parser/run_local.py": "40c63041f212656f50c0a2e45524e14a2bc09b12b41adb0a0300121e0dd1a039",
121
+ "runtime/dense_uv_parser/runtime.py": "c374381063f7f559dc9e2a384982b411c4eb0f5160c0bf0e40f53e4286a15d83",
122
+ "runtime/dense_uv_parser/semantic.py": "7d390f827e423d4e97ec9e20e39604c5a4801d97b1796b036016bae55c755249",
123
+ "runtime/dense_uv_parser/semantic_backbone.py": "1008138e58f4bc665930d786dc68b6bb44b91bef69bcc71b8d41e252957bc273",
124
+ "runtime/dense_uv_parser/semantic_cache.py": "057629ce8aafbf60b379fef487a8a0ba33a2fe7e24a4e11b71ebdb3084489d40",
125
+ "runtime/dense_uv_parser/semantic_generalization.py": "c8266c0ffd3a2e07cc1ed42ce62de69d80440c3bbba69b466d1121260d200c0e",
126
+ "runtime/dense_uv_parser/semantic_targets.py": "f5e8dd1c7fb53847c5645b8f1cc03fc4594805de6b7d0bf482f223956a5c2008",
127
+ "runtime/dense_uv_parser/simple_inpainting.py": "00359b7d9217ccf7b86f2684caee8a464d6142d35b930b464e0e963a74b750ff",
128
+ "runtime/dense_uv_parser/skin_dataset.py": "67af52006b15b86c82dc10297ee3e78bc9e634ea20515202c46a6dcb29bb4887",
129
+ "runtime/dense_uv_parser/train.py": "76343eb77af5b67d6baefdb80e14cf097da847bb536d47f833f4cc0963ec9233",
130
+ "runtime/dense_uv_parser/train_accessories.py": "37de0c34887a4da47f63d7611a5f12a25c45f45e5eea21c6483f5e7b5f4a2a43",
131
+ "runtime/dense_uv_parser/train_foreground.py": "6830de93089ef19d5f0e9171bbba19d8ec7dc53d488fd95f0c5346d67883f6f6",
132
+ "runtime/dense_uv_parser/train_headphone_presence.py": "b95332c38bce2af876987342b9a3b42fc587722a2531d9a9f3c4f6d0bc6fdc61",
133
+ "runtime/dense_uv_parser/train_headwear.py": "61042a2373cecddcc623f42418778b041c481442cc45da098e2c5b27175b8ac1",
134
+ "runtime/dense_uv_parser/train_headwear_presence.py": "32249430cf1333e54f1d6915fad32976108ffa720e5ae9f79cd6c571bd2736ac",
135
+ "runtime/dense_uv_parser/train_ownership.py": "6d06464752fcf4722d94d6a353c907a8d5cc70bd632ff0253a3ffa1d942ce1ec",
136
+ "runtime/dense_uv_parser/utils.py": "34ef3658087014d8a5de36231e4911eb752c4a62fae6601e60725173fed956d3",
137
+ "runtime/dense_uv_parser/uv_layout.py": "ddce13bf72bfa01c1e553f1f2760ce5a3ba4b55bae884740a9a3246fe6694e90",
138
+ "runtime/dense_uv_parser/uv_topology.py": "8cfe03e229d6f3ea7297165c0f97f5e9b6cf297d7a86da1b6f51c2e6a2f397e2",
139
+ "runtime/renderer.py": "e843c16b0d4b2534b6fe24646d15206c24f3aacf820f3fe30b5d42773e199d24",
140
+ "tested_environments.json": "fce93e20cf26758a5a7472c1354ba9c2c158d68b3c514b1c19249637033b5bf1"
141
+ }
142
+ }
SKING_DDJ_v101c/runtime/LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
SKING_DDJ_v101c/runtime/dense_uv_parser/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """Dense render-pixel to Minecraft UV parser."""
2
+
SKING_DDJ_v101c/runtime/dense_uv_parser/accessories.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Learned head accessory masks, object losses and geometry-safe routing.
2
+
3
+ Classes are object identities for one player: none, glasses, hat, outer hair.
4
+ RGB colour and projected-cell occupancy never create an accessory label.
5
+ """
6
+ import torch
7
+ from torch import nn
8
+ import torch.nn.functional as F
9
+
10
+ ACCESSORY_CLASSES = ('none', 'glasses', 'hat', 'outer_hair')
11
+ HEAD_CROP = (0.0625, 0.0, 0.9375, 0.34375) # fixed Steve camera ROI, not a mask
12
+
13
+
14
+ def head_bounds(height, width):
15
+ x0, y0, x1, y1 = HEAD_CROP
16
+ return round(y0*height), round(y1*height), round(x0*width), round(x1*width)
17
+
18
+
19
+ def head_crop(images, foreground=None):
20
+ y0, y1, x0, x1 = head_bounds(*images.shape[-2:])
21
+ rgb = images[:, :3]
22
+ if foreground is None:
23
+ foreground = torch.ones_like(rgb[:, :1])
24
+ elif foreground.dim() == 3:
25
+ foreground = foreground[:, None]
26
+ foreground = foreground.float()
27
+ rgb = rgb * foreground + 0.5 * (1-foreground)
28
+ crop = torch.cat([rgb, foreground], 1)[:, :, y0:y1, x0:x1]
29
+ return F.interpolate(crop.float(), (224, 224), mode='bilinear', align_corners=False)
30
+
31
+
32
+ def restore_logits(logits, size):
33
+ h, w = size
34
+ y0, y1, x0, x1 = head_bounds(h, w)
35
+ patch = F.interpolate(logits, (y1-y0, x1-x0), mode='bilinear', align_corners=False)
36
+ # Outside the crop the new branch is exactly inactive.
37
+ prior = logits.new_tensor([0.]+[-20.]*(logits.shape[1]-1))[None, :, None, None]
38
+ return F.pad(patch-prior, (x0, w-x1, y0, h-y1)) + prior
39
+
40
+
41
+ def block(cin, cout):
42
+ return nn.Sequential(nn.Conv2d(cin, cout, 3, padding=1), nn.GroupNorm(8, cout),
43
+ nn.SiLU(), nn.Conv2d(cout, cout, 3, padding=1),
44
+ nn.GroupNorm(8, cout), nn.SiLU())
45
+
46
+
47
+ class HeadAccessoryHead(nn.Module):
48
+ def __init__(self, semantic_dim=768, predict_hat_components=False):
49
+ super().__init__()
50
+ self.enc0 = block(4, 24)
51
+ self.enc1 = block(24, 48)
52
+ self.enc2 = block(48, 96)
53
+ self.enc3 = block(96, 96)
54
+ self.semantic = nn.Conv2d(semantic_dim, 96, 1)
55
+ self.context = nn.TransformerEncoder(
56
+ nn.TransformerEncoderLayer(96, 4, 256, 0.05, batch_first=True, norm_first=True),
57
+ 2, enable_nested_tensor=False)
58
+ self.dec2 = block(192, 96)
59
+ self.dec1 = block(144, 48)
60
+ self.dec0 = block(72, 24)
61
+ self.classifier = nn.Conv2d(24, 4, 1)
62
+ self.components = nn.Conv2d(24,6,1) if predict_hat_components else None
63
+ if self.components is not None:
64
+ nn.init.zeros_(self.components.weight)
65
+ nn.init.constant_(self.components.bias,-2.)
66
+ with torch.no_grad():self.components.bias[0]=2.
67
+ nn.init.constant_(self.classifier.bias, -2.)
68
+ with torch.no_grad():
69
+ self.classifier.bias[0] = 2.
70
+
71
+ def forward(self, crop, semantic_features, return_components=False):
72
+ s0 = self.enc0(crop)
73
+ s1 = self.enc1(F.avg_pool2d(s0, 2))
74
+ s2 = self.enc2(F.avg_pool2d(s1, 2))
75
+ z = self.enc3(F.avg_pool2d(s2, 2))
76
+ z = F.avg_pool2d(z, 2) + self.semantic(semantic_features.to(z.dtype))
77
+ z = self.context(z.flatten(2).transpose(1, 2)).transpose(1, 2).reshape_as(z)
78
+ z = self.dec2(torch.cat([F.interpolate(z, s2.shape[-2:], mode='bilinear', align_corners=False), s2], 1))
79
+ z = self.dec1(torch.cat([F.interpolate(z, s1.shape[-2:], mode='bilinear', align_corners=False), s1], 1))
80
+ z = self.dec0(torch.cat([F.interpolate(z, s0.shape[-2:], mode='bilinear', align_corners=False), s0], 1))
81
+ logits=self.classifier(z)
82
+ return (logits,self.components(z)) if return_components and self.components is not None else logits
83
+
84
+
85
+ def accessory_loss(logits, labels, valid=None):
86
+ """Per-object Dice + class-balanced CE + boundary affinity, preserving holes."""
87
+ if valid is None:
88
+ valid = torch.ones_like(labels, dtype=torch.bool)
89
+ target = labels.masked_fill(~valid, -100)
90
+ ce = F.cross_entropy(logits.float(), target, weight=logits.new_tensor([1., 3., 2., 2.]).float())
91
+ probability = logits.float().softmax(1)
92
+ onehot = F.one_hot(labels.clamp(0, 3), 4).permute(0, 3, 1, 2).float()
93
+ mask = valid[:, None]
94
+ p, g = probability * mask, onehot * mask
95
+ intersection = (p * g).sum((2, 3))
96
+ dice = (1-(2*intersection+1)/(p.sum((2, 3))+g.sum((2, 3))+1))[:, 1:].mean()
97
+ # Neighbour agreement targets also include object/background boundaries;
98
+ # there is no indiscriminate smoothness term that fills lens/frame holes.
99
+ affinity = logits.sum() * 0
100
+ for axis in (2, 3):
101
+ delta = torch.diff(p[:, 1:], dim=axis)
102
+ truth_delta = torch.diff(g[:, 1:], dim=axis)
103
+ affinity = affinity + F.smooth_l1_loss(delta, truth_delta)
104
+ return ce + dice + .2 * affinity
105
+
106
+
107
+ def connected_object_support(probability, identity, valid, seed_threshold=.90, grow_threshold=0.0):
108
+ """Keep a learned object region around confident seeds, across RGB changes.
109
+
110
+ Growth is restricted to the SAME predicted object class and foreground.
111
+ A low-confidence region without a seed cannot manufacture an accessory.
112
+ """
113
+ seeds = (probability >= seed_threshold) & (identity > 0) & valid
114
+ grown = seeds.clone()
115
+ for cls in (1,2,3):
116
+ candidate = (identity == cls) & (probability >= grow_threshold) & valid
117
+ current = seeds & (identity == cls)
118
+ if not current.any():
119
+ continue
120
+ while True:
121
+ neighbours = current.clone()
122
+ neighbours[:,1:] |= current[:,:-1]
123
+ neighbours[:,:-1] |= current[:,1:]
124
+ neighbours[:,:,1:] |= current[:,:,:-1]
125
+ neighbours[:,:,:-1] |= current[:,:,1:]
126
+ updated = current | (candidate & neighbours)
127
+ if torch.equal(updated,current):
128
+ break
129
+ current = updated
130
+ grown |= current
131
+ return grown, seeds
132
+
133
+
134
+ def apply_accessory_routing(routing, outputs, foreground, renderer, views, threshold=.80):
135
+ """Promote learned object evidence even when the old route selected inner.
136
+
137
+ This is an explicit object-evidence bypass of local texel voting. Actual
138
+ foreground and valid head geometry are required; later silhouette vetoes
139
+ and colour-background safeguards still apply.
140
+ """
141
+ from SkingToolkit.dense_uv_parser.utils import build_static_surface_routing
142
+ threshold = float(outputs.get('accessory_route_threshold', threshold))
143
+ logits = outputs.get('accessory_logits')
144
+ support = torch.zeros_like(foreground)
145
+ if logits is None:
146
+ return support
147
+ probability, identity = logits.float().softmax(1).max(1)
148
+ valid = torch.zeros_like(foreground)
149
+ for vi,view in enumerate(views):
150
+ static = build_static_surface_routing(renderer,view,foreground.device)
151
+ valid[vi::len(views)] = foreground[vi::len(views)] & static['masks'][1] & (static['part'][1] == 0)
152
+ support, seeds = connected_object_support(probability,identity,valid,threshold)
153
+ for vi, view in enumerate(views):
154
+ sl = slice(vi, foreground.shape[0], len(views))
155
+ static = build_static_surface_routing(renderer, view, foreground.device)
156
+ accepted = support[sl]
157
+ for name, value in [('layer', 1), ('foreground', True), ('surface', 1),
158
+ ('secondary', False), ('secondary_routed', False),
159
+ ('semantic_fallback', False), ('consensus_outer_gate_rejected', False)]:
160
+ if name in routing:
161
+ routing[name][sl] = torch.where(accepted, torch.full_like(routing[name][sl], value), routing[name][sl])
162
+ for name in ('flat_uv', 'part', 'face', 'texel_center_score'):
163
+ if name in routing:
164
+ routing[name][sl] = torch.where(accepted, static[name][1], routing[name][sl])
165
+ routing['confidence'][sl] = torch.where(accepted, probability[sl], routing['confidence'][sl])
166
+ margin = (2*probability[sl]-1).clamp_min(0)
167
+ for name, value in [('confidence_margin', margin), ('confidence_margin_ratio', margin/probability[sl].clamp_min(1e-6))]:
168
+ if name in routing:
169
+ routing[name][sl] = torch.where(accepted, value, routing[name][sl])
170
+ # Learned inner crown/band evidence can also correct an old outer route.
171
+ # This is restricted to explicitly trained components; no RGB rule is used.
172
+ inner_support=torch.zeros_like(foreground)
173
+ component_logits=outputs.get('hat_component_logits')
174
+ if component_logits is not None:
175
+ cp,ci=component_logits.float().softmax(1).max(1)
176
+ candidate=((ci==1)|(ci==2))&(cp>=.95)&(identity==0)&foreground
177
+ for vi,view in enumerate(views):
178
+ sl=slice(vi,foreground.shape[0],len(views))
179
+ static=build_static_surface_routing(renderer,view,foreground.device)
180
+ accepted=candidate[sl]&static['masks'][0]&(static['part'][0]==0)
181
+ inner_support[sl]=accepted
182
+ for name,value in [('layer',0),('foreground',True),('surface',0),('secondary',False),('secondary_routed',False),('semantic_fallback',False)]:
183
+ if name in routing:routing[name][sl]=torch.where(accepted,torch.full_like(routing[name][sl],value),routing[name][sl])
184
+ for name in ('flat_uv','part','face','texel_center_score'):
185
+ if name in routing:routing[name][sl]=torch.where(accepted,static[name][0],routing[name][sl])
186
+ routing['confidence'][sl]=torch.where(accepted,cp[sl],routing['confidence'][sl])
187
+ cm=(2*cp[sl]-1).clamp_min(0)
188
+ for name,value in [('confidence_margin',cm),('confidence_margin_ratio',cm/cp[sl].clamp_min(1e-6))]:
189
+ if name in routing:routing[name][sl]=torch.where(accepted,value,routing[name][sl])
190
+ routing['hat_inner_supported']=inner_support
191
+ routing['accessory_identity'] = identity
192
+ routing['accessory_probability'] = probability
193
+ routing['accessory_supported'] = support
194
+ routing['accessory_seed'] = seeds
195
+ from SkingToolkit.dense_uv_parser.ownership import apply_head_ownership
196
+ apply_head_ownership(routing, outputs, foreground, renderer, views)
197
+ from SkingToolkit.dense_uv_parser.headwear import apply_headwear_routing
198
+ apply_headwear_routing(routing, outputs, foreground, renderer, views)
199
+ return routing['accessory_supported']
SKING_DDJ_v101c/runtime/dense_uv_parser/accessory_data.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Procedural object-labelled skins. Labels describe authored objects, not RGB rules."""
2
+ import numpy as np
3
+ import torch
4
+ from torch.utils.data import Dataset
5
+ from SkingToolkit.dense_uv_parser.skin_dataset import load_skin
6
+
7
+
8
+ def make_accessory_skin(original, seed, return_components=False):
9
+ rng = np.random.default_rng(seed)
10
+ uv = original.permute(1, 2, 0).numpy().copy()
11
+ objects = np.zeros((64, 64), dtype=np.int64)
12
+ components = np.zeros((64,64),dtype=np.int64) # none, inner crown/band, outer crown/band, brim
13
+ # All six head faces are authored together. Body pixels remain the source skin.
14
+ uv[:16, :32] = 0
15
+ uv[:16, 32:] = 0
16
+ faces = [(8, 8), (24, 8), (0, 8), (16, 8), (8, 0), (16, 0)]
17
+ skin = np.array(rng.choice([[.87,.63,.43],[.45,.28,.19],[.65,.44,.30],
18
+ [.95,.78,.62],[.32,.20,.13],[.74,.62,.49]]))
19
+ if rng.random() < .12:
20
+ skin = rng.uniform(.2, .9, 3)
21
+ hair = rng.uniform(.03, .30, 3) if rng.random() < .7 else rng.uniform(.1, .85, 3)
22
+ for fi, (x, y) in enumerate(faces):
23
+ tex = np.clip(skin[None,None] + rng.normal(0,.025,(8,8,1)), 0, 1)
24
+ if fi in (1,4): tex[:] = hair + rng.normal(0,.025,(8,8,1))
25
+ if fi in (0,2,3): tex[:rng.integers(1,3)] = hair
26
+ uv[y:y+8, x:x+8, :3] = np.clip(tex,0,1)
27
+ uv[y:y+8, x:x+8, 3] = 1
28
+ # Eyes, eyebrows and mouth are explicit negative facial examples.
29
+ for x in (9, 13):
30
+ uv[11:12, x:x+2, :3] = rng.uniform(.01,.18,3)
31
+ uv[14,11:13,:3] = rng.uniform(.05,.5,3)
32
+ if rng.random() < .4:
33
+ uv[10,9:11,:3] = hair
34
+ uv[10,13:15,:3] = hair
35
+
36
+ def put(face, mask, color, identity, layer=1, component=0):
37
+ x, y = faces[face]; x += 32*layer
38
+ patch = uv[y:y+8, x:x+8]
39
+ patch[mask, :3] = color[mask] if np.asarray(color).ndim == 3 else color
40
+ patch[mask, 3] = 1
41
+ objects[y:y+8, x:x+8][mask] = identity
42
+ components[y:y+8, x:x+8][mask] = component
43
+
44
+ yy, xx = np.mgrid[:8,:8]
45
+ negative = rng.random() < .18
46
+ if not negative and rng.random() < .78:
47
+ top = int(rng.integers(2,4)); height = int(rng.integers(3,5))
48
+ frame_color = rng.uniform(.025,.23,3) if rng.random()<.70 else rng.uniform(.01,.85,3)
49
+ lens_color = rng.uniform(.05,.95,3)
50
+ frame = np.zeros((8,8),bool); lenses = np.zeros_like(frame)
51
+ # Distinct connected eyewear styles; class ID is independent of palette.
52
+ visor = rng.random()<.20
53
+ boxes = [(0,3),(4,7)] if visor else [(0,2),(5,7)]
54
+ hollow = rng.random()<.30
55
+ rimless_top = rng.random()<.45 and not hollow
56
+ for box_index,(left, right) in enumerate(boxes):
57
+ rectangle = (xx>=left)&(xx<=right)&(yy>=top)&(yy<top+height)
58
+ edge = rectangle & ((xx==left)|(xx==right)|(yy==top)|(yy==top+height-1))
59
+ if rimless_top:
60
+ edge &= (yy!=top)
61
+ # Thin inner rim variants preserve two-column lenses on an 8px face.
62
+ if not visor and not hollow and rng.random()<.65:
63
+ inner_x=right if box_index==0 else left
64
+ edge &= ~((xx==inner_x)&(yy<top+height-1))
65
+ if rng.random() < .2:
66
+ edge &= ~(((xx==left)|(xx==right))&(yy==top+height-1))
67
+ frame |= edge
68
+ lenses |= rectangle & ~edge
69
+ bridge_y = min(7,top+int(rng.integers(0,2)))
70
+ frame[bridge_y,2:6] = True
71
+ lenses[frame] = False
72
+ if hollow: lenses[:] = False # open-frame holes stay empty
73
+ color = np.broadcast_to(frame_color,(8,8,3)).copy()
74
+ color[lenses] = lens_color
75
+ # Lens shading keeps the same object ID across several colours.
76
+ color[lenses] *= rng.uniform(.65,1.05,(8,8,1))[lenses]
77
+ put(0, frame|lenses, np.clip(color,0,1), 1)
78
+ for face in (2,3):
79
+ length = int(rng.integers(3,9))
80
+ temple = (yy==bridge_y)&(xx<length)
81
+ put(face,temple,frame_color,1)
82
+ kind = int(rng.choice([0,2,3], p=[.35,.40,.25])) if not negative else 0
83
+ if kind==2:
84
+ # Geometry and material are independent variables. A whole hat can have
85
+ # an inner crown/band and an extruded brim; the band is not background.
86
+ color = rng.uniform(.02,.17,3) if rng.random()<.65 else rng.uniform(.05,.85,3)
87
+ depth = int(rng.integers(2,6))
88
+ stepped = rng.random()<.70
89
+ variant = int(rng.choice(3,p=[.75,.15,.10])) # full ring, front visor, partial/asymmetric
90
+ band_color = rng.uniform(.04,.95,3)
91
+ if rng.random()<.3: band_color=np.array([rng.uniform(.5,.95),rng.uniform(.02,.12),rng.uniform(.02,.12)])
92
+ if rng.random()<.2: band_color=color*rng.uniform(.7,1.2)
93
+ has_band = rng.random()<.85
94
+ crown_layer=0 if stepped else 1
95
+ crown_component=1 if stepped else 3
96
+ band_component=2 if stepped else 4
97
+ put(4,np.ones((8,8),bool),color,0 if stepped else 2,layer=crown_layer,component=crown_component)
98
+ for face in (0,1,2,3):
99
+ tex=np.clip(np.broadcast_to(color,(8,8,3))+rng.normal(0,.02,(8,8,1)),0,1)
100
+ crown=yy<depth-1
101
+ put(face,crown,tex,0 if stepped else 2,layer=crown_layer,component=crown_component)
102
+ if has_band:
103
+ put(face,yy==depth-2,np.clip(band_color,0,1),0 if stepped else 2,layer=crown_layer,component=band_component)
104
+ brim=yy==depth-1
105
+ if variant==1 and face!=0: brim[:]=False
106
+ if variant==2 and face in (1,3): brim &= xx<5
107
+ put(face,brim,color,2,component=5)
108
+ elif kind==3:
109
+ put(4,np.ones((8,8),bool),hair,3)
110
+ for face in (0,1,2,3):
111
+ depth=int(rng.integers(1,4)) if face==0 else int(rng.integers(2,7))
112
+ mask=(yy<depth)|((yy==depth)&(rng.random((8,8))>.45))
113
+ tex=np.clip(np.broadcast_to(hair,(8,8,3))+rng.normal(0,.025,(8,8,1)),0,1)
114
+ put(face,mask,tex,3)
115
+ if return_components:
116
+ return torch.from_numpy(uv).permute(2,0,1).float(),torch.from_numpy(objects),torch.from_numpy(components)
117
+ return torch.from_numpy(uv).permute(2,0,1).float(), torch.from_numpy(objects)
118
+
119
+
120
+ class AccessoryDataset(Dataset):
121
+ def __init__(self, paths, count, seed):
122
+ self.paths, self.count, self.seed, self.epoch = list(paths), count, seed, 0
123
+
124
+ def __len__(self): return self.count
125
+
126
+ def __getitem__(self, index):
127
+ seed = self.seed + index*104729 + self.epoch*self.count*104729
128
+ source = load_skin(self.paths[(index + self.epoch*self.count) % len(self.paths)])
129
+ uv, objects, components = make_accessory_skin(source, seed, return_components=True)
130
+ return {'uv':uv,'objects':objects,'components':components,'seed':seed}
131
+
132
+
133
+ def render_accessories(uv, objects, renderer, views, components=None):
134
+ from SkingToolkit.dense_uv_parser.utils import build_dense_parser_batch
135
+ images, labels, foregrounds, parts = [], [], [], []
136
+ for view in views:
137
+ rendered, target = build_dense_parser_batch(uv, renderer, view)
138
+ xy = (target['uv']*63).round().long().clamp(0,63)
139
+ flat = xy[:,1]*64+xy[:,0]
140
+ identity = objects.flatten(1).gather(1,flat.flatten(1)).reshape_as(flat)
141
+ identity = identity.masked_fill((target['layer'] != 1) | (target['foreground'][:,0] < .5), 0)
142
+ images.append(rendered);labels.append(identity);foregrounds.append(target['foreground'][:,0].bool())
143
+ if components is not None:
144
+ part=components.flatten(1).gather(1,flat.flatten(1)).reshape_as(flat)
145
+ parts.append(part.masked_fill(target['foreground'][:,0]<.5,0))
146
+ b = uv.shape[0]
147
+ result=(torch.stack(images,1).flatten(0,1),torch.stack(labels,1).flatten(0,1),torch.stack(foregrounds,1).flatten(0,1))
148
+ return result+(torch.stack(parts,1).flatten(0,1),) if components is not None else result
SKING_DDJ_v101c/runtime/dense_uv_parser/accessory_pipeline.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The same foreground, routing, completion and renderer path for v101 eval/infer."""
2
+ import json
3
+ from pathlib import Path
4
+ import torch
5
+ from SkingToolkit.dense_uv_parser.foreground import build_parser_input,learned_foreground_support
6
+ from SkingToolkit.dense_uv_parser.utils import estimate_top_left_flood_foreground, splat_parser_predictions_to_uv_conditioning
7
+ from SkingToolkit.dense_uv_parser.infer import simple_inpaint_uv
8
+
9
+
10
+ def load_pipeline(path=None):
11
+ return json.loads(Path(path or Path(__file__).with_name('v101_pipeline.json')).read_text())
12
+
13
+
14
+ @torch.no_grad()
15
+ def run_pipeline(model, renderer, images, config=None, complete=False, outputs=None, foreground_probability=None):
16
+ config = config or load_pipeline()
17
+ views = config['routing']['views']
18
+ color_sources=None
19
+ if foreground_probability is None:
20
+ fg = estimate_top_left_flood_foreground(images, config['foreground_flood_tolerance'])
21
+ else:
22
+ if foreground_probability.shape != images.shape[:1]+images.shape[-2:]:
23
+ raise ValueError('Foreground probability must have shape (N,H,W)')
24
+ probability=foreground_probability.to(device=images.device,dtype=torch.float32)
25
+ if not torch.isfinite(probability).all() or probability.min()<0 or probability.max()>1:
26
+ raise ValueError('Foreground probability must be finite in [0,1]')
27
+ fg,color_sources=learned_foreground_support(probability,config.get('foreground_probability_threshold',.5),config.get('foreground_source_threshold',.98),config.get('foreground_source_inset',1))
28
+ actual = build_parser_input(images, fg, background_mode=config['foreground_background'])
29
+ if outputs is None:
30
+ outputs = model(actual, view_ids=torch.arange(images.shape[0], device=images.device) % len(views), semantic_foreground=fg)
31
+ outputs = {**outputs, 'accessory_route_threshold':config['accessory_route_threshold']}
32
+ outputs['headwear_presence_threshold']=config.get('headwear_presence_threshold',.95)
33
+ outputs['headphone_presence_threshold']=config.get('headphone_presence_threshold',.9)
34
+ outputs['headphone_presence_consensus']=config.get('headphone_presence_consensus',False)
35
+ mode=config.get('headphone_routing_mode','unrestricted')
36
+ def splat(current):
37
+ return splat_parser_predictions_to_uv_conditioning(
38
+ images,current,renderer=renderer,observed_foreground=fg,observed_color_support=color_sources,return_details=True,**config['routing'])
39
+ if mode=='existing_uv' and 'head_ownership_logits' in outputs:
40
+ # The new headphone head may recover colour ownership inside geometry
41
+ # already accepted by v101. It cannot manufacture new outer occupancy.
42
+ initial,_=splat({**outputs,'headphone_routing_mode':'disabled'})
43
+ outputs={**outputs,'headphone_routing_mode':'existing_uv','headphone_uv_support':(initial[:,9]>.5).flatten(1)}
44
+ else:outputs={**outputs,'headphone_routing_mode':mode}
45
+ cond,details=splat(outputs)
46
+ geometry_mode = config.get('crown_top_geometry_mode', 'legacy_consensus')
47
+ if geometry_mode == 'rendered_semantics':
48
+ from SkingToolkit.dense_uv_parser.crown_geometry import reconcile_crown_geometry
49
+ cond = reconcile_crown_geometry(cond, details, renderer, views)
50
+ elif geometry_mode == 'legacy_consensus':
51
+ from SkingToolkit.dense_uv_parser.headwear import reconcile_crown_top
52
+ cond = reconcile_crown_top(cond, details, renderer, views)
53
+ else:
54
+ raise ValueError('Unknown crown top geometry mode: ' + str(geometry_mode))
55
+ result = {'foreground_color_sources':color_sources,'foreground_probability':foreground_probability,'conditioning':cond,'details':details,'outputs':outputs,'foreground':fg}
56
+ if complete:
57
+ result['uv'] = torch.stack([simple_inpaint_uv(c[None].cpu())[0] for c in cond]).to(images.device)
58
+ if config.get('head_semantic_inpaint',False):
59
+ from SkingToolkit.dense_uv_parser.head_inpainting import repair_hidden_head_material
60
+ result['uv']=repair_hidden_head_material(result['uv'],cond,details,views)
61
+ from SkingToolkit.dense_uv_parser.headwear import isolate_headwear_material
62
+ result['uv'],headwear_uv=isolate_headwear_material(result['uv'],cond,details,views)
63
+ if config.get('head_material_refine_steps',0):
64
+ from SkingToolkit.dense_uv_parser.material_refine import refine_head_material
65
+ if config.get('head_material_refine_mode')!='isolated':
66
+ from SkingToolkit.dense_uv_parser.material_refine import refine_head_material_legacy
67
+ result['uv']=refine_head_material_legacy(result['uv'],details['rendered'],details['color_source_support'],renderer,views,config['head_material_refine_steps'])
68
+ else:
69
+ result['uv']=refine_head_material(result['uv'],details['rendered'],details['color_source_support'],renderer,views,config['head_material_refine_steps'],ownership=details['outputs'].get('head_ownership_logits'),inner_exclusion=details['routing'].get('head_color_boundary_excluded'),inner_texel_support=cond[:,4]>.5,headwear_layer=details['routing'].get('headwear_layer'),headwear_uv=headwear_uv,headwear_family=details['routing'].get('headwear_family'))
70
+ result['render'] = torch.stack([renderer.forward_view(result['uv'], view) for view in views],1).flatten(0,1)
71
+ return result
72
+
73
+
74
+ def cached_real_foreground(images, source, config):
75
+ """Load verified learned foreground for real development evaluation."""
76
+ import hashlib
77
+ import numpy as np
78
+ from PIL import Image
79
+ import torch.nn.functional as F
80
+ cache=config.get('foreground_cache')
81
+ if cache is None:return None
82
+ source=Path(source).resolve();entry=cache.get(str(source))
83
+ if entry is None:raise ValueError('Missing learned foreground for '+str(source))
84
+ data=Path(entry['probability']).read_bytes()
85
+ if hashlib.sha256(source.read_bytes()).hexdigest()!=entry['input_sha256'] or hashlib.sha256(data).hexdigest()!=entry['probability_sha256']:
86
+ raise ValueError('Learned foreground cache changed')
87
+ import io
88
+ p=torch.from_numpy(np.array(Image.open(io.BytesIO(data))).copy()).float().to(images.device)/255.
89
+ return F.interpolate(torch.stack(p.chunk(len(config['routing']['views']),1))[:,None],images.shape[-2:],mode='nearest-exact')[:,0]
SKING_DDJ_v101c/runtime/dense_uv_parser/accessory_regression.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Visually traced development regression, kept separate from training/test data."""
2
+ import hashlib
3
+ import json
4
+ from pathlib import Path
5
+ from types import SimpleNamespace
6
+ import numpy as np
7
+ from PIL import Image
8
+ import torch
9
+ from PIL import ImageDraw,ImageFilter
10
+ import torch.nn.functional as F
11
+ from torchvision.utils import save_image
12
+ from SkingToolkit.dense_uv_parser.infer import load_view_images
13
+ from SkingToolkit.dense_uv_parser.accessory_pipeline import run_pipeline,cached_real_foreground
14
+ from SkingToolkit.dense_uv_parser.uv_layout import tensor_to_rgba_image
15
+
16
+
17
+ @torch.no_grad()
18
+ def evaluate_real_regression(model,renderer,config,output_dir,step):
19
+ root=Path(__file__).parent
20
+ metadata=json.loads((root/'v101_real_regression.json').read_text())
21
+ image_path=Path(metadata['combined'])
22
+ if hashlib.sha256(image_path.read_bytes()).hexdigest()!=metadata['source_sha256']:
23
+ raise ValueError('Regression input changed; review the annotation before using it')
24
+ images=load_view_images(SimpleNamespace(combined=image_path),config['routing']['views'],renderer).cuda()
25
+ probability=cached_real_foreground(images,image_path,config)
26
+ result=run_pipeline(model,renderer,images,config,complete=True,foreground_probability=probability)
27
+ baseline=run_pipeline(model,renderer,images,config,outputs={k:v for k,v in result['outputs'].items() if k not in ('accessory_logits','hat_component_logits')},foreground_probability=probability)
28
+ annotation=torch.from_numpy(np.array(Image.open(root/metadata['mask']))>0).cuda()
29
+ eroded=(-F.max_pool2d(-annotation[None,None].float(),5,1,2))[0,0]>.5
30
+ expanded=F.max_pool2d(annotation[None,None].float(),5,1,2)[0,0]>.5
31
+ uncertain=expanded&~eroded
32
+ pred=result['outputs']['accessory_logits'][0].softmax(0)
33
+ glasses=(pred.argmax(0)==1)&result['details']['routing']['accessory_supported'][0]
34
+ valid=result['foreground'][0]&~uncertain
35
+ tp=int((glasses&annotation&valid).sum());fp=int((glasses&~annotation&valid).sum());fn=int((~glasses&annotation&valid).sum())
36
+ r=result['details']['routing'];br=baseline['details']['routing']
37
+ final_outer=r['foreground'][0]&(r['layer'][0]==1)
38
+ base_outer=br['foreground'][0]&(br['layer'][0]==1)
39
+ rgb=images[0,:3];yy=torch.arange(rgb.shape[1],device=rgb.device)[:,None];xx=torch.arange(rgb.shape[2],device=rgb.device)[None,:]
40
+ green=(rgb[1]>rgb[0]+.12)&(rgb[1]>rgb[2]+.14)&(rgb[1]>.25)&(yy<145)&(xx>90)
41
+ metrics={'scope':metadata['role'],'glasses_mask_precision':tp/max(1,tp+fp),'glasses_mask_recall':tp/max(1,tp+fn),
42
+ 'whole_glasses_outer_recall':float(final_outer[eroded].float().mean()),
43
+ 'baseline_whole_glasses_outer_recall':float(base_outer[eroded].float().mean())}
44
+ for name,mask in [('left',green&(xx<160)),('right',green&(xx>=160))]:
45
+ metrics[name+'_lens_outer_recall']=float(final_outer[mask].float().mean())
46
+ metrics['baseline_'+name+'_lens_outer_recall']=float(base_outer[mask].float().mean())
47
+ save_image(torch.cat(list(result['render'][:,:3]),dim=2).cpu(),output_dir/f'real_{step}_render.png')
48
+ save_image(pred[1:2].cpu(),output_dir/f'real_{step}_glasses_probability.png')
49
+ tensor_to_rgba_image(result['uv'][0]).save(output_dir/f'real_{step}_uv.png')
50
+ if config.get("hat_development"):
51
+ metrics.update(evaluate_hat_regression(model,renderer,config,output_dir,step))
52
+ return metrics
53
+
54
+
55
+ @torch.no_grad()
56
+ def evaluate_hat_regression(model,renderer,config,output_dir,step):
57
+ spec=config['hat_development'];source=Path(spec['input'])
58
+ if hashlib.sha256(source.read_bytes()).hexdigest()!=spec['input_sha256']:raise ValueError('Hat input changed')
59
+ images=load_view_images(SimpleNamespace(combined=source),config['routing']['views'],renderer).cuda()
60
+ probability=cached_real_foreground(images,source,config)
61
+ result=run_pipeline(model,renderer,images,config,complete=True,foreground_probability=probability)
62
+ mask=torch.from_numpy(np.array(Image.open(spec['brim_mask']).filter(ImageFilter.MinFilter(3)))>0).cuda()
63
+ routing=result['details']['routing'];outer=routing['foreground']&(routing['layer']==1)
64
+ # Explicit colour-band region, used only as a development render diagnostic.
65
+ band=Image.new('L',(256,512));ImageDraw.Draw(band).polygon([(48,56),(107,80),(207,65),(207,79),(107,94),(48,69)],fill=255)
66
+ band=torch.from_numpy(np.array(band.filter(ImageFilter.MaxFilter(9)))>0).cuda()
67
+ def chroma(rgb):return (rgb[:,0]-rgb[:,1:3].amax(1)-.15).clamp_min(0)[:,band].sum(1)
68
+ reference=chroma(images[:,:3]);observed=chroma(result['render'][:,:3])
69
+ metrics={'hat_brim_outer_recall':[float(v[mask].float().mean()) for v in outer],
70
+ 'hat_band_chroma_retention':[float(x) for x in (observed/reference.clamp_min(1e-5))]}
71
+ save_image(torch.cat(list(result['render'][:,:3]),2).cpu(),output_dir/f'hat_{step}_render.png')
72
+ tensor_to_rgba_image(result['uv'][0]).save(output_dir/f'hat_{step}_uv.png')
73
+ return metrics