Segformer++ (code, models, paper)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+4
- Segformer++. Efficient Token-Merging Strategies for High-Resolution Semantic Segmentation.pdfAdded+3
- code/SegformerPlusPlus.zipAdded+3
- models/SegformerPlusPlus (KieDani)/.gitattributesAdded+38
- models/SegformerPlusPlus (KieDani)/LICENSE.txtAdded+674
- models/SegformerPlusPlus (KieDani)/README.mdAdded+96
- models/SegformerPlusPlus (KieDani)/docs/figures/pose.pngAdded
- models/SegformerPlusPlus (KieDani)/docs/figures/segmentation.pngAdded
- models/SegformerPlusPlus (KieDani)/docs/run/run_mmeng.mdAdded+15
- models/SegformerPlusPlus (KieDani)/docs/run/run_mmpose.mdAdded+23
- models/SegformerPlusPlus (KieDani)/docs/run/run_mmseg.mdAdded+23
- models/SegformerPlusPlus (KieDani)/docs/run/run_noopenmmlab.mdAdded+137
- models/SegformerPlusPlus (KieDani)/docs/run/token_merging.mdAdded+50
- models/SegformerPlusPlus (KieDani)/docs/setup/mmeng_setup.mdAdded+34
- models/SegformerPlusPlus (KieDani)/docs/setup/mmpose_setup.mdAdded+24
- models/SegformerPlusPlus (KieDani)/docs/setup/mmseg_setup.mdAdded+25
- models/SegformerPlusPlus (KieDani)/docs/setup/noopenmmlab_setup.mdAdded+15
- models/SegformerPlusPlus (KieDani)/docs/setup/torchhub_setup.mdAdded+139
- models/SegformerPlusPlus (KieDani)/example_torchhub.pyAdded+58
- models/SegformerPlusPlus (KieDani)/hubconf.pyAdded+185
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/pyproject.tomlAdded+40
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/Registry/__init__.pyAdded+3
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/Registry/__pycache__/__init__.cpython-310.pycAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/Registry/__pycache__/default_scope.cpython-310.pycAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/Registry/__pycache__/registry.cpython-310.pycAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/Registry/default_scope.pyAdded+95
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/Registry/registry.pyAdded+557
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/__init__.pyAdded+4
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/__pycache__/__init__.cpython-310.pycAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/__pycache__/build_model.cpython-310.pycAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/__pycache__/cityscape_benchmark.cpython-310.pycAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/__pycache__/random_benchmark.cpython-310.pycAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/__pycache__/start_cityscape_benchmark.cpython-310.pycAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/build_model.pyAdded+107
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/cityscape/berlin_000543_000019_leftImg8bit.pngAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/cityscape_benchmark.pyAdded+108
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/cityscapes_prediction_output.txtAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/cityscapes_prediction_output__reference_b05_bsm_hq_checkpoint.txtAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/__init__.pyAdded+1
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/__pycache__/__init__.cpython-310.pycAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/config/__pycache__/config.cpython-310.pycAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/config/__pycache__/lazy.cpython-310.pycAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/config/__pycache__/utils.cpython-310.pycAdded
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/config/config.pyAdded+1545
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/config/lazy.pyAdded+267
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/config/utils.pyAdded+687
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b0.pyAdded+28
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b1.pyAdded+8
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b2.pyAdded+6
- models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b3.pyAdded+6
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353637383932 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textmodels/SegformerPlusPlus[[:space:]](KieDani)/docs/figures/pose.png filter=lfs diff=lfs merge=lfs -textmodels/SegformerPlusPlus[[:space:]](KieDani)/docs/figures/segmentation.png filter=lfs diff=lfs merge=lfs -textmodels/SegformerPlusPlus[[:space:]](KieDani)/model_without_OpenMMLab/segformer_plusplus/cityscape/berlin_000543_000019_leftImg8bit.png filter=lfs diff=lfs merge=lfs -textSegformer++.[[:space:]]Efficient[[:space:]]Token-Merging[[:space:]]Strategies[[:space:]]for[[:space:]]High-Resolution[[:space:]]Semantic[[:space:]]Segmentation.pdf filter=lfs diff=lfs merge=lfs -text
123version https://git-lfs.github.com/spec/v1oid sha256:b8160e1122cfac1856295d5959ae6277c17a5423b28fab92591a6672559a5d82size 825467123version https://git-lfs.github.com/spec/v1oid sha256:baba867edf2a41fb5ecbc04eae20911e827bb58c0ce2606e8a72dcf303485e00size 97198811234567891011121314151617181920212223242526272829303132333435363738*.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 -text
saved_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
docs/figures/pose.png filter=lfs diff=lfs merge=lfs -text
docs/figures/segmentation.png filter=lfs diff=lfs merge=lfs -text
model_without_OpenMMLab/segformer_plusplus/cityscape/berlin_000543_000019_leftImg8bit.png filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 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 General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. 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 work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a 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 visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation 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 to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients 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 to
produce it from the Program, in the form of source code under the
terms 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 independent
works, 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 not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-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 excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the 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 install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional 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 you
add to a covered work, you may (if authorized by the copyright holders of
that 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 "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form 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 expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered 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 automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent 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 anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain 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 limiting
any implied license or other defenses to infringement that may
otherwise 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 or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES 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 OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy 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 greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "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 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 General Public License for more details.
You should have received a copy of the GNU 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 the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
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 GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596---
license: gpl-3.0
language:
- en
pipeline_tag: image-segmentation
---
# SegFormer++
Paper: [Segformer++: Efficient Token-Merging Strategies for High-Resolution Semantic Segmentation](https://arxiv.org/abs/2405.14467)


## Abstract
Utilizing transformer architectures for semantic segmentation of high-resolution images is hindered by the attention's quadratic computational complexity in the number of tokens. A solution to this challenge involves decreasing the number of tokens through token merging, which has exhibited remarkable enhancements in inference speed, training efficiency, and memory utilization for image classification tasks. In this paper, we explore various token merging strategies within the framework of the SegFormer architecture and perform experiments on multiple semantic segmentation and human pose estimation datasets. Notably, without model re-training, we, for example, achieve an inference acceleration of 61% on the Cityscapes dataset while maintaining the mIoU performance. Consequently, this paper facilitates the deployment of transformer-based architectures on resource-constrained devices and in real-time applications.
**Update:** It is now possible to load the model via torch.hub. See [here](docs/setup/torchhub_setup.md).
**Update:** It is now possible to run the model **without OpenMMLab dependencies**, enabling users to utilize the SegFormerPlusPlus architecture without installing the full OpenMMLab framework.
## Results and Models
Memory refers to the VRAM requirements during the training process.
### Inference on Cityscapes (MiT-B5)
The weights of the Segformer (Original) model were used to get the inference results.
| Method | mIoU | Speed-Up | download |
|-----------------------------------|------:|---------:|----------------------------------------------------------------|
| Segformer (Original) | 82.39 | - | [model](https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/) |
| Segformer++<sub>HQ</sub> (ours) | 82.31 | 1.61 | [model](https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/) |
| Segformer++<sub>fast</sub> (ours) | 82.04 | 1.94 | [model](https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/) |
| Segformer++<sub>2x2</sub> (ours) | 81.96 | 1.90 | [model](https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/) |
| Segformer (Downsampling) | 77.31 | 6.51 | [model](https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/) |
### Training on Cityscapes (MiT-B5)
| Method | mIoU | Speed-Up | Memory (GB) | download |
|-----------------------------------|------:|---------:|-------------|-----------------------------------------------------------------|
| Segformer (Original) | 82.39 | - | 48.3 | [model](https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/) |
| Segformer++<sub>HQ</sub> (ours) | 82.19 | 1.40 | 34.0 | [model](https://mediastore.rz.uni-augsburg.de/get/i8fY8uXJrV/ ) |
| Segformer++<sub>fast</sub> (ours) | 81.77 | 1.55 | 30.5 | [model](https://mediastore.rz.uni-augsburg.de/get/cmG974iAxt/ ) |
| Segformer++<sub>2x2</sub> (ours) | 82.38 | 1.63 | 31.1 | [model](https://mediastore.rz.uni-augsburg.de/get/p0uMKbw531/) |
| Segformer (Downsampling) | 79.24 | 2.95 | 10.0 | [model](https://mediastore.rz.uni-augsburg.de/get/73zkKSO21t/) |
### Training on ADE20K (640x640) (MiT-B5)
| Method | mIoU | Speed-Up | Memory (GB) | download |
|-----------------------------------|------:|---------:|------------:|----------------------------------------------------------------|
| Segformer (Original) | 49.72 | - | 33.7 | [model](https://mediastore.rz.uni-augsburg.de/get/nKEjUHNAfK/) |
| Segformer++<sub>HQ</sub> (ours) | 49.77 | 1.15 | 29.2 | [model](https://mediastore.rz.uni-augsburg.de/get/Odyie8usgj/) |
| Segformer++<sub>fast</sub> (ours) | 49.10 | 1.20 | 28.0 | [model](https://mediastore.rz.uni-augsburg.de/get/K0IGkx4O2s/) |
| Segformer++<sub>2x2</sub> (ours) | 49.35 | 1.26 | 27.2 | [model](https://mediastore.rz.uni-augsburg.de/get/w5_Pxx4Q5C/) |
| Segformer (Downsampling) | 46.71 | 1.89 | 12.4 | [model](https://mediastore.rz.uni-augsburg.de/get/dFVvZQL6iL/) |
### Training on JBD
| Method | PCK@0.1 | PCK@0.05 | Speed-Up | Memory (GB) | download |
|-----------------------------------|--------:|---------:|---------:|------------:|----------------------------------------------------------------|
| Segformer (Original) | 95.20 | 90.65 | - | 40.0 | [model](https://mediastore.rz.uni-augsburg.de/get/psolrWXLLp/) |
| Segformer++<sub>HQ</sub> (ours) | 95.18 | 90.51 | 1.19 | 36.0 | [model](https://mediastore.rz.uni-augsburg.de/get/jx1eyecMLF/) |
| Segformer++<sub>fast</sub> (ours) | 94.58 | 89.87 | 1.25 | 34.6 | [model](https://mediastore.rz.uni-augsburg.de/get/K0IGkx4O2s/) |
| Segformer++<sub>2x2</sub> (ours) | 95.17 | 90.16 | 1.27 | 33.4 | [model](https://mediastore.rz.uni-augsburg.de/get/HumKbSB1vI/) |
### Training on MS COCO
| Method | PCK@0.1 | PCK@0.05 | Speed-Up | Memory (GB) | download |
|-----------------------------------|--------:|---------:|---------:|------------:|----------------------------------------------------------------|
| Segformer (Original) | 95.16 | 87.61 | - | 13.5 | [model](https://mediastore.rz.uni-augsburg.de/get/ZOgj2NmQLy/) |
| Segformer++<sub>HQ</sub> (ours) | 94.97 | 87.35 | 0.97 | 13.1 | [model](https://mediastore.rz.uni-augsburg.de/get/oAH5IlPxG8/) |
| Segformer++<sub>fast</sub> (ours) | 95.02 | 87.37 | 0.99 | 12.9 | [model](https://mediastore.rz.uni-augsburg.de/get/3E2mMNLAAn/) |
| Segformer++<sub>2x2</sub> (ours) | 94.98 | 87.36 | 1.24 | 12.3 | [model](https://mediastore.rz.uni-augsburg.de/get/rzlgKC5XLc/) |
## Usage
Easy usage:
- [Use the SegFormer++ easily via TorchHub](docs/setup/torchhub_setup.md)
- [Use the SegFormer++ directly](docs/setup/noopenmmlab_setup.md)
Explanation of the different token merging strategies:
- [Token Merging Settings](docs/run/token_merging.md)
Legacy Variants (e.g. as part of mmseg or mmpose) can be found on GitHub: https://github.com/KieDani/SegformerPlusPlus
## Citation
```bibtex
@article{kienzle2024segformer++,
title={Segformer++: Efficient Token-Merging Strategies for High-Resolution Semantic Segmentation},
author={Kienzle, Daniel and Kantonis, Marco and Sch{\"o}n, Robin and Lienhart, Rainer},
journal={IEEE International Conference on Multimedia Information Processing and Retrieval (MIPR)},
year={2024}
}
```123456789101112131415# Use the SegFormer++ outside MMSegmentation/MMPose
- Use [build_model.py](../../model/segformer/build_model.py) to build preset and custom SegFormer++ models
```python
model = create_model('b5', 'bsm_hq', pretrained=True)
```
Running this code snippet yields our SegFormer++<sub>HQ</sub> model pretrained on ImageNet.
- Use [random_benchmark.py](../../model/segformer/random_benchmark.py) to evaluate a model in terms of FPS
```python
v = random_benchmark(model)
```
Calculate the FPS using our script.1234567891011121314151617181920212223# Run Experiments (MMPose)
The configuration files for our models can be found here:
- [Custom configuration files](../../mmpose/local_configs)
## Training
```shell
python tools/train.py 'path/to/config'
```
## Evaluation
```shell
python tools/test.py 'path/to/config' 'path/to/checkpoint'
```
## FPS
```shell
python tools/analysis_tools/random_benchmark.py -c 'path/to/config' -i 3x480x640 -b 16
```1234567891011121314151617181920212223# Run Experiments (MMSegmentation)
The configuration files for our models can be found here:
- [Custom configuration files](../../mmsegmentation/local_configs)
## Training
```shell
python tools/train.py 'path/to/config'
```
## Evaluation
```shell
python tools/test.py 'path/to/config' 'path/to/checkpoint'
```
## FPS
```shell
python tools/analysis_tools/random_benchmark.py -c 'path/to/config' -i 3x1024x1024 -b 8
```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137# Use the SegFormer++ without OpenMMLab:
## Building a Model
- Use [build_model.py](../../model_without_OpenMMLab/segformer_plusplus/build_model.py) to build preset and custom SegFormer++ models
Navigate to model_without_OpenMMLab.
```python
from segformer_plusplus.build_model import create_model
# backbone: choose from ['b0', 'b1', 'b2', 'b3', 'b4', 'b5']
# tome_strategy: choose from ['bsm_hq', 'bsm_fast', 'n2d_2x2']
out_channels = 19 # number of classes, e.g. 19 for cityscapes
model = create_model('b5', 'bsm_hq', out_channels=out_channels, pretrained=True)
```
Running this code snippet yields our SegFormer++<sub>HQ</sub> model pretrained on ImageNet.
- Use [random_benchmark.py](../../model_without_OpenMMLab/segformer_plusplus/random_benchmark.py) to evaluate a model in terms of FPS
```python
from segformer_plusplus.random_benchmark import random_benchmark
v = random_benchmark(model)
```
Calculate the FPS using our script.
## Loading a Checkpoint
[Checkpoints](../../README.md) are provided in this Repository.
They can be loaded and integrated into the model via PyTorch:
```python
import torch
checkpoint_path = "path_to_your_checkpoint.pth that you downloaded (links in Readme)"
checkpoint = torch.load(checkpoint_path)
model.load_state_dict(checkpoint)
```
An Example can be found in [start_cityscape_benchmark.py](../../model_without_OpenMMLab/segformer_plusplus/start_cityscape_benchmark.py)
## Image Preperation
Images can be imported via PIL and then converted into RGB:
```python
from PIL import Image
image_path = "path_to_your_image.png"
image = Image.open(image_path).convert("RGB")
```
After that, convert the image into a torch tensor:
```python
import torch
import numpy as np
img_tensor = torch.from_numpy(np.array(image) / 255.0)
img_tensor = img_tensor.permute(2, 0, 1).float().unsqueeze(0) # (1, C, H, W)
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
img_tensor = img_tensor.to(device)
```
Now we can load the model:
```python
from segformer_plusplus.build_model import create_model
out_channels = 19
model = create_model(
backbone='b5',
tome_strategy='bsm_hq',
out_channels=out_channels,
pretrained=False
).to(device)
model.load_state_dict(torch.load("path_to_checkpoint", map_location=device))
model.eval()
```
Inference:
```python
with torch.no_grad():
output = model(img_tensor)
segmentation_map = torch.argmax(output, dim=1).squeeze().cpu().numpy()
```
Visualize the results (this is for cityscapes classes):
```python
import numpy as np
# Official Cityscapes colors for train IDs 0-18
cityscapes_colors = np.array([
[128, 64, 128], # 0: road
[244, 35, 232], # 1: sidewalk
[ 70, 70, 70], # 2: building
[102, 102, 156], # 3: wall
[190, 153, 153], # 4: fence
[153, 153, 153], # 5: pole
[250, 170, 30], # 6: traffic light
[220, 220, 0], # 7: traffic sign
[107, 142, 35], # 8: vegetation
[152, 251, 152], # 9: terrain
[ 70, 130, 180], # 10: sky
[220, 20, 60], # 11: person
[255, 0, 0], # 12: rider
[ 0, 0, 142], # 13: car
[ 0, 0, 70], # 14: truck
[ 0, 60, 100], # 15: bus
[ 0, 80, 100], # 16: train
[ 0, 0, 230], # 17: motorcycle
[119, 11, 32], # 18: bicycle
], dtype=np.uint8)
# Map each class to its corresponding color
height, width = segmentation_map.shape
color_image = np.zeros((height, width, 3), dtype=np.uint8)
for class_index in range(len(cityscapes_colors)):
color_image[segmentation_map == class_index] = cityscapes_colors[class_index]
```
Display and save output:
```python
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 6))
plt.imshow(color_image)
plt.title("Semantic Segmentation Visualization")
plt.axis('off')
plt.show()
# Save the colorized output as an image - important when using a System without GUI
plt.imsave("segmentation_output.png", color_image)
```
> Note: You have to install matplotlib for visualization.
## Token-Merge Setting
For information to the settings for the Token Merging look [here](../../docs/run/token_merging.md).
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950## Specify Algorithms and Parameters for Token Merging
In order for token merging to be applied, a list of python dictionary called *tome_cfg* must be added to the configuration file within the context of the SegFormer backbone.
**Example**
Bipartite Soft Matching high quality preset:
```python
model = dict(
backbone=dict(
tome_cfg=[
dict(kv_mode='bsm', kv_r=0.6, kv_sx=2, kv_sy=2), # Stage 1
dict(kv_mode='bsm', kv_r=0.6, kv_sx=2, kv_sy=2), # Stage 2
dict(q_mode='bsm', q_r=0.8, q_sx=4, q_sy=4), # Stage 3
dict(q_mode='bsm', q_r=0.8, q_sx=4, q_sy=4) # Stage 4
]
)
)
```
Both a *q_mode* and a *kv_mode* can be specified for each stage.
The following modes are available:
#### Bipartite Soft Matching (SegFormer++<sub>HQ</sub> and SegFormer++<sub>fast</sub>)
```python
dict(q_mode='bsm', q_scale_factor=0.8, q_sx=2, q_sy=2)
```
This works in the same way as *bsm*. However, additionally *q_sx* and *q_sy* have to be specified that are the strides
used to select the tokens in the destination set.
#### 1D Neighbour Merging
```python
dict(q_mode='n1d', q_s=2)
```
The stride/kernel size employed for the average pooling has to be specified using the *q_scale_factor*.
#### 2D Neighbour Merging
```python
dict(q_mode='n2d', q_s=(2, 2))
```
Here, two strides for both directions have to be specified.
If token merging is applied for keys and values exclusively, the *q_mode* has to be set to *None* and the parameters
have to be specified for keys and values. It is also possible to merge the query tokens as well as the key and value tokens.
Therefore, parameters for both sequences have to be specified:
```python
dict(q_mode='n2d', kv_mode='bsm', q_s=(2, 2), kv_r=0.6, kv_sx=2, kv_sy=2)
```12345678910111213141516171819202122232425262728293031323334# Install the SegFormer++ without MMSegmentation/MMPose
**Step 0.** Prerequisites
- Pytorch: 2.3 (CUDA 12.1) (older versions should also work fine)
**Step 1.** Install [MMCV](https://github.com/open-mmlab/mmcv) using [MIM](https://github.com/open-mmlab/mim).
```shell
pip install -U openmim
mim install mmengine
mim install "mmcv>=2.0.0"
```
**Step 2.** Install Segformer++
```shell
cd model
pip install .
```
**Step 3.** [Run the SegFormer++](../run/run_mmeng.md)
**Troubleshooting**
There might be installation troubles with openmim, mmengine, and mmcv for new python versions. Thus, Step 1 might not work correctly.
In this case, try the following alternative for step 1:
```shell
pip install torch torchvision numpy
pip install mmcv-full==1.2.7
pip install mmcv
```
If it is still not working, make sure to use a pip virtual environment (python -m venv "name of the environment"), not a conda environment.123456789101112131415161718192021222324# MMSegmentation Setup
**Step 0.** Prerequisites
- Pytorch: 2.0.1 (CUDA 11.8)
**Step 1.** Install [MMCV](https://github.com/open-mmlab/mmcv) using [MIM](https://github.com/open-mmlab/mim).
```shell
pip install -U openmim
mim install mmengine
mim install "mmcv==2.0.0"
```
**Step 2.** Install MMPose
```shell
# starting from the project root
cd mmpose
pip install -r requirements.txt
pip install -v -e .
```
**Step 3.** [Run the SegFormer++ using MMPose](../run/run_mmpose.md)12345678910111213141516171819202122232425# MMSegmentation Setup
**Step 0.** Prerequisites
- Pytorch: 2.0.1 (CUDA 11.8)
**Step 1.** Install [MMCV](https://github.com/open-mmlab/mmcv) using [MIM](https://github.com/open-mmlab/mim).
```shell
pip install -U openmim
mim install mmengine
mim install "mmcv==2.0.0"
```
**Step 2.** Install MMSegmentation
```shell
# starting from the project root
cd mmsegmentation
pip install -v -e .
pip install -r requirements.txt
```
**Step 3.** [Run the SegFormer++ using MMSegmentation](../run/run_mmseg.md)
123456789101112131415# Install the SegFormer++ without OpenMMLab
**Step 0.** Prerequisites
- Pytorch: 2.3 (CUDA 12.1) (older versions should also work fine)
- Setup a virtual enviroment (optional, python -m venv "name of the environment")
**Step 1.** Install Segformer++
```shell
cd model_without_OpenMMLab
pip install .
```
**Step 2.** [Run the SegFormer++](../run/run_noopenmmlab.md)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139# Using the SegFormer++ Model via PyTorch Hub
This document explains how to use a pre-trained SegFormer++ model and its associated data transformations by loading them directly from a GitHub repository using PyTorch Hub. The process streamlines model access, making it easy to integrate the model into your projects with a simple one-liner.
## Prerequisites
Before running the script, ensure you have PyTorch installed. You also need to install the following dependencies, which are required by the model and its entry points:
```bash
pip install tomesd omegaconf numpy rich yapf addict tqdm packaging torchvision
```
## How It Works
The provided Python script demonstrates a full workflow, from loading the model and transformations to running inference on a dummy image.
## Step 1: Loading the Model
You can easily load the model from torchhub.
The parameters are:
- `pretrained`: If set to True, it loads the model with pre-trained ImageNet weights.
- `backbone`: Specifies the backbone architecture (e.g., 'b5' for MiT-B5). Other options include 'b0', 'b1', 'b2', 'b3', and 'b4'.
- `tome_strategy`: Defines the token merging strategy. Options include 'bsm_hq' (high quality), 'bsm_fast' (faster), and 'n2d_2x2' (non-overlapping 2x2).
- `checkpoint_url`: A URL to a specific checkpoint file. This way you can load our trained model weights that you can find in the README. Make sure, that your weight fit to the model size and number of classes.
- `out_channels`: The number of output classes for segmentation (e.g., 19 for Cityscapes).
```python
import torch
model = torch.hub.load(
'KieDani/SegformerPlusPlus',
'segformer_plusplus',
pretrained=True,
backbone='b5',
tome_strategy='bsm_hq',
checkpoint_url='https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/', # URL to checkpoints, optional
out_channels=19,
)
model.eval() # Set the model to evaluation mode
```
## Step 2: Loading Data Transformations
The data_transforms entry point returns a torchvision.transforms.Compose object, which encapsulates the standard preprocessing steps required by the model (resizing and normalization).
```python
# Load the data transformations
transform = torch.hub.load(
'KieDani/SegformerPlusPlus',
'data_transforms',
)
```
## Step 3: Preparing the Image and Running Inference
After loading the model and transformations, you can apply them to an input image. The script creates a dummy image for this example, but in a real-world scenario, you would load an image from your file system.
```python
from PIL import Image
# In a real-world scenario, you would load your image here:
# image = Image.open('path_to_your_image.jpg').convert('RGB')
dummy_image = Image.new('RGB', (1300, 1300), color='red')
# Apply the transformations
input_tensor = transform(dummy_image).unsqueeze(0) # Add a batch dimension
# Run inference
with torch.no_grad():
output = model(input_tensor)
# Process the output tensor to get the final segmentation map
segmentation_map = torch.argmax(output.squeeze(0), dim=0)
```
The final segmentation_map is a tensor where each pixel value represents the predicted class (from 0 to 18).
## Full Script
Below is the complete, runnable script for your reference.
```python
import torch.hub
from PIL import Image
# --- IMPORTANT: TorchHub Dependencies ---
# Install the dependencies via:
# pip install tomesd omegaconf numpy rich yapf addict tqdm packaging torchvision
# Load the SegFormer++ model with predefined parameters.
print("Loading SegFormer++ Model...")
# Replace 'your_username/your_repo' with the actual path to your repository
model = torch.hub.load(
'KieDani/SegformerPlusPlus', # This is a placeholder, replace it with your actual GitHub path
'segformer_plusplus',
pretrained=True,
backbone='b5',
tome_strategy='bsm_hq',
checkpoint_url='https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/',
out_channels=19,
)
model.eval()
print("Model loaded successfully.")
# Load the data transformations via the 'data_transforms' entry point.
print("Loading data transformations...")
transform = torch.hub.load(
'KieDani/SegformerPlusPlus', # Placeholder, replace it with your actual GitHub path
'data_transforms',
)
print("Transformations loaded successfully.")
# --- Example for Image Preparation and Inference ---
# Create a dummy image, as we don't need a real image file.
# In a real scenario, you would load an image from the hard drive, e.g.
# from PIL import Image
# image = Image.open('path_to_your_image.jpg').convert('RGB')
print("Creating a dummy image for demonstration...")
dummy_image = Image.new('RGB', (1300, 1300), color='red')
print("Original image size:", dummy_image.size)
# Apply the transformations loaded from the Hub to the image.
print("Applying transformations to the image...")
input_tensor = transform(dummy_image).unsqueeze(0) # Adds a batch dimension
print("Transformed image tensor size:", input_tensor.shape)
# Run inference.
print("Running inference...")
with torch.no_grad():
output = model(input_tensor)
# The output tensor has the shape [1, num_classes, height, width]
# We remove the batch dimension (1)
output_tensor = output.squeeze(0)
print(f"\nInference completed. Output tensor size: {output_tensor.shape}")
# To get the final segmentation map, you would use argmax.
segmentation_map = torch.argmax(output_tensor, dim=0)
print(f"Size of the generated segmentation map: {segmentation_map.shape}")
```12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import torch.hub
from PIL import Image
# --- IMPORTANT: TorchHub Dependencies ---
# Install the dependencies via:
# pip install tomesd omegaconf numpy rich yapf addict tqdm packaging torchvision
# Load the SegFormer++ model with predefined parameters.
print("Loading SegFormer++ Model...")
# Replace 'your_username/your_repo' with the actual path to your repository
model = torch.hub.load(
'KieDani/SegformerPlusPlus',
'segformer_plusplus',
pretrained=True,
backbone='b5',
tome_strategy='bsm_hq',
checkpoint_url='https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/',
out_channels=19,
)
model.eval()
print("Model loaded successfully.")
# Load the data transformations via the 'data_transforms' entry point.
print("Loading data transformations...")
transform = torch.hub.load(
'KieDani/SegformerPlusPlus',
'data_transforms',
)
print("Transformations loaded successfully.")
# --- Example for Image Preparation and Inference ---
# Create a dummy image, as we don't need a real image file.
# In a real scenario, you would load an image from the hard drive, e.g.
# from PIL import Image
# image = Image.open('path_to_your_image.jpg').convert('RGB')
print("Creating a dummy image for demonstration...")
dummy_image = Image.new('RGB', (1300, 1300), color='red')
print("Original image size:", dummy_image.size)
# Apply the transformations loaded from the Hub to the image.
print("Applying transformations to the image...")
input_tensor = transform(dummy_image).unsqueeze(0) # Adds a batch dimension
print("Transformed image tensor size:", input_tensor.shape)
# Run inference.
print("Running inference...")
with torch.no_grad():
output = model(input_tensor)
# The output tensor has the shape [1, num_classes, height, width]
# We remove the batch dimension (1)
output_tensor = output.squeeze(0)
print(f"\nInference completed. Output tensor size: {output_tensor.shape}")
# To get the final segmentation map, you would use argmax.
segmentation_map = torch.argmax(output_tensor, dim=0)
print(f"Size of the generated segmentation map: {segmentation_map.shape}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185import sys
import os
import torch
import torchvision.transforms as T
from typing import List, Tuple
# Import the necessary functions for custom download
from torch.hub import download_url_to_file
import urllib.parse
# --- WICHTIG: TorchHub Dependencies ---
# These are informational only. Users must install these packages.
dependencies = [
'tomesd',
'omegaconf',
'numpy',
'rich',
'yapf',
'addict',
'tqdm',
'packaging',
'torchvision'
]
# Adds the path to the 'model_without_OpenMMLab' subdirectory to the sys.path list.
model_dir = os.path.join(os.path.dirname(__file__), 'model_without_OpenMMLab')
sys.path.insert(0, model_dir)
# Imports all entry points from the subdirectory.
from segformer_plusplus.build_model import create_model
from segformer_plusplus.random_benchmark import random_benchmark
# Removes the added path again to keep the sys.path list clean.
sys.path.pop(0)
def _get_local_cache_path(url: str, filename: str) -> str:
"""
Creates the full local path to the checkpoint file in the PyTorch Hub cache.
"""
# Retrieves the root folder of the PyTorch Hub cache (~/.cache/torch/)
torch_home = torch.hub._get_torch_home()
# The default checkpoint directory
checkpoint_dir = os.path.join(torch_home, 'checkpoints')
os.makedirs(checkpoint_dir, exist_ok=True)
# Adds a hash component for the URL to ensure uniqueness,
# as the URL itself does not contain a unique file name.
# We use the URL path as part of the hash.
url_path_hash = urllib.parse.quote_plus(url)
# The final local file name, including the base name + URL hash.
local_filename = f"{filename}_{url_path_hash[:10]}.pt"
return os.path.join(checkpoint_dir, local_filename)
# --- ENTRYPOINT 1: Main Model (ADJUSTED) ---
def segformer_plusplus(
backbone: str = 'b5',
tome_strategy: str = 'bsm_hq',
out_channels: int = 19,
pretrained: bool = True,
checkpoint_url: str = None,
**kwargs
) -> torch.nn.Module:
"""
Segformer++: Efficient Token-Merging Strategies for High-Resolution Semantic Segmentation.
Loads a SegFormer++ model with the specified backbone and head architecture.
Install requirements via:
pip install tomesd omegaconf numpy rich yapf addict tqdm packaging torchvision
Args:
backbone (str): The backbone type. Selectable from: ['b0', 'b1', 'b2', 'b3', 'b4', 'b5'].
tome_strategy (str): The token merging strategy. Selectable from: ['bsm_hq', 'bsm_fast', 'n2d_2x2'].
out_channels (int): Number of output classes (e.g., 19 for Cityscapes).
pretrained (bool): Whether to load the ImageNet pre-trained weights.
checkpoint_url (str, optional): A URL to a specific checkpoint.
**Important:** The download uses torch.hub.download_url_to_file(),
which may be required for non-direct links.
Returns:
torch.nn.Module: The instantiated SegFormer++ model.
"""
model = create_model(
backbone=backbone,
tome_strategy=tome_strategy,
out_channels=out_channels,
pretrained=pretrained
)
if checkpoint_url:
# Generate a unique file path in the PyTorch cache
# We use the backbone name as part of the file name
local_filepath = _get_local_cache_path(
url=checkpoint_url,
filename=f"segformer_plusplus_{backbone}"
)
print(f"Attempting to load checkpoint from {checkpoint_url}...")
if not os.path.exists(local_filepath):
# Use download_url_to_file for the non-direct download
try:
print(f"File not in cache. Downloading to {local_filepath}...")
# This replaces load_state_dict_from_url and saves the file in the cache
download_url_to_file(
checkpoint_url,
local_filepath,
progress=True
)
print("Download successful.")
except Exception as e:
print(f"Error downloading checkpoint from {checkpoint_url}. Check the URL or use a direct asset link. Error: {e}")
# If the download fails, we return an un-loaded model
return model
# Load the state dictionary from the downloaded file
try:
state_dict = torch.load(local_filepath, map_location='cpu')
# Perform state_dict cleanup here if necessary,
# e.g., if the state is nested under a 'model' key
if 'state_dict' in state_dict:
state_dict = state_dict['state_dict']
model.load_state_dict(state_dict, strict=True)
print("Checkpoint loaded successfully.")
except Exception as e:
print(f"Error loading state dict from file {local_filepath}: {e}")
# Again, return the un-loaded/ImageNet pre-trained model
print("The model was instantiated, but the checkpoint could not be loaded.")
return model
# --- ENTRYPOINT 2: Data Processing ---
def data_transforms(
resolution: Tuple[int, int] = (1024, 1024),
mean: List[float] = [0.485, 0.456, 0.406],
std: List[float] = [0.229, 0.224, 0.225],
) -> T.Compose:
"""
Provides the appropriate data transformations for a given dataset.
This function is an entry point to get the necessary preprocessing steps
for images based on typical ImageNet values.
Args:
resolution (Tuple[int, int]): The desired size for the images (width, height).
Defaults to (1024, 1024).
mean (List[float]): The mean values for normalization. Defaults to the
ImageNet means.
std (List[float]): The standard deviations for normalization. Defaults to the
ImageNet standard deviations.
Returns:
torchvision.transforms.Compose: A composition of transforms
that can be applied to input images.
Example:
>>> # Load transforms with default parameters
>>> transform = torch.hub.load('user/repo_name', 'data_transforms')
>>>
>>> # Load transforms with resize to custom image resolution and default normalization
>>> transform_small = torch.hub.load('user/repo_name', 'data_transforms', resolution=(512, 512))
"""
transform = T.Compose([
T.Resize(resolution),
T.ToTensor(),
T.Normalize(mean=mean, std=std)
])
return transform
# --- ENTRYPOINT 3: Random Benchmark ---
def random_benchmark_entrypoint(**kwargs):
"""
Runs a random benchmark for SegFormer++.
"""
return random_benchmark(**kwargs)12345678910111213141516171819202122232425262728293031323334353637383940[build-system]
requires = ["setuptools>=61.0.0", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "segformer_plusplus"
version = "0.2"
authors = [
{name = "Daniel Kienzle"},
]
description = "Segformer++: Efficient Token-Merging Strategies for High-Resolution Semantic Segmentation"
license = {text = "MIT"}
# Entspricht long_description
readme = "README.md" # Gehen wir davon aus, dass Sie eine README.md verwenden.
# Wenn Sie den Link aus der setup.py übernehmen möchten,
# nutzen Sie die Sektion [project.urls] (siehe unten).
# Entspricht install_requires
dependencies = [
"torch>=2.0.1",
"tomesd",
"omegaconf",
"pyyaml",
"numpy",
"rich",
"yapf",
"addict",
"tqdm",
"packaging",
"Pillow",
"torchvision",
]
# Setuptools wird hier die Pakete automatisch finden (entspricht find_packages())
# Solange keine packages/py_modules gesetzt sind, nutzt setuptools die automatische Paketerkennung.
# Optional: Zusätzliche URLs, wenn Sie den arXiv-Link beibehalten möchten
[project.urls]
Documentation = "https://arxiv.org/abs/2405.14467"123from .registry import Registry
__all__ = ["Registry"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495# Copyright (c) OpenMMLab. All rights reserved.
import copy
import time
from contextlib import contextmanager
from typing import Generator, Optional
from ..utils.manager import ManagerMixin, _accquire_lock, _release_lock
class DefaultScope(ManagerMixin):
"""Scope of current task used to reset the current registry, which can be
accessed globally.
Consider the case of resetting the current ``Registry`` by
``default_scope`` in the internal module which cannot access runner
directly, it is difficult to get the ``default_scope`` defined in
``Runner``. However, if ``Runner`` created ``DefaultScope`` instance
by given ``default_scope``, the internal module can get
``default_scope`` by ``DefaultScope.get_current_instance`` everywhere.
Args:
name (str): Name of default scope for global access.
scope_name (str): Scope of current task.
Examples:
>>> from mmengine.model import MODELS
>>> # Define default scope in runner.
>>> DefaultScope.get_instance('task', scope_name='mmdet')
>>> # Get default scope globally.
>>> scope_name = DefaultScope.get_instance('task').scope_name
"""
def __init__(self, name: str, scope_name: str):
super().__init__(name)
assert isinstance(
scope_name,
str), (f'scope_name should be a string, but got {scope_name}')
self._scope_name = scope_name
@property
def scope_name(self) -> str:
"""
Returns:
str: Get current scope.
"""
return self._scope_name
@classmethod
def get_current_instance(cls) -> Optional['DefaultScope']:
"""Get latest created default scope.
Since default_scope is an optional argument for ``Registry.build``.
``get_current_instance`` should return ``None`` if there is no
``DefaultScope`` created.
Examples:
>>> default_scope = DefaultScope.get_current_instance()
>>> # There is no `DefaultScope` created yet,
>>> # `get_current_instance` return `None`.
>>> default_scope = DefaultScope.get_instance(
>>> 'instance_name', scope_name='mmengine')
>>> default_scope.scope_name
mmengine
>>> default_scope = DefaultScope.get_current_instance()
>>> default_scope.scope_name
mmengine
Returns:
Optional[DefaultScope]: Return None If there has not been
``DefaultScope`` instance created yet, otherwise return the
latest created DefaultScope instance.
"""
_accquire_lock()
if cls._instance_dict:
instance = super().get_current_instance()
else:
instance = None
_release_lock()
return instance
@classmethod
@contextmanager
def overwrite_default_scope(cls, scope_name: Optional[str]) -> Generator:
"""Overwrite the current default scope with `scope_name`"""
if scope_name is None:
yield
else:
tmp = copy.deepcopy(cls._instance_dict)
# To avoid create an instance with the same name.
time.sleep(1e-6)
cls.get_instance(f'overwrite-{time.time()}', scope_name=scope_name)
try:
yield
finally:
cls._instance_dict = tmp123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557# Copyright (c) OpenMMLab. All rights reserved.
import inspect
import sys
import types
from collections import abc
from collections.abc import Callable
from contextlib import contextmanager
from importlib import import_module
from typing import Any, Dict, Generator, List, Optional, Tuple, Type, Union
from rich.console import Console
from rich.table import Table
from .default_scope import DefaultScope
MODULE2PACKAGE = {
'mmcls': 'mmcls',
'mmdet': 'mmdet',
'mmdet3d': 'mmdet3d',
'mmseg': 'mmsegmentation',
'mmaction': 'mmaction2',
'mmtrack': 'mmtrack',
'mmpose': 'mmpose',
'mmedit': 'mmedit',
'mmocr': 'mmocr',
'mmgen': 'mmgen',
'mmfewshot': 'mmfewshot',
'mmrazor': 'mmrazor',
'mmflow': 'mmflow',
'mmhuman3d': 'mmhuman3d',
'mmrotate': 'mmrotate',
'mmselfsup': 'mmselfsup',
'mmyolo': 'mmyolo',
'mmpretrain': 'mmpretrain',
'mmagic': 'mmagic',
}
class Registry:
"""A registry to map strings to classes or functions.
Registered object could be built from registry. Meanwhile, registered
functions could be called from registry.
Args:
name (str): Registry name.
build_func (callable, optional): A function to construct instance
from Registry. :func:`build_from_cfg` is used if neither ``parent``
or ``build_func`` is specified. If ``parent`` is specified and
``build_func`` is not given, ``build_func`` will be inherited
from ``parent``. Defaults to None.
parent (:obj:`Registry`, optional): Parent registry. The class
registered in children registry could be built from parent.
Defaults to None.
scope (str, optional): The scope of registry. It is the key to search
for children registry. If not specified, scope will be the name of
the package where class is defined, e.g. mmdet, mmcls, mmseg.
Defaults to None.
locations (list): The locations to import the modules registered
in this registry. Defaults to [].
New in version 0.4.0.
"""
def __init__(self,
name: str,
build_func: Optional[Callable] = None,
parent: Optional['Registry'] = None,
scope: Optional[str] = None,
locations: List = []):
self._name = name
self._module_dict: Dict[str, Type] = dict()
self._children: Dict[str, 'Registry'] = dict()
self._locations = locations
self._imported = False
if scope is not None:
assert isinstance(scope, str)
self._scope = scope
else:
self._scope = self.infer_scope()
self.parent: Optional['Registry']
if parent is not None:
assert isinstance(parent, Registry)
parent._add_child(self)
self.parent = parent
else:
self.parent = None
self.build_func: Callable
if build_func is None:
if self.parent is not None:
self.build_func = self.parent.build_func
else:
from ..utils.build_functions import build_from_cfg
self.build_func = build_from_cfg
else:
self.build_func = build_func
def __len__(self):
return len(self._module_dict)
def __contains__(self, key):
return self.get(key) is not None
def __repr__(self):
table = Table(title=f'Registry of {self._name}')
table.add_column('Names', justify='left', style='cyan')
table.add_column('Objects', justify='left', style='green')
for name, obj in sorted(self._module_dict.items()):
table.add_row(name, str(obj))
console = Console()
with console.capture() as capture:
console.print(table, end='')
return capture.get()
@staticmethod
def infer_scope() -> str:
"""Infer the scope of registry.
The name of the package where registry is defined will be returned.
Returns:
str: The inferred scope name.
"""
module = inspect.getmodule(sys._getframe(2))
if module is not None:
filename = module.__name__
split_filename = filename.split('.')
scope = split_filename[0]
else:
scope = 'mmengine'
return scope
@staticmethod
def split_scope_key(key: str) -> Tuple[Optional[str], str]:
"""Split scope and key.
The first scope will be split from key.
Return:
tuple[str | None, str]: The former element is the first scope of
the key, which can be ``None``. The latter is the remaining key.
"""
split_index = key.find('.')
if split_index != -1:
return key[:split_index], key[split_index + 1:]
else:
return None, key
@property
def name(self):
return self._name
@property
def scope(self):
return self._scope
@property
def module_dict(self):
return self._module_dict
@property
def children(self):
return self._children
@property
def root(self):
return self._get_root_registry()
@contextmanager
def switch_scope_and_registry(self, scope: Optional[str]) -> Generator:
"""Temporarily switch default scope to the target scope, and get the
corresponding registry.
If the registry of the corresponding scope exists, yield the
registry, otherwise yield the current itself.
Args:
scope (str, optional): The target scope.
"""
with DefaultScope.overwrite_default_scope(scope):
# Get the global default scope
default_scope = DefaultScope.get_current_instance()
# Get registry by scope
if default_scope is not None:
scope_name = default_scope.scope_name
try:
import_module(f'{scope_name}.registry')
except (ImportError, AttributeError, ModuleNotFoundError):
if scope in MODULE2PACKAGE:
print(
f'{scope} is not installed and its '
'modules will not be registered. If you '
'want to use modules defined in '
f'{scope}, Please install {scope} by '
f'`pip install {MODULE2PACKAGE[scope]}.')
else:
print(
f'Failed to import `{scope}.registry` '
f'make sure the registry.py exists in `{scope}` '
'package.',)
root = self._get_root_registry()
registry = root._search_child(scope_name)
if registry is None:
print(
f'Failed to search registry with scope "{scope_name}" '
f'in the "{root.name}" registry tree. '
f'As a workaround, the current "{self.name}" registry '
f'in "{self.scope}" is used to build instance. This '
'may cause unexpected failure when running the built '
f'modules. Please check whether "{scope_name}" is a '
'correct scope, or whether the registry is '
'initialized.',)
registry = self
else:
registry = self
yield registry
def _get_root_registry(self) -> 'Registry':
"""Return the root registry."""
root = self
while root.parent is not None:
root = root.parent
return root
def import_from_location(self) -> None:
"""Import modules from the pre-defined locations in self._location."""
if not self._imported:
# avoid BC breaking
if len(self._locations) == 0 and self.scope in MODULE2PACKAGE:
print(
f'The "{self.name}" registry in {self.scope} did not '
'set import location. Fallback to call '
f'`{self.scope}.utils.register_all_modules` '
'instead.',)
try:
module = import_module(f'{self.scope}.utils')
except (ImportError, AttributeError, ModuleNotFoundError):
if self.scope in MODULE2PACKAGE:
print(
f'{self.scope} is not installed and its '
'modules will not be registered. If you '
'want to use modules defined in '
f'{self.scope}, Please install {self.scope} by '
f'`pip install {MODULE2PACKAGE[self.scope]}.',)
else:
print(
f'Failed to import {self.scope} and register '
'its modules, please make sure you '
'have registered the module manually.',)
else:
module.register_all_modules(False) # type: ignore
for loc in self._locations:
import_module(loc)
print(
f"Modules of {self.scope}'s {self.name} registry have "
f'been automatically imported from {loc}',)
self._imported = True
def get(self, key: str) -> Optional[Type]:
"""Get the registry record.
If `key`` represents the whole object name with its module
information, for example, `mmengine.model.BaseModel`, ``get``
will directly return the class object :class:`BaseModel`.
Otherwise, it will first parse ``key`` and check whether it
contains a scope name. The logic to search for ``key``:
- ``key`` does not contain a scope name, i.e., it is purely a module
name like "ResNet": :meth:`get` will search for ``ResNet`` from the
current registry to its parent or ancestors until finding it.
- ``key`` contains a scope name and it is equal to the scope of the
current registry (e.g., "mmcls"), e.g., "mmcls.ResNet": :meth:`get`
will only search for ``ResNet`` in the current registry.
- ``key`` contains a scope name and it is not equal to the scope of
the current registry (e.g., "mmdet"), e.g., "mmcls.FCNet": If the
scope exists in its children, :meth:`get` will get "FCNet" from
them. If not, :meth:`get` will first get the root registry and root
registry call its own :meth:`get` method.
Args:
key (str): Name of the registered item, e.g., the class name in
string format.
Returns:
Type or None: Return the corresponding class if ``key`` exists,
otherwise return None.
"""
if not isinstance(key, str):
raise TypeError(
'The key argument of `Registry.get` must be a str, '
f'got {type(key)}')
scope, real_key = self.split_scope_key(key)
obj_cls = None
registry_name = self.name
scope_name = self.scope
# lazy import the modules to register them into the registry
self.import_from_location()
if scope is None or scope == self._scope:
# get from self
if real_key in self._module_dict:
obj_cls = self._module_dict[real_key]
elif scope is None:
# try to get the target from its parent or ancestors
parent = self.parent
while parent is not None:
if real_key in parent._module_dict:
obj_cls = parent._module_dict[real_key]
registry_name = parent.name
scope_name = parent.scope
break
parent = parent.parent
else:
# import the registry to add the nodes into the registry tree
try:
import_module(f'{scope}.registry')
print(
f'Registry node of {scope} has been automatically '
'imported.',)
except (ImportError, AttributeError, ModuleNotFoundError):
print(
f'Cannot auto import {scope}.registry, please check '
f'whether the package "{scope}" is installed correctly '
'or import the registry manually.',)
# get from self._children
if scope in self._children:
obj_cls = self._children[scope].get(real_key)
registry_name = self._children[scope].name
scope_name = scope
else:
root = self._get_root_registry()
if scope != root._scope and scope not in root._children:
# If not skip directly, `root.get(key)` will recursively
# call itself until RecursionError is thrown.
pass
else:
obj_cls = root.get(key)
if obj_cls is None:
try:
obj_cls = get_object_from_string(key)
except Exception:
raise RuntimeError(f'Failed to get {key}')
if obj_cls is not None:
# For some rare cases (e.g. obj_cls is a partial function), obj_cls
# doesn't have `__name__`. Use default value to prevent error
cls_name = getattr(obj_cls, '__name__', str(obj_cls))
return obj_cls
def _search_child(self, scope: str) -> Optional['Registry']:
"""Depth-first search for the corresponding registry in its children.
Note that the method only search for the corresponding registry from
the current registry. Therefore, if we want to search from the root
registry, :meth:`_get_root_registry` should be called to get the
root registry first.
Args:
scope (str): The scope name used for searching for its
corresponding registry.
Returns:
Registry or None: Return the corresponding registry if ``scope``
exists, otherwise return None.
"""
if self._scope == scope:
return self
for child in self._children.values():
registry = child._search_child(scope)
if registry is not None:
return registry
return None
def build(self, cfg: dict, *args, **kwargs) -> Any:
"""Build an instance.
Build an instance by calling :attr:`build_func`.
Args:
cfg (dict): Config dict needs to be built.
Returns:
Any: The constructed object.
"""
return self.build_func(cfg, *args, **kwargs, registry=self)
def _add_child(self, registry: 'Registry') -> None:
"""Add a child for a registry.
Args:
registry (:obj:`Registry`): The ``registry`` will be added as a
child of the ``self``.
"""
assert isinstance(registry, Registry)
assert registry.scope is not None
assert registry.scope not in self.children, \
f'scope {registry.scope} exists in {self.name} registry'
self.children[registry.scope] = registry
def _register_module(self,
module: Type,
module_name: Optional[Union[str, List[str]]] = None,
force: bool = False) -> None:
"""Register a module.
Args:
module (type): Module to be registered. Typically a class or a
function, but generally all ``Callable`` are acceptable.
module_name (str or list of str, optional): The module name to be
registered. If not specified, the class name will be used.
Defaults to None.
force (bool): Whether to override an existing class with the same
name. Defaults to False.
"""
if not callable(module):
raise TypeError(f'module must be Callable, but got {type(module)}')
if module_name is None:
module_name = module.__name__
if isinstance(module_name, str):
module_name = [module_name]
for name in module_name:
if not force and name in self._module_dict:
existed_module = self.module_dict[name]
raise KeyError(f'{name} is already registered in {self.name} '
f'at {existed_module.__module__}')
self._module_dict[name] = module
def register_module(
self,
name: Optional[Union[str, List[str]]] = None,
force: bool = False,
module: Optional[Type] = None) -> Union[type, Callable]:
"""Register a module.
A record will be added to ``self._module_dict``, whose key is the class
name or the specified name, and value is the class itself.
It can be used as a decorator or a normal function.
Args:
name (str or list of str, optional): The module name to be
registered. If not specified, the class name will be used.
force (bool): Whether to override an existing class with the same
name. Defaults to False.
module (type, optional): Module class or function to be registered.
Defaults to None.
"""
if not isinstance(force, bool):
raise TypeError(f'force must be a boolean, but got {type(force)}')
# raise the error ahead of time
if not (name is None or isinstance(name, str) or is_seq_of(name, str)):
raise TypeError(
'name must be None, an instance of str, or a sequence of str, '
f'but got {type(name)}')
# use it as a normal method: x.register_module(module=SomeClass)
if module is not None:
self._register_module(module=module, module_name=name, force=force)
return module
# use it as a decorator: @x.register_module()
def _register(module):
self._register_module(module=module, module_name=name, force=force)
return module
return _register
def is_seq_of(seq: Any,
expected_type: Union[Type, tuple],
seq_type: Optional[Type] = None) -> bool:
"""Check whether it is a sequence of some type.
Args:
seq (Sequence): The sequence to be checked.
expected_type (type or tuple): Expected type of sequence items.
seq_type (type, optional): Expected sequence type. Defaults to None.
Returns:
bool: Return True if ``seq`` is valid else False.
"""
if seq_type is None:
exp_seq_type = abc.Sequence
else:
assert isinstance(seq_type, type)
exp_seq_type = seq_type
if not isinstance(seq, exp_seq_type):
return False
for item in seq:
if not isinstance(item, expected_type):
return False
return True
def get_object_from_string(obj_name: str):
"""Get object from name.
Args:
obj_name (str): The name of the object.
"""
parts = iter(obj_name.split('.'))
module_name = next(parts)
# import module
while True:
try:
module = import_module(module_name)
part = next(parts)
# mmcv.ops has nms.py and nms function at the same time. So the
# function will have a higher priority
obj = getattr(module, part, None)
if obj is not None and not ismodule(obj):
break
module_name = f'{module_name}.{part}'
except StopIteration:
# if obj is a module
return module
except ImportError:
return None
# get class or attribute from module
obj = module
while True:
try:
obj = getattr(obj, part)
part = next(parts)
except StopIteration:
return obj
except AttributeError:
return None
def ismodule(object):
"""Return true if the object is a module.
Module objects provide these attributes:
__cached__ pathname to byte compiled file
__doc__ documentation string
__file__ filename (missing for built-in modules)"""
return isinstance(object, types.ModuleType)1234from .build_model import create_model, create_custom_model
from .random_benchmark import random_benchmark
__all__ = ['create_model', 'create_custom_model', 'random_benchmark']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107import os
from .utils import MODELS, imagenet_weights
from .utils import tome_presets
from .model.base_module import BaseModule
from .configs.config.config import Config
from .utils.build_functions import build_model_from_cfg
class SegFormer(BaseModule):
"""
This class represents a SegFormer model that allows for the application of token merging.
Attributes:
backbone (BaseModule): MixVisionTransformer backbone
decode_head (BaseModule): SegFormer head
"""
def __init__(self, cfg):
"""
Initialize the SegFormer model.
Args:
cfg (Config): an mmengine Config object, which defines the backbone, head and token merging strategy used.
"""
super().__init__()
self.backbone = build_model_from_cfg(cfg.backbone, registry=MODELS)
self.decode_head = build_model_from_cfg(cfg.decode_head, registry=MODELS)
def forward(self, x):
"""
Forward pass of the model.
Args:
x (torch.Tensor): input tensor of shape [B, C, H, W]
Returns:
torch.Tensor: output tensor
"""
x = self.backbone(x)
x = self.decode_head(x)
return x
def create_model(
backbone: str = 'b0',
tome_strategy: str = None,
out_channels: int = 19,
pretrained: bool = False,
):
"""
Create a SegFormer model using the predefined SegFormer backbones from the MiT series (b0-b5).
Args:
backbone (str): backbone name (e.g. 'b0')
tome_strategy (str | list(dict)): select strategy from presets ('bsm_hq', 'bsm_fast', 'n2d_2x2') or define a
custom strategy using a list, that contains of dictionaries, in which the strategies for the stage are
defined
out_channels (int): number of output channels (e.g. 19 for the cityscapes semantic segmentation task)
pretrained: use pretrained (imagenet) weights
Returns:
BaseModule: SegFormer model
"""
backbone = backbone.lower()
assert backbone in [f'b{i}' for i in range(6)]
wd = os.path.dirname(os.path.abspath(__file__))
cfg = Config.fromfile(os.path.join(wd, 'configs', f'segformer_mit_{backbone}.py'))
cfg.decode_head.out_channels = out_channels
if tome_strategy is not None:
if tome_strategy not in list(tome_presets.keys()):
print("Using custom merging strategy.")
cfg.backbone.tome_cfg = tome_presets[tome_strategy]
# load imagenet weights
if pretrained:
cfg.backbone.init_cfg = dict(type='Pretrained', checkpoint=imagenet_weights[backbone])
return SegFormer(cfg)
def create_custom_model(
model_cfg: Config,
tome_strategy: list[dict] = None,
):
"""
Create a SegFormer model with customizable backbone and head.
Args:
model_cfg (Config): backbone name (e.g. 'b0')
tome_strategy (list(dict)): custom token merging strategy
Returns:
BaseModule: SegFormer model
"""
if tome_strategy is not None:
model_cfg.backbone.tome_cfg = tome_strategy
return SegFormer(model_cfg)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import torch
from PIL import Image
import torchvision.transforms as T
import os
from typing import Union, List, Tuple
import numpy as np
from .utils.benchmark import benchmark
# Gerät auswählen
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"Using device: {device}")
if device.type == 'cuda':
print(f"CUDA Device Name: {torch.cuda.get_device_name(torch.cuda.current_device())}")
def cityscape_benchmark(
model: torch.nn.Module,
image_path: str,
batch_size: Union[int, List[int]] = 1,
image_size: Union[Tuple[int], List[Tuple[int]]] = (3, 1024, 1024),
save_output: bool = True,
):
"""
Calculate the FPS of a given model using an actual Cityscapes image.
Args:
model: instance of a model (e.g. SegFormer)
image_path: the path to the Cityscapes image
batch_size: the batch size(s) at which to calculate the FPS (e.g. 1 or [1, 2, 4])
image_size: the size of the images to use (e.g. (3, 1024, 1024))
save_output: whether to save the output prediction (default True)
Returns:
the FPS values calculated for all image sizes and batch sizes in the form of a dictionary
"""
if isinstance(batch_size, int):
batch_size = [batch_size]
if isinstance(image_size, tuple):
image_size = [image_size]
values = {}
throughput_values = []
model = model.to(device)
model.eval()
assert os.path.exists(image_path), f"Image not found: {image_path}"
image = Image.open(image_path).convert("RGB")
img_tensor = T.ToTensor()(image)
mean = img_tensor.mean(dim=(1, 2))
std = img_tensor.std(dim=(1, 2))
print(f"Calculated Mean: {mean}")
print(f"Calculated Std: {std}")
transform = T.Compose([
T.Resize((image_size[0][1], image_size[0][2])),
T.ToTensor(),
T.Normalize(mean=mean.tolist(),
std=std.tolist())
])
img_tensor = transform(image).unsqueeze(0).to(device)
for i in image_size:
# fill with fps for each batch size
fps = []
for b in batch_size:
for _ in range(4):
# Baseline benchmark
if i[1] >= 1024:
r = 16
else:
r = 32
baseline_throughput = benchmark(
model.to(device),
device=device,
verbose=True,
runs=r,
batch_size=b,
input_size=i
)
throughput_values.append(baseline_throughput)
throughput_values = np.asarray(throughput_values)
throughput = np.around(np.mean(throughput_values), decimals=2)
print('Im_size:', i, 'Batch_size:', b, 'Mean:', throughput, 'Std:',
np.around(np.std(throughput_values), decimals=2))
throughput_values = []
fps.append({b: throughput})
values[i] = fps
if save_output:
with torch.no_grad():
output = model(img_tensor)
pred = torch.argmax(output, dim=1).squeeze(0).cpu().numpy()
# Speichere Prediction als Text ab
cwd = os.getcwd()
output_path = os.path.join(cwd, 'segformer_plusplus', 'cityscapes_prediction_output.txt')
np.savetxt(output_path, pred, fmt="%d")
print("Prediction saved as cityscapes_prediction_output.txt")
return values1__all__ = []123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545import ast
import copy
import os
import os.path as osp
import platform
import shutil
import sys
import tempfile
import types
import uuid
import re
import warnings
from argparse import ArgumentParser
from collections import OrderedDict, abc
from pathlib import Path
from typing import Any, Optional, Tuple, Union
from omegaconf import OmegaConf
import yapf
from addict import Dict
from yapf.yapflib.yapf_api import FormatCode
from .lazy import LazyAttr, LazyObject
from .utils import (check_file_exist, get_installed_path, import_modules_from_strings, is_installed, RemoveAssignFromAST,
ImportTransformer, _gather_abs_import_lazyobj, _get_external_cfg_base_path,
_get_external_cfg_path, _get_package_and_cfg_path, _is_builtin_module, dump)
BASE_KEY = '_base_'
DELETE_KEY = '_delete_'
DEPRECATION_KEY = '_deprecation_'
RESERVED_KEYS = ['filename', 'text', 'pretty_text', 'env_variables']
def _lazy2string(cfg_dict, dict_type=None):
if isinstance(cfg_dict, dict):
dict_type = dict_type or type(cfg_dict)
return dict_type(
{k: _lazy2string(v, dict_type)
for k, v in dict.items(cfg_dict)})
elif isinstance(cfg_dict, (tuple, list)):
return type(cfg_dict)(_lazy2string(v, dict_type) for v in cfg_dict)
elif isinstance(cfg_dict, (LazyAttr, LazyObject)):
return f'{cfg_dict.module}.{str(cfg_dict)}'
else:
return cfg_dict
class ConfigDict(Dict):
"""A dictionary for config which has the same interface as python's built-
in dictionary and can be used as a normal dictionary.
The Config class would transform the nested fields (dictionary-like fields)
in config file into ``ConfigDict``.
If the class attribute ``lazy`` is ``False``, users will get the
object built by ``LazyObject`` or ``LazyAttr``, otherwise users will get
the ``LazyObject`` or ``LazyAttr`` itself.
The ``lazy`` should be set to ``True`` to avoid building the imported
object during configuration parsing, and it should be set to False outside
the Config to ensure that users do not experience the ``LazyObject``.
"""
lazy = False
def __init__(__self, *args, **kwargs):
object.__setattr__(__self, '__parent', kwargs.pop('__parent', None))
object.__setattr__(__self, '__key', kwargs.pop('__key', None))
object.__setattr__(__self, '__frozen', False)
for arg in args:
if not arg:
continue
# Since ConfigDict.items will convert LazyObject to real object
# automatically, we need to call super().items() to make sure
# the LazyObject will not be converted.
if isinstance(arg, ConfigDict):
for key, val in dict.items(arg):
__self[key] = __self._hook(val)
elif isinstance(arg, dict):
for key, val in arg.items():
__self[key] = __self._hook(val)
elif isinstance(arg, tuple) and (not isinstance(arg[0], tuple)):
__self[arg[0]] = __self._hook(arg[1])
else:
for key, val in iter(arg):
__self[key] = __self._hook(val)
for key, val in dict.items(kwargs):
__self[key] = __self._hook(val)
def __missing__(self, name):
raise KeyError(name)
def __getattr__(self, name):
try:
value = super().__getattr__(name)
if isinstance(value, (LazyAttr, LazyObject)) and not self.lazy:
value = value.build()
except KeyError:
raise AttributeError(f"'{self.__class__.__name__}' object has no "
f"attribute '{name}'")
except Exception as e:
raise e
else:
return value
@classmethod
def _hook(cls, item):
# avoid to convert user defined dict to ConfigDict.
if type(item) in (dict, OrderedDict):
return cls(item)
elif isinstance(item, (list, tuple)):
return type(item)(cls._hook(elem) for elem in item)
return item
def __setattr__(self, name, value):
value = self._hook(value)
return super().__setattr__(name, value)
def __setitem__(self, name, value):
value = self._hook(value)
return super().__setitem__(name, value)
def __getitem__(self, key):
return self.build_lazy(super().__getitem__(key))
def __deepcopy__(self, memo):
other = self.__class__()
memo[id(self)] = other
for key, value in super().items():
other[copy.deepcopy(key, memo)] = copy.deepcopy(value, memo)
return other
def __copy__(self):
other = self.__class__()
for key, value in super().items():
other[key] = value
return other
copy = __copy__
def __iter__(self):
# Implement `__iter__` to overwrite the unpacking operator `**cfg_dict`
# to get the built lazy object
return iter(self.keys())
def get(self, key: str, default: Optional[Any] = None) -> Any:
"""Get the value of the key. If class attribute ``lazy`` is True, the
LazyObject will be built and returned.
Args:
key (str): The key.
default (any, optional): The default value. Defaults to None.
Returns:
Any: The value of the key.
"""
return self.build_lazy(super().get(key, default))
def pop(self, key, default=None):
"""Pop the value of the key. If class attribute ``lazy`` is True, the
LazyObject will be built and returned.
Args:
key (str): The key.
default (any, optional): The default value. Defaults to None.
Returns:
Any: The value of the key.
"""
return self.build_lazy(super().pop(key, default))
def update(self, *args, **kwargs) -> None:
"""Override this method to make sure the LazyObject will not be built
during updating."""
other = {}
if args:
if len(args) > 1:
raise TypeError('update only accept one positional argument')
# Avoid to used self.items to build LazyObject
for key, value in dict.items(args[0]):
other[key] = value
for key, value in dict(kwargs).items():
other[key] = value
for k, v in other.items():
if ((k not in self) or (not isinstance(self[k], dict))
or (not isinstance(v, dict))):
self[k] = self._hook(v)
else:
self[k].update(v)
def build_lazy(self, value: Any) -> Any:
"""If class attribute ``lazy`` is False, the LazyObject will be built
and returned.
Args:
value (Any): The value to be built.
Returns:
Any: The built value.
"""
if isinstance(value, (LazyAttr, LazyObject)) and not self.lazy:
value = value.build()
return value
def values(self):
"""Yield the values of the dictionary.
If class attribute ``lazy`` is False, the value of ``LazyObject`` or
``LazyAttr`` will be built and returned.
"""
values = []
for value in super().values():
values.append(self.build_lazy(value))
return values
def items(self):
"""Yield the keys and values of the dictionary.
If class attribute ``lazy`` is False, the value of ``LazyObject`` or
``LazyAttr`` will be built and returned.
"""
items = []
for key, value in super().items():
items.append((key, self.build_lazy(value)))
return items
def merge(self, other: dict):
"""Merge another dictionary into current dictionary.
Args:
other (dict): Another dictionary.
"""
default = object()
def _merge_a_into_b(a, b):
if isinstance(a, dict):
if not isinstance(b, dict):
a.pop(DELETE_KEY, None)
return a
if a.pop(DELETE_KEY, False):
b.clear()
all_keys = list(b.keys()) + list(a.keys())
return {
key:
_merge_a_into_b(a.get(key, default), b.get(key, default))
for key in all_keys if key != DELETE_KEY
}
else:
return a if a is not default else b
merged = _merge_a_into_b(copy.deepcopy(other), copy.deepcopy(self))
self.clear()
for key, value in merged.items():
self[key] = value
def __reduce_ex__(self):
# Override __reduce_ex__ to avoid `self.items` will be
# called by CPython interpreter during pickling. See more details in
# https://github.com/python/cpython/blob/8d61a71f9c81619e34d4a30b625922ebc83c561b/Objects/typeobject.c#L6196 # noqa: E501
from ...utils import digit_version
if digit_version(platform.python_version()) < digit_version('3.8'):
return (self.__class__, ({k: v
for k, v in super().items()}, ), None,
None, None)
else:
return (self.__class__, ({k: v
for k, v in super().items()}, ), None,
None, None, None)
def __eq__(self, other):
if isinstance(other, ConfigDict):
return other.to_dict() == self.to_dict()
elif isinstance(other, dict):
return {k: v for k, v in self.items()} == other
else:
return False
def _to_lazy_dict(self):
"""Convert the ConfigDict to a normal dictionary recursively, and keep
the ``LazyObject`` or ``LazyAttr`` object not built."""
def _to_dict(data):
if isinstance(data, ConfigDict):
return {
key: _to_dict(value)
for key, value in Dict.items(data)
}
elif isinstance(data, dict):
return {key: _to_dict(value) for key, value in data.items()}
elif isinstance(data, (list, tuple)):
return type(data)(_to_dict(item) for item in data)
else:
return data
return _to_dict(self)
def to_dict(self):
"""Convert the ConfigDict to a normal dictionary recursively, and
convert the ``LazyObject`` or ``LazyAttr`` to string."""
return _lazy2string(self, dict_type=dict)
def add_args(parser: ArgumentParser,
cfg: dict,
prefix: str = '') -> ArgumentParser:
"""Add config fields into argument parser.
Args:
parser (ArgumentParser): Argument parser.
cfg (dict): Config dictionary.
prefix (str, optional): Prefix of parser argument.
Defaults to ''.
Returns:
ArgumentParser: Argument parser containing config fields.
"""
for k, v in cfg.items():
if isinstance(v, str):
parser.add_argument('--' + prefix + k)
elif isinstance(v, bool):
parser.add_argument('--' + prefix + k, action='store_true')
elif isinstance(v, int):
parser.add_argument('--' + prefix + k, type=int)
elif isinstance(v, float):
parser.add_argument('--' + prefix + k, type=float)
elif isinstance(v, dict):
add_args(parser, v, prefix + k + '.')
elif isinstance(v, abc.Iterable):
parser.add_argument(
'--' + prefix + k, type=type(next(iter(v))), nargs='+')
return parser
class Config:
"""A facility for config and config files.
It supports common file formats as configs: python/json/yaml.
``Config.fromfile`` can parse a dictionary from a config file, then
build a ``Config`` instance with the dictionary.
The interface is the same as a dict object and also allows access config
values as attributes.
Args:
cfg_dict (dict, optional): A config dictionary. Defaults to None.
cfg_text (str, optional): Text of config. Defaults to None.
filename (str or Path, optional): Name of config file.
Defaults to None.
format_python_code (bool): Whether to format Python code by yapf.
Defaults to True.
""" # noqa: E501
def __init__(
self,
cfg_dict: Optional[dict] = None,
cfg_text: Optional[str] = None,
filename: Optional[Union[str, Path]] = None,
env_variables: Optional[dict] = None,
format_python_code: bool = True,
):
filename = str(filename) if isinstance(filename, Path) else filename
if cfg_dict is None:
cfg_dict = dict()
elif not isinstance(cfg_dict, dict):
raise TypeError('cfg_dict must be a dict, but '
f'got {type(cfg_dict)}')
for key in cfg_dict:
if key in RESERVED_KEYS:
raise KeyError(f'{key} is reserved for config file')
if not isinstance(cfg_dict, ConfigDict):
cfg_dict = ConfigDict(cfg_dict)
super().__setattr__('_cfg_dict', cfg_dict)
super().__setattr__('_filename', filename)
super().__setattr__('_format_python_code', format_python_code)
if not hasattr(self, '_imported_names'):
super().__setattr__('_imported_names', set())
if cfg_text:
text = cfg_text
elif filename:
with open(filename, encoding='utf-8') as f:
text = f.read()
else:
text = ''
super().__setattr__('_text', text)
if env_variables is None:
env_variables = dict()
super().__setattr__('_env_variables', env_variables)
@staticmethod
def fromfile(filename: Union[str, Path],
use_predefined_variables: bool = True,
import_custom_modules: bool = True,
use_environment_variables: bool = True,
lazy_import: Optional[bool] = None,
format_python_code: bool = True) -> 'Config':
"""Build a Config instance from config file.
Args:
filename (str or Path): Name of config file.
use_predefined_variables (bool, optional): Whether to use
predefined variables. Defaults to True.
import_custom_modules (bool, optional): Whether to support
importing custom modules in config. Defaults to None.
use_environment_variables (bool, optional): Whether to use
environment variables. Defaults to True.
lazy_import (bool): Whether to load config in `lazy_import` mode.
If it is `None`, it will be deduced by the content of the
config file. Defaults to None.
format_python_code (bool): Whether to format Python code by yapf.
Defaults to True.
Returns:
Config: Config instance built from config file.
"""
filename = str(filename) if isinstance(filename, Path) else filename
if lazy_import is False or \
lazy_import is None and not Config._is_lazy_import(filename):
cfg_dict, cfg_text, env_variables = Config._file2dict(
filename, use_predefined_variables, use_environment_variables,
lazy_import)
if import_custom_modules and cfg_dict.get('custom_imports', None):
try:
import_modules_from_strings(**cfg_dict['custom_imports'])
except ImportError as e:
err_msg = (
'Failed to import custom modules from '
f"{cfg_dict['custom_imports']}, the current sys.path "
'is: ')
for p in sys.path:
err_msg += f'\n {p}'
err_msg += (
'\nYou should set `PYTHONPATH` to make `sys.path` '
'include the directory which contains your custom '
'module')
raise ImportError(err_msg) from e
return Config(
cfg_dict,
cfg_text=cfg_text,
filename=filename,
env_variables=env_variables,
)
else:
# Enable lazy import when parsing the config.
# Using try-except to make sure ``ConfigDict.lazy`` will be reset
# to False. See more details about lazy in the docstring of
# ConfigDict
ConfigDict.lazy = True
try:
cfg_dict, imported_names = Config._parse_lazy_import(filename)
except Exception as e:
raise e
finally:
# disable lazy import to get the real type. See more details
# about lazy in the docstring of ConfigDict
ConfigDict.lazy = False
cfg = Config(
cfg_dict,
filename=filename,
format_python_code=format_python_code)
object.__setattr__(cfg, '_imported_names', imported_names)
return cfg
@staticmethod
def _get_base_modules(nodes: list) -> list:
"""Get base module name from parsed code.
Args:
nodes (list): Parsed code of the config file.
Returns:
list: Name of base modules.
"""
def _get_base_module_from_with(with_nodes: list) -> list:
"""Get base module name from if statement in python file.
Args:
with_nodes (list): List of if statement.
Returns:
list: Name of base modules.
"""
base_modules = []
for node in with_nodes:
assert isinstance(node, ast.ImportFrom), (
'Illegal syntax in config file! Only '
'`from ... import ...` could be implemented` in '
'with read_base()`')
assert node.module is not None, (
'Illegal syntax in config file! Syntax like '
'`from . import xxx` is not allowed in `with read_base()`')
base_modules.append(node.level * '.' + node.module)
return base_modules
for idx, node in enumerate(nodes):
if (isinstance(node, ast.Assign)
and isinstance(node.targets[0], ast.Name)
and node.targets[0].id == BASE_KEY):
raise SyntaxError(
'The configuration file type in the inheritance chain '
'must match the current configuration file type, either '
'"lazy_import" or non-"lazy_import". You got this error '
f'since you use the syntax like `_base_ = "{node.targets[0].id}"` ' # noqa: E501
'in your config. You should use `with read_base(): ... to` ' # noqa: E501
'mark the inherited config file. See more information '# noqa: E501
)
if not isinstance(node, ast.With):
continue
expr = node.items[0].context_expr
if (not isinstance(expr, ast.Call)
or not expr.func.id == 'read_base' or # type: ignore
len(node.items) > 1):
raise SyntaxError(
'Only `read_base` context manager can be used in the '
'config')
for nested_idx, nested_node in enumerate(node.body):
nodes.insert(idx + nested_idx + 1, nested_node)
nodes.pop(idx)
return _get_base_module_from_with(node.body)
return []
@staticmethod
def _validate_py_syntax(filename: str):
"""Validate syntax of python config.
Args:
filename (str): Filename of python config file.
"""
with open(filename, encoding='utf-8') as f:
content = f.read()
try:
ast.parse(content)
except SyntaxError as e:
raise SyntaxError('There are syntax errors in config '
f'file {filename}: {e}')
@staticmethod
def _substitute_predefined_vars(filename: str, temp_config_name: str):
"""Substitute predefined variables in config with actual values.
Sometimes we want some variables in the config to be related to the
current path or file name, etc.
Here is an example of a typical usage scenario. When training a model,
we define a working directory in the config that save the models and
logs. For different configs, we expect to define different working
directories. A common way for users is to use the config file name
directly as part of the working directory name, e.g. for the config
``config_setting1.py``, the working directory is
``. /work_dir/config_setting1``.
This can be easily achieved using predefined variables, which can be
written in the config `config_setting1.py` as follows
.. code-block:: python
work_dir = '. /work_dir/{{ fileBasenameNoExtension }}'
Here `{{ fileBasenameNoExtension }}` indicates the file name of the
config (without the extension), and when the config class reads the
config file, it will automatically parse this double-bracketed string
to the corresponding actual value.
.. code-block:: python
cfg = Config.fromfile('. /config_setting1.py')
cfg.work_dir # ". /work_dir/config_setting1"
For details, Please refer to docs/zh_cn/advanced_tutorials/config.md .
Args:
filename (str): Filename of config.
temp_config_name (str): Temporary filename to save substituted
config.
"""
file_dirname = osp.dirname(filename)
file_basename = osp.basename(filename)
file_basename_no_extension = osp.splitext(file_basename)[0]
file_extname = osp.splitext(filename)[1]
support_templates = dict(
fileDirname=file_dirname,
fileBasename=file_basename,
fileBasenameNoExtension=file_basename_no_extension,
fileExtname=file_extname)
with open(filename, encoding='utf-8') as f:
config_file = f.read()
for key, value in support_templates.items():
regexp = r'\{\{\s*' + str(key) + r'\s*\}\}'
value = value.replace('\\', '/')
config_file = re.sub(regexp, value, config_file)
with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file:
tmp_config_file.write(config_file)
@staticmethod
def _substitute_env_variables(filename: str, temp_config_name: str):
"""Substitute environment variables in config with actual values.
Sometimes, we want to change some items in the config with environment
variables. For examples, we expect to change dataset root by setting
``DATASET_ROOT=/dataset/root/path`` in the command line. This can be
easily achieved by writing lines in the config as follows
.. code-block:: python
data_root = '{{$DATASET_ROOT:/default/dataset}}/images'
Here, ``{{$DATASET_ROOT:/default/dataset}}`` indicates using the
environment variable ``DATASET_ROOT`` to replace the part between
``{{}}``. If the ``DATASET_ROOT`` is not set, the default value
``/default/dataset`` will be used.
Environment variables not only can replace items in the string, they
can also substitute other types of data in config. In this situation,
we can write the config as below
.. code-block:: python
model = dict(
bbox_head = dict(num_classes={{'$NUM_CLASSES:80'}}))
For details, Please refer to docs/zh_cn/tutorials/config.md .
Args:
filename (str): Filename of config.
temp_config_name (str): Temporary filename to save substituted
config.
"""
with open(filename, encoding='utf-8') as f:
config_file = f.read()
regexp = r'\{\{[\'\"]?\s*\$(\w+)\s*\:\s*(\S*?)\s*[\'\"]?\}\}'
keys = re.findall(regexp, config_file)
env_variables = dict()
for var_name, value in keys:
regexp = r'\{\{[\'\"]?\s*\$' + var_name + r'\s*\:\s*' \
+ value + r'\s*[\'\"]?\}\}'
if var_name in os.environ:
value = os.environ[var_name]
env_variables[var_name] = value
if not value:
raise KeyError(f'`{var_name}` cannot be found in `os.environ`.'
f' Please set `{var_name}` in environment or '
'give a default value.')
config_file = re.sub(regexp, value, config_file)
with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file:
tmp_config_file.write(config_file)
return env_variables
@staticmethod
def _pre_substitute_base_vars(filename: str,
temp_config_name: str) -> dict:
"""Preceding step for substituting variables in base config with actual
value.
Args:
filename (str): Filename of config.
temp_config_name (str): Temporary filename to save substituted
config.
Returns:
dict: A dictionary contains variables in base config.
"""
with open(filename, encoding='utf-8') as f:
config_file = f.read()
base_var_dict = {}
regexp = r'\{\{\s*' + BASE_KEY + r'\.([\w\.]+)\s*\}\}'
base_vars = set(re.findall(regexp, config_file))
for base_var in base_vars:
randstr = f'_{base_var}_{uuid.uuid4().hex.lower()[:6]}'
base_var_dict[randstr] = base_var
regexp = r'\{\{\s*' + BASE_KEY + r'\.' + base_var + r'\s*\}\}'
config_file = re.sub(regexp, f'"{randstr}"', config_file)
with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file:
tmp_config_file.write(config_file)
return base_var_dict
@staticmethod
def _substitute_base_vars(cfg: Any, base_var_dict: dict,
base_cfg: dict) -> Any:
"""Substitute base variables from strings to their actual values.
Args:
Any : Config dictionary.
base_var_dict (dict): A dictionary contains variables in base
config.
base_cfg (dict): Base config dictionary.
Returns:
Any : A dictionary with origin base variables
substituted with actual values.
"""
cfg = copy.deepcopy(cfg)
if isinstance(cfg, dict):
for k, v in cfg.items():
if isinstance(v, str) and v in base_var_dict:
new_v = base_cfg
for new_k in base_var_dict[v].split('.'):
new_v = new_v[new_k]
cfg[k] = new_v
elif isinstance(v, (list, tuple, dict)):
cfg[k] = Config._substitute_base_vars(
v, base_var_dict, base_cfg)
elif isinstance(cfg, tuple):
cfg = tuple(
Config._substitute_base_vars(c, base_var_dict, base_cfg)
for c in cfg)
elif isinstance(cfg, list):
cfg = [
Config._substitute_base_vars(c, base_var_dict, base_cfg)
for c in cfg
]
elif isinstance(cfg, str) and cfg in base_var_dict:
new_v = base_cfg
for new_k in base_var_dict[cfg].split('.'):
new_v = new_v[new_k]
cfg = new_v
return cfg
@staticmethod
def _file2dict(
filename: str,
use_predefined_variables: bool = True,
use_environment_variables: bool = True,
lazy_import: Optional[bool] = None) -> Tuple[dict, str, dict]:
"""Transform file to variables dictionary.
Args:
filename (str): Name of config file.
use_predefined_variables (bool, optional): Whether to use
predefined variables. Defaults to True.
use_environment_variables (bool, optional): Whether to use
environment variables. Defaults to True.
lazy_import (bool): Whether to load config in `lazy_import` mode.
If it is `None`, it will be deduced by the content of the
config file. Defaults to None.
Returns:
Tuple[dict, str]: Variables dictionary and text of Config.
"""
if lazy_import is None and Config._is_lazy_import(filename):
raise RuntimeError(
'The configuration file type in the inheritance chain '
'must match the current configuration file type, either '
'"lazy_import" or non-"lazy_import". You got this error '
'since you use the syntax like `with read_base(): ...` '
f'or import non-builtin module in {filename}.' # noqa: E501
)
filename = osp.abspath(osp.expanduser(filename))
check_file_exist(filename)
fileExtname = osp.splitext(filename)[1]
if fileExtname not in ['.py', '.json', '.yaml', '.yml']:
raise OSError('Only py/yml/yaml/json type are supported now!')
try:
with tempfile.TemporaryDirectory() as temp_config_dir:
temp_config_file = tempfile.NamedTemporaryFile(
dir=temp_config_dir, suffix=fileExtname, delete=False)
if platform.system() == 'Windows':
temp_config_file.close()
# Substitute predefined variables
if use_predefined_variables:
Config._substitute_predefined_vars(filename,
temp_config_file.name)
else:
shutil.copyfile(filename, temp_config_file.name)
# Substitute environment variables
env_variables = dict()
if use_environment_variables:
env_variables = Config._substitute_env_variables(
temp_config_file.name, temp_config_file.name)
# Substitute base variables from placeholders to strings
base_var_dict = Config._pre_substitute_base_vars(
temp_config_file.name, temp_config_file.name)
# Handle base files
base_cfg_dict = ConfigDict()
cfg_text_list = list()
for base_cfg_path in Config._get_base_files(
temp_config_file.name):
base_cfg_path, scope = Config._get_cfg_path(
base_cfg_path, filename)
_cfg_dict, _cfg_text, _env_variables = Config._file2dict(
filename=base_cfg_path,
use_predefined_variables=use_predefined_variables,
use_environment_variables=use_environment_variables,
lazy_import=lazy_import,
)
cfg_text_list.append(_cfg_text)
env_variables.update(_env_variables)
duplicate_keys = base_cfg_dict.keys() & _cfg_dict.keys()
if len(duplicate_keys) > 0:
raise KeyError(
'Duplicate key is not allowed among bases. '
f'Duplicate keys: {duplicate_keys}')
# _dict_to_config_dict will do the following things:
# 1. Recursively converts ``dict`` to :obj:`ConfigDict`.
# 2. Set `_scope_` for the outer dict variable for the base
# config.
# 3. Set `scope` attribute for each base variable.
# Different from `_scope_`, `scope` is not a key of base
# dict, `scope` attribute will be parsed to key `_scope_`
# by function `_parse_scope` only if the base variable is
# accessed by the current config.
_cfg_dict = Config._dict_to_config_dict(_cfg_dict, scope)
base_cfg_dict.update(_cfg_dict)
if filename.endswith('.py'):
with open(temp_config_file.name, encoding='utf-8') as f:
parsed_codes = ast.parse(f.read())
parsed_codes = RemoveAssignFromAST(BASE_KEY).visit(
parsed_codes)
codeobj = compile(parsed_codes, filename, mode='exec')
# Support load global variable in nested function of the
# config.
global_locals_var = {BASE_KEY: base_cfg_dict}
ori_keys = set(global_locals_var.keys())
eval(codeobj, global_locals_var, global_locals_var)
cfg_dict = {
key: value
for key, value in global_locals_var.items()
if (key not in ori_keys and not key.startswith('__'))
}
elif filename.endswith(('.yml', '.yaml', '.json')):
cfg = OmegaConf.load(temp_config_file.name)
cfg_dict = OmegaConf.to_container(cfg, resolve=True)
# close temp file
for key, value in list(cfg_dict.items()):
if isinstance(value,
(types.FunctionType, types.ModuleType)):
cfg_dict.pop(key)
temp_config_file.close()
# If the current config accesses a base variable of base
# configs, The ``scope`` attribute of corresponding variable
# will be converted to the `_scope_`.
Config._parse_scope(cfg_dict)
except Exception as e:
if osp.exists(temp_config_dir):
shutil.rmtree(temp_config_dir)
raise e
# check deprecation information
if DEPRECATION_KEY in cfg_dict:
deprecation_info = cfg_dict.pop(DEPRECATION_KEY)
warning_msg = f'The config file {filename} will be deprecated ' \
'in the future.'
if 'expected' in deprecation_info:
warning_msg += f' Please use {deprecation_info["expected"]} ' \
'instead.'
if 'reference' in deprecation_info:
warning_msg += ' More information can be found at ' \
f'{deprecation_info["reference"]}'
warnings.warn(warning_msg, DeprecationWarning)
cfg_text = filename + '\n'
with open(filename, encoding='utf-8') as f:
# Setting encoding explicitly to resolve coding issue on windows
cfg_text += f.read()
# Substitute base variables from strings to their actual values
cfg_dict = Config._substitute_base_vars(cfg_dict, base_var_dict,
base_cfg_dict)
cfg_dict.pop(BASE_KEY, None)
cfg_dict = Config._merge_a_into_b(cfg_dict, base_cfg_dict)
cfg_dict = {
k: v
for k, v in cfg_dict.items() if not k.startswith('__')
}
# merge cfg_text
cfg_text_list.append(cfg_text)
cfg_text = '\n'.join(cfg_text_list)
return cfg_dict, cfg_text, env_variables
@staticmethod
def _parse_lazy_import(filename: str) -> Tuple[ConfigDict, set]:
"""Transform file to variables dictionary.
Args:
filename (str): Name of config file.
Returns:
Tuple[dict, dict]: ``cfg_dict`` and ``imported_names``.
- cfg_dict (dict): Variables dictionary of parsed config.
- imported_names (set): Used to mark the names of
imported object.
"""
# In lazy import mode, users can use the Python syntax `import` to
# implement inheritance between configuration files, which is easier
# for users to understand the hierarchical relationships between
# different configuration files.
# Besides, users can also using `import` syntax to import corresponding
# module which will be filled in the `type` field. It means users
# can directly navigate to the source of the module in the
# configuration file by clicking the `type` field.
# To avoid really importing the third party package like `torch`
# during import `type` object, we use `_parse_lazy_import` to parse the
# configuration file, which will not actually trigger the import
# process, but simply parse the imported `type`s as LazyObject objects.
# The overall pipeline of _parse_lazy_import is:
# 1. Parse the base module from the config file.
# ||
# \/
# base_module = ['mmdet.configs.default_runtime']
# ||
# \/
# 2. recursively parse the base module and gather imported objects to
# a dict.
# ||
# \/
# The base_dict will be:
# {
# 'mmdet.configs.default_runtime': {...}
# 'mmdet.configs.retinanet_r50_fpn_1x_coco': {...}
# ...
# }, each item in base_dict is a dict of `LazyObject`
# 3. parse the current config file filling the imported variable
# with the base_dict.
#
# 4. During the parsing process, all imported variable will be
# recorded in the `imported_names` set. These variables can be
# accessed, but will not be dumped by default.
with open(filename, encoding='utf-8') as f:
global_dict = {'LazyObject': LazyObject, '__file__': filename}
base_dict = {}
parsed_codes = ast.parse(f.read())
# get the names of base modules, and remove the
# `with read_base():'` statement
base_modules = Config._get_base_modules(parsed_codes.body)
base_imported_names = set()
for base_module in base_modules:
# If base_module means a relative import, assuming the level is
# 2, which means the module is imported like
# "from ..a.b import c". we must ensure that c is an
# object `defined` in module b, and module b should not be a
# package including `__init__` file but a single python file.
level = len(re.match(r'\.*', base_module).group())
if level > 0:
# Relative import
base_dir = osp.dirname(filename)
module_path = osp.join(
base_dir, *(['..'] * (level - 1)),
f'{base_module[level:].replace(".", "/")}.py')
else:
# Absolute import
module_list = base_module.split('.')
if len(module_list) == 1:
raise SyntaxError(
'The imported configuration file should not be '
f'an independent package {module_list[0]}. Here '
'is an example: '
'`with read_base(): from mmdet.configs.retinanet_r50_fpn_1x_coco import *`' # noqa: E501
)
else:
package = module_list[0]
root_path = get_installed_path(package)
module_path = f'{osp.join(root_path, *module_list[1:])}.py' # noqa: E501
if not osp.isfile(module_path):
raise SyntaxError(
f'{module_path} not found! It means that incorrect '
'module is defined in '
f'`with read_base(): = from {base_module} import ...`, please ' # noqa: E501
'make sure the base config module is valid '
'and is consistent with the prior import '
'logic')
_base_cfg_dict, _base_imported_names = Config._parse_lazy_import( # noqa: E501
module_path)
base_imported_names |= _base_imported_names
# The base_dict will be:
# {
# 'mmdet.configs.default_runtime': {...}
# 'mmdet.configs.retinanet_r50_fpn_1x_coco': {...}
# ...
# }
base_dict[base_module] = _base_cfg_dict
# `base_dict` contains all the imported modules from `base_cfg`.
# In order to collect the specific imported module from `base_cfg`
# before parse the current file, we using AST Transform to
# transverse the imported module from base_cfg and merge then into
# the global dict. After the ast transformation, most of import
# syntax will be removed (except for the builtin import) and
# replaced with the `LazyObject`
transform = ImportTransformer(
global_dict=global_dict,
base_dict=base_dict,
filename=filename)
modified_code = transform.visit(parsed_codes)
modified_code, abs_imported = _gather_abs_import_lazyobj(
modified_code, filename=filename)
imported_names = transform.imported_obj | abs_imported
imported_names |= base_imported_names
modified_code = ast.fix_missing_locations(modified_code)
exec(
compile(modified_code, filename, mode='exec'), global_dict,
global_dict)
ret: dict = {}
for key, value in global_dict.items():
if key.startswith('__') or key in ['LazyObject']:
continue
ret[key] = value
# convert dict to ConfigDict
cfg_dict = Config._dict_to_config_dict_lazy(ret)
return cfg_dict, imported_names
@staticmethod
def _dict_to_config_dict_lazy(cfg: dict):
"""Recursively converts ``dict`` to :obj:`ConfigDict`. The only
difference between ``_dict_to_config_dict_lazy`` and
``_dict_to_config_dict_lazy`` is that the former one does not consider
the scope, and will not trigger the building of ``LazyObject``.
Args:
cfg (dict): Config dict.
Returns:
ConfigDict: Converted dict.
"""
# Only the outer dict with key `type` should have the key `_scope_`.
if isinstance(cfg, dict):
cfg_dict = ConfigDict()
for key, value in cfg.items():
cfg_dict[key] = Config._dict_to_config_dict_lazy(value)
return cfg_dict
if isinstance(cfg, (tuple, list)):
return type(cfg)(
Config._dict_to_config_dict_lazy(_cfg) for _cfg in cfg)
return cfg
@staticmethod
def _dict_to_config_dict(cfg: dict,
scope: Optional[str] = None,
has_scope=True):
"""Recursively converts ``dict`` to :obj:`ConfigDict`.
Args:
cfg (dict): Config dict.
scope (str, optional): Scope of instance.
has_scope (bool): Whether to add `_scope_` key to config dict.
Returns:
ConfigDict: Converted dict.
"""
# Only the outer dict with key `type` should have the key `_scope_`.
if isinstance(cfg, dict):
if has_scope and 'type' in cfg:
has_scope = False
if scope is not None and cfg.get('_scope_', None) is None:
cfg._scope_ = scope # type: ignore
cfg = ConfigDict(cfg)
dict.__setattr__(cfg, 'scope', scope)
for key, value in cfg.items():
cfg[key] = Config._dict_to_config_dict(
value, scope=scope, has_scope=has_scope)
elif isinstance(cfg, tuple):
cfg = tuple(
Config._dict_to_config_dict(_cfg, scope, has_scope=has_scope)
for _cfg in cfg)
elif isinstance(cfg, list):
cfg = [
Config._dict_to_config_dict(_cfg, scope, has_scope=has_scope)
for _cfg in cfg
]
return cfg
@staticmethod
def _parse_scope(cfg: dict) -> None:
"""Adds ``_scope_`` to :obj:`ConfigDict` instance, which means a base
variable.
If the config dict already has the scope, scope will not be
overwritten.
Args:
cfg (dict): Config needs to be parsed with scope.
"""
if isinstance(cfg, ConfigDict):
cfg._scope_ = cfg.scope
elif isinstance(cfg, (tuple, list)):
[Config._parse_scope(value) for value in cfg]
else:
return
@staticmethod
def _get_base_files(filename: str) -> list:
"""Get the base config file.
Args:
filename (str): The config file.
Raises:
TypeError: Name of config file.
Returns:
list: A list of base config.
"""
file_format = osp.splitext(filename)[1]
if file_format == '.py':
Config._validate_py_syntax(filename)
with open(filename, encoding='utf-8') as f:
parsed_codes = ast.parse(f.read()).body
def is_base_line(c):
return (isinstance(c, ast.Assign)
and isinstance(c.targets[0], ast.Name)
and c.targets[0].id == BASE_KEY)
base_code = next((c for c in parsed_codes if is_base_line(c)),
None)
if base_code is not None:
base_code = ast.Expression( # type: ignore
body=base_code.value) # type: ignore
base_files = eval(compile(base_code, '',
mode='eval')) # type: ignore
else:
base_files = []
elif file_format in ('.yml', '.yaml', '.json'):
cfg = OmegaConf.load(filename)
cfg_dict = OmegaConf.to_container(cfg, resolve=True)
base_files = cfg_dict.get(BASE_KEY, [])
else:
raise SyntaxError(
'The config type should be py, json, yaml or '
f'yml, but got {file_format}')
base_files = base_files if isinstance(base_files,
list) else [base_files]
return base_files
@staticmethod
def _get_cfg_path(cfg_path: str,
filename: str) -> Tuple[str, Optional[str]]:
"""Get the config path from the current or external package.
Args:
cfg_path (str): Relative path of config.
filename (str): The config file being parsed.
Returns:
Tuple[str, str or None]: Path and scope of config. If the config
is not an external config, the scope will be `None`.
"""
if '::' in cfg_path:
# `cfg_path` startswith '::' means an external config path.
# Get package name and relative config path.
scope = cfg_path.partition('::')[0]
package, cfg_path = _get_package_and_cfg_path(cfg_path)
if not is_installed(package):
raise ModuleNotFoundError(
f'{package} is not installed, please install {package} '
f'manually')
# Get installed package path.
package_path = get_installed_path(package)
try:
# Get config path from meta file.
cfg_path = _get_external_cfg_path(package_path, cfg_path)
except ValueError:
# Since base config does not have a metafile, it should be
# concatenated with package path and relative config path.
cfg_path = _get_external_cfg_base_path(package_path, cfg_path)
except FileNotFoundError as e:
raise e
return cfg_path, scope
else:
# Get local config path.
cfg_dir = osp.dirname(filename)
cfg_path = osp.join(cfg_dir, cfg_path)
return cfg_path, None
@staticmethod
def _merge_a_into_b(a: dict,
b: dict,
allow_list_keys: bool = False) -> dict:
"""Merge dict ``a`` into dict ``b`` (non-inplace).
Values in ``a`` will overwrite ``b``. ``b`` is copied first to avoid
in-place modifications.
Args:
a (dict): The source dict to be merged into ``b``.
b (dict): The origin dict to be fetch keys from ``a``.
allow_list_keys (bool): If True, int string keys (e.g. '0', '1')
are allowed in source ``a`` and will replace the element of the
corresponding index in b if b is a list. Defaults to False.
Returns:
dict: The modified dict of ``b`` using ``a``.
Examples:
# Normally merge a into b.
>>> Config._merge_a_into_b(
... dict(obj=dict(a=2)), dict(obj=dict(a=1)))
{'obj': {'a': 2}}
# Delete b first and merge a into b.
>>> Config._merge_a_into_b(
... dict(obj=dict(_delete_=True, a=2)), dict(obj=dict(a=1)))
{'obj': {'a': 2}}
# b is a list
>>> Config._merge_a_into_b(
... {'0': dict(a=2)}, [dict(a=1), dict(b=2)], True)
[{'a': 2}, {'b': 2}]
"""
b = b.copy()
for k, v in a.items():
if allow_list_keys and k.isdigit() and isinstance(b, list):
k = int(k)
if len(b) <= k:
raise KeyError(f'Index {k} exceeds the length of list {b}')
b[k] = Config._merge_a_into_b(v, b[k], allow_list_keys)
elif isinstance(v, dict):
if k in b and not v.pop(DELETE_KEY, False):
allowed_types: Union[Tuple, type] = (
dict, list) if allow_list_keys else dict
if not isinstance(b[k], allowed_types):
raise TypeError(
f'{k}={v} in child config cannot inherit from '
f'base because {k} is a dict in the child config '
f'but is of type {type(b[k])} in base config. '
f'You may set `{DELETE_KEY}=True` to ignore the '
f'base config.')
b[k] = Config._merge_a_into_b(v, b[k], allow_list_keys)
else:
b[k] = ConfigDict(v)
else:
b[k] = v
return b
@property
def filename(self) -> str:
"""Get file name of config."""
return self._filename
@property
def text(self) -> str:
"""Get config text."""
return self._text
@property
def env_variables(self) -> dict:
"""Get used environment variables."""
return self._env_variables
@property
def pretty_text(self) -> str:
"""Get formatted python config text."""
indent = 4
def _indent(s_, num_spaces):
s = s_.split('\n')
if len(s) == 1:
return s_
first = s.pop(0)
s = [(num_spaces * ' ') + line for line in s]
s = '\n'.join(s)
s = first + '\n' + s
return s
def _format_basic_types(k, v, use_mapping=False):
if isinstance(v, str):
v_str = repr(v)
else:
v_str = str(v)
if use_mapping:
k_str = f"'{k}'" if isinstance(k, str) else str(k)
attr_str = f'{k_str}: {v_str}'
else:
attr_str = f'{str(k)}={v_str}'
attr_str = _indent(attr_str, indent)
return attr_str
def _format_list_tuple(k, v, use_mapping=False):
if isinstance(v, list):
left = '['
right = ']'
else:
left = '('
right = ')'
v_str = f'{left}\n'
# check if all items in the list are dict
for item in v:
if isinstance(item, dict):
v_str += f'dict({_indent(_format_dict(item), indent)}),\n'
elif isinstance(item, tuple):
v_str += f'{_indent(_format_list_tuple(None, item), indent)},\n' # noqa: 501
elif isinstance(item, list):
v_str += f'{_indent(_format_list_tuple(None, item), indent)},\n' # noqa: 501
elif isinstance(item, str):
v_str += f'{_indent(repr(item), indent)},\n'
else:
v_str += str(item) + ',\n'
if k is None:
return _indent(v_str, indent) + right
if use_mapping:
k_str = f"'{k}'" if isinstance(k, str) else str(k)
attr_str = f'{k_str}: {v_str}'
else:
attr_str = f'{str(k)}={v_str}'
attr_str = _indent(attr_str, indent) + right
return attr_str
def _contain_invalid_identifier(dict_str):
contain_invalid_identifier = False
for key_name in dict_str:
contain_invalid_identifier |= \
(not str(key_name).isidentifier())
return contain_invalid_identifier
def _format_dict(input_dict, outest_level=False):
r = ''
s = []
use_mapping = _contain_invalid_identifier(input_dict)
if use_mapping:
r += '{'
for idx, (k, v) in enumerate(
sorted(input_dict.items(), key=lambda x: str(x[0]))):
is_last = idx >= len(input_dict) - 1
end = '' if outest_level or is_last else ','
if isinstance(v, dict):
v_str = '\n' + _format_dict(v)
if use_mapping:
k_str = f"'{k}'" if isinstance(k, str) else str(k)
attr_str = f'{k_str}: dict({v_str}'
else:
attr_str = f'{str(k)}=dict({v_str}'
attr_str = _indent(attr_str, indent) + ')' + end
elif isinstance(v, (list, tuple)):
attr_str = _format_list_tuple(k, v, use_mapping) + end
else:
attr_str = _format_basic_types(k, v, use_mapping) + end
s.append(attr_str)
r += '\n'.join(s)
if use_mapping:
r += '}'
return r
cfg_dict = self.to_dict()
text = _format_dict(cfg_dict, outest_level=True)
if self._format_python_code:
# copied from setup.cfg
yapf_style = dict(
based_on_style='pep8',
blank_line_before_nested_class_or_def=True,
split_before_expression_after_opening_paren=True)
try:
from ...utils import digit_version
if digit_version(yapf.__version__) >= digit_version('0.40.2'):
text, _ = FormatCode(text, style_config=yapf_style)
else:
text, _ = FormatCode(
text, style_config=yapf_style, verify=True)
except: # noqa: E722
raise SyntaxError('Failed to format the config file, please '
f'check the syntax of: \n{text}')
return text
def __repr__(self):
return f'Config (path: {self.filename}): {self._cfg_dict.__repr__()}'
def __len__(self):
return len(self._cfg_dict)
def __getattr__(self, name: str) -> Any:
return getattr(self._cfg_dict, name)
def __getitem__(self, name):
return self._cfg_dict.__getitem__(name)
def __setattr__(self, name, value):
if isinstance(value, dict):
value = ConfigDict(value)
self._cfg_dict.__setattr__(name, value)
def __setitem__(self, name, value):
if isinstance(value, dict):
value = ConfigDict(value)
self._cfg_dict.__setitem__(name, value)
def __iter__(self):
return iter(self._cfg_dict)
def __getstate__(
self
) -> Tuple[dict, Optional[str], Optional[str], dict, bool, set]:
state = (self._cfg_dict, self._filename, self._text,
self._env_variables, self._format_python_code,
self._imported_names)
return state
def __deepcopy__(self, memo):
cls = self.__class__
other = cls.__new__(cls)
memo[id(self)] = other
for key, value in self.__dict__.items():
super(Config, other).__setattr__(key, copy.deepcopy(value, memo))
return other
def __copy__(self):
cls = self.__class__
other = cls.__new__(cls)
other.__dict__.update(self.__dict__)
super(Config, other).__setattr__('_cfg_dict', self._cfg_dict.copy())
return other
copy = __copy__
def __setstate__(self, state: Tuple[dict, Optional[str], Optional[str],
dict, bool, set]):
super().__setattr__('_cfg_dict', state[0])
super().__setattr__('_filename', state[1])
super().__setattr__('_text', state[2])
super().__setattr__('_env_variables', state[3])
super().__setattr__('_format_python_code', state[4])
super().__setattr__('_imported_names', state[5])
def dump(self, file: Optional[Union[str, Path]] = None):
"""Dump config to file or return config text.
Args:
file (str or Path, optional): If not specified, then the object
is dumped to a str, otherwise to a file specified by the filename.
Defaults to None.
Returns:
str or None: Config text.
"""
file = str(file) if isinstance(file, Path) else file
cfg_dict = self.to_dict()
if file is None:
if self.filename is None or self.filename.endswith('.py'):
return self.pretty_text
else:
file_format = self.filename.split('.')[-1]
return dump(cfg_dict, file_format=file_format)
elif file.endswith('.py'):
with open(file, 'w', encoding='utf-8') as f:
f.write(self.pretty_text)
else:
file_format = file.split('.')[-1]
return dump(cfg_dict, file=file, file_format=file_format)
@staticmethod
def _is_lazy_import(filename: str) -> bool:
if not filename.endswith('.py'):
return False
with open(filename, encoding='utf-8') as f:
codes_str = f.read()
parsed_codes = ast.parse(codes_str)
for node in ast.walk(parsed_codes):
if (isinstance(node, ast.Assign)
and isinstance(node.targets[0], ast.Name)
and node.targets[0].id == BASE_KEY):
return False
if isinstance(node, ast.With):
expr = node.items[0].context_expr
if (not isinstance(expr, ast.Call)
or not expr.func.id == 'read_base'): # type: ignore
raise SyntaxError(
'Only `read_base` context manager can be used in the '
'config')
return True
if isinstance(node, ast.ImportFrom):
# relative import -> lazy_import
if node.level != 0:
return True
# Skip checking when using `mmengine.config` in cfg file
if (node.module == 'mmengine' and len(node.names) == 1
and node.names[0].name == 'Config'):
continue
if not isinstance(node.module, str):
continue
# non-builtin module -> lazy_import
if not _is_builtin_module(node.module):
return True
if isinstance(node, ast.Import):
for alias_node in node.names:
if not _is_builtin_module(alias_node.name):
return True
return False
def _to_lazy_dict(self, keep_imported: bool = False) -> dict:
"""Convert config object to dictionary with lazy object, and filter the
imported object."""
res = self._cfg_dict._to_lazy_dict()
if hasattr(self, '_imported_names') and not keep_imported:
res = {
key: value
for key, value in res.items()
if key not in self._imported_names
}
return res
def to_dict(self, keep_imported: bool = False):
"""Convert all data in the config to a builtin ``dict``.
Args:
keep_imported (bool): Whether to keep the imported field.
Defaults to False
If you import third-party objects in the config file, all imported
objects will be converted to a string like ``torch.optim.SGD``
"""
cfg_dict = self._cfg_dict.to_dict()
if hasattr(self, '_imported_names') and not keep_imported:
cfg_dict = {
key: value
for key, value in cfg_dict.items()
if key not in self._imported_names
}
return cfg_dict123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267import importlib
from typing import Any, Optional, Union, Type
from collections import abc
class LazyObject:
"""LazyObject is used to lazily initialize the imported module during
parsing the configuration file.
During parsing process, the syntax like:
Examples:
>>> import torch.nn as nn
>>> from mmdet.models import RetinaNet
>>> import mmcls.models
>>> import mmcls.datasets
>>> import mmcls
Will be parsed as:
Examples:
>>> # import torch.nn as nn
>>> nn = lazyObject('torch.nn')
>>> # from mmdet.models import RetinaNet
>>> RetinaNet = lazyObject('mmdet.models', 'RetinaNet')
>>> # import mmcls.models; import mmcls.datasets; import mmcls
>>> mmcls = lazyObject(['mmcls', 'mmcls.datasets', 'mmcls.models'])
``LazyObject`` records all module information and will be further
referenced by the configuration file.
Args:
module (str or list or tuple): The module name to be imported.
imported (str, optional): The imported module name. Defaults to None.
location (str, optional): The filename and line number of the imported
module statement happened.
"""
def __init__(self,
module: Union[str, list, tuple],
imported: Optional[str] = None,
location: Optional[str] = None):
if not isinstance(module, str) and not is_seq_of(module, str):
raise TypeError('module should be `str`, `list`, or `tuple`'
f'but got {type(module)}, this might be '
'a bug, please report it')
self._module: Union[str, list, tuple] = module
if not isinstance(imported, str) and imported is not None:
raise TypeError('imported should be `str` or None, but got '
f'{type(imported)}, this might be '
'a bug , please report it')
self._imported = imported
self.location = location
def build(self) -> Any:
"""Return imported object.
Returns:
Any: Imported object
"""
if isinstance(self._module, str):
try:
module = importlib.import_module(self._module)
except Exception as e:
raise type(e)(f'Failed to import {self._module} '
f'in {self.location} for {e}')
if self._imported is not None:
if hasattr(module, self._imported):
module = getattr(module, self._imported)
else:
raise ImportError(
f'Failed to import {self._imported} '
f'from {self._module} in {self.location}')
return module
else:
try:
for module in self._module:
importlib.import_module(module) # type: ignore
module_name = self._module[0].split('.')[0]
return importlib.import_module(module_name)
except Exception as e:
raise type(e)(f'Failed to import {self.module} '
f'in {self.location} for {e}')
@property
def module(self):
if isinstance(self._module, str):
return self._module
return self._module[0].split('.')[0]
def __call__(self, *args, **kwargs):
raise RuntimeError()
def __deepcopy__(self, memo):
return LazyObject(self._module, self._imported, self.location)
def __getattr__(self, name):
# Cannot locate the line number of the getting attribute.
# Therefore only record the filename.
if self.location is not None:
location = self.location.split(', line')[0]
else:
location = self.location
return LazyAttr(name, self, location)
def __str__(self) -> str:
if self._imported is not None:
return self._imported
return self.module
__repr__ = __str__
# `pickle.dump` will try to get the `__getstate__` and `__setstate__`
# methods of the dumped object. If these two methods are not defined,
# LazyObject will return a `__getstate__` LazyObject` or `__setstate__`
# LazyObject.
def __getstate__(self):
return self.__dict__
def __setstate__(self, state):
self.__dict__ = state
class LazyAttr:
"""The attribute of the LazyObject.
When parsing the configuration file, the imported syntax will be
parsed as the assignment ``LazyObject``. During the subsequent parsing
process, users may reference the attributes of the LazyObject.
To ensure that these attributes also contain information needed to
reconstruct the attribute itself, LazyAttr was introduced.
Examples:
>>> models = LazyObject(['mmdet.models'])
>>> model = dict(type=models.RetinaNet)
>>> print(type(model['type'])) # <class 'mmengine.config.lazy.LazyAttr'>
>>> print(model['type'].build()) # <class 'mmdet.models.detectors.retinanet.RetinaNet'>
""" # noqa: E501
def __init__(self,
name: str,
source: Union['LazyObject', 'LazyAttr'],
location=None):
self.name = name
self.source: Union[LazyAttr, LazyObject] = source
if isinstance(self.source, LazyObject):
if isinstance(self.source._module, str):
if self.source._imported is None:
# source code:
# from xxx.yyy import zzz
# equivalent code:
# zzz = LazyObject('xxx.yyy', 'zzz')
# The source code of get attribute:
# eee = zzz.eee
# Then, `eee._module` should be "xxx.yyy.zzz"
self._module = self.source._module
else:
# source code:
# import xxx.yyy as zzz
# equivalent code:
# zzz = LazyObject('xxx.yyy')
# The source code of get attribute:
# eee = zzz.eee
# Then, `eee._module` should be "xxx.yyy"
self._module = f'{self.source._module}.{self.source}'
else:
# The source code of LazyObject should be
# 1. import xxx.yyy
# 2. import xxx.zzz
# Equivalent to
# xxx = LazyObject(['xxx.yyy', 'xxx.zzz'])
# The source code of LazyAttr should be
# eee = xxx.eee
# Then, eee._module = xxx
self._module = str(self.source)
elif isinstance(self.source, LazyAttr):
# 1. import xxx
# 2. zzz = xxx.yyy.zzz
# Equivalent to:
# xxx = LazyObject('xxx')
# zzz = xxx.yyy.zzz
# zzz._module = xxx.yyy._module + zzz.name
self._module = f'{self.source._module}.{self.source.name}'
self.location = location
@property
def module(self):
return self._module
def __call__(self, *args, **kwargs: Any) -> Any:
raise RuntimeError()
def __getattr__(self, name: str) -> 'LazyAttr':
return LazyAttr(name, self)
def __deepcopy__(self, memo):
return LazyAttr(self.name, self.source)
def build(self) -> Any:
"""Return the attribute of the imported object.
Returns:
Any: attribute of the imported object.
"""
obj = self.source.build()
try:
return getattr(obj, self.name)
except AttributeError:
raise ImportError(f'Failed to import {self.module}.{self.name} in '
f'{self.location}')
except ImportError as e:
raise e
def __str__(self) -> str:
return self.name
__repr__ = __str__
# `pickle.dump` will try to get the `__getstate__` and `__setstate__`
# methods of the dumped object. If these two methods are not defined,
# LazyAttr will return a `__getstate__` LazyAttr` or `__setstate__`
# LazyAttr.
def __getstate__(self):
return self.__dict__
def __setstate__(self, state):
self.__dict__ = state
def is_seq_of(seq: Any,
expected_type: Union[Type, tuple],
seq_type: Optional[Type] = None) -> bool:
"""Check whether it is a sequence of some type.
Args:
seq (Sequence): The sequence to be checked.
expected_type (type or tuple): Expected type of sequence items.
seq_type (type, optional): Expected sequence type. Defaults to None.
Returns:
bool: Return True if ``seq`` is valid else False.
Examples:
>>> from mmengine.utils import is_seq_of
>>> seq = ['a', 'b', 'c']
>>> is_seq_of(seq, str)
True
>>> is_seq_of(seq, int)
False
"""
if seq_type is None:
exp_seq_type = abc.Sequence
else:
assert isinstance(seq_type, type)
exp_seq_type = seq_type
if not isinstance(seq, exp_seq_type):
return False
for item in seq:
if not isinstance(item, expected_type):
return False
return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687import ast
import os.path as osp
import re
import sys
import warnings
from collections import defaultdict
from importlib.util import find_spec
from typing import List, Optional, Tuple, Union
from importlib import import_module as real_import_module
import json
import pickle
from pathlib import Path
import itertools
import importlib.util # Hinzugefügt für find_spec in Python >= 3.7
import importlib.metadata # Ersatz für pkg_resources.get_distribution und package2module
# Ersetzt: from pkg_resources.extern import packaging
# Ersetzt: __import__('pkg_resources.extern.packaging.version')
# Ersetzt: __import__('pkg_resources.extern.packaging.specifiers')
# Ersetzt: __import__('pkg_resources.extern.packaging.requirements')
# Ersetzt: __import__('pkg_resources.extern.packaging.markers')
# Importiert nun das externe 'packaging'-Paket direkt
try:
import packaging.version
import packaging.specifiers
import packaging.requirements
import packaging.markers
except ImportError as e:
raise ImportError(
"The 'packaging' package is required but not installed. "
"Install it with 'pip install packaging'."
) from e
import yaml
from omegaconf import OmegaConf
# Die folgenden Hilfsfunktionen aus pkg_resources wurden unten neu implementiert
# oder durch `packaging` ersetzt: get_distribution, package2module, Requirement,
# parse_requirements, yield_lines, safe_extra, safe_name.
# --- Hilfsfunktionen für `packaging` (Ersatz für pkg_resources-Logik) ---
# Implementierung der pkg_resources-Hilfsfunktionen mit 'packaging'
def safe_extra(extra: str) -> str:
"""Convert an arbitrary string to a standard 'extra' name"""
# pkg_resources implementation detail using packaging's rules
return re.sub(r'[^A-Za-z0-9.-]+', '_', extra).lower()
def safe_name(name: str) -> str:
"""Convert an arbitrary string to a standard distribution name"""
# pkg_resources implementation detail using packaging's rules
return re.sub(r'[^A-Za-z0-9.]+', '-', name)
class DistributionNotFound(Exception):
"""Exception raised when a distribution is not found."""
pass
def get_distribution(dist_name: str) -> importlib.metadata.Distribution:
"""Return a current distribution object for a package name or string requirement.
Args:
dist_name (str): The name of the package or a requirement string.
Returns:
importlib.metadata.Distribution: The found distribution object.
Raises:
DistributionNotFound: If the package is not found.
ValueError: If a requirement string is used (not supported by this simplified function).
"""
if ' ' in dist_name or any(op in dist_name for op in ('==', '>=', '<=', '>', '<', '~=', '!=', '==')):
# importlib.metadata.distribution does not handle requirement strings.
# It's better to use the distribution name directly.
# Fallback to direct name extraction.
try:
req = packaging.requirements.Requirement(dist_name)
dist_name = req.name
except packaging.requirements.InvalidRequirement:
raise ValueError(
f"get_distribution only supports package names or simple requirements, "
f"but got: {dist_name}"
)
try:
# Use importlib.metadata.distribution for name-based lookup
return importlib.metadata.distribution(dist_name)
except importlib.metadata.PackageNotFoundError:
raise DistributionNotFound(f"The 'Distribution' '{dist_name}' was not found and is required")
def package2module(package: str) -> str:
"""Infer module name from package using importlib.metadata.
Args:
package (str): Package to infer module name.
Returns:
str: The module name.
Raises:
ValueError: If the top-level module name cannot be inferred.
"""
try:
# Use importlib.metadata.distribution
dist = get_distribution(package)
# Check for top_level.txt metadata
top_level_txt = dist.read_text('top_level.txt')
if top_level_txt:
# The first non-empty line is usually the top-level module name
module_name = top_level_txt.split('\n')[0].strip()
if module_name:
return module_name
except (DistributionNotFound, FileNotFoundError):
# Package not found or top_level.txt not available/found
pass # Will raise ValueError below
raise ValueError(
highlighted_error(f'can not infer the module name of {package}. '
'Metadata (top_level.txt) not found or package not installed.')
)
# Neuimplementierung der Requirement-Logik von pkg_resources mit packaging.requirements.Requirement
class Requirement(packaging.requirements.Requirement):
"""Reimplementation of pkg_resources.Requirement using packaging.requirements.Requirement."""
def __init__(self, requirement_string):
"""DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
super().__init__(requirement_string)
self.unsafe_name = self.name
project_name = safe_name(self.name)
self.project_name, self.key = project_name, project_name.lower()
# specs is an internal list in pkg_resources
self.specs = [
(spec.operator, spec.version) for spec in self.specifier
] if self.specifier else []
self.extras = tuple(map(safe_extra, self.extras))
# hashCmp logic from pkg_resources
self.hashCmp = (
self.key,
self.url,
str(self.specifier) if self.specifier else '',
frozenset(self.extras),
str(self.marker) if self.marker else None,
)
self.__hash = hash(self.hashCmp)
def __eq__(self, other):
return (
isinstance(other, Requirement) and
self.hashCmp == other.hashCmp
)
def __contains__(self, item: packaging.version.Version) -> bool:
"""Check if a specific version is contained in the requirement."""
if isinstance(item, str):
try:
item = packaging.version.Version(item)
except packaging.version.InvalidVersion:
warnings.warn(f"Invalid version string: {item}", UserWarning)
return False
if self.key != safe_name(item.base_version).lower():
# This check is an oversimplification but reflects pkg_resources' intent
# In a real-world scenario, you should compare the package name.
# Since the original code only imports 'packaging' and not a distribution object,
# this check can only be an approximation.
return False
# The packaging specifier can check against packaging.version.Version objects
# prereleases=True is required to match pkg_resources' default behavior
return self.specifier.contains(item, prereleases=True)
def __hash__(self):
return self.__hash
@staticmethod
def parse(s):
reqs = list(parse_requirements(s))
if not reqs:
raise ValueError(f"Could not parse requirement from string: {s}")
return reqs[0]
def yield_lines(iterable: Union[str, list, tuple]) -> List[str]:
"""Yield valid lines of a string or iterable, recursively."""
if isinstance(iterable, str):
return [line for line in iterable.splitlines() if line.strip() and not line.strip().startswith('#')]
lines = []
for item in iterable:
lines.extend(yield_lines(item))
return lines
def parse_requirements(strs: Union[str, list, tuple]) -> 'Requirement':
"""Yield ``Requirement`` objects for each specification in `strs`."""
lines = iter(yield_lines(strs))
for line in lines:
# Drop comments and handle line continuation
if ' #' in line:
line = line[:line.find(' #')]
line = line.strip()
# If there is a line continuation, drop it, and append the next line.
while line.endswith('\\'):
line = line[:-1].strip()
try:
line += next(lines).strip()
except StopIteration:
break # End of lines
if line:
yield Requirement(line)
# --- Ende der Hilfsfunktionen ---
PYTHON_ROOT_DIR = osp.dirname(osp.dirname(sys.executable))
SYSTEM_PYTHON_PREFIX = '/usr/lib/python'
class ConfigParsingError(RuntimeError):
"""Raise error when failed to parse pure Python style config files."""
def _get_cfg_metainfo(package_path: str, cfg_path: str) -> dict:
"""Get target meta information from all 'metafile.yml' defined in `mode-
index.yml` of external package.
Args:
package_path (str): Path of external package.
cfg_path (str): Name of experiment config.
Returns:
dict: Meta information of target experiment.
"""
meta_index_path = osp.join(package_path, '.mim', 'model-index.yml')
meta_index = OmegaConf.to_container(OmegaConf.load(meta_index_path), resolve=True)
cfg_dict = dict()
for meta_path in meta_index['Import']:
meta_path = osp.join(package_path, '.mim', meta_path)
cfg_meta = OmegaConf.to_container(OmegaConf.load(meta_path), resolve=True)
for model_cfg in cfg_meta['Models']:
if 'Config' not in model_cfg:
warnings.warn(f'There is not `Config` define in {model_cfg}')
continue
cfg_name = model_cfg['Config'].partition('/')[-1]
# Some config could have multiple weights, we only pick the
# first one.
if cfg_name in cfg_dict:
continue
cfg_dict[cfg_name] = model_cfg
if cfg_path not in cfg_dict:
raise ValueError(f'Expected configs: {cfg_dict.keys()}, but got '
f'{cfg_path}')
return cfg_dict[cfg_path]
def _get_external_cfg_path(package_path: str, cfg_file: str) -> str:
"""Get config path of external package.
Args:
package_path (str): Path of external package.
cfg_file (str): Name of experiment config.
Returns:
str: Absolute config path from external package.
"""
cfg_file = cfg_file.split('.')[0]
model_cfg = _get_cfg_metainfo(package_path, cfg_file)
cfg_path = osp.join(package_path, model_cfg['Config'])
check_file_exist(cfg_path)
return cfg_path
def _get_external_cfg_base_path(package_path: str, cfg_name: str) -> str:
"""Get base config path of external package.
Args:
package_path (str): Path of external package.
cfg_name (str): External relative config path with 'package::'.
Returns:
str: Absolute config path from external package.
"""
cfg_path = osp.join(package_path, '.mim', 'configs', cfg_name)
check_file_exist(cfg_path)
return cfg_path
def _get_package_and_cfg_path(cfg_path: str) -> Tuple[str, str]:
"""Get package name and relative config path.
Args:
cfg_path (str): External relative config path with 'package::'.
Returns:
Tuple[str, str]: Package name and config path.
"""
if re.match(r'\w*::\w*/\w*', cfg_path) is None:
raise ValueError(
'`_get_package_and_cfg_path` is used for get external package, '
'please specify the package name and relative config path, just '
'like `mmdet::faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py`')
package_cfg = cfg_path.split('::')
if len(package_cfg) > 2:
raise ValueError('`::` should only be used to separate package and '
'config name, but found multiple `::` in '
f'{cfg_path}')
package, cfg_path = package_cfg
return package, cfg_path
class RemoveAssignFromAST(ast.NodeTransformer):
"""Remove Assign node if the target's name match the key.
Args:
key (str): The target name of the Assign node.
"""
def __init__(self, key):
self.key = key
def visit_Assign(self, node):
if (isinstance(node.targets[0], ast.Name)
and node.targets[0].id == self.key):
return None
else:
return node
def _is_builtin_module(module_name: str) -> bool:
"""Check if a module is a built-in module.
Arg:
module_name: name of module.
"""
if module_name.startswith('.'):
return False
if module_name.startswith('mmengine.config'):
return True
if module_name in sys.builtin_module_names:
return True
spec = find_spec(module_name.split('.')[0])
# Module not found
if spec is None:
return False
origin_path = getattr(spec, 'origin', None)
if origin_path is None:
return False
origin_path = osp.abspath(origin_path)
if ('site-package' in origin_path or 'dist-package' in origin_path
or not origin_path.startswith(
(PYTHON_ROOT_DIR, SYSTEM_PYTHON_PREFIX))):
return False
else:
return True
class ImportTransformer(ast.NodeTransformer):
"""Convert the import syntax to the assignment of
:class:`mmengine.config.LazyObject` and preload the base variable before
parsing the configuration file.
"""
# noqa: E501
def __init__(self,
global_dict: dict,
base_dict: Optional[dict] = None,
filename: Optional[str] = None):
self.base_dict = base_dict if base_dict is not None else {}
self.global_dict = global_dict
if isinstance(filename, str):
filename = filename.encode('unicode_escape').decode()
self.filename = filename
self.imported_obj: set = set()
super().__init__()
def visit_ImportFrom(
self, node: ast.ImportFrom
) -> Optional[Union[List[ast.Assign], ast.ImportFrom]]:
# Built-in modules will not be parsed as LazyObject
module = f'{node.level * "."}{node.module}'
if _is_builtin_module(module):
# Make sure builtin module will be added into `self.imported_obj`
for alias in node.names:
if alias.asname is not None:
self.imported_obj.add(alias.asname)
elif alias.name == '*':
raise ConfigParsingError(
'Cannot import * from non-base config')
else:
self.imported_obj.add(alias.name)
return node
if module in self.base_dict:
for alias_node in node.names:
if alias_node.name == '*':
self.global_dict.update(self.base_dict[module])
return None
if alias_node.asname is not None:
base_key = alias_node.asname
else:
base_key = alias_node.name
self.global_dict[base_key] = self.base_dict[module][
alias_node.name]
return None
nodes: List[ast.Assign] = []
for alias_node in node.names:
# `ast.alias` has lineno attr after Python 3.10,
if hasattr(alias_node, 'lineno'):
lineno = alias_node.lineno
else:
lineno = node.lineno
if alias_node.name == '*':
raise ConfigParsingError(
'Illegal syntax in config! `from xxx import *` is not '
'allowed to appear outside the `if base:` statement')
elif alias_node.asname is not None:
code = f'{alias_node.asname} = LazyObject("{module}", "{alias_node.name}", "{self.filename}, line {lineno}")' # noqa: E501
self.imported_obj.add(alias_node.asname)
else:
code = f'{alias_node.name} = LazyObject("{module}", "{alias_node.name}", "{self.filename}, line {lineno}")' # noqa: E501
self.imported_obj.add(alias_node.name)
try:
nodes.append(ast.parse(code).body[0]) # type: ignore
except Exception as e:
raise ConfigParsingError(
f'Cannot import {alias_node} from {module}'
'1. Cannot import * from 3rd party lib in the config '
'file\n'
'2. Please check if the module is a base config which '
'should be added to `_base_`\n') from e
return nodes
def visit_Import(self, node) -> Union[ast.Assign, ast.Import]:
"""Work with ``_gather_abs_import_lazyobj`` to hack the ``import ...``
syntax.
"""
alias_list = node.names
assert len(alias_list) == 1, (
'Illegal syntax in config! import multiple modules in one line is '
'not supported')
# TODO Support multiline import
alias = alias_list[0]
if alias.asname is not None:
self.imported_obj.add(alias.asname)
if _is_builtin_module(alias.name.split('.')[0]):
return node
return ast.parse( # type: ignore
f'{alias.asname} = LazyObject('
f'"{alias.name}",'
f'location="{self.filename}, line {node.lineno}")').body[0]
return node
def _gather_abs_import_lazyobj(tree: ast.Module,
filename: Optional[str] = None):
"""Experimental implementation of gathering absolute import information."""
if isinstance(filename, str):
filename = filename.encode('unicode_escape').decode()
imported = defaultdict(list)
abs_imported = set()
new_body: List[ast.stmt] = []
# module2node is used to get lineno when Python < 3.10
module2node: dict = dict()
for node in tree.body:
if isinstance(node, ast.Import):
for alias in node.names:
# Skip converting built-in module to LazyObject
if _is_builtin_module(alias.name):
new_body.append(node)
continue
module = alias.name.split('.')[0]
module2node.setdefault(module, node)
imported[module].append(alias)
continue
new_body.append(node)
for key, value in imported.items():
names = [_value.name for _value in value]
if hasattr(value[0], 'lineno'):
lineno = value[0].lineno
else:
lineno = module2node[key].lineno
lazy_module_assign = ast.parse(
f'{key} = LazyObject({names}, location="{filename}, line {lineno}")' # noqa: E501
) # noqa: E501
abs_imported.add(key)
new_body.insert(0, lazy_module_assign.body[0])
tree.body = new_body
return tree, abs_imported
def get_installed_path(package: str) -> str:
"""Get installed path of package.
Replaced:
from pkg_resources import DistributionNotFound, get_distribution
Uses:
importlib.metadata
Args:
package (str): Name of package.
"""
try:
# 1. Try with importlib.metadata
pkg = importlib.metadata.distribution(package)
# pkg.locate is the directory containing the package, similar to pkg.location
possible_path = osp.join(pkg.locate(), package2module(package)) # Use package2module to ensure correct module dir
# Check if the main package dir exists in the location
if osp.exists(possible_path):
return possible_path
# Fallback to the distribution location itself (e.g., for namespace packages)
return pkg.locate()
except importlib.metadata.PackageNotFoundError as e:
# 2. If not found via metadata, check PYTHONPATH/sys.path via importlib.util.find_spec
spec = importlib.util.find_spec(package)
if spec is not None:
if spec.origin is not None:
# spec.origin is the path to the __init__.py or .py file
return osp.dirname(spec.origin)
else:
# Namespace packages don't have an origin but a spec exists
raise RuntimeError(
f'{package} is a namespace package, which is invalid '
'for `get_install_path` in this context')
else:
# Re-raise the original not found error, but as the new type
raise DistributionNotFound(
f"The 'Distribution' '{package}' was not found and is required"
) from e
def import_modules_from_strings(imports, allow_failed_imports=False):
"""Import modules from the given list of strings.
Args:
imports (list | str | None): The given module names to be imported.
allow_failed_imports (bool): If True, the failed imports will return
None. Otherwise, an ImportError is raise. Defaults to False.
Returns:
list[module] | module | None: The imported modules.
"""
if not imports:
return
single_import = False
if isinstance(imports, str):
single_import = True
imports = [imports]
if not isinstance(imports, list):
raise TypeError(
f'custom_imports must be a list but got type {type(imports)}')
imported = []
for imp in imports:
if not isinstance(imp, str):
raise TypeError(
f'{imp} is of type {type(imp)} and cannot be imported.')
try:
imported_tmp = import_module(imp)
except ImportError:
if allow_failed_imports:
warnings.warn(f'{imp} failed to import and is ignored.',
UserWarning)
imported_tmp = None
else:
raise ImportError(f'Failed to import {imp}')
imported.append(imported_tmp)
if single_import:
imported = imported[0]
return imported
def import_module(name, package=None):
"""Import a module, optionally supporting relative imports."""
return real_import_module(name, package)
def is_installed(package: str) -> bool:
"""Check package whether installed.
Replaced:
import pkg_resources
from pkg_resources import get_distribution
Uses:
importlib.metadata
Args:
package (str): Name of package to be checked.
"""
# Note: importlib.metadata.distribution() is generally the most reliable check
# for an installed package (e.g., via pip/wheel).
# 1. Check via importlib.metadata.distribution
try:
importlib.metadata.distribution(package)
return True
except importlib.metadata.PackageNotFoundError:
pass # Continue to step 2
# 2. Fallback check for packages potentially in PYTHONPATH without full metadata
spec = importlib.util.find_spec(package)
if spec is not None:
# If spec.origin is None, it's a namespace package (which is "found" but not installed like a normal package)
# If spec.origin is not None, it's a module/package file that was found.
return spec.origin is not None
return False
def dump(obj, file=None, file_format=None, **kwargs):
"""Dump data to json/yaml/pickle strings or files (mmengine-like replacement)."""
if isinstance(file, Path):
file = str(file)
# Guess file format if not explicitly given
if file_format is None:
if isinstance(file, str):
file_format = file.split('.')[-1].lower()
elif file is None:
raise ValueError("file_format must be specified if file is None")
if file_format not in ['json', 'yaml', 'yml', 'pkl', 'pickle']:
raise TypeError(f"Unsupported file format: {file_format}")
# Convert YAML extension
if file_format == 'yml':
file_format = 'yaml'
if file_format == 'pickle':
file_format = 'pkl'
# Handle output to string
if file is None:
if file_format == 'json':
return json.dumps(obj, indent=4, **kwargs)
elif file_format == 'yaml':
return yaml.dump(obj, **kwargs)
elif file_format == 'pkl':
return pickle.dumps(obj, **kwargs)
# Handle output to file
mode = 'w' if file_format in ['json', 'yaml'] else 'wb'
with open(file, mode, encoding='utf-8' if 'b' not in mode else None) as f:
if file_format == 'json':
json.dump(obj, f, indent=4, **kwargs)
elif file_format == 'yaml':
yaml.dump(obj, f, **kwargs)
elif file_format == 'pkl':
pickle.dump(obj, f, **kwargs)
return True
def check_file_exist(filename, msg_tmpl='file "{}" does not exist'):
if not osp.isfile(filename):
raise FileNotFoundError(msg_tmpl.format(filename))
def highlighted_error(msg: Union[str, Exception]) -> str:
# Assuming 'click' is installed or this is a placeholder
# If not using click, you can replace it with a simple string formatting for bold/red
try:
import click
return click.style(str(msg), fg='red', bold=True)
except ImportError:
return f"[ERROR] {msg}"12345678910111213141516171819202122232425262728norm_cfg = dict(type='SyncBN', requires_grad=True)
backbone = dict(
type='MixVisionTransformer',
in_channels=3,
embed_dims=32,
num_stages=4,
num_layers=[2, 2, 2, 2],
num_heads=[1, 2, 5, 8],
patch_sizes=[7, 3, 3, 3],
sr_ratios=[8, 4, 2, 1],
out_indices=(0, 1, 2, 3),
mlp_ratio=4,
qkv_bias=True,
drop_rate=0.0,
attn_drop_rate=0.0,
drop_path_rate=0.1
)
decode_head = dict(
type='SegformerHead',
in_channels=[32, 64, 160, 256],
in_index=[0, 1, 2, 3],
channels=256,
dropout_ratio=0.1,
out_channels=19,
norm_cfg=norm_cfg,
align_corners=False,
interpolate_mode='bilinear'
)12345678_base_ = ['./segformer_mit_b0.py']
backbone = dict(
embed_dims=64,
)
decode_head = dict(
in_channels=[64, 128, 320, 512]
)123456_base_ = ['./segformer_mit_b1.py']
backbone = dict(
embed_dims=64,
num_layers=[3, 4, 6, 3]
)123456_base_ = ['./segformer_mit_b1.py']
backbone = dict(
embed_dims=64,
num_layers=[3, 4, 18, 3]
).gitattributes+4
Segformer++. Efficient Token-Merging Strategies for High-Resolution Semantic Segmentation.pdfAdded+3
code/SegformerPlusPlus.zipAdded+3
models/SegformerPlusPlus (KieDani)/.gitattributesAdded+38
models/SegformerPlusPlus (KieDani)/LICENSE.txtAdded+674
models/SegformerPlusPlus (KieDani)/README.mdAdded+96
models/SegformerPlusPlus (KieDani)/docs/figures/pose.pngAdded
/docs/figures/pose.png)
Large File Pointer Details
- SHA256: 1083548df4d741dd264b7f2c8c91278fa946b111b19f8f6ade26c0e2cf654540
- Pointer size: 131 Bytes
- Size of remote file: 797 kB
models/SegformerPlusPlus (KieDani)/docs/figures/segmentation.pngAdded
/docs/figures/segmentation.png)
Large File Pointer Details
- SHA256: dfabdd3fe1e70365875b9f1d8674772b2636db1431ed49ccf8551f4438c9939b
- Pointer size: 131 Bytes
- Size of remote file: 398 kB
models/SegformerPlusPlus (KieDani)/docs/run/run_mmeng.mdAdded+15
models/SegformerPlusPlus (KieDani)/docs/run/run_mmpose.mdAdded+23
models/SegformerPlusPlus (KieDani)/docs/run/run_mmseg.mdAdded+23
models/SegformerPlusPlus (KieDani)/docs/run/run_noopenmmlab.mdAdded+137
models/SegformerPlusPlus (KieDani)/docs/run/token_merging.mdAdded+50
models/SegformerPlusPlus (KieDani)/docs/setup/mmeng_setup.mdAdded+34
models/SegformerPlusPlus (KieDani)/docs/setup/mmpose_setup.mdAdded+24
models/SegformerPlusPlus (KieDani)/docs/setup/mmseg_setup.mdAdded+25
models/SegformerPlusPlus (KieDani)/docs/setup/noopenmmlab_setup.mdAdded+15
models/SegformerPlusPlus (KieDani)/docs/setup/torchhub_setup.mdAdded+139
models/SegformerPlusPlus (KieDani)/example_torchhub.pyAdded+58
models/SegformerPlusPlus (KieDani)/hubconf.pyAdded+185
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/pyproject.tomlAdded+40
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/Registry/__init__.pyAdded+3
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/Registry/__pycache__/__init__.cpython-310.pycAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/Registry/__pycache__/default_scope.cpython-310.pycAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/Registry/__pycache__/registry.cpython-310.pycAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/Registry/default_scope.pyAdded+95
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/Registry/registry.pyAdded+557
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/__init__.pyAdded+4
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/__pycache__/__init__.cpython-310.pycAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/__pycache__/build_model.cpython-310.pycAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/__pycache__/cityscape_benchmark.cpython-310.pycAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/__pycache__/random_benchmark.cpython-310.pycAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/__pycache__/start_cityscape_benchmark.cpython-310.pycAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/build_model.pyAdded+107
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/cityscape/berlin_000543_000019_leftImg8bit.pngAdded
/model_without_OpenMMLab/segformer_plusplus/cityscape/berlin_000543_000019_leftImg8bit.png)
Large File Pointer Details
- SHA256: 3d616adab2c462fdee7f47a2de927436aebfb73843c38c3e3fbc85a6220955d4
- Pointer size: 132 Bytes
- Size of remote file: 2.37 MB
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/cityscape_benchmark.pyAdded+108
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/cityscapes_prediction_output.txtAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/cityscapes_prediction_output__reference_b05_bsm_hq_checkpoint.txtAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/__init__.pyAdded+1
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/__pycache__/__init__.cpython-310.pycAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/config/__pycache__/config.cpython-310.pycAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/config/__pycache__/lazy.cpython-310.pycAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/config/__pycache__/utils.cpython-310.pycAdded
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/config/config.pyAdded+1545
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/config/lazy.pyAdded+267
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/config/utils.pyAdded+687
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b0.pyAdded+28
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b1.pyAdded+8
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b2.pyAdded+6
models/SegformerPlusPlus (KieDani)/model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b3.pyAdded+6