Initial upload
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +3 -0
- LICENSE.txt +674 -0
- README.md +93 -3
- docs/figures/pose.png +3 -0
- docs/figures/segmentation.png +3 -0
- docs/run/run_mmeng.md +15 -0
- docs/run/run_mmpose.md +23 -0
- docs/run/run_mmseg.md +23 -0
- docs/run/run_noopenmmlab.md +137 -0
- docs/run/token_merging.md +50 -0
- docs/setup/mmeng_setup.md +34 -0
- docs/setup/mmpose_setup.md +24 -0
- docs/setup/mmseg_setup.md +25 -0
- docs/setup/noopenmmlab_setup.md +15 -0
- docs/setup/torchhub_setup.md +139 -0
- example_torchhub.py +58 -0
- hubconf.py +185 -0
- model_without_OpenMMLab/pyproject.toml +40 -0
- model_without_OpenMMLab/segformer_plusplus/Registry/__init__.py +3 -0
- model_without_OpenMMLab/segformer_plusplus/Registry/__pycache__/__init__.cpython-310.pyc +0 -0
- model_without_OpenMMLab/segformer_plusplus/Registry/__pycache__/default_scope.cpython-310.pyc +0 -0
- model_without_OpenMMLab/segformer_plusplus/Registry/__pycache__/registry.cpython-310.pyc +0 -0
- model_without_OpenMMLab/segformer_plusplus/Registry/default_scope.py +95 -0
- model_without_OpenMMLab/segformer_plusplus/Registry/registry.py +557 -0
- model_without_OpenMMLab/segformer_plusplus/__init__.py +4 -0
- model_without_OpenMMLab/segformer_plusplus/__pycache__/__init__.cpython-310.pyc +0 -0
- model_without_OpenMMLab/segformer_plusplus/__pycache__/build_model.cpython-310.pyc +0 -0
- model_without_OpenMMLab/segformer_plusplus/__pycache__/cityscape_benchmark.cpython-310.pyc +0 -0
- model_without_OpenMMLab/segformer_plusplus/__pycache__/random_benchmark.cpython-310.pyc +0 -0
- model_without_OpenMMLab/segformer_plusplus/__pycache__/start_cityscape_benchmark.cpython-310.pyc +0 -0
- model_without_OpenMMLab/segformer_plusplus/build_model.py +107 -0
- model_without_OpenMMLab/segformer_plusplus/cityscape/berlin_000543_000019_leftImg8bit.png +3 -0
- model_without_OpenMMLab/segformer_plusplus/cityscape_benchmark.py +108 -0
- model_without_OpenMMLab/segformer_plusplus/cityscapes_prediction_output.txt +0 -0
- model_without_OpenMMLab/segformer_plusplus/cityscapes_prediction_output__reference_b05_bsm_hq_checkpoint.txt +0 -0
- model_without_OpenMMLab/segformer_plusplus/configs/__init__.py +1 -0
- model_without_OpenMMLab/segformer_plusplus/configs/__pycache__/__init__.cpython-310.pyc +0 -0
- model_without_OpenMMLab/segformer_plusplus/configs/config/__pycache__/config.cpython-310.pyc +0 -0
- model_without_OpenMMLab/segformer_plusplus/configs/config/__pycache__/lazy.cpython-310.pyc +0 -0
- model_without_OpenMMLab/segformer_plusplus/configs/config/__pycache__/utils.cpython-310.pyc +0 -0
- model_without_OpenMMLab/segformer_plusplus/configs/config/config.py +1545 -0
- model_without_OpenMMLab/segformer_plusplus/configs/config/lazy.py +267 -0
- model_without_OpenMMLab/segformer_plusplus/configs/config/utils.py +687 -0
- model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b0.py +28 -0
- model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b1.py +8 -0
- model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b2.py +6 -0
- model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b3.py +6 -0
- model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b4.py +6 -0
- model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b5.py +6 -0
- model_without_OpenMMLab/segformer_plusplus/model/__init__.py +1 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
docs/figures/pose.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
docs/figures/segmentation.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
model_without_OpenMMLab/segformer_plusplus/cityscape/berlin_000543_000019_leftImg8bit.png filter=lfs diff=lfs merge=lfs -text
|
LICENSE.txt
ADDED
|
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GNU GENERAL PUBLIC LICENSE
|
| 2 |
+
Version 3, 29 June 2007
|
| 3 |
+
|
| 4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
| 5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
| 6 |
+
of this license document, but changing it is not allowed.
|
| 7 |
+
|
| 8 |
+
Preamble
|
| 9 |
+
|
| 10 |
+
The GNU General Public License is a free, copyleft license for
|
| 11 |
+
software and other kinds of works.
|
| 12 |
+
|
| 13 |
+
The licenses for most software and other practical works are designed
|
| 14 |
+
to take away your freedom to share and change the works. By contrast,
|
| 15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
| 16 |
+
share and change all versions of a program--to make sure it remains free
|
| 17 |
+
software for all its users. We, the Free Software Foundation, use the
|
| 18 |
+
GNU General Public License for most of our software; it applies also to
|
| 19 |
+
any other work released this way by its authors. You can apply it to
|
| 20 |
+
your programs, too.
|
| 21 |
+
|
| 22 |
+
When we speak of free software, we are referring to freedom, not
|
| 23 |
+
price. Our General Public Licenses are designed to make sure that you
|
| 24 |
+
have the freedom to distribute copies of free software (and charge for
|
| 25 |
+
them if you wish), that you receive source code or can get it if you
|
| 26 |
+
want it, that you can change the software or use pieces of it in new
|
| 27 |
+
free programs, and that you know you can do these things.
|
| 28 |
+
|
| 29 |
+
To protect your rights, we need to prevent others from denying you
|
| 30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
| 31 |
+
certain responsibilities if you distribute copies of the software, or if
|
| 32 |
+
you modify it: responsibilities to respect the freedom of others.
|
| 33 |
+
|
| 34 |
+
For example, if you distribute copies of such a program, whether
|
| 35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
| 36 |
+
freedoms that you received. You must make sure that they, too, receive
|
| 37 |
+
or can get the source code. And you must show them these terms so they
|
| 38 |
+
know their rights.
|
| 39 |
+
|
| 40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
| 41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
| 42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
| 43 |
+
|
| 44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
| 45 |
+
that there is no warranty for this free software. For both users' and
|
| 46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
| 47 |
+
changed, so that their problems will not be attributed erroneously to
|
| 48 |
+
authors of previous versions.
|
| 49 |
+
|
| 50 |
+
Some devices are designed to deny users access to install or run
|
| 51 |
+
modified versions of the software inside them, although the manufacturer
|
| 52 |
+
can do so. This is fundamentally incompatible with the aim of
|
| 53 |
+
protecting users' freedom to change the software. The systematic
|
| 54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
| 55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
| 56 |
+
have designed this version of the GPL to prohibit the practice for those
|
| 57 |
+
products. If such problems arise substantially in other domains, we
|
| 58 |
+
stand ready to extend this provision to those domains in future versions
|
| 59 |
+
of the GPL, as needed to protect the freedom of users.
|
| 60 |
+
|
| 61 |
+
Finally, every program is threatened constantly by software patents.
|
| 62 |
+
States should not allow patents to restrict development and use of
|
| 63 |
+
software on general-purpose computers, but in those that do, we wish to
|
| 64 |
+
avoid the special danger that patents applied to a free program could
|
| 65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
| 66 |
+
patents cannot be used to render the program non-free.
|
| 67 |
+
|
| 68 |
+
The precise terms and conditions for copying, distribution and
|
| 69 |
+
modification follow.
|
| 70 |
+
|
| 71 |
+
TERMS AND CONDITIONS
|
| 72 |
+
|
| 73 |
+
0. Definitions.
|
| 74 |
+
|
| 75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
| 76 |
+
|
| 77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
| 78 |
+
works, such as semiconductor masks.
|
| 79 |
+
|
| 80 |
+
"The Program" refers to any copyrightable work licensed under this
|
| 81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
| 82 |
+
"recipients" may be individuals or organizations.
|
| 83 |
+
|
| 84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
| 85 |
+
in a fashion requiring copyright permission, other than the making of an
|
| 86 |
+
exact copy. The resulting work is called a "modified version" of the
|
| 87 |
+
earlier work or a work "based on" the earlier work.
|
| 88 |
+
|
| 89 |
+
A "covered work" means either the unmodified Program or a work based
|
| 90 |
+
on the Program.
|
| 91 |
+
|
| 92 |
+
To "propagate" a work means to do anything with it that, without
|
| 93 |
+
permission, would make you directly or secondarily liable for
|
| 94 |
+
infringement under applicable copyright law, except executing it on a
|
| 95 |
+
computer or modifying a private copy. Propagation includes copying,
|
| 96 |
+
distribution (with or without modification), making available to the
|
| 97 |
+
public, and in some countries other activities as well.
|
| 98 |
+
|
| 99 |
+
To "convey" a work means any kind of propagation that enables other
|
| 100 |
+
parties to make or receive copies. Mere interaction with a user through
|
| 101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
| 102 |
+
|
| 103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
| 104 |
+
to the extent that it includes a convenient and prominently visible
|
| 105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
| 106 |
+
tells the user that there is no warranty for the work (except to the
|
| 107 |
+
extent that warranties are provided), that licensees may convey the
|
| 108 |
+
work under this License, and how to view a copy of this License. If
|
| 109 |
+
the interface presents a list of user commands or options, such as a
|
| 110 |
+
menu, a prominent item in the list meets this criterion.
|
| 111 |
+
|
| 112 |
+
1. Source Code.
|
| 113 |
+
|
| 114 |
+
The "source code" for a work means the preferred form of the work
|
| 115 |
+
for making modifications to it. "Object code" means any non-source
|
| 116 |
+
form of a work.
|
| 117 |
+
|
| 118 |
+
A "Standard Interface" means an interface that either is an official
|
| 119 |
+
standard defined by a recognized standards body, or, in the case of
|
| 120 |
+
interfaces specified for a particular programming language, one that
|
| 121 |
+
is widely used among developers working in that language.
|
| 122 |
+
|
| 123 |
+
The "System Libraries" of an executable work include anything, other
|
| 124 |
+
than the work as a whole, that (a) is included in the normal form of
|
| 125 |
+
packaging a Major Component, but which is not part of that Major
|
| 126 |
+
Component, and (b) serves only to enable use of the work with that
|
| 127 |
+
Major Component, or to implement a Standard Interface for which an
|
| 128 |
+
implementation is available to the public in source code form. A
|
| 129 |
+
"Major Component", in this context, means a major essential component
|
| 130 |
+
(kernel, window system, and so on) of the specific operating system
|
| 131 |
+
(if any) on which the executable work runs, or a compiler used to
|
| 132 |
+
produce the work, or an object code interpreter used to run it.
|
| 133 |
+
|
| 134 |
+
The "Corresponding Source" for a work in object code form means all
|
| 135 |
+
the source code needed to generate, install, and (for an executable
|
| 136 |
+
work) run the object code and to modify the work, including scripts to
|
| 137 |
+
control those activities. However, it does not include the work's
|
| 138 |
+
System Libraries, or general-purpose tools or generally available free
|
| 139 |
+
programs which are used unmodified in performing those activities but
|
| 140 |
+
which are not part of the work. For example, Corresponding Source
|
| 141 |
+
includes interface definition files associated with source files for
|
| 142 |
+
the work, and the source code for shared libraries and dynamically
|
| 143 |
+
linked subprograms that the work is specifically designed to require,
|
| 144 |
+
such as by intimate data communication or control flow between those
|
| 145 |
+
subprograms and other parts of the work.
|
| 146 |
+
|
| 147 |
+
The Corresponding Source need not include anything that users
|
| 148 |
+
can regenerate automatically from other parts of the Corresponding
|
| 149 |
+
Source.
|
| 150 |
+
|
| 151 |
+
The Corresponding Source for a work in source code form is that
|
| 152 |
+
same work.
|
| 153 |
+
|
| 154 |
+
2. Basic Permissions.
|
| 155 |
+
|
| 156 |
+
All rights granted under this License are granted for the term of
|
| 157 |
+
copyright on the Program, and are irrevocable provided the stated
|
| 158 |
+
conditions are met. This License explicitly affirms your unlimited
|
| 159 |
+
permission to run the unmodified Program. The output from running a
|
| 160 |
+
covered work is covered by this License only if the output, given its
|
| 161 |
+
content, constitutes a covered work. This License acknowledges your
|
| 162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
| 163 |
+
|
| 164 |
+
You may make, run and propagate covered works that you do not
|
| 165 |
+
convey, without conditions so long as your license otherwise remains
|
| 166 |
+
in force. You may convey covered works to others for the sole purpose
|
| 167 |
+
of having them make modifications exclusively for you, or provide you
|
| 168 |
+
with facilities for running those works, provided that you comply with
|
| 169 |
+
the terms of this License in conveying all material for which you do
|
| 170 |
+
not control copyright. Those thus making or running the covered works
|
| 171 |
+
for you must do so exclusively on your behalf, under your direction
|
| 172 |
+
and control, on terms that prohibit them from making any copies of
|
| 173 |
+
your copyrighted material outside their relationship with you.
|
| 174 |
+
|
| 175 |
+
Conveying under any other circumstances is permitted solely under
|
| 176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
| 177 |
+
makes it unnecessary.
|
| 178 |
+
|
| 179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
| 180 |
+
|
| 181 |
+
No covered work shall be deemed part of an effective technological
|
| 182 |
+
measure under any applicable law fulfilling obligations under article
|
| 183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
| 184 |
+
similar laws prohibiting or restricting circumvention of such
|
| 185 |
+
measures.
|
| 186 |
+
|
| 187 |
+
When you convey a covered work, you waive any legal power to forbid
|
| 188 |
+
circumvention of technological measures to the extent such circumvention
|
| 189 |
+
is effected by exercising rights under this License with respect to
|
| 190 |
+
the covered work, and you disclaim any intention to limit operation or
|
| 191 |
+
modification of the work as a means of enforcing, against the work's
|
| 192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
| 193 |
+
technological measures.
|
| 194 |
+
|
| 195 |
+
4. Conveying Verbatim Copies.
|
| 196 |
+
|
| 197 |
+
You may convey verbatim copies of the Program's source code as you
|
| 198 |
+
receive it, in any medium, provided that you conspicuously and
|
| 199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
| 200 |
+
keep intact all notices stating that this License and any
|
| 201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
| 202 |
+
keep intact all notices of the absence of any warranty; and give all
|
| 203 |
+
recipients a copy of this License along with the Program.
|
| 204 |
+
|
| 205 |
+
You may charge any price or no price for each copy that you convey,
|
| 206 |
+
and you may offer support or warranty protection for a fee.
|
| 207 |
+
|
| 208 |
+
5. Conveying Modified Source Versions.
|
| 209 |
+
|
| 210 |
+
You may convey a work based on the Program, or the modifications to
|
| 211 |
+
produce it from the Program, in the form of source code under the
|
| 212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
| 213 |
+
|
| 214 |
+
a) The work must carry prominent notices stating that you modified
|
| 215 |
+
it, and giving a relevant date.
|
| 216 |
+
|
| 217 |
+
b) The work must carry prominent notices stating that it is
|
| 218 |
+
released under this License and any conditions added under section
|
| 219 |
+
7. This requirement modifies the requirement in section 4 to
|
| 220 |
+
"keep intact all notices".
|
| 221 |
+
|
| 222 |
+
c) You must license the entire work, as a whole, under this
|
| 223 |
+
License to anyone who comes into possession of a copy. This
|
| 224 |
+
License will therefore apply, along with any applicable section 7
|
| 225 |
+
additional terms, to the whole of the work, and all its parts,
|
| 226 |
+
regardless of how they are packaged. This License gives no
|
| 227 |
+
permission to license the work in any other way, but it does not
|
| 228 |
+
invalidate such permission if you have separately received it.
|
| 229 |
+
|
| 230 |
+
d) If the work has interactive user interfaces, each must display
|
| 231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
| 232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
| 233 |
+
work need not make them do so.
|
| 234 |
+
|
| 235 |
+
A compilation of a covered work with other separate and independent
|
| 236 |
+
works, which are not by their nature extensions of the covered work,
|
| 237 |
+
and which are not combined with it such as to form a larger program,
|
| 238 |
+
in or on a volume of a storage or distribution medium, is called an
|
| 239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
| 240 |
+
used to limit the access or legal rights of the compilation's users
|
| 241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
| 242 |
+
in an aggregate does not cause this License to apply to the other
|
| 243 |
+
parts of the aggregate.
|
| 244 |
+
|
| 245 |
+
6. Conveying Non-Source Forms.
|
| 246 |
+
|
| 247 |
+
You may convey a covered work in object code form under the terms
|
| 248 |
+
of sections 4 and 5, provided that you also convey the
|
| 249 |
+
machine-readable Corresponding Source under the terms of this License,
|
| 250 |
+
in one of these ways:
|
| 251 |
+
|
| 252 |
+
a) Convey the object code in, or embodied in, a physical product
|
| 253 |
+
(including a physical distribution medium), accompanied by the
|
| 254 |
+
Corresponding Source fixed on a durable physical medium
|
| 255 |
+
customarily used for software interchange.
|
| 256 |
+
|
| 257 |
+
b) Convey the object code in, or embodied in, a physical product
|
| 258 |
+
(including a physical distribution medium), accompanied by a
|
| 259 |
+
written offer, valid for at least three years and valid for as
|
| 260 |
+
long as you offer spare parts or customer support for that product
|
| 261 |
+
model, to give anyone who possesses the object code either (1) a
|
| 262 |
+
copy of the Corresponding Source for all the software in the
|
| 263 |
+
product that is covered by this License, on a durable physical
|
| 264 |
+
medium customarily used for software interchange, for a price no
|
| 265 |
+
more than your reasonable cost of physically performing this
|
| 266 |
+
conveying of source, or (2) access to copy the
|
| 267 |
+
Corresponding Source from a network server at no charge.
|
| 268 |
+
|
| 269 |
+
c) Convey individual copies of the object code with a copy of the
|
| 270 |
+
written offer to provide the Corresponding Source. This
|
| 271 |
+
alternative is allowed only occasionally and noncommercially, and
|
| 272 |
+
only if you received the object code with such an offer, in accord
|
| 273 |
+
with subsection 6b.
|
| 274 |
+
|
| 275 |
+
d) Convey the object code by offering access from a designated
|
| 276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
| 277 |
+
Corresponding Source in the same way through the same place at no
|
| 278 |
+
further charge. You need not require recipients to copy the
|
| 279 |
+
Corresponding Source along with the object code. If the place to
|
| 280 |
+
copy the object code is a network server, the Corresponding Source
|
| 281 |
+
may be on a different server (operated by you or a third party)
|
| 282 |
+
that supports equivalent copying facilities, provided you maintain
|
| 283 |
+
clear directions next to the object code saying where to find the
|
| 284 |
+
Corresponding Source. Regardless of what server hosts the
|
| 285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
| 286 |
+
available for as long as needed to satisfy these requirements.
|
| 287 |
+
|
| 288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
| 289 |
+
you inform other peers where the object code and Corresponding
|
| 290 |
+
Source of the work are being offered to the general public at no
|
| 291 |
+
charge under subsection 6d.
|
| 292 |
+
|
| 293 |
+
A separable portion of the object code, whose source code is excluded
|
| 294 |
+
from the Corresponding Source as a System Library, need not be
|
| 295 |
+
included in conveying the object code work.
|
| 296 |
+
|
| 297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
| 298 |
+
tangible personal property which is normally used for personal, family,
|
| 299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
| 300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
| 301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
| 302 |
+
product received by a particular user, "normally used" refers to a
|
| 303 |
+
typical or common use of that class of product, regardless of the status
|
| 304 |
+
of the particular user or of the way in which the particular user
|
| 305 |
+
actually uses, or expects or is expected to use, the product. A product
|
| 306 |
+
is a consumer product regardless of whether the product has substantial
|
| 307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
| 308 |
+
the only significant mode of use of the product.
|
| 309 |
+
|
| 310 |
+
"Installation Information" for a User Product means any methods,
|
| 311 |
+
procedures, authorization keys, or other information required to install
|
| 312 |
+
and execute modified versions of a covered work in that User Product from
|
| 313 |
+
a modified version of its Corresponding Source. The information must
|
| 314 |
+
suffice to ensure that the continued functioning of the modified object
|
| 315 |
+
code is in no case prevented or interfered with solely because
|
| 316 |
+
modification has been made.
|
| 317 |
+
|
| 318 |
+
If you convey an object code work under this section in, or with, or
|
| 319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
| 320 |
+
part of a transaction in which the right of possession and use of the
|
| 321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
| 322 |
+
fixed term (regardless of how the transaction is characterized), the
|
| 323 |
+
Corresponding Source conveyed under this section must be accompanied
|
| 324 |
+
by the Installation Information. But this requirement does not apply
|
| 325 |
+
if neither you nor any third party retains the ability to install
|
| 326 |
+
modified object code on the User Product (for example, the work has
|
| 327 |
+
been installed in ROM).
|
| 328 |
+
|
| 329 |
+
The requirement to provide Installation Information does not include a
|
| 330 |
+
requirement to continue to provide support service, warranty, or updates
|
| 331 |
+
for a work that has been modified or installed by the recipient, or for
|
| 332 |
+
the User Product in which it has been modified or installed. Access to a
|
| 333 |
+
network may be denied when the modification itself materially and
|
| 334 |
+
adversely affects the operation of the network or violates the rules and
|
| 335 |
+
protocols for communication across the network.
|
| 336 |
+
|
| 337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
| 338 |
+
in accord with this section must be in a format that is publicly
|
| 339 |
+
documented (and with an implementation available to the public in
|
| 340 |
+
source code form), and must require no special password or key for
|
| 341 |
+
unpacking, reading or copying.
|
| 342 |
+
|
| 343 |
+
7. Additional Terms.
|
| 344 |
+
|
| 345 |
+
"Additional permissions" are terms that supplement the terms of this
|
| 346 |
+
License by making exceptions from one or more of its conditions.
|
| 347 |
+
Additional permissions that are applicable to the entire Program shall
|
| 348 |
+
be treated as though they were included in this License, to the extent
|
| 349 |
+
that they are valid under applicable law. If additional permissions
|
| 350 |
+
apply only to part of the Program, that part may be used separately
|
| 351 |
+
under those permissions, but the entire Program remains governed by
|
| 352 |
+
this License without regard to the additional permissions.
|
| 353 |
+
|
| 354 |
+
When you convey a copy of a covered work, you may at your option
|
| 355 |
+
remove any additional permissions from that copy, or from any part of
|
| 356 |
+
it. (Additional permissions may be written to require their own
|
| 357 |
+
removal in certain cases when you modify the work.) You may place
|
| 358 |
+
additional permissions on material, added by you to a covered work,
|
| 359 |
+
for which you have or can give appropriate copyright permission.
|
| 360 |
+
|
| 361 |
+
Notwithstanding any other provision of this License, for material you
|
| 362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
| 363 |
+
that material) supplement the terms of this License with terms:
|
| 364 |
+
|
| 365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
| 366 |
+
terms of sections 15 and 16 of this License; or
|
| 367 |
+
|
| 368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
| 369 |
+
author attributions in that material or in the Appropriate Legal
|
| 370 |
+
Notices displayed by works containing it; or
|
| 371 |
+
|
| 372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
| 373 |
+
requiring that modified versions of such material be marked in
|
| 374 |
+
reasonable ways as different from the original version; or
|
| 375 |
+
|
| 376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
| 377 |
+
authors of the material; or
|
| 378 |
+
|
| 379 |
+
e) Declining to grant rights under trademark law for use of some
|
| 380 |
+
trade names, trademarks, or service marks; or
|
| 381 |
+
|
| 382 |
+
f) Requiring indemnification of licensors and authors of that
|
| 383 |
+
material by anyone who conveys the material (or modified versions of
|
| 384 |
+
it) with contractual assumptions of liability to the recipient, for
|
| 385 |
+
any liability that these contractual assumptions directly impose on
|
| 386 |
+
those licensors and authors.
|
| 387 |
+
|
| 388 |
+
All other non-permissive additional terms are considered "further
|
| 389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
| 390 |
+
received it, or any part of it, contains a notice stating that it is
|
| 391 |
+
governed by this License along with a term that is a further
|
| 392 |
+
restriction, you may remove that term. If a license document contains
|
| 393 |
+
a further restriction but permits relicensing or conveying under this
|
| 394 |
+
License, you may add to a covered work material governed by the terms
|
| 395 |
+
of that license document, provided that the further restriction does
|
| 396 |
+
not survive such relicensing or conveying.
|
| 397 |
+
|
| 398 |
+
If you add terms to a covered work in accord with this section, you
|
| 399 |
+
must place, in the relevant source files, a statement of the
|
| 400 |
+
additional terms that apply to those files, or a notice indicating
|
| 401 |
+
where to find the applicable terms.
|
| 402 |
+
|
| 403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
| 404 |
+
form of a separately written license, or stated as exceptions;
|
| 405 |
+
the above requirements apply either way.
|
| 406 |
+
|
| 407 |
+
8. Termination.
|
| 408 |
+
|
| 409 |
+
You may not propagate or modify a covered work except as expressly
|
| 410 |
+
provided under this License. Any attempt otherwise to propagate or
|
| 411 |
+
modify it is void, and will automatically terminate your rights under
|
| 412 |
+
this License (including any patent licenses granted under the third
|
| 413 |
+
paragraph of section 11).
|
| 414 |
+
|
| 415 |
+
However, if you cease all violation of this License, then your
|
| 416 |
+
license from a particular copyright holder is reinstated (a)
|
| 417 |
+
provisionally, unless and until the copyright holder explicitly and
|
| 418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
| 419 |
+
holder fails to notify you of the violation by some reasonable means
|
| 420 |
+
prior to 60 days after the cessation.
|
| 421 |
+
|
| 422 |
+
Moreover, your license from a particular copyright holder is
|
| 423 |
+
reinstated permanently if the copyright holder notifies you of the
|
| 424 |
+
violation by some reasonable means, this is the first time you have
|
| 425 |
+
received notice of violation of this License (for any work) from that
|
| 426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
| 427 |
+
your receipt of the notice.
|
| 428 |
+
|
| 429 |
+
Termination of your rights under this section does not terminate the
|
| 430 |
+
licenses of parties who have received copies or rights from you under
|
| 431 |
+
this License. If your rights have been terminated and not permanently
|
| 432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
| 433 |
+
material under section 10.
|
| 434 |
+
|
| 435 |
+
9. Acceptance Not Required for Having Copies.
|
| 436 |
+
|
| 437 |
+
You are not required to accept this License in order to receive or
|
| 438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
| 439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
| 440 |
+
to receive a copy likewise does not require acceptance. However,
|
| 441 |
+
nothing other than this License grants you permission to propagate or
|
| 442 |
+
modify any covered work. These actions infringe copyright if you do
|
| 443 |
+
not accept this License. Therefore, by modifying or propagating a
|
| 444 |
+
covered work, you indicate your acceptance of this License to do so.
|
| 445 |
+
|
| 446 |
+
10. Automatic Licensing of Downstream Recipients.
|
| 447 |
+
|
| 448 |
+
Each time you convey a covered work, the recipient automatically
|
| 449 |
+
receives a license from the original licensors, to run, modify and
|
| 450 |
+
propagate that work, subject to this License. You are not responsible
|
| 451 |
+
for enforcing compliance by third parties with this License.
|
| 452 |
+
|
| 453 |
+
An "entity transaction" is a transaction transferring control of an
|
| 454 |
+
organization, or substantially all assets of one, or subdividing an
|
| 455 |
+
organization, or merging organizations. If propagation of a covered
|
| 456 |
+
work results from an entity transaction, each party to that
|
| 457 |
+
transaction who receives a copy of the work also receives whatever
|
| 458 |
+
licenses to the work the party's predecessor in interest had or could
|
| 459 |
+
give under the previous paragraph, plus a right to possession of the
|
| 460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
| 461 |
+
the predecessor has it or can get it with reasonable efforts.
|
| 462 |
+
|
| 463 |
+
You may not impose any further restrictions on the exercise of the
|
| 464 |
+
rights granted or affirmed under this License. For example, you may
|
| 465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
| 466 |
+
rights granted under this License, and you may not initiate litigation
|
| 467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
| 468 |
+
any patent claim is infringed by making, using, selling, offering for
|
| 469 |
+
sale, or importing the Program or any portion of it.
|
| 470 |
+
|
| 471 |
+
11. Patents.
|
| 472 |
+
|
| 473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
| 474 |
+
License of the Program or a work on which the Program is based. The
|
| 475 |
+
work thus licensed is called the contributor's "contributor version".
|
| 476 |
+
|
| 477 |
+
A contributor's "essential patent claims" are all patent claims
|
| 478 |
+
owned or controlled by the contributor, whether already acquired or
|
| 479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
| 480 |
+
by this License, of making, using, or selling its contributor version,
|
| 481 |
+
but do not include claims that would be infringed only as a
|
| 482 |
+
consequence of further modification of the contributor version. For
|
| 483 |
+
purposes of this definition, "control" includes the right to grant
|
| 484 |
+
patent sublicenses in a manner consistent with the requirements of
|
| 485 |
+
this License.
|
| 486 |
+
|
| 487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
| 488 |
+
patent license under the contributor's essential patent claims, to
|
| 489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
| 490 |
+
propagate the contents of its contributor version.
|
| 491 |
+
|
| 492 |
+
In the following three paragraphs, a "patent license" is any express
|
| 493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
| 494 |
+
(such as an express permission to practice a patent or covenant not to
|
| 495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
| 496 |
+
party means to make such an agreement or commitment not to enforce a
|
| 497 |
+
patent against the party.
|
| 498 |
+
|
| 499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
| 500 |
+
and the Corresponding Source of the work is not available for anyone
|
| 501 |
+
to copy, free of charge and under the terms of this License, through a
|
| 502 |
+
publicly available network server or other readily accessible means,
|
| 503 |
+
then you must either (1) cause the Corresponding Source to be so
|
| 504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
| 505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
| 506 |
+
consistent with the requirements of this License, to extend the patent
|
| 507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
| 508 |
+
actual knowledge that, but for the patent license, your conveying the
|
| 509 |
+
covered work in a country, or your recipient's use of the covered work
|
| 510 |
+
in a country, would infringe one or more identifiable patents in that
|
| 511 |
+
country that you have reason to believe are valid.
|
| 512 |
+
|
| 513 |
+
If, pursuant to or in connection with a single transaction or
|
| 514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
| 515 |
+
covered work, and grant a patent license to some of the parties
|
| 516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
| 517 |
+
or convey a specific copy of the covered work, then the patent license
|
| 518 |
+
you grant is automatically extended to all recipients of the covered
|
| 519 |
+
work and works based on it.
|
| 520 |
+
|
| 521 |
+
A patent license is "discriminatory" if it does not include within
|
| 522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
| 523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
| 524 |
+
specifically granted under this License. You may not convey a covered
|
| 525 |
+
work if you are a party to an arrangement with a third party that is
|
| 526 |
+
in the business of distributing software, under which you make payment
|
| 527 |
+
to the third party based on the extent of your activity of conveying
|
| 528 |
+
the work, and under which the third party grants, to any of the
|
| 529 |
+
parties who would receive the covered work from you, a discriminatory
|
| 530 |
+
patent license (a) in connection with copies of the covered work
|
| 531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
| 532 |
+
for and in connection with specific products or compilations that
|
| 533 |
+
contain the covered work, unless you entered into that arrangement,
|
| 534 |
+
or that patent license was granted, prior to 28 March 2007.
|
| 535 |
+
|
| 536 |
+
Nothing in this License shall be construed as excluding or limiting
|
| 537 |
+
any implied license or other defenses to infringement that may
|
| 538 |
+
otherwise be available to you under applicable patent law.
|
| 539 |
+
|
| 540 |
+
12. No Surrender of Others' Freedom.
|
| 541 |
+
|
| 542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
| 543 |
+
otherwise) that contradict the conditions of this License, they do not
|
| 544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
| 545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
| 546 |
+
License and any other pertinent obligations, then as a consequence you may
|
| 547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
| 548 |
+
to collect a royalty for further conveying from those to whom you convey
|
| 549 |
+
the Program, the only way you could satisfy both those terms and this
|
| 550 |
+
License would be to refrain entirely from conveying the Program.
|
| 551 |
+
|
| 552 |
+
13. Use with the GNU Affero General Public License.
|
| 553 |
+
|
| 554 |
+
Notwithstanding any other provision of this License, you have
|
| 555 |
+
permission to link or combine any covered work with a work licensed
|
| 556 |
+
under version 3 of the GNU Affero General Public License into a single
|
| 557 |
+
combined work, and to convey the resulting work. The terms of this
|
| 558 |
+
License will continue to apply to the part which is the covered work,
|
| 559 |
+
but the special requirements of the GNU Affero General Public License,
|
| 560 |
+
section 13, concerning interaction through a network will apply to the
|
| 561 |
+
combination as such.
|
| 562 |
+
|
| 563 |
+
14. Revised Versions of this License.
|
| 564 |
+
|
| 565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
| 566 |
+
the GNU General Public License from time to time. Such new versions will
|
| 567 |
+
be similar in spirit to the present version, but may differ in detail to
|
| 568 |
+
address new problems or concerns.
|
| 569 |
+
|
| 570 |
+
Each version is given a distinguishing version number. If the
|
| 571 |
+
Program specifies that a certain numbered version of the GNU General
|
| 572 |
+
Public License "or any later version" applies to it, you have the
|
| 573 |
+
option of following the terms and conditions either of that numbered
|
| 574 |
+
version or of any later version published by the Free Software
|
| 575 |
+
Foundation. If the Program does not specify a version number of the
|
| 576 |
+
GNU General Public License, you may choose any version ever published
|
| 577 |
+
by the Free Software Foundation.
|
| 578 |
+
|
| 579 |
+
If the Program specifies that a proxy can decide which future
|
| 580 |
+
versions of the GNU General Public License can be used, that proxy's
|
| 581 |
+
public statement of acceptance of a version permanently authorizes you
|
| 582 |
+
to choose that version for the Program.
|
| 583 |
+
|
| 584 |
+
Later license versions may give you additional or different
|
| 585 |
+
permissions. However, no additional obligations are imposed on any
|
| 586 |
+
author or copyright holder as a result of your choosing to follow a
|
| 587 |
+
later version.
|
| 588 |
+
|
| 589 |
+
15. Disclaimer of Warranty.
|
| 590 |
+
|
| 591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
| 592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
| 593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
| 594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
| 595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
| 596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
| 597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
| 598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
| 599 |
+
|
| 600 |
+
16. Limitation of Liability.
|
| 601 |
+
|
| 602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
| 603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
| 604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
| 605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
| 606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
| 607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
| 608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
| 609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
| 610 |
+
SUCH DAMAGES.
|
| 611 |
+
|
| 612 |
+
17. Interpretation of Sections 15 and 16.
|
| 613 |
+
|
| 614 |
+
If the disclaimer of warranty and limitation of liability provided
|
| 615 |
+
above cannot be given local legal effect according to their terms,
|
| 616 |
+
reviewing courts shall apply local law that most closely approximates
|
| 617 |
+
an absolute waiver of all civil liability in connection with the
|
| 618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
| 619 |
+
copy of the Program in return for a fee.
|
| 620 |
+
|
| 621 |
+
END OF TERMS AND CONDITIONS
|
| 622 |
+
|
| 623 |
+
How to Apply These Terms to Your New Programs
|
| 624 |
+
|
| 625 |
+
If you develop a new program, and you want it to be of the greatest
|
| 626 |
+
possible use to the public, the best way to achieve this is to make it
|
| 627 |
+
free software which everyone can redistribute and change under these terms.
|
| 628 |
+
|
| 629 |
+
To do so, attach the following notices to the program. It is safest
|
| 630 |
+
to attach them to the start of each source file to most effectively
|
| 631 |
+
state the exclusion of warranty; and each file should have at least
|
| 632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
| 633 |
+
|
| 634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
| 635 |
+
Copyright (C) <year> <name of author>
|
| 636 |
+
|
| 637 |
+
This program is free software: you can redistribute it and/or modify
|
| 638 |
+
it under the terms of the GNU General Public License as published by
|
| 639 |
+
the Free Software Foundation, either version 3 of the License, or
|
| 640 |
+
(at your option) any later version.
|
| 641 |
+
|
| 642 |
+
This program is distributed in the hope that it will be useful,
|
| 643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 645 |
+
GNU General Public License for more details.
|
| 646 |
+
|
| 647 |
+
You should have received a copy of the GNU General Public License
|
| 648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 649 |
+
|
| 650 |
+
Also add information on how to contact you by electronic and paper mail.
|
| 651 |
+
|
| 652 |
+
If the program does terminal interaction, make it output a short
|
| 653 |
+
notice like this when it starts in an interactive mode:
|
| 654 |
+
|
| 655 |
+
<program> Copyright (C) <year> <name of author>
|
| 656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
| 657 |
+
This is free software, and you are welcome to redistribute it
|
| 658 |
+
under certain conditions; type `show c' for details.
|
| 659 |
+
|
| 660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
| 661 |
+
parts of the General Public License. Of course, your program's commands
|
| 662 |
+
might be different; for a GUI interface, you would use an "about box".
|
| 663 |
+
|
| 664 |
+
You should also get your employer (if you work as a programmer) or school,
|
| 665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
| 666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
| 667 |
+
<https://www.gnu.org/licenses/>.
|
| 668 |
+
|
| 669 |
+
The GNU General Public License does not permit incorporating your program
|
| 670 |
+
into proprietary programs. If your program is a subroutine library, you
|
| 671 |
+
may consider it more useful to permit linking proprietary applications with
|
| 672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
| 673 |
+
Public License instead of this License. But first, please read
|
| 674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
README.md
CHANGED
|
@@ -1,3 +1,93 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SegFormer++
|
| 2 |
+
|
| 3 |
+
Paper: [Segformer++: Efficient Token-Merging Strategies for High-Resolution Semantic Segmentation](https://arxiv.org/abs/2405.14467)
|
| 4 |
+
|
| 5 |
+

|
| 6 |
+
|
| 7 |
+

|
| 8 |
+
|
| 9 |
+
## Abstract
|
| 10 |
+
|
| 11 |
+
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.
|
| 12 |
+
|
| 13 |
+
**Update:** It is now possible to load the model via torch.hub. See [here](docs/setup/torchhub_setup.md).
|
| 14 |
+
|
| 15 |
+
**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.
|
| 16 |
+
|
| 17 |
+
## Results and Models
|
| 18 |
+
|
| 19 |
+
Memory refers to the VRAM requirements during the training process.
|
| 20 |
+
|
| 21 |
+
### Inference on Cityscapes (MiT-B5)
|
| 22 |
+
|
| 23 |
+
The weights of the Segformer (Original) model were used to get the inference results.
|
| 24 |
+
|
| 25 |
+
| Method | mIoU | Speed-Up | config | download |
|
| 26 |
+
|-----------------------------------|------:|---------:|--------------------------------------------------------------------------------------------|----------------------------------------------------------------|
|
| 27 |
+
| Segformer (Original) | 82.39 | - | [config](mmsegmentation/local_configs/cityscapes/B5/segformer-cityscapes-b5-default.py) | [model](https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/) |
|
| 28 |
+
| Segformer++<sub>HQ</sub> (ours) | 82.31 | 1.61 | [config](mmsegmentation/local_configs/cityscapes/B5/segformer-cityscapes-b5-bsm-hq.py) | [model](https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/) |
|
| 29 |
+
| Segformer++<sub>fast</sub> (ours) | 82.04 | 1.94 | [config](mmsegmentation/local_configs/cityscapes/B5/segformer-cityscapes-b5-bsm-fast.py) | [model](https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/) |
|
| 30 |
+
| Segformer++<sub>2x2</sub> (ours) | 81.96 | 1.90 | [config](mmsegmentation/local_configs/cityscapes/B5/segformer-cityscapes-b5-n2d-2x2.py) | [model](https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/) |
|
| 31 |
+
| Segformer (Downsampling) | 77.31 | 6.51 | [config](mmsegmentation/local_configs/cityscapes/B5/segformer-cityscapes-b5-downsample.py) | [model](https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/) |
|
| 32 |
+
|
| 33 |
+
### Training on Cityscapes (MiT-B5)
|
| 34 |
+
|
| 35 |
+
| Method | mIoU | Speed-Up | Memory (GB) | config | download |
|
| 36 |
+
|-----------------------------------|------:|---------:|-------------|--------------------------------------------------------------------------------------------|-----------------------------------------------------------------|
|
| 37 |
+
| Segformer (Original) | 82.39 | - | 48.3 | [config](mmsegmentation/local_configs/cityscapes/B5/segformer-cityscapes-b5-default.py) | [model](https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/) |
|
| 38 |
+
| Segformer++<sub>HQ</sub> (ours) | 82.19 | 1.40 | 34.0 | [config](mmsegmentation/local_configs/cityscapes/B5/segformer-cityscapes-b5-bsm-hq.py) | [model](https://mediastore.rz.uni-augsburg.de/get/i8fY8uXJrV/ ) |
|
| 39 |
+
| Segformer++<sub>fast</sub> (ours) | 81.77 | 1.55 | 30.5 | [config](mmsegmentation/local_configs/cityscapes/B5/segformer-cityscapes-b5-bsm-fast.py) | [model](https://mediastore.rz.uni-augsburg.de/get/cmG974iAxt/ ) |
|
| 40 |
+
| Segformer++<sub>2x2</sub> (ours) | 82.38 | 1.63 | 31.1 | [config](mmsegmentation/local_configs/cityscapes/B5/segformer-cityscapes-b5-n2d-2x2.py) | [model](https://mediastore.rz.uni-augsburg.de/get/p0uMKbw531/) |
|
| 41 |
+
| Segformer (Downsampling) | 79.24 | 2.95 | 10.0 | [config](mmsegmentation/local_configs/cityscapes/B5/segformer-cityscapes-b5-downsample.py) | [model](https://mediastore.rz.uni-augsburg.de/get/73zkKSO21t/) |
|
| 42 |
+
|
| 43 |
+
### Training on ADE20K (640x640) (MiT-B5)
|
| 44 |
+
|
| 45 |
+
| Method | mIoU | Speed-Up | Memory (GB) | config | download |
|
| 46 |
+
|-----------------------------------|------:|---------:|------------:|---------------------------------------------------------------------------------------|----------------------------------------------------------------|
|
| 47 |
+
| Segformer (Original) | 49.72 | - | 33.7 | [config](mmsegmentation/local_configs/ade20k/B5/segformer-ade20k640-b5-default.py) | [model](https://mediastore.rz.uni-augsburg.de/get/nKEjUHNAfK/) |
|
| 48 |
+
| Segformer++<sub>HQ</sub> (ours) | 49.77 | 1.15 | 29.2 | [config](mmsegmentation/local_configs/ade20k/B5/segformer-ade20k640-b5-bsm-hq.py) | [model](https://mediastore.rz.uni-augsburg.de/get/Odyie8usgj/) |
|
| 49 |
+
| Segformer++<sub>fast</sub> (ours) | 49.10 | 1.20 | 28.0 | [config](mmsegmentation/local_configs/ade20k/B5/segformer-ade20k640-b5-bsm-fast.py) | [model](https://mediastore.rz.uni-augsburg.de/get/K0IGkx4O2s/) |
|
| 50 |
+
| Segformer++<sub>2x2</sub> (ours) | 49.35 | 1.26 | 27.2 | [config](mmsegmentation/local_configs/ade20k/B5/segformer-ade20k640-b5-n2d-2x2.py) | [model](https://mediastore.rz.uni-augsburg.de/get/w5_Pxx4Q5C/) |
|
| 51 |
+
| Segformer (Downsampling) | 46.71 | 1.89 | 12.4 | [config](mmsegmentation/local_configs/ade20k/B5/segformer-ade20k640-b5-downsample.py) | [model](https://mediastore.rz.uni-augsburg.de/get/dFVvZQL6iL/) |
|
| 52 |
+
|
| 53 |
+
### Training on JBD
|
| 54 |
+
|
| 55 |
+
| Method | PCK@0.1 | PCK@0.05 | Speed-Up | Memory (GB) | config | download |
|
| 56 |
+
|-----------------------------------|--------:|---------:|---------:|------------:|---------------------------------------------------------------------|----------------------------------------------------------------|
|
| 57 |
+
| Segformer (Original) | 95.20 | 90.65 | - | 40.0 | [config](mmpose/local_configs/jbd/B5/segformer-jump-b5-default.py) | [model](https://mediastore.rz.uni-augsburg.de/get/psolrWXLLp/) |
|
| 58 |
+
| Segformer++<sub>HQ</sub> (ours) | 95.18 | 90.51 | 1.19 | 36.0 | [config](mmpose/local_configs/jbd/B5/segformer-jump-b5-bsm-hq.py) | [model](https://mediastore.rz.uni-augsburg.de/get/jx1eyecMLF/) |
|
| 59 |
+
| Segformer++<sub>fast</sub> (ours) | 94.58 | 89.87 | 1.25 | 34.6 | [config](mmpose/local_configs/jbd/B5/segformer-jump-b5-bsm-fast.py) | [model](https://mediastore.rz.uni-augsburg.de/get/K0IGkx4O2s/) |
|
| 60 |
+
| Segformer++<sub>2x2</sub> (ours) | 95.17 | 90.16 | 1.27 | 33.4 | [config](mmpose/local_configs/jbd/B5/segformer-jump-b5-n2d-2x2.py) | [model](https://mediastore.rz.uni-augsburg.de/get/HumKbSB1vI/) |
|
| 61 |
+
|
| 62 |
+
### Training on MS COCO
|
| 63 |
+
|
| 64 |
+
| Method | PCK@0.1 | PCK@0.05 | Speed-Up | Memory (GB) | config | download |
|
| 65 |
+
|-----------------------------------|--------:|---------:|---------:|------------:|----------------------------------------------------------------------|----------------------------------------------------------------|
|
| 66 |
+
| Segformer (Original) | 95.16 | 87.61 | - | 13.5 | [config](mmpose/local_configs/coco/B5/segformer-coco-b5-default.py) | [model](https://mediastore.rz.uni-augsburg.de/get/ZOgj2NmQLy/) |
|
| 67 |
+
| Segformer++<sub>HQ</sub> (ours) | 94.97 | 87.35 | 0.97 | 13.1 | [config](mmpose/local_configs/coco/B5/segformer-coco-b5-bsm-hq.py) | [model](https://mediastore.rz.uni-augsburg.de/get/oAH5IlPxG8/) |
|
| 68 |
+
| Segformer++<sub>fast</sub> (ours) | 95.02 | 87.37 | 0.99 | 12.9 | [config](mmpose/local_configs/coco/B5/segformer-coco-b5-bsm-fast.py) | [model](https://mediastore.rz.uni-augsburg.de/get/3E2mMNLAAn/) |
|
| 69 |
+
| Segformer++<sub>2x2</sub> (ours) | 94.98 | 87.36 | 1.24 | 12.3 | [config](mmpose/local_configs/coco/B5/segformer-coco-b5-n2d-2x2.py) | [model](https://mediastore.rz.uni-augsburg.de/get/rzlgKC5XLc/) |
|
| 70 |
+
|
| 71 |
+
## Usage
|
| 72 |
+
|
| 73 |
+
Easy usage:
|
| 74 |
+
- [Use the SegFormer++ via TorchHub](docs/setup/torchhub_setup.md)
|
| 75 |
+
- [Use the SegFormer++ without OpenMMLab](docs/setup/noopenmmlab_setup.md)
|
| 76 |
+
|
| 77 |
+
Legacy Variants. To use our models for semantic segmentation or 2D human pose estimation, please follow the installation instructions for MMSegmentation and MMPose respectively, which can be found in the documentation of the respective repositories.
|
| 78 |
+
- [Use the SegFormer++ with MMSegmentation](docs/setup/mmseg_setup.md)
|
| 79 |
+
- [Use the SegFormer++ with MMPose](docs/setup/mmpose_setup.md)
|
| 80 |
+
- [Use the SegFormer++ without MMSegmentation/MMPose](docs/setup/mmeng_setup.md)
|
| 81 |
+
|
| 82 |
+
Explanation of the different token merging strategies:
|
| 83 |
+
- [Token Merging Settings](docs/run/token_merging.md)
|
| 84 |
+
|
| 85 |
+
## Citation
|
| 86 |
+
```bibtex
|
| 87 |
+
@article{kienzle2024segformer++,
|
| 88 |
+
title={Segformer++: Efficient Token-Merging Strategies for High-Resolution Semantic Segmentation},
|
| 89 |
+
author={Kienzle, Daniel and Kantonis, Marco and Sch{\"o}n, Robin and Lienhart, Rainer},
|
| 90 |
+
journal={IEEE International Conference on Multimedia Information Processing and Retrieval (MIPR)},
|
| 91 |
+
year={2024}
|
| 92 |
+
}
|
| 93 |
+
```
|
docs/figures/pose.png
ADDED
|
Git LFS Details
|
docs/figures/segmentation.png
ADDED
|
Git LFS Details
|
docs/run/run_mmeng.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use the SegFormer++ outside MMSegmentation/MMPose
|
| 2 |
+
|
| 3 |
+
- Use [build_model.py](../../model/segformer/build_model.py) to build preset and custom SegFormer++ models
|
| 4 |
+
|
| 5 |
+
```python
|
| 6 |
+
model = create_model('b5', 'bsm_hq', pretrained=True)
|
| 7 |
+
```
|
| 8 |
+
Running this code snippet yields our SegFormer++<sub>HQ</sub> model pretrained on ImageNet.
|
| 9 |
+
|
| 10 |
+
- Use [random_benchmark.py](../../model/segformer/random_benchmark.py) to evaluate a model in terms of FPS
|
| 11 |
+
|
| 12 |
+
```python
|
| 13 |
+
v = random_benchmark(model)
|
| 14 |
+
```
|
| 15 |
+
Calculate the FPS using our script.
|
docs/run/run_mmpose.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Run Experiments (MMPose)
|
| 2 |
+
|
| 3 |
+
The configuration files for our models can be found here:
|
| 4 |
+
|
| 5 |
+
- [Custom configuration files](../../mmpose/local_configs)
|
| 6 |
+
|
| 7 |
+
## Training
|
| 8 |
+
|
| 9 |
+
```shell
|
| 10 |
+
python tools/train.py 'path/to/config'
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
## Evaluation
|
| 14 |
+
|
| 15 |
+
```shell
|
| 16 |
+
python tools/test.py 'path/to/config' 'path/to/checkpoint'
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
## FPS
|
| 20 |
+
|
| 21 |
+
```shell
|
| 22 |
+
python tools/analysis_tools/random_benchmark.py -c 'path/to/config' -i 3x480x640 -b 16
|
| 23 |
+
```
|
docs/run/run_mmseg.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Run Experiments (MMSegmentation)
|
| 2 |
+
|
| 3 |
+
The configuration files for our models can be found here:
|
| 4 |
+
|
| 5 |
+
- [Custom configuration files](../../mmsegmentation/local_configs)
|
| 6 |
+
|
| 7 |
+
## Training
|
| 8 |
+
|
| 9 |
+
```shell
|
| 10 |
+
python tools/train.py 'path/to/config'
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
## Evaluation
|
| 14 |
+
|
| 15 |
+
```shell
|
| 16 |
+
python tools/test.py 'path/to/config' 'path/to/checkpoint'
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
## FPS
|
| 20 |
+
|
| 21 |
+
```shell
|
| 22 |
+
python tools/analysis_tools/random_benchmark.py -c 'path/to/config' -i 3x1024x1024 -b 8
|
| 23 |
+
```
|
docs/run/run_noopenmmlab.md
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use the SegFormer++ without OpenMMLab:
|
| 2 |
+
|
| 3 |
+
## Building a Model
|
| 4 |
+
|
| 5 |
+
- Use [build_model.py](../../model_without_OpenMMLab/segformer_plusplus/build_model.py) to build preset and custom SegFormer++ models
|
| 6 |
+
|
| 7 |
+
Navigate to model_without_OpenMMLab.
|
| 8 |
+
```python
|
| 9 |
+
from segformer_plusplus.build_model import create_model
|
| 10 |
+
# backbone: choose from ['b0', 'b1', 'b2', 'b3', 'b4', 'b5']
|
| 11 |
+
# tome_strategy: choose from ['bsm_hq', 'bsm_fast', 'n2d_2x2']
|
| 12 |
+
out_channels = 19 # number of classes, e.g. 19 for cityscapes
|
| 13 |
+
model = create_model('b5', 'bsm_hq', out_channels=out_channels, pretrained=True)
|
| 14 |
+
```
|
| 15 |
+
Running this code snippet yields our SegFormer++<sub>HQ</sub> model pretrained on ImageNet.
|
| 16 |
+
|
| 17 |
+
- Use [random_benchmark.py](../../model_without_OpenMMLab/segformer_plusplus/random_benchmark.py) to evaluate a model in terms of FPS
|
| 18 |
+
|
| 19 |
+
```python
|
| 20 |
+
from segformer_plusplus.random_benchmark import random_benchmark
|
| 21 |
+
v = random_benchmark(model)
|
| 22 |
+
```
|
| 23 |
+
Calculate the FPS using our script.
|
| 24 |
+
|
| 25 |
+
## Loading a Checkpoint
|
| 26 |
+
|
| 27 |
+
[Checkpoints](../../README.md) are provided in this Repository.
|
| 28 |
+
They can be loaded and integrated into the model via PyTorch:
|
| 29 |
+
```python
|
| 30 |
+
import torch
|
| 31 |
+
checkpoint_path = "path_to_your_checkpoint.pth that you downloaded (links in Readme)"
|
| 32 |
+
checkpoint = torch.load(checkpoint_path)
|
| 33 |
+
model.load_state_dict(checkpoint)
|
| 34 |
+
```
|
| 35 |
+
An Example can be found in [start_cityscape_benchmark.py](../../model_without_OpenMMLab/segformer_plusplus/start_cityscape_benchmark.py)
|
| 36 |
+
|
| 37 |
+
## Image Preperation
|
| 38 |
+
|
| 39 |
+
Images can be imported via PIL and then converted into RGB:
|
| 40 |
+
|
| 41 |
+
```python
|
| 42 |
+
from PIL import Image
|
| 43 |
+
image_path = "path_to_your_image.png"
|
| 44 |
+
image = Image.open(image_path).convert("RGB")
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
After that, convert the image into a torch tensor:
|
| 48 |
+
|
| 49 |
+
```python
|
| 50 |
+
import torch
|
| 51 |
+
import numpy as np
|
| 52 |
+
|
| 53 |
+
img_tensor = torch.from_numpy(np.array(image) / 255.0)
|
| 54 |
+
img_tensor = img_tensor.permute(2, 0, 1).float().unsqueeze(0) # (1, C, H, W)
|
| 55 |
+
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
| 56 |
+
img_tensor = img_tensor.to(device)
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
Now we can load the model:
|
| 60 |
+
|
| 61 |
+
```python
|
| 62 |
+
from segformer_plusplus.build_model import create_model
|
| 63 |
+
|
| 64 |
+
out_channels = 19
|
| 65 |
+
model = create_model(
|
| 66 |
+
backbone='b5',
|
| 67 |
+
tome_strategy='bsm_hq',
|
| 68 |
+
out_channels=out_channels,
|
| 69 |
+
pretrained=False
|
| 70 |
+
).to(device)
|
| 71 |
+
|
| 72 |
+
model.load_state_dict(torch.load("path_to_checkpoint", map_location=device))
|
| 73 |
+
model.eval()
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
Inference:
|
| 77 |
+
```python
|
| 78 |
+
with torch.no_grad():
|
| 79 |
+
output = model(img_tensor)
|
| 80 |
+
segmentation_map = torch.argmax(output, dim=1).squeeze().cpu().numpy()
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
Visualize the results (this is for cityscapes classes):
|
| 84 |
+
|
| 85 |
+
```python
|
| 86 |
+
import numpy as np
|
| 87 |
+
|
| 88 |
+
# Official Cityscapes colors for train IDs 0-18
|
| 89 |
+
cityscapes_colors = np.array([
|
| 90 |
+
[128, 64, 128], # 0: road
|
| 91 |
+
[244, 35, 232], # 1: sidewalk
|
| 92 |
+
[ 70, 70, 70], # 2: building
|
| 93 |
+
[102, 102, 156], # 3: wall
|
| 94 |
+
[190, 153, 153], # 4: fence
|
| 95 |
+
[153, 153, 153], # 5: pole
|
| 96 |
+
[250, 170, 30], # 6: traffic light
|
| 97 |
+
[220, 220, 0], # 7: traffic sign
|
| 98 |
+
[107, 142, 35], # 8: vegetation
|
| 99 |
+
[152, 251, 152], # 9: terrain
|
| 100 |
+
[ 70, 130, 180], # 10: sky
|
| 101 |
+
[220, 20, 60], # 11: person
|
| 102 |
+
[255, 0, 0], # 12: rider
|
| 103 |
+
[ 0, 0, 142], # 13: car
|
| 104 |
+
[ 0, 0, 70], # 14: truck
|
| 105 |
+
[ 0, 60, 100], # 15: bus
|
| 106 |
+
[ 0, 80, 100], # 16: train
|
| 107 |
+
[ 0, 0, 230], # 17: motorcycle
|
| 108 |
+
[119, 11, 32], # 18: bicycle
|
| 109 |
+
], dtype=np.uint8)
|
| 110 |
+
|
| 111 |
+
# Map each class to its corresponding color
|
| 112 |
+
height, width = segmentation_map.shape
|
| 113 |
+
color_image = np.zeros((height, width, 3), dtype=np.uint8)
|
| 114 |
+
for class_index in range(len(cityscapes_colors)):
|
| 115 |
+
color_image[segmentation_map == class_index] = cityscapes_colors[class_index]
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
Display and save output:
|
| 119 |
+
```python
|
| 120 |
+
import matplotlib.pyplot as plt
|
| 121 |
+
|
| 122 |
+
plt.figure(figsize=(6, 6))
|
| 123 |
+
plt.imshow(color_image)
|
| 124 |
+
plt.title("Semantic Segmentation Visualization")
|
| 125 |
+
plt.axis('off')
|
| 126 |
+
plt.show()
|
| 127 |
+
# Save the colorized output as an image - important when using a System without GUI
|
| 128 |
+
plt.imsave("segmentation_output.png", color_image)
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
> Note: You have to install matplotlib for visualization.
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
## Token-Merge Setting
|
| 135 |
+
|
| 136 |
+
For information to the settings for the Token Merging look [here](../../docs/run/token_merging.md).
|
| 137 |
+
|
docs/run/token_merging.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Specify Algorithms and Parameters for Token Merging
|
| 2 |
+
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
**Example**
|
| 6 |
+
Bipartite Soft Matching high quality preset:
|
| 7 |
+
|
| 8 |
+
```python
|
| 9 |
+
model = dict(
|
| 10 |
+
backbone=dict(
|
| 11 |
+
tome_cfg=[
|
| 12 |
+
dict(kv_mode='bsm', kv_r=0.6, kv_sx=2, kv_sy=2), # Stage 1
|
| 13 |
+
dict(kv_mode='bsm', kv_r=0.6, kv_sx=2, kv_sy=2), # Stage 2
|
| 14 |
+
dict(q_mode='bsm', q_r=0.8, q_sx=4, q_sy=4), # Stage 3
|
| 15 |
+
dict(q_mode='bsm', q_r=0.8, q_sx=4, q_sy=4) # Stage 4
|
| 16 |
+
]
|
| 17 |
+
)
|
| 18 |
+
)
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Both a *q_mode* and a *kv_mode* can be specified for each stage.
|
| 22 |
+
|
| 23 |
+
The following modes are available:
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
#### Bipartite Soft Matching (SegFormer++<sub>HQ</sub> and SegFormer++<sub>fast</sub>)
|
| 27 |
+
```python
|
| 28 |
+
dict(q_mode='bsm', q_scale_factor=0.8, q_sx=2, q_sy=2)
|
| 29 |
+
```
|
| 30 |
+
This works in the same way as *bsm*. However, additionally *q_sx* and *q_sy* have to be specified that are the strides
|
| 31 |
+
used to select the tokens in the destination set.
|
| 32 |
+
|
| 33 |
+
#### 1D Neighbour Merging
|
| 34 |
+
```python
|
| 35 |
+
dict(q_mode='n1d', q_s=2)
|
| 36 |
+
```
|
| 37 |
+
The stride/kernel size employed for the average pooling has to be specified using the *q_scale_factor*.
|
| 38 |
+
|
| 39 |
+
#### 2D Neighbour Merging
|
| 40 |
+
```python
|
| 41 |
+
dict(q_mode='n2d', q_s=(2, 2))
|
| 42 |
+
```
|
| 43 |
+
Here, two strides for both directions have to be specified.
|
| 44 |
+
|
| 45 |
+
If token merging is applied for keys and values exclusively, the *q_mode* has to be set to *None* and the parameters
|
| 46 |
+
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.
|
| 47 |
+
Therefore, parameters for both sequences have to be specified:
|
| 48 |
+
```python
|
| 49 |
+
dict(q_mode='n2d', kv_mode='bsm', q_s=(2, 2), kv_r=0.6, kv_sx=2, kv_sy=2)
|
| 50 |
+
```
|
docs/setup/mmeng_setup.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Install the SegFormer++ without MMSegmentation/MMPose
|
| 2 |
+
|
| 3 |
+
**Step 0.** Prerequisites
|
| 4 |
+
|
| 5 |
+
- Pytorch: 2.3 (CUDA 12.1) (older versions should also work fine)
|
| 6 |
+
|
| 7 |
+
**Step 1.** Install [MMCV](https://github.com/open-mmlab/mmcv) using [MIM](https://github.com/open-mmlab/mim).
|
| 8 |
+
|
| 9 |
+
```shell
|
| 10 |
+
pip install -U openmim
|
| 11 |
+
mim install mmengine
|
| 12 |
+
mim install "mmcv>=2.0.0"
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
**Step 2.** Install Segformer++
|
| 16 |
+
|
| 17 |
+
```shell
|
| 18 |
+
cd model
|
| 19 |
+
pip install .
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
**Step 3.** [Run the SegFormer++](../run/run_mmeng.md)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
**Troubleshooting**
|
| 27 |
+
There might be installation troubles with openmim, mmengine, and mmcv for new python versions. Thus, Step 1 might not work correctly.
|
| 28 |
+
In this case, try the following alternative for step 1:
|
| 29 |
+
```shell
|
| 30 |
+
pip install torch torchvision numpy
|
| 31 |
+
pip install mmcv-full==1.2.7
|
| 32 |
+
pip install mmcv
|
| 33 |
+
```
|
| 34 |
+
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.
|
docs/setup/mmpose_setup.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MMSegmentation Setup
|
| 2 |
+
|
| 3 |
+
**Step 0.** Prerequisites
|
| 4 |
+
|
| 5 |
+
- Pytorch: 2.0.1 (CUDA 11.8)
|
| 6 |
+
|
| 7 |
+
**Step 1.** Install [MMCV](https://github.com/open-mmlab/mmcv) using [MIM](https://github.com/open-mmlab/mim).
|
| 8 |
+
|
| 9 |
+
```shell
|
| 10 |
+
pip install -U openmim
|
| 11 |
+
mim install mmengine
|
| 12 |
+
mim install "mmcv==2.0.0"
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
**Step 2.** Install MMPose
|
| 16 |
+
|
| 17 |
+
```shell
|
| 18 |
+
# starting from the project root
|
| 19 |
+
cd mmpose
|
| 20 |
+
pip install -r requirements.txt
|
| 21 |
+
pip install -v -e .
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
**Step 3.** [Run the SegFormer++ using MMPose](../run/run_mmpose.md)
|
docs/setup/mmseg_setup.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MMSegmentation Setup
|
| 2 |
+
|
| 3 |
+
**Step 0.** Prerequisites
|
| 4 |
+
|
| 5 |
+
- Pytorch: 2.0.1 (CUDA 11.8)
|
| 6 |
+
|
| 7 |
+
**Step 1.** Install [MMCV](https://github.com/open-mmlab/mmcv) using [MIM](https://github.com/open-mmlab/mim).
|
| 8 |
+
|
| 9 |
+
```shell
|
| 10 |
+
pip install -U openmim
|
| 11 |
+
mim install mmengine
|
| 12 |
+
mim install "mmcv==2.0.0"
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
**Step 2.** Install MMSegmentation
|
| 16 |
+
|
| 17 |
+
```shell
|
| 18 |
+
# starting from the project root
|
| 19 |
+
cd mmsegmentation
|
| 20 |
+
pip install -v -e .
|
| 21 |
+
pip install -r requirements.txt
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
**Step 3.** [Run the SegFormer++ using MMSegmentation](../run/run_mmseg.md)
|
| 25 |
+
|
docs/setup/noopenmmlab_setup.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Install the SegFormer++ without OpenMMLab
|
| 2 |
+
|
| 3 |
+
**Step 0.** Prerequisites
|
| 4 |
+
|
| 5 |
+
- Pytorch: 2.3 (CUDA 12.1) (older versions should also work fine)
|
| 6 |
+
- Setup a virtual enviroment (optional, python -m venv "name of the environment")
|
| 7 |
+
|
| 8 |
+
**Step 1.** Install Segformer++
|
| 9 |
+
|
| 10 |
+
```shell
|
| 11 |
+
cd model_without_OpenMMLab
|
| 12 |
+
pip install .
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
**Step 2.** [Run the SegFormer++](../run/run_noopenmmlab.md)
|
docs/setup/torchhub_setup.md
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Using the SegFormer++ Model via PyTorch Hub
|
| 2 |
+
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
## Prerequisites
|
| 6 |
+
|
| 7 |
+
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:
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
pip install tomesd omegaconf numpy rich yapf addict tqdm packaging torchvision
|
| 11 |
+
```
|
| 12 |
+
## How It Works
|
| 13 |
+
|
| 14 |
+
The provided Python script demonstrates a full workflow, from loading the model and transformations to running inference on a dummy image.
|
| 15 |
+
|
| 16 |
+
## Step 1: Loading the Model
|
| 17 |
+
|
| 18 |
+
You can easily load the model from torchhub.
|
| 19 |
+
The parameters are:
|
| 20 |
+
- `pretrained`: If set to True, it loads the model with pre-trained ImageNet weights.
|
| 21 |
+
- `backbone`: Specifies the backbone architecture (e.g., 'b5' for MiT-B5). Other options include 'b0', 'b1', 'b2', 'b3', and 'b4'.
|
| 22 |
+
- `tome_strategy`: Defines the token merging strategy. Options include 'bsm_hq' (high quality), 'bsm_fast' (faster), and 'n2d_2x2' (non-overlapping 2x2).
|
| 23 |
+
- `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.
|
| 24 |
+
- `out_channels`: The number of output classes for segmentation (e.g., 19 for Cityscapes).
|
| 25 |
+
|
| 26 |
+
```python
|
| 27 |
+
import torch
|
| 28 |
+
model = torch.hub.load(
|
| 29 |
+
'KieDani/SegformerPlusPlus',
|
| 30 |
+
'segformer_plusplus',
|
| 31 |
+
pretrained=True,
|
| 32 |
+
backbone='b5',
|
| 33 |
+
tome_strategy='bsm_hq',
|
| 34 |
+
checkpoint_url='https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/', # URL to checkpoints, optional
|
| 35 |
+
out_channels=19,
|
| 36 |
+
)
|
| 37 |
+
model.eval() # Set the model to evaluation mode
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
## Step 2: Loading Data Transformations
|
| 41 |
+
|
| 42 |
+
The data_transforms entry point returns a torchvision.transforms.Compose object, which encapsulates the standard preprocessing steps required by the model (resizing and normalization).
|
| 43 |
+
|
| 44 |
+
```python
|
| 45 |
+
# Load the data transformations
|
| 46 |
+
transform = torch.hub.load(
|
| 47 |
+
'KieDani/SegformerPlusPlus',
|
| 48 |
+
'data_transforms',
|
| 49 |
+
)
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
## Step 3: Preparing the Image and Running Inference
|
| 53 |
+
|
| 54 |
+
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.
|
| 55 |
+
|
| 56 |
+
```python
|
| 57 |
+
from PIL import Image
|
| 58 |
+
|
| 59 |
+
# In a real-world scenario, you would load your image here:
|
| 60 |
+
# image = Image.open('path_to_your_image.jpg').convert('RGB')
|
| 61 |
+
dummy_image = Image.new('RGB', (1300, 1300), color='red')
|
| 62 |
+
|
| 63 |
+
# Apply the transformations
|
| 64 |
+
input_tensor = transform(dummy_image).unsqueeze(0) # Add a batch dimension
|
| 65 |
+
|
| 66 |
+
# Run inference
|
| 67 |
+
with torch.no_grad():
|
| 68 |
+
output = model(input_tensor)
|
| 69 |
+
|
| 70 |
+
# Process the output tensor to get the final segmentation map
|
| 71 |
+
segmentation_map = torch.argmax(output.squeeze(0), dim=0)
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
The final segmentation_map is a tensor where each pixel value represents the predicted class (from 0 to 18).
|
| 75 |
+
|
| 76 |
+
## Full Script
|
| 77 |
+
|
| 78 |
+
Below is the complete, runnable script for your reference.
|
| 79 |
+
|
| 80 |
+
```python
|
| 81 |
+
import torch.hub
|
| 82 |
+
from PIL import Image
|
| 83 |
+
|
| 84 |
+
# --- IMPORTANT: TorchHub Dependencies ---
|
| 85 |
+
# Install the dependencies via:
|
| 86 |
+
# pip install tomesd omegaconf numpy rich yapf addict tqdm packaging torchvision
|
| 87 |
+
|
| 88 |
+
# Load the SegFormer++ model with predefined parameters.
|
| 89 |
+
print("Loading SegFormer++ Model...")
|
| 90 |
+
# Replace 'your_username/your_repo' with the actual path to your repository
|
| 91 |
+
model = torch.hub.load(
|
| 92 |
+
'KieDani/SegformerPlusPlus', # This is a placeholder, replace it with your actual GitHub path
|
| 93 |
+
'segformer_plusplus',
|
| 94 |
+
pretrained=True,
|
| 95 |
+
backbone='b5',
|
| 96 |
+
tome_strategy='bsm_hq',
|
| 97 |
+
checkpoint_url='https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/',
|
| 98 |
+
out_channels=19,
|
| 99 |
+
)
|
| 100 |
+
model.eval()
|
| 101 |
+
print("Model loaded successfully.")
|
| 102 |
+
|
| 103 |
+
# Load the data transformations via the 'data_transforms' entry point.
|
| 104 |
+
print("Loading data transformations...")
|
| 105 |
+
transform = torch.hub.load(
|
| 106 |
+
'KieDani/SegformerPlusPlus', # Placeholder, replace it with your actual GitHub path
|
| 107 |
+
'data_transforms',
|
| 108 |
+
)
|
| 109 |
+
print("Transformations loaded successfully.")
|
| 110 |
+
|
| 111 |
+
# --- Example for Image Preparation and Inference ---
|
| 112 |
+
# Create a dummy image, as we don't need a real image file.
|
| 113 |
+
# In a real scenario, you would load an image from the hard drive, e.g.
|
| 114 |
+
# from PIL import Image
|
| 115 |
+
# image = Image.open('path_to_your_image.jpg').convert('RGB')
|
| 116 |
+
print("Creating a dummy image for demonstration...")
|
| 117 |
+
dummy_image = Image.new('RGB', (1300, 1300), color='red')
|
| 118 |
+
print("Original image size:", dummy_image.size)
|
| 119 |
+
|
| 120 |
+
# Apply the transformations loaded from the Hub to the image.
|
| 121 |
+
print("Applying transformations to the image...")
|
| 122 |
+
input_tensor = transform(dummy_image).unsqueeze(0) # Adds a batch dimension
|
| 123 |
+
print("Transformed image tensor size:", input_tensor.shape)
|
| 124 |
+
|
| 125 |
+
# Run inference.
|
| 126 |
+
print("Running inference...")
|
| 127 |
+
with torch.no_grad():
|
| 128 |
+
output = model(input_tensor)
|
| 129 |
+
|
| 130 |
+
# The output tensor has the shape [1, num_classes, height, width]
|
| 131 |
+
# We remove the batch dimension (1)
|
| 132 |
+
output_tensor = output.squeeze(0)
|
| 133 |
+
|
| 134 |
+
print(f"\nInference completed. Output tensor size: {output_tensor.shape}")
|
| 135 |
+
|
| 136 |
+
# To get the final segmentation map, you would use argmax.
|
| 137 |
+
segmentation_map = torch.argmax(output_tensor, dim=0)
|
| 138 |
+
print(f"Size of the generated segmentation map: {segmentation_map.shape}")
|
| 139 |
+
```
|
example_torchhub.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.hub
|
| 2 |
+
from PIL import Image
|
| 3 |
+
|
| 4 |
+
# --- IMPORTANT: TorchHub Dependencies ---
|
| 5 |
+
# Install the dependencies via:
|
| 6 |
+
# pip install tomesd omegaconf numpy rich yapf addict tqdm packaging torchvision
|
| 7 |
+
|
| 8 |
+
# Load the SegFormer++ model with predefined parameters.
|
| 9 |
+
print("Loading SegFormer++ Model...")
|
| 10 |
+
# Replace 'your_username/your_repo' with the actual path to your repository
|
| 11 |
+
model = torch.hub.load(
|
| 12 |
+
'KieDani/SegformerPlusPlus',
|
| 13 |
+
'segformer_plusplus',
|
| 14 |
+
pretrained=True,
|
| 15 |
+
backbone='b5',
|
| 16 |
+
tome_strategy='bsm_hq',
|
| 17 |
+
checkpoint_url='https://mediastore.rz.uni-augsburg.de/get/yzE65lzm6N/',
|
| 18 |
+
out_channels=19,
|
| 19 |
+
)
|
| 20 |
+
model.eval()
|
| 21 |
+
print("Model loaded successfully.")
|
| 22 |
+
|
| 23 |
+
# Load the data transformations via the 'data_transforms' entry point.
|
| 24 |
+
print("Loading data transformations...")
|
| 25 |
+
transform = torch.hub.load(
|
| 26 |
+
'KieDani/SegformerPlusPlus',
|
| 27 |
+
'data_transforms',
|
| 28 |
+
)
|
| 29 |
+
print("Transformations loaded successfully.")
|
| 30 |
+
|
| 31 |
+
# --- Example for Image Preparation and Inference ---
|
| 32 |
+
# Create a dummy image, as we don't need a real image file.
|
| 33 |
+
# In a real scenario, you would load an image from the hard drive, e.g.
|
| 34 |
+
# from PIL import Image
|
| 35 |
+
# image = Image.open('path_to_your_image.jpg').convert('RGB')
|
| 36 |
+
print("Creating a dummy image for demonstration...")
|
| 37 |
+
dummy_image = Image.new('RGB', (1300, 1300), color='red')
|
| 38 |
+
print("Original image size:", dummy_image.size)
|
| 39 |
+
|
| 40 |
+
# Apply the transformations loaded from the Hub to the image.
|
| 41 |
+
print("Applying transformations to the image...")
|
| 42 |
+
input_tensor = transform(dummy_image).unsqueeze(0) # Adds a batch dimension
|
| 43 |
+
print("Transformed image tensor size:", input_tensor.shape)
|
| 44 |
+
|
| 45 |
+
# Run inference.
|
| 46 |
+
print("Running inference...")
|
| 47 |
+
with torch.no_grad():
|
| 48 |
+
output = model(input_tensor)
|
| 49 |
+
|
| 50 |
+
# The output tensor has the shape [1, num_classes, height, width]
|
| 51 |
+
# We remove the batch dimension (1)
|
| 52 |
+
output_tensor = output.squeeze(0)
|
| 53 |
+
|
| 54 |
+
print(f"\nInference completed. Output tensor size: {output_tensor.shape}")
|
| 55 |
+
|
| 56 |
+
# To get the final segmentation map, you would use argmax.
|
| 57 |
+
segmentation_map = torch.argmax(output_tensor, dim=0)
|
| 58 |
+
print(f"Size of the generated segmentation map: {segmentation_map.shape}")
|
hubconf.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import os
|
| 3 |
+
import torch
|
| 4 |
+
import torchvision.transforms as T
|
| 5 |
+
from typing import List, Tuple
|
| 6 |
+
# Import the necessary functions for custom download
|
| 7 |
+
from torch.hub import download_url_to_file
|
| 8 |
+
import urllib.parse
|
| 9 |
+
|
| 10 |
+
# --- WICHTIG: TorchHub Dependencies ---
|
| 11 |
+
# These are informational only. Users must install these packages.
|
| 12 |
+
dependencies = [
|
| 13 |
+
'tomesd',
|
| 14 |
+
'omegaconf',
|
| 15 |
+
'numpy',
|
| 16 |
+
'rich',
|
| 17 |
+
'yapf',
|
| 18 |
+
'addict',
|
| 19 |
+
'tqdm',
|
| 20 |
+
'packaging',
|
| 21 |
+
'torchvision'
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
# Adds the path to the 'model_without_OpenMMLab' subdirectory to the sys.path list.
|
| 25 |
+
model_dir = os.path.join(os.path.dirname(__file__), 'model_without_OpenMMLab')
|
| 26 |
+
sys.path.insert(0, model_dir)
|
| 27 |
+
|
| 28 |
+
# Imports all entry points from the subdirectory.
|
| 29 |
+
from segformer_plusplus.build_model import create_model
|
| 30 |
+
from segformer_plusplus.random_benchmark import random_benchmark
|
| 31 |
+
|
| 32 |
+
# Removes the added path again to keep the sys.path list clean.
|
| 33 |
+
sys.path.pop(0)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _get_local_cache_path(url: str, filename: str) -> str:
|
| 37 |
+
"""
|
| 38 |
+
Creates the full local path to the checkpoint file in the PyTorch Hub cache.
|
| 39 |
+
"""
|
| 40 |
+
# Retrieves the root folder of the PyTorch Hub cache (~/.cache/torch/)
|
| 41 |
+
torch_home = torch.hub._get_torch_home()
|
| 42 |
+
|
| 43 |
+
# The default checkpoint directory
|
| 44 |
+
checkpoint_dir = os.path.join(torch_home, 'checkpoints')
|
| 45 |
+
os.makedirs(checkpoint_dir, exist_ok=True)
|
| 46 |
+
|
| 47 |
+
# Adds a hash component for the URL to ensure uniqueness,
|
| 48 |
+
# as the URL itself does not contain a unique file name.
|
| 49 |
+
# We use the URL path as part of the hash.
|
| 50 |
+
url_path_hash = urllib.parse.quote_plus(url)
|
| 51 |
+
|
| 52 |
+
# The final local file name, including the base name + URL hash.
|
| 53 |
+
local_filename = f"{filename}_{url_path_hash[:10]}.pt"
|
| 54 |
+
|
| 55 |
+
return os.path.join(checkpoint_dir, local_filename)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# --- ENTRYPOINT 1: Main Model (ADJUSTED) ---
|
| 59 |
+
def segformer_plusplus(
|
| 60 |
+
backbone: str = 'b5',
|
| 61 |
+
tome_strategy: str = 'bsm_hq',
|
| 62 |
+
out_channels: int = 19,
|
| 63 |
+
pretrained: bool = True,
|
| 64 |
+
checkpoint_url: str = None,
|
| 65 |
+
**kwargs
|
| 66 |
+
) -> torch.nn.Module:
|
| 67 |
+
"""
|
| 68 |
+
Segformer++: Efficient Token-Merging Strategies for High-Resolution Semantic Segmentation.
|
| 69 |
+
|
| 70 |
+
Loads a SegFormer++ model with the specified backbone and head architecture.
|
| 71 |
+
Install requirements via:
|
| 72 |
+
pip install tomesd omegaconf numpy rich yapf addict tqdm packaging torchvision
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
backbone (str): The backbone type. Selectable from: ['b0', 'b1', 'b2', 'b3', 'b4', 'b5'].
|
| 76 |
+
tome_strategy (str): The token merging strategy. Selectable from: ['bsm_hq', 'bsm_fast', 'n2d_2x2'].
|
| 77 |
+
out_channels (int): Number of output classes (e.g., 19 for Cityscapes).
|
| 78 |
+
pretrained (bool): Whether to load the ImageNet pre-trained weights.
|
| 79 |
+
checkpoint_url (str, optional): A URL to a specific checkpoint.
|
| 80 |
+
**Important:** The download uses torch.hub.download_url_to_file(),
|
| 81 |
+
which may be required for non-direct links.
|
| 82 |
+
|
| 83 |
+
Returns:
|
| 84 |
+
torch.nn.Module: The instantiated SegFormer++ model.
|
| 85 |
+
"""
|
| 86 |
+
model = create_model(
|
| 87 |
+
backbone=backbone,
|
| 88 |
+
tome_strategy=tome_strategy,
|
| 89 |
+
out_channels=out_channels,
|
| 90 |
+
pretrained=pretrained
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
if checkpoint_url:
|
| 94 |
+
# Generate a unique file path in the PyTorch cache
|
| 95 |
+
# We use the backbone name as part of the file name
|
| 96 |
+
local_filepath = _get_local_cache_path(
|
| 97 |
+
url=checkpoint_url,
|
| 98 |
+
filename=f"segformer_plusplus_{backbone}"
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
print(f"Attempting to load checkpoint from {checkpoint_url}...")
|
| 102 |
+
|
| 103 |
+
if not os.path.exists(local_filepath):
|
| 104 |
+
# Use download_url_to_file for the non-direct download
|
| 105 |
+
try:
|
| 106 |
+
print(f"File not in cache. Downloading to {local_filepath}...")
|
| 107 |
+
|
| 108 |
+
# This replaces load_state_dict_from_url and saves the file in the cache
|
| 109 |
+
download_url_to_file(
|
| 110 |
+
checkpoint_url,
|
| 111 |
+
local_filepath,
|
| 112 |
+
progress=True
|
| 113 |
+
)
|
| 114 |
+
print("Download successful.")
|
| 115 |
+
|
| 116 |
+
except Exception as e:
|
| 117 |
+
print(f"Error downloading checkpoint from {checkpoint_url}. Check the URL or use a direct asset link. Error: {e}")
|
| 118 |
+
# If the download fails, we return an un-loaded model
|
| 119 |
+
return model
|
| 120 |
+
|
| 121 |
+
# Load the state dictionary from the downloaded file
|
| 122 |
+
try:
|
| 123 |
+
state_dict = torch.load(local_filepath, map_location='cpu')
|
| 124 |
+
|
| 125 |
+
# Perform state_dict cleanup here if necessary,
|
| 126 |
+
# e.g., if the state is nested under a 'model' key
|
| 127 |
+
if 'state_dict' in state_dict:
|
| 128 |
+
state_dict = state_dict['state_dict']
|
| 129 |
+
|
| 130 |
+
model.load_state_dict(state_dict, strict=True)
|
| 131 |
+
print("Checkpoint loaded successfully.")
|
| 132 |
+
|
| 133 |
+
except Exception as e:
|
| 134 |
+
print(f"Error loading state dict from file {local_filepath}: {e}")
|
| 135 |
+
# Again, return the un-loaded/ImageNet pre-trained model
|
| 136 |
+
print("The model was instantiated, but the checkpoint could not be loaded.")
|
| 137 |
+
|
| 138 |
+
return model
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# --- ENTRYPOINT 2: Data Processing ---
|
| 142 |
+
def data_transforms(
|
| 143 |
+
resolution: Tuple[int, int] = (1024, 1024),
|
| 144 |
+
mean: List[float] = [0.485, 0.456, 0.406],
|
| 145 |
+
std: List[float] = [0.229, 0.224, 0.225],
|
| 146 |
+
) -> T.Compose:
|
| 147 |
+
"""
|
| 148 |
+
Provides the appropriate data transformations for a given dataset.
|
| 149 |
+
|
| 150 |
+
This function is an entry point to get the necessary preprocessing steps
|
| 151 |
+
for images based on typical ImageNet values.
|
| 152 |
+
|
| 153 |
+
Args:
|
| 154 |
+
resolution (Tuple[int, int]): The desired size for the images (width, height).
|
| 155 |
+
Defaults to (1024, 1024).
|
| 156 |
+
mean (List[float]): The mean values for normalization. Defaults to the
|
| 157 |
+
ImageNet means.
|
| 158 |
+
std (List[float]): The standard deviations for normalization. Defaults to the
|
| 159 |
+
ImageNet standard deviations.
|
| 160 |
+
|
| 161 |
+
Returns:
|
| 162 |
+
torchvision.transforms.Compose: A composition of transforms
|
| 163 |
+
that can be applied to input images.
|
| 164 |
+
|
| 165 |
+
Example:
|
| 166 |
+
>>> # Load transforms with default parameters
|
| 167 |
+
>>> transform = torch.hub.load('user/repo_name', 'data_transforms')
|
| 168 |
+
>>>
|
| 169 |
+
>>> # Load transforms with resize to custom image resolution and default normalization
|
| 170 |
+
>>> transform_small = torch.hub.load('user/repo_name', 'data_transforms', resolution=(512, 512))
|
| 171 |
+
"""
|
| 172 |
+
transform = T.Compose([
|
| 173 |
+
T.Resize(resolution),
|
| 174 |
+
T.ToTensor(),
|
| 175 |
+
T.Normalize(mean=mean, std=std)
|
| 176 |
+
])
|
| 177 |
+
return transform
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# --- ENTRYPOINT 3: Random Benchmark ---
|
| 181 |
+
def random_benchmark_entrypoint(**kwargs):
|
| 182 |
+
"""
|
| 183 |
+
Runs a random benchmark for SegFormer++.
|
| 184 |
+
"""
|
| 185 |
+
return random_benchmark(**kwargs)
|
model_without_OpenMMLab/pyproject.toml
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=61.0.0", "wheel"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "segformer_plusplus"
|
| 7 |
+
version = "0.2"
|
| 8 |
+
authors = [
|
| 9 |
+
{name = "Daniel Kienzle"},
|
| 10 |
+
]
|
| 11 |
+
description = "Segformer++: Efficient Token-Merging Strategies for High-Resolution Semantic Segmentation"
|
| 12 |
+
license = {text = "MIT"}
|
| 13 |
+
|
| 14 |
+
# Entspricht long_description
|
| 15 |
+
readme = "README.md" # Gehen wir davon aus, dass Sie eine README.md verwenden.
|
| 16 |
+
# Wenn Sie den Link aus der setup.py übernehmen möchten,
|
| 17 |
+
# nutzen Sie die Sektion [project.urls] (siehe unten).
|
| 18 |
+
|
| 19 |
+
# Entspricht install_requires
|
| 20 |
+
dependencies = [
|
| 21 |
+
"torch>=2.0.1",
|
| 22 |
+
"tomesd",
|
| 23 |
+
"omegaconf",
|
| 24 |
+
"pyyaml",
|
| 25 |
+
"numpy",
|
| 26 |
+
"rich",
|
| 27 |
+
"yapf",
|
| 28 |
+
"addict",
|
| 29 |
+
"tqdm",
|
| 30 |
+
"packaging",
|
| 31 |
+
"Pillow",
|
| 32 |
+
"torchvision",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
# Setuptools wird hier die Pakete automatisch finden (entspricht find_packages())
|
| 36 |
+
# Solange keine packages/py_modules gesetzt sind, nutzt setuptools die automatische Paketerkennung.
|
| 37 |
+
|
| 38 |
+
# Optional: Zusätzliche URLs, wenn Sie den arXiv-Link beibehalten möchten
|
| 39 |
+
[project.urls]
|
| 40 |
+
Documentation = "https://arxiv.org/abs/2405.14467"
|
model_without_OpenMMLab/segformer_plusplus/Registry/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .registry import Registry
|
| 2 |
+
|
| 3 |
+
__all__ = ["Registry"]
|
model_without_OpenMMLab/segformer_plusplus/Registry/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (244 Bytes). View file
|
|
|
model_without_OpenMMLab/segformer_plusplus/Registry/__pycache__/default_scope.cpython-310.pyc
ADDED
|
Binary file (3.73 kB). View file
|
|
|
model_without_OpenMMLab/segformer_plusplus/Registry/__pycache__/registry.cpython-310.pyc
ADDED
|
Binary file (16.6 kB). View file
|
|
|
model_without_OpenMMLab/segformer_plusplus/Registry/default_scope.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import copy
|
| 3 |
+
import time
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
from typing import Generator, Optional
|
| 6 |
+
|
| 7 |
+
from ..utils.manager import ManagerMixin, _accquire_lock, _release_lock
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class DefaultScope(ManagerMixin):
|
| 11 |
+
"""Scope of current task used to reset the current registry, which can be
|
| 12 |
+
accessed globally.
|
| 13 |
+
|
| 14 |
+
Consider the case of resetting the current ``Registry`` by
|
| 15 |
+
``default_scope`` in the internal module which cannot access runner
|
| 16 |
+
directly, it is difficult to get the ``default_scope`` defined in
|
| 17 |
+
``Runner``. However, if ``Runner`` created ``DefaultScope`` instance
|
| 18 |
+
by given ``default_scope``, the internal module can get
|
| 19 |
+
``default_scope`` by ``DefaultScope.get_current_instance`` everywhere.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
name (str): Name of default scope for global access.
|
| 23 |
+
scope_name (str): Scope of current task.
|
| 24 |
+
|
| 25 |
+
Examples:
|
| 26 |
+
>>> from mmengine.model import MODELS
|
| 27 |
+
>>> # Define default scope in runner.
|
| 28 |
+
>>> DefaultScope.get_instance('task', scope_name='mmdet')
|
| 29 |
+
>>> # Get default scope globally.
|
| 30 |
+
>>> scope_name = DefaultScope.get_instance('task').scope_name
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, name: str, scope_name: str):
|
| 34 |
+
super().__init__(name)
|
| 35 |
+
assert isinstance(
|
| 36 |
+
scope_name,
|
| 37 |
+
str), (f'scope_name should be a string, but got {scope_name}')
|
| 38 |
+
self._scope_name = scope_name
|
| 39 |
+
|
| 40 |
+
@property
|
| 41 |
+
def scope_name(self) -> str:
|
| 42 |
+
"""
|
| 43 |
+
Returns:
|
| 44 |
+
str: Get current scope.
|
| 45 |
+
"""
|
| 46 |
+
return self._scope_name
|
| 47 |
+
|
| 48 |
+
@classmethod
|
| 49 |
+
def get_current_instance(cls) -> Optional['DefaultScope']:
|
| 50 |
+
"""Get latest created default scope.
|
| 51 |
+
|
| 52 |
+
Since default_scope is an optional argument for ``Registry.build``.
|
| 53 |
+
``get_current_instance`` should return ``None`` if there is no
|
| 54 |
+
``DefaultScope`` created.
|
| 55 |
+
|
| 56 |
+
Examples:
|
| 57 |
+
>>> default_scope = DefaultScope.get_current_instance()
|
| 58 |
+
>>> # There is no `DefaultScope` created yet,
|
| 59 |
+
>>> # `get_current_instance` return `None`.
|
| 60 |
+
>>> default_scope = DefaultScope.get_instance(
|
| 61 |
+
>>> 'instance_name', scope_name='mmengine')
|
| 62 |
+
>>> default_scope.scope_name
|
| 63 |
+
mmengine
|
| 64 |
+
>>> default_scope = DefaultScope.get_current_instance()
|
| 65 |
+
>>> default_scope.scope_name
|
| 66 |
+
mmengine
|
| 67 |
+
|
| 68 |
+
Returns:
|
| 69 |
+
Optional[DefaultScope]: Return None If there has not been
|
| 70 |
+
``DefaultScope`` instance created yet, otherwise return the
|
| 71 |
+
latest created DefaultScope instance.
|
| 72 |
+
"""
|
| 73 |
+
_accquire_lock()
|
| 74 |
+
if cls._instance_dict:
|
| 75 |
+
instance = super().get_current_instance()
|
| 76 |
+
else:
|
| 77 |
+
instance = None
|
| 78 |
+
_release_lock()
|
| 79 |
+
return instance
|
| 80 |
+
|
| 81 |
+
@classmethod
|
| 82 |
+
@contextmanager
|
| 83 |
+
def overwrite_default_scope(cls, scope_name: Optional[str]) -> Generator:
|
| 84 |
+
"""Overwrite the current default scope with `scope_name`"""
|
| 85 |
+
if scope_name is None:
|
| 86 |
+
yield
|
| 87 |
+
else:
|
| 88 |
+
tmp = copy.deepcopy(cls._instance_dict)
|
| 89 |
+
# To avoid create an instance with the same name.
|
| 90 |
+
time.sleep(1e-6)
|
| 91 |
+
cls.get_instance(f'overwrite-{time.time()}', scope_name=scope_name)
|
| 92 |
+
try:
|
| 93 |
+
yield
|
| 94 |
+
finally:
|
| 95 |
+
cls._instance_dict = tmp
|
model_without_OpenMMLab/segformer_plusplus/Registry/registry.py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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import inspect
|
| 3 |
+
import sys
|
| 4 |
+
import types
|
| 5 |
+
from collections import abc
|
| 6 |
+
from collections.abc import Callable
|
| 7 |
+
from contextlib import contextmanager
|
| 8 |
+
from importlib import import_module
|
| 9 |
+
from typing import Any, Dict, Generator, List, Optional, Tuple, Type, Union
|
| 10 |
+
from rich.console import Console
|
| 11 |
+
from rich.table import Table
|
| 12 |
+
|
| 13 |
+
from .default_scope import DefaultScope
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
MODULE2PACKAGE = {
|
| 17 |
+
'mmcls': 'mmcls',
|
| 18 |
+
'mmdet': 'mmdet',
|
| 19 |
+
'mmdet3d': 'mmdet3d',
|
| 20 |
+
'mmseg': 'mmsegmentation',
|
| 21 |
+
'mmaction': 'mmaction2',
|
| 22 |
+
'mmtrack': 'mmtrack',
|
| 23 |
+
'mmpose': 'mmpose',
|
| 24 |
+
'mmedit': 'mmedit',
|
| 25 |
+
'mmocr': 'mmocr',
|
| 26 |
+
'mmgen': 'mmgen',
|
| 27 |
+
'mmfewshot': 'mmfewshot',
|
| 28 |
+
'mmrazor': 'mmrazor',
|
| 29 |
+
'mmflow': 'mmflow',
|
| 30 |
+
'mmhuman3d': 'mmhuman3d',
|
| 31 |
+
'mmrotate': 'mmrotate',
|
| 32 |
+
'mmselfsup': 'mmselfsup',
|
| 33 |
+
'mmyolo': 'mmyolo',
|
| 34 |
+
'mmpretrain': 'mmpretrain',
|
| 35 |
+
'mmagic': 'mmagic',
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
class Registry:
|
| 39 |
+
"""A registry to map strings to classes or functions.
|
| 40 |
+
|
| 41 |
+
Registered object could be built from registry. Meanwhile, registered
|
| 42 |
+
functions could be called from registry.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
name (str): Registry name.
|
| 46 |
+
build_func (callable, optional): A function to construct instance
|
| 47 |
+
from Registry. :func:`build_from_cfg` is used if neither ``parent``
|
| 48 |
+
or ``build_func`` is specified. If ``parent`` is specified and
|
| 49 |
+
``build_func`` is not given, ``build_func`` will be inherited
|
| 50 |
+
from ``parent``. Defaults to None.
|
| 51 |
+
parent (:obj:`Registry`, optional): Parent registry. The class
|
| 52 |
+
registered in children registry could be built from parent.
|
| 53 |
+
Defaults to None.
|
| 54 |
+
scope (str, optional): The scope of registry. It is the key to search
|
| 55 |
+
for children registry. If not specified, scope will be the name of
|
| 56 |
+
the package where class is defined, e.g. mmdet, mmcls, mmseg.
|
| 57 |
+
Defaults to None.
|
| 58 |
+
locations (list): The locations to import the modules registered
|
| 59 |
+
in this registry. Defaults to [].
|
| 60 |
+
New in version 0.4.0.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(self,
|
| 64 |
+
name: str,
|
| 65 |
+
build_func: Optional[Callable] = None,
|
| 66 |
+
parent: Optional['Registry'] = None,
|
| 67 |
+
scope: Optional[str] = None,
|
| 68 |
+
locations: List = []):
|
| 69 |
+
self._name = name
|
| 70 |
+
self._module_dict: Dict[str, Type] = dict()
|
| 71 |
+
self._children: Dict[str, 'Registry'] = dict()
|
| 72 |
+
self._locations = locations
|
| 73 |
+
self._imported = False
|
| 74 |
+
|
| 75 |
+
if scope is not None:
|
| 76 |
+
assert isinstance(scope, str)
|
| 77 |
+
self._scope = scope
|
| 78 |
+
else:
|
| 79 |
+
self._scope = self.infer_scope()
|
| 80 |
+
|
| 81 |
+
self.parent: Optional['Registry']
|
| 82 |
+
if parent is not None:
|
| 83 |
+
assert isinstance(parent, Registry)
|
| 84 |
+
parent._add_child(self)
|
| 85 |
+
self.parent = parent
|
| 86 |
+
else:
|
| 87 |
+
self.parent = None
|
| 88 |
+
|
| 89 |
+
self.build_func: Callable
|
| 90 |
+
if build_func is None:
|
| 91 |
+
if self.parent is not None:
|
| 92 |
+
self.build_func = self.parent.build_func
|
| 93 |
+
else:
|
| 94 |
+
from ..utils.build_functions import build_from_cfg
|
| 95 |
+
self.build_func = build_from_cfg
|
| 96 |
+
else:
|
| 97 |
+
self.build_func = build_func
|
| 98 |
+
|
| 99 |
+
def __len__(self):
|
| 100 |
+
return len(self._module_dict)
|
| 101 |
+
|
| 102 |
+
def __contains__(self, key):
|
| 103 |
+
return self.get(key) is not None
|
| 104 |
+
|
| 105 |
+
def __repr__(self):
|
| 106 |
+
table = Table(title=f'Registry of {self._name}')
|
| 107 |
+
table.add_column('Names', justify='left', style='cyan')
|
| 108 |
+
table.add_column('Objects', justify='left', style='green')
|
| 109 |
+
|
| 110 |
+
for name, obj in sorted(self._module_dict.items()):
|
| 111 |
+
table.add_row(name, str(obj))
|
| 112 |
+
|
| 113 |
+
console = Console()
|
| 114 |
+
with console.capture() as capture:
|
| 115 |
+
console.print(table, end='')
|
| 116 |
+
|
| 117 |
+
return capture.get()
|
| 118 |
+
|
| 119 |
+
@staticmethod
|
| 120 |
+
def infer_scope() -> str:
|
| 121 |
+
"""Infer the scope of registry.
|
| 122 |
+
|
| 123 |
+
The name of the package where registry is defined will be returned.
|
| 124 |
+
|
| 125 |
+
Returns:
|
| 126 |
+
str: The inferred scope name.
|
| 127 |
+
"""
|
| 128 |
+
module = inspect.getmodule(sys._getframe(2))
|
| 129 |
+
if module is not None:
|
| 130 |
+
filename = module.__name__
|
| 131 |
+
split_filename = filename.split('.')
|
| 132 |
+
scope = split_filename[0]
|
| 133 |
+
else:
|
| 134 |
+
scope = 'mmengine'
|
| 135 |
+
return scope
|
| 136 |
+
|
| 137 |
+
@staticmethod
|
| 138 |
+
def split_scope_key(key: str) -> Tuple[Optional[str], str]:
|
| 139 |
+
"""Split scope and key.
|
| 140 |
+
|
| 141 |
+
The first scope will be split from key.
|
| 142 |
+
|
| 143 |
+
Return:
|
| 144 |
+
tuple[str | None, str]: The former element is the first scope of
|
| 145 |
+
the key, which can be ``None``. The latter is the remaining key.
|
| 146 |
+
|
| 147 |
+
"""
|
| 148 |
+
split_index = key.find('.')
|
| 149 |
+
if split_index != -1:
|
| 150 |
+
return key[:split_index], key[split_index + 1:]
|
| 151 |
+
else:
|
| 152 |
+
return None, key
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
def name(self):
|
| 156 |
+
return self._name
|
| 157 |
+
|
| 158 |
+
@property
|
| 159 |
+
def scope(self):
|
| 160 |
+
return self._scope
|
| 161 |
+
|
| 162 |
+
@property
|
| 163 |
+
def module_dict(self):
|
| 164 |
+
return self._module_dict
|
| 165 |
+
|
| 166 |
+
@property
|
| 167 |
+
def children(self):
|
| 168 |
+
return self._children
|
| 169 |
+
|
| 170 |
+
@property
|
| 171 |
+
def root(self):
|
| 172 |
+
return self._get_root_registry()
|
| 173 |
+
|
| 174 |
+
@contextmanager
|
| 175 |
+
def switch_scope_and_registry(self, scope: Optional[str]) -> Generator:
|
| 176 |
+
"""Temporarily switch default scope to the target scope, and get the
|
| 177 |
+
corresponding registry.
|
| 178 |
+
|
| 179 |
+
If the registry of the corresponding scope exists, yield the
|
| 180 |
+
registry, otherwise yield the current itself.
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
scope (str, optional): The target scope.
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
with DefaultScope.overwrite_default_scope(scope):
|
| 187 |
+
# Get the global default scope
|
| 188 |
+
default_scope = DefaultScope.get_current_instance()
|
| 189 |
+
# Get registry by scope
|
| 190 |
+
if default_scope is not None:
|
| 191 |
+
scope_name = default_scope.scope_name
|
| 192 |
+
try:
|
| 193 |
+
import_module(f'{scope_name}.registry')
|
| 194 |
+
except (ImportError, AttributeError, ModuleNotFoundError):
|
| 195 |
+
if scope in MODULE2PACKAGE:
|
| 196 |
+
print(
|
| 197 |
+
f'{scope} is not installed and its '
|
| 198 |
+
'modules will not be registered. If you '
|
| 199 |
+
'want to use modules defined in '
|
| 200 |
+
f'{scope}, Please install {scope} by '
|
| 201 |
+
f'`pip install {MODULE2PACKAGE[scope]}.')
|
| 202 |
+
else:
|
| 203 |
+
print(
|
| 204 |
+
f'Failed to import `{scope}.registry` '
|
| 205 |
+
f'make sure the registry.py exists in `{scope}` '
|
| 206 |
+
'package.',)
|
| 207 |
+
root = self._get_root_registry()
|
| 208 |
+
registry = root._search_child(scope_name)
|
| 209 |
+
if registry is None:
|
| 210 |
+
print(
|
| 211 |
+
f'Failed to search registry with scope "{scope_name}" '
|
| 212 |
+
f'in the "{root.name}" registry tree. '
|
| 213 |
+
f'As a workaround, the current "{self.name}" registry '
|
| 214 |
+
f'in "{self.scope}" is used to build instance. This '
|
| 215 |
+
'may cause unexpected failure when running the built '
|
| 216 |
+
f'modules. Please check whether "{scope_name}" is a '
|
| 217 |
+
'correct scope, or whether the registry is '
|
| 218 |
+
'initialized.',)
|
| 219 |
+
registry = self
|
| 220 |
+
else:
|
| 221 |
+
registry = self
|
| 222 |
+
yield registry
|
| 223 |
+
|
| 224 |
+
def _get_root_registry(self) -> 'Registry':
|
| 225 |
+
"""Return the root registry."""
|
| 226 |
+
root = self
|
| 227 |
+
while root.parent is not None:
|
| 228 |
+
root = root.parent
|
| 229 |
+
return root
|
| 230 |
+
|
| 231 |
+
def import_from_location(self) -> None:
|
| 232 |
+
"""Import modules from the pre-defined locations in self._location."""
|
| 233 |
+
if not self._imported:
|
| 234 |
+
# avoid BC breaking
|
| 235 |
+
if len(self._locations) == 0 and self.scope in MODULE2PACKAGE:
|
| 236 |
+
print(
|
| 237 |
+
f'The "{self.name}" registry in {self.scope} did not '
|
| 238 |
+
'set import location. Fallback to call '
|
| 239 |
+
f'`{self.scope}.utils.register_all_modules` '
|
| 240 |
+
'instead.',)
|
| 241 |
+
try:
|
| 242 |
+
module = import_module(f'{self.scope}.utils')
|
| 243 |
+
except (ImportError, AttributeError, ModuleNotFoundError):
|
| 244 |
+
if self.scope in MODULE2PACKAGE:
|
| 245 |
+
print(
|
| 246 |
+
f'{self.scope} is not installed and its '
|
| 247 |
+
'modules will not be registered. If you '
|
| 248 |
+
'want to use modules defined in '
|
| 249 |
+
f'{self.scope}, Please install {self.scope} by '
|
| 250 |
+
f'`pip install {MODULE2PACKAGE[self.scope]}.',)
|
| 251 |
+
else:
|
| 252 |
+
print(
|
| 253 |
+
f'Failed to import {self.scope} and register '
|
| 254 |
+
'its modules, please make sure you '
|
| 255 |
+
'have registered the module manually.',)
|
| 256 |
+
else:
|
| 257 |
+
module.register_all_modules(False) # type: ignore
|
| 258 |
+
|
| 259 |
+
for loc in self._locations:
|
| 260 |
+
import_module(loc)
|
| 261 |
+
print(
|
| 262 |
+
f"Modules of {self.scope}'s {self.name} registry have "
|
| 263 |
+
f'been automatically imported from {loc}',)
|
| 264 |
+
self._imported = True
|
| 265 |
+
|
| 266 |
+
def get(self, key: str) -> Optional[Type]:
|
| 267 |
+
"""Get the registry record.
|
| 268 |
+
|
| 269 |
+
If `key`` represents the whole object name with its module
|
| 270 |
+
information, for example, `mmengine.model.BaseModel`, ``get``
|
| 271 |
+
will directly return the class object :class:`BaseModel`.
|
| 272 |
+
|
| 273 |
+
Otherwise, it will first parse ``key`` and check whether it
|
| 274 |
+
contains a scope name. The logic to search for ``key``:
|
| 275 |
+
|
| 276 |
+
- ``key`` does not contain a scope name, i.e., it is purely a module
|
| 277 |
+
name like "ResNet": :meth:`get` will search for ``ResNet`` from the
|
| 278 |
+
current registry to its parent or ancestors until finding it.
|
| 279 |
+
|
| 280 |
+
- ``key`` contains a scope name and it is equal to the scope of the
|
| 281 |
+
current registry (e.g., "mmcls"), e.g., "mmcls.ResNet": :meth:`get`
|
| 282 |
+
will only search for ``ResNet`` in the current registry.
|
| 283 |
+
|
| 284 |
+
- ``key`` contains a scope name and it is not equal to the scope of
|
| 285 |
+
the current registry (e.g., "mmdet"), e.g., "mmcls.FCNet": If the
|
| 286 |
+
scope exists in its children, :meth:`get` will get "FCNet" from
|
| 287 |
+
them. If not, :meth:`get` will first get the root registry and root
|
| 288 |
+
registry call its own :meth:`get` method.
|
| 289 |
+
|
| 290 |
+
Args:
|
| 291 |
+
key (str): Name of the registered item, e.g., the class name in
|
| 292 |
+
string format.
|
| 293 |
+
|
| 294 |
+
Returns:
|
| 295 |
+
Type or None: Return the corresponding class if ``key`` exists,
|
| 296 |
+
otherwise return None.
|
| 297 |
+
"""
|
| 298 |
+
|
| 299 |
+
if not isinstance(key, str):
|
| 300 |
+
raise TypeError(
|
| 301 |
+
'The key argument of `Registry.get` must be a str, '
|
| 302 |
+
f'got {type(key)}')
|
| 303 |
+
|
| 304 |
+
scope, real_key = self.split_scope_key(key)
|
| 305 |
+
obj_cls = None
|
| 306 |
+
registry_name = self.name
|
| 307 |
+
scope_name = self.scope
|
| 308 |
+
|
| 309 |
+
# lazy import the modules to register them into the registry
|
| 310 |
+
self.import_from_location()
|
| 311 |
+
|
| 312 |
+
if scope is None or scope == self._scope:
|
| 313 |
+
# get from self
|
| 314 |
+
if real_key in self._module_dict:
|
| 315 |
+
obj_cls = self._module_dict[real_key]
|
| 316 |
+
elif scope is None:
|
| 317 |
+
# try to get the target from its parent or ancestors
|
| 318 |
+
parent = self.parent
|
| 319 |
+
while parent is not None:
|
| 320 |
+
if real_key in parent._module_dict:
|
| 321 |
+
obj_cls = parent._module_dict[real_key]
|
| 322 |
+
registry_name = parent.name
|
| 323 |
+
scope_name = parent.scope
|
| 324 |
+
break
|
| 325 |
+
parent = parent.parent
|
| 326 |
+
else:
|
| 327 |
+
# import the registry to add the nodes into the registry tree
|
| 328 |
+
try:
|
| 329 |
+
import_module(f'{scope}.registry')
|
| 330 |
+
print(
|
| 331 |
+
f'Registry node of {scope} has been automatically '
|
| 332 |
+
'imported.',)
|
| 333 |
+
except (ImportError, AttributeError, ModuleNotFoundError):
|
| 334 |
+
print(
|
| 335 |
+
f'Cannot auto import {scope}.registry, please check '
|
| 336 |
+
f'whether the package "{scope}" is installed correctly '
|
| 337 |
+
'or import the registry manually.',)
|
| 338 |
+
# get from self._children
|
| 339 |
+
if scope in self._children:
|
| 340 |
+
obj_cls = self._children[scope].get(real_key)
|
| 341 |
+
registry_name = self._children[scope].name
|
| 342 |
+
scope_name = scope
|
| 343 |
+
else:
|
| 344 |
+
root = self._get_root_registry()
|
| 345 |
+
|
| 346 |
+
if scope != root._scope and scope not in root._children:
|
| 347 |
+
# If not skip directly, `root.get(key)` will recursively
|
| 348 |
+
# call itself until RecursionError is thrown.
|
| 349 |
+
pass
|
| 350 |
+
else:
|
| 351 |
+
obj_cls = root.get(key)
|
| 352 |
+
|
| 353 |
+
if obj_cls is None:
|
| 354 |
+
try:
|
| 355 |
+
obj_cls = get_object_from_string(key)
|
| 356 |
+
except Exception:
|
| 357 |
+
raise RuntimeError(f'Failed to get {key}')
|
| 358 |
+
|
| 359 |
+
if obj_cls is not None:
|
| 360 |
+
# For some rare cases (e.g. obj_cls is a partial function), obj_cls
|
| 361 |
+
# doesn't have `__name__`. Use default value to prevent error
|
| 362 |
+
cls_name = getattr(obj_cls, '__name__', str(obj_cls))
|
| 363 |
+
return obj_cls
|
| 364 |
+
|
| 365 |
+
def _search_child(self, scope: str) -> Optional['Registry']:
|
| 366 |
+
"""Depth-first search for the corresponding registry in its children.
|
| 367 |
+
|
| 368 |
+
Note that the method only search for the corresponding registry from
|
| 369 |
+
the current registry. Therefore, if we want to search from the root
|
| 370 |
+
registry, :meth:`_get_root_registry` should be called to get the
|
| 371 |
+
root registry first.
|
| 372 |
+
|
| 373 |
+
Args:
|
| 374 |
+
scope (str): The scope name used for searching for its
|
| 375 |
+
corresponding registry.
|
| 376 |
+
|
| 377 |
+
Returns:
|
| 378 |
+
Registry or None: Return the corresponding registry if ``scope``
|
| 379 |
+
exists, otherwise return None.
|
| 380 |
+
"""
|
| 381 |
+
if self._scope == scope:
|
| 382 |
+
return self
|
| 383 |
+
|
| 384 |
+
for child in self._children.values():
|
| 385 |
+
registry = child._search_child(scope)
|
| 386 |
+
if registry is not None:
|
| 387 |
+
return registry
|
| 388 |
+
|
| 389 |
+
return None
|
| 390 |
+
|
| 391 |
+
def build(self, cfg: dict, *args, **kwargs) -> Any:
|
| 392 |
+
"""Build an instance.
|
| 393 |
+
|
| 394 |
+
Build an instance by calling :attr:`build_func`.
|
| 395 |
+
|
| 396 |
+
Args:
|
| 397 |
+
cfg (dict): Config dict needs to be built.
|
| 398 |
+
|
| 399 |
+
Returns:
|
| 400 |
+
Any: The constructed object.
|
| 401 |
+
"""
|
| 402 |
+
return self.build_func(cfg, *args, **kwargs, registry=self)
|
| 403 |
+
|
| 404 |
+
def _add_child(self, registry: 'Registry') -> None:
|
| 405 |
+
"""Add a child for a registry.
|
| 406 |
+
|
| 407 |
+
Args:
|
| 408 |
+
registry (:obj:`Registry`): The ``registry`` will be added as a
|
| 409 |
+
child of the ``self``.
|
| 410 |
+
"""
|
| 411 |
+
|
| 412 |
+
assert isinstance(registry, Registry)
|
| 413 |
+
assert registry.scope is not None
|
| 414 |
+
assert registry.scope not in self.children, \
|
| 415 |
+
f'scope {registry.scope} exists in {self.name} registry'
|
| 416 |
+
self.children[registry.scope] = registry
|
| 417 |
+
|
| 418 |
+
def _register_module(self,
|
| 419 |
+
module: Type,
|
| 420 |
+
module_name: Optional[Union[str, List[str]]] = None,
|
| 421 |
+
force: bool = False) -> None:
|
| 422 |
+
"""Register a module.
|
| 423 |
+
|
| 424 |
+
Args:
|
| 425 |
+
module (type): Module to be registered. Typically a class or a
|
| 426 |
+
function, but generally all ``Callable`` are acceptable.
|
| 427 |
+
module_name (str or list of str, optional): The module name to be
|
| 428 |
+
registered. If not specified, the class name will be used.
|
| 429 |
+
Defaults to None.
|
| 430 |
+
force (bool): Whether to override an existing class with the same
|
| 431 |
+
name. Defaults to False.
|
| 432 |
+
"""
|
| 433 |
+
if not callable(module):
|
| 434 |
+
raise TypeError(f'module must be Callable, but got {type(module)}')
|
| 435 |
+
|
| 436 |
+
if module_name is None:
|
| 437 |
+
module_name = module.__name__
|
| 438 |
+
if isinstance(module_name, str):
|
| 439 |
+
module_name = [module_name]
|
| 440 |
+
for name in module_name:
|
| 441 |
+
if not force and name in self._module_dict:
|
| 442 |
+
existed_module = self.module_dict[name]
|
| 443 |
+
raise KeyError(f'{name} is already registered in {self.name} '
|
| 444 |
+
f'at {existed_module.__module__}')
|
| 445 |
+
self._module_dict[name] = module
|
| 446 |
+
|
| 447 |
+
def register_module(
|
| 448 |
+
self,
|
| 449 |
+
name: Optional[Union[str, List[str]]] = None,
|
| 450 |
+
force: bool = False,
|
| 451 |
+
module: Optional[Type] = None) -> Union[type, Callable]:
|
| 452 |
+
"""Register a module.
|
| 453 |
+
|
| 454 |
+
A record will be added to ``self._module_dict``, whose key is the class
|
| 455 |
+
name or the specified name, and value is the class itself.
|
| 456 |
+
It can be used as a decorator or a normal function.
|
| 457 |
+
|
| 458 |
+
Args:
|
| 459 |
+
name (str or list of str, optional): The module name to be
|
| 460 |
+
registered. If not specified, the class name will be used.
|
| 461 |
+
force (bool): Whether to override an existing class with the same
|
| 462 |
+
name. Defaults to False.
|
| 463 |
+
module (type, optional): Module class or function to be registered.
|
| 464 |
+
Defaults to None.
|
| 465 |
+
"""
|
| 466 |
+
if not isinstance(force, bool):
|
| 467 |
+
raise TypeError(f'force must be a boolean, but got {type(force)}')
|
| 468 |
+
|
| 469 |
+
# raise the error ahead of time
|
| 470 |
+
if not (name is None or isinstance(name, str) or is_seq_of(name, str)):
|
| 471 |
+
raise TypeError(
|
| 472 |
+
'name must be None, an instance of str, or a sequence of str, '
|
| 473 |
+
f'but got {type(name)}')
|
| 474 |
+
|
| 475 |
+
# use it as a normal method: x.register_module(module=SomeClass)
|
| 476 |
+
if module is not None:
|
| 477 |
+
self._register_module(module=module, module_name=name, force=force)
|
| 478 |
+
return module
|
| 479 |
+
|
| 480 |
+
# use it as a decorator: @x.register_module()
|
| 481 |
+
def _register(module):
|
| 482 |
+
self._register_module(module=module, module_name=name, force=force)
|
| 483 |
+
return module
|
| 484 |
+
|
| 485 |
+
return _register
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def is_seq_of(seq: Any,
|
| 489 |
+
expected_type: Union[Type, tuple],
|
| 490 |
+
seq_type: Optional[Type] = None) -> bool:
|
| 491 |
+
"""Check whether it is a sequence of some type.
|
| 492 |
+
|
| 493 |
+
Args:
|
| 494 |
+
seq (Sequence): The sequence to be checked.
|
| 495 |
+
expected_type (type or tuple): Expected type of sequence items.
|
| 496 |
+
seq_type (type, optional): Expected sequence type. Defaults to None.
|
| 497 |
+
|
| 498 |
+
Returns:
|
| 499 |
+
bool: Return True if ``seq`` is valid else False.
|
| 500 |
+
"""
|
| 501 |
+
if seq_type is None:
|
| 502 |
+
exp_seq_type = abc.Sequence
|
| 503 |
+
else:
|
| 504 |
+
assert isinstance(seq_type, type)
|
| 505 |
+
exp_seq_type = seq_type
|
| 506 |
+
if not isinstance(seq, exp_seq_type):
|
| 507 |
+
return False
|
| 508 |
+
for item in seq:
|
| 509 |
+
if not isinstance(item, expected_type):
|
| 510 |
+
return False
|
| 511 |
+
return True
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def get_object_from_string(obj_name: str):
|
| 515 |
+
"""Get object from name.
|
| 516 |
+
|
| 517 |
+
Args:
|
| 518 |
+
obj_name (str): The name of the object.
|
| 519 |
+
"""
|
| 520 |
+
parts = iter(obj_name.split('.'))
|
| 521 |
+
module_name = next(parts)
|
| 522 |
+
# import module
|
| 523 |
+
while True:
|
| 524 |
+
try:
|
| 525 |
+
module = import_module(module_name)
|
| 526 |
+
part = next(parts)
|
| 527 |
+
# mmcv.ops has nms.py and nms function at the same time. So the
|
| 528 |
+
# function will have a higher priority
|
| 529 |
+
obj = getattr(module, part, None)
|
| 530 |
+
if obj is not None and not ismodule(obj):
|
| 531 |
+
break
|
| 532 |
+
module_name = f'{module_name}.{part}'
|
| 533 |
+
except StopIteration:
|
| 534 |
+
# if obj is a module
|
| 535 |
+
return module
|
| 536 |
+
except ImportError:
|
| 537 |
+
return None
|
| 538 |
+
|
| 539 |
+
# get class or attribute from module
|
| 540 |
+
obj = module
|
| 541 |
+
while True:
|
| 542 |
+
try:
|
| 543 |
+
obj = getattr(obj, part)
|
| 544 |
+
part = next(parts)
|
| 545 |
+
except StopIteration:
|
| 546 |
+
return obj
|
| 547 |
+
except AttributeError:
|
| 548 |
+
return None
|
| 549 |
+
|
| 550 |
+
def ismodule(object):
|
| 551 |
+
"""Return true if the object is a module.
|
| 552 |
+
|
| 553 |
+
Module objects provide these attributes:
|
| 554 |
+
__cached__ pathname to byte compiled file
|
| 555 |
+
__doc__ documentation string
|
| 556 |
+
__file__ filename (missing for built-in modules)"""
|
| 557 |
+
return isinstance(object, types.ModuleType)
|
model_without_OpenMMLab/segformer_plusplus/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .build_model import create_model, create_custom_model
|
| 2 |
+
from .random_benchmark import random_benchmark
|
| 3 |
+
|
| 4 |
+
__all__ = ['create_model', 'create_custom_model', 'random_benchmark']
|
model_without_OpenMMLab/segformer_plusplus/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (325 Bytes). View file
|
|
|
model_without_OpenMMLab/segformer_plusplus/__pycache__/build_model.cpython-310.pyc
ADDED
|
Binary file (3.59 kB). View file
|
|
|
model_without_OpenMMLab/segformer_plusplus/__pycache__/cityscape_benchmark.cpython-310.pyc
ADDED
|
Binary file (2.97 kB). View file
|
|
|
model_without_OpenMMLab/segformer_plusplus/__pycache__/random_benchmark.cpython-310.pyc
ADDED
|
Binary file (1.66 kB). View file
|
|
|
model_without_OpenMMLab/segformer_plusplus/__pycache__/start_cityscape_benchmark.cpython-310.pyc
ADDED
|
Binary file (2 kB). View file
|
|
|
model_without_OpenMMLab/segformer_plusplus/build_model.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from .utils import MODELS, imagenet_weights
|
| 4 |
+
from .utils import tome_presets
|
| 5 |
+
from .model.base_module import BaseModule
|
| 6 |
+
from .configs.config.config import Config
|
| 7 |
+
from .utils.build_functions import build_model_from_cfg
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class SegFormer(BaseModule):
|
| 11 |
+
"""
|
| 12 |
+
This class represents a SegFormer model that allows for the application of token merging.
|
| 13 |
+
|
| 14 |
+
Attributes:
|
| 15 |
+
backbone (BaseModule): MixVisionTransformer backbone
|
| 16 |
+
decode_head (BaseModule): SegFormer head
|
| 17 |
+
|
| 18 |
+
"""
|
| 19 |
+
def __init__(self, cfg):
|
| 20 |
+
"""
|
| 21 |
+
Initialize the SegFormer model.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
cfg (Config): an mmengine Config object, which defines the backbone, head and token merging strategy used.
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.backbone = build_model_from_cfg(cfg.backbone, registry=MODELS)
|
| 29 |
+
self.decode_head = build_model_from_cfg(cfg.decode_head, registry=MODELS)
|
| 30 |
+
|
| 31 |
+
def forward(self, x):
|
| 32 |
+
"""
|
| 33 |
+
Forward pass of the model.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
x (torch.Tensor): input tensor of shape [B, C, H, W]
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
torch.Tensor: output tensor
|
| 40 |
+
|
| 41 |
+
"""
|
| 42 |
+
x = self.backbone(x)
|
| 43 |
+
x = self.decode_head(x)
|
| 44 |
+
return x
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def create_model(
|
| 48 |
+
backbone: str = 'b0',
|
| 49 |
+
tome_strategy: str = None,
|
| 50 |
+
out_channels: int = 19,
|
| 51 |
+
pretrained: bool = False,
|
| 52 |
+
):
|
| 53 |
+
"""
|
| 54 |
+
Create a SegFormer model using the predefined SegFormer backbones from the MiT series (b0-b5).
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
backbone (str): backbone name (e.g. 'b0')
|
| 58 |
+
tome_strategy (str | list(dict)): select strategy from presets ('bsm_hq', 'bsm_fast', 'n2d_2x2') or define a
|
| 59 |
+
custom strategy using a list, that contains of dictionaries, in which the strategies for the stage are
|
| 60 |
+
defined
|
| 61 |
+
out_channels (int): number of output channels (e.g. 19 for the cityscapes semantic segmentation task)
|
| 62 |
+
pretrained: use pretrained (imagenet) weights
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
BaseModule: SegFormer model
|
| 66 |
+
|
| 67 |
+
"""
|
| 68 |
+
backbone = backbone.lower()
|
| 69 |
+
assert backbone in [f'b{i}' for i in range(6)]
|
| 70 |
+
|
| 71 |
+
wd = os.path.dirname(os.path.abspath(__file__))
|
| 72 |
+
|
| 73 |
+
cfg = Config.fromfile(os.path.join(wd, 'configs', f'segformer_mit_{backbone}.py'))
|
| 74 |
+
|
| 75 |
+
cfg.decode_head.out_channels = out_channels
|
| 76 |
+
|
| 77 |
+
if tome_strategy is not None:
|
| 78 |
+
if tome_strategy not in list(tome_presets.keys()):
|
| 79 |
+
print("Using custom merging strategy.")
|
| 80 |
+
cfg.backbone.tome_cfg = tome_presets[tome_strategy]
|
| 81 |
+
|
| 82 |
+
# load imagenet weights
|
| 83 |
+
if pretrained:
|
| 84 |
+
cfg.backbone.init_cfg = dict(type='Pretrained', checkpoint=imagenet_weights[backbone])
|
| 85 |
+
|
| 86 |
+
return SegFormer(cfg)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def create_custom_model(
|
| 90 |
+
model_cfg: Config,
|
| 91 |
+
tome_strategy: list[dict] = None,
|
| 92 |
+
):
|
| 93 |
+
"""
|
| 94 |
+
Create a SegFormer model with customizable backbone and head.
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
model_cfg (Config): backbone name (e.g. 'b0')
|
| 98 |
+
tome_strategy (list(dict)): custom token merging strategy
|
| 99 |
+
|
| 100 |
+
Returns:
|
| 101 |
+
BaseModule: SegFormer model
|
| 102 |
+
|
| 103 |
+
"""
|
| 104 |
+
if tome_strategy is not None:
|
| 105 |
+
model_cfg.backbone.tome_cfg = tome_strategy
|
| 106 |
+
|
| 107 |
+
return SegFormer(model_cfg)
|
model_without_OpenMMLab/segformer_plusplus/cityscape/berlin_000543_000019_leftImg8bit.png
ADDED
|
Git LFS Details
|
model_without_OpenMMLab/segformer_plusplus/cityscape_benchmark.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import torchvision.transforms as T
|
| 4 |
+
import os
|
| 5 |
+
from typing import Union, List, Tuple
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
from .utils.benchmark import benchmark
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# Gerät auswählen
|
| 12 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 13 |
+
print(f"Using device: {device}")
|
| 14 |
+
if device.type == 'cuda':
|
| 15 |
+
print(f"CUDA Device Name: {torch.cuda.get_device_name(torch.cuda.current_device())}")
|
| 16 |
+
|
| 17 |
+
def cityscape_benchmark(
|
| 18 |
+
model: torch.nn.Module,
|
| 19 |
+
image_path: str,
|
| 20 |
+
batch_size: Union[int, List[int]] = 1,
|
| 21 |
+
image_size: Union[Tuple[int], List[Tuple[int]]] = (3, 1024, 1024),
|
| 22 |
+
save_output: bool = True,
|
| 23 |
+
|
| 24 |
+
):
|
| 25 |
+
"""
|
| 26 |
+
Calculate the FPS of a given model using an actual Cityscapes image.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
model: instance of a model (e.g. SegFormer)
|
| 30 |
+
image_path: the path to the Cityscapes image
|
| 31 |
+
batch_size: the batch size(s) at which to calculate the FPS (e.g. 1 or [1, 2, 4])
|
| 32 |
+
image_size: the size of the images to use (e.g. (3, 1024, 1024))
|
| 33 |
+
save_output: whether to save the output prediction (default True)
|
| 34 |
+
|
| 35 |
+
Returns:
|
| 36 |
+
the FPS values calculated for all image sizes and batch sizes in the form of a dictionary
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if isinstance(batch_size, int):
|
| 41 |
+
batch_size = [batch_size]
|
| 42 |
+
if isinstance(image_size, tuple):
|
| 43 |
+
image_size = [image_size]
|
| 44 |
+
|
| 45 |
+
values = {}
|
| 46 |
+
throughput_values = []
|
| 47 |
+
|
| 48 |
+
model = model.to(device)
|
| 49 |
+
model.eval()
|
| 50 |
+
|
| 51 |
+
assert os.path.exists(image_path), f"Image not found: {image_path}"
|
| 52 |
+
image = Image.open(image_path).convert("RGB")
|
| 53 |
+
|
| 54 |
+
img_tensor = T.ToTensor()(image)
|
| 55 |
+
mean = img_tensor.mean(dim=(1, 2))
|
| 56 |
+
std = img_tensor.std(dim=(1, 2))
|
| 57 |
+
print(f"Calculated Mean: {mean}")
|
| 58 |
+
print(f"Calculated Std: {std}")
|
| 59 |
+
|
| 60 |
+
transform = T.Compose([
|
| 61 |
+
T.Resize((image_size[0][1], image_size[0][2])),
|
| 62 |
+
T.ToTensor(),
|
| 63 |
+
T.Normalize(mean=mean.tolist(),
|
| 64 |
+
std=std.tolist())
|
| 65 |
+
])
|
| 66 |
+
|
| 67 |
+
img_tensor = transform(image).unsqueeze(0).to(device)
|
| 68 |
+
|
| 69 |
+
for i in image_size:
|
| 70 |
+
# fill with fps for each batch size
|
| 71 |
+
fps = []
|
| 72 |
+
for b in batch_size:
|
| 73 |
+
for _ in range(4):
|
| 74 |
+
# Baseline benchmark
|
| 75 |
+
if i[1] >= 1024:
|
| 76 |
+
r = 16
|
| 77 |
+
else:
|
| 78 |
+
r = 32
|
| 79 |
+
baseline_throughput = benchmark(
|
| 80 |
+
model.to(device),
|
| 81 |
+
device=device,
|
| 82 |
+
verbose=True,
|
| 83 |
+
runs=r,
|
| 84 |
+
batch_size=b,
|
| 85 |
+
input_size=i
|
| 86 |
+
)
|
| 87 |
+
throughput_values.append(baseline_throughput)
|
| 88 |
+
throughput_values = np.asarray(throughput_values)
|
| 89 |
+
throughput = np.around(np.mean(throughput_values), decimals=2)
|
| 90 |
+
print('Im_size:', i, 'Batch_size:', b, 'Mean:', throughput, 'Std:',
|
| 91 |
+
np.around(np.std(throughput_values), decimals=2))
|
| 92 |
+
throughput_values = []
|
| 93 |
+
fps.append({b: throughput})
|
| 94 |
+
values[i] = fps
|
| 95 |
+
|
| 96 |
+
if save_output:
|
| 97 |
+
with torch.no_grad():
|
| 98 |
+
output = model(img_tensor)
|
| 99 |
+
pred = torch.argmax(output, dim=1).squeeze(0).cpu().numpy()
|
| 100 |
+
|
| 101 |
+
# Speichere Prediction als Text ab
|
| 102 |
+
cwd = os.getcwd()
|
| 103 |
+
output_path = os.path.join(cwd, 'segformer_plusplus', 'cityscapes_prediction_output.txt')
|
| 104 |
+
np.savetxt(output_path, pred, fmt="%d")
|
| 105 |
+
|
| 106 |
+
print("Prediction saved as cityscapes_prediction_output.txt")
|
| 107 |
+
|
| 108 |
+
return values
|
model_without_OpenMMLab/segformer_plusplus/cityscapes_prediction_output.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model_without_OpenMMLab/segformer_plusplus/cityscapes_prediction_output__reference_b05_bsm_hq_checkpoint.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model_without_OpenMMLab/segformer_plusplus/configs/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
__all__ = []
|
model_without_OpenMMLab/segformer_plusplus/configs/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (190 Bytes). View file
|
|
|
model_without_OpenMMLab/segformer_plusplus/configs/config/__pycache__/config.cpython-310.pyc
ADDED
|
Binary file (46.6 kB). View file
|
|
|
model_without_OpenMMLab/segformer_plusplus/configs/config/__pycache__/lazy.cpython-310.pyc
ADDED
|
Binary file (7.54 kB). View file
|
|
|
model_without_OpenMMLab/segformer_plusplus/configs/config/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|
model_without_OpenMMLab/segformer_plusplus/configs/config/config.py
ADDED
|
@@ -0,0 +1,1545 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import copy
|
| 3 |
+
import os
|
| 4 |
+
import os.path as osp
|
| 5 |
+
import platform
|
| 6 |
+
import shutil
|
| 7 |
+
import sys
|
| 8 |
+
import tempfile
|
| 9 |
+
import types
|
| 10 |
+
import uuid
|
| 11 |
+
import re
|
| 12 |
+
import warnings
|
| 13 |
+
from argparse import ArgumentParser
|
| 14 |
+
from collections import OrderedDict, abc
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any, Optional, Tuple, Union
|
| 17 |
+
from omegaconf import OmegaConf
|
| 18 |
+
import yapf
|
| 19 |
+
from addict import Dict
|
| 20 |
+
from yapf.yapflib.yapf_api import FormatCode
|
| 21 |
+
|
| 22 |
+
from .lazy import LazyAttr, LazyObject
|
| 23 |
+
from .utils import (check_file_exist, get_installed_path, import_modules_from_strings, is_installed, RemoveAssignFromAST,
|
| 24 |
+
ImportTransformer, _gather_abs_import_lazyobj, _get_external_cfg_base_path,
|
| 25 |
+
_get_external_cfg_path, _get_package_and_cfg_path, _is_builtin_module, dump)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
BASE_KEY = '_base_'
|
| 29 |
+
DELETE_KEY = '_delete_'
|
| 30 |
+
DEPRECATION_KEY = '_deprecation_'
|
| 31 |
+
RESERVED_KEYS = ['filename', 'text', 'pretty_text', 'env_variables']
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _lazy2string(cfg_dict, dict_type=None):
|
| 35 |
+
if isinstance(cfg_dict, dict):
|
| 36 |
+
dict_type = dict_type or type(cfg_dict)
|
| 37 |
+
return dict_type(
|
| 38 |
+
{k: _lazy2string(v, dict_type)
|
| 39 |
+
for k, v in dict.items(cfg_dict)})
|
| 40 |
+
elif isinstance(cfg_dict, (tuple, list)):
|
| 41 |
+
return type(cfg_dict)(_lazy2string(v, dict_type) for v in cfg_dict)
|
| 42 |
+
elif isinstance(cfg_dict, (LazyAttr, LazyObject)):
|
| 43 |
+
return f'{cfg_dict.module}.{str(cfg_dict)}'
|
| 44 |
+
else:
|
| 45 |
+
return cfg_dict
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class ConfigDict(Dict):
|
| 49 |
+
"""A dictionary for config which has the same interface as python's built-
|
| 50 |
+
in dictionary and can be used as a normal dictionary.
|
| 51 |
+
|
| 52 |
+
The Config class would transform the nested fields (dictionary-like fields)
|
| 53 |
+
in config file into ``ConfigDict``.
|
| 54 |
+
|
| 55 |
+
If the class attribute ``lazy`` is ``False``, users will get the
|
| 56 |
+
object built by ``LazyObject`` or ``LazyAttr``, otherwise users will get
|
| 57 |
+
the ``LazyObject`` or ``LazyAttr`` itself.
|
| 58 |
+
|
| 59 |
+
The ``lazy`` should be set to ``True`` to avoid building the imported
|
| 60 |
+
object during configuration parsing, and it should be set to False outside
|
| 61 |
+
the Config to ensure that users do not experience the ``LazyObject``.
|
| 62 |
+
"""
|
| 63 |
+
lazy = False
|
| 64 |
+
|
| 65 |
+
def __init__(__self, *args, **kwargs):
|
| 66 |
+
object.__setattr__(__self, '__parent', kwargs.pop('__parent', None))
|
| 67 |
+
object.__setattr__(__self, '__key', kwargs.pop('__key', None))
|
| 68 |
+
object.__setattr__(__self, '__frozen', False)
|
| 69 |
+
for arg in args:
|
| 70 |
+
if not arg:
|
| 71 |
+
continue
|
| 72 |
+
# Since ConfigDict.items will convert LazyObject to real object
|
| 73 |
+
# automatically, we need to call super().items() to make sure
|
| 74 |
+
# the LazyObject will not be converted.
|
| 75 |
+
if isinstance(arg, ConfigDict):
|
| 76 |
+
for key, val in dict.items(arg):
|
| 77 |
+
__self[key] = __self._hook(val)
|
| 78 |
+
elif isinstance(arg, dict):
|
| 79 |
+
for key, val in arg.items():
|
| 80 |
+
__self[key] = __self._hook(val)
|
| 81 |
+
elif isinstance(arg, tuple) and (not isinstance(arg[0], tuple)):
|
| 82 |
+
__self[arg[0]] = __self._hook(arg[1])
|
| 83 |
+
else:
|
| 84 |
+
for key, val in iter(arg):
|
| 85 |
+
__self[key] = __self._hook(val)
|
| 86 |
+
|
| 87 |
+
for key, val in dict.items(kwargs):
|
| 88 |
+
__self[key] = __self._hook(val)
|
| 89 |
+
|
| 90 |
+
def __missing__(self, name):
|
| 91 |
+
raise KeyError(name)
|
| 92 |
+
|
| 93 |
+
def __getattr__(self, name):
|
| 94 |
+
try:
|
| 95 |
+
value = super().__getattr__(name)
|
| 96 |
+
if isinstance(value, (LazyAttr, LazyObject)) and not self.lazy:
|
| 97 |
+
value = value.build()
|
| 98 |
+
except KeyError:
|
| 99 |
+
raise AttributeError(f"'{self.__class__.__name__}' object has no "
|
| 100 |
+
f"attribute '{name}'")
|
| 101 |
+
except Exception as e:
|
| 102 |
+
raise e
|
| 103 |
+
else:
|
| 104 |
+
return value
|
| 105 |
+
|
| 106 |
+
@classmethod
|
| 107 |
+
def _hook(cls, item):
|
| 108 |
+
# avoid to convert user defined dict to ConfigDict.
|
| 109 |
+
if type(item) in (dict, OrderedDict):
|
| 110 |
+
return cls(item)
|
| 111 |
+
elif isinstance(item, (list, tuple)):
|
| 112 |
+
return type(item)(cls._hook(elem) for elem in item)
|
| 113 |
+
return item
|
| 114 |
+
|
| 115 |
+
def __setattr__(self, name, value):
|
| 116 |
+
value = self._hook(value)
|
| 117 |
+
return super().__setattr__(name, value)
|
| 118 |
+
|
| 119 |
+
def __setitem__(self, name, value):
|
| 120 |
+
value = self._hook(value)
|
| 121 |
+
return super().__setitem__(name, value)
|
| 122 |
+
|
| 123 |
+
def __getitem__(self, key):
|
| 124 |
+
return self.build_lazy(super().__getitem__(key))
|
| 125 |
+
|
| 126 |
+
def __deepcopy__(self, memo):
|
| 127 |
+
other = self.__class__()
|
| 128 |
+
memo[id(self)] = other
|
| 129 |
+
for key, value in super().items():
|
| 130 |
+
other[copy.deepcopy(key, memo)] = copy.deepcopy(value, memo)
|
| 131 |
+
return other
|
| 132 |
+
|
| 133 |
+
def __copy__(self):
|
| 134 |
+
other = self.__class__()
|
| 135 |
+
for key, value in super().items():
|
| 136 |
+
other[key] = value
|
| 137 |
+
return other
|
| 138 |
+
|
| 139 |
+
copy = __copy__
|
| 140 |
+
|
| 141 |
+
def __iter__(self):
|
| 142 |
+
# Implement `__iter__` to overwrite the unpacking operator `**cfg_dict`
|
| 143 |
+
# to get the built lazy object
|
| 144 |
+
return iter(self.keys())
|
| 145 |
+
|
| 146 |
+
def get(self, key: str, default: Optional[Any] = None) -> Any:
|
| 147 |
+
"""Get the value of the key. If class attribute ``lazy`` is True, the
|
| 148 |
+
LazyObject will be built and returned.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
key (str): The key.
|
| 152 |
+
default (any, optional): The default value. Defaults to None.
|
| 153 |
+
|
| 154 |
+
Returns:
|
| 155 |
+
Any: The value of the key.
|
| 156 |
+
"""
|
| 157 |
+
return self.build_lazy(super().get(key, default))
|
| 158 |
+
|
| 159 |
+
def pop(self, key, default=None):
|
| 160 |
+
"""Pop the value of the key. If class attribute ``lazy`` is True, the
|
| 161 |
+
LazyObject will be built and returned.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
key (str): The key.
|
| 165 |
+
default (any, optional): The default value. Defaults to None.
|
| 166 |
+
|
| 167 |
+
Returns:
|
| 168 |
+
Any: The value of the key.
|
| 169 |
+
"""
|
| 170 |
+
return self.build_lazy(super().pop(key, default))
|
| 171 |
+
|
| 172 |
+
def update(self, *args, **kwargs) -> None:
|
| 173 |
+
"""Override this method to make sure the LazyObject will not be built
|
| 174 |
+
during updating."""
|
| 175 |
+
other = {}
|
| 176 |
+
if args:
|
| 177 |
+
if len(args) > 1:
|
| 178 |
+
raise TypeError('update only accept one positional argument')
|
| 179 |
+
# Avoid to used self.items to build LazyObject
|
| 180 |
+
for key, value in dict.items(args[0]):
|
| 181 |
+
other[key] = value
|
| 182 |
+
|
| 183 |
+
for key, value in dict(kwargs).items():
|
| 184 |
+
other[key] = value
|
| 185 |
+
for k, v in other.items():
|
| 186 |
+
if ((k not in self) or (not isinstance(self[k], dict))
|
| 187 |
+
or (not isinstance(v, dict))):
|
| 188 |
+
self[k] = self._hook(v)
|
| 189 |
+
else:
|
| 190 |
+
self[k].update(v)
|
| 191 |
+
|
| 192 |
+
def build_lazy(self, value: Any) -> Any:
|
| 193 |
+
"""If class attribute ``lazy`` is False, the LazyObject will be built
|
| 194 |
+
and returned.
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
value (Any): The value to be built.
|
| 198 |
+
|
| 199 |
+
Returns:
|
| 200 |
+
Any: The built value.
|
| 201 |
+
"""
|
| 202 |
+
if isinstance(value, (LazyAttr, LazyObject)) and not self.lazy:
|
| 203 |
+
value = value.build()
|
| 204 |
+
return value
|
| 205 |
+
|
| 206 |
+
def values(self):
|
| 207 |
+
"""Yield the values of the dictionary.
|
| 208 |
+
|
| 209 |
+
If class attribute ``lazy`` is False, the value of ``LazyObject`` or
|
| 210 |
+
``LazyAttr`` will be built and returned.
|
| 211 |
+
"""
|
| 212 |
+
values = []
|
| 213 |
+
for value in super().values():
|
| 214 |
+
values.append(self.build_lazy(value))
|
| 215 |
+
return values
|
| 216 |
+
|
| 217 |
+
def items(self):
|
| 218 |
+
"""Yield the keys and values of the dictionary.
|
| 219 |
+
|
| 220 |
+
If class attribute ``lazy`` is False, the value of ``LazyObject`` or
|
| 221 |
+
``LazyAttr`` will be built and returned.
|
| 222 |
+
"""
|
| 223 |
+
items = []
|
| 224 |
+
for key, value in super().items():
|
| 225 |
+
items.append((key, self.build_lazy(value)))
|
| 226 |
+
return items
|
| 227 |
+
|
| 228 |
+
def merge(self, other: dict):
|
| 229 |
+
"""Merge another dictionary into current dictionary.
|
| 230 |
+
|
| 231 |
+
Args:
|
| 232 |
+
other (dict): Another dictionary.
|
| 233 |
+
"""
|
| 234 |
+
default = object()
|
| 235 |
+
|
| 236 |
+
def _merge_a_into_b(a, b):
|
| 237 |
+
if isinstance(a, dict):
|
| 238 |
+
if not isinstance(b, dict):
|
| 239 |
+
a.pop(DELETE_KEY, None)
|
| 240 |
+
return a
|
| 241 |
+
if a.pop(DELETE_KEY, False):
|
| 242 |
+
b.clear()
|
| 243 |
+
all_keys = list(b.keys()) + list(a.keys())
|
| 244 |
+
return {
|
| 245 |
+
key:
|
| 246 |
+
_merge_a_into_b(a.get(key, default), b.get(key, default))
|
| 247 |
+
for key in all_keys if key != DELETE_KEY
|
| 248 |
+
}
|
| 249 |
+
else:
|
| 250 |
+
return a if a is not default else b
|
| 251 |
+
|
| 252 |
+
merged = _merge_a_into_b(copy.deepcopy(other), copy.deepcopy(self))
|
| 253 |
+
self.clear()
|
| 254 |
+
for key, value in merged.items():
|
| 255 |
+
self[key] = value
|
| 256 |
+
|
| 257 |
+
def __reduce_ex__(self):
|
| 258 |
+
# Override __reduce_ex__ to avoid `self.items` will be
|
| 259 |
+
# called by CPython interpreter during pickling. See more details in
|
| 260 |
+
# https://github.com/python/cpython/blob/8d61a71f9c81619e34d4a30b625922ebc83c561b/Objects/typeobject.c#L6196 # noqa: E501
|
| 261 |
+
from ...utils import digit_version
|
| 262 |
+
if digit_version(platform.python_version()) < digit_version('3.8'):
|
| 263 |
+
return (self.__class__, ({k: v
|
| 264 |
+
for k, v in super().items()}, ), None,
|
| 265 |
+
None, None)
|
| 266 |
+
else:
|
| 267 |
+
return (self.__class__, ({k: v
|
| 268 |
+
for k, v in super().items()}, ), None,
|
| 269 |
+
None, None, None)
|
| 270 |
+
|
| 271 |
+
def __eq__(self, other):
|
| 272 |
+
if isinstance(other, ConfigDict):
|
| 273 |
+
return other.to_dict() == self.to_dict()
|
| 274 |
+
elif isinstance(other, dict):
|
| 275 |
+
return {k: v for k, v in self.items()} == other
|
| 276 |
+
else:
|
| 277 |
+
return False
|
| 278 |
+
|
| 279 |
+
def _to_lazy_dict(self):
|
| 280 |
+
"""Convert the ConfigDict to a normal dictionary recursively, and keep
|
| 281 |
+
the ``LazyObject`` or ``LazyAttr`` object not built."""
|
| 282 |
+
|
| 283 |
+
def _to_dict(data):
|
| 284 |
+
if isinstance(data, ConfigDict):
|
| 285 |
+
return {
|
| 286 |
+
key: _to_dict(value)
|
| 287 |
+
for key, value in Dict.items(data)
|
| 288 |
+
}
|
| 289 |
+
elif isinstance(data, dict):
|
| 290 |
+
return {key: _to_dict(value) for key, value in data.items()}
|
| 291 |
+
elif isinstance(data, (list, tuple)):
|
| 292 |
+
return type(data)(_to_dict(item) for item in data)
|
| 293 |
+
else:
|
| 294 |
+
return data
|
| 295 |
+
|
| 296 |
+
return _to_dict(self)
|
| 297 |
+
|
| 298 |
+
def to_dict(self):
|
| 299 |
+
"""Convert the ConfigDict to a normal dictionary recursively, and
|
| 300 |
+
convert the ``LazyObject`` or ``LazyAttr`` to string."""
|
| 301 |
+
return _lazy2string(self, dict_type=dict)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def add_args(parser: ArgumentParser,
|
| 305 |
+
cfg: dict,
|
| 306 |
+
prefix: str = '') -> ArgumentParser:
|
| 307 |
+
"""Add config fields into argument parser.
|
| 308 |
+
|
| 309 |
+
Args:
|
| 310 |
+
parser (ArgumentParser): Argument parser.
|
| 311 |
+
cfg (dict): Config dictionary.
|
| 312 |
+
prefix (str, optional): Prefix of parser argument.
|
| 313 |
+
Defaults to ''.
|
| 314 |
+
|
| 315 |
+
Returns:
|
| 316 |
+
ArgumentParser: Argument parser containing config fields.
|
| 317 |
+
"""
|
| 318 |
+
for k, v in cfg.items():
|
| 319 |
+
if isinstance(v, str):
|
| 320 |
+
parser.add_argument('--' + prefix + k)
|
| 321 |
+
elif isinstance(v, bool):
|
| 322 |
+
parser.add_argument('--' + prefix + k, action='store_true')
|
| 323 |
+
elif isinstance(v, int):
|
| 324 |
+
parser.add_argument('--' + prefix + k, type=int)
|
| 325 |
+
elif isinstance(v, float):
|
| 326 |
+
parser.add_argument('--' + prefix + k, type=float)
|
| 327 |
+
elif isinstance(v, dict):
|
| 328 |
+
add_args(parser, v, prefix + k + '.')
|
| 329 |
+
elif isinstance(v, abc.Iterable):
|
| 330 |
+
parser.add_argument(
|
| 331 |
+
'--' + prefix + k, type=type(next(iter(v))), nargs='+')
|
| 332 |
+
return parser
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class Config:
|
| 336 |
+
"""A facility for config and config files.
|
| 337 |
+
|
| 338 |
+
It supports common file formats as configs: python/json/yaml.
|
| 339 |
+
``Config.fromfile`` can parse a dictionary from a config file, then
|
| 340 |
+
build a ``Config`` instance with the dictionary.
|
| 341 |
+
The interface is the same as a dict object and also allows access config
|
| 342 |
+
values as attributes.
|
| 343 |
+
|
| 344 |
+
Args:
|
| 345 |
+
cfg_dict (dict, optional): A config dictionary. Defaults to None.
|
| 346 |
+
cfg_text (str, optional): Text of config. Defaults to None.
|
| 347 |
+
filename (str or Path, optional): Name of config file.
|
| 348 |
+
Defaults to None.
|
| 349 |
+
format_python_code (bool): Whether to format Python code by yapf.
|
| 350 |
+
Defaults to True.
|
| 351 |
+
""" # noqa: E501
|
| 352 |
+
|
| 353 |
+
def __init__(
|
| 354 |
+
self,
|
| 355 |
+
cfg_dict: Optional[dict] = None,
|
| 356 |
+
cfg_text: Optional[str] = None,
|
| 357 |
+
filename: Optional[Union[str, Path]] = None,
|
| 358 |
+
env_variables: Optional[dict] = None,
|
| 359 |
+
format_python_code: bool = True,
|
| 360 |
+
):
|
| 361 |
+
filename = str(filename) if isinstance(filename, Path) else filename
|
| 362 |
+
if cfg_dict is None:
|
| 363 |
+
cfg_dict = dict()
|
| 364 |
+
elif not isinstance(cfg_dict, dict):
|
| 365 |
+
raise TypeError('cfg_dict must be a dict, but '
|
| 366 |
+
f'got {type(cfg_dict)}')
|
| 367 |
+
for key in cfg_dict:
|
| 368 |
+
if key in RESERVED_KEYS:
|
| 369 |
+
raise KeyError(f'{key} is reserved for config file')
|
| 370 |
+
|
| 371 |
+
if not isinstance(cfg_dict, ConfigDict):
|
| 372 |
+
cfg_dict = ConfigDict(cfg_dict)
|
| 373 |
+
super().__setattr__('_cfg_dict', cfg_dict)
|
| 374 |
+
super().__setattr__('_filename', filename)
|
| 375 |
+
super().__setattr__('_format_python_code', format_python_code)
|
| 376 |
+
if not hasattr(self, '_imported_names'):
|
| 377 |
+
super().__setattr__('_imported_names', set())
|
| 378 |
+
|
| 379 |
+
if cfg_text:
|
| 380 |
+
text = cfg_text
|
| 381 |
+
elif filename:
|
| 382 |
+
with open(filename, encoding='utf-8') as f:
|
| 383 |
+
text = f.read()
|
| 384 |
+
else:
|
| 385 |
+
text = ''
|
| 386 |
+
super().__setattr__('_text', text)
|
| 387 |
+
if env_variables is None:
|
| 388 |
+
env_variables = dict()
|
| 389 |
+
super().__setattr__('_env_variables', env_variables)
|
| 390 |
+
|
| 391 |
+
@staticmethod
|
| 392 |
+
def fromfile(filename: Union[str, Path],
|
| 393 |
+
use_predefined_variables: bool = True,
|
| 394 |
+
import_custom_modules: bool = True,
|
| 395 |
+
use_environment_variables: bool = True,
|
| 396 |
+
lazy_import: Optional[bool] = None,
|
| 397 |
+
format_python_code: bool = True) -> 'Config':
|
| 398 |
+
"""Build a Config instance from config file.
|
| 399 |
+
|
| 400 |
+
Args:
|
| 401 |
+
filename (str or Path): Name of config file.
|
| 402 |
+
use_predefined_variables (bool, optional): Whether to use
|
| 403 |
+
predefined variables. Defaults to True.
|
| 404 |
+
import_custom_modules (bool, optional): Whether to support
|
| 405 |
+
importing custom modules in config. Defaults to None.
|
| 406 |
+
use_environment_variables (bool, optional): Whether to use
|
| 407 |
+
environment variables. Defaults to True.
|
| 408 |
+
lazy_import (bool): Whether to load config in `lazy_import` mode.
|
| 409 |
+
If it is `None`, it will be deduced by the content of the
|
| 410 |
+
config file. Defaults to None.
|
| 411 |
+
format_python_code (bool): Whether to format Python code by yapf.
|
| 412 |
+
Defaults to True.
|
| 413 |
+
|
| 414 |
+
Returns:
|
| 415 |
+
Config: Config instance built from config file.
|
| 416 |
+
"""
|
| 417 |
+
filename = str(filename) if isinstance(filename, Path) else filename
|
| 418 |
+
if lazy_import is False or \
|
| 419 |
+
lazy_import is None and not Config._is_lazy_import(filename):
|
| 420 |
+
cfg_dict, cfg_text, env_variables = Config._file2dict(
|
| 421 |
+
filename, use_predefined_variables, use_environment_variables,
|
| 422 |
+
lazy_import)
|
| 423 |
+
if import_custom_modules and cfg_dict.get('custom_imports', None):
|
| 424 |
+
try:
|
| 425 |
+
import_modules_from_strings(**cfg_dict['custom_imports'])
|
| 426 |
+
except ImportError as e:
|
| 427 |
+
err_msg = (
|
| 428 |
+
'Failed to import custom modules from '
|
| 429 |
+
f"{cfg_dict['custom_imports']}, the current sys.path "
|
| 430 |
+
'is: ')
|
| 431 |
+
for p in sys.path:
|
| 432 |
+
err_msg += f'\n {p}'
|
| 433 |
+
err_msg += (
|
| 434 |
+
'\nYou should set `PYTHONPATH` to make `sys.path` '
|
| 435 |
+
'include the directory which contains your custom '
|
| 436 |
+
'module')
|
| 437 |
+
raise ImportError(err_msg) from e
|
| 438 |
+
return Config(
|
| 439 |
+
cfg_dict,
|
| 440 |
+
cfg_text=cfg_text,
|
| 441 |
+
filename=filename,
|
| 442 |
+
env_variables=env_variables,
|
| 443 |
+
)
|
| 444 |
+
else:
|
| 445 |
+
# Enable lazy import when parsing the config.
|
| 446 |
+
# Using try-except to make sure ``ConfigDict.lazy`` will be reset
|
| 447 |
+
# to False. See more details about lazy in the docstring of
|
| 448 |
+
# ConfigDict
|
| 449 |
+
ConfigDict.lazy = True
|
| 450 |
+
try:
|
| 451 |
+
cfg_dict, imported_names = Config._parse_lazy_import(filename)
|
| 452 |
+
except Exception as e:
|
| 453 |
+
raise e
|
| 454 |
+
finally:
|
| 455 |
+
# disable lazy import to get the real type. See more details
|
| 456 |
+
# about lazy in the docstring of ConfigDict
|
| 457 |
+
ConfigDict.lazy = False
|
| 458 |
+
|
| 459 |
+
cfg = Config(
|
| 460 |
+
cfg_dict,
|
| 461 |
+
filename=filename,
|
| 462 |
+
format_python_code=format_python_code)
|
| 463 |
+
object.__setattr__(cfg, '_imported_names', imported_names)
|
| 464 |
+
return cfg
|
| 465 |
+
|
| 466 |
+
@staticmethod
|
| 467 |
+
def _get_base_modules(nodes: list) -> list:
|
| 468 |
+
"""Get base module name from parsed code.
|
| 469 |
+
|
| 470 |
+
Args:
|
| 471 |
+
nodes (list): Parsed code of the config file.
|
| 472 |
+
|
| 473 |
+
Returns:
|
| 474 |
+
list: Name of base modules.
|
| 475 |
+
"""
|
| 476 |
+
|
| 477 |
+
def _get_base_module_from_with(with_nodes: list) -> list:
|
| 478 |
+
"""Get base module name from if statement in python file.
|
| 479 |
+
|
| 480 |
+
Args:
|
| 481 |
+
with_nodes (list): List of if statement.
|
| 482 |
+
|
| 483 |
+
Returns:
|
| 484 |
+
list: Name of base modules.
|
| 485 |
+
"""
|
| 486 |
+
base_modules = []
|
| 487 |
+
for node in with_nodes:
|
| 488 |
+
assert isinstance(node, ast.ImportFrom), (
|
| 489 |
+
'Illegal syntax in config file! Only '
|
| 490 |
+
'`from ... import ...` could be implemented` in '
|
| 491 |
+
'with read_base()`')
|
| 492 |
+
assert node.module is not None, (
|
| 493 |
+
'Illegal syntax in config file! Syntax like '
|
| 494 |
+
'`from . import xxx` is not allowed in `with read_base()`')
|
| 495 |
+
base_modules.append(node.level * '.' + node.module)
|
| 496 |
+
return base_modules
|
| 497 |
+
|
| 498 |
+
for idx, node in enumerate(nodes):
|
| 499 |
+
if (isinstance(node, ast.Assign)
|
| 500 |
+
and isinstance(node.targets[0], ast.Name)
|
| 501 |
+
and node.targets[0].id == BASE_KEY):
|
| 502 |
+
raise SyntaxError(
|
| 503 |
+
'The configuration file type in the inheritance chain '
|
| 504 |
+
'must match the current configuration file type, either '
|
| 505 |
+
'"lazy_import" or non-"lazy_import". You got this error '
|
| 506 |
+
f'since you use the syntax like `_base_ = "{node.targets[0].id}"` ' # noqa: E501
|
| 507 |
+
'in your config. You should use `with read_base(): ... to` ' # noqa: E501
|
| 508 |
+
'mark the inherited config file. See more information '# noqa: E501
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
if not isinstance(node, ast.With):
|
| 512 |
+
continue
|
| 513 |
+
|
| 514 |
+
expr = node.items[0].context_expr
|
| 515 |
+
if (not isinstance(expr, ast.Call)
|
| 516 |
+
or not expr.func.id == 'read_base' or # type: ignore
|
| 517 |
+
len(node.items) > 1):
|
| 518 |
+
raise SyntaxError(
|
| 519 |
+
'Only `read_base` context manager can be used in the '
|
| 520 |
+
'config')
|
| 521 |
+
for nested_idx, nested_node in enumerate(node.body):
|
| 522 |
+
nodes.insert(idx + nested_idx + 1, nested_node)
|
| 523 |
+
nodes.pop(idx)
|
| 524 |
+
return _get_base_module_from_with(node.body)
|
| 525 |
+
return []
|
| 526 |
+
|
| 527 |
+
@staticmethod
|
| 528 |
+
def _validate_py_syntax(filename: str):
|
| 529 |
+
"""Validate syntax of python config.
|
| 530 |
+
|
| 531 |
+
Args:
|
| 532 |
+
filename (str): Filename of python config file.
|
| 533 |
+
"""
|
| 534 |
+
with open(filename, encoding='utf-8') as f:
|
| 535 |
+
content = f.read()
|
| 536 |
+
try:
|
| 537 |
+
ast.parse(content)
|
| 538 |
+
except SyntaxError as e:
|
| 539 |
+
raise SyntaxError('There are syntax errors in config '
|
| 540 |
+
f'file {filename}: {e}')
|
| 541 |
+
|
| 542 |
+
@staticmethod
|
| 543 |
+
def _substitute_predefined_vars(filename: str, temp_config_name: str):
|
| 544 |
+
"""Substitute predefined variables in config with actual values.
|
| 545 |
+
|
| 546 |
+
Sometimes we want some variables in the config to be related to the
|
| 547 |
+
current path or file name, etc.
|
| 548 |
+
|
| 549 |
+
Here is an example of a typical usage scenario. When training a model,
|
| 550 |
+
we define a working directory in the config that save the models and
|
| 551 |
+
logs. For different configs, we expect to define different working
|
| 552 |
+
directories. A common way for users is to use the config file name
|
| 553 |
+
directly as part of the working directory name, e.g. for the config
|
| 554 |
+
``config_setting1.py``, the working directory is
|
| 555 |
+
``. /work_dir/config_setting1``.
|
| 556 |
+
|
| 557 |
+
This can be easily achieved using predefined variables, which can be
|
| 558 |
+
written in the config `config_setting1.py` as follows
|
| 559 |
+
|
| 560 |
+
.. code-block:: python
|
| 561 |
+
|
| 562 |
+
work_dir = '. /work_dir/{{ fileBasenameNoExtension }}'
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
Here `{{ fileBasenameNoExtension }}` indicates the file name of the
|
| 566 |
+
config (without the extension), and when the config class reads the
|
| 567 |
+
config file, it will automatically parse this double-bracketed string
|
| 568 |
+
to the corresponding actual value.
|
| 569 |
+
|
| 570 |
+
.. code-block:: python
|
| 571 |
+
|
| 572 |
+
cfg = Config.fromfile('. /config_setting1.py')
|
| 573 |
+
cfg.work_dir # ". /work_dir/config_setting1"
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
For details, Please refer to docs/zh_cn/advanced_tutorials/config.md .
|
| 577 |
+
|
| 578 |
+
Args:
|
| 579 |
+
filename (str): Filename of config.
|
| 580 |
+
temp_config_name (str): Temporary filename to save substituted
|
| 581 |
+
config.
|
| 582 |
+
"""
|
| 583 |
+
file_dirname = osp.dirname(filename)
|
| 584 |
+
file_basename = osp.basename(filename)
|
| 585 |
+
file_basename_no_extension = osp.splitext(file_basename)[0]
|
| 586 |
+
file_extname = osp.splitext(filename)[1]
|
| 587 |
+
support_templates = dict(
|
| 588 |
+
fileDirname=file_dirname,
|
| 589 |
+
fileBasename=file_basename,
|
| 590 |
+
fileBasenameNoExtension=file_basename_no_extension,
|
| 591 |
+
fileExtname=file_extname)
|
| 592 |
+
with open(filename, encoding='utf-8') as f:
|
| 593 |
+
config_file = f.read()
|
| 594 |
+
for key, value in support_templates.items():
|
| 595 |
+
regexp = r'\{\{\s*' + str(key) + r'\s*\}\}'
|
| 596 |
+
value = value.replace('\\', '/')
|
| 597 |
+
config_file = re.sub(regexp, value, config_file)
|
| 598 |
+
with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file:
|
| 599 |
+
tmp_config_file.write(config_file)
|
| 600 |
+
|
| 601 |
+
@staticmethod
|
| 602 |
+
def _substitute_env_variables(filename: str, temp_config_name: str):
|
| 603 |
+
"""Substitute environment variables in config with actual values.
|
| 604 |
+
|
| 605 |
+
Sometimes, we want to change some items in the config with environment
|
| 606 |
+
variables. For examples, we expect to change dataset root by setting
|
| 607 |
+
``DATASET_ROOT=/dataset/root/path`` in the command line. This can be
|
| 608 |
+
easily achieved by writing lines in the config as follows
|
| 609 |
+
|
| 610 |
+
.. code-block:: python
|
| 611 |
+
|
| 612 |
+
data_root = '{{$DATASET_ROOT:/default/dataset}}/images'
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
Here, ``{{$DATASET_ROOT:/default/dataset}}`` indicates using the
|
| 616 |
+
environment variable ``DATASET_ROOT`` to replace the part between
|
| 617 |
+
``{{}}``. If the ``DATASET_ROOT`` is not set, the default value
|
| 618 |
+
``/default/dataset`` will be used.
|
| 619 |
+
|
| 620 |
+
Environment variables not only can replace items in the string, they
|
| 621 |
+
can also substitute other types of data in config. In this situation,
|
| 622 |
+
we can write the config as below
|
| 623 |
+
|
| 624 |
+
.. code-block:: python
|
| 625 |
+
|
| 626 |
+
model = dict(
|
| 627 |
+
bbox_head = dict(num_classes={{'$NUM_CLASSES:80'}}))
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
For details, Please refer to docs/zh_cn/tutorials/config.md .
|
| 631 |
+
|
| 632 |
+
Args:
|
| 633 |
+
filename (str): Filename of config.
|
| 634 |
+
temp_config_name (str): Temporary filename to save substituted
|
| 635 |
+
config.
|
| 636 |
+
"""
|
| 637 |
+
with open(filename, encoding='utf-8') as f:
|
| 638 |
+
config_file = f.read()
|
| 639 |
+
regexp = r'\{\{[\'\"]?\s*\$(\w+)\s*\:\s*(\S*?)\s*[\'\"]?\}\}'
|
| 640 |
+
keys = re.findall(regexp, config_file)
|
| 641 |
+
env_variables = dict()
|
| 642 |
+
for var_name, value in keys:
|
| 643 |
+
regexp = r'\{\{[\'\"]?\s*\$' + var_name + r'\s*\:\s*' \
|
| 644 |
+
+ value + r'\s*[\'\"]?\}\}'
|
| 645 |
+
if var_name in os.environ:
|
| 646 |
+
value = os.environ[var_name]
|
| 647 |
+
env_variables[var_name] = value
|
| 648 |
+
if not value:
|
| 649 |
+
raise KeyError(f'`{var_name}` cannot be found in `os.environ`.'
|
| 650 |
+
f' Please set `{var_name}` in environment or '
|
| 651 |
+
'give a default value.')
|
| 652 |
+
config_file = re.sub(regexp, value, config_file)
|
| 653 |
+
|
| 654 |
+
with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file:
|
| 655 |
+
tmp_config_file.write(config_file)
|
| 656 |
+
return env_variables
|
| 657 |
+
|
| 658 |
+
@staticmethod
|
| 659 |
+
def _pre_substitute_base_vars(filename: str,
|
| 660 |
+
temp_config_name: str) -> dict:
|
| 661 |
+
"""Preceding step for substituting variables in base config with actual
|
| 662 |
+
value.
|
| 663 |
+
|
| 664 |
+
Args:
|
| 665 |
+
filename (str): Filename of config.
|
| 666 |
+
temp_config_name (str): Temporary filename to save substituted
|
| 667 |
+
config.
|
| 668 |
+
|
| 669 |
+
Returns:
|
| 670 |
+
dict: A dictionary contains variables in base config.
|
| 671 |
+
"""
|
| 672 |
+
with open(filename, encoding='utf-8') as f:
|
| 673 |
+
config_file = f.read()
|
| 674 |
+
base_var_dict = {}
|
| 675 |
+
regexp = r'\{\{\s*' + BASE_KEY + r'\.([\w\.]+)\s*\}\}'
|
| 676 |
+
base_vars = set(re.findall(regexp, config_file))
|
| 677 |
+
for base_var in base_vars:
|
| 678 |
+
randstr = f'_{base_var}_{uuid.uuid4().hex.lower()[:6]}'
|
| 679 |
+
base_var_dict[randstr] = base_var
|
| 680 |
+
regexp = r'\{\{\s*' + BASE_KEY + r'\.' + base_var + r'\s*\}\}'
|
| 681 |
+
config_file = re.sub(regexp, f'"{randstr}"', config_file)
|
| 682 |
+
with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file:
|
| 683 |
+
tmp_config_file.write(config_file)
|
| 684 |
+
return base_var_dict
|
| 685 |
+
|
| 686 |
+
@staticmethod
|
| 687 |
+
def _substitute_base_vars(cfg: Any, base_var_dict: dict,
|
| 688 |
+
base_cfg: dict) -> Any:
|
| 689 |
+
"""Substitute base variables from strings to their actual values.
|
| 690 |
+
|
| 691 |
+
Args:
|
| 692 |
+
Any : Config dictionary.
|
| 693 |
+
base_var_dict (dict): A dictionary contains variables in base
|
| 694 |
+
config.
|
| 695 |
+
base_cfg (dict): Base config dictionary.
|
| 696 |
+
|
| 697 |
+
Returns:
|
| 698 |
+
Any : A dictionary with origin base variables
|
| 699 |
+
substituted with actual values.
|
| 700 |
+
"""
|
| 701 |
+
cfg = copy.deepcopy(cfg)
|
| 702 |
+
|
| 703 |
+
if isinstance(cfg, dict):
|
| 704 |
+
for k, v in cfg.items():
|
| 705 |
+
if isinstance(v, str) and v in base_var_dict:
|
| 706 |
+
new_v = base_cfg
|
| 707 |
+
for new_k in base_var_dict[v].split('.'):
|
| 708 |
+
new_v = new_v[new_k]
|
| 709 |
+
cfg[k] = new_v
|
| 710 |
+
elif isinstance(v, (list, tuple, dict)):
|
| 711 |
+
cfg[k] = Config._substitute_base_vars(
|
| 712 |
+
v, base_var_dict, base_cfg)
|
| 713 |
+
elif isinstance(cfg, tuple):
|
| 714 |
+
cfg = tuple(
|
| 715 |
+
Config._substitute_base_vars(c, base_var_dict, base_cfg)
|
| 716 |
+
for c in cfg)
|
| 717 |
+
elif isinstance(cfg, list):
|
| 718 |
+
cfg = [
|
| 719 |
+
Config._substitute_base_vars(c, base_var_dict, base_cfg)
|
| 720 |
+
for c in cfg
|
| 721 |
+
]
|
| 722 |
+
elif isinstance(cfg, str) and cfg in base_var_dict:
|
| 723 |
+
new_v = base_cfg
|
| 724 |
+
for new_k in base_var_dict[cfg].split('.'):
|
| 725 |
+
new_v = new_v[new_k]
|
| 726 |
+
cfg = new_v
|
| 727 |
+
|
| 728 |
+
return cfg
|
| 729 |
+
|
| 730 |
+
@staticmethod
|
| 731 |
+
def _file2dict(
|
| 732 |
+
filename: str,
|
| 733 |
+
use_predefined_variables: bool = True,
|
| 734 |
+
use_environment_variables: bool = True,
|
| 735 |
+
lazy_import: Optional[bool] = None) -> Tuple[dict, str, dict]:
|
| 736 |
+
"""Transform file to variables dictionary.
|
| 737 |
+
|
| 738 |
+
Args:
|
| 739 |
+
filename (str): Name of config file.
|
| 740 |
+
use_predefined_variables (bool, optional): Whether to use
|
| 741 |
+
predefined variables. Defaults to True.
|
| 742 |
+
use_environment_variables (bool, optional): Whether to use
|
| 743 |
+
environment variables. Defaults to True.
|
| 744 |
+
lazy_import (bool): Whether to load config in `lazy_import` mode.
|
| 745 |
+
If it is `None`, it will be deduced by the content of the
|
| 746 |
+
config file. Defaults to None.
|
| 747 |
+
|
| 748 |
+
Returns:
|
| 749 |
+
Tuple[dict, str]: Variables dictionary and text of Config.
|
| 750 |
+
"""
|
| 751 |
+
if lazy_import is None and Config._is_lazy_import(filename):
|
| 752 |
+
raise RuntimeError(
|
| 753 |
+
'The configuration file type in the inheritance chain '
|
| 754 |
+
'must match the current configuration file type, either '
|
| 755 |
+
'"lazy_import" or non-"lazy_import". You got this error '
|
| 756 |
+
'since you use the syntax like `with read_base(): ...` '
|
| 757 |
+
f'or import non-builtin module in {filename}.' # noqa: E501
|
| 758 |
+
)
|
| 759 |
+
|
| 760 |
+
filename = osp.abspath(osp.expanduser(filename))
|
| 761 |
+
check_file_exist(filename)
|
| 762 |
+
fileExtname = osp.splitext(filename)[1]
|
| 763 |
+
if fileExtname not in ['.py', '.json', '.yaml', '.yml']:
|
| 764 |
+
raise OSError('Only py/yml/yaml/json type are supported now!')
|
| 765 |
+
try:
|
| 766 |
+
with tempfile.TemporaryDirectory() as temp_config_dir:
|
| 767 |
+
temp_config_file = tempfile.NamedTemporaryFile(
|
| 768 |
+
dir=temp_config_dir, suffix=fileExtname, delete=False)
|
| 769 |
+
if platform.system() == 'Windows':
|
| 770 |
+
temp_config_file.close()
|
| 771 |
+
|
| 772 |
+
# Substitute predefined variables
|
| 773 |
+
if use_predefined_variables:
|
| 774 |
+
Config._substitute_predefined_vars(filename,
|
| 775 |
+
temp_config_file.name)
|
| 776 |
+
else:
|
| 777 |
+
shutil.copyfile(filename, temp_config_file.name)
|
| 778 |
+
# Substitute environment variables
|
| 779 |
+
env_variables = dict()
|
| 780 |
+
if use_environment_variables:
|
| 781 |
+
env_variables = Config._substitute_env_variables(
|
| 782 |
+
temp_config_file.name, temp_config_file.name)
|
| 783 |
+
# Substitute base variables from placeholders to strings
|
| 784 |
+
base_var_dict = Config._pre_substitute_base_vars(
|
| 785 |
+
temp_config_file.name, temp_config_file.name)
|
| 786 |
+
|
| 787 |
+
# Handle base files
|
| 788 |
+
base_cfg_dict = ConfigDict()
|
| 789 |
+
cfg_text_list = list()
|
| 790 |
+
for base_cfg_path in Config._get_base_files(
|
| 791 |
+
temp_config_file.name):
|
| 792 |
+
base_cfg_path, scope = Config._get_cfg_path(
|
| 793 |
+
base_cfg_path, filename)
|
| 794 |
+
_cfg_dict, _cfg_text, _env_variables = Config._file2dict(
|
| 795 |
+
filename=base_cfg_path,
|
| 796 |
+
use_predefined_variables=use_predefined_variables,
|
| 797 |
+
use_environment_variables=use_environment_variables,
|
| 798 |
+
lazy_import=lazy_import,
|
| 799 |
+
)
|
| 800 |
+
cfg_text_list.append(_cfg_text)
|
| 801 |
+
env_variables.update(_env_variables)
|
| 802 |
+
duplicate_keys = base_cfg_dict.keys() & _cfg_dict.keys()
|
| 803 |
+
if len(duplicate_keys) > 0:
|
| 804 |
+
raise KeyError(
|
| 805 |
+
'Duplicate key is not allowed among bases. '
|
| 806 |
+
f'Duplicate keys: {duplicate_keys}')
|
| 807 |
+
|
| 808 |
+
# _dict_to_config_dict will do the following things:
|
| 809 |
+
# 1. Recursively converts ``dict`` to :obj:`ConfigDict`.
|
| 810 |
+
# 2. Set `_scope_` for the outer dict variable for the base
|
| 811 |
+
# config.
|
| 812 |
+
# 3. Set `scope` attribute for each base variable.
|
| 813 |
+
# Different from `_scope_`, `scope` is not a key of base
|
| 814 |
+
# dict, `scope` attribute will be parsed to key `_scope_`
|
| 815 |
+
# by function `_parse_scope` only if the base variable is
|
| 816 |
+
# accessed by the current config.
|
| 817 |
+
_cfg_dict = Config._dict_to_config_dict(_cfg_dict, scope)
|
| 818 |
+
base_cfg_dict.update(_cfg_dict)
|
| 819 |
+
|
| 820 |
+
if filename.endswith('.py'):
|
| 821 |
+
with open(temp_config_file.name, encoding='utf-8') as f:
|
| 822 |
+
parsed_codes = ast.parse(f.read())
|
| 823 |
+
parsed_codes = RemoveAssignFromAST(BASE_KEY).visit(
|
| 824 |
+
parsed_codes)
|
| 825 |
+
codeobj = compile(parsed_codes, filename, mode='exec')
|
| 826 |
+
# Support load global variable in nested function of the
|
| 827 |
+
# config.
|
| 828 |
+
global_locals_var = {BASE_KEY: base_cfg_dict}
|
| 829 |
+
ori_keys = set(global_locals_var.keys())
|
| 830 |
+
eval(codeobj, global_locals_var, global_locals_var)
|
| 831 |
+
cfg_dict = {
|
| 832 |
+
key: value
|
| 833 |
+
for key, value in global_locals_var.items()
|
| 834 |
+
if (key not in ori_keys and not key.startswith('__'))
|
| 835 |
+
}
|
| 836 |
+
elif filename.endswith(('.yml', '.yaml', '.json')):
|
| 837 |
+
cfg = OmegaConf.load(temp_config_file.name)
|
| 838 |
+
cfg_dict = OmegaConf.to_container(cfg, resolve=True)
|
| 839 |
+
# close temp file
|
| 840 |
+
for key, value in list(cfg_dict.items()):
|
| 841 |
+
if isinstance(value,
|
| 842 |
+
(types.FunctionType, types.ModuleType)):
|
| 843 |
+
cfg_dict.pop(key)
|
| 844 |
+
temp_config_file.close()
|
| 845 |
+
|
| 846 |
+
# If the current config accesses a base variable of base
|
| 847 |
+
# configs, The ``scope`` attribute of corresponding variable
|
| 848 |
+
# will be converted to the `_scope_`.
|
| 849 |
+
Config._parse_scope(cfg_dict)
|
| 850 |
+
except Exception as e:
|
| 851 |
+
if osp.exists(temp_config_dir):
|
| 852 |
+
shutil.rmtree(temp_config_dir)
|
| 853 |
+
raise e
|
| 854 |
+
|
| 855 |
+
# check deprecation information
|
| 856 |
+
if DEPRECATION_KEY in cfg_dict:
|
| 857 |
+
deprecation_info = cfg_dict.pop(DEPRECATION_KEY)
|
| 858 |
+
warning_msg = f'The config file {filename} will be deprecated ' \
|
| 859 |
+
'in the future.'
|
| 860 |
+
if 'expected' in deprecation_info:
|
| 861 |
+
warning_msg += f' Please use {deprecation_info["expected"]} ' \
|
| 862 |
+
'instead.'
|
| 863 |
+
if 'reference' in deprecation_info:
|
| 864 |
+
warning_msg += ' More information can be found at ' \
|
| 865 |
+
f'{deprecation_info["reference"]}'
|
| 866 |
+
warnings.warn(warning_msg, DeprecationWarning)
|
| 867 |
+
|
| 868 |
+
cfg_text = filename + '\n'
|
| 869 |
+
with open(filename, encoding='utf-8') as f:
|
| 870 |
+
# Setting encoding explicitly to resolve coding issue on windows
|
| 871 |
+
cfg_text += f.read()
|
| 872 |
+
|
| 873 |
+
# Substitute base variables from strings to their actual values
|
| 874 |
+
cfg_dict = Config._substitute_base_vars(cfg_dict, base_var_dict,
|
| 875 |
+
base_cfg_dict)
|
| 876 |
+
cfg_dict.pop(BASE_KEY, None)
|
| 877 |
+
|
| 878 |
+
cfg_dict = Config._merge_a_into_b(cfg_dict, base_cfg_dict)
|
| 879 |
+
cfg_dict = {
|
| 880 |
+
k: v
|
| 881 |
+
for k, v in cfg_dict.items() if not k.startswith('__')
|
| 882 |
+
}
|
| 883 |
+
|
| 884 |
+
# merge cfg_text
|
| 885 |
+
cfg_text_list.append(cfg_text)
|
| 886 |
+
cfg_text = '\n'.join(cfg_text_list)
|
| 887 |
+
|
| 888 |
+
return cfg_dict, cfg_text, env_variables
|
| 889 |
+
|
| 890 |
+
@staticmethod
|
| 891 |
+
def _parse_lazy_import(filename: str) -> Tuple[ConfigDict, set]:
|
| 892 |
+
"""Transform file to variables dictionary.
|
| 893 |
+
|
| 894 |
+
Args:
|
| 895 |
+
filename (str): Name of config file.
|
| 896 |
+
|
| 897 |
+
Returns:
|
| 898 |
+
Tuple[dict, dict]: ``cfg_dict`` and ``imported_names``.
|
| 899 |
+
|
| 900 |
+
- cfg_dict (dict): Variables dictionary of parsed config.
|
| 901 |
+
- imported_names (set): Used to mark the names of
|
| 902 |
+
imported object.
|
| 903 |
+
"""
|
| 904 |
+
# In lazy import mode, users can use the Python syntax `import` to
|
| 905 |
+
# implement inheritance between configuration files, which is easier
|
| 906 |
+
# for users to understand the hierarchical relationships between
|
| 907 |
+
# different configuration files.
|
| 908 |
+
|
| 909 |
+
# Besides, users can also using `import` syntax to import corresponding
|
| 910 |
+
# module which will be filled in the `type` field. It means users
|
| 911 |
+
# can directly navigate to the source of the module in the
|
| 912 |
+
# configuration file by clicking the `type` field.
|
| 913 |
+
|
| 914 |
+
# To avoid really importing the third party package like `torch`
|
| 915 |
+
# during import `type` object, we use `_parse_lazy_import` to parse the
|
| 916 |
+
# configuration file, which will not actually trigger the import
|
| 917 |
+
# process, but simply parse the imported `type`s as LazyObject objects.
|
| 918 |
+
|
| 919 |
+
# The overall pipeline of _parse_lazy_import is:
|
| 920 |
+
# 1. Parse the base module from the config file.
|
| 921 |
+
# ||
|
| 922 |
+
# \/
|
| 923 |
+
# base_module = ['mmdet.configs.default_runtime']
|
| 924 |
+
# ||
|
| 925 |
+
# \/
|
| 926 |
+
# 2. recursively parse the base module and gather imported objects to
|
| 927 |
+
# a dict.
|
| 928 |
+
# ||
|
| 929 |
+
# \/
|
| 930 |
+
# The base_dict will be:
|
| 931 |
+
# {
|
| 932 |
+
# 'mmdet.configs.default_runtime': {...}
|
| 933 |
+
# 'mmdet.configs.retinanet_r50_fpn_1x_coco': {...}
|
| 934 |
+
# ...
|
| 935 |
+
# }, each item in base_dict is a dict of `LazyObject`
|
| 936 |
+
# 3. parse the current config file filling the imported variable
|
| 937 |
+
# with the base_dict.
|
| 938 |
+
#
|
| 939 |
+
# 4. During the parsing process, all imported variable will be
|
| 940 |
+
# recorded in the `imported_names` set. These variables can be
|
| 941 |
+
# accessed, but will not be dumped by default.
|
| 942 |
+
|
| 943 |
+
with open(filename, encoding='utf-8') as f:
|
| 944 |
+
global_dict = {'LazyObject': LazyObject, '__file__': filename}
|
| 945 |
+
base_dict = {}
|
| 946 |
+
|
| 947 |
+
parsed_codes = ast.parse(f.read())
|
| 948 |
+
# get the names of base modules, and remove the
|
| 949 |
+
# `with read_base():'` statement
|
| 950 |
+
base_modules = Config._get_base_modules(parsed_codes.body)
|
| 951 |
+
base_imported_names = set()
|
| 952 |
+
for base_module in base_modules:
|
| 953 |
+
# If base_module means a relative import, assuming the level is
|
| 954 |
+
# 2, which means the module is imported like
|
| 955 |
+
# "from ..a.b import c". we must ensure that c is an
|
| 956 |
+
# object `defined` in module b, and module b should not be a
|
| 957 |
+
# package including `__init__` file but a single python file.
|
| 958 |
+
level = len(re.match(r'\.*', base_module).group())
|
| 959 |
+
if level > 0:
|
| 960 |
+
# Relative import
|
| 961 |
+
base_dir = osp.dirname(filename)
|
| 962 |
+
module_path = osp.join(
|
| 963 |
+
base_dir, *(['..'] * (level - 1)),
|
| 964 |
+
f'{base_module[level:].replace(".", "/")}.py')
|
| 965 |
+
else:
|
| 966 |
+
# Absolute import
|
| 967 |
+
module_list = base_module.split('.')
|
| 968 |
+
if len(module_list) == 1:
|
| 969 |
+
raise SyntaxError(
|
| 970 |
+
'The imported configuration file should not be '
|
| 971 |
+
f'an independent package {module_list[0]}. Here '
|
| 972 |
+
'is an example: '
|
| 973 |
+
'`with read_base(): from mmdet.configs.retinanet_r50_fpn_1x_coco import *`' # noqa: E501
|
| 974 |
+
)
|
| 975 |
+
else:
|
| 976 |
+
package = module_list[0]
|
| 977 |
+
root_path = get_installed_path(package)
|
| 978 |
+
module_path = f'{osp.join(root_path, *module_list[1:])}.py' # noqa: E501
|
| 979 |
+
if not osp.isfile(module_path):
|
| 980 |
+
raise SyntaxError(
|
| 981 |
+
f'{module_path} not found! It means that incorrect '
|
| 982 |
+
'module is defined in '
|
| 983 |
+
f'`with read_base(): = from {base_module} import ...`, please ' # noqa: E501
|
| 984 |
+
'make sure the base config module is valid '
|
| 985 |
+
'and is consistent with the prior import '
|
| 986 |
+
'logic')
|
| 987 |
+
_base_cfg_dict, _base_imported_names = Config._parse_lazy_import( # noqa: E501
|
| 988 |
+
module_path)
|
| 989 |
+
base_imported_names |= _base_imported_names
|
| 990 |
+
# The base_dict will be:
|
| 991 |
+
# {
|
| 992 |
+
# 'mmdet.configs.default_runtime': {...}
|
| 993 |
+
# 'mmdet.configs.retinanet_r50_fpn_1x_coco': {...}
|
| 994 |
+
# ...
|
| 995 |
+
# }
|
| 996 |
+
base_dict[base_module] = _base_cfg_dict
|
| 997 |
+
|
| 998 |
+
# `base_dict` contains all the imported modules from `base_cfg`.
|
| 999 |
+
# In order to collect the specific imported module from `base_cfg`
|
| 1000 |
+
# before parse the current file, we using AST Transform to
|
| 1001 |
+
# transverse the imported module from base_cfg and merge then into
|
| 1002 |
+
# the global dict. After the ast transformation, most of import
|
| 1003 |
+
# syntax will be removed (except for the builtin import) and
|
| 1004 |
+
# replaced with the `LazyObject`
|
| 1005 |
+
transform = ImportTransformer(
|
| 1006 |
+
global_dict=global_dict,
|
| 1007 |
+
base_dict=base_dict,
|
| 1008 |
+
filename=filename)
|
| 1009 |
+
modified_code = transform.visit(parsed_codes)
|
| 1010 |
+
modified_code, abs_imported = _gather_abs_import_lazyobj(
|
| 1011 |
+
modified_code, filename=filename)
|
| 1012 |
+
imported_names = transform.imported_obj | abs_imported
|
| 1013 |
+
imported_names |= base_imported_names
|
| 1014 |
+
modified_code = ast.fix_missing_locations(modified_code)
|
| 1015 |
+
exec(
|
| 1016 |
+
compile(modified_code, filename, mode='exec'), global_dict,
|
| 1017 |
+
global_dict)
|
| 1018 |
+
|
| 1019 |
+
ret: dict = {}
|
| 1020 |
+
for key, value in global_dict.items():
|
| 1021 |
+
if key.startswith('__') or key in ['LazyObject']:
|
| 1022 |
+
continue
|
| 1023 |
+
ret[key] = value
|
| 1024 |
+
# convert dict to ConfigDict
|
| 1025 |
+
cfg_dict = Config._dict_to_config_dict_lazy(ret)
|
| 1026 |
+
|
| 1027 |
+
return cfg_dict, imported_names
|
| 1028 |
+
|
| 1029 |
+
@staticmethod
|
| 1030 |
+
def _dict_to_config_dict_lazy(cfg: dict):
|
| 1031 |
+
"""Recursively converts ``dict`` to :obj:`ConfigDict`. The only
|
| 1032 |
+
difference between ``_dict_to_config_dict_lazy`` and
|
| 1033 |
+
``_dict_to_config_dict_lazy`` is that the former one does not consider
|
| 1034 |
+
the scope, and will not trigger the building of ``LazyObject``.
|
| 1035 |
+
|
| 1036 |
+
Args:
|
| 1037 |
+
cfg (dict): Config dict.
|
| 1038 |
+
|
| 1039 |
+
Returns:
|
| 1040 |
+
ConfigDict: Converted dict.
|
| 1041 |
+
"""
|
| 1042 |
+
# Only the outer dict with key `type` should have the key `_scope_`.
|
| 1043 |
+
if isinstance(cfg, dict):
|
| 1044 |
+
cfg_dict = ConfigDict()
|
| 1045 |
+
for key, value in cfg.items():
|
| 1046 |
+
cfg_dict[key] = Config._dict_to_config_dict_lazy(value)
|
| 1047 |
+
return cfg_dict
|
| 1048 |
+
if isinstance(cfg, (tuple, list)):
|
| 1049 |
+
return type(cfg)(
|
| 1050 |
+
Config._dict_to_config_dict_lazy(_cfg) for _cfg in cfg)
|
| 1051 |
+
return cfg
|
| 1052 |
+
|
| 1053 |
+
@staticmethod
|
| 1054 |
+
def _dict_to_config_dict(cfg: dict,
|
| 1055 |
+
scope: Optional[str] = None,
|
| 1056 |
+
has_scope=True):
|
| 1057 |
+
"""Recursively converts ``dict`` to :obj:`ConfigDict`.
|
| 1058 |
+
|
| 1059 |
+
Args:
|
| 1060 |
+
cfg (dict): Config dict.
|
| 1061 |
+
scope (str, optional): Scope of instance.
|
| 1062 |
+
has_scope (bool): Whether to add `_scope_` key to config dict.
|
| 1063 |
+
|
| 1064 |
+
Returns:
|
| 1065 |
+
ConfigDict: Converted dict.
|
| 1066 |
+
"""
|
| 1067 |
+
# Only the outer dict with key `type` should have the key `_scope_`.
|
| 1068 |
+
if isinstance(cfg, dict):
|
| 1069 |
+
if has_scope and 'type' in cfg:
|
| 1070 |
+
has_scope = False
|
| 1071 |
+
if scope is not None and cfg.get('_scope_', None) is None:
|
| 1072 |
+
cfg._scope_ = scope # type: ignore
|
| 1073 |
+
cfg = ConfigDict(cfg)
|
| 1074 |
+
dict.__setattr__(cfg, 'scope', scope)
|
| 1075 |
+
for key, value in cfg.items():
|
| 1076 |
+
cfg[key] = Config._dict_to_config_dict(
|
| 1077 |
+
value, scope=scope, has_scope=has_scope)
|
| 1078 |
+
elif isinstance(cfg, tuple):
|
| 1079 |
+
cfg = tuple(
|
| 1080 |
+
Config._dict_to_config_dict(_cfg, scope, has_scope=has_scope)
|
| 1081 |
+
for _cfg in cfg)
|
| 1082 |
+
elif isinstance(cfg, list):
|
| 1083 |
+
cfg = [
|
| 1084 |
+
Config._dict_to_config_dict(_cfg, scope, has_scope=has_scope)
|
| 1085 |
+
for _cfg in cfg
|
| 1086 |
+
]
|
| 1087 |
+
return cfg
|
| 1088 |
+
|
| 1089 |
+
@staticmethod
|
| 1090 |
+
def _parse_scope(cfg: dict) -> None:
|
| 1091 |
+
"""Adds ``_scope_`` to :obj:`ConfigDict` instance, which means a base
|
| 1092 |
+
variable.
|
| 1093 |
+
|
| 1094 |
+
If the config dict already has the scope, scope will not be
|
| 1095 |
+
overwritten.
|
| 1096 |
+
|
| 1097 |
+
Args:
|
| 1098 |
+
cfg (dict): Config needs to be parsed with scope.
|
| 1099 |
+
"""
|
| 1100 |
+
if isinstance(cfg, ConfigDict):
|
| 1101 |
+
cfg._scope_ = cfg.scope
|
| 1102 |
+
elif isinstance(cfg, (tuple, list)):
|
| 1103 |
+
[Config._parse_scope(value) for value in cfg]
|
| 1104 |
+
else:
|
| 1105 |
+
return
|
| 1106 |
+
|
| 1107 |
+
@staticmethod
|
| 1108 |
+
def _get_base_files(filename: str) -> list:
|
| 1109 |
+
"""Get the base config file.
|
| 1110 |
+
|
| 1111 |
+
Args:
|
| 1112 |
+
filename (str): The config file.
|
| 1113 |
+
|
| 1114 |
+
Raises:
|
| 1115 |
+
TypeError: Name of config file.
|
| 1116 |
+
|
| 1117 |
+
Returns:
|
| 1118 |
+
list: A list of base config.
|
| 1119 |
+
"""
|
| 1120 |
+
file_format = osp.splitext(filename)[1]
|
| 1121 |
+
if file_format == '.py':
|
| 1122 |
+
Config._validate_py_syntax(filename)
|
| 1123 |
+
with open(filename, encoding='utf-8') as f:
|
| 1124 |
+
parsed_codes = ast.parse(f.read()).body
|
| 1125 |
+
|
| 1126 |
+
def is_base_line(c):
|
| 1127 |
+
return (isinstance(c, ast.Assign)
|
| 1128 |
+
and isinstance(c.targets[0], ast.Name)
|
| 1129 |
+
and c.targets[0].id == BASE_KEY)
|
| 1130 |
+
|
| 1131 |
+
base_code = next((c for c in parsed_codes if is_base_line(c)),
|
| 1132 |
+
None)
|
| 1133 |
+
if base_code is not None:
|
| 1134 |
+
base_code = ast.Expression( # type: ignore
|
| 1135 |
+
body=base_code.value) # type: ignore
|
| 1136 |
+
base_files = eval(compile(base_code, '',
|
| 1137 |
+
mode='eval')) # type: ignore
|
| 1138 |
+
else:
|
| 1139 |
+
base_files = []
|
| 1140 |
+
elif file_format in ('.yml', '.yaml', '.json'):
|
| 1141 |
+
cfg = OmegaConf.load(filename)
|
| 1142 |
+
cfg_dict = OmegaConf.to_container(cfg, resolve=True)
|
| 1143 |
+
base_files = cfg_dict.get(BASE_KEY, [])
|
| 1144 |
+
else:
|
| 1145 |
+
raise SyntaxError(
|
| 1146 |
+
'The config type should be py, json, yaml or '
|
| 1147 |
+
f'yml, but got {file_format}')
|
| 1148 |
+
base_files = base_files if isinstance(base_files,
|
| 1149 |
+
list) else [base_files]
|
| 1150 |
+
return base_files
|
| 1151 |
+
|
| 1152 |
+
@staticmethod
|
| 1153 |
+
def _get_cfg_path(cfg_path: str,
|
| 1154 |
+
filename: str) -> Tuple[str, Optional[str]]:
|
| 1155 |
+
"""Get the config path from the current or external package.
|
| 1156 |
+
|
| 1157 |
+
Args:
|
| 1158 |
+
cfg_path (str): Relative path of config.
|
| 1159 |
+
filename (str): The config file being parsed.
|
| 1160 |
+
|
| 1161 |
+
Returns:
|
| 1162 |
+
Tuple[str, str or None]: Path and scope of config. If the config
|
| 1163 |
+
is not an external config, the scope will be `None`.
|
| 1164 |
+
"""
|
| 1165 |
+
if '::' in cfg_path:
|
| 1166 |
+
# `cfg_path` startswith '::' means an external config path.
|
| 1167 |
+
# Get package name and relative config path.
|
| 1168 |
+
scope = cfg_path.partition('::')[0]
|
| 1169 |
+
package, cfg_path = _get_package_and_cfg_path(cfg_path)
|
| 1170 |
+
|
| 1171 |
+
if not is_installed(package):
|
| 1172 |
+
raise ModuleNotFoundError(
|
| 1173 |
+
f'{package} is not installed, please install {package} '
|
| 1174 |
+
f'manually')
|
| 1175 |
+
|
| 1176 |
+
# Get installed package path.
|
| 1177 |
+
package_path = get_installed_path(package)
|
| 1178 |
+
try:
|
| 1179 |
+
# Get config path from meta file.
|
| 1180 |
+
cfg_path = _get_external_cfg_path(package_path, cfg_path)
|
| 1181 |
+
except ValueError:
|
| 1182 |
+
# Since base config does not have a metafile, it should be
|
| 1183 |
+
# concatenated with package path and relative config path.
|
| 1184 |
+
cfg_path = _get_external_cfg_base_path(package_path, cfg_path)
|
| 1185 |
+
except FileNotFoundError as e:
|
| 1186 |
+
raise e
|
| 1187 |
+
return cfg_path, scope
|
| 1188 |
+
else:
|
| 1189 |
+
# Get local config path.
|
| 1190 |
+
cfg_dir = osp.dirname(filename)
|
| 1191 |
+
cfg_path = osp.join(cfg_dir, cfg_path)
|
| 1192 |
+
return cfg_path, None
|
| 1193 |
+
|
| 1194 |
+
@staticmethod
|
| 1195 |
+
def _merge_a_into_b(a: dict,
|
| 1196 |
+
b: dict,
|
| 1197 |
+
allow_list_keys: bool = False) -> dict:
|
| 1198 |
+
"""Merge dict ``a`` into dict ``b`` (non-inplace).
|
| 1199 |
+
|
| 1200 |
+
Values in ``a`` will overwrite ``b``. ``b`` is copied first to avoid
|
| 1201 |
+
in-place modifications.
|
| 1202 |
+
|
| 1203 |
+
Args:
|
| 1204 |
+
a (dict): The source dict to be merged into ``b``.
|
| 1205 |
+
b (dict): The origin dict to be fetch keys from ``a``.
|
| 1206 |
+
allow_list_keys (bool): If True, int string keys (e.g. '0', '1')
|
| 1207 |
+
are allowed in source ``a`` and will replace the element of the
|
| 1208 |
+
corresponding index in b if b is a list. Defaults to False.
|
| 1209 |
+
|
| 1210 |
+
Returns:
|
| 1211 |
+
dict: The modified dict of ``b`` using ``a``.
|
| 1212 |
+
|
| 1213 |
+
Examples:
|
| 1214 |
+
# Normally merge a into b.
|
| 1215 |
+
>>> Config._merge_a_into_b(
|
| 1216 |
+
... dict(obj=dict(a=2)), dict(obj=dict(a=1)))
|
| 1217 |
+
{'obj': {'a': 2}}
|
| 1218 |
+
|
| 1219 |
+
# Delete b first and merge a into b.
|
| 1220 |
+
>>> Config._merge_a_into_b(
|
| 1221 |
+
... dict(obj=dict(_delete_=True, a=2)), dict(obj=dict(a=1)))
|
| 1222 |
+
{'obj': {'a': 2}}
|
| 1223 |
+
|
| 1224 |
+
# b is a list
|
| 1225 |
+
>>> Config._merge_a_into_b(
|
| 1226 |
+
... {'0': dict(a=2)}, [dict(a=1), dict(b=2)], True)
|
| 1227 |
+
[{'a': 2}, {'b': 2}]
|
| 1228 |
+
"""
|
| 1229 |
+
b = b.copy()
|
| 1230 |
+
for k, v in a.items():
|
| 1231 |
+
if allow_list_keys and k.isdigit() and isinstance(b, list):
|
| 1232 |
+
k = int(k)
|
| 1233 |
+
if len(b) <= k:
|
| 1234 |
+
raise KeyError(f'Index {k} exceeds the length of list {b}')
|
| 1235 |
+
b[k] = Config._merge_a_into_b(v, b[k], allow_list_keys)
|
| 1236 |
+
elif isinstance(v, dict):
|
| 1237 |
+
if k in b and not v.pop(DELETE_KEY, False):
|
| 1238 |
+
allowed_types: Union[Tuple, type] = (
|
| 1239 |
+
dict, list) if allow_list_keys else dict
|
| 1240 |
+
if not isinstance(b[k], allowed_types):
|
| 1241 |
+
raise TypeError(
|
| 1242 |
+
f'{k}={v} in child config cannot inherit from '
|
| 1243 |
+
f'base because {k} is a dict in the child config '
|
| 1244 |
+
f'but is of type {type(b[k])} in base config. '
|
| 1245 |
+
f'You may set `{DELETE_KEY}=True` to ignore the '
|
| 1246 |
+
f'base config.')
|
| 1247 |
+
b[k] = Config._merge_a_into_b(v, b[k], allow_list_keys)
|
| 1248 |
+
else:
|
| 1249 |
+
b[k] = ConfigDict(v)
|
| 1250 |
+
else:
|
| 1251 |
+
b[k] = v
|
| 1252 |
+
return b
|
| 1253 |
+
|
| 1254 |
+
@property
|
| 1255 |
+
def filename(self) -> str:
|
| 1256 |
+
"""Get file name of config."""
|
| 1257 |
+
return self._filename
|
| 1258 |
+
|
| 1259 |
+
@property
|
| 1260 |
+
def text(self) -> str:
|
| 1261 |
+
"""Get config text."""
|
| 1262 |
+
return self._text
|
| 1263 |
+
|
| 1264 |
+
@property
|
| 1265 |
+
def env_variables(self) -> dict:
|
| 1266 |
+
"""Get used environment variables."""
|
| 1267 |
+
return self._env_variables
|
| 1268 |
+
|
| 1269 |
+
@property
|
| 1270 |
+
def pretty_text(self) -> str:
|
| 1271 |
+
"""Get formatted python config text."""
|
| 1272 |
+
|
| 1273 |
+
indent = 4
|
| 1274 |
+
|
| 1275 |
+
def _indent(s_, num_spaces):
|
| 1276 |
+
s = s_.split('\n')
|
| 1277 |
+
if len(s) == 1:
|
| 1278 |
+
return s_
|
| 1279 |
+
first = s.pop(0)
|
| 1280 |
+
s = [(num_spaces * ' ') + line for line in s]
|
| 1281 |
+
s = '\n'.join(s)
|
| 1282 |
+
s = first + '\n' + s
|
| 1283 |
+
return s
|
| 1284 |
+
|
| 1285 |
+
def _format_basic_types(k, v, use_mapping=False):
|
| 1286 |
+
if isinstance(v, str):
|
| 1287 |
+
v_str = repr(v)
|
| 1288 |
+
else:
|
| 1289 |
+
v_str = str(v)
|
| 1290 |
+
|
| 1291 |
+
if use_mapping:
|
| 1292 |
+
k_str = f"'{k}'" if isinstance(k, str) else str(k)
|
| 1293 |
+
attr_str = f'{k_str}: {v_str}'
|
| 1294 |
+
else:
|
| 1295 |
+
attr_str = f'{str(k)}={v_str}'
|
| 1296 |
+
attr_str = _indent(attr_str, indent)
|
| 1297 |
+
|
| 1298 |
+
return attr_str
|
| 1299 |
+
|
| 1300 |
+
def _format_list_tuple(k, v, use_mapping=False):
|
| 1301 |
+
if isinstance(v, list):
|
| 1302 |
+
left = '['
|
| 1303 |
+
right = ']'
|
| 1304 |
+
else:
|
| 1305 |
+
left = '('
|
| 1306 |
+
right = ')'
|
| 1307 |
+
|
| 1308 |
+
v_str = f'{left}\n'
|
| 1309 |
+
# check if all items in the list are dict
|
| 1310 |
+
for item in v:
|
| 1311 |
+
if isinstance(item, dict):
|
| 1312 |
+
v_str += f'dict({_indent(_format_dict(item), indent)}),\n'
|
| 1313 |
+
elif isinstance(item, tuple):
|
| 1314 |
+
v_str += f'{_indent(_format_list_tuple(None, item), indent)},\n' # noqa: 501
|
| 1315 |
+
elif isinstance(item, list):
|
| 1316 |
+
v_str += f'{_indent(_format_list_tuple(None, item), indent)},\n' # noqa: 501
|
| 1317 |
+
elif isinstance(item, str):
|
| 1318 |
+
v_str += f'{_indent(repr(item), indent)},\n'
|
| 1319 |
+
else:
|
| 1320 |
+
v_str += str(item) + ',\n'
|
| 1321 |
+
if k is None:
|
| 1322 |
+
return _indent(v_str, indent) + right
|
| 1323 |
+
if use_mapping:
|
| 1324 |
+
k_str = f"'{k}'" if isinstance(k, str) else str(k)
|
| 1325 |
+
attr_str = f'{k_str}: {v_str}'
|
| 1326 |
+
else:
|
| 1327 |
+
attr_str = f'{str(k)}={v_str}'
|
| 1328 |
+
attr_str = _indent(attr_str, indent) + right
|
| 1329 |
+
return attr_str
|
| 1330 |
+
|
| 1331 |
+
def _contain_invalid_identifier(dict_str):
|
| 1332 |
+
contain_invalid_identifier = False
|
| 1333 |
+
for key_name in dict_str:
|
| 1334 |
+
contain_invalid_identifier |= \
|
| 1335 |
+
(not str(key_name).isidentifier())
|
| 1336 |
+
return contain_invalid_identifier
|
| 1337 |
+
|
| 1338 |
+
def _format_dict(input_dict, outest_level=False):
|
| 1339 |
+
r = ''
|
| 1340 |
+
s = []
|
| 1341 |
+
|
| 1342 |
+
use_mapping = _contain_invalid_identifier(input_dict)
|
| 1343 |
+
if use_mapping:
|
| 1344 |
+
r += '{'
|
| 1345 |
+
for idx, (k, v) in enumerate(
|
| 1346 |
+
sorted(input_dict.items(), key=lambda x: str(x[0]))):
|
| 1347 |
+
is_last = idx >= len(input_dict) - 1
|
| 1348 |
+
end = '' if outest_level or is_last else ','
|
| 1349 |
+
if isinstance(v, dict):
|
| 1350 |
+
v_str = '\n' + _format_dict(v)
|
| 1351 |
+
if use_mapping:
|
| 1352 |
+
k_str = f"'{k}'" if isinstance(k, str) else str(k)
|
| 1353 |
+
attr_str = f'{k_str}: dict({v_str}'
|
| 1354 |
+
else:
|
| 1355 |
+
attr_str = f'{str(k)}=dict({v_str}'
|
| 1356 |
+
attr_str = _indent(attr_str, indent) + ')' + end
|
| 1357 |
+
elif isinstance(v, (list, tuple)):
|
| 1358 |
+
attr_str = _format_list_tuple(k, v, use_mapping) + end
|
| 1359 |
+
else:
|
| 1360 |
+
attr_str = _format_basic_types(k, v, use_mapping) + end
|
| 1361 |
+
|
| 1362 |
+
s.append(attr_str)
|
| 1363 |
+
r += '\n'.join(s)
|
| 1364 |
+
if use_mapping:
|
| 1365 |
+
r += '}'
|
| 1366 |
+
return r
|
| 1367 |
+
|
| 1368 |
+
cfg_dict = self.to_dict()
|
| 1369 |
+
text = _format_dict(cfg_dict, outest_level=True)
|
| 1370 |
+
if self._format_python_code:
|
| 1371 |
+
# copied from setup.cfg
|
| 1372 |
+
yapf_style = dict(
|
| 1373 |
+
based_on_style='pep8',
|
| 1374 |
+
blank_line_before_nested_class_or_def=True,
|
| 1375 |
+
split_before_expression_after_opening_paren=True)
|
| 1376 |
+
try:
|
| 1377 |
+
from ...utils import digit_version
|
| 1378 |
+
if digit_version(yapf.__version__) >= digit_version('0.40.2'):
|
| 1379 |
+
text, _ = FormatCode(text, style_config=yapf_style)
|
| 1380 |
+
else:
|
| 1381 |
+
text, _ = FormatCode(
|
| 1382 |
+
text, style_config=yapf_style, verify=True)
|
| 1383 |
+
except: # noqa: E722
|
| 1384 |
+
raise SyntaxError('Failed to format the config file, please '
|
| 1385 |
+
f'check the syntax of: \n{text}')
|
| 1386 |
+
return text
|
| 1387 |
+
|
| 1388 |
+
def __repr__(self):
|
| 1389 |
+
return f'Config (path: {self.filename}): {self._cfg_dict.__repr__()}'
|
| 1390 |
+
|
| 1391 |
+
def __len__(self):
|
| 1392 |
+
return len(self._cfg_dict)
|
| 1393 |
+
|
| 1394 |
+
def __getattr__(self, name: str) -> Any:
|
| 1395 |
+
return getattr(self._cfg_dict, name)
|
| 1396 |
+
|
| 1397 |
+
def __getitem__(self, name):
|
| 1398 |
+
return self._cfg_dict.__getitem__(name)
|
| 1399 |
+
|
| 1400 |
+
def __setattr__(self, name, value):
|
| 1401 |
+
if isinstance(value, dict):
|
| 1402 |
+
value = ConfigDict(value)
|
| 1403 |
+
self._cfg_dict.__setattr__(name, value)
|
| 1404 |
+
|
| 1405 |
+
def __setitem__(self, name, value):
|
| 1406 |
+
if isinstance(value, dict):
|
| 1407 |
+
value = ConfigDict(value)
|
| 1408 |
+
self._cfg_dict.__setitem__(name, value)
|
| 1409 |
+
|
| 1410 |
+
def __iter__(self):
|
| 1411 |
+
return iter(self._cfg_dict)
|
| 1412 |
+
|
| 1413 |
+
def __getstate__(
|
| 1414 |
+
self
|
| 1415 |
+
) -> Tuple[dict, Optional[str], Optional[str], dict, bool, set]:
|
| 1416 |
+
state = (self._cfg_dict, self._filename, self._text,
|
| 1417 |
+
self._env_variables, self._format_python_code,
|
| 1418 |
+
self._imported_names)
|
| 1419 |
+
return state
|
| 1420 |
+
|
| 1421 |
+
def __deepcopy__(self, memo):
|
| 1422 |
+
cls = self.__class__
|
| 1423 |
+
other = cls.__new__(cls)
|
| 1424 |
+
memo[id(self)] = other
|
| 1425 |
+
|
| 1426 |
+
for key, value in self.__dict__.items():
|
| 1427 |
+
super(Config, other).__setattr__(key, copy.deepcopy(value, memo))
|
| 1428 |
+
|
| 1429 |
+
return other
|
| 1430 |
+
|
| 1431 |
+
def __copy__(self):
|
| 1432 |
+
cls = self.__class__
|
| 1433 |
+
other = cls.__new__(cls)
|
| 1434 |
+
other.__dict__.update(self.__dict__)
|
| 1435 |
+
super(Config, other).__setattr__('_cfg_dict', self._cfg_dict.copy())
|
| 1436 |
+
|
| 1437 |
+
return other
|
| 1438 |
+
|
| 1439 |
+
copy = __copy__
|
| 1440 |
+
|
| 1441 |
+
def __setstate__(self, state: Tuple[dict, Optional[str], Optional[str],
|
| 1442 |
+
dict, bool, set]):
|
| 1443 |
+
super().__setattr__('_cfg_dict', state[0])
|
| 1444 |
+
super().__setattr__('_filename', state[1])
|
| 1445 |
+
super().__setattr__('_text', state[2])
|
| 1446 |
+
super().__setattr__('_env_variables', state[3])
|
| 1447 |
+
super().__setattr__('_format_python_code', state[4])
|
| 1448 |
+
super().__setattr__('_imported_names', state[5])
|
| 1449 |
+
|
| 1450 |
+
def dump(self, file: Optional[Union[str, Path]] = None):
|
| 1451 |
+
"""Dump config to file or return config text.
|
| 1452 |
+
|
| 1453 |
+
Args:
|
| 1454 |
+
file (str or Path, optional): If not specified, then the object
|
| 1455 |
+
is dumped to a str, otherwise to a file specified by the filename.
|
| 1456 |
+
Defaults to None.
|
| 1457 |
+
|
| 1458 |
+
Returns:
|
| 1459 |
+
str or None: Config text.
|
| 1460 |
+
"""
|
| 1461 |
+
file = str(file) if isinstance(file, Path) else file
|
| 1462 |
+
cfg_dict = self.to_dict()
|
| 1463 |
+
if file is None:
|
| 1464 |
+
if self.filename is None or self.filename.endswith('.py'):
|
| 1465 |
+
return self.pretty_text
|
| 1466 |
+
else:
|
| 1467 |
+
file_format = self.filename.split('.')[-1]
|
| 1468 |
+
return dump(cfg_dict, file_format=file_format)
|
| 1469 |
+
elif file.endswith('.py'):
|
| 1470 |
+
with open(file, 'w', encoding='utf-8') as f:
|
| 1471 |
+
f.write(self.pretty_text)
|
| 1472 |
+
else:
|
| 1473 |
+
file_format = file.split('.')[-1]
|
| 1474 |
+
return dump(cfg_dict, file=file, file_format=file_format)
|
| 1475 |
+
|
| 1476 |
+
@staticmethod
|
| 1477 |
+
def _is_lazy_import(filename: str) -> bool:
|
| 1478 |
+
if not filename.endswith('.py'):
|
| 1479 |
+
return False
|
| 1480 |
+
with open(filename, encoding='utf-8') as f:
|
| 1481 |
+
codes_str = f.read()
|
| 1482 |
+
parsed_codes = ast.parse(codes_str)
|
| 1483 |
+
for node in ast.walk(parsed_codes):
|
| 1484 |
+
if (isinstance(node, ast.Assign)
|
| 1485 |
+
and isinstance(node.targets[0], ast.Name)
|
| 1486 |
+
and node.targets[0].id == BASE_KEY):
|
| 1487 |
+
return False
|
| 1488 |
+
|
| 1489 |
+
if isinstance(node, ast.With):
|
| 1490 |
+
expr = node.items[0].context_expr
|
| 1491 |
+
if (not isinstance(expr, ast.Call)
|
| 1492 |
+
or not expr.func.id == 'read_base'): # type: ignore
|
| 1493 |
+
raise SyntaxError(
|
| 1494 |
+
'Only `read_base` context manager can be used in the '
|
| 1495 |
+
'config')
|
| 1496 |
+
return True
|
| 1497 |
+
if isinstance(node, ast.ImportFrom):
|
| 1498 |
+
# relative import -> lazy_import
|
| 1499 |
+
if node.level != 0:
|
| 1500 |
+
return True
|
| 1501 |
+
# Skip checking when using `mmengine.config` in cfg file
|
| 1502 |
+
if (node.module == 'mmengine' and len(node.names) == 1
|
| 1503 |
+
and node.names[0].name == 'Config'):
|
| 1504 |
+
continue
|
| 1505 |
+
if not isinstance(node.module, str):
|
| 1506 |
+
continue
|
| 1507 |
+
# non-builtin module -> lazy_import
|
| 1508 |
+
if not _is_builtin_module(node.module):
|
| 1509 |
+
return True
|
| 1510 |
+
if isinstance(node, ast.Import):
|
| 1511 |
+
for alias_node in node.names:
|
| 1512 |
+
if not _is_builtin_module(alias_node.name):
|
| 1513 |
+
return True
|
| 1514 |
+
return False
|
| 1515 |
+
|
| 1516 |
+
def _to_lazy_dict(self, keep_imported: bool = False) -> dict:
|
| 1517 |
+
"""Convert config object to dictionary with lazy object, and filter the
|
| 1518 |
+
imported object."""
|
| 1519 |
+
res = self._cfg_dict._to_lazy_dict()
|
| 1520 |
+
if hasattr(self, '_imported_names') and not keep_imported:
|
| 1521 |
+
res = {
|
| 1522 |
+
key: value
|
| 1523 |
+
for key, value in res.items()
|
| 1524 |
+
if key not in self._imported_names
|
| 1525 |
+
}
|
| 1526 |
+
return res
|
| 1527 |
+
|
| 1528 |
+
def to_dict(self, keep_imported: bool = False):
|
| 1529 |
+
"""Convert all data in the config to a builtin ``dict``.
|
| 1530 |
+
|
| 1531 |
+
Args:
|
| 1532 |
+
keep_imported (bool): Whether to keep the imported field.
|
| 1533 |
+
Defaults to False
|
| 1534 |
+
|
| 1535 |
+
If you import third-party objects in the config file, all imported
|
| 1536 |
+
objects will be converted to a string like ``torch.optim.SGD``
|
| 1537 |
+
"""
|
| 1538 |
+
cfg_dict = self._cfg_dict.to_dict()
|
| 1539 |
+
if hasattr(self, '_imported_names') and not keep_imported:
|
| 1540 |
+
cfg_dict = {
|
| 1541 |
+
key: value
|
| 1542 |
+
for key, value in cfg_dict.items()
|
| 1543 |
+
if key not in self._imported_names
|
| 1544 |
+
}
|
| 1545 |
+
return cfg_dict
|
model_without_OpenMMLab/segformer_plusplus/configs/config/lazy.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 2 |
+
from typing import Any, Optional, Union, Type
|
| 3 |
+
from collections import abc
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class LazyObject:
|
| 7 |
+
"""LazyObject is used to lazily initialize the imported module during
|
| 8 |
+
parsing the configuration file.
|
| 9 |
+
|
| 10 |
+
During parsing process, the syntax like:
|
| 11 |
+
|
| 12 |
+
Examples:
|
| 13 |
+
>>> import torch.nn as nn
|
| 14 |
+
>>> from mmdet.models import RetinaNet
|
| 15 |
+
>>> import mmcls.models
|
| 16 |
+
>>> import mmcls.datasets
|
| 17 |
+
>>> import mmcls
|
| 18 |
+
|
| 19 |
+
Will be parsed as:
|
| 20 |
+
|
| 21 |
+
Examples:
|
| 22 |
+
>>> # import torch.nn as nn
|
| 23 |
+
>>> nn = lazyObject('torch.nn')
|
| 24 |
+
>>> # from mmdet.models import RetinaNet
|
| 25 |
+
>>> RetinaNet = lazyObject('mmdet.models', 'RetinaNet')
|
| 26 |
+
>>> # import mmcls.models; import mmcls.datasets; import mmcls
|
| 27 |
+
>>> mmcls = lazyObject(['mmcls', 'mmcls.datasets', 'mmcls.models'])
|
| 28 |
+
|
| 29 |
+
``LazyObject`` records all module information and will be further
|
| 30 |
+
referenced by the configuration file.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
module (str or list or tuple): The module name to be imported.
|
| 34 |
+
imported (str, optional): The imported module name. Defaults to None.
|
| 35 |
+
location (str, optional): The filename and line number of the imported
|
| 36 |
+
module statement happened.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
def __init__(self,
|
| 40 |
+
module: Union[str, list, tuple],
|
| 41 |
+
imported: Optional[str] = None,
|
| 42 |
+
location: Optional[str] = None):
|
| 43 |
+
if not isinstance(module, str) and not is_seq_of(module, str):
|
| 44 |
+
raise TypeError('module should be `str`, `list`, or `tuple`'
|
| 45 |
+
f'but got {type(module)}, this might be '
|
| 46 |
+
'a bug, please report it')
|
| 47 |
+
self._module: Union[str, list, tuple] = module
|
| 48 |
+
|
| 49 |
+
if not isinstance(imported, str) and imported is not None:
|
| 50 |
+
raise TypeError('imported should be `str` or None, but got '
|
| 51 |
+
f'{type(imported)}, this might be '
|
| 52 |
+
'a bug , please report it')
|
| 53 |
+
self._imported = imported
|
| 54 |
+
self.location = location
|
| 55 |
+
|
| 56 |
+
def build(self) -> Any:
|
| 57 |
+
"""Return imported object.
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
Any: Imported object
|
| 61 |
+
"""
|
| 62 |
+
if isinstance(self._module, str):
|
| 63 |
+
try:
|
| 64 |
+
module = importlib.import_module(self._module)
|
| 65 |
+
except Exception as e:
|
| 66 |
+
raise type(e)(f'Failed to import {self._module} '
|
| 67 |
+
f'in {self.location} for {e}')
|
| 68 |
+
|
| 69 |
+
if self._imported is not None:
|
| 70 |
+
if hasattr(module, self._imported):
|
| 71 |
+
module = getattr(module, self._imported)
|
| 72 |
+
else:
|
| 73 |
+
raise ImportError(
|
| 74 |
+
f'Failed to import {self._imported} '
|
| 75 |
+
f'from {self._module} in {self.location}')
|
| 76 |
+
|
| 77 |
+
return module
|
| 78 |
+
else:
|
| 79 |
+
try:
|
| 80 |
+
for module in self._module:
|
| 81 |
+
importlib.import_module(module) # type: ignore
|
| 82 |
+
module_name = self._module[0].split('.')[0]
|
| 83 |
+
return importlib.import_module(module_name)
|
| 84 |
+
except Exception as e:
|
| 85 |
+
raise type(e)(f'Failed to import {self.module} '
|
| 86 |
+
f'in {self.location} for {e}')
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def module(self):
|
| 90 |
+
if isinstance(self._module, str):
|
| 91 |
+
return self._module
|
| 92 |
+
return self._module[0].split('.')[0]
|
| 93 |
+
|
| 94 |
+
def __call__(self, *args, **kwargs):
|
| 95 |
+
raise RuntimeError()
|
| 96 |
+
|
| 97 |
+
def __deepcopy__(self, memo):
|
| 98 |
+
return LazyObject(self._module, self._imported, self.location)
|
| 99 |
+
|
| 100 |
+
def __getattr__(self, name):
|
| 101 |
+
# Cannot locate the line number of the getting attribute.
|
| 102 |
+
# Therefore only record the filename.
|
| 103 |
+
if self.location is not None:
|
| 104 |
+
location = self.location.split(', line')[0]
|
| 105 |
+
else:
|
| 106 |
+
location = self.location
|
| 107 |
+
return LazyAttr(name, self, location)
|
| 108 |
+
|
| 109 |
+
def __str__(self) -> str:
|
| 110 |
+
if self._imported is not None:
|
| 111 |
+
return self._imported
|
| 112 |
+
return self.module
|
| 113 |
+
|
| 114 |
+
__repr__ = __str__
|
| 115 |
+
|
| 116 |
+
# `pickle.dump` will try to get the `__getstate__` and `__setstate__`
|
| 117 |
+
# methods of the dumped object. If these two methods are not defined,
|
| 118 |
+
# LazyObject will return a `__getstate__` LazyObject` or `__setstate__`
|
| 119 |
+
# LazyObject.
|
| 120 |
+
def __getstate__(self):
|
| 121 |
+
return self.__dict__
|
| 122 |
+
|
| 123 |
+
def __setstate__(self, state):
|
| 124 |
+
self.__dict__ = state
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class LazyAttr:
|
| 128 |
+
"""The attribute of the LazyObject.
|
| 129 |
+
|
| 130 |
+
When parsing the configuration file, the imported syntax will be
|
| 131 |
+
parsed as the assignment ``LazyObject``. During the subsequent parsing
|
| 132 |
+
process, users may reference the attributes of the LazyObject.
|
| 133 |
+
To ensure that these attributes also contain information needed to
|
| 134 |
+
reconstruct the attribute itself, LazyAttr was introduced.
|
| 135 |
+
|
| 136 |
+
Examples:
|
| 137 |
+
>>> models = LazyObject(['mmdet.models'])
|
| 138 |
+
>>> model = dict(type=models.RetinaNet)
|
| 139 |
+
>>> print(type(model['type'])) # <class 'mmengine.config.lazy.LazyAttr'>
|
| 140 |
+
>>> print(model['type'].build()) # <class 'mmdet.models.detectors.retinanet.RetinaNet'>
|
| 141 |
+
""" # noqa: E501
|
| 142 |
+
|
| 143 |
+
def __init__(self,
|
| 144 |
+
name: str,
|
| 145 |
+
source: Union['LazyObject', 'LazyAttr'],
|
| 146 |
+
location=None):
|
| 147 |
+
self.name = name
|
| 148 |
+
self.source: Union[LazyAttr, LazyObject] = source
|
| 149 |
+
|
| 150 |
+
if isinstance(self.source, LazyObject):
|
| 151 |
+
if isinstance(self.source._module, str):
|
| 152 |
+
if self.source._imported is None:
|
| 153 |
+
# source code:
|
| 154 |
+
# from xxx.yyy import zzz
|
| 155 |
+
# equivalent code:
|
| 156 |
+
# zzz = LazyObject('xxx.yyy', 'zzz')
|
| 157 |
+
# The source code of get attribute:
|
| 158 |
+
# eee = zzz.eee
|
| 159 |
+
# Then, `eee._module` should be "xxx.yyy.zzz"
|
| 160 |
+
self._module = self.source._module
|
| 161 |
+
else:
|
| 162 |
+
# source code:
|
| 163 |
+
# import xxx.yyy as zzz
|
| 164 |
+
# equivalent code:
|
| 165 |
+
# zzz = LazyObject('xxx.yyy')
|
| 166 |
+
# The source code of get attribute:
|
| 167 |
+
# eee = zzz.eee
|
| 168 |
+
# Then, `eee._module` should be "xxx.yyy"
|
| 169 |
+
self._module = f'{self.source._module}.{self.source}'
|
| 170 |
+
else:
|
| 171 |
+
# The source code of LazyObject should be
|
| 172 |
+
# 1. import xxx.yyy
|
| 173 |
+
# 2. import xxx.zzz
|
| 174 |
+
# Equivalent to
|
| 175 |
+
# xxx = LazyObject(['xxx.yyy', 'xxx.zzz'])
|
| 176 |
+
|
| 177 |
+
# The source code of LazyAttr should be
|
| 178 |
+
# eee = xxx.eee
|
| 179 |
+
# Then, eee._module = xxx
|
| 180 |
+
self._module = str(self.source)
|
| 181 |
+
elif isinstance(self.source, LazyAttr):
|
| 182 |
+
# 1. import xxx
|
| 183 |
+
# 2. zzz = xxx.yyy.zzz
|
| 184 |
+
|
| 185 |
+
# Equivalent to:
|
| 186 |
+
# xxx = LazyObject('xxx')
|
| 187 |
+
# zzz = xxx.yyy.zzz
|
| 188 |
+
# zzz._module = xxx.yyy._module + zzz.name
|
| 189 |
+
self._module = f'{self.source._module}.{self.source.name}'
|
| 190 |
+
self.location = location
|
| 191 |
+
|
| 192 |
+
@property
|
| 193 |
+
def module(self):
|
| 194 |
+
return self._module
|
| 195 |
+
|
| 196 |
+
def __call__(self, *args, **kwargs: Any) -> Any:
|
| 197 |
+
raise RuntimeError()
|
| 198 |
+
|
| 199 |
+
def __getattr__(self, name: str) -> 'LazyAttr':
|
| 200 |
+
return LazyAttr(name, self)
|
| 201 |
+
|
| 202 |
+
def __deepcopy__(self, memo):
|
| 203 |
+
return LazyAttr(self.name, self.source)
|
| 204 |
+
|
| 205 |
+
def build(self) -> Any:
|
| 206 |
+
"""Return the attribute of the imported object.
|
| 207 |
+
|
| 208 |
+
Returns:
|
| 209 |
+
Any: attribute of the imported object.
|
| 210 |
+
"""
|
| 211 |
+
obj = self.source.build()
|
| 212 |
+
try:
|
| 213 |
+
return getattr(obj, self.name)
|
| 214 |
+
except AttributeError:
|
| 215 |
+
raise ImportError(f'Failed to import {self.module}.{self.name} in '
|
| 216 |
+
f'{self.location}')
|
| 217 |
+
except ImportError as e:
|
| 218 |
+
raise e
|
| 219 |
+
|
| 220 |
+
def __str__(self) -> str:
|
| 221 |
+
return self.name
|
| 222 |
+
|
| 223 |
+
__repr__ = __str__
|
| 224 |
+
|
| 225 |
+
# `pickle.dump` will try to get the `__getstate__` and `__setstate__`
|
| 226 |
+
# methods of the dumped object. If these two methods are not defined,
|
| 227 |
+
# LazyAttr will return a `__getstate__` LazyAttr` or `__setstate__`
|
| 228 |
+
# LazyAttr.
|
| 229 |
+
def __getstate__(self):
|
| 230 |
+
return self.__dict__
|
| 231 |
+
|
| 232 |
+
def __setstate__(self, state):
|
| 233 |
+
self.__dict__ = state
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def is_seq_of(seq: Any,
|
| 237 |
+
expected_type: Union[Type, tuple],
|
| 238 |
+
seq_type: Optional[Type] = None) -> bool:
|
| 239 |
+
"""Check whether it is a sequence of some type.
|
| 240 |
+
|
| 241 |
+
Args:
|
| 242 |
+
seq (Sequence): The sequence to be checked.
|
| 243 |
+
expected_type (type or tuple): Expected type of sequence items.
|
| 244 |
+
seq_type (type, optional): Expected sequence type. Defaults to None.
|
| 245 |
+
|
| 246 |
+
Returns:
|
| 247 |
+
bool: Return True if ``seq`` is valid else False.
|
| 248 |
+
|
| 249 |
+
Examples:
|
| 250 |
+
>>> from mmengine.utils import is_seq_of
|
| 251 |
+
>>> seq = ['a', 'b', 'c']
|
| 252 |
+
>>> is_seq_of(seq, str)
|
| 253 |
+
True
|
| 254 |
+
>>> is_seq_of(seq, int)
|
| 255 |
+
False
|
| 256 |
+
"""
|
| 257 |
+
if seq_type is None:
|
| 258 |
+
exp_seq_type = abc.Sequence
|
| 259 |
+
else:
|
| 260 |
+
assert isinstance(seq_type, type)
|
| 261 |
+
exp_seq_type = seq_type
|
| 262 |
+
if not isinstance(seq, exp_seq_type):
|
| 263 |
+
return False
|
| 264 |
+
for item in seq:
|
| 265 |
+
if not isinstance(item, expected_type):
|
| 266 |
+
return False
|
| 267 |
+
return True
|
model_without_OpenMMLab/segformer_plusplus/configs/config/utils.py
ADDED
|
@@ -0,0 +1,687 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import os.path as osp
|
| 3 |
+
import re
|
| 4 |
+
import sys
|
| 5 |
+
import warnings
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from importlib.util import find_spec
|
| 8 |
+
from typing import List, Optional, Tuple, Union
|
| 9 |
+
from importlib import import_module as real_import_module
|
| 10 |
+
import json
|
| 11 |
+
import pickle
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import itertools
|
| 14 |
+
import importlib.util # Hinzugefügt für find_spec in Python >= 3.7
|
| 15 |
+
import importlib.metadata # Ersatz für pkg_resources.get_distribution und package2module
|
| 16 |
+
|
| 17 |
+
# Ersetzt: from pkg_resources.extern import packaging
|
| 18 |
+
# Ersetzt: __import__('pkg_resources.extern.packaging.version')
|
| 19 |
+
# Ersetzt: __import__('pkg_resources.extern.packaging.specifiers')
|
| 20 |
+
# Ersetzt: __import__('pkg_resources.extern.packaging.requirements')
|
| 21 |
+
# Ersetzt: __import__('pkg_resources.extern.packaging.markers')
|
| 22 |
+
# Importiert nun das externe 'packaging'-Paket direkt
|
| 23 |
+
try:
|
| 24 |
+
import packaging.version
|
| 25 |
+
import packaging.specifiers
|
| 26 |
+
import packaging.requirements
|
| 27 |
+
import packaging.markers
|
| 28 |
+
except ImportError as e:
|
| 29 |
+
raise ImportError(
|
| 30 |
+
"The 'packaging' package is required but not installed. "
|
| 31 |
+
"Install it with 'pip install packaging'."
|
| 32 |
+
) from e
|
| 33 |
+
|
| 34 |
+
import yaml
|
| 35 |
+
from omegaconf import OmegaConf
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# Die folgenden Hilfsfunktionen aus pkg_resources wurden unten neu implementiert
|
| 39 |
+
# oder durch `packaging` ersetzt: get_distribution, package2module, Requirement,
|
| 40 |
+
# parse_requirements, yield_lines, safe_extra, safe_name.
|
| 41 |
+
|
| 42 |
+
# --- Hilfsfunktionen für `packaging` (Ersatz für pkg_resources-Logik) ---
|
| 43 |
+
|
| 44 |
+
# Implementierung der pkg_resources-Hilfsfunktionen mit 'packaging'
|
| 45 |
+
def safe_extra(extra: str) -> str:
|
| 46 |
+
"""Convert an arbitrary string to a standard 'extra' name"""
|
| 47 |
+
# pkg_resources implementation detail using packaging's rules
|
| 48 |
+
return re.sub(r'[^A-Za-z0-9.-]+', '_', extra).lower()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def safe_name(name: str) -> str:
|
| 52 |
+
"""Convert an arbitrary string to a standard distribution name"""
|
| 53 |
+
# pkg_resources implementation detail using packaging's rules
|
| 54 |
+
return re.sub(r'[^A-Za-z0-9.]+', '-', name)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class DistributionNotFound(Exception):
|
| 58 |
+
"""Exception raised when a distribution is not found."""
|
| 59 |
+
pass
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def get_distribution(dist_name: str) -> importlib.metadata.Distribution:
|
| 63 |
+
"""Return a current distribution object for a package name or string requirement.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
dist_name (str): The name of the package or a requirement string.
|
| 67 |
+
|
| 68 |
+
Returns:
|
| 69 |
+
importlib.metadata.Distribution: The found distribution object.
|
| 70 |
+
|
| 71 |
+
Raises:
|
| 72 |
+
DistributionNotFound: If the package is not found.
|
| 73 |
+
ValueError: If a requirement string is used (not supported by this simplified function).
|
| 74 |
+
"""
|
| 75 |
+
if ' ' in dist_name or any(op in dist_name for op in ('==', '>=', '<=', '>', '<', '~=', '!=', '==')):
|
| 76 |
+
# importlib.metadata.distribution does not handle requirement strings.
|
| 77 |
+
# It's better to use the distribution name directly.
|
| 78 |
+
# Fallback to direct name extraction.
|
| 79 |
+
try:
|
| 80 |
+
req = packaging.requirements.Requirement(dist_name)
|
| 81 |
+
dist_name = req.name
|
| 82 |
+
except packaging.requirements.InvalidRequirement:
|
| 83 |
+
raise ValueError(
|
| 84 |
+
f"get_distribution only supports package names or simple requirements, "
|
| 85 |
+
f"but got: {dist_name}"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
# Use importlib.metadata.distribution for name-based lookup
|
| 90 |
+
return importlib.metadata.distribution(dist_name)
|
| 91 |
+
except importlib.metadata.PackageNotFoundError:
|
| 92 |
+
raise DistributionNotFound(f"The 'Distribution' '{dist_name}' was not found and is required")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def package2module(package: str) -> str:
|
| 96 |
+
"""Infer module name from package using importlib.metadata.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
package (str): Package to infer module name.
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
str: The module name.
|
| 103 |
+
|
| 104 |
+
Raises:
|
| 105 |
+
ValueError: If the top-level module name cannot be inferred.
|
| 106 |
+
"""
|
| 107 |
+
try:
|
| 108 |
+
# Use importlib.metadata.distribution
|
| 109 |
+
dist = get_distribution(package)
|
| 110 |
+
|
| 111 |
+
# Check for top_level.txt metadata
|
| 112 |
+
top_level_txt = dist.read_text('top_level.txt')
|
| 113 |
+
if top_level_txt:
|
| 114 |
+
# The first non-empty line is usually the top-level module name
|
| 115 |
+
module_name = top_level_txt.split('\n')[0].strip()
|
| 116 |
+
if module_name:
|
| 117 |
+
return module_name
|
| 118 |
+
|
| 119 |
+
except (DistributionNotFound, FileNotFoundError):
|
| 120 |
+
# Package not found or top_level.txt not available/found
|
| 121 |
+
pass # Will raise ValueError below
|
| 122 |
+
|
| 123 |
+
raise ValueError(
|
| 124 |
+
highlighted_error(f'can not infer the module name of {package}. '
|
| 125 |
+
'Metadata (top_level.txt) not found or package not installed.')
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# Neuimplementierung der Requirement-Logik von pkg_resources mit packaging.requirements.Requirement
|
| 130 |
+
|
| 131 |
+
class Requirement(packaging.requirements.Requirement):
|
| 132 |
+
"""Reimplementation of pkg_resources.Requirement using packaging.requirements.Requirement."""
|
| 133 |
+
|
| 134 |
+
def __init__(self, requirement_string):
|
| 135 |
+
"""DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
|
| 136 |
+
super().__init__(requirement_string)
|
| 137 |
+
self.unsafe_name = self.name
|
| 138 |
+
project_name = safe_name(self.name)
|
| 139 |
+
self.project_name, self.key = project_name, project_name.lower()
|
| 140 |
+
|
| 141 |
+
# specs is an internal list in pkg_resources
|
| 142 |
+
self.specs = [
|
| 143 |
+
(spec.operator, spec.version) for spec in self.specifier
|
| 144 |
+
] if self.specifier else []
|
| 145 |
+
|
| 146 |
+
self.extras = tuple(map(safe_extra, self.extras))
|
| 147 |
+
|
| 148 |
+
# hashCmp logic from pkg_resources
|
| 149 |
+
self.hashCmp = (
|
| 150 |
+
self.key,
|
| 151 |
+
self.url,
|
| 152 |
+
str(self.specifier) if self.specifier else '',
|
| 153 |
+
frozenset(self.extras),
|
| 154 |
+
str(self.marker) if self.marker else None,
|
| 155 |
+
)
|
| 156 |
+
self.__hash = hash(self.hashCmp)
|
| 157 |
+
|
| 158 |
+
def __eq__(self, other):
|
| 159 |
+
return (
|
| 160 |
+
isinstance(other, Requirement) and
|
| 161 |
+
self.hashCmp == other.hashCmp
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
def __contains__(self, item: packaging.version.Version) -> bool:
|
| 165 |
+
"""Check if a specific version is contained in the requirement."""
|
| 166 |
+
if isinstance(item, str):
|
| 167 |
+
try:
|
| 168 |
+
item = packaging.version.Version(item)
|
| 169 |
+
except packaging.version.InvalidVersion:
|
| 170 |
+
warnings.warn(f"Invalid version string: {item}", UserWarning)
|
| 171 |
+
return False
|
| 172 |
+
|
| 173 |
+
if self.key != safe_name(item.base_version).lower():
|
| 174 |
+
# This check is an oversimplification but reflects pkg_resources' intent
|
| 175 |
+
# In a real-world scenario, you should compare the package name.
|
| 176 |
+
# Since the original code only imports 'packaging' and not a distribution object,
|
| 177 |
+
# this check can only be an approximation.
|
| 178 |
+
return False
|
| 179 |
+
|
| 180 |
+
# The packaging specifier can check against packaging.version.Version objects
|
| 181 |
+
# prereleases=True is required to match pkg_resources' default behavior
|
| 182 |
+
return self.specifier.contains(item, prereleases=True)
|
| 183 |
+
|
| 184 |
+
def __hash__(self):
|
| 185 |
+
return self.__hash
|
| 186 |
+
|
| 187 |
+
@staticmethod
|
| 188 |
+
def parse(s):
|
| 189 |
+
reqs = list(parse_requirements(s))
|
| 190 |
+
if not reqs:
|
| 191 |
+
raise ValueError(f"Could not parse requirement from string: {s}")
|
| 192 |
+
return reqs[0]
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def yield_lines(iterable: Union[str, list, tuple]) -> List[str]:
|
| 196 |
+
"""Yield valid lines of a string or iterable, recursively."""
|
| 197 |
+
if isinstance(iterable, str):
|
| 198 |
+
return [line for line in iterable.splitlines() if line.strip() and not line.strip().startswith('#')]
|
| 199 |
+
|
| 200 |
+
lines = []
|
| 201 |
+
for item in iterable:
|
| 202 |
+
lines.extend(yield_lines(item))
|
| 203 |
+
return lines
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def parse_requirements(strs: Union[str, list, tuple]) -> 'Requirement':
|
| 207 |
+
"""Yield ``Requirement`` objects for each specification in `strs`."""
|
| 208 |
+
lines = iter(yield_lines(strs))
|
| 209 |
+
|
| 210 |
+
for line in lines:
|
| 211 |
+
# Drop comments and handle line continuation
|
| 212 |
+
if ' #' in line:
|
| 213 |
+
line = line[:line.find(' #')]
|
| 214 |
+
|
| 215 |
+
line = line.strip()
|
| 216 |
+
|
| 217 |
+
# If there is a line continuation, drop it, and append the next line.
|
| 218 |
+
while line.endswith('\\'):
|
| 219 |
+
line = line[:-1].strip()
|
| 220 |
+
try:
|
| 221 |
+
line += next(lines).strip()
|
| 222 |
+
except StopIteration:
|
| 223 |
+
break # End of lines
|
| 224 |
+
|
| 225 |
+
if line:
|
| 226 |
+
yield Requirement(line)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
# --- Ende der Hilfsfunktionen ---
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
PYTHON_ROOT_DIR = osp.dirname(osp.dirname(sys.executable))
|
| 233 |
+
SYSTEM_PYTHON_PREFIX = '/usr/lib/python'
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class ConfigParsingError(RuntimeError):
|
| 237 |
+
"""Raise error when failed to parse pure Python style config files."""
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _get_cfg_metainfo(package_path: str, cfg_path: str) -> dict:
|
| 241 |
+
"""Get target meta information from all 'metafile.yml' defined in `mode-
|
| 242 |
+
index.yml` of external package.
|
| 243 |
+
|
| 244 |
+
Args:
|
| 245 |
+
package_path (str): Path of external package.
|
| 246 |
+
cfg_path (str): Name of experiment config.
|
| 247 |
+
|
| 248 |
+
Returns:
|
| 249 |
+
dict: Meta information of target experiment.
|
| 250 |
+
"""
|
| 251 |
+
meta_index_path = osp.join(package_path, '.mim', 'model-index.yml')
|
| 252 |
+
meta_index = OmegaConf.to_container(OmegaConf.load(meta_index_path), resolve=True)
|
| 253 |
+
cfg_dict = dict()
|
| 254 |
+
for meta_path in meta_index['Import']:
|
| 255 |
+
meta_path = osp.join(package_path, '.mim', meta_path)
|
| 256 |
+
cfg_meta = OmegaConf.to_container(OmegaConf.load(meta_path), resolve=True)
|
| 257 |
+
for model_cfg in cfg_meta['Models']:
|
| 258 |
+
if 'Config' not in model_cfg:
|
| 259 |
+
warnings.warn(f'There is not `Config` define in {model_cfg}')
|
| 260 |
+
continue
|
| 261 |
+
cfg_name = model_cfg['Config'].partition('/')[-1]
|
| 262 |
+
# Some config could have multiple weights, we only pick the
|
| 263 |
+
# first one.
|
| 264 |
+
if cfg_name in cfg_dict:
|
| 265 |
+
continue
|
| 266 |
+
cfg_dict[cfg_name] = model_cfg
|
| 267 |
+
if cfg_path not in cfg_dict:
|
| 268 |
+
raise ValueError(f'Expected configs: {cfg_dict.keys()}, but got '
|
| 269 |
+
f'{cfg_path}')
|
| 270 |
+
return cfg_dict[cfg_path]
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def _get_external_cfg_path(package_path: str, cfg_file: str) -> str:
|
| 274 |
+
"""Get config path of external package.
|
| 275 |
+
|
| 276 |
+
Args:
|
| 277 |
+
package_path (str): Path of external package.
|
| 278 |
+
cfg_file (str): Name of experiment config.
|
| 279 |
+
|
| 280 |
+
Returns:
|
| 281 |
+
str: Absolute config path from external package.
|
| 282 |
+
"""
|
| 283 |
+
cfg_file = cfg_file.split('.')[0]
|
| 284 |
+
model_cfg = _get_cfg_metainfo(package_path, cfg_file)
|
| 285 |
+
cfg_path = osp.join(package_path, model_cfg['Config'])
|
| 286 |
+
check_file_exist(cfg_path)
|
| 287 |
+
return cfg_path
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def _get_external_cfg_base_path(package_path: str, cfg_name: str) -> str:
|
| 291 |
+
"""Get base config path of external package.
|
| 292 |
+
|
| 293 |
+
Args:
|
| 294 |
+
package_path (str): Path of external package.
|
| 295 |
+
cfg_name (str): External relative config path with 'package::'.
|
| 296 |
+
|
| 297 |
+
Returns:
|
| 298 |
+
str: Absolute config path from external package.
|
| 299 |
+
"""
|
| 300 |
+
cfg_path = osp.join(package_path, '.mim', 'configs', cfg_name)
|
| 301 |
+
check_file_exist(cfg_path)
|
| 302 |
+
return cfg_path
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def _get_package_and_cfg_path(cfg_path: str) -> Tuple[str, str]:
|
| 306 |
+
"""Get package name and relative config path.
|
| 307 |
+
|
| 308 |
+
Args:
|
| 309 |
+
cfg_path (str): External relative config path with 'package::'.
|
| 310 |
+
|
| 311 |
+
Returns:
|
| 312 |
+
Tuple[str, str]: Package name and config path.
|
| 313 |
+
"""
|
| 314 |
+
if re.match(r'\w*::\w*/\w*', cfg_path) is None:
|
| 315 |
+
raise ValueError(
|
| 316 |
+
'`_get_package_and_cfg_path` is used for get external package, '
|
| 317 |
+
'please specify the package name and relative config path, just '
|
| 318 |
+
'like `mmdet::faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py`')
|
| 319 |
+
package_cfg = cfg_path.split('::')
|
| 320 |
+
if len(package_cfg) > 2:
|
| 321 |
+
raise ValueError('`::` should only be used to separate package and '
|
| 322 |
+
'config name, but found multiple `::` in '
|
| 323 |
+
f'{cfg_path}')
|
| 324 |
+
package, cfg_path = package_cfg
|
| 325 |
+
return package, cfg_path
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class RemoveAssignFromAST(ast.NodeTransformer):
|
| 329 |
+
"""Remove Assign node if the target's name match the key.
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
key (str): The target name of the Assign node.
|
| 333 |
+
"""
|
| 334 |
+
|
| 335 |
+
def __init__(self, key):
|
| 336 |
+
self.key = key
|
| 337 |
+
|
| 338 |
+
def visit_Assign(self, node):
|
| 339 |
+
if (isinstance(node.targets[0], ast.Name)
|
| 340 |
+
and node.targets[0].id == self.key):
|
| 341 |
+
return None
|
| 342 |
+
else:
|
| 343 |
+
return node
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def _is_builtin_module(module_name: str) -> bool:
|
| 347 |
+
"""Check if a module is a built-in module.
|
| 348 |
+
|
| 349 |
+
Arg:
|
| 350 |
+
module_name: name of module.
|
| 351 |
+
"""
|
| 352 |
+
if module_name.startswith('.'):
|
| 353 |
+
return False
|
| 354 |
+
if module_name.startswith('mmengine.config'):
|
| 355 |
+
return True
|
| 356 |
+
if module_name in sys.builtin_module_names:
|
| 357 |
+
return True
|
| 358 |
+
spec = find_spec(module_name.split('.')[0])
|
| 359 |
+
# Module not found
|
| 360 |
+
if spec is None:
|
| 361 |
+
return False
|
| 362 |
+
origin_path = getattr(spec, 'origin', None)
|
| 363 |
+
if origin_path is None:
|
| 364 |
+
return False
|
| 365 |
+
origin_path = osp.abspath(origin_path)
|
| 366 |
+
if ('site-package' in origin_path or 'dist-package' in origin_path
|
| 367 |
+
or not origin_path.startswith(
|
| 368 |
+
(PYTHON_ROOT_DIR, SYSTEM_PYTHON_PREFIX))):
|
| 369 |
+
return False
|
| 370 |
+
else:
|
| 371 |
+
return True
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
class ImportTransformer(ast.NodeTransformer):
|
| 375 |
+
"""Convert the import syntax to the assignment of
|
| 376 |
+
:class:`mmengine.config.LazyObject` and preload the base variable before
|
| 377 |
+
parsing the configuration file.
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
# noqa: E501
|
| 381 |
+
|
| 382 |
+
def __init__(self,
|
| 383 |
+
global_dict: dict,
|
| 384 |
+
base_dict: Optional[dict] = None,
|
| 385 |
+
filename: Optional[str] = None):
|
| 386 |
+
self.base_dict = base_dict if base_dict is not None else {}
|
| 387 |
+
self.global_dict = global_dict
|
| 388 |
+
if isinstance(filename, str):
|
| 389 |
+
filename = filename.encode('unicode_escape').decode()
|
| 390 |
+
self.filename = filename
|
| 391 |
+
self.imported_obj: set = set()
|
| 392 |
+
super().__init__()
|
| 393 |
+
|
| 394 |
+
def visit_ImportFrom(
|
| 395 |
+
self, node: ast.ImportFrom
|
| 396 |
+
) -> Optional[Union[List[ast.Assign], ast.ImportFrom]]:
|
| 397 |
+
# Built-in modules will not be parsed as LazyObject
|
| 398 |
+
module = f'{node.level * "."}{node.module}'
|
| 399 |
+
if _is_builtin_module(module):
|
| 400 |
+
# Make sure builtin module will be added into `self.imported_obj`
|
| 401 |
+
for alias in node.names:
|
| 402 |
+
if alias.asname is not None:
|
| 403 |
+
self.imported_obj.add(alias.asname)
|
| 404 |
+
elif alias.name == '*':
|
| 405 |
+
raise ConfigParsingError(
|
| 406 |
+
'Cannot import * from non-base config')
|
| 407 |
+
else:
|
| 408 |
+
self.imported_obj.add(alias.name)
|
| 409 |
+
return node
|
| 410 |
+
|
| 411 |
+
if module in self.base_dict:
|
| 412 |
+
for alias_node in node.names:
|
| 413 |
+
if alias_node.name == '*':
|
| 414 |
+
self.global_dict.update(self.base_dict[module])
|
| 415 |
+
return None
|
| 416 |
+
if alias_node.asname is not None:
|
| 417 |
+
base_key = alias_node.asname
|
| 418 |
+
else:
|
| 419 |
+
base_key = alias_node.name
|
| 420 |
+
self.global_dict[base_key] = self.base_dict[module][
|
| 421 |
+
alias_node.name]
|
| 422 |
+
return None
|
| 423 |
+
|
| 424 |
+
nodes: List[ast.Assign] = []
|
| 425 |
+
for alias_node in node.names:
|
| 426 |
+
# `ast.alias` has lineno attr after Python 3.10,
|
| 427 |
+
if hasattr(alias_node, 'lineno'):
|
| 428 |
+
lineno = alias_node.lineno
|
| 429 |
+
else:
|
| 430 |
+
lineno = node.lineno
|
| 431 |
+
if alias_node.name == '*':
|
| 432 |
+
raise ConfigParsingError(
|
| 433 |
+
'Illegal syntax in config! `from xxx import *` is not '
|
| 434 |
+
'allowed to appear outside the `if base:` statement')
|
| 435 |
+
elif alias_node.asname is not None:
|
| 436 |
+
code = f'{alias_node.asname} = LazyObject("{module}", "{alias_node.name}", "{self.filename}, line {lineno}")' # noqa: E501
|
| 437 |
+
self.imported_obj.add(alias_node.asname)
|
| 438 |
+
else:
|
| 439 |
+
code = f'{alias_node.name} = LazyObject("{module}", "{alias_node.name}", "{self.filename}, line {lineno}")' # noqa: E501
|
| 440 |
+
self.imported_obj.add(alias_node.name)
|
| 441 |
+
try:
|
| 442 |
+
nodes.append(ast.parse(code).body[0]) # type: ignore
|
| 443 |
+
except Exception as e:
|
| 444 |
+
raise ConfigParsingError(
|
| 445 |
+
f'Cannot import {alias_node} from {module}'
|
| 446 |
+
'1. Cannot import * from 3rd party lib in the config '
|
| 447 |
+
'file\n'
|
| 448 |
+
'2. Please check if the module is a base config which '
|
| 449 |
+
'should be added to `_base_`\n') from e
|
| 450 |
+
return nodes
|
| 451 |
+
|
| 452 |
+
def visit_Import(self, node) -> Union[ast.Assign, ast.Import]:
|
| 453 |
+
"""Work with ``_gather_abs_import_lazyobj`` to hack the ``import ...``
|
| 454 |
+
syntax.
|
| 455 |
+
"""
|
| 456 |
+
alias_list = node.names
|
| 457 |
+
assert len(alias_list) == 1, (
|
| 458 |
+
'Illegal syntax in config! import multiple modules in one line is '
|
| 459 |
+
'not supported')
|
| 460 |
+
# TODO Support multiline import
|
| 461 |
+
alias = alias_list[0]
|
| 462 |
+
if alias.asname is not None:
|
| 463 |
+
self.imported_obj.add(alias.asname)
|
| 464 |
+
if _is_builtin_module(alias.name.split('.')[0]):
|
| 465 |
+
return node
|
| 466 |
+
return ast.parse( # type: ignore
|
| 467 |
+
f'{alias.asname} = LazyObject('
|
| 468 |
+
f'"{alias.name}",'
|
| 469 |
+
f'location="{self.filename}, line {node.lineno}")').body[0]
|
| 470 |
+
return node
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def _gather_abs_import_lazyobj(tree: ast.Module,
|
| 474 |
+
filename: Optional[str] = None):
|
| 475 |
+
"""Experimental implementation of gathering absolute import information."""
|
| 476 |
+
if isinstance(filename, str):
|
| 477 |
+
filename = filename.encode('unicode_escape').decode()
|
| 478 |
+
imported = defaultdict(list)
|
| 479 |
+
abs_imported = set()
|
| 480 |
+
new_body: List[ast.stmt] = []
|
| 481 |
+
# module2node is used to get lineno when Python < 3.10
|
| 482 |
+
module2node: dict = dict()
|
| 483 |
+
for node in tree.body:
|
| 484 |
+
if isinstance(node, ast.Import):
|
| 485 |
+
for alias in node.names:
|
| 486 |
+
# Skip converting built-in module to LazyObject
|
| 487 |
+
if _is_builtin_module(alias.name):
|
| 488 |
+
new_body.append(node)
|
| 489 |
+
continue
|
| 490 |
+
module = alias.name.split('.')[0]
|
| 491 |
+
module2node.setdefault(module, node)
|
| 492 |
+
imported[module].append(alias)
|
| 493 |
+
continue
|
| 494 |
+
new_body.append(node)
|
| 495 |
+
|
| 496 |
+
for key, value in imported.items():
|
| 497 |
+
names = [_value.name for _value in value]
|
| 498 |
+
if hasattr(value[0], 'lineno'):
|
| 499 |
+
lineno = value[0].lineno
|
| 500 |
+
else:
|
| 501 |
+
lineno = module2node[key].lineno
|
| 502 |
+
lazy_module_assign = ast.parse(
|
| 503 |
+
f'{key} = LazyObject({names}, location="{filename}, line {lineno}")' # noqa: E501
|
| 504 |
+
) # noqa: E501
|
| 505 |
+
abs_imported.add(key)
|
| 506 |
+
new_body.insert(0, lazy_module_assign.body[0])
|
| 507 |
+
tree.body = new_body
|
| 508 |
+
return tree, abs_imported
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def get_installed_path(package: str) -> str:
|
| 512 |
+
"""Get installed path of package.
|
| 513 |
+
|
| 514 |
+
Replaced:
|
| 515 |
+
from pkg_resources import DistributionNotFound, get_distribution
|
| 516 |
+
|
| 517 |
+
Uses:
|
| 518 |
+
importlib.metadata
|
| 519 |
+
|
| 520 |
+
Args:
|
| 521 |
+
package (str): Name of package.
|
| 522 |
+
"""
|
| 523 |
+
try:
|
| 524 |
+
# 1. Try with importlib.metadata
|
| 525 |
+
pkg = importlib.metadata.distribution(package)
|
| 526 |
+
# pkg.locate is the directory containing the package, similar to pkg.location
|
| 527 |
+
possible_path = osp.join(pkg.locate(), package2module(package)) # Use package2module to ensure correct module dir
|
| 528 |
+
|
| 529 |
+
# Check if the main package dir exists in the location
|
| 530 |
+
if osp.exists(possible_path):
|
| 531 |
+
return possible_path
|
| 532 |
+
# Fallback to the distribution location itself (e.g., for namespace packages)
|
| 533 |
+
return pkg.locate()
|
| 534 |
+
|
| 535 |
+
except importlib.metadata.PackageNotFoundError as e:
|
| 536 |
+
# 2. If not found via metadata, check PYTHONPATH/sys.path via importlib.util.find_spec
|
| 537 |
+
spec = importlib.util.find_spec(package)
|
| 538 |
+
if spec is not None:
|
| 539 |
+
if spec.origin is not None:
|
| 540 |
+
# spec.origin is the path to the __init__.py or .py file
|
| 541 |
+
return osp.dirname(spec.origin)
|
| 542 |
+
else:
|
| 543 |
+
# Namespace packages don't have an origin but a spec exists
|
| 544 |
+
raise RuntimeError(
|
| 545 |
+
f'{package} is a namespace package, which is invalid '
|
| 546 |
+
'for `get_install_path` in this context')
|
| 547 |
+
else:
|
| 548 |
+
# Re-raise the original not found error, but as the new type
|
| 549 |
+
raise DistributionNotFound(
|
| 550 |
+
f"The 'Distribution' '{package}' was not found and is required"
|
| 551 |
+
) from e
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
def import_modules_from_strings(imports, allow_failed_imports=False):
|
| 555 |
+
"""Import modules from the given list of strings.
|
| 556 |
+
|
| 557 |
+
Args:
|
| 558 |
+
imports (list | str | None): The given module names to be imported.
|
| 559 |
+
allow_failed_imports (bool): If True, the failed imports will return
|
| 560 |
+
None. Otherwise, an ImportError is raise. Defaults to False.
|
| 561 |
+
|
| 562 |
+
Returns:
|
| 563 |
+
list[module] | module | None: The imported modules.
|
| 564 |
+
"""
|
| 565 |
+
if not imports:
|
| 566 |
+
return
|
| 567 |
+
single_import = False
|
| 568 |
+
if isinstance(imports, str):
|
| 569 |
+
single_import = True
|
| 570 |
+
imports = [imports]
|
| 571 |
+
if not isinstance(imports, list):
|
| 572 |
+
raise TypeError(
|
| 573 |
+
f'custom_imports must be a list but got type {type(imports)}')
|
| 574 |
+
imported = []
|
| 575 |
+
for imp in imports:
|
| 576 |
+
if not isinstance(imp, str):
|
| 577 |
+
raise TypeError(
|
| 578 |
+
f'{imp} is of type {type(imp)} and cannot be imported.')
|
| 579 |
+
try:
|
| 580 |
+
imported_tmp = import_module(imp)
|
| 581 |
+
except ImportError:
|
| 582 |
+
if allow_failed_imports:
|
| 583 |
+
warnings.warn(f'{imp} failed to import and is ignored.',
|
| 584 |
+
UserWarning)
|
| 585 |
+
imported_tmp = None
|
| 586 |
+
else:
|
| 587 |
+
raise ImportError(f'Failed to import {imp}')
|
| 588 |
+
imported.append(imported_tmp)
|
| 589 |
+
if single_import:
|
| 590 |
+
imported = imported[0]
|
| 591 |
+
return imported
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def import_module(name, package=None):
|
| 595 |
+
"""Import a module, optionally supporting relative imports."""
|
| 596 |
+
return real_import_module(name, package)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
def is_installed(package: str) -> bool:
|
| 600 |
+
"""Check package whether installed.
|
| 601 |
+
|
| 602 |
+
Replaced:
|
| 603 |
+
import pkg_resources
|
| 604 |
+
from pkg_resources import get_distribution
|
| 605 |
+
|
| 606 |
+
Uses:
|
| 607 |
+
importlib.metadata
|
| 608 |
+
|
| 609 |
+
Args:
|
| 610 |
+
package (str): Name of package to be checked.
|
| 611 |
+
"""
|
| 612 |
+
# Note: importlib.metadata.distribution() is generally the most reliable check
|
| 613 |
+
# for an installed package (e.g., via pip/wheel).
|
| 614 |
+
|
| 615 |
+
# 1. Check via importlib.metadata.distribution
|
| 616 |
+
try:
|
| 617 |
+
importlib.metadata.distribution(package)
|
| 618 |
+
return True
|
| 619 |
+
except importlib.metadata.PackageNotFoundError:
|
| 620 |
+
pass # Continue to step 2
|
| 621 |
+
|
| 622 |
+
# 2. Fallback check for packages potentially in PYTHONPATH without full metadata
|
| 623 |
+
spec = importlib.util.find_spec(package)
|
| 624 |
+
if spec is not None:
|
| 625 |
+
# If spec.origin is None, it's a namespace package (which is "found" but not installed like a normal package)
|
| 626 |
+
# If spec.origin is not None, it's a module/package file that was found.
|
| 627 |
+
return spec.origin is not None
|
| 628 |
+
|
| 629 |
+
return False
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
def dump(obj, file=None, file_format=None, **kwargs):
|
| 633 |
+
"""Dump data to json/yaml/pickle strings or files (mmengine-like replacement)."""
|
| 634 |
+
if isinstance(file, Path):
|
| 635 |
+
file = str(file)
|
| 636 |
+
|
| 637 |
+
# Guess file format if not explicitly given
|
| 638 |
+
if file_format is None:
|
| 639 |
+
if isinstance(file, str):
|
| 640 |
+
file_format = file.split('.')[-1].lower()
|
| 641 |
+
elif file is None:
|
| 642 |
+
raise ValueError("file_format must be specified if file is None")
|
| 643 |
+
|
| 644 |
+
if file_format not in ['json', 'yaml', 'yml', 'pkl', 'pickle']:
|
| 645 |
+
raise TypeError(f"Unsupported file format: {file_format}")
|
| 646 |
+
|
| 647 |
+
# Convert YAML extension
|
| 648 |
+
if file_format == 'yml':
|
| 649 |
+
file_format = 'yaml'
|
| 650 |
+
if file_format == 'pickle':
|
| 651 |
+
file_format = 'pkl'
|
| 652 |
+
|
| 653 |
+
# Handle output to string
|
| 654 |
+
if file is None:
|
| 655 |
+
if file_format == 'json':
|
| 656 |
+
return json.dumps(obj, indent=4, **kwargs)
|
| 657 |
+
elif file_format == 'yaml':
|
| 658 |
+
return yaml.dump(obj, **kwargs)
|
| 659 |
+
elif file_format == 'pkl':
|
| 660 |
+
return pickle.dumps(obj, **kwargs)
|
| 661 |
+
|
| 662 |
+
# Handle output to file
|
| 663 |
+
mode = 'w' if file_format in ['json', 'yaml'] else 'wb'
|
| 664 |
+
with open(file, mode, encoding='utf-8' if 'b' not in mode else None) as f:
|
| 665 |
+
if file_format == 'json':
|
| 666 |
+
json.dump(obj, f, indent=4, **kwargs)
|
| 667 |
+
elif file_format == 'yaml':
|
| 668 |
+
yaml.dump(obj, f, **kwargs)
|
| 669 |
+
elif file_format == 'pkl':
|
| 670 |
+
pickle.dump(obj, f, **kwargs)
|
| 671 |
+
|
| 672 |
+
return True
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
def check_file_exist(filename, msg_tmpl='file "{}" does not exist'):
|
| 676 |
+
if not osp.isfile(filename):
|
| 677 |
+
raise FileNotFoundError(msg_tmpl.format(filename))
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
def highlighted_error(msg: Union[str, Exception]) -> str:
|
| 681 |
+
# Assuming 'click' is installed or this is a placeholder
|
| 682 |
+
# If not using click, you can replace it with a simple string formatting for bold/red
|
| 683 |
+
try:
|
| 684 |
+
import click
|
| 685 |
+
return click.style(str(msg), fg='red', bold=True)
|
| 686 |
+
except ImportError:
|
| 687 |
+
return f"[ERROR] {msg}"
|
model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b0.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
norm_cfg = dict(type='SyncBN', requires_grad=True)
|
| 2 |
+
backbone = dict(
|
| 3 |
+
type='MixVisionTransformer',
|
| 4 |
+
in_channels=3,
|
| 5 |
+
embed_dims=32,
|
| 6 |
+
num_stages=4,
|
| 7 |
+
num_layers=[2, 2, 2, 2],
|
| 8 |
+
num_heads=[1, 2, 5, 8],
|
| 9 |
+
patch_sizes=[7, 3, 3, 3],
|
| 10 |
+
sr_ratios=[8, 4, 2, 1],
|
| 11 |
+
out_indices=(0, 1, 2, 3),
|
| 12 |
+
mlp_ratio=4,
|
| 13 |
+
qkv_bias=True,
|
| 14 |
+
drop_rate=0.0,
|
| 15 |
+
attn_drop_rate=0.0,
|
| 16 |
+
drop_path_rate=0.1
|
| 17 |
+
)
|
| 18 |
+
decode_head = dict(
|
| 19 |
+
type='SegformerHead',
|
| 20 |
+
in_channels=[32, 64, 160, 256],
|
| 21 |
+
in_index=[0, 1, 2, 3],
|
| 22 |
+
channels=256,
|
| 23 |
+
dropout_ratio=0.1,
|
| 24 |
+
out_channels=19,
|
| 25 |
+
norm_cfg=norm_cfg,
|
| 26 |
+
align_corners=False,
|
| 27 |
+
interpolate_mode='bilinear'
|
| 28 |
+
)
|
model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b1.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_base_ = ['./segformer_mit_b0.py']
|
| 2 |
+
|
| 3 |
+
backbone = dict(
|
| 4 |
+
embed_dims=64,
|
| 5 |
+
)
|
| 6 |
+
decode_head = dict(
|
| 7 |
+
in_channels=[64, 128, 320, 512]
|
| 8 |
+
)
|
model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b2.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_base_ = ['./segformer_mit_b1.py']
|
| 2 |
+
|
| 3 |
+
backbone = dict(
|
| 4 |
+
embed_dims=64,
|
| 5 |
+
num_layers=[3, 4, 6, 3]
|
| 6 |
+
)
|
model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b3.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_base_ = ['./segformer_mit_b1.py']
|
| 2 |
+
|
| 3 |
+
backbone = dict(
|
| 4 |
+
embed_dims=64,
|
| 5 |
+
num_layers=[3, 4, 18, 3]
|
| 6 |
+
)
|
model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b4.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_base_ = ['./segformer_mit_b1.py']
|
| 2 |
+
|
| 3 |
+
backbone = dict(
|
| 4 |
+
embed_dims=64,
|
| 5 |
+
num_layers=[3, 8, 27, 3]
|
| 6 |
+
)
|
model_without_OpenMMLab/segformer_plusplus/configs/segformer_mit_b5.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_base_ = ['./segformer_mit_b1.py']
|
| 2 |
+
|
| 3 |
+
backbone = dict(
|
| 4 |
+
embed_dims=64,
|
| 5 |
+
num_layers=[3, 6, 40, 3]
|
| 6 |
+
)
|
model_without_OpenMMLab/segformer_plusplus/model/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
__all__ = []
|