Commit ·
cbe1737
0
Parent(s):
Duplicate from EntropyDrop/Sking
Browse filesCo-authored-by: EntropyDrop <EntropyDrop@users.noreply.huggingface.co>
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded+39
- LICENSEAdded+662
- README.mdAdded+75
- SKING_DDJ_v101c/LICENSEAdded+661
- SKING_DDJ_v101c/README.mdAdded+64
- SKING_DDJ_v101c/THIRD_PARTY_NOTICES.mdAdded+7
- SKING_DDJ_v101c/foreground.ptAdded+3
- SKING_DDJ_v101c/foreground_base/BiRefNet_config.pyAdded+11
- SKING_DDJ_v101c/foreground_base/birefnet.pyAdded+2249
- SKING_DDJ_v101c/foreground_base/config.jsonAdded+20
- SKING_DDJ_v101c/foreground_base/model.safetensorsAdded+3
- SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/refs/mainAdded+1
- SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/config.jsonAdded+12
- SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/model.safetensorsAdded+3
- SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/preprocessor_config.jsonAdded+24
- SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/special_tokens_map.jsonAdded+34
- SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.jsonAdded+3
- SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.modelAdded+3
- SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer_config.jsonAdded+2020
- SKING_DDJ_v101c/hf_cache/modules/__init__.pyAdded
- SKING_DDJ_v101c/hf_cache/modules/transformers_modules/__init__.pyAdded
- SKING_DDJ_v101c/hf_cache/modules/transformers_modules/foreground_base/BiRefNet_config.pyAdded+11
- SKING_DDJ_v101c/hf_cache/modules/transformers_modules/foreground_base/__init__.pyAdded
- SKING_DDJ_v101c/hf_cache/modules/transformers_modules/foreground_base/birefnet.pyAdded+2249
- SKING_DDJ_v101c/infer.pyAdded+214
- SKING_DDJ_v101c/licenses/BiRefNet_LICENSE.txtAdded+21
- SKING_DDJ_v101c/licenses/SigLIP2_LICENSE.txtAdded+201
- SKING_DDJ_v101c/licenses/sources.jsonAdded+14
- SKING_DDJ_v101c/mappings_256x512/back_left_mapping.ptAdded+3
- SKING_DDJ_v101c/mappings_256x512/back_left_overlay_mapping.ptAdded+3
- SKING_DDJ_v101c/mappings_256x512/back_right_mapping.ptAdded+3
- SKING_DDJ_v101c/mappings_256x512/back_right_overlay_mapping.ptAdded+3
- SKING_DDJ_v101c/mappings_256x512/front_left_mapping.ptAdded+3
- SKING_DDJ_v101c/mappings_256x512/front_left_overlay_mapping.ptAdded+3
- SKING_DDJ_v101c/mappings_256x512/front_right_mapping.ptAdded+3
- SKING_DDJ_v101c/mappings_256x512/front_right_overlay_mapping.ptAdded+3
- SKING_DDJ_v101c/mappings_256x512/static_back_mapping.ptAdded+3
- SKING_DDJ_v101c/mappings_256x512/static_front_mapping.ptAdded+3
- SKING_DDJ_v101c/mappings_256x512/walk_back_base_layer_ortho_mapping.ptAdded+3
- SKING_DDJ_v101c/mappings_256x512/walk_back_both_layer_ortho_mapping.ptAdded+3
- SKING_DDJ_v101c/mappings_256x512/walk_front_base_layer_ortho_mapping.ptAdded+3
- SKING_DDJ_v101c/mappings_256x512/walk_front_both_layer_ortho_mapping.ptAdded+3
- SKING_DDJ_v101c/parser.ptAdded+3
- SKING_DDJ_v101c/pipeline.jsonAdded+79
- SKING_DDJ_v101c/release.jsonAdded+142
- SKING_DDJ_v101c/runtime/LICENSEAdded+661
- SKING_DDJ_v101c/runtime/dense_uv_parser/__init__.pyAdded+2
- SKING_DDJ_v101c/runtime/dense_uv_parser/accessories.pyAdded+199
- SKING_DDJ_v101c/runtime/dense_uv_parser/accessory_data.pyAdded+148
- SKING_DDJ_v101c/runtime/dense_uv_parser/accessory_pipeline.pyAdded+89
123456789101112131415161718192021222324252627282930313233343536373839*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -textSKING_DDJ_v104/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.json filter=lfs diff=lfs merge=lfs -textSKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.json filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license forsoftware and other kinds of works, specifically designed to ensurecooperation with the community in the case of network server software.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,our General Public Licenses are intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rightswith two steps: (1) assert copyright on the software, and (2) offeryou this License which gives you legal permission to copy, distributeand/or modify the software.
A secondary benefit of defending all users' freedom is thatimprovements made in alternate versions of the program, if theyreceive widespread use, become available for other developers toincorporate. Many developers of free software are heartened andencouraged by the resulting cooperation. However, in the case ofsoftware used on network servers, this result may fail to come about.The GNU General Public License permits making a modified version andletting the public access it on a server without ever releasing itssource code to the public.
The GNU Affero General Public License is designed specifically toensure that, in such cases, the modified source code becomes availableto the community. It requires the operator of a network server toprovide the source code of the modified version running there to theusers of that server. Therefore, public use of a modified version, ona publicly accessible server, gives the public access to the sourcecode of the modified version.
An older license, called the Affero General Public License andpublished by Affero, was designed to accomplish similar goals. This isa different license, not a version of the Affero GPL, but Affero hasreleased a new version of the Affero GPL which permits relicensing underthis license.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as "you". "Licensees" and"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"to the extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A"Major Component", in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an"aggregate" if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-readable Corresponding Source under the terms of this License,in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe only significant mode of use of the product.
"Installation Information" for a User Product means any methods,procedures, authorization keys, or other information required to installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holders ofthat material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions;the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.
If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain the covered work, unless you entered into that arrangement,or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify theProgram, your modified version must prominently offer all usersinteracting with it remotely through a computer network (if your versionsupports such interaction) an opportunity to receive the CorrespondingSource of your version by providing access to the Corresponding Sourcefrom a network server at no charge, through some standard or customarymeans of facilitating copying of software. This Corresponding Sourceshall include the Corresponding Source for any work covered by version 3of the GNU General Public License that is incorporated pursuant to thefollowing paragraph.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the work with which it is combined will remain governed by version3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU Affero General Public License from time to time. Such new versionswill be similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU Affero GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU Affero General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU Affero General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computernetwork, you should also make sure that it provides a way for users toget its source. For example, if your program is a web application, itsinterface could display a "Source" link that leads users to an archiveof the code. There are many ways you could offer source, and differentsolutions will be better for different programs; see section 13 for thespecific requirements.
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU AGPL, see<https://www.gnu.org/licenses/>.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475---license: agpl-3.0tags:- minecraft- image-to-skin- dense-uv---
# Sking: Image To Minecraft Skin Generator
**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.
## SKING_DDJ_v101c — recommended production UV release (2026-09-16)
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.
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.
## SKING_DDJ_v104 — production UV release (2026-09-08)
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.
See the [v104 download and inference instructions](SKING_DDJ_v104/README.md). Download the complete directory rather than only `parser.pt`. Earlier model versions remain available below. The root `infer.py` is the earlier image-generation entry point; use `SKING_DDJ_v104/infer.py` for this release.
## 🔗 Resources
* **🌐 Online Demo**: [EntropyDrop Web Portal](https://entropydrop.com)* **🗂️ Dataset**: [Hugging Face Sking Dataset](https://huggingface.co/datasets/EntropyDrop/Sking)* **🧠 Trained Model**: [Hugging Face Sking Model](https://huggingface.co/EntropyDrop/Sking)* **📝 Technical Report**: [Technical Architecture](https://entropydrop.com/public/blog/skingen)* **YouTube**: [YouTube](https://youtu.be/n5t48aNm9Ew)
## Examples






## Delopy locally
```python ./infer.py```
## License
This project is licensed under the GNU Affero General Public License v3.0 - see the [LICENSE](LICENSE) file for details.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license forsoftware and other kinds of works, specifically designed to ensurecooperation with the community in the case of network server software.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,our General Public Licenses are intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rightswith two steps: (1) assert copyright on the software, and (2) offeryou this License which gives you legal permission to copy, distributeand/or modify the software.
A secondary benefit of defending all users' freedom is thatimprovements made in alternate versions of the program, if theyreceive widespread use, become available for other developers toincorporate. Many developers of free software are heartened andencouraged by the resulting cooperation. However, in the case ofsoftware used on network servers, this result may fail to come about.The GNU General Public License permits making a modified version andletting the public access it on a server without ever releasing itssource code to the public.
The GNU Affero General Public License is designed specifically toensure that, in such cases, the modified source code becomes availableto the community. It requires the operator of a network server toprovide the source code of the modified version running there to theusers of that server. Therefore, public use of a modified version, ona publicly accessible server, gives the public access to the sourcecode of the modified version.
An older license, called the Affero General Public License andpublished by Affero, was designed to accomplish similar goals. This isa different license, not a version of the Affero GPL, but Affero hasreleased a new version of the Affero GPL which permits relicensing underthis license.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as "you". "Licensees" and"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"to the extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A"Major Component", in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an"aggregate" if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-readable Corresponding Source under the terms of this License,in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe only significant mode of use of the product.
"Installation Information" for a User Product means any methods,procedures, authorization keys, or other information required to installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holders ofthat material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions;the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.
If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain the covered work, unless you entered into that arrangement,or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify theProgram, your modified version must prominently offer all usersinteracting with it remotely through a computer network (if your versionsupports such interaction) an opportunity to receive the CorrespondingSource of your version by providing access to the Corresponding Sourcefrom a network server at no charge, through some standard or customarymeans of facilitating copying of software. This Corresponding Sourceshall include the Corresponding Source for any work covered by version 3of the GNU General Public License that is incorporated pursuant to thefollowing paragraph.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the work with which it is combined will remain governed by version3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU Affero General Public License from time to time. Such new versionswill be similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU Affero GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU Affero General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU Affero General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computernetwork, you should also make sure that it provides a way for users toget its source. For example, if your program is a web application, itsinterface could display a "Source" link that leads users to an archiveof the code. There are many ways you could offer source, and differentsolutions will be better for different programs; see section 13 for thespecific requirements.
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU AGPL, see<https://www.gnu.org/licenses/>.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# SKING_DDJ_v101c
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.
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.
## Contents
| Path | Purpose || --- | --- || `parser.pt` | Sanitized v101c dense UV parser checkpoint || `foreground.pt` | Sanitized trained Minecraft foreground decoder checkpoint || `pipeline.json` | Inference configuration with development-only path metadata removed || `foreground_base/` | BiRefNet base model and implementation || `hf_cache/` | Pinned SigLIP2 model and tokenizer for offline inference || `runtime/` | Matching inference and training source snapshot, without private test images || `mappings_256x512/` | UV mapping tensors used by production || `infer.py` | Portable foreground + parser + final inpainting launcher || `release.json` | Checksums, source artifact identities, and sanitization record || `tested_environments.json` | Dependency versions used for verification |
Download the complete directory. `parser.pt` by itself is insufficient to reproduce the full pipeline.
## Download
```pythonfrom huggingface_hub import snapshot_download
snapshot_download( repo_id="EntropyDrop/Sking", allow_patterns=["SKING_DDJ_v101c/*"], local_dir="./Sking",)```
For repeatable deployments, pass the release commit hash as `revision` instead of following the repository's moving `main` branch.
## Run
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.
```bashpython ./Sking/SKING_DDJ_v101c/infer.py --verify-only
/path/to/parser-env/bin/python ./Sking/SKING_DDJ_v101c/infer.py \ --parser-python /path/to/parser-env/bin/python \ --foreground-python /path/to/foreground-env/bin/python \ --input ./character_edited.png \ --output ./character_result_v101c.png```
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.
## Validation and limits
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.
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.
Semantic errors can still occur, and the model assumes the expected edited-render layout.
## License and upstream components
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.1234567# Third-party components
- `foreground_base/`: [ZhengPeng7/BiRefNet](https://huggingface.co/ZhengPeng7/BiRefNet/tree/6a62b7dcfa18a3829087877fb16c8006831e4220), MIT. License: `licenses/BiRefNet_LICENSE.txt`.- `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).- Sking weights, inference/runtime code and UV mappings are provided under the repository AGPL-3.0 license; third-party components retain their respective licenses.
Upstream license retrieval URLs and SHA-256 hashes are recorded in `licenses/sources.json`.123version https://git-lfs.github.com/spec/v1oid sha256:f00c1abbf736d54fcda6800ec6046817456ef9fbc45bb67bc1e6d759cfb45331size 1001425581234567891011from transformers import PretrainedConfig
class BiRefNetConfig(PretrainedConfig): model_type = "SegformerForSemanticSegmentation" def __init__( self, bb_pretrained=False, **kwargs ): self.bb_pretrained = bb_pretrained super().__init__(**kwargs)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249### config.py
import osimport mathfrom transformers import PretrainedConfig
class Config(PretrainedConfig): def __init__(self) -> None: # PATH settings 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
# TASK settings self.task = ['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'][0] self.training_set = { 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0], 'COD': 'TR-COD10K+TR-CAMO', '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], '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. 'P3M-10k': 'TR-P3M-10k', }[self.task] self.prompt4loc = ['dense', 'sparse'][0]
# Faster-Training settings self.load_all = True self.compile = True # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch. # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting. # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607. # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training. self.precisionHigh = True
# MODEL settings self.ms_supervision = True self.out_ref = self.ms_supervision and True self.dec_ipt = True self.dec_ipt_split = True self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder self.mul_scl_ipt = ['', 'add', 'cat'][2] self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2] self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1] self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0]
# TRAINING settings self.batch_size = 4 self.IoU_finetune_last_epochs = [ 0, { 'DIS5K': -50, 'COD': -20, 'HRSOD': -20, 'DIS5K+HRSOD+HRS10K': -20, 'P3M-10k': -20, }[self.task] ][1] # choose 0 to skip 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 self.size = 1024 self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader
# Backbone settings self.bb = [ 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2 'swin_v1_t', 'swin_v1_s', # 3, 4 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs4 'pvt_v2_b0', 'pvt_v2_b1', # 7, 8 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5 ][6] self.lateral_channels_in_collection = { 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96], 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64], }[self.bb] if self.mul_scl_ipt == 'cat': self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection] self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []
# MODEL settings - inactive self.lat_blk = ['BasicLatBlk'][0] self.dec_channels_inter = ['fixed', 'adap'][0] self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0] self.progressive_ref = self.refine and True self.ender = self.progressive_ref and False self.scale = self.progressive_ref and 2 self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`. self.refine_iteration = 1 self.freeze_bb = False self.model = [ 'BiRefNet', ][0] if self.dec_blk == 'HierarAttDecBlk': self.batch_size = 2 ** [0, 1, 2, 3, 4][2]
# TRAINING settings - inactive self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4] self.optimizer = ['Adam', 'AdamW'][1] self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch. self.lr_decay_rate = 0.5 # Loss self.lambdas_pix_last = { # not 0 means opening this loss # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30 'bce': 30 * 1, # high performance 'iou': 0.5 * 1, # 0 / 255 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64) 'mse': 150 * 0, # can smooth the saliency map 'triplet': 3 * 0, 'reg': 100 * 0, 'ssim': 10 * 1, # help contours, 'cnt': 5 * 0, # help contours '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. } self.lambdas_cls = { 'ce': 5.0 } # Adv self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training self.lambda_adv_d = 3. * (self.lambda_adv_g > 0)
# PATH settings - inactive self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis') self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights') self.weights = { 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'), 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]), '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]), '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]), 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]), 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]), 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]), 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]), }
# Callbacks - inactive self.verbose_eval = True self.only_S_MAE = False self.use_fp16 = False # Bugs. It may cause nan in training. self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs
# others self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')
self.batch_size_valid = 1 self.rand_seed = 7 # 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] # with open(run_sh_file[0], 'r') as f: # lines = f.readlines() # 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]) # 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]) # self.val_step = [0, self.save_step][0]
def print_task(self) -> None: # Return task for choosing settings in shell scripts. print(self.task)
### models/backbones/pvt_v2.py
import torchimport torch.nn as nnfrom functools import partial
from timm.models.layers import DropPath, to_2tuple, trunc_normal_from timm.models.registry import register_model
import math
# from config import Config
# config = Config()
class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.dwconv = DWConv(hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop)
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def forward(self, x, H, W): x = self.fc1(x) x = self.dwconv(x, H, W) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x
class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1): super().__init__() assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
self.dim = dim self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5
self.q = nn.Linear(dim, dim, bias=qkv_bias) self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias) self.attn_drop_prob = attn_drop self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop)
self.sr_ratio = sr_ratio if sr_ratio > 1: self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio) self.norm = nn.LayerNorm(dim)
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def forward(self, x, H, W): B, N, C = x.shape q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
if self.sr_ratio > 1: x_ = x.permute(0, 2, 1).reshape(B, C, H, W) x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1) x_ = self.norm(x_) kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) else: kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) k, v = kv[0], kv[1]
if config.SDPA_enabled: x = torch.nn.functional.scaled_dot_product_attention( q, k, v, attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False ).transpose(1, 2).reshape(B, N, C) else: attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x)
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio) # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def forward(self, x, H, W): x = x + self.drop_path(self.attn(self.norm1(x), H, W)) x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
return x
class OverlapPatchEmbed(nn.Module): """ Image to Patch Embedding """
def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size)
self.img_size = img_size self.patch_size = patch_size self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1] self.num_patches = self.H * self.W self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride, padding=(patch_size[0] // 2, patch_size[1] // 2)) self.norm = nn.LayerNorm(embed_dim)
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def forward(self, x): x = self.proj(x) _, _, H, W = x.shape x = x.flatten(2).transpose(1, 2) x = self.norm(x)
return x, H, W
class PyramidVisionTransformerImpr(nn.Module): def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512], num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm, depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]): super().__init__() self.num_classes = num_classes self.depths = depths
# patch_embed self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels, embed_dim=embed_dims[0]) self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0], embed_dim=embed_dims[1]) self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1], embed_dim=embed_dims[2]) self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2], embed_dim=embed_dims[3])
# transformer encoder dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule cur = 0 self.block1 = nn.ModuleList([Block( dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[0]) for i in range(depths[0])]) self.norm1 = norm_layer(embed_dims[0])
cur += depths[0] self.block2 = nn.ModuleList([Block( dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[1]) for i in range(depths[1])]) self.norm2 = norm_layer(embed_dims[1])
cur += depths[1] self.block3 = nn.ModuleList([Block( dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[2]) for i in range(depths[2])]) self.norm3 = norm_layer(embed_dims[2])
cur += depths[2] self.block4 = nn.ModuleList([Block( dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[3]) for i in range(depths[3])]) self.norm4 = norm_layer(embed_dims[3])
# classification head # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def init_weights(self, pretrained=None): if isinstance(pretrained, str): logger = 1 #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
def reset_drop_path(self, drop_path_rate): dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))] cur = 0 for i in range(self.depths[0]): self.block1[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[0] for i in range(self.depths[1]): self.block2[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[1] for i in range(self.depths[2]): self.block3[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[2] for i in range(self.depths[3]): self.block4[i].drop_path.drop_prob = dpr[cur + i]
def freeze_patch_emb(self): self.patch_embed1.requires_grad = False
@torch.jit.ignore def no_weight_decay(self): return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
def get_classifier(self): return self.head
def reset_classifier(self, num_classes, global_pool=''): self.num_classes = num_classes self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
def forward_features(self, x): B = x.shape[0] outs = []
# stage 1 x, H, W = self.patch_embed1(x) for i, blk in enumerate(self.block1): x = blk(x, H, W) x = self.norm1(x) x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() outs.append(x)
# stage 2 x, H, W = self.patch_embed2(x) for i, blk in enumerate(self.block2): x = blk(x, H, W) x = self.norm2(x) x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() outs.append(x)
# stage 3 x, H, W = self.patch_embed3(x) for i, blk in enumerate(self.block3): x = blk(x, H, W) x = self.norm3(x) x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() outs.append(x)
# stage 4 x, H, W = self.patch_embed4(x) for i, blk in enumerate(self.block4): x = blk(x, H, W) x = self.norm4(x) x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() outs.append(x)
return outs
# return x.mean(dim=1)
def forward(self, x): x = self.forward_features(x) # x = self.head(x)
return x
class DWConv(nn.Module): def __init__(self, dim=768): super(DWConv, self).__init__() self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
def forward(self, x, H, W): B, N, C = x.shape x = x.transpose(1, 2).view(B, C, H, W).contiguous() x = self.dwconv(x) x = x.flatten(2).transpose(1, 2)
return x
def _conv_filter(state_dict, patch_size=16): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k: v = v.reshape((v.shape[0], 3, patch_size, patch_size)) out_dict[k] = v
return out_dict
## @register_modelclass pvt_v2_b0(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b0, self).__init__( patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
## @register_modelclass pvt_v2_b1(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b1, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
## @register_modelclass pvt_v2_b2(PyramidVisionTransformerImpr): def __init__(self, in_channels=3, **kwargs): super(pvt_v2_b2, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)
## @register_modelclass pvt_v2_b3(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b3, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
## @register_modelclass pvt_v2_b4(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b4, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
## @register_modelclass pvt_v2_b5(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b5, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
### models/backbones/swin_v1.py
# --------------------------------------------------------# Swin Transformer# Copyright (c) 2021 Microsoft# Licensed under The MIT License [see LICENSE for details]# Written by Ze Liu, Yutong Lin, Yixuan Wei# --------------------------------------------------------
import torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.utils.checkpoint as checkpointimport numpy as npfrom timm.models.layers import DropPath, to_2tuple, trunc_normal_
# from config import Config
# config = Config()
class Mlp(nn.Module): """ Multilayer perceptron."""
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop)
def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x
def window_partition(x, window_size): """ Args: x: (B, H, W, C) window_size (int): window size
Returns: windows: (num_windows*B, window_size, window_size, C) """ B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) return windows
def window_reverse(windows, window_size, H, W): """ Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image
Returns: x: (B, H, W, C) """ B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return x
class WindowAttention(nn.Module): """ Window based multi-head self attention (W-MSA) module with relative position bias. It supports both of shifted and non-shifted window.
Args: dim (int): Number of input channels. window_size (tuple[int]): The height and width of the window. num_heads (int): Number of attention heads. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 proj_drop (float, optional): Dropout ratio of output. Default: 0.0 """
def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
super().__init__() self.dim = dim self.window_size = window_size # Wh, Ww self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5
# define a parameter table of relative position bias self.relative_position_bias_table = nn.Parameter( torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
# get pair-wise relative position index for each token inside the window coords_h = torch.arange(self.window_size[0]) coords_w = torch.arange(self.window_size[1]) coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 relative_coords[:, :, 1] += self.window_size[1] - 1 relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww self.register_buffer("relative_position_index", relative_position_index)
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop_prob = attn_drop self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop)
trunc_normal_(self.relative_position_bias_table, std=.02) self.softmax = nn.Softmax(dim=-1)
def forward(self, x, mask=None): """ Forward function.
Args: x: input features with shape of (num_windows*B, N, C) mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None """ B_, N, C = x.shape qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
q = q * self.scale
if config.SDPA_enabled: x = torch.nn.functional.scaled_dot_product_attention( q, k, v, attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False ).transpose(1, 2).reshape(B_, N, C) else: attn = (q @ k.transpose(-2, -1))
relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1 ) # Wh*Ww, Wh*Ww, nH relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww attn = attn + relative_position_bias.unsqueeze(0)
if mask is not None: nW = mask.shape[0] attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) attn = attn.view(-1, self.num_heads, N, N) attn = self.softmax(attn) else: attn = self.softmax(attn)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B_, N, C) x = self.proj(x) x = self.proj_drop(x) return x
class SwinTransformerBlock(nn.Module): """ Swin Transformer Block.
Args: dim (int): Number of input channels. num_heads (int): Number of attention heads. window_size (int): Window size. shift_size (int): Shift size for SW-MSA. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. drop (float, optional): Dropout rate. Default: 0.0 attn_drop (float, optional): Attention dropout rate. Default: 0.0 drop_path (float, optional): Stochastic depth rate. Default: 0.0 act_layer (nn.Module, optional): Activation layer. Default: nn.GELU norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """
def __init__(self, dim, num_heads, window_size=7, shift_size=0, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.dim = dim self.num_heads = num_heads self.window_size = window_size self.shift_size = shift_size self.mlp_ratio = mlp_ratio assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
self.norm1 = norm_layer(dim) self.attn = WindowAttention( dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.H = None self.W = None
def forward(self, x, mask_matrix): """ Forward function.
Args: x: Input feature, tensor size (B, H*W, C). H, W: Spatial resolution of the input feature. mask_matrix: Attention mask for cyclic shift. """ B, L, C = x.shape H, W = self.H, self.W assert L == H * W, "input feature has wrong size"
shortcut = x x = self.norm1(x) x = x.view(B, H, W, C)
# pad feature maps to multiples of window size pad_l = pad_t = 0 pad_r = (self.window_size - W % self.window_size) % self.window_size pad_b = (self.window_size - H % self.window_size) % self.window_size x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) _, Hp, Wp, _ = x.shape
# cyclic shift if self.shift_size > 0: shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) attn_mask = mask_matrix else: shifted_x = x attn_mask = None
# partition windows x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
# W-MSA/SW-MSA attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
# merge windows attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
# reverse cyclic shift if self.shift_size > 0: x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) else: x = shifted_x
if pad_r > 0 or pad_b > 0: x = x[:, :H, :W, :].contiguous()
x = x.view(B, H * W, C)
# FFN x = shortcut + self.drop_path(x) x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
class PatchMerging(nn.Module): """ Patch Merging Layer
Args: dim (int): Number of input channels. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """ def __init__(self, dim, norm_layer=nn.LayerNorm): super().__init__() self.dim = dim self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) self.norm = norm_layer(4 * dim)
def forward(self, x, H, W): """ Forward function.
Args: x: Input feature, tensor size (B, H*W, C). H, W: Spatial resolution of the input feature. """ B, L, C = x.shape assert L == H * W, "input feature has wrong size"
x = x.view(B, H, W, C)
# padding pad_input = (H % 2 == 1) or (W % 2 == 1) if pad_input: x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
x = self.norm(x) x = self.reduction(x)
return x
class BasicLayer(nn.Module): """ A basic Swin Transformer layer for one stage.
Args: dim (int): Number of feature channels depth (int): Depths of this stage. num_heads (int): Number of attention head. window_size (int): Local window size. Default: 7. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. drop (float, optional): Dropout rate. Default: 0.0 attn_drop (float, optional): Attention dropout rate. Default: 0.0 drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. """
def __init__(self, dim, depth, num_heads, window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False): super().__init__() self.window_size = window_size self.shift_size = window_size // 2 self.depth = depth self.use_checkpoint = use_checkpoint
# build blocks self.blocks = nn.ModuleList([ SwinTransformerBlock( dim=dim, num_heads=num_heads, window_size=window_size, shift_size=0 if (i % 2 == 0) else window_size // 2, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop, attn_drop=attn_drop, drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, norm_layer=norm_layer) for i in range(depth)])
# patch merging layer if downsample is not None: self.downsample = downsample(dim=dim, norm_layer=norm_layer) else: self.downsample = None
def forward(self, x, H, W): """ Forward function.
Args: x: Input feature, tensor size (B, H*W, C). H, W: Spatial resolution of the input feature. """
# calculate attention mask for SW-MSA # Turn int to torch.tensor for the compatiability with torch.compile in PyTorch 2.5. Hp = torch.ceil(torch.tensor(H) / self.window_size).to(torch.int64) * self.window_size Wp = torch.ceil(torch.tensor(W) / self.window_size).to(torch.int64) * self.window_size img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1 h_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) w_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) cnt = 0 for h in h_slices: for w in w_slices: img_mask[:, h, w, :] = cnt cnt += 1
mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1 mask_windows = mask_windows.view(-1, self.window_size * self.window_size) attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)).to(x.dtype)
for blk in self.blocks: blk.H, blk.W = H, W if self.use_checkpoint: x = checkpoint.checkpoint(blk, x, attn_mask) else: x = blk(x, attn_mask) if self.downsample is not None: x_down = self.downsample(x, H, W) Wh, Ww = (H + 1) // 2, (W + 1) // 2 return x, H, W, x_down, Wh, Ww else: return x, H, W, x, H, W
class PatchEmbed(nn.Module): """ Image to Patch Embedding
Args: patch_size (int): Patch token size. Default: 4. in_channels (int): Number of input image channels. Default: 3. embed_dim (int): Number of linear projection output channels. Default: 96. norm_layer (nn.Module, optional): Normalization layer. Default: None """
def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None): super().__init__() patch_size = to_2tuple(patch_size) self.patch_size = patch_size
self.in_channels = in_channels self.embed_dim = embed_dim
self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size) if norm_layer is not None: self.norm = norm_layer(embed_dim) else: self.norm = None
def forward(self, x): """Forward function.""" # padding _, _, H, W = x.size() if W % self.patch_size[1] != 0: x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1])) if H % self.patch_size[0] != 0: x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
x = self.proj(x) # B C Wh Ww if self.norm is not None: Wh, Ww = x.size(2), x.size(3) x = x.flatten(2).transpose(1, 2) x = self.norm(x) x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
return x
class SwinTransformer(nn.Module): """ Swin Transformer backbone. A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - https://arxiv.org/pdf/2103.14030
Args: pretrain_img_size (int): Input image size for training the pretrained model, used in absolute postion embedding. Default 224. patch_size (int | tuple(int)): Patch size. Default: 4. in_channels (int): Number of input image channels. Default: 3. embed_dim (int): Number of linear projection output channels. Default: 96. depths (tuple[int]): Depths of each Swin Transformer stage. num_heads (tuple[int]): Number of attention head of each stage. window_size (int): Window size. Default: 7. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. drop_rate (float): Dropout rate. attn_drop_rate (float): Attention dropout rate. Default: 0. drop_path_rate (float): Stochastic depth rate. Default: 0.2. norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. ape (bool): If True, add absolute position embedding to the patch embedding. Default: False. patch_norm (bool): If True, add normalization after patch embedding. Default: True. out_indices (Sequence[int]): Output from which stages. frozen_stages (int): Stages to be frozen (stop grad and set eval mode). -1 means not freezing any parameters. use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. """
def __init__(self, pretrain_img_size=224, patch_size=4, in_channels=3, embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.2, norm_layer=nn.LayerNorm, ape=False, patch_norm=True, out_indices=(0, 1, 2, 3), frozen_stages=-1, use_checkpoint=False): super().__init__()
self.pretrain_img_size = pretrain_img_size self.num_layers = len(depths) self.embed_dim = embed_dim self.ape = ape self.patch_norm = patch_norm self.out_indices = out_indices self.frozen_stages = frozen_stages
# split image into non-overlapping patches self.patch_embed = PatchEmbed( patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim, norm_layer=norm_layer if self.patch_norm else None)
# absolute position embedding if self.ape: pretrain_img_size = to_2tuple(pretrain_img_size) patch_size = to_2tuple(patch_size) patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1])) trunc_normal_(self.absolute_pos_embed, std=.02)
self.pos_drop = nn.Dropout(p=drop_rate)
# stochastic depth dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
# build layers self.layers = nn.ModuleList() for i_layer in range(self.num_layers): layer = BasicLayer( dim=int(embed_dim * 2 ** i_layer), depth=depths[i_layer], num_heads=num_heads[i_layer], window_size=window_size, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], norm_layer=norm_layer, downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, use_checkpoint=use_checkpoint) self.layers.append(layer)
num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)] self.num_features = num_features
# add a norm layer for each output for i_layer in out_indices: layer = norm_layer(num_features[i_layer]) layer_name = f'norm{i_layer}' self.add_module(layer_name, layer)
self._freeze_stages()
def _freeze_stages(self): if self.frozen_stages >= 0: self.patch_embed.eval() for param in self.patch_embed.parameters(): param.requires_grad = False
if self.frozen_stages >= 1 and self.ape: self.absolute_pos_embed.requires_grad = False
if self.frozen_stages >= 2: self.pos_drop.eval() for i in range(0, self.frozen_stages - 1): m = self.layers[i] m.eval() for param in m.parameters(): param.requires_grad = False
def forward(self, x): """Forward function.""" x = self.patch_embed(x)
Wh, Ww = x.size(2), x.size(3) if self.ape: # interpolate the position embedding to the corresponding size absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic') x = (x + absolute_pos_embed) # B Wh*Ww C outs = []#x.contiguous()] x = x.flatten(2).transpose(1, 2) x = self.pos_drop(x) for i in range(self.num_layers): layer = self.layers[i] x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
if i in self.out_indices: norm_layer = getattr(self, f'norm{i}') x_out = norm_layer(x_out)
out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous() outs.append(out)
return tuple(outs)
def train(self, mode=True): """Convert the model into training mode while keep layers freezed.""" super(SwinTransformer, self).train(mode) self._freeze_stages()
def swin_v1_t(): model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7) return model
def swin_v1_s(): model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7) return model
def swin_v1_b(): model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12) return model
def swin_v1_l(): model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12) return model
### models/modules/deform_conv.py
import torchimport torch.nn as nnfrom torchvision.ops import deform_conv2d
class DeformableConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False):
super(DeformableConv2d, self).__init__() assert type(kernel_size) == tuple or type(kernel_size) == int
kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size) self.stride = stride if type(stride) == tuple else (stride, stride) self.padding = padding self.offset_conv = nn.Conv2d(in_channels, 2 * kernel_size[0] * kernel_size[1], kernel_size=kernel_size, stride=stride, padding=self.padding, bias=True)
nn.init.constant_(self.offset_conv.weight, 0.) nn.init.constant_(self.offset_conv.bias, 0.) self.modulator_conv = nn.Conv2d(in_channels, 1 * kernel_size[0] * kernel_size[1], kernel_size=kernel_size, stride=stride, padding=self.padding, bias=True)
nn.init.constant_(self.modulator_conv.weight, 0.) nn.init.constant_(self.modulator_conv.bias, 0.)
self.regular_conv = nn.Conv2d(in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=self.padding, bias=bias)
def forward(self, x): #h, w = x.shape[2:] #max_offset = max(h, w)/4.
offset = self.offset_conv(x)#.clamp(-max_offset, max_offset) modulator = 2. * torch.sigmoid(self.modulator_conv(x)) x = deform_conv2d( input=x, offset=offset, weight=self.regular_conv.weight, bias=self.regular_conv.bias, padding=self.padding, mask=modulator, stride=self.stride, ) return x
### utils.py
import torch.nn as nn
def build_act_layer(act_layer): if act_layer == 'ReLU': return nn.ReLU(inplace=True) elif act_layer == 'SiLU': return nn.SiLU(inplace=True) elif act_layer == 'GELU': return nn.GELU()
raise NotImplementedError(f'build_act_layer does not support {act_layer}')
def build_norm_layer(dim, norm_layer, in_format='channels_last', out_format='channels_last', eps=1e-6): layers = [] if norm_layer == 'BN': if in_format == 'channels_last': layers.append(to_channels_first()) layers.append(nn.BatchNorm2d(dim)) if out_format == 'channels_last': layers.append(to_channels_last()) elif norm_layer == 'LN': if in_format == 'channels_first': layers.append(to_channels_last()) layers.append(nn.LayerNorm(dim, eps=eps)) if out_format == 'channels_first': layers.append(to_channels_first()) else: raise NotImplementedError( f'build_norm_layer does not support {norm_layer}') return nn.Sequential(*layers)
class to_channels_first(nn.Module):
def __init__(self): super().__init__()
def forward(self, x): return x.permute(0, 3, 1, 2)
class to_channels_last(nn.Module):
def __init__(self): super().__init__()
def forward(self, x): return x.permute(0, 2, 3, 1)
### dataset.py
_class_labels_TR_sorted = ( 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, ' 'BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, ' 'CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, ' 'Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, ' 'Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, ' 'Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, ' 'KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, ' 'Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, ' 'OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, ' 'RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, ' 'ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, ' 'Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, ' 'TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, ' 'UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht')class_labels_TR_sorted = _class_labels_TR_sorted.split(', ')
### models/backbones/build_backbones.py
import torchimport torch.nn as nnfrom collections import OrderedDictfrom torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights# from models.pvt_v2 import pvt_v2_b0, pvt_v2_b1, pvt_v2_b2, pvt_v2_b5# from models.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l# from config import Config
config = Config()
def build_backbone(bb_name, pretrained=True, params_settings=''): if bb_name == 'vgg16': bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0] bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]})) elif bb_name == 'vgg16bn': bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0] bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]})) elif bb_name == 'resnet50': bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children()) bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]})) else: bb = eval('{}({})'.format(bb_name, params_settings)) if pretrained: bb = load_weights(bb, bb_name) return bb
def load_weights(model, model_name): save_model = torch.load(config.weights[model_name], map_location='cpu') model_dict = model.state_dict() 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()} # to ignore the weights with mismatched size when I modify the backbone itself. if not state_dict: save_model_keys = list(save_model.keys()) sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None 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()} if not state_dict or not sub_item: print('Weights are not successully loaded. Check the state dict of weights file.') return None else: print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item)) model_dict.update(state_dict) model.load_state_dict(model_dict) return model
### models/modules/decoder_blocks.py
import torchimport torch.nn as nn# from models.aspp import ASPP, ASPPDeformable# from config import Config
# config = Config()
class BasicDecBlk(nn.Module): def __init__(self, in_channels=64, out_channels=64, inter_channels=64): super(BasicDecBlk, self).__init__() inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1) self.relu_in = nn.ReLU(inplace=True) if config.dec_att == 'ASPP': self.dec_att = ASPP(in_channels=inter_channels) elif config.dec_att == 'ASPPDeformable': self.dec_att = ASPPDeformable(in_channels=inter_channels) self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1) self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity() self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
def forward(self, x): x = self.conv_in(x) x = self.bn_in(x) x = self.relu_in(x) if hasattr(self, 'dec_att'): x = self.dec_att(x) x = self.conv_out(x) x = self.bn_out(x) return x
class ResBlk(nn.Module): def __init__(self, in_channels=64, out_channels=None, inter_channels=64): super(ResBlk, self).__init__() if out_channels is None: out_channels = in_channels inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1) self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity() self.relu_in = nn.ReLU(inplace=True)
if config.dec_att == 'ASPP': self.dec_att = ASPP(in_channels=inter_channels) elif config.dec_att == 'ASPPDeformable': self.dec_att = ASPPDeformable(in_channels=inter_channels)
self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1) self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity() self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
def forward(self, x): _x = self.conv_resi(x) x = self.conv_in(x) x = self.bn_in(x) x = self.relu_in(x) if hasattr(self, 'dec_att'): x = self.dec_att(x) x = self.conv_out(x) x = self.bn_out(x) return x + _x
### models/modules/lateral_blocks.py
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom functools import partial
# from config import Config
# config = Config()
class BasicLatBlk(nn.Module): def __init__(self, in_channels=64, out_channels=64, inter_channels=64): super(BasicLatBlk, self).__init__() inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
def forward(self, x): x = self.conv(x) return x
### models/modules/aspp.py
import torchimport torch.nn as nnimport torch.nn.functional as F# from models.deform_conv import DeformableConv2d# from config import Config
# config = Config()
class _ASPPModule(nn.Module): def __init__(self, in_channels, planes, kernel_size, padding, dilation): super(_ASPPModule, self).__init__() self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size, stride=1, padding=padding, dilation=dilation, bias=False) self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity() self.relu = nn.ReLU(inplace=True)
def forward(self, x): x = self.atrous_conv(x) x = self.bn(x)
return self.relu(x)
class ASPP(nn.Module): def __init__(self, in_channels=64, out_channels=None, output_stride=16): super(ASPP, self).__init__() self.down_scale = 1 if out_channels is None: out_channels = in_channels self.in_channelster = 256 // self.down_scale if output_stride == 16: dilations = [1, 6, 12, 18] elif output_stride == 8: dilations = [1, 12, 24, 36] else: raise NotImplementedError
self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0]) self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1]) self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2]) self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3])
self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True)) self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False) self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity() self.relu = nn.ReLU(inplace=True) self.dropout = nn.Dropout(0.5)
def forward(self, x): x1 = self.aspp1(x) x2 = self.aspp2(x) x3 = self.aspp3(x) x4 = self.aspp4(x) x5 = self.global_avg_pool(x) x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) x = torch.cat((x1, x2, x3, x4, x5), dim=1)
x = self.conv1(x) x = self.bn1(x) x = self.relu(x)
return self.dropout(x)
##################### Deformableclass _ASPPModuleDeformable(nn.Module): def __init__(self, in_channels, planes, kernel_size, padding): super(_ASPPModuleDeformable, self).__init__() self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size, stride=1, padding=padding, bias=False) self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity() self.relu = nn.ReLU(inplace=True)
def forward(self, x): x = self.atrous_conv(x) x = self.bn(x)
return self.relu(x)
class ASPPDeformable(nn.Module): def __init__(self, in_channels, out_channels=None, parallel_block_sizes=[1, 3, 7]): super(ASPPDeformable, self).__init__() self.down_scale = 1 if out_channels is None: out_channels = in_channels self.in_channelster = 256 // self.down_scale
self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0) self.aspp_deforms = nn.ModuleList([ _ASPPModuleDeformable(in_channels, self.in_channelster, conv_size, padding=int(conv_size//2)) for conv_size in parallel_block_sizes ])
self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True)) self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False) self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity() self.relu = nn.ReLU(inplace=True) self.dropout = nn.Dropout(0.5)
def forward(self, x): x1 = self.aspp1(x) x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms] x5 = self.global_avg_pool(x) x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) x = torch.cat((x1, *x_aspp_deforms, x5), dim=1)
x = self.conv1(x) x = self.bn1(x) x = self.relu(x)
return self.dropout(x)
### models/refinement/refiner.py
import torchimport torch.nn as nnfrom collections import OrderedDictimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torchvision.models import vgg16, vgg16_bnfrom torchvision.models import resnet50
# from config import Config# from dataset import class_labels_TR_sorted# from models.build_backbone import build_backbone# from models.decoder_blocks import BasicDecBlk# from models.lateral_blocks import BasicLatBlk# from models.ing import *# from models.stem_layer import StemLayer
class RefinerPVTInChannels4(nn.Module): def __init__(self, in_channels=3+1): super(RefinerPVTInChannels4, self).__init__() self.config = Config() self.epoch = 1 self.bb = build_backbone(self.config.bb, params_settings='in_channels=4')
lateral_channels_in_collection = { 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], } channels = lateral_channels_in_collection[self.config.bb] self.squeeze_module = BasicDecBlk(channels[0], channels[0])
self.decoder = Decoder(channels)
if 0: for key, value in self.named_parameters(): if 'bb.' in key: value.requires_grad = False
def forward(self, x): if isinstance(x, list): x = torch.cat(x, dim=1) ########## Encoder ########## if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: x1 = self.bb.conv1(x) x2 = self.bb.conv2(x1) x3 = self.bb.conv3(x2) x4 = self.bb.conv4(x3) else: x1, x2, x3, x4 = self.bb(x)
x4 = self.squeeze_module(x4)
########## Decoder ##########
features = [x, x1, x2, x3, x4] scaled_preds = self.decoder(features)
return scaled_preds
class Refiner(nn.Module): def __init__(self, in_channels=3+1): super(Refiner, self).__init__() self.config = Config() self.epoch = 1 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') self.bb = build_backbone(self.config.bb)
lateral_channels_in_collection = { 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], } channels = lateral_channels_in_collection[self.config.bb] self.squeeze_module = BasicDecBlk(channels[0], channels[0])
self.decoder = Decoder(channels)
if 0: for key, value in self.named_parameters(): if 'bb.' in key: value.requires_grad = False
def forward(self, x): if isinstance(x, list): x = torch.cat(x, dim=1) x = self.stem_layer(x) ########## Encoder ########## if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: x1 = self.bb.conv1(x) x2 = self.bb.conv2(x1) x3 = self.bb.conv3(x2) x4 = self.bb.conv4(x3) else: x1, x2, x3, x4 = self.bb(x)
x4 = self.squeeze_module(x4)
########## Decoder ##########
features = [x, x1, x2, x3, x4] scaled_preds = self.decoder(features)
return scaled_preds
class Decoder(nn.Module): def __init__(self, channels): super(Decoder, self).__init__() self.config = Config() DecoderBlock = eval('BasicDecBlk') LateralBlock = eval('BasicLatBlk')
self.decoder_block4 = DecoderBlock(channels[0], channels[1]) self.decoder_block3 = DecoderBlock(channels[1], channels[2]) self.decoder_block2 = DecoderBlock(channels[2], channels[3]) self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2)
self.lateral_block4 = LateralBlock(channels[1], channels[1]) self.lateral_block3 = LateralBlock(channels[2], channels[2]) self.lateral_block2 = LateralBlock(channels[3], channels[3])
if self.config.ms_supervision: self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0) self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0) self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0) self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0))
def forward(self, features): x, x1, x2, x3, x4 = features outs = [] p4 = self.decoder_block4(x4) _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True) _p3 = _p4 + self.lateral_block4(x3)
p3 = self.decoder_block3(_p3) _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True) _p2 = _p3 + self.lateral_block3(x2)
p2 = self.decoder_block2(_p2) _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True) _p1 = _p2 + self.lateral_block2(x1)
_p1 = self.decoder_block1(_p1) _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True) p1_out = self.conv_out1(_p1)
if self.config.ms_supervision: outs.append(self.conv_ms_spvn_4(p4)) outs.append(self.conv_ms_spvn_3(p3)) outs.append(self.conv_ms_spvn_2(p2)) outs.append(p1_out) return outs
class RefUNet(nn.Module): # Refinement def __init__(self, in_channels=3+1): super(RefUNet, self).__init__() self.encoder_1 = nn.Sequential( nn.Conv2d(in_channels, 64, 3, 1, 1), nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.encoder_2 = nn.Sequential( nn.MaxPool2d(2, 2, ceil_mode=True), nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.encoder_3 = nn.Sequential( nn.MaxPool2d(2, 2, ceil_mode=True), nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.encoder_4 = nn.Sequential( nn.MaxPool2d(2, 2, ceil_mode=True), nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True) ##### self.decoder_5 = nn.Sequential( nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) ) ##### self.decoder_4 = nn.Sequential( nn.Conv2d(128, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.decoder_3 = nn.Sequential( nn.Conv2d(128, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.decoder_2 = nn.Sequential( nn.Conv2d(128, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.decoder_1 = nn.Sequential( nn.Conv2d(128, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1)
self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
def forward(self, x): outs = [] if isinstance(x, list): x = torch.cat(x, dim=1) hx = x
hx1 = self.encoder_1(hx) hx2 = self.encoder_2(hx1) hx3 = self.encoder_3(hx2) hx4 = self.encoder_4(hx3)
hx = self.decoder_5(self.pool4(hx4)) hx = torch.cat((self.upscore2(hx), hx4), 1)
d4 = self.decoder_4(hx) hx = torch.cat((self.upscore2(d4), hx3), 1)
d3 = self.decoder_3(hx) hx = torch.cat((self.upscore2(d3), hx2), 1)
d2 = self.decoder_2(hx) hx = torch.cat((self.upscore2(d2), hx1), 1)
d1 = self.decoder_1(hx)
x = self.conv_d0(d1) outs.append(x) return outs
### models/stem_layer.py
import torch.nn as nn# from utils import build_act_layer, build_norm_layer
class StemLayer(nn.Module): r""" Stem layer of InternImage Args: in_channels (int): number of input channels out_channels (int): number of output channels act_layer (str): activation layer norm_layer (str): normalization layer """
def __init__(self, in_channels=3+1, inter_channels=48, out_channels=96, act_layer='GELU', norm_layer='BN'): super().__init__() self.conv1 = nn.Conv2d(in_channels, inter_channels, kernel_size=3, stride=1, padding=1) self.norm1 = build_norm_layer( inter_channels, norm_layer, 'channels_first', 'channels_first' ) self.act = build_act_layer(act_layer) self.conv2 = nn.Conv2d(inter_channels, out_channels, kernel_size=3, stride=1, padding=1) self.norm2 = build_norm_layer( out_channels, norm_layer, 'channels_first', 'channels_first' )
def forward(self, x): x = self.conv1(x) x = self.norm1(x) x = self.act(x) x = self.conv2(x) x = self.norm2(x) return x
### models/birefnet.py
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom kornia.filters import laplacianfrom transformers import PreTrainedModelfrom einops import rearrange
# from config import Config# from dataset import class_labels_TR_sorted# from models.build_backbone import build_backbone# from models.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk# from models.lateral_blocks import BasicLatBlk# from models.aspp import ASPP, ASPPDeformable# from models.ing import *# from models.refiner import Refiner, RefinerPVTInChannels4, RefUNet# from models.stem_layer import StemLayerfrom .BiRefNet_config import BiRefNetConfig
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'): if patch_ref is not None: grid_h, grid_w = image.shape[-2] // patch_ref.shape[-2], image.shape[-1] // patch_ref.shape[-1] patches = rearrange(image, transformation, hg=grid_h, wg=grid_w) return patches
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)'): if patch_ref is not None: grid_h, grid_w = patch_ref.shape[-2] // patches[0].shape[-2], patch_ref.shape[-1] // patches[0].shape[-1] image = rearrange(patches, transformation, hg=grid_h, wg=grid_w) return image
class BiRefNet( PreTrainedModel): config_class = BiRefNetConfig def __init__(self, bb_pretrained=True, config=BiRefNetConfig()): super(BiRefNet, self).__init__(config) bb_pretrained = config.bb_pretrained self.config = Config() self.epoch = 1 self.bb = build_backbone(self.config.bb, pretrained=bb_pretrained)
channels = self.config.lateral_channels_in_collection
if self.config.auxiliary_classification: self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.cls_head = nn.Sequential( nn.Linear(channels[0], len(class_labels_TR_sorted)) )
if self.config.squeeze_block: self.squeeze_module = nn.Sequential(*[ eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0]) for _ in range(eval(self.config.squeeze_block.split('_x')[1])) ])
self.decoder = Decoder(channels)
if self.config.ender: self.dec_end = nn.Sequential( nn.Conv2d(1, 16, 3, 1, 1), nn.Conv2d(16, 1, 3, 1, 1), nn.ReLU(inplace=True), )
# refine patch-level segmentation if self.config.refine: if self.config.refine == 'itself': 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') else: self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1'))
if self.config.freeze_bb: # Freeze the backbone... print(self.named_parameters()) for key, value in self.named_parameters(): if 'bb.' in key and 'refiner.' not in key: value.requires_grad = False
def forward_enc(self, x): if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3) else: x1, x2, x3, x4 = self.bb(x) if self.config.mul_scl_ipt == 'cat': B, C, H, W = x.shape x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True)) x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1) x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1) x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1) x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1) elif self.config.mul_scl_ipt == 'add': B, C, H, W = x.shape x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True)) x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True) x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True) x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True) x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True) class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None if self.config.cxt: x4 = torch.cat( ( *[ F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True), F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True), F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True), ][-len(self.config.cxt):], x4 ), dim=1 ) return (x1, x2, x3, x4), class_preds
def forward_ori(self, x): ########## Encoder ########## (x1, x2, x3, x4), class_preds = self.forward_enc(x) if self.config.squeeze_block: x4 = self.squeeze_module(x4) ########## Decoder ########## features = [x, x1, x2, x3, x4] if self.training and self.config.out_ref: features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5)) scaled_preds = self.decoder(features) return scaled_preds, class_preds
def forward(self, x): scaled_preds, class_preds = self.forward_ori(x) class_preds_lst = [class_preds] return [scaled_preds, class_preds_lst] if self.training else scaled_preds
class Decoder(nn.Module): def __init__(self, channels): super(Decoder, self).__init__() self.config = Config() DecoderBlock = eval(self.config.dec_blk) LateralBlock = eval(self.config.lat_blk)
if self.config.dec_ipt: self.split = self.config.dec_ipt_split N_dec_ipt = 64 DBlock = SimpleConvs ic = 64 ipt_cha_opt = 1 self.ipt_blk5 = DBlock(2**10*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic) self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic) self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic) self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic) self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic) else: self.split = None
self.decoder_block4 = DecoderBlock(channels[0]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[1]) self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2]) self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]) 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) 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))
self.lateral_block4 = LateralBlock(channels[1], channels[1]) self.lateral_block3 = LateralBlock(channels[2], channels[2]) self.lateral_block2 = LateralBlock(channels[3], channels[3])
if self.config.ms_supervision: self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0) self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0) self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
if self.config.out_ref: _N = 16 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)) 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)) 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))
self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
def forward(self, features): if self.training and self.config.out_ref: outs_gdt_pred = [] outs_gdt_label = [] x, x1, x2, x3, x4, gdt_gt = features else: x, x1, x2, x3, x4 = features outs = []
if self.config.dec_ipt: 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 x4 = torch.cat((x4, self.ipt_blk5(F.interpolate(patches_batch, size=x4.shape[2:], mode='bilinear', align_corners=True))), 1) p4 = self.decoder_block4(x4) m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision and self.training else None if self.config.out_ref: p4_gdt = self.gdt_convs_4(p4) if self.training: # >> GT: m4_dia = m4 gdt_label_main_4 = gdt_gt * F.interpolate(m4_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) outs_gdt_label.append(gdt_label_main_4) # >> Pred: gdt_pred_4 = self.gdt_convs_pred_4(p4_gdt) outs_gdt_pred.append(gdt_pred_4) gdt_attn_4 = self.gdt_convs_attn_4(p4_gdt).sigmoid() # >> Finally: p4 = p4 * gdt_attn_4 _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True) _p3 = _p4 + self.lateral_block4(x3)
if self.config.dec_ipt: 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 _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1) p3 = self.decoder_block3(_p3) m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision and self.training else None if self.config.out_ref: p3_gdt = self.gdt_convs_3(p3) if self.training: # >> GT: # m3 --dilation--> m3_dia # G_3^gt * m3_dia --> G_3^m, which is the label of gradient m3_dia = m3 gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) outs_gdt_label.append(gdt_label_main_3) # >> Pred: # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx # F_3^G --sigmoid--> A_3^G gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt) outs_gdt_pred.append(gdt_pred_3) gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid() # >> Finally: # p3 = p3 * A_3^G p3 = p3 * gdt_attn_3 _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True) _p2 = _p3 + self.lateral_block3(x2)
if self.config.dec_ipt: 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 _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1) p2 = self.decoder_block2(_p2) m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision and self.training else None if self.config.out_ref: p2_gdt = self.gdt_convs_2(p2) if self.training: # >> GT: m2_dia = m2 gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) outs_gdt_label.append(gdt_label_main_2) # >> Pred: gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt) outs_gdt_pred.append(gdt_pred_2) gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid() # >> Finally: p2 = p2 * gdt_attn_2 _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True) _p1 = _p2 + self.lateral_block2(x1)
if self.config.dec_ipt: 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 _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1) _p1 = self.decoder_block1(_p1) _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
if self.config.dec_ipt: 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 _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1) p1_out = self.conv_out1(_p1)
if self.config.ms_supervision and self.training: outs.append(m4) outs.append(m3) outs.append(m2) outs.append(p1_out) return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs)
class SimpleConvs(nn.Module): def __init__( self, in_channels: int, out_channels: int, inter_channels=64 ) -> None: super().__init__() self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1) self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)
def forward(self, x): return self.conv_out(self.conv1(x))1234567891011121314151617181920{ "_name_or_path": "ZhengPeng7/BiRefNet", "architectures": [ "BiRefNet" ], "auto_map": { "AutoConfig": "BiRefNet_config.BiRefNetConfig", "AutoModelForImageSegmentation": "birefnet.BiRefNet" }, "custom_pipelines": { "image-segmentation": { "pt": [ "AutoModelForImageSegmentation" ], "tf": [], "type": "image" } }, "bb_pretrained": false}123version https://git-lfs.github.com/spec/v1oid sha256:9ab37426bf4de0567af6b5d21b16151357149139362e6e8992021b8ce356a154size 444473596175de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2123456789101112{ "initializer_factor": 1.0, "model_type": "siglip", "text_config": { "model_type": "siglip_text_model", "vocab_size": 256000 }, "transformers_version": "4.49.0.dev0", "vision_config": { "model_type": "siglip_vision_model" }}123version https://git-lfs.github.com/spec/v1oid sha256:612923381c76ec5a9bed335d1c48827e3f2e506ac31b044b63b2031fadee6a0bsize 1500800904123456789101112131415161718192021222324{ "do_convert_rgb": null, "do_normalize": true, "do_rescale": true, "do_resize": true, "image_mean": [ 0.5, 0.5, 0.5 ], "image_processor_type": "SiglipImageProcessor", "image_std": [ 0.5, 0.5, 0.5 ], "processor_class": "SiglipProcessor", "resample": 2, "rescale_factor": 0.00392156862745098, "size": { "height": 224, "width": 224 }}12345678910111213141516171819202122232425262728293031323334{ "additional_special_tokens": [ "<start_of_turn>", "<end_of_turn>" ], "bos_token": { "content": "<bos>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": { "content": "<eos>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<pad>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "unk_token": { "content": "<unk>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}123version https://git-lfs.github.com/spec/v1oid sha256:cb9140fae3ac5122c972d37adf83e1248471a38147ad76f8215c8872c6fd8322size 34363039123version https://git-lfs.github.com/spec/v1oid sha256:61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2size 42410031234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020{ "add_bos_token": false, "add_eos_token": true, "added_tokens_decoder": { "0": { "content": "<pad>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "1": { "content": "<eos>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "2": { "content": "<bos>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "3": { "content": "<unk>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "4": { "content": "<mask>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "5": { "content": "<2mass>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "6": { "content": "[@BOS@]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "7": { "content": "<unused0>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "8": { "content": "<unused1>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "9": { "content": "<unused2>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "10": { "content": "<unused3>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "11": { "content": "<unused4>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "12": { "content": "<unused5>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "13": { "content": "<unused6>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "14": { "content": "<unused7>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "15": { "content": "<unused8>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "16": { "content": "<unused9>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "17": { "content": "<unused10>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "18": { "content": "<unused11>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "19": { "content": "<unused12>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "20": { "content": "<unused13>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "21": { "content": "<unused14>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "22": { "content": "<unused15>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "23": { "content": "<unused16>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "24": { "content": "<unused17>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "25": { "content": "<unused18>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "26": { "content": "<unused19>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "27": { "content": "<unused20>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "28": { "content": "<unused21>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "29": { "content": "<unused22>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "30": { "content": "<unused23>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "31": { "content": "<unused24>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "32": { "content": "<unused25>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "33": { "content": "<unused26>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "34": { "content": "<unused27>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "35": { "content": "<unused28>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "36": { "content": "<unused29>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "37": { "content": "<unused30>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "38": { "content": "<unused31>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "39": { "content": "<unused32>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "40": { "content": "<unused33>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "41": { "content": "<unused34>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "42": { "content": "<unused35>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "43": { "content": "<unused36>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "44": { "content": "<unused37>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "45": { "content": "<unused38>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "46": { "content": "<unused39>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "47": { "content": "<unused40>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "48": { "content": "<unused41>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "49": { "content": "<unused42>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "50": { "content": "<unused43>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "51": { "content": "<unused44>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "52": { "content": "<unused45>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "53": { "content": "<unused46>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "54": { "content": "<unused47>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "55": { "content": "<unused48>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "56": { "content": "<unused49>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "57": { "content": "<unused50>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "58": { "content": "<unused51>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "59": { "content": "<unused52>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "60": { "content": "<unused53>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "61": { "content": "<unused54>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "62": { "content": "<unused55>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "63": { "content": "<unused56>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "64": { "content": "<unused57>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "65": { "content": "<unused58>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "66": { "content": "<unused59>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "67": { "content": "<unused60>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "68": { "content": "<unused61>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "69": { "content": "<unused62>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "70": { "content": "<unused63>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "71": { "content": "<unused64>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "72": { "content": "<unused65>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "73": { "content": "<unused66>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "74": { "content": "<unused67>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "75": { "content": "<unused68>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "76": { "content": "<unused69>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "77": { "content": "<unused70>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "78": { "content": "<unused71>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "79": { "content": "<unused72>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "80": { "content": "<unused73>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "81": { "content": "<unused74>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "82": { "content": "<unused75>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "83": { "content": "<unused76>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "84": { "content": "<unused77>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "85": { "content": "<unused78>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "86": { "content": "<unused79>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "87": { "content": "<unused80>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "88": { "content": "<unused81>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "89": { "content": "<unused82>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "90": { "content": "<unused83>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "91": { "content": "<unused84>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "92": { "content": "<unused85>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "93": { "content": "<unused86>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "94": { "content": "<unused87>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "95": { "content": "<unused88>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "96": { "content": "<unused89>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "97": { "content": "<unused90>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "98": { "content": "<unused91>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "99": { "content": "<unused92>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "100": { "content": "<unused93>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "101": { "content": "<unused94>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "102": { "content": "<unused95>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "103": { "content": "<unused96>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "104": { "content": "<unused97>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "105": { "content": "<unused98>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "106": { "content": "<start_of_turn>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "107": { "content": "<end_of_turn>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "108": { "content": "\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "109": { "content": "\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "110": { "content": "\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "111": { "content": "\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "112": { "content": "\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "113": { "content": "\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "114": { "content": "\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "115": { "content": "\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "116": { "content": "\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "117": { "content": "\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "118": { "content": "\n\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "119": { "content": "\n\n\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "120": { "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "121": { "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "122": { "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "123": { "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "124": { "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "125": { "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "126": { "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "127": { "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "128": { "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "129": { "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "130": { "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "131": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "132": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "133": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "134": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "135": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "136": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "137": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "138": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "139": { "content": "▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "140": { "content": "▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "141": { "content": "▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "142": { "content": "▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "143": { "content": "▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "144": { "content": "▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "145": { "content": "▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "146": { "content": "▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "147": { "content": "▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "148": { "content": "▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "149": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "150": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "152": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "153": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "154": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "155": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "156": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "157": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "158": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "159": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "160": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "161": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "162": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "163": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "164": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "165": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "166": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "167": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "168": { "content": "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "169": { "content": "<table>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "170": { "content": "<caption>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "171": { "content": "<thead>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "172": { "content": "<tbody>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "173": { "content": "<tfoot>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "174": { "content": "<tr>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "175": { "content": "<th>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "176": { "content": "<td>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "177": { "content": "</table>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "178": { "content": "</caption>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "179": { "content": "</thead>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "180": { "content": "</tbody>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "181": { "content": "</tfoot>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "182": { "content": "</tr>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "183": { "content": "</th>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "184": { "content": "</td>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "185": { "content": "<h1>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "186": { "content": "<h2>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "187": { "content": "<h3>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "188": { "content": "<h4>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "189": { "content": "<h5>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "190": { "content": "<h6>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "191": { "content": "<blockquote>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "192": { "content": "</h1>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "193": { "content": "</h2>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "194": { "content": "</h3>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "195": { "content": "</h4>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "196": { "content": "</h5>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "197": { "content": "</h6>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "198": { "content": "</blockquote>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "199": { "content": "<strong>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "200": { "content": "<em>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "201": { "content": "<b>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "202": { "content": "<i>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "203": { "content": "<u>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "204": { "content": "<s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "205": { "content": "<sub>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "206": { "content": "<sup>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "207": { "content": "<code>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "208": { "content": "</strong>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "209": { "content": "</em>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "210": { "content": "</b>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "211": { "content": "</i>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "212": { "content": "</u>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "213": { "content": "</s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "214": { "content": "</sub>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "215": { "content": "</sup>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "216": { "content": "</code>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255968": { "content": "[toxicity=0]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255969": { "content": "\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255970": { "content": "\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255971": { "content": "\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255972": { "content": "\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255973": { "content": "\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255974": { "content": "\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255975": { "content": "\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255976": { "content": "\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255977": { "content": "\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255978": { "content": "\t\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255979": { "content": "\t\t\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255980": { "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255981": { "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255982": { "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255983": { "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255984": { "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255985": { "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255986": { "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255987": { "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255988": { "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255989": { "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255990": { "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255991": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255992": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255993": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255994": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255995": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255996": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255997": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255998": { "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", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "255999": { "content": "<unused99>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false } }, "additional_special_tokens": [ "<start_of_turn>", "<end_of_turn>" ], "bos_token": "<bos>", "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 %}", "clean_up_tokenization_spaces": false, "do_lower_case": true, "eos_token": "<eos>", "extra_special_tokens": {}, "model_input_names": [ "input_ids" ], "model_max_length": 1000000000000000019884624838656, "pad_token": "<pad>", "padding_side": "right", "processor_class": "SiglipProcessor", "sp_model_kwargs": {}, "spaces_between_special_tokens": false, "tokenizer_class": "GemmaTokenizer", "unk_token": "<unk>", "use_default_system_prompt": false}1234567891011from transformers import PretrainedConfig
class BiRefNetConfig(PretrainedConfig): model_type = "SegformerForSemanticSegmentation" def __init__( self, bb_pretrained=False, **kwargs ): self.bb_pretrained = bb_pretrained super().__init__(**kwargs)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249### config.py
import osimport mathfrom transformers import PretrainedConfig
class Config(PretrainedConfig): def __init__(self) -> None: # PATH settings 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
# TASK settings self.task = ['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'][0] self.training_set = { 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0], 'COD': 'TR-COD10K+TR-CAMO', '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], '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. 'P3M-10k': 'TR-P3M-10k', }[self.task] self.prompt4loc = ['dense', 'sparse'][0]
# Faster-Training settings self.load_all = True self.compile = True # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch. # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting. # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607. # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training. self.precisionHigh = True
# MODEL settings self.ms_supervision = True self.out_ref = self.ms_supervision and True self.dec_ipt = True self.dec_ipt_split = True self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder self.mul_scl_ipt = ['', 'add', 'cat'][2] self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2] self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1] self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0]
# TRAINING settings self.batch_size = 4 self.IoU_finetune_last_epochs = [ 0, { 'DIS5K': -50, 'COD': -20, 'HRSOD': -20, 'DIS5K+HRSOD+HRS10K': -20, 'P3M-10k': -20, }[self.task] ][1] # choose 0 to skip 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 self.size = 1024 self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader
# Backbone settings self.bb = [ 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2 'swin_v1_t', 'swin_v1_s', # 3, 4 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs4 'pvt_v2_b0', 'pvt_v2_b1', # 7, 8 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5 ][6] self.lateral_channels_in_collection = { 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96], 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64], }[self.bb] if self.mul_scl_ipt == 'cat': self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection] self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []
# MODEL settings - inactive self.lat_blk = ['BasicLatBlk'][0] self.dec_channels_inter = ['fixed', 'adap'][0] self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0] self.progressive_ref = self.refine and True self.ender = self.progressive_ref and False self.scale = self.progressive_ref and 2 self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`. self.refine_iteration = 1 self.freeze_bb = False self.model = [ 'BiRefNet', ][0] if self.dec_blk == 'HierarAttDecBlk': self.batch_size = 2 ** [0, 1, 2, 3, 4][2]
# TRAINING settings - inactive self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4] self.optimizer = ['Adam', 'AdamW'][1] self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch. self.lr_decay_rate = 0.5 # Loss self.lambdas_pix_last = { # not 0 means opening this loss # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30 'bce': 30 * 1, # high performance 'iou': 0.5 * 1, # 0 / 255 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64) 'mse': 150 * 0, # can smooth the saliency map 'triplet': 3 * 0, 'reg': 100 * 0, 'ssim': 10 * 1, # help contours, 'cnt': 5 * 0, # help contours '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. } self.lambdas_cls = { 'ce': 5.0 } # Adv self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training self.lambda_adv_d = 3. * (self.lambda_adv_g > 0)
# PATH settings - inactive self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis') self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights') self.weights = { 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'), 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]), '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]), '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]), 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]), 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]), 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]), 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]), }
# Callbacks - inactive self.verbose_eval = True self.only_S_MAE = False self.use_fp16 = False # Bugs. It may cause nan in training. self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs
# others self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')
self.batch_size_valid = 1 self.rand_seed = 7 # 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] # with open(run_sh_file[0], 'r') as f: # lines = f.readlines() # 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]) # 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]) # self.val_step = [0, self.save_step][0]
def print_task(self) -> None: # Return task for choosing settings in shell scripts. print(self.task)
### models/backbones/pvt_v2.py
import torchimport torch.nn as nnfrom functools import partial
from timm.models.layers import DropPath, to_2tuple, trunc_normal_from timm.models.registry import register_model
import math
# from config import Config
# config = Config()
class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.dwconv = DWConv(hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop)
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def forward(self, x, H, W): x = self.fc1(x) x = self.dwconv(x, H, W) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x
class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1): super().__init__() assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
self.dim = dim self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5
self.q = nn.Linear(dim, dim, bias=qkv_bias) self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias) self.attn_drop_prob = attn_drop self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop)
self.sr_ratio = sr_ratio if sr_ratio > 1: self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio) self.norm = nn.LayerNorm(dim)
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def forward(self, x, H, W): B, N, C = x.shape q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
if self.sr_ratio > 1: x_ = x.permute(0, 2, 1).reshape(B, C, H, W) x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1) x_ = self.norm(x_) kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) else: kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) k, v = kv[0], kv[1]
if config.SDPA_enabled: x = torch.nn.functional.scaled_dot_product_attention( q, k, v, attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False ).transpose(1, 2).reshape(B, N, C) else: attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x)
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio) # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def forward(self, x, H, W): x = x + self.drop_path(self.attn(self.norm1(x), H, W)) x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
return x
class OverlapPatchEmbed(nn.Module): """ Image to Patch Embedding """
def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size)
self.img_size = img_size self.patch_size = patch_size self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1] self.num_patches = self.H * self.W self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride, padding=(patch_size[0] // 2, patch_size[1] // 2)) self.norm = nn.LayerNorm(embed_dim)
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def forward(self, x): x = self.proj(x) _, _, H, W = x.shape x = x.flatten(2).transpose(1, 2) x = self.norm(x)
return x, H, W
class PyramidVisionTransformerImpr(nn.Module): def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512], num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm, depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]): super().__init__() self.num_classes = num_classes self.depths = depths
# patch_embed self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels, embed_dim=embed_dims[0]) self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0], embed_dim=embed_dims[1]) self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1], embed_dim=embed_dims[2]) self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2], embed_dim=embed_dims[3])
# transformer encoder dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule cur = 0 self.block1 = nn.ModuleList([Block( dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[0]) for i in range(depths[0])]) self.norm1 = norm_layer(embed_dims[0])
cur += depths[0] self.block2 = nn.ModuleList([Block( dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[1]) for i in range(depths[1])]) self.norm2 = norm_layer(embed_dims[1])
cur += depths[1] self.block3 = nn.ModuleList([Block( dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[2]) for i in range(depths[2])]) self.norm3 = norm_layer(embed_dims[2])
cur += depths[2] self.block4 = nn.ModuleList([Block( dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer, sr_ratio=sr_ratios[3]) for i in range(depths[3])]) self.norm4 = norm_layer(embed_dims[3])
# classification head # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
self.apply(self._init_weights)
def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) elif isinstance(m, nn.Conv2d): fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels fan_out //= m.groups m.weight.data.normal_(0, math.sqrt(2.0 / fan_out)) if m.bias is not None: m.bias.data.zero_()
def init_weights(self, pretrained=None): if isinstance(pretrained, str): logger = 1 #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
def reset_drop_path(self, drop_path_rate): dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))] cur = 0 for i in range(self.depths[0]): self.block1[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[0] for i in range(self.depths[1]): self.block2[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[1] for i in range(self.depths[2]): self.block3[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[2] for i in range(self.depths[3]): self.block4[i].drop_path.drop_prob = dpr[cur + i]
def freeze_patch_emb(self): self.patch_embed1.requires_grad = False
@torch.jit.ignore def no_weight_decay(self): return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
def get_classifier(self): return self.head
def reset_classifier(self, num_classes, global_pool=''): self.num_classes = num_classes self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
def forward_features(self, x): B = x.shape[0] outs = []
# stage 1 x, H, W = self.patch_embed1(x) for i, blk in enumerate(self.block1): x = blk(x, H, W) x = self.norm1(x) x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() outs.append(x)
# stage 2 x, H, W = self.patch_embed2(x) for i, blk in enumerate(self.block2): x = blk(x, H, W) x = self.norm2(x) x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() outs.append(x)
# stage 3 x, H, W = self.patch_embed3(x) for i, blk in enumerate(self.block3): x = blk(x, H, W) x = self.norm3(x) x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() outs.append(x)
# stage 4 x, H, W = self.patch_embed4(x) for i, blk in enumerate(self.block4): x = blk(x, H, W) x = self.norm4(x) x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() outs.append(x)
return outs
# return x.mean(dim=1)
def forward(self, x): x = self.forward_features(x) # x = self.head(x)
return x
class DWConv(nn.Module): def __init__(self, dim=768): super(DWConv, self).__init__() self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
def forward(self, x, H, W): B, N, C = x.shape x = x.transpose(1, 2).view(B, C, H, W).contiguous() x = self.dwconv(x) x = x.flatten(2).transpose(1, 2)
return x
def _conv_filter(state_dict, patch_size=16): """ convert patch embedding weight from manual patchify + linear proj to conv""" out_dict = {} for k, v in state_dict.items(): if 'patch_embed.proj.weight' in k: v = v.reshape((v.shape[0], 3, patch_size, patch_size)) out_dict[k] = v
return out_dict
## @register_modelclass pvt_v2_b0(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b0, self).__init__( patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
## @register_modelclass pvt_v2_b1(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b1, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
## @register_modelclass pvt_v2_b2(PyramidVisionTransformerImpr): def __init__(self, in_channels=3, **kwargs): super(pvt_v2_b2, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)
## @register_modelclass pvt_v2_b3(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b3, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
## @register_modelclass pvt_v2_b4(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b4, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
## @register_modelclass pvt_v2_b5(PyramidVisionTransformerImpr): def __init__(self, **kwargs): super(pvt_v2_b5, self).__init__( patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1], drop_rate=0.0, drop_path_rate=0.1)
### models/backbones/swin_v1.py
# --------------------------------------------------------# Swin Transformer# Copyright (c) 2021 Microsoft# Licensed under The MIT License [see LICENSE for details]# Written by Ze Liu, Yutong Lin, Yixuan Wei# --------------------------------------------------------
import torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.utils.checkpoint as checkpointimport numpy as npfrom timm.models.layers import DropPath, to_2tuple, trunc_normal_
# from config import Config
# config = Config()
class Mlp(nn.Module): """ Multilayer perceptron."""
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop)
def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x
def window_partition(x, window_size): """ Args: x: (B, H, W, C) window_size (int): window size
Returns: windows: (num_windows*B, window_size, window_size, C) """ B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) return windows
def window_reverse(windows, window_size, H, W): """ Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image
Returns: x: (B, H, W, C) """ B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return x
class WindowAttention(nn.Module): """ Window based multi-head self attention (W-MSA) module with relative position bias. It supports both of shifted and non-shifted window.
Args: dim (int): Number of input channels. window_size (tuple[int]): The height and width of the window. num_heads (int): Number of attention heads. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 proj_drop (float, optional): Dropout ratio of output. Default: 0.0 """
def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
super().__init__() self.dim = dim self.window_size = window_size # Wh, Ww self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5
# define a parameter table of relative position bias self.relative_position_bias_table = nn.Parameter( torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
# get pair-wise relative position index for each token inside the window coords_h = torch.arange(self.window_size[0]) coords_w = torch.arange(self.window_size[1]) coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 relative_coords[:, :, 1] += self.window_size[1] - 1 relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww self.register_buffer("relative_position_index", relative_position_index)
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop_prob = attn_drop self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop)
trunc_normal_(self.relative_position_bias_table, std=.02) self.softmax = nn.Softmax(dim=-1)
def forward(self, x, mask=None): """ Forward function.
Args: x: input features with shape of (num_windows*B, N, C) mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None """ B_, N, C = x.shape qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
q = q * self.scale
if config.SDPA_enabled: x = torch.nn.functional.scaled_dot_product_attention( q, k, v, attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False ).transpose(1, 2).reshape(B_, N, C) else: attn = (q @ k.transpose(-2, -1))
relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view( self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1 ) # Wh*Ww, Wh*Ww, nH relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww attn = attn + relative_position_bias.unsqueeze(0)
if mask is not None: nW = mask.shape[0] attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) attn = attn.view(-1, self.num_heads, N, N) attn = self.softmax(attn) else: attn = self.softmax(attn)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B_, N, C) x = self.proj(x) x = self.proj_drop(x) return x
class SwinTransformerBlock(nn.Module): """ Swin Transformer Block.
Args: dim (int): Number of input channels. num_heads (int): Number of attention heads. window_size (int): Window size. shift_size (int): Shift size for SW-MSA. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. drop (float, optional): Dropout rate. Default: 0.0 attn_drop (float, optional): Attention dropout rate. Default: 0.0 drop_path (float, optional): Stochastic depth rate. Default: 0.0 act_layer (nn.Module, optional): Activation layer. Default: nn.GELU norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """
def __init__(self, dim, num_heads, window_size=7, shift_size=0, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.dim = dim self.num_heads = num_heads self.window_size = window_size self.shift_size = shift_size self.mlp_ratio = mlp_ratio assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
self.norm1 = norm_layer(dim) self.attn = WindowAttention( dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.H = None self.W = None
def forward(self, x, mask_matrix): """ Forward function.
Args: x: Input feature, tensor size (B, H*W, C). H, W: Spatial resolution of the input feature. mask_matrix: Attention mask for cyclic shift. """ B, L, C = x.shape H, W = self.H, self.W assert L == H * W, "input feature has wrong size"
shortcut = x x = self.norm1(x) x = x.view(B, H, W, C)
# pad feature maps to multiples of window size pad_l = pad_t = 0 pad_r = (self.window_size - W % self.window_size) % self.window_size pad_b = (self.window_size - H % self.window_size) % self.window_size x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) _, Hp, Wp, _ = x.shape
# cyclic shift if self.shift_size > 0: shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) attn_mask = mask_matrix else: shifted_x = x attn_mask = None
# partition windows x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
# W-MSA/SW-MSA attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
# merge windows attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
# reverse cyclic shift if self.shift_size > 0: x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) else: x = shifted_x
if pad_r > 0 or pad_b > 0: x = x[:, :H, :W, :].contiguous()
x = x.view(B, H * W, C)
# FFN x = shortcut + self.drop_path(x) x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
class PatchMerging(nn.Module): """ Patch Merging Layer
Args: dim (int): Number of input channels. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """ def __init__(self, dim, norm_layer=nn.LayerNorm): super().__init__() self.dim = dim self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) self.norm = norm_layer(4 * dim)
def forward(self, x, H, W): """ Forward function.
Args: x: Input feature, tensor size (B, H*W, C). H, W: Spatial resolution of the input feature. """ B, L, C = x.shape assert L == H * W, "input feature has wrong size"
x = x.view(B, H, W, C)
# padding pad_input = (H % 2 == 1) or (W % 2 == 1) if pad_input: x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
x = self.norm(x) x = self.reduction(x)
return x
class BasicLayer(nn.Module): """ A basic Swin Transformer layer for one stage.
Args: dim (int): Number of feature channels depth (int): Depths of this stage. num_heads (int): Number of attention head. window_size (int): Local window size. Default: 7. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. drop (float, optional): Dropout rate. Default: 0.0 attn_drop (float, optional): Attention dropout rate. Default: 0.0 drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. """
def __init__(self, dim, depth, num_heads, window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False): super().__init__() self.window_size = window_size self.shift_size = window_size // 2 self.depth = depth self.use_checkpoint = use_checkpoint
# build blocks self.blocks = nn.ModuleList([ SwinTransformerBlock( dim=dim, num_heads=num_heads, window_size=window_size, shift_size=0 if (i % 2 == 0) else window_size // 2, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop, attn_drop=attn_drop, drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, norm_layer=norm_layer) for i in range(depth)])
# patch merging layer if downsample is not None: self.downsample = downsample(dim=dim, norm_layer=norm_layer) else: self.downsample = None
def forward(self, x, H, W): """ Forward function.
Args: x: Input feature, tensor size (B, H*W, C). H, W: Spatial resolution of the input feature. """
# calculate attention mask for SW-MSA # Turn int to torch.tensor for the compatiability with torch.compile in PyTorch 2.5. Hp = torch.ceil(torch.tensor(H) / self.window_size).to(torch.int64) * self.window_size Wp = torch.ceil(torch.tensor(W) / self.window_size).to(torch.int64) * self.window_size img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1 h_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) w_slices = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) cnt = 0 for h in h_slices: for w in w_slices: img_mask[:, h, w, :] = cnt cnt += 1
mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1 mask_windows = mask_windows.view(-1, self.window_size * self.window_size) attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)).to(x.dtype)
for blk in self.blocks: blk.H, blk.W = H, W if self.use_checkpoint: x = checkpoint.checkpoint(blk, x, attn_mask) else: x = blk(x, attn_mask) if self.downsample is not None: x_down = self.downsample(x, H, W) Wh, Ww = (H + 1) // 2, (W + 1) // 2 return x, H, W, x_down, Wh, Ww else: return x, H, W, x, H, W
class PatchEmbed(nn.Module): """ Image to Patch Embedding
Args: patch_size (int): Patch token size. Default: 4. in_channels (int): Number of input image channels. Default: 3. embed_dim (int): Number of linear projection output channels. Default: 96. norm_layer (nn.Module, optional): Normalization layer. Default: None """
def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None): super().__init__() patch_size = to_2tuple(patch_size) self.patch_size = patch_size
self.in_channels = in_channels self.embed_dim = embed_dim
self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size) if norm_layer is not None: self.norm = norm_layer(embed_dim) else: self.norm = None
def forward(self, x): """Forward function.""" # padding _, _, H, W = x.size() if W % self.patch_size[1] != 0: x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1])) if H % self.patch_size[0] != 0: x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
x = self.proj(x) # B C Wh Ww if self.norm is not None: Wh, Ww = x.size(2), x.size(3) x = x.flatten(2).transpose(1, 2) x = self.norm(x) x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
return x
class SwinTransformer(nn.Module): """ Swin Transformer backbone. A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - https://arxiv.org/pdf/2103.14030
Args: pretrain_img_size (int): Input image size for training the pretrained model, used in absolute postion embedding. Default 224. patch_size (int | tuple(int)): Patch size. Default: 4. in_channels (int): Number of input image channels. Default: 3. embed_dim (int): Number of linear projection output channels. Default: 96. depths (tuple[int]): Depths of each Swin Transformer stage. num_heads (tuple[int]): Number of attention head of each stage. window_size (int): Window size. Default: 7. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. drop_rate (float): Dropout rate. attn_drop_rate (float): Attention dropout rate. Default: 0. drop_path_rate (float): Stochastic depth rate. Default: 0.2. norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. ape (bool): If True, add absolute position embedding to the patch embedding. Default: False. patch_norm (bool): If True, add normalization after patch embedding. Default: True. out_indices (Sequence[int]): Output from which stages. frozen_stages (int): Stages to be frozen (stop grad and set eval mode). -1 means not freezing any parameters. use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. """
def __init__(self, pretrain_img_size=224, patch_size=4, in_channels=3, embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.2, norm_layer=nn.LayerNorm, ape=False, patch_norm=True, out_indices=(0, 1, 2, 3), frozen_stages=-1, use_checkpoint=False): super().__init__()
self.pretrain_img_size = pretrain_img_size self.num_layers = len(depths) self.embed_dim = embed_dim self.ape = ape self.patch_norm = patch_norm self.out_indices = out_indices self.frozen_stages = frozen_stages
# split image into non-overlapping patches self.patch_embed = PatchEmbed( patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim, norm_layer=norm_layer if self.patch_norm else None)
# absolute position embedding if self.ape: pretrain_img_size = to_2tuple(pretrain_img_size) patch_size = to_2tuple(patch_size) patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1])) trunc_normal_(self.absolute_pos_embed, std=.02)
self.pos_drop = nn.Dropout(p=drop_rate)
# stochastic depth dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
# build layers self.layers = nn.ModuleList() for i_layer in range(self.num_layers): layer = BasicLayer( dim=int(embed_dim * 2 ** i_layer), depth=depths[i_layer], num_heads=num_heads[i_layer], window_size=window_size, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], norm_layer=norm_layer, downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, use_checkpoint=use_checkpoint) self.layers.append(layer)
num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)] self.num_features = num_features
# add a norm layer for each output for i_layer in out_indices: layer = norm_layer(num_features[i_layer]) layer_name = f'norm{i_layer}' self.add_module(layer_name, layer)
self._freeze_stages()
def _freeze_stages(self): if self.frozen_stages >= 0: self.patch_embed.eval() for param in self.patch_embed.parameters(): param.requires_grad = False
if self.frozen_stages >= 1 and self.ape: self.absolute_pos_embed.requires_grad = False
if self.frozen_stages >= 2: self.pos_drop.eval() for i in range(0, self.frozen_stages - 1): m = self.layers[i] m.eval() for param in m.parameters(): param.requires_grad = False
def forward(self, x): """Forward function.""" x = self.patch_embed(x)
Wh, Ww = x.size(2), x.size(3) if self.ape: # interpolate the position embedding to the corresponding size absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic') x = (x + absolute_pos_embed) # B Wh*Ww C outs = []#x.contiguous()] x = x.flatten(2).transpose(1, 2) x = self.pos_drop(x) for i in range(self.num_layers): layer = self.layers[i] x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
if i in self.out_indices: norm_layer = getattr(self, f'norm{i}') x_out = norm_layer(x_out)
out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous() outs.append(out)
return tuple(outs)
def train(self, mode=True): """Convert the model into training mode while keep layers freezed.""" super(SwinTransformer, self).train(mode) self._freeze_stages()
def swin_v1_t(): model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7) return model
def swin_v1_s(): model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7) return model
def swin_v1_b(): model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12) return model
def swin_v1_l(): model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12) return model
### models/modules/deform_conv.py
import torchimport torch.nn as nnfrom torchvision.ops import deform_conv2d
class DeformableConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False):
super(DeformableConv2d, self).__init__() assert type(kernel_size) == tuple or type(kernel_size) == int
kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size) self.stride = stride if type(stride) == tuple else (stride, stride) self.padding = padding self.offset_conv = nn.Conv2d(in_channels, 2 * kernel_size[0] * kernel_size[1], kernel_size=kernel_size, stride=stride, padding=self.padding, bias=True)
nn.init.constant_(self.offset_conv.weight, 0.) nn.init.constant_(self.offset_conv.bias, 0.) self.modulator_conv = nn.Conv2d(in_channels, 1 * kernel_size[0] * kernel_size[1], kernel_size=kernel_size, stride=stride, padding=self.padding, bias=True)
nn.init.constant_(self.modulator_conv.weight, 0.) nn.init.constant_(self.modulator_conv.bias, 0.)
self.regular_conv = nn.Conv2d(in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=self.padding, bias=bias)
def forward(self, x): #h, w = x.shape[2:] #max_offset = max(h, w)/4.
offset = self.offset_conv(x)#.clamp(-max_offset, max_offset) modulator = 2. * torch.sigmoid(self.modulator_conv(x)) x = deform_conv2d( input=x, offset=offset, weight=self.regular_conv.weight, bias=self.regular_conv.bias, padding=self.padding, mask=modulator, stride=self.stride, ) return x
### utils.py
import torch.nn as nn
def build_act_layer(act_layer): if act_layer == 'ReLU': return nn.ReLU(inplace=True) elif act_layer == 'SiLU': return nn.SiLU(inplace=True) elif act_layer == 'GELU': return nn.GELU()
raise NotImplementedError(f'build_act_layer does not support {act_layer}')
def build_norm_layer(dim, norm_layer, in_format='channels_last', out_format='channels_last', eps=1e-6): layers = [] if norm_layer == 'BN': if in_format == 'channels_last': layers.append(to_channels_first()) layers.append(nn.BatchNorm2d(dim)) if out_format == 'channels_last': layers.append(to_channels_last()) elif norm_layer == 'LN': if in_format == 'channels_first': layers.append(to_channels_last()) layers.append(nn.LayerNorm(dim, eps=eps)) if out_format == 'channels_first': layers.append(to_channels_first()) else: raise NotImplementedError( f'build_norm_layer does not support {norm_layer}') return nn.Sequential(*layers)
class to_channels_first(nn.Module):
def __init__(self): super().__init__()
def forward(self, x): return x.permute(0, 3, 1, 2)
class to_channels_last(nn.Module):
def __init__(self): super().__init__()
def forward(self, x): return x.permute(0, 2, 3, 1)
### dataset.py
_class_labels_TR_sorted = ( 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, ' 'BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, ' 'CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, ' 'Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, ' 'Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, ' 'Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, ' 'KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, ' 'Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, ' 'OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, ' 'RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, ' 'ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, ' 'Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, ' 'TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, ' 'UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht')class_labels_TR_sorted = _class_labels_TR_sorted.split(', ')
### models/backbones/build_backbones.py
import torchimport torch.nn as nnfrom collections import OrderedDictfrom torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights# from models.pvt_v2 import pvt_v2_b0, pvt_v2_b1, pvt_v2_b2, pvt_v2_b5# from models.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l# from config import Config
config = Config()
def build_backbone(bb_name, pretrained=True, params_settings=''): if bb_name == 'vgg16': bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0] bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]})) elif bb_name == 'vgg16bn': bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0] bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]})) elif bb_name == 'resnet50': bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children()) bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]})) else: bb = eval('{}({})'.format(bb_name, params_settings)) if pretrained: bb = load_weights(bb, bb_name) return bb
def load_weights(model, model_name): save_model = torch.load(config.weights[model_name], map_location='cpu') model_dict = model.state_dict() 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()} # to ignore the weights with mismatched size when I modify the backbone itself. if not state_dict: save_model_keys = list(save_model.keys()) sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None 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()} if not state_dict or not sub_item: print('Weights are not successully loaded. Check the state dict of weights file.') return None else: print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item)) model_dict.update(state_dict) model.load_state_dict(model_dict) return model
### models/modules/decoder_blocks.py
import torchimport torch.nn as nn# from models.aspp import ASPP, ASPPDeformable# from config import Config
# config = Config()
class BasicDecBlk(nn.Module): def __init__(self, in_channels=64, out_channels=64, inter_channels=64): super(BasicDecBlk, self).__init__() inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1) self.relu_in = nn.ReLU(inplace=True) if config.dec_att == 'ASPP': self.dec_att = ASPP(in_channels=inter_channels) elif config.dec_att == 'ASPPDeformable': self.dec_att = ASPPDeformable(in_channels=inter_channels) self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1) self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity() self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
def forward(self, x): x = self.conv_in(x) x = self.bn_in(x) x = self.relu_in(x) if hasattr(self, 'dec_att'): x = self.dec_att(x) x = self.conv_out(x) x = self.bn_out(x) return x
class ResBlk(nn.Module): def __init__(self, in_channels=64, out_channels=None, inter_channels=64): super(ResBlk, self).__init__() if out_channels is None: out_channels = in_channels inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1) self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity() self.relu_in = nn.ReLU(inplace=True)
if config.dec_att == 'ASPP': self.dec_att = ASPP(in_channels=inter_channels) elif config.dec_att == 'ASPPDeformable': self.dec_att = ASPPDeformable(in_channels=inter_channels)
self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1) self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity() self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
def forward(self, x): _x = self.conv_resi(x) x = self.conv_in(x) x = self.bn_in(x) x = self.relu_in(x) if hasattr(self, 'dec_att'): x = self.dec_att(x) x = self.conv_out(x) x = self.bn_out(x) return x + _x
### models/modules/lateral_blocks.py
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom functools import partial
# from config import Config
# config = Config()
class BasicLatBlk(nn.Module): def __init__(self, in_channels=64, out_channels=64, inter_channels=64): super(BasicLatBlk, self).__init__() inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64 self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
def forward(self, x): x = self.conv(x) return x
### models/modules/aspp.py
import torchimport torch.nn as nnimport torch.nn.functional as F# from models.deform_conv import DeformableConv2d# from config import Config
# config = Config()
class _ASPPModule(nn.Module): def __init__(self, in_channels, planes, kernel_size, padding, dilation): super(_ASPPModule, self).__init__() self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size, stride=1, padding=padding, dilation=dilation, bias=False) self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity() self.relu = nn.ReLU(inplace=True)
def forward(self, x): x = self.atrous_conv(x) x = self.bn(x)
return self.relu(x)
class ASPP(nn.Module): def __init__(self, in_channels=64, out_channels=None, output_stride=16): super(ASPP, self).__init__() self.down_scale = 1 if out_channels is None: out_channels = in_channels self.in_channelster = 256 // self.down_scale if output_stride == 16: dilations = [1, 6, 12, 18] elif output_stride == 8: dilations = [1, 12, 24, 36] else: raise NotImplementedError
self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0]) self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1]) self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2]) self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3])
self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True)) self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False) self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity() self.relu = nn.ReLU(inplace=True) self.dropout = nn.Dropout(0.5)
def forward(self, x): x1 = self.aspp1(x) x2 = self.aspp2(x) x3 = self.aspp3(x) x4 = self.aspp4(x) x5 = self.global_avg_pool(x) x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) x = torch.cat((x1, x2, x3, x4, x5), dim=1)
x = self.conv1(x) x = self.bn1(x) x = self.relu(x)
return self.dropout(x)
##################### Deformableclass _ASPPModuleDeformable(nn.Module): def __init__(self, in_channels, planes, kernel_size, padding): super(_ASPPModuleDeformable, self).__init__() self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size, stride=1, padding=padding, bias=False) self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity() self.relu = nn.ReLU(inplace=True)
def forward(self, x): x = self.atrous_conv(x) x = self.bn(x)
return self.relu(x)
class ASPPDeformable(nn.Module): def __init__(self, in_channels, out_channels=None, parallel_block_sizes=[1, 3, 7]): super(ASPPDeformable, self).__init__() self.down_scale = 1 if out_channels is None: out_channels = in_channels self.in_channelster = 256 // self.down_scale
self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0) self.aspp_deforms = nn.ModuleList([ _ASPPModuleDeformable(in_channels, self.in_channelster, conv_size, padding=int(conv_size//2)) for conv_size in parallel_block_sizes ])
self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False), nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True)) self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False) self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity() self.relu = nn.ReLU(inplace=True) self.dropout = nn.Dropout(0.5)
def forward(self, x): x1 = self.aspp1(x) x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms] x5 = self.global_avg_pool(x) x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True) x = torch.cat((x1, *x_aspp_deforms, x5), dim=1)
x = self.conv1(x) x = self.bn1(x) x = self.relu(x)
return self.dropout(x)
### models/refinement/refiner.py
import torchimport torch.nn as nnfrom collections import OrderedDictimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torchvision.models import vgg16, vgg16_bnfrom torchvision.models import resnet50
# from config import Config# from dataset import class_labels_TR_sorted# from models.build_backbone import build_backbone# from models.decoder_blocks import BasicDecBlk# from models.lateral_blocks import BasicLatBlk# from models.ing import *# from models.stem_layer import StemLayer
class RefinerPVTInChannels4(nn.Module): def __init__(self, in_channels=3+1): super(RefinerPVTInChannels4, self).__init__() self.config = Config() self.epoch = 1 self.bb = build_backbone(self.config.bb, params_settings='in_channels=4')
lateral_channels_in_collection = { 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], } channels = lateral_channels_in_collection[self.config.bb] self.squeeze_module = BasicDecBlk(channels[0], channels[0])
self.decoder = Decoder(channels)
if 0: for key, value in self.named_parameters(): if 'bb.' in key: value.requires_grad = False
def forward(self, x): if isinstance(x, list): x = torch.cat(x, dim=1) ########## Encoder ########## if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: x1 = self.bb.conv1(x) x2 = self.bb.conv2(x1) x3 = self.bb.conv3(x2) x4 = self.bb.conv4(x3) else: x1, x2, x3, x4 = self.bb(x)
x4 = self.squeeze_module(x4)
########## Decoder ##########
features = [x, x1, x2, x3, x4] scaled_preds = self.decoder(features)
return scaled_preds
class Refiner(nn.Module): def __init__(self, in_channels=3+1): super(Refiner, self).__init__() self.config = Config() self.epoch = 1 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') self.bb = build_backbone(self.config.bb)
lateral_channels_in_collection = { 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64], 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64], 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192], } channels = lateral_channels_in_collection[self.config.bb] self.squeeze_module = BasicDecBlk(channels[0], channels[0])
self.decoder = Decoder(channels)
if 0: for key, value in self.named_parameters(): if 'bb.' in key: value.requires_grad = False
def forward(self, x): if isinstance(x, list): x = torch.cat(x, dim=1) x = self.stem_layer(x) ########## Encoder ########## if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: x1 = self.bb.conv1(x) x2 = self.bb.conv2(x1) x3 = self.bb.conv3(x2) x4 = self.bb.conv4(x3) else: x1, x2, x3, x4 = self.bb(x)
x4 = self.squeeze_module(x4)
########## Decoder ##########
features = [x, x1, x2, x3, x4] scaled_preds = self.decoder(features)
return scaled_preds
class Decoder(nn.Module): def __init__(self, channels): super(Decoder, self).__init__() self.config = Config() DecoderBlock = eval('BasicDecBlk') LateralBlock = eval('BasicLatBlk')
self.decoder_block4 = DecoderBlock(channels[0], channels[1]) self.decoder_block3 = DecoderBlock(channels[1], channels[2]) self.decoder_block2 = DecoderBlock(channels[2], channels[3]) self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2)
self.lateral_block4 = LateralBlock(channels[1], channels[1]) self.lateral_block3 = LateralBlock(channels[2], channels[2]) self.lateral_block2 = LateralBlock(channels[3], channels[3])
if self.config.ms_supervision: self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0) self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0) self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0) self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0))
def forward(self, features): x, x1, x2, x3, x4 = features outs = [] p4 = self.decoder_block4(x4) _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True) _p3 = _p4 + self.lateral_block4(x3)
p3 = self.decoder_block3(_p3) _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True) _p2 = _p3 + self.lateral_block3(x2)
p2 = self.decoder_block2(_p2) _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True) _p1 = _p2 + self.lateral_block2(x1)
_p1 = self.decoder_block1(_p1) _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True) p1_out = self.conv_out1(_p1)
if self.config.ms_supervision: outs.append(self.conv_ms_spvn_4(p4)) outs.append(self.conv_ms_spvn_3(p3)) outs.append(self.conv_ms_spvn_2(p2)) outs.append(p1_out) return outs
class RefUNet(nn.Module): # Refinement def __init__(self, in_channels=3+1): super(RefUNet, self).__init__() self.encoder_1 = nn.Sequential( nn.Conv2d(in_channels, 64, 3, 1, 1), nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.encoder_2 = nn.Sequential( nn.MaxPool2d(2, 2, ceil_mode=True), nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.encoder_3 = nn.Sequential( nn.MaxPool2d(2, 2, ceil_mode=True), nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.encoder_4 = nn.Sequential( nn.MaxPool2d(2, 2, ceil_mode=True), nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True) ##### self.decoder_5 = nn.Sequential( nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) ) ##### self.decoder_4 = nn.Sequential( nn.Conv2d(128, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.decoder_3 = nn.Sequential( nn.Conv2d(128, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.decoder_2 = nn.Sequential( nn.Conv2d(128, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.decoder_1 = nn.Sequential( nn.Conv2d(128, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(inplace=True) )
self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1)
self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
def forward(self, x): outs = [] if isinstance(x, list): x = torch.cat(x, dim=1) hx = x
hx1 = self.encoder_1(hx) hx2 = self.encoder_2(hx1) hx3 = self.encoder_3(hx2) hx4 = self.encoder_4(hx3)
hx = self.decoder_5(self.pool4(hx4)) hx = torch.cat((self.upscore2(hx), hx4), 1)
d4 = self.decoder_4(hx) hx = torch.cat((self.upscore2(d4), hx3), 1)
d3 = self.decoder_3(hx) hx = torch.cat((self.upscore2(d3), hx2), 1)
d2 = self.decoder_2(hx) hx = torch.cat((self.upscore2(d2), hx1), 1)
d1 = self.decoder_1(hx)
x = self.conv_d0(d1) outs.append(x) return outs
### models/stem_layer.py
import torch.nn as nn# from utils import build_act_layer, build_norm_layer
class StemLayer(nn.Module): r""" Stem layer of InternImage Args: in_channels (int): number of input channels out_channels (int): number of output channels act_layer (str): activation layer norm_layer (str): normalization layer """
def __init__(self, in_channels=3+1, inter_channels=48, out_channels=96, act_layer='GELU', norm_layer='BN'): super().__init__() self.conv1 = nn.Conv2d(in_channels, inter_channels, kernel_size=3, stride=1, padding=1) self.norm1 = build_norm_layer( inter_channels, norm_layer, 'channels_first', 'channels_first' ) self.act = build_act_layer(act_layer) self.conv2 = nn.Conv2d(inter_channels, out_channels, kernel_size=3, stride=1, padding=1) self.norm2 = build_norm_layer( out_channels, norm_layer, 'channels_first', 'channels_first' )
def forward(self, x): x = self.conv1(x) x = self.norm1(x) x = self.act(x) x = self.conv2(x) x = self.norm2(x) return x
### models/birefnet.py
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom kornia.filters import laplacianfrom transformers import PreTrainedModelfrom einops import rearrange
# from config import Config# from dataset import class_labels_TR_sorted# from models.build_backbone import build_backbone# from models.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk# from models.lateral_blocks import BasicLatBlk# from models.aspp import ASPP, ASPPDeformable# from models.ing import *# from models.refiner import Refiner, RefinerPVTInChannels4, RefUNet# from models.stem_layer import StemLayerfrom .BiRefNet_config import BiRefNetConfig
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'): if patch_ref is not None: grid_h, grid_w = image.shape[-2] // patch_ref.shape[-2], image.shape[-1] // patch_ref.shape[-1] patches = rearrange(image, transformation, hg=grid_h, wg=grid_w) return patches
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)'): if patch_ref is not None: grid_h, grid_w = patch_ref.shape[-2] // patches[0].shape[-2], patch_ref.shape[-1] // patches[0].shape[-1] image = rearrange(patches, transformation, hg=grid_h, wg=grid_w) return image
class BiRefNet( PreTrainedModel): config_class = BiRefNetConfig def __init__(self, bb_pretrained=True, config=BiRefNetConfig()): super(BiRefNet, self).__init__(config) bb_pretrained = config.bb_pretrained self.config = Config() self.epoch = 1 self.bb = build_backbone(self.config.bb, pretrained=bb_pretrained)
channels = self.config.lateral_channels_in_collection
if self.config.auxiliary_classification: self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.cls_head = nn.Sequential( nn.Linear(channels[0], len(class_labels_TR_sorted)) )
if self.config.squeeze_block: self.squeeze_module = nn.Sequential(*[ eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0]) for _ in range(eval(self.config.squeeze_block.split('_x')[1])) ])
self.decoder = Decoder(channels)
if self.config.ender: self.dec_end = nn.Sequential( nn.Conv2d(1, 16, 3, 1, 1), nn.Conv2d(16, 1, 3, 1, 1), nn.ReLU(inplace=True), )
# refine patch-level segmentation if self.config.refine: if self.config.refine == 'itself': 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') else: self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1'))
if self.config.freeze_bb: # Freeze the backbone... print(self.named_parameters()) for key, value in self.named_parameters(): if 'bb.' in key and 'refiner.' not in key: value.requires_grad = False
def forward_enc(self, x): if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']: x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3) else: x1, x2, x3, x4 = self.bb(x) if self.config.mul_scl_ipt == 'cat': B, C, H, W = x.shape x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True)) x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1) x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1) x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1) x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1) elif self.config.mul_scl_ipt == 'add': B, C, H, W = x.shape x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True)) x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True) x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True) x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True) x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True) class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None if self.config.cxt: x4 = torch.cat( ( *[ F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True), F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True), F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True), ][-len(self.config.cxt):], x4 ), dim=1 ) return (x1, x2, x3, x4), class_preds
def forward_ori(self, x): ########## Encoder ########## (x1, x2, x3, x4), class_preds = self.forward_enc(x) if self.config.squeeze_block: x4 = self.squeeze_module(x4) ########## Decoder ########## features = [x, x1, x2, x3, x4] if self.training and self.config.out_ref: features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5)) scaled_preds = self.decoder(features) return scaled_preds, class_preds
def forward(self, x): scaled_preds, class_preds = self.forward_ori(x) class_preds_lst = [class_preds] return [scaled_preds, class_preds_lst] if self.training else scaled_preds
class Decoder(nn.Module): def __init__(self, channels): super(Decoder, self).__init__() self.config = Config() DecoderBlock = eval(self.config.dec_blk) LateralBlock = eval(self.config.lat_blk)
if self.config.dec_ipt: self.split = self.config.dec_ipt_split N_dec_ipt = 64 DBlock = SimpleConvs ic = 64 ipt_cha_opt = 1 self.ipt_blk5 = DBlock(2**10*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic) self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic) self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic) self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic) self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic) else: self.split = None
self.decoder_block4 = DecoderBlock(channels[0]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[1]) self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2]) self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]) 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) 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))
self.lateral_block4 = LateralBlock(channels[1], channels[1]) self.lateral_block3 = LateralBlock(channels[2], channels[2]) self.lateral_block2 = LateralBlock(channels[3], channels[3])
if self.config.ms_supervision: self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0) self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0) self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
if self.config.out_ref: _N = 16 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)) 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)) 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))
self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0)) self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
def forward(self, features): if self.training and self.config.out_ref: outs_gdt_pred = [] outs_gdt_label = [] x, x1, x2, x3, x4, gdt_gt = features else: x, x1, x2, x3, x4 = features outs = []
if self.config.dec_ipt: 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 x4 = torch.cat((x4, self.ipt_blk5(F.interpolate(patches_batch, size=x4.shape[2:], mode='bilinear', align_corners=True))), 1) p4 = self.decoder_block4(x4) m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision and self.training else None if self.config.out_ref: p4_gdt = self.gdt_convs_4(p4) if self.training: # >> GT: m4_dia = m4 gdt_label_main_4 = gdt_gt * F.interpolate(m4_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) outs_gdt_label.append(gdt_label_main_4) # >> Pred: gdt_pred_4 = self.gdt_convs_pred_4(p4_gdt) outs_gdt_pred.append(gdt_pred_4) gdt_attn_4 = self.gdt_convs_attn_4(p4_gdt).sigmoid() # >> Finally: p4 = p4 * gdt_attn_4 _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True) _p3 = _p4 + self.lateral_block4(x3)
if self.config.dec_ipt: 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 _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1) p3 = self.decoder_block3(_p3) m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision and self.training else None if self.config.out_ref: p3_gdt = self.gdt_convs_3(p3) if self.training: # >> GT: # m3 --dilation--> m3_dia # G_3^gt * m3_dia --> G_3^m, which is the label of gradient m3_dia = m3 gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) outs_gdt_label.append(gdt_label_main_3) # >> Pred: # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx # F_3^G --sigmoid--> A_3^G gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt) outs_gdt_pred.append(gdt_pred_3) gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid() # >> Finally: # p3 = p3 * A_3^G p3 = p3 * gdt_attn_3 _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True) _p2 = _p3 + self.lateral_block3(x2)
if self.config.dec_ipt: 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 _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1) p2 = self.decoder_block2(_p2) m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision and self.training else None if self.config.out_ref: p2_gdt = self.gdt_convs_2(p2) if self.training: # >> GT: m2_dia = m2 gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True) outs_gdt_label.append(gdt_label_main_2) # >> Pred: gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt) outs_gdt_pred.append(gdt_pred_2) gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid() # >> Finally: p2 = p2 * gdt_attn_2 _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True) _p1 = _p2 + self.lateral_block2(x1)
if self.config.dec_ipt: 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 _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1) _p1 = self.decoder_block1(_p1) _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
if self.config.dec_ipt: 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 _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1) p1_out = self.conv_out1(_p1)
if self.config.ms_supervision and self.training: outs.append(m4) outs.append(m3) outs.append(m2) outs.append(p1_out) return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs)
class SimpleConvs(nn.Module): def __init__( self, in_channels: int, out_channels: int, inter_channels=64 ) -> None: super().__init__() self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1) self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)
def forward(self, x): return self.conv_out(self.conv1(x))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214"""Portable launcher for the sanitized SKING_DDJ_v101c inference bundle."""import argparseimport hashlibimport jsonimport osfrom pathlib import Pathimport runpyimport shutilimport subprocessimport sysimport tempfile
ROOT = Path(__file__).resolve().parent
def sha(path): digest = hashlib.sha256() with Path(path).open("rb") as stream: for block in iter(lambda: stream.read(4 * 1024 * 1024), b""): digest.update(block) return digest.hexdigest()
def verify(): release = json.loads((ROOT / "release.json").read_text()) if ( release["format"] != "sking-hf-bundle-v1" or release["model_version"] != "SKING_DDJ_v101c" ): raise ValueError("Wrong release identity") for name, expected in release["sha256"].items(): path = (ROOT / name).resolve() if not path.is_relative_to(ROOT) or sha(path) != expected: raise ValueError("Release integrity failure: " + name) return release
def parser_stage(options): sys.path.insert(0, str(ROOT / "runtime/dense_uv_parser")) from run_local import bind_checkout
bind_checkout() import SkingToolkit.dense_uv_parser.infer as parser_module
original = parser_module.load_parser
def load_portable(*args, **kwargs): model, config = original(*args, **kwargs) config = dict(config) config["mappings_dir"] = str(ROOT / "mappings_256x512") return model, config
parser_module.load_parser = load_portable sys.argv = [ "batch_accessories", "--checkpoint", str(ROOT / "parser.pt"), "--pipeline", str(ROOT / "pipeline.json"), "--output-dir", str(options.output), "--foreground-probabilities", str(options.probability), "--inputs", str(options.input), ] runpy.run_module( "SkingToolkit.dense_uv_parser.batch_accessories", run_name="__main__" )
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", type=Path, help="Square combined front/back edited render") parser.add_argument("--output", type=Path, help="Output 64x64 RGBA PNG") parser.add_argument("--parser-python", default=sys.executable) parser.add_argument("--foreground-python", default=sys.executable) parser.add_argument("--verify-only", action="store_true") parser.add_argument("--parser-stage", action="store_true", help=argparse.SUPPRESS) parser.add_argument("--probability", type=Path, help=argparse.SUPPRESS) options = parser.parse_args() os.environ.update( HF_HUB_OFFLINE="1", HF_HOME=str(ROOT / "hf_cache"), HF_HUB_CACHE=str(ROOT / "hf_cache/hub"), HF_HUB_DISABLE_PROGRESS_BARS="1", PYTHONDONTWRITEBYTECODE="1", OMP_NUM_THREADS="4", MKL_NUM_THREADS="4", CUBLAS_WORKSPACE_CONFIG=":4096:8", ) if options.parser_stage: parser_stage(options) return release = verify() if options.verify_only: print( json.dumps( { "verified_files": len(release["sha256"]), "model_version": release["model_version"], } ) ) return if options.input is None or options.output is None: parser.error("--input and --output are required for inference") options.input = options.input.resolve() options.output = options.output.resolve() if options.input == options.output: parser.error("Input and output must be different files") from PIL import Image
with Image.open(options.input) as source: width, height = source.size if width != height or width < 256 or width > 4096 or width % 2: raise ValueError("Expected an even square combined render, 256 to 4096 pixels") source.verify() options.output.parent.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix="sking-v101c-") as directory: work = Path(directory) source_path = work / "input.png" shutil.copyfile(options.input, source_path) index = work / "foreground.json" entry = ROOT / "runtime/dense_uv_parser/run_local.py" subprocess.run( [ options.foreground_python, str(entry), "foreground_provider", "--checkpoint", str(ROOT / "foreground.pt"), "--model-dir", str(ROOT / "foreground_base"), "--output-dir", str(work / "foreground"), "--result-manifest", str(index), "--inputs", str(source_path), ], check=True, cwd=ROOT / "runtime", ) probabilities = json.loads(index.read_text())["probabilities"] if len(probabilities) != 1: raise RuntimeError("Foreground stage did not return one result") subprocess.run( [ options.parser_python, str(Path(__file__).resolve()), "--parser-stage", "--input", str(source_path), "--output", str(work / "uv"), "--probability", probabilities[0], ], check=True, cwd=ROOT / "runtime", ) outputs = list((work / "uv").glob("*/manifest.json")) if len(outputs) != 1: raise RuntimeError("Parser did not return one result") manifest = json.loads(outputs[0].read_text()) expected_sources = { Path(name).name: digest for name, digest in release["sha256"].items() if Path(name).parent == Path("runtime/dense_uv_parser") and name.endswith(".py") } if ( manifest.get("complete") is not True or manifest.get("input_sha256") != sha(source_path) or manifest.get("checkpoint_sha256") != release["sha256"]["parser.pt"] or manifest.get("pipeline") != json.loads((ROOT / "pipeline.json").read_text()) or manifest.get("source_sha256") != expected_sources or manifest.get("foreground_provider", {}).get("adaptation_sha256") != release["sha256"]["foreground.pt"] or manifest.get("foreground_provider", {}).get("model_sha256") != release["sha256"]["foreground_base/model.safetensors"] ): raise RuntimeError("Output provenance does not match this release") result = outputs[0].parent / "pred_uv.png" with Image.open(result) as uv: if uv.size != (64, 64) or uv.mode != "RGBA" or not uv.getchannel("A").getbbox(): raise RuntimeError("Invalid UV output") with tempfile.NamedTemporaryFile( dir=options.output.parent, prefix=".sking-v101c-", suffix=".png", delete=False, ) as stream: temporary = Path(stream.name) stream.write(result.read_bytes()) try: os.replace(temporary, options.output) finally: temporary.unlink(missing_ok=True) print( json.dumps( { "model_version": "SKING_DDJ_v101c", "output": str(options.output), "sha256": sha(options.output), } ) )
if __name__ == "__main__": main()123456789101112131415161718192021MIT License
Copyright (c) 2024 ZhengPeng
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1234567891011121314[ { "file": "BiRefNet_LICENSE.txt", "url": "https://raw.githubusercontent.com/ZhengPeng7/BiRefNet/main/LICENSE", "sha256": "92a7089e0915fc32bc40067560b398f1e6a7a5958abd7d04eda393629a5acefb", "bytes": 1066 }, { "file": "SigLIP2_LICENSE.txt", "url": "https://raw.githubusercontent.com/google-research/big_vision/main/LICENSE", "sha256": "43070e2d4e532684de521b885f385d0841030efa2b1a20bafb76133a5e1379c1", "bytes": 11356 }]123version https://git-lfs.github.com/spec/v1oid sha256:4966dc30a35f7884dad1f37d4cf2b14bcf8fdfdbe34f3dbbec1ed2ebd31f9308size 18878693123version https://git-lfs.github.com/spec/v1oid sha256:66796f7e6f321f9bd1739fbd9f2110c6477d814cf9a98f968190a255b2e128e7size 13373861123version https://git-lfs.github.com/spec/v1oid sha256:3baa16ca38e7b62f38d04c29746c72c5a3c05ca054d72300cda2c08b2645c4c8size 18878709123version https://git-lfs.github.com/spec/v1oid sha256:63e7dde6cfb22edebe4b45b1ebecaa9ee5679aca1be022e26fabdfc922c84fb8size 13373877123version https://git-lfs.github.com/spec/v1oid sha256:f09e38516ed10a81c86939119d776353d795554093c699b10d89741ea78dce7fsize 18878709123version https://git-lfs.github.com/spec/v1oid sha256:56db06fe4bf215e06b6f9e8a7b81747e4e24483d770619660b26f555e5402f97size 13373877123version https://git-lfs.github.com/spec/v1oid sha256:d9f32bdcbbd98ea6f75aaacc966d6553582d676c06154003dde1559d3f92f1f5size 18878725123version https://git-lfs.github.com/spec/v1oid sha256:138481fd6da1746f21dd90bb42f432a532fa79d73d60515d4558bda2cf56365dsize 13373893123version https://git-lfs.github.com/spec/v1oid sha256:14213de89eaac720fd83892033c5e42301e682ad37c678dd723619bf10982ca2size 18878725123version https://git-lfs.github.com/spec/v1oid sha256:d42e32902fedb9af2bd0f34ae50d18107c3d2264e519beb3b4eb8619d8a0f703size 18878741123version https://git-lfs.github.com/spec/v1oid sha256:9fdc06695caada150b071bc0632fb83a8fed04c6ae1135b25c9519077eddfdcasize 13374005123version https://git-lfs.github.com/spec/v1oid sha256:9dfe71bab556365f9e4a33c2eca9d1905806b4278d422adfcf58cb6678b65853size 21501093123version https://git-lfs.github.com/spec/v1oid sha256:c406299c5bab60cc4b8d7afa59f833a41a693ba7b2efa7a819ee2828e4f4008bsize 13374021123version https://git-lfs.github.com/spec/v1oid sha256:84ad02344ba9777c18d0ec41004d6fed5211b8a1e5cffd62dcac43ba7e4f3148size 21501111123version https://git-lfs.github.com/spec/v1oid sha256:ea3bd7d0e0d2eeb73d0bea68233412bf74ddc5ae8ddfb9a3a6957c381f1b2540size 3177176312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879{ "foreground_flood_tolerance": 0.09, "foreground_background": "adaptive", "routing": { "views": [ "front_left", "back_left" ], "group_size": 2, "fg_threshold": 0.5, "bg_color": [ 128, 128, 128 ], "semantic_gate": true, "affine_refine": false, "affine_refine_translation_px": 0.0, "affine_refine_scale": 0.0, "route_confidence_threshold": 0.0, "route_margin_threshold": 0.0, "outer_route_confidence_threshold": 0.8, "outer_route_margin_threshold": 0.55, "outer_uv_min_coverage": 0.25, "outer_uv_min_source_pixels": 30, "outer_silhouette_consistency": true, "outer_silhouette_min_coverage": 0.5, "outer_silhouette_dilation": 0, "outer_silhouette_min_pixels": 4, "outer_geometry_rescue": true, "outer_semantic_rescue": true, "outer_semantic_presence_threshold": 0.8, "outer_semantic_coverage_threshold": 0.2, "outer_rescue_confidence_threshold": 0.6, "outer_rescue_margin_threshold": 0.25, "outer_rescue_min_coverage": 0.1, "color_aggregation": "grid_mode", "geometry_route_texel_consensus": true, "geometry_route_texel_consensus_weight": 0.6, "geometry_route_preserve_outer_confidence": 0.8, "geometry_route_preserve_outer_margin": 0.35, "geometry_route_consensus_outer_confidence": 0.7, "geometry_route_consensus_outer_margin": 0.2, "geometry_cross_view_outer_consistency": false, "geometry_cross_view_outer_weight": 0.5, "geometry_cross_view_outer_positive_confidence": 0.7, "geometry_cross_view_outer_positive_margin": 0.2, "geometry_cross_view_outer_negative_confidence": 0.7, "geometry_cross_view_outer_negative_margin": 0.2, "geometry_cross_view_outer_background_max_coverage": 0.25, "geometry_cross_view_outer_min_views": 2, "outer_uv_occupancy": false, "outer_uv_occupancy_blend_weight": 0.0, "outer_uv_occupancy_gate_threshold": 0.15, "outer_uv_occupancy_rescue_threshold": 0.7, "outer_uv_occupancy_rescue_route_threshold": 0.3, "outer_uv_component_routing": false, "outer_uv_component_seed_threshold": 0.8, "outer_uv_component_grow_threshold": 0.5, "outer_uv_component_min_size": 2, "background_color_tolerance": 0.25, "color_background_tolerance": 0.031372549, "color_foreground_inset": 1, "reject_semantic_fallback": true, "include_rejected_context": false, "include_confidence": false, "head_color_separation_inset": 2 }, "accessory_route_threshold": 0.9, "synthetic_alpha_foreground": true, "head_material_refine_steps": 48, "head_material_refine_mode": "isolated", "headphone_routing_mode": "existing_uv", "headphone_presence_threshold": 0.99, "headphone_presence_consensus": true, "head_semantic_inpaint": true, "headwear_presence_threshold": 0.95, "crown_top_geometry_mode": "rendered_semantics"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142{ "format": "sking-hf-bundle-v1", "model_version": "SKING_DDJ_v101c", "original_version": "v101", "original_revision": "crown_geometry_20260906", "source_code_commit": "28f548a5be37868022cfbafaddbe095895e18210", "production_artifacts": { "parser_sha256": "a8aa3d8cd51cc6fec28d7c525aa1b012976d7cb1206e8b00c707de76bfb205dc", "foreground_sha256": "8585a698d38969e6e7562e9c7d8c5f0b5e934e8f0811cf5b8678fcf05734e732", "pipeline_sha256": "3e14b98437eba9c5189a3344f560e7183f8daad44b9c40c55e15f7e0fda27685" }, "sanitization": { "pipeline_fields_removed": [ "foreground_cache", "foreground_release", "hat_development" ], "private_paths_removed": true, "optimizer_states_removed": true, "user_and_regression_images_excluded": true, "parser_tensor_count": 386, "foreground_tensor_count": 397, "parser_metadata_paths_removed": 1, "foreground_metadata_paths_removed": 3, "optimizer_state_removed": { "parser": false, "foreground": true }, "excluded_private_tests": [ "test_accessories.py", "test_affine_routing.py", "test_crown_geometry.py", "test_foreground.py", "test_headwear.py", "test_matting_data.py", "test_ownership.py", "test_semantic_generalization.py", "test_semantic_parser.py" ], "portable_path_adjustments": [ "batch_accessories.py", "foreground_batch.py", "released_inference.py" ] }, "validation": { "historical_samples": 8, "alpha_exact": 8, "visible_rgb_max": 1, "deployment_regression_samples": 6 }, "sha256": { "LICENSE": "8486a10c4393cee1c25392769ddd3b2d6c242d6ec7928e1414efff7dfb2f07ef", "README.md": "342c7e13ea8a7cad51d77bf999074168ea99db7a48e2c4cc6b7b78e80b362667", "THIRD_PARTY_NOTICES.md": "58533726d4b29528a102039a8d1c6d42cf6c7b07b42dd9b026cf418348fc14af", "foreground.pt": "f00c1abbf736d54fcda6800ec6046817456ef9fbc45bb67bc1e6d759cfb45331", "foreground_base/BiRefNet_config.py": "e7b8c2a74f6cea6a59553d517f71d47f2c1d90e670a13416af17c25fe2f3dc52", "foreground_base/birefnet.py": "a9566611aa07a6fbb68ddb6ac8e19e62c879a428fbfc2f44efa53d233f2e302f", "foreground_base/config.json": "c97ea21569daf66b205491a4635147dd3bc42c7c168b89d7d75b53f67ef548ae", "foreground_base/model.safetensors": "9ab37426bf4de0567af6b5d21b16151357149139362e6e8992021b8ce356a154", "hf_cache/hub/models--google--siglip2-base-patch16-224/refs/main": "5adaedd88ee9835df44ae379db76ca2e0a84427d427f05d9b268f5556b02ff97", "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/config.json": "fe8b5fe6d5734360678fd71c11c21e1ea3364bd8598d34295d9206335973ffd7", "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/model.safetensors": "612923381c76ec5a9bed335d1c48827e3f2e506ac31b044b63b2031fadee6a0b", "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/preprocessor_config.json": "9b36b57ebaf20f09bf4c22100ccc21877ea6bfe5aead0c00c59f8af8ccefacfc", "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/special_tokens_map.json": "baec30ea10906f16adb8c18af7a34023002c1746542612b8b41c9f09e1351351", "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.json": "cb9140fae3ac5122c972d37adf83e1248471a38147ad76f8215c8872c6fd8322", "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.model": "61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2", "hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer_config.json": "14afe629fe4959b9e0d51e1852b8d9f7ad074f90a1a7125a4fcdd17f06e78fc8", "hf_cache/modules/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "hf_cache/modules/transformers_modules/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "hf_cache/modules/transformers_modules/foreground_base/BiRefNet_config.py": "e7b8c2a74f6cea6a59553d517f71d47f2c1d90e670a13416af17c25fe2f3dc52", "hf_cache/modules/transformers_modules/foreground_base/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "hf_cache/modules/transformers_modules/foreground_base/birefnet.py": "a9566611aa07a6fbb68ddb6ac8e19e62c879a428fbfc2f44efa53d233f2e302f", "infer.py": "4454b60fe21440cd8036cb7fdac54063d4b82a1636347c650475a59dcda45c29", "licenses/BiRefNet_LICENSE.txt": "92a7089e0915fc32bc40067560b398f1e6a7a5958abd7d04eda393629a5acefb", "licenses/SigLIP2_LICENSE.txt": "43070e2d4e532684de521b885f385d0841030efa2b1a20bafb76133a5e1379c1", "licenses/sources.json": "61b376b10e8f5d18d7d99c0cb9db89f761e60d1b2ad5333b8408502d535c4218", "mappings_256x512/back_left_mapping.pt": "4966dc30a35f7884dad1f37d4cf2b14bcf8fdfdbe34f3dbbec1ed2ebd31f9308", "mappings_256x512/back_left_overlay_mapping.pt": "66796f7e6f321f9bd1739fbd9f2110c6477d814cf9a98f968190a255b2e128e7", "mappings_256x512/back_right_mapping.pt": "3baa16ca38e7b62f38d04c29746c72c5a3c05ca054d72300cda2c08b2645c4c8", "mappings_256x512/back_right_overlay_mapping.pt": "63e7dde6cfb22edebe4b45b1ebecaa9ee5679aca1be022e26fabdfc922c84fb8", "mappings_256x512/front_left_mapping.pt": "f09e38516ed10a81c86939119d776353d795554093c699b10d89741ea78dce7f", "mappings_256x512/front_left_overlay_mapping.pt": "56db06fe4bf215e06b6f9e8a7b81747e4e24483d770619660b26f555e5402f97", "mappings_256x512/front_right_mapping.pt": "d9f32bdcbbd98ea6f75aaacc966d6553582d676c06154003dde1559d3f92f1f5", "mappings_256x512/front_right_overlay_mapping.pt": "138481fd6da1746f21dd90bb42f432a532fa79d73d60515d4558bda2cf56365d", "mappings_256x512/static_back_mapping.pt": "14213de89eaac720fd83892033c5e42301e682ad37c678dd723619bf10982ca2", "mappings_256x512/static_front_mapping.pt": "d42e32902fedb9af2bd0f34ae50d18107c3d2264e519beb3b4eb8619d8a0f703", "mappings_256x512/walk_back_base_layer_ortho_mapping.pt": "9fdc06695caada150b071bc0632fb83a8fed04c6ae1135b25c9519077eddfdca", "mappings_256x512/walk_back_both_layer_ortho_mapping.pt": "9dfe71bab556365f9e4a33c2eca9d1905806b4278d422adfcf58cb6678b65853", "mappings_256x512/walk_front_base_layer_ortho_mapping.pt": "c406299c5bab60cc4b8d7afa59f833a41a693ba7b2efa7a819ee2828e4f4008b", "mappings_256x512/walk_front_both_layer_ortho_mapping.pt": "84ad02344ba9777c18d0ec41004d6fed5211b8a1e5cffd62dcac43ba7e4f3148", "parser.pt": "ea3bd7d0e0d2eeb73d0bea68233412bf74ddc5ae8ddfb9a3a6957c381f1b2540", "pipeline.json": "b3ecdcc8400621c21d3d03af249ffa8968b019184b1e82f478581b97ba49a394", "runtime/LICENSE": "8486a10c4393cee1c25392769ddd3b2d6c242d6ec7928e1414efff7dfb2f07ef", "runtime/dense_uv_parser/__init__.py": "044e6ec3019c5cf9175ddb7a5df3083630a491d01864837ee6139b01600c2ceb", "runtime/dense_uv_parser/accessories.py": "5e1787c41640196e94b7a99576d269408f56c80406577cfd0b1afe23ccd8d014", "runtime/dense_uv_parser/accessory_data.py": "7989807a1771b00df4d80cab9a7f3a0e80a8aa24546c729a9627919ffbab0728", "runtime/dense_uv_parser/accessory_pipeline.py": "66f8927b310aed4b1dae1eedfb01c1493f8aa7f7bf25e646b662bbe3f40d7ca1", "runtime/dense_uv_parser/accessory_regression.py": "9fa90be8bd6f3ba50438ec7abc394824a300270fa9dcdf3ad55968a5be73a238", "runtime/dense_uv_parser/batch_accessories.py": "9800436d24e06e3856abf4e2325546c11ba2b5b97b55099693b3d77d088ae694", "runtime/dense_uv_parser/cache_semantic_features.py": "9c439ba5a95c5a3f55c8114975872c4ad0eb38087f44f5d2f82e41d07b4a0961", "runtime/dense_uv_parser/crown_geometry.py": "608a28c8223cb0ffb0882c3ff183b9a44a3f6d2987b660517548ca657cfca14a", "runtime/dense_uv_parser/foreground.py": "6d488ef64135fd57cc661bcab531748bc242b4034b07b748bf61d34deba61db6", "runtime/dense_uv_parser/foreground_acceptance.py": "d9c6b9367cc0a4333fe08832bf558a1738a0e533dab257a3be0a181481dfb2ed", "runtime/dense_uv_parser/foreground_batch.py": "7d7917b61a3dd13a08a5afb181a9c43ad6d8973fb1e485d9503fe79d950730e4", "runtime/dense_uv_parser/foreground_model.py": "96b1cf0a4944df39d3cb1e3c0cf490508e65306b8b2428fc64fdd6974ffb978a", "runtime/dense_uv_parser/foreground_provider.py": "1970ad563d3e8aeb7df5e84fc5f4264353d4ceca80f362a13fba75f5cdbeaa5e", "runtime/dense_uv_parser/head_inpainting.py": "076c8844db555f168599e06a77efa4ae4da48b9d34860a3a2cfdf1da3ccc0638", "runtime/dense_uv_parser/headwear.py": "0e553177b9214fe6252df3dc9a0ae351c605c7d8127b1de976a04dda4ee5f09d", "runtime/dense_uv_parser/headwear_data.py": "114f904bd0743206223cf98b71bb027513c2e81c62a1ca0540d5af441384a915", "runtime/dense_uv_parser/infer.py": "819d6c78b4065b1835a5c39c152b2014adfabf7dfb0180e151b434293d1ae678", "runtime/dense_uv_parser/losses.py": "87de937f9087284de4a84ce555229c5995ed582d91af99685a2861bc6e8b66f6", "runtime/dense_uv_parser/material_refine.py": "c236307c541798ef7e232107a9da7d95b95866584c645551477bbce45eca7e18", "runtime/dense_uv_parser/matting_data.py": "107db91d98bca7a02c7501b648860e75faf7ef32a89919f4cbcd107c479d0429", "runtime/dense_uv_parser/model.py": "9729d3c97aa4c593e3891609f467563b037bf8dbc9dce597346b5b09bbc5b885", "runtime/dense_uv_parser/ownership.py": "1f414be584390f0f853423f47af85cf0a5b6a40c1c4503a0e0b76557e70f1ee8", "runtime/dense_uv_parser/ownership_data.py": "d4ff687cbbba2634aca13f4a9c02db8cf0479b3b2a1bcdc40e9bc501676c6ef1", "runtime/dense_uv_parser/prepare_foreground_data.py": "13c03bc989b1c89bf2446147b6dd5ef6d0a72bde7e3f903045ef4c7e825c2e91", "runtime/dense_uv_parser/released_inference.py": "3ca2f766ee6d89788973ef9d116b3b406e2e3556827efaef224d46e71b47cc48", "runtime/dense_uv_parser/run_local.py": "40c63041f212656f50c0a2e45524e14a2bc09b12b41adb0a0300121e0dd1a039", "runtime/dense_uv_parser/runtime.py": "c374381063f7f559dc9e2a384982b411c4eb0f5160c0bf0e40f53e4286a15d83", "runtime/dense_uv_parser/semantic.py": "7d390f827e423d4e97ec9e20e39604c5a4801d97b1796b036016bae55c755249", "runtime/dense_uv_parser/semantic_backbone.py": "1008138e58f4bc665930d786dc68b6bb44b91bef69bcc71b8d41e252957bc273", "runtime/dense_uv_parser/semantic_cache.py": "057629ce8aafbf60b379fef487a8a0ba33a2fe7e24a4e11b71ebdb3084489d40", "runtime/dense_uv_parser/semantic_generalization.py": "c8266c0ffd3a2e07cc1ed42ce62de69d80440c3bbba69b466d1121260d200c0e", "runtime/dense_uv_parser/semantic_targets.py": "f5e8dd1c7fb53847c5645b8f1cc03fc4594805de6b7d0bf482f223956a5c2008", "runtime/dense_uv_parser/simple_inpainting.py": "00359b7d9217ccf7b86f2684caee8a464d6142d35b930b464e0e963a74b750ff", "runtime/dense_uv_parser/skin_dataset.py": "67af52006b15b86c82dc10297ee3e78bc9e634ea20515202c46a6dcb29bb4887", "runtime/dense_uv_parser/train.py": "76343eb77af5b67d6baefdb80e14cf097da847bb536d47f833f4cc0963ec9233", "runtime/dense_uv_parser/train_accessories.py": "37de0c34887a4da47f63d7611a5f12a25c45f45e5eea21c6483f5e7b5f4a2a43", "runtime/dense_uv_parser/train_foreground.py": "6830de93089ef19d5f0e9171bbba19d8ec7dc53d488fd95f0c5346d67883f6f6", "runtime/dense_uv_parser/train_headphone_presence.py": "b95332c38bce2af876987342b9a3b42fc587722a2531d9a9f3c4f6d0bc6fdc61", "runtime/dense_uv_parser/train_headwear.py": "61042a2373cecddcc623f42418778b041c481442cc45da098e2c5b27175b8ac1", "runtime/dense_uv_parser/train_headwear_presence.py": "32249430cf1333e54f1d6915fad32976108ffa720e5ae9f79cd6c571bd2736ac", "runtime/dense_uv_parser/train_ownership.py": "6d06464752fcf4722d94d6a353c907a8d5cc70bd632ff0253a3ffa1d942ce1ec", "runtime/dense_uv_parser/utils.py": "34ef3658087014d8a5de36231e4911eb752c4a62fae6601e60725173fed956d3", "runtime/dense_uv_parser/uv_layout.py": "ddce13bf72bfa01c1e553f1f2760ce5a3ba4b55bae884740a9a3246fe6694e90", "runtime/dense_uv_parser/uv_topology.py": "8cfe03e229d6f3ea7297165c0f97f5e9b6cf297d7a86da1b6f51c2e6a2f397e2", "runtime/renderer.py": "e843c16b0d4b2534b6fe24646d15206c24f3aacf820f3fe30b5d42773e199d24", "tested_environments.json": "fce93e20cf26758a5a7472c1354ba9c2c158d68b3c514b1c19249637033b5bf1" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license forsoftware and other kinds of works, specifically designed to ensurecooperation with the community in the case of network server software.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,our General Public Licenses are intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rightswith two steps: (1) assert copyright on the software, and (2) offeryou this License which gives you legal permission to copy, distributeand/or modify the software.
A secondary benefit of defending all users' freedom is thatimprovements made in alternate versions of the program, if theyreceive widespread use, become available for other developers toincorporate. Many developers of free software are heartened andencouraged by the resulting cooperation. However, in the case ofsoftware used on network servers, this result may fail to come about.The GNU General Public License permits making a modified version andletting the public access it on a server without ever releasing itssource code to the public.
The GNU Affero General Public License is designed specifically toensure that, in such cases, the modified source code becomes availableto the community. It requires the operator of a network server toprovide the source code of the modified version running there to theusers of that server. Therefore, public use of a modified version, ona publicly accessible server, gives the public access to the sourcecode of the modified version.
An older license, called the Affero General Public License andpublished by Affero, was designed to accomplish similar goals. This isa different license, not a version of the Affero GPL, but Affero hasreleased a new version of the Affero GPL which permits relicensing underthis license.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as "you". "Licensees" and"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"to the extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A"Major Component", in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an"aggregate" if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-readable Corresponding Source under the terms of this License,in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe only significant mode of use of the product.
"Installation Information" for a User Product means any methods,procedures, authorization keys, or other information required to installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holders ofthat material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions;the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.
If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain the covered work, unless you entered into that arrangement,or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify theProgram, your modified version must prominently offer all usersinteracting with it remotely through a computer network (if your versionsupports such interaction) an opportunity to receive the CorrespondingSource of your version by providing access to the Corresponding Sourcefrom a network server at no charge, through some standard or customarymeans of facilitating copying of software. This Corresponding Sourceshall include the Corresponding Source for any work covered by version 3of the GNU General Public License that is incorporated pursuant to thefollowing paragraph.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the work with which it is combined will remain governed by version3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU Affero General Public License from time to time. Such new versionswill be similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU Affero GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU Affero General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU Affero General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computernetwork, you should also make sure that it provides a way for users toget its source. For example, if your program is a web application, itsinterface could display a "Source" link that leads users to an archiveof the code. There are many ways you could offer source, and differentsolutions will be better for different programs; see section 13 for thespecific requirements.
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU AGPL, see<https://www.gnu.org/licenses/>.12"""Dense render-pixel to Minecraft UV parser."""
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199"""Learned head accessory masks, object losses and geometry-safe routing.
Classes are object identities for one player: none, glasses, hat, outer hair.RGB colour and projected-cell occupancy never create an accessory label."""import torchfrom torch import nnimport torch.nn.functional as F
ACCESSORY_CLASSES = ('none', 'glasses', 'hat', 'outer_hair')HEAD_CROP = (0.0625, 0.0, 0.9375, 0.34375) # fixed Steve camera ROI, not a mask
def head_bounds(height, width): x0, y0, x1, y1 = HEAD_CROP return round(y0*height), round(y1*height), round(x0*width), round(x1*width)
def head_crop(images, foreground=None): y0, y1, x0, x1 = head_bounds(*images.shape[-2:]) rgb = images[:, :3] if foreground is None: foreground = torch.ones_like(rgb[:, :1]) elif foreground.dim() == 3: foreground = foreground[:, None] foreground = foreground.float() rgb = rgb * foreground + 0.5 * (1-foreground) crop = torch.cat([rgb, foreground], 1)[:, :, y0:y1, x0:x1] return F.interpolate(crop.float(), (224, 224), mode='bilinear', align_corners=False)
def restore_logits(logits, size): h, w = size y0, y1, x0, x1 = head_bounds(h, w) patch = F.interpolate(logits, (y1-y0, x1-x0), mode='bilinear', align_corners=False) # Outside the crop the new branch is exactly inactive. prior = logits.new_tensor([0.]+[-20.]*(logits.shape[1]-1))[None, :, None, None] return F.pad(patch-prior, (x0, w-x1, y0, h-y1)) + prior
def block(cin, cout): return nn.Sequential(nn.Conv2d(cin, cout, 3, padding=1), nn.GroupNorm(8, cout), nn.SiLU(), nn.Conv2d(cout, cout, 3, padding=1), nn.GroupNorm(8, cout), nn.SiLU())
class HeadAccessoryHead(nn.Module): def __init__(self, semantic_dim=768, predict_hat_components=False): super().__init__() self.enc0 = block(4, 24) self.enc1 = block(24, 48) self.enc2 = block(48, 96) self.enc3 = block(96, 96) self.semantic = nn.Conv2d(semantic_dim, 96, 1) self.context = nn.TransformerEncoder( nn.TransformerEncoderLayer(96, 4, 256, 0.05, batch_first=True, norm_first=True), 2, enable_nested_tensor=False) self.dec2 = block(192, 96) self.dec1 = block(144, 48) self.dec0 = block(72, 24) self.classifier = nn.Conv2d(24, 4, 1) self.components = nn.Conv2d(24,6,1) if predict_hat_components else None if self.components is not None: nn.init.zeros_(self.components.weight) nn.init.constant_(self.components.bias,-2.) with torch.no_grad():self.components.bias[0]=2. nn.init.constant_(self.classifier.bias, -2.) with torch.no_grad(): self.classifier.bias[0] = 2.
def forward(self, crop, semantic_features, return_components=False): s0 = self.enc0(crop) s1 = self.enc1(F.avg_pool2d(s0, 2)) s2 = self.enc2(F.avg_pool2d(s1, 2)) z = self.enc3(F.avg_pool2d(s2, 2)) z = F.avg_pool2d(z, 2) + self.semantic(semantic_features.to(z.dtype)) z = self.context(z.flatten(2).transpose(1, 2)).transpose(1, 2).reshape_as(z) z = self.dec2(torch.cat([F.interpolate(z, s2.shape[-2:], mode='bilinear', align_corners=False), s2], 1)) z = self.dec1(torch.cat([F.interpolate(z, s1.shape[-2:], mode='bilinear', align_corners=False), s1], 1)) z = self.dec0(torch.cat([F.interpolate(z, s0.shape[-2:], mode='bilinear', align_corners=False), s0], 1)) logits=self.classifier(z) return (logits,self.components(z)) if return_components and self.components is not None else logits
def accessory_loss(logits, labels, valid=None): """Per-object Dice + class-balanced CE + boundary affinity, preserving holes.""" if valid is None: valid = torch.ones_like(labels, dtype=torch.bool) target = labels.masked_fill(~valid, -100) ce = F.cross_entropy(logits.float(), target, weight=logits.new_tensor([1., 3., 2., 2.]).float()) probability = logits.float().softmax(1) onehot = F.one_hot(labels.clamp(0, 3), 4).permute(0, 3, 1, 2).float() mask = valid[:, None] p, g = probability * mask, onehot * mask intersection = (p * g).sum((2, 3)) dice = (1-(2*intersection+1)/(p.sum((2, 3))+g.sum((2, 3))+1))[:, 1:].mean() # Neighbour agreement targets also include object/background boundaries; # there is no indiscriminate smoothness term that fills lens/frame holes. affinity = logits.sum() * 0 for axis in (2, 3): delta = torch.diff(p[:, 1:], dim=axis) truth_delta = torch.diff(g[:, 1:], dim=axis) affinity = affinity + F.smooth_l1_loss(delta, truth_delta) return ce + dice + .2 * affinity
def connected_object_support(probability, identity, valid, seed_threshold=.90, grow_threshold=0.0): """Keep a learned object region around confident seeds, across RGB changes.
Growth is restricted to the SAME predicted object class and foreground. A low-confidence region without a seed cannot manufacture an accessory. """ seeds = (probability >= seed_threshold) & (identity > 0) & valid grown = seeds.clone() for cls in (1,2,3): candidate = (identity == cls) & (probability >= grow_threshold) & valid current = seeds & (identity == cls) if not current.any(): continue while True: neighbours = current.clone() neighbours[:,1:] |= current[:,:-1] neighbours[:,:-1] |= current[:,1:] neighbours[:,:,1:] |= current[:,:,:-1] neighbours[:,:,:-1] |= current[:,:,1:] updated = current | (candidate & neighbours) if torch.equal(updated,current): break current = updated grown |= current return grown, seeds
def apply_accessory_routing(routing, outputs, foreground, renderer, views, threshold=.80): """Promote learned object evidence even when the old route selected inner.
This is an explicit object-evidence bypass of local texel voting. Actual foreground and valid head geometry are required; later silhouette vetoes and colour-background safeguards still apply. """ from SkingToolkit.dense_uv_parser.utils import build_static_surface_routing threshold = float(outputs.get('accessory_route_threshold', threshold)) logits = outputs.get('accessory_logits') support = torch.zeros_like(foreground) if logits is None: return support probability, identity = logits.float().softmax(1).max(1) valid = torch.zeros_like(foreground) for vi,view in enumerate(views): static = build_static_surface_routing(renderer,view,foreground.device) valid[vi::len(views)] = foreground[vi::len(views)] & static['masks'][1] & (static['part'][1] == 0) support, seeds = connected_object_support(probability,identity,valid,threshold) for vi, view in enumerate(views): sl = slice(vi, foreground.shape[0], len(views)) static = build_static_surface_routing(renderer, view, foreground.device) accepted = support[sl] for name, value in [('layer', 1), ('foreground', True), ('surface', 1), ('secondary', False), ('secondary_routed', False), ('semantic_fallback', False), ('consensus_outer_gate_rejected', False)]: if name in routing: routing[name][sl] = torch.where(accepted, torch.full_like(routing[name][sl], value), routing[name][sl]) for name in ('flat_uv', 'part', 'face', 'texel_center_score'): if name in routing: routing[name][sl] = torch.where(accepted, static[name][1], routing[name][sl]) routing['confidence'][sl] = torch.where(accepted, probability[sl], routing['confidence'][sl]) margin = (2*probability[sl]-1).clamp_min(0) for name, value in [('confidence_margin', margin), ('confidence_margin_ratio', margin/probability[sl].clamp_min(1e-6))]: if name in routing: routing[name][sl] = torch.where(accepted, value, routing[name][sl]) # Learned inner crown/band evidence can also correct an old outer route. # This is restricted to explicitly trained components; no RGB rule is used. inner_support=torch.zeros_like(foreground) component_logits=outputs.get('hat_component_logits') if component_logits is not None: cp,ci=component_logits.float().softmax(1).max(1) candidate=((ci==1)|(ci==2))&(cp>=.95)&(identity==0)&foreground for vi,view in enumerate(views): sl=slice(vi,foreground.shape[0],len(views)) static=build_static_surface_routing(renderer,view,foreground.device) accepted=candidate[sl]&static['masks'][0]&(static['part'][0]==0) inner_support[sl]=accepted for name,value in [('layer',0),('foreground',True),('surface',0),('secondary',False),('secondary_routed',False),('semantic_fallback',False)]: if name in routing:routing[name][sl]=torch.where(accepted,torch.full_like(routing[name][sl],value),routing[name][sl]) for name in ('flat_uv','part','face','texel_center_score'): if name in routing:routing[name][sl]=torch.where(accepted,static[name][0],routing[name][sl]) routing['confidence'][sl]=torch.where(accepted,cp[sl],routing['confidence'][sl]) cm=(2*cp[sl]-1).clamp_min(0) for name,value in [('confidence_margin',cm),('confidence_margin_ratio',cm/cp[sl].clamp_min(1e-6))]: if name in routing:routing[name][sl]=torch.where(accepted,value,routing[name][sl]) routing['hat_inner_supported']=inner_support routing['accessory_identity'] = identity routing['accessory_probability'] = probability routing['accessory_supported'] = support routing['accessory_seed'] = seeds from SkingToolkit.dense_uv_parser.ownership import apply_head_ownership apply_head_ownership(routing, outputs, foreground, renderer, views) from SkingToolkit.dense_uv_parser.headwear import apply_headwear_routing apply_headwear_routing(routing, outputs, foreground, renderer, views) return routing['accessory_supported']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Procedural object-labelled skins. Labels describe authored objects, not RGB rules."""import numpy as npimport torchfrom torch.utils.data import Datasetfrom SkingToolkit.dense_uv_parser.skin_dataset import load_skin
def make_accessory_skin(original, seed, return_components=False): rng = np.random.default_rng(seed) uv = original.permute(1, 2, 0).numpy().copy() objects = np.zeros((64, 64), dtype=np.int64) components = np.zeros((64,64),dtype=np.int64) # none, inner crown/band, outer crown/band, brim # All six head faces are authored together. Body pixels remain the source skin. uv[:16, :32] = 0 uv[:16, 32:] = 0 faces = [(8, 8), (24, 8), (0, 8), (16, 8), (8, 0), (16, 0)] skin = np.array(rng.choice([[.87,.63,.43],[.45,.28,.19],[.65,.44,.30], [.95,.78,.62],[.32,.20,.13],[.74,.62,.49]])) if rng.random() < .12: skin = rng.uniform(.2, .9, 3) hair = rng.uniform(.03, .30, 3) if rng.random() < .7 else rng.uniform(.1, .85, 3) for fi, (x, y) in enumerate(faces): tex = np.clip(skin[None,None] + rng.normal(0,.025,(8,8,1)), 0, 1) if fi in (1,4): tex[:] = hair + rng.normal(0,.025,(8,8,1)) if fi in (0,2,3): tex[:rng.integers(1,3)] = hair uv[y:y+8, x:x+8, :3] = np.clip(tex,0,1) uv[y:y+8, x:x+8, 3] = 1 # Eyes, eyebrows and mouth are explicit negative facial examples. for x in (9, 13): uv[11:12, x:x+2, :3] = rng.uniform(.01,.18,3) uv[14,11:13,:3] = rng.uniform(.05,.5,3) if rng.random() < .4: uv[10,9:11,:3] = hair uv[10,13:15,:3] = hair
def put(face, mask, color, identity, layer=1, component=0): x, y = faces[face]; x += 32*layer patch = uv[y:y+8, x:x+8] patch[mask, :3] = color[mask] if np.asarray(color).ndim == 3 else color patch[mask, 3] = 1 objects[y:y+8, x:x+8][mask] = identity components[y:y+8, x:x+8][mask] = component
yy, xx = np.mgrid[:8,:8] negative = rng.random() < .18 if not negative and rng.random() < .78: top = int(rng.integers(2,4)); height = int(rng.integers(3,5)) frame_color = rng.uniform(.025,.23,3) if rng.random()<.70 else rng.uniform(.01,.85,3) lens_color = rng.uniform(.05,.95,3) frame = np.zeros((8,8),bool); lenses = np.zeros_like(frame) # Distinct connected eyewear styles; class ID is independent of palette. visor = rng.random()<.20 boxes = [(0,3),(4,7)] if visor else [(0,2),(5,7)] hollow = rng.random()<.30 rimless_top = rng.random()<.45 and not hollow for box_index,(left, right) in enumerate(boxes): rectangle = (xx>=left)&(xx<=right)&(yy>=top)&(yy<top+height) edge = rectangle & ((xx==left)|(xx==right)|(yy==top)|(yy==top+height-1)) if rimless_top: edge &= (yy!=top) # Thin inner rim variants preserve two-column lenses on an 8px face. if not visor and not hollow and rng.random()<.65: inner_x=right if box_index==0 else left edge &= ~((xx==inner_x)&(yy<top+height-1)) if rng.random() < .2: edge &= ~(((xx==left)|(xx==right))&(yy==top+height-1)) frame |= edge lenses |= rectangle & ~edge bridge_y = min(7,top+int(rng.integers(0,2))) frame[bridge_y,2:6] = True lenses[frame] = False if hollow: lenses[:] = False # open-frame holes stay empty color = np.broadcast_to(frame_color,(8,8,3)).copy() color[lenses] = lens_color # Lens shading keeps the same object ID across several colours. color[lenses] *= rng.uniform(.65,1.05,(8,8,1))[lenses] put(0, frame|lenses, np.clip(color,0,1), 1) for face in (2,3): length = int(rng.integers(3,9)) temple = (yy==bridge_y)&(xx<length) put(face,temple,frame_color,1) kind = int(rng.choice([0,2,3], p=[.35,.40,.25])) if not negative else 0 if kind==2: # Geometry and material are independent variables. A whole hat can have # an inner crown/band and an extruded brim; the band is not background. color = rng.uniform(.02,.17,3) if rng.random()<.65 else rng.uniform(.05,.85,3) depth = int(rng.integers(2,6)) stepped = rng.random()<.70 variant = int(rng.choice(3,p=[.75,.15,.10])) # full ring, front visor, partial/asymmetric band_color = rng.uniform(.04,.95,3) if rng.random()<.3: band_color=np.array([rng.uniform(.5,.95),rng.uniform(.02,.12),rng.uniform(.02,.12)]) if rng.random()<.2: band_color=color*rng.uniform(.7,1.2) has_band = rng.random()<.85 crown_layer=0 if stepped else 1 crown_component=1 if stepped else 3 band_component=2 if stepped else 4 put(4,np.ones((8,8),bool),color,0 if stepped else 2,layer=crown_layer,component=crown_component) for face in (0,1,2,3): tex=np.clip(np.broadcast_to(color,(8,8,3))+rng.normal(0,.02,(8,8,1)),0,1) crown=yy<depth-1 put(face,crown,tex,0 if stepped else 2,layer=crown_layer,component=crown_component) if has_band: put(face,yy==depth-2,np.clip(band_color,0,1),0 if stepped else 2,layer=crown_layer,component=band_component) brim=yy==depth-1 if variant==1 and face!=0: brim[:]=False if variant==2 and face in (1,3): brim &= xx<5 put(face,brim,color,2,component=5) elif kind==3: put(4,np.ones((8,8),bool),hair,3) for face in (0,1,2,3): depth=int(rng.integers(1,4)) if face==0 else int(rng.integers(2,7)) mask=(yy<depth)|((yy==depth)&(rng.random((8,8))>.45)) tex=np.clip(np.broadcast_to(hair,(8,8,3))+rng.normal(0,.025,(8,8,1)),0,1) put(face,mask,tex,3) if return_components: return torch.from_numpy(uv).permute(2,0,1).float(),torch.from_numpy(objects),torch.from_numpy(components) return torch.from_numpy(uv).permute(2,0,1).float(), torch.from_numpy(objects)
class AccessoryDataset(Dataset): def __init__(self, paths, count, seed): self.paths, self.count, self.seed, self.epoch = list(paths), count, seed, 0
def __len__(self): return self.count
def __getitem__(self, index): seed = self.seed + index*104729 + self.epoch*self.count*104729 source = load_skin(self.paths[(index + self.epoch*self.count) % len(self.paths)]) uv, objects, components = make_accessory_skin(source, seed, return_components=True) return {'uv':uv,'objects':objects,'components':components,'seed':seed}
def render_accessories(uv, objects, renderer, views, components=None): from SkingToolkit.dense_uv_parser.utils import build_dense_parser_batch images, labels, foregrounds, parts = [], [], [], [] for view in views: rendered, target = build_dense_parser_batch(uv, renderer, view) xy = (target['uv']*63).round().long().clamp(0,63) flat = xy[:,1]*64+xy[:,0] identity = objects.flatten(1).gather(1,flat.flatten(1)).reshape_as(flat) identity = identity.masked_fill((target['layer'] != 1) | (target['foreground'][:,0] < .5), 0) images.append(rendered);labels.append(identity);foregrounds.append(target['foreground'][:,0].bool()) if components is not None: part=components.flatten(1).gather(1,flat.flatten(1)).reshape_as(flat) parts.append(part.masked_fill(target['foreground'][:,0]<.5,0)) b = uv.shape[0] result=(torch.stack(images,1).flatten(0,1),torch.stack(labels,1).flatten(0,1),torch.stack(foregrounds,1).flatten(0,1)) return result+(torch.stack(parts,1).flatten(0,1),) if components is not None else result1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889"""The same foreground, routing, completion and renderer path for v101 eval/infer."""import jsonfrom pathlib import Pathimport torchfrom SkingToolkit.dense_uv_parser.foreground import build_parser_input,learned_foreground_supportfrom SkingToolkit.dense_uv_parser.utils import estimate_top_left_flood_foreground, splat_parser_predictions_to_uv_conditioningfrom SkingToolkit.dense_uv_parser.infer import simple_inpaint_uv
def load_pipeline(path=None): return json.loads(Path(path or Path(__file__).with_name('v101_pipeline.json')).read_text())
@torch.no_grad()def run_pipeline(model, renderer, images, config=None, complete=False, outputs=None, foreground_probability=None): config = config or load_pipeline() views = config['routing']['views'] color_sources=None if foreground_probability is None: fg = estimate_top_left_flood_foreground(images, config['foreground_flood_tolerance']) else: if foreground_probability.shape != images.shape[:1]+images.shape[-2:]: raise ValueError('Foreground probability must have shape (N,H,W)') probability=foreground_probability.to(device=images.device,dtype=torch.float32) if not torch.isfinite(probability).all() or probability.min()<0 or probability.max()>1: raise ValueError('Foreground probability must be finite in [0,1]') 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)) actual = build_parser_input(images, fg, background_mode=config['foreground_background']) if outputs is None: outputs = model(actual, view_ids=torch.arange(images.shape[0], device=images.device) % len(views), semantic_foreground=fg) outputs = {**outputs, 'accessory_route_threshold':config['accessory_route_threshold']} outputs['headwear_presence_threshold']=config.get('headwear_presence_threshold',.95) outputs['headphone_presence_threshold']=config.get('headphone_presence_threshold',.9) outputs['headphone_presence_consensus']=config.get('headphone_presence_consensus',False) mode=config.get('headphone_routing_mode','unrestricted') def splat(current): return splat_parser_predictions_to_uv_conditioning( images,current,renderer=renderer,observed_foreground=fg,observed_color_support=color_sources,return_details=True,**config['routing']) if mode=='existing_uv' and 'head_ownership_logits' in outputs: # The new headphone head may recover colour ownership inside geometry # already accepted by v101. It cannot manufacture new outer occupancy. initial,_=splat({**outputs,'headphone_routing_mode':'disabled'}) outputs={**outputs,'headphone_routing_mode':'existing_uv','headphone_uv_support':(initial[:,9]>.5).flatten(1)} else:outputs={**outputs,'headphone_routing_mode':mode} cond,details=splat(outputs) geometry_mode = config.get('crown_top_geometry_mode', 'legacy_consensus') if geometry_mode == 'rendered_semantics': from SkingToolkit.dense_uv_parser.crown_geometry import reconcile_crown_geometry cond = reconcile_crown_geometry(cond, details, renderer, views) elif geometry_mode == 'legacy_consensus': from SkingToolkit.dense_uv_parser.headwear import reconcile_crown_top cond = reconcile_crown_top(cond, details, renderer, views) else: raise ValueError('Unknown crown top geometry mode: ' + str(geometry_mode)) result = {'foreground_color_sources':color_sources,'foreground_probability':foreground_probability,'conditioning':cond,'details':details,'outputs':outputs,'foreground':fg} if complete: result['uv'] = torch.stack([simple_inpaint_uv(c[None].cpu())[0] for c in cond]).to(images.device) if config.get('head_semantic_inpaint',False): from SkingToolkit.dense_uv_parser.head_inpainting import repair_hidden_head_material result['uv']=repair_hidden_head_material(result['uv'],cond,details,views) from SkingToolkit.dense_uv_parser.headwear import isolate_headwear_material result['uv'],headwear_uv=isolate_headwear_material(result['uv'],cond,details,views) if config.get('head_material_refine_steps',0): from SkingToolkit.dense_uv_parser.material_refine import refine_head_material if config.get('head_material_refine_mode')!='isolated': from SkingToolkit.dense_uv_parser.material_refine import refine_head_material_legacy result['uv']=refine_head_material_legacy(result['uv'],details['rendered'],details['color_source_support'],renderer,views,config['head_material_refine_steps']) else: 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')) result['render'] = torch.stack([renderer.forward_view(result['uv'], view) for view in views],1).flatten(0,1) return result
def cached_real_foreground(images, source, config): """Load verified learned foreground for real development evaluation.""" import hashlib import numpy as np from PIL import Image import torch.nn.functional as F cache=config.get('foreground_cache') if cache is None:return None source=Path(source).resolve();entry=cache.get(str(source)) if entry is None:raise ValueError('Missing learned foreground for '+str(source)) data=Path(entry['probability']).read_bytes() if hashlib.sha256(source.read_bytes()).hexdigest()!=entry['input_sha256'] or hashlib.sha256(data).hexdigest()!=entry['probability_sha256']: raise ValueError('Learned foreground cache changed') import io p=torch.from_numpy(np.array(Image.open(io.BytesIO(data))).copy()).float().to(images.device)/255. return F.interpolate(torch.stack(p.chunk(len(config['routing']['views']),1))[:,None],images.shape[-2:],mode='nearest-exact')[:,0].gitattributesAdded+39
LICENSEAdded+662
README.mdAdded+75
SKING_DDJ_v101c/LICENSEAdded+661
SKING_DDJ_v101c/README.mdAdded+64
SKING_DDJ_v101c/THIRD_PARTY_NOTICES.mdAdded+7
SKING_DDJ_v101c/foreground.ptAdded+3
SKING_DDJ_v101c/foreground_base/BiRefNet_config.pyAdded+11
SKING_DDJ_v101c/foreground_base/birefnet.pyAdded+2249
SKING_DDJ_v101c/foreground_base/config.jsonAdded+20
SKING_DDJ_v101c/foreground_base/model.safetensorsAdded+3
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/refs/mainAdded+1
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/config.jsonAdded+12
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/model.safetensorsAdded+3
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/preprocessor_config.jsonAdded+24
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/special_tokens_map.jsonAdded+34
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.jsonAdded+3
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer.modelAdded+3
SKING_DDJ_v101c/hf_cache/hub/models--google--siglip2-base-patch16-224/snapshots/75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2/tokenizer_config.jsonAdded+2020
SKING_DDJ_v101c/hf_cache/modules/__init__.pyAdded
SKING_DDJ_v101c/hf_cache/modules/transformers_modules/__init__.pyAdded
SKING_DDJ_v101c/hf_cache/modules/transformers_modules/foreground_base/BiRefNet_config.pyAdded+11
SKING_DDJ_v101c/hf_cache/modules/transformers_modules/foreground_base/__init__.pyAdded
SKING_DDJ_v101c/hf_cache/modules/transformers_modules/foreground_base/birefnet.pyAdded+2249
SKING_DDJ_v101c/infer.pyAdded+214
SKING_DDJ_v101c/licenses/BiRefNet_LICENSE.txtAdded+21
SKING_DDJ_v101c/licenses/SigLIP2_LICENSE.txtAdded+201
SKING_DDJ_v101c/licenses/sources.jsonAdded+14
SKING_DDJ_v101c/mappings_256x512/back_left_mapping.ptAdded+3
SKING_DDJ_v101c/mappings_256x512/back_left_overlay_mapping.ptAdded+3
SKING_DDJ_v101c/mappings_256x512/back_right_mapping.ptAdded+3
SKING_DDJ_v101c/mappings_256x512/back_right_overlay_mapping.ptAdded+3
SKING_DDJ_v101c/mappings_256x512/front_left_mapping.ptAdded+3
SKING_DDJ_v101c/mappings_256x512/front_left_overlay_mapping.ptAdded+3
SKING_DDJ_v101c/mappings_256x512/front_right_mapping.ptAdded+3
SKING_DDJ_v101c/mappings_256x512/front_right_overlay_mapping.ptAdded+3
SKING_DDJ_v101c/mappings_256x512/static_back_mapping.ptAdded+3
SKING_DDJ_v101c/mappings_256x512/static_front_mapping.ptAdded+3
SKING_DDJ_v101c/mappings_256x512/walk_back_base_layer_ortho_mapping.ptAdded+3
SKING_DDJ_v101c/mappings_256x512/walk_back_both_layer_ortho_mapping.ptAdded+3
SKING_DDJ_v101c/mappings_256x512/walk_front_base_layer_ortho_mapping.ptAdded+3
SKING_DDJ_v101c/mappings_256x512/walk_front_both_layer_ortho_mapping.ptAdded+3
SKING_DDJ_v101c/parser.ptAdded+3
SKING_DDJ_v101c/pipeline.jsonAdded+79
SKING_DDJ_v101c/release.jsonAdded+142
SKING_DDJ_v101c/runtime/LICENSEAdded+661
SKING_DDJ_v101c/runtime/dense_uv_parser/__init__.pyAdded+2
SKING_DDJ_v101c/runtime/dense_uv_parser/accessories.pyAdded+199
SKING_DDJ_v101c/runtime/dense_uv_parser/accessory_data.pyAdded+148
SKING_DDJ_v101c/runtime/dense_uv_parser/accessory_pipeline.pyAdded+89