Spaces:
Running
on
Zero
Running
on
Zero
root
commited on
Commit
·
d01f62c
1
Parent(s):
6c86528
add test code
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitignore +141 -0
- LICENSE +437 -0
- dataset/__init__.py +0 -0
- dataset/range_transform.py +44 -0
- dataset/reseed.py +6 -0
- dataset/static_dataset.py +179 -0
- dataset/tps.py +37 -0
- dataset/util.py +12 -0
- dataset/vos_dataset.py +210 -0
- inference/__init__.py +0 -0
- inference/data/__init__.py +0 -0
- inference/data/mask_mapper.py +67 -0
- inference/data/test_datasets.py +29 -0
- inference/data/video_reader.py +107 -0
- inference/inference_core.py +111 -0
- inference/interact/__init__.py +0 -0
- inference/interact/fbrs/LICENSE +373 -0
- inference/interact/fbrs/__init__.py +0 -0
- inference/interact/fbrs/controller.py +103 -0
- inference/interact/fbrs/inference/__init__.py +0 -0
- inference/interact/fbrs/inference/clicker.py +103 -0
- inference/interact/fbrs/inference/evaluation.py +56 -0
- inference/interact/fbrs/inference/predictors/__init__.py +95 -0
- inference/interact/fbrs/inference/predictors/base.py +100 -0
- inference/interact/fbrs/inference/predictors/brs.py +280 -0
- inference/interact/fbrs/inference/predictors/brs_functors.py +109 -0
- inference/interact/fbrs/inference/predictors/brs_losses.py +58 -0
- inference/interact/fbrs/inference/transforms/__init__.py +5 -0
- inference/interact/fbrs/inference/transforms/base.py +38 -0
- inference/interact/fbrs/inference/transforms/crops.py +97 -0
- inference/interact/fbrs/inference/transforms/flip.py +37 -0
- inference/interact/fbrs/inference/transforms/limit_longest_side.py +22 -0
- inference/interact/fbrs/inference/transforms/zoom_in.py +171 -0
- inference/interact/fbrs/inference/utils.py +177 -0
- inference/interact/fbrs/model/__init__.py +0 -0
- inference/interact/fbrs/model/initializer.py +105 -0
- inference/interact/fbrs/model/is_deeplab_model.py +86 -0
- inference/interact/fbrs/model/is_hrnet_model.py +87 -0
- inference/interact/fbrs/model/losses.py +134 -0
- inference/interact/fbrs/model/metrics.py +101 -0
- inference/interact/fbrs/model/modeling/__init__.py +0 -0
- inference/interact/fbrs/model/modeling/basic_blocks.py +71 -0
- inference/interact/fbrs/model/modeling/deeplab_v3.py +176 -0
- inference/interact/fbrs/model/modeling/hrnet_ocr.py +399 -0
- inference/interact/fbrs/model/modeling/ocr.py +141 -0
- inference/interact/fbrs/model/modeling/resnet.py +39 -0
- inference/interact/fbrs/model/modeling/resnetv1b.py +276 -0
- inference/interact/fbrs/model/ops.py +83 -0
- inference/interact/fbrs/model/syncbn/LICENSE +21 -0
- inference/interact/fbrs/model/syncbn/README.md +127 -0
.gitignore
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
log/
|
2 |
+
output/
|
3 |
+
.vscode/
|
4 |
+
workspace/
|
5 |
+
tmp_occupy_memory_saves/
|
6 |
+
run*.sh
|
7 |
+
py-thin-plate-spline
|
8 |
+
wandb/
|
9 |
+
pretrain/
|
10 |
+
Pytorch-Correlation-extension/
|
11 |
+
result
|
12 |
+
|
13 |
+
# Byte-compiled / optimized / DLL files
|
14 |
+
__pycache__/
|
15 |
+
*.py[cod]
|
16 |
+
*$py.class
|
17 |
+
|
18 |
+
# C extensions
|
19 |
+
*.so
|
20 |
+
|
21 |
+
# Distribution / packaging
|
22 |
+
.Python
|
23 |
+
build/
|
24 |
+
develop-eggs/
|
25 |
+
dist/
|
26 |
+
downloads/
|
27 |
+
eggs/
|
28 |
+
.eggs/
|
29 |
+
lib/
|
30 |
+
lib64/
|
31 |
+
parts/
|
32 |
+
sdist/
|
33 |
+
var/
|
34 |
+
wheels/
|
35 |
+
pip-wheel-metadata/
|
36 |
+
share/python-wheels/
|
37 |
+
*.egg-info/
|
38 |
+
.installed.cfg
|
39 |
+
*.egg
|
40 |
+
MANIFEST
|
41 |
+
|
42 |
+
# PyInstaller
|
43 |
+
# Usually these files are written by a python script from a template
|
44 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
45 |
+
*.manifest
|
46 |
+
*.spec
|
47 |
+
|
48 |
+
# Installer logs
|
49 |
+
pip-log.txt
|
50 |
+
pip-delete-this-directory.txt
|
51 |
+
|
52 |
+
# Unit test / coverage reports
|
53 |
+
htmlcov/
|
54 |
+
.tox/
|
55 |
+
.nox/
|
56 |
+
.coverage
|
57 |
+
.coverage.*
|
58 |
+
.cache
|
59 |
+
nosetests.xml
|
60 |
+
coverage.xml
|
61 |
+
*.cover
|
62 |
+
*.py,cover
|
63 |
+
.hypothesis/
|
64 |
+
.pytest_cache/
|
65 |
+
|
66 |
+
# Translations
|
67 |
+
*.mo
|
68 |
+
*.pot
|
69 |
+
|
70 |
+
# Django stuff:
|
71 |
+
*.log
|
72 |
+
local_settings.py
|
73 |
+
db.sqlite3
|
74 |
+
db.sqlite3-journal
|
75 |
+
|
76 |
+
# Flask stuff:
|
77 |
+
instance/
|
78 |
+
.webassets-cache
|
79 |
+
|
80 |
+
# Scrapy stuff:
|
81 |
+
.scrapy
|
82 |
+
|
83 |
+
# Sphinx documentation
|
84 |
+
docs/_build/
|
85 |
+
|
86 |
+
# PyBuilder
|
87 |
+
target/
|
88 |
+
|
89 |
+
# Jupyter Notebook
|
90 |
+
.ipynb_checkpoints
|
91 |
+
|
92 |
+
# IPython
|
93 |
+
profile_default/
|
94 |
+
ipython_config.py
|
95 |
+
|
96 |
+
# pyenv
|
97 |
+
.python-version
|
98 |
+
|
99 |
+
# pipenv
|
100 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
101 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
102 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
103 |
+
# install all needed dependencies.
|
104 |
+
#Pipfile.lock
|
105 |
+
|
106 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
107 |
+
__pypackages__/
|
108 |
+
|
109 |
+
# Celery stuff
|
110 |
+
celerybeat-schedule
|
111 |
+
celerybeat.pid
|
112 |
+
|
113 |
+
# SageMath parsed files
|
114 |
+
*.sage.py
|
115 |
+
|
116 |
+
# Environments
|
117 |
+
.env
|
118 |
+
.venv
|
119 |
+
env/
|
120 |
+
venv/
|
121 |
+
ENV/
|
122 |
+
env.bak/
|
123 |
+
venv.bak/
|
124 |
+
|
125 |
+
# Spyder project settings
|
126 |
+
.spyderproject
|
127 |
+
.spyproject
|
128 |
+
|
129 |
+
# Rope project settings
|
130 |
+
.ropeproject
|
131 |
+
|
132 |
+
# mkdocs documentation
|
133 |
+
/site
|
134 |
+
|
135 |
+
# mypy
|
136 |
+
.mypy_cache/
|
137 |
+
.dmypy.json
|
138 |
+
dmypy.json
|
139 |
+
|
140 |
+
# Pyre type checker
|
141 |
+
.pyre/
|
LICENSE
ADDED
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Attribution-NonCommercial-ShareAlike 4.0 International
|
2 |
+
|
3 |
+
=======================================================================
|
4 |
+
|
5 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
6 |
+
does not provide legal services or legal advice. Distribution of
|
7 |
+
Creative Commons public licenses does not create a lawyer-client or
|
8 |
+
other relationship. Creative Commons makes its licenses and related
|
9 |
+
information available on an "as-is" basis. Creative Commons gives no
|
10 |
+
warranties regarding its licenses, any material licensed under their
|
11 |
+
terms and conditions, or any related information. Creative Commons
|
12 |
+
disclaims all liability for damages resulting from their use to the
|
13 |
+
fullest extent possible.
|
14 |
+
|
15 |
+
Using Creative Commons Public Licenses
|
16 |
+
|
17 |
+
Creative Commons public licenses provide a standard set of terms and
|
18 |
+
conditions that creators and other rights holders may use to share
|
19 |
+
original works of authorship and other material subject to copyright
|
20 |
+
and certain other rights specified in the public license below. The
|
21 |
+
following considerations are for informational purposes only, are not
|
22 |
+
exhaustive, and do not form part of our licenses.
|
23 |
+
|
24 |
+
Considerations for licensors: Our public licenses are
|
25 |
+
intended for use by those authorized to give the public
|
26 |
+
permission to use material in ways otherwise restricted by
|
27 |
+
copyright and certain other rights. Our licenses are
|
28 |
+
irrevocable. Licensors should read and understand the terms
|
29 |
+
and conditions of the license they choose before applying it.
|
30 |
+
Licensors should also secure all rights necessary before
|
31 |
+
applying our licenses so that the public can reuse the
|
32 |
+
material as expected. Licensors should clearly mark any
|
33 |
+
material not subject to the license. This includes other CC-
|
34 |
+
licensed material, or material used under an exception or
|
35 |
+
limitation to copyright. More considerations for licensors:
|
36 |
+
wiki.creativecommons.org/Considerations_for_licensors
|
37 |
+
|
38 |
+
Considerations for the public: By using one of our public
|
39 |
+
licenses, a licensor grants the public permission to use the
|
40 |
+
licensed material under specified terms and conditions. If
|
41 |
+
the licensor's permission is not necessary for any reason--for
|
42 |
+
example, because of any applicable exception or limitation to
|
43 |
+
copyright--then that use is not regulated by the license. Our
|
44 |
+
licenses grant only permissions under copyright and certain
|
45 |
+
other rights that a licensor has authority to grant. Use of
|
46 |
+
the licensed material may still be restricted for other
|
47 |
+
reasons, including because others have copyright or other
|
48 |
+
rights in the material. A licensor may make special requests,
|
49 |
+
such as asking that all changes be marked or described.
|
50 |
+
Although not required by our licenses, you are encouraged to
|
51 |
+
respect those requests where reasonable. More considerations
|
52 |
+
for the public:
|
53 |
+
wiki.creativecommons.org/Considerations_for_licensees
|
54 |
+
|
55 |
+
=======================================================================
|
56 |
+
|
57 |
+
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
|
58 |
+
Public License
|
59 |
+
|
60 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
61 |
+
to be bound by the terms and conditions of this Creative Commons
|
62 |
+
Attribution-NonCommercial-ShareAlike 4.0 International Public License
|
63 |
+
("Public License"). To the extent this Public License may be
|
64 |
+
interpreted as a contract, You are granted the Licensed Rights in
|
65 |
+
consideration of Your acceptance of these terms and conditions, and the
|
66 |
+
Licensor grants You such rights in consideration of benefits the
|
67 |
+
Licensor receives from making the Licensed Material available under
|
68 |
+
these terms and conditions.
|
69 |
+
|
70 |
+
|
71 |
+
Section 1 -- Definitions.
|
72 |
+
|
73 |
+
a. Adapted Material means material subject to Copyright and Similar
|
74 |
+
Rights that is derived from or based upon the Licensed Material
|
75 |
+
and in which the Licensed Material is translated, altered,
|
76 |
+
arranged, transformed, or otherwise modified in a manner requiring
|
77 |
+
permission under the Copyright and Similar Rights held by the
|
78 |
+
Licensor. For purposes of this Public License, where the Licensed
|
79 |
+
Material is a musical work, performance, or sound recording,
|
80 |
+
Adapted Material is always produced where the Licensed Material is
|
81 |
+
synched in timed relation with a moving image.
|
82 |
+
|
83 |
+
b. Adapter's License means the license You apply to Your Copyright
|
84 |
+
and Similar Rights in Your contributions to Adapted Material in
|
85 |
+
accordance with the terms and conditions of this Public License.
|
86 |
+
|
87 |
+
c. BY-NC-SA Compatible License means a license listed at
|
88 |
+
creativecommons.org/compatiblelicenses, approved by Creative
|
89 |
+
Commons as essentially the equivalent of this Public License.
|
90 |
+
|
91 |
+
d. Copyright and Similar Rights means copyright and/or similar rights
|
92 |
+
closely related to copyright including, without limitation,
|
93 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
94 |
+
Rights, without regard to how the rights are labeled or
|
95 |
+
categorized. For purposes of this Public License, the rights
|
96 |
+
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
97 |
+
Rights.
|
98 |
+
|
99 |
+
e. Effective Technological Measures means those measures that, in the
|
100 |
+
absence of proper authority, may not be circumvented under laws
|
101 |
+
fulfilling obligations under Article 11 of the WIPO Copyright
|
102 |
+
Treaty adopted on December 20, 1996, and/or similar international
|
103 |
+
agreements.
|
104 |
+
|
105 |
+
f. Exceptions and Limitations means fair use, fair dealing, and/or
|
106 |
+
any other exception or limitation to Copyright and Similar Rights
|
107 |
+
that applies to Your use of the Licensed Material.
|
108 |
+
|
109 |
+
g. License Elements means the license attributes listed in the name
|
110 |
+
of a Creative Commons Public License. The License Elements of this
|
111 |
+
Public License are Attribution, NonCommercial, and ShareAlike.
|
112 |
+
|
113 |
+
h. Licensed Material means the artistic or literary work, database,
|
114 |
+
or other material to which the Licensor applied this Public
|
115 |
+
License.
|
116 |
+
|
117 |
+
i. Licensed Rights means the rights granted to You subject to the
|
118 |
+
terms and conditions of this Public License, which are limited to
|
119 |
+
all Copyright and Similar Rights that apply to Your use of the
|
120 |
+
Licensed Material and that the Licensor has authority to license.
|
121 |
+
|
122 |
+
j. Licensor means the individual(s) or entity(ies) granting rights
|
123 |
+
under this Public License.
|
124 |
+
|
125 |
+
k. NonCommercial means not primarily intended for or directed towards
|
126 |
+
commercial advantage or monetary compensation. For purposes of
|
127 |
+
this Public License, the exchange of the Licensed Material for
|
128 |
+
other material subject to Copyright and Similar Rights by digital
|
129 |
+
file-sharing or similar means is NonCommercial provided there is
|
130 |
+
no payment of monetary compensation in connection with the
|
131 |
+
exchange.
|
132 |
+
|
133 |
+
l. Share means to provide material to the public by any means or
|
134 |
+
process that requires permission under the Licensed Rights, such
|
135 |
+
as reproduction, public display, public performance, distribution,
|
136 |
+
dissemination, communication, or importation, and to make material
|
137 |
+
available to the public including in ways that members of the
|
138 |
+
public may access the material from a place and at a time
|
139 |
+
individually chosen by them.
|
140 |
+
|
141 |
+
m. Sui Generis Database Rights means rights other than copyright
|
142 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
143 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
144 |
+
as amended and/or succeeded, as well as other essentially
|
145 |
+
equivalent rights anywhere in the world.
|
146 |
+
|
147 |
+
n. You means the individual or entity exercising the Licensed Rights
|
148 |
+
under this Public License. Your has a corresponding meaning.
|
149 |
+
|
150 |
+
|
151 |
+
Section 2 -- Scope.
|
152 |
+
|
153 |
+
a. License grant.
|
154 |
+
|
155 |
+
1. Subject to the terms and conditions of this Public License,
|
156 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
157 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
158 |
+
exercise the Licensed Rights in the Licensed Material to:
|
159 |
+
|
160 |
+
a. reproduce and Share the Licensed Material, in whole or
|
161 |
+
in part, for NonCommercial purposes only; and
|
162 |
+
|
163 |
+
b. produce, reproduce, and Share Adapted Material for
|
164 |
+
NonCommercial purposes only.
|
165 |
+
|
166 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where
|
167 |
+
Exceptions and Limitations apply to Your use, this Public
|
168 |
+
License does not apply, and You do not need to comply with
|
169 |
+
its terms and conditions.
|
170 |
+
|
171 |
+
3. Term. The term of this Public License is specified in Section
|
172 |
+
6(a).
|
173 |
+
|
174 |
+
4. Media and formats; technical modifications allowed. The
|
175 |
+
Licensor authorizes You to exercise the Licensed Rights in
|
176 |
+
all media and formats whether now known or hereafter created,
|
177 |
+
and to make technical modifications necessary to do so. The
|
178 |
+
Licensor waives and/or agrees not to assert any right or
|
179 |
+
authority to forbid You from making technical modifications
|
180 |
+
necessary to exercise the Licensed Rights, including
|
181 |
+
technical modifications necessary to circumvent Effective
|
182 |
+
Technological Measures. For purposes of this Public License,
|
183 |
+
simply making modifications authorized by this Section 2(a)
|
184 |
+
(4) never produces Adapted Material.
|
185 |
+
|
186 |
+
5. Downstream recipients.
|
187 |
+
|
188 |
+
a. Offer from the Licensor -- Licensed Material. Every
|
189 |
+
recipient of the Licensed Material automatically
|
190 |
+
receives an offer from the Licensor to exercise the
|
191 |
+
Licensed Rights under the terms and conditions of this
|
192 |
+
Public License.
|
193 |
+
|
194 |
+
b. Additional offer from the Licensor -- Adapted Material.
|
195 |
+
Every recipient of Adapted Material from You
|
196 |
+
automatically receives an offer from the Licensor to
|
197 |
+
exercise the Licensed Rights in the Adapted Material
|
198 |
+
under the conditions of the Adapter's License You apply.
|
199 |
+
|
200 |
+
c. No downstream restrictions. You may not offer or impose
|
201 |
+
any additional or different terms or conditions on, or
|
202 |
+
apply any Effective Technological Measures to, the
|
203 |
+
Licensed Material if doing so restricts exercise of the
|
204 |
+
Licensed Rights by any recipient of the Licensed
|
205 |
+
Material.
|
206 |
+
|
207 |
+
6. No endorsement. Nothing in this Public License constitutes or
|
208 |
+
may be construed as permission to assert or imply that You
|
209 |
+
are, or that Your use of the Licensed Material is, connected
|
210 |
+
with, or sponsored, endorsed, or granted official status by,
|
211 |
+
the Licensor or others designated to receive attribution as
|
212 |
+
provided in Section 3(a)(1)(A)(i).
|
213 |
+
|
214 |
+
b. Other rights.
|
215 |
+
|
216 |
+
1. Moral rights, such as the right of integrity, are not
|
217 |
+
licensed under this Public License, nor are publicity,
|
218 |
+
privacy, and/or other similar personality rights; however, to
|
219 |
+
the extent possible, the Licensor waives and/or agrees not to
|
220 |
+
assert any such rights held by the Licensor to the limited
|
221 |
+
extent necessary to allow You to exercise the Licensed
|
222 |
+
Rights, but not otherwise.
|
223 |
+
|
224 |
+
2. Patent and trademark rights are not licensed under this
|
225 |
+
Public License.
|
226 |
+
|
227 |
+
3. To the extent possible, the Licensor waives any right to
|
228 |
+
collect royalties from You for the exercise of the Licensed
|
229 |
+
Rights, whether directly or through a collecting society
|
230 |
+
under any voluntary or waivable statutory or compulsory
|
231 |
+
licensing scheme. In all other cases the Licensor expressly
|
232 |
+
reserves any right to collect such royalties, including when
|
233 |
+
the Licensed Material is used other than for NonCommercial
|
234 |
+
purposes.
|
235 |
+
|
236 |
+
|
237 |
+
Section 3 -- License Conditions.
|
238 |
+
|
239 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
240 |
+
following conditions.
|
241 |
+
|
242 |
+
a. Attribution.
|
243 |
+
|
244 |
+
1. If You Share the Licensed Material (including in modified
|
245 |
+
form), You must:
|
246 |
+
|
247 |
+
a. retain the following if it is supplied by the Licensor
|
248 |
+
with the Licensed Material:
|
249 |
+
|
250 |
+
i. identification of the creator(s) of the Licensed
|
251 |
+
Material and any others designated to receive
|
252 |
+
attribution, in any reasonable manner requested by
|
253 |
+
the Licensor (including by pseudonym if
|
254 |
+
designated);
|
255 |
+
|
256 |
+
ii. a copyright notice;
|
257 |
+
|
258 |
+
iii. a notice that refers to this Public License;
|
259 |
+
|
260 |
+
iv. a notice that refers to the disclaimer of
|
261 |
+
warranties;
|
262 |
+
|
263 |
+
v. a URI or hyperlink to the Licensed Material to the
|
264 |
+
extent reasonably practicable;
|
265 |
+
|
266 |
+
b. indicate if You modified the Licensed Material and
|
267 |
+
retain an indication of any previous modifications; and
|
268 |
+
|
269 |
+
c. indicate the Licensed Material is licensed under this
|
270 |
+
Public License, and include the text of, or the URI or
|
271 |
+
hyperlink to, this Public License.
|
272 |
+
|
273 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any
|
274 |
+
reasonable manner based on the medium, means, and context in
|
275 |
+
which You Share the Licensed Material. For example, it may be
|
276 |
+
reasonable to satisfy the conditions by providing a URI or
|
277 |
+
hyperlink to a resource that includes the required
|
278 |
+
information.
|
279 |
+
3. If requested by the Licensor, You must remove any of the
|
280 |
+
information required by Section 3(a)(1)(A) to the extent
|
281 |
+
reasonably practicable.
|
282 |
+
|
283 |
+
b. ShareAlike.
|
284 |
+
|
285 |
+
In addition to the conditions in Section 3(a), if You Share
|
286 |
+
Adapted Material You produce, the following conditions also apply.
|
287 |
+
|
288 |
+
1. The Adapter's License You apply must be a Creative Commons
|
289 |
+
license with the same License Elements, this version or
|
290 |
+
later, or a BY-NC-SA Compatible License.
|
291 |
+
|
292 |
+
2. You must include the text of, or the URI or hyperlink to, the
|
293 |
+
Adapter's License You apply. You may satisfy this condition
|
294 |
+
in any reasonable manner based on the medium, means, and
|
295 |
+
context in which You Share Adapted Material.
|
296 |
+
|
297 |
+
3. You may not offer or impose any additional or different terms
|
298 |
+
or conditions on, or apply any Effective Technological
|
299 |
+
Measures to, Adapted Material that restrict exercise of the
|
300 |
+
rights granted under the Adapter's License You apply.
|
301 |
+
|
302 |
+
|
303 |
+
Section 4 -- Sui Generis Database Rights.
|
304 |
+
|
305 |
+
Where the Licensed Rights include Sui Generis Database Rights that
|
306 |
+
apply to Your use of the Licensed Material:
|
307 |
+
|
308 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
309 |
+
to extract, reuse, reproduce, and Share all or a substantial
|
310 |
+
portion of the contents of the database for NonCommercial purposes
|
311 |
+
only;
|
312 |
+
|
313 |
+
b. if You include all or a substantial portion of the database
|
314 |
+
contents in a database in which You have Sui Generis Database
|
315 |
+
Rights, then the database in which You have Sui Generis Database
|
316 |
+
Rights (but not its individual contents) is Adapted Material,
|
317 |
+
including for purposes of Section 3(b); and
|
318 |
+
|
319 |
+
c. You must comply with the conditions in Section 3(a) if You Share
|
320 |
+
all or a substantial portion of the contents of the database.
|
321 |
+
|
322 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
323 |
+
replace Your obligations under this Public License where the Licensed
|
324 |
+
Rights include other Copyright and Similar Rights.
|
325 |
+
|
326 |
+
|
327 |
+
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
328 |
+
|
329 |
+
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
330 |
+
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
331 |
+
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
332 |
+
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
333 |
+
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
334 |
+
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
335 |
+
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
336 |
+
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
337 |
+
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
338 |
+
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
339 |
+
|
340 |
+
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
341 |
+
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
342 |
+
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
343 |
+
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
344 |
+
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
345 |
+
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
346 |
+
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
347 |
+
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
348 |
+
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
349 |
+
|
350 |
+
c. The disclaimer of warranties and limitation of liability provided
|
351 |
+
above shall be interpreted in a manner that, to the extent
|
352 |
+
possible, most closely approximates an absolute disclaimer and
|
353 |
+
waiver of all liability.
|
354 |
+
|
355 |
+
|
356 |
+
Section 6 -- Term and Termination.
|
357 |
+
|
358 |
+
a. This Public License applies for the term of the Copyright and
|
359 |
+
Similar Rights licensed here. However, if You fail to comply with
|
360 |
+
this Public License, then Your rights under this Public License
|
361 |
+
terminate automatically.
|
362 |
+
|
363 |
+
b. Where Your right to use the Licensed Material has terminated under
|
364 |
+
Section 6(a), it reinstates:
|
365 |
+
|
366 |
+
1. automatically as of the date the violation is cured, provided
|
367 |
+
it is cured within 30 days of Your discovery of the
|
368 |
+
violation; or
|
369 |
+
|
370 |
+
2. upon express reinstatement by the Licensor.
|
371 |
+
|
372 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
373 |
+
right the Licensor may have to seek remedies for Your violations
|
374 |
+
of this Public License.
|
375 |
+
|
376 |
+
c. For the avoidance of doubt, the Licensor may also offer the
|
377 |
+
Licensed Material under separate terms or conditions or stop
|
378 |
+
distributing the Licensed Material at any time; however, doing so
|
379 |
+
will not terminate this Public License.
|
380 |
+
|
381 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
382 |
+
License.
|
383 |
+
|
384 |
+
|
385 |
+
Section 7 -- Other Terms and Conditions.
|
386 |
+
|
387 |
+
a. The Licensor shall not be bound by any additional or different
|
388 |
+
terms or conditions communicated by You unless expressly agreed.
|
389 |
+
|
390 |
+
b. Any arrangements, understandings, or agreements regarding the
|
391 |
+
Licensed Material not stated herein are separate from and
|
392 |
+
independent of the terms and conditions of this Public License.
|
393 |
+
|
394 |
+
|
395 |
+
Section 8 -- Interpretation.
|
396 |
+
|
397 |
+
a. For the avoidance of doubt, this Public License does not, and
|
398 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
399 |
+
conditions on any use of the Licensed Material that could lawfully
|
400 |
+
be made without permission under this Public License.
|
401 |
+
|
402 |
+
b. To the extent possible, if any provision of this Public License is
|
403 |
+
deemed unenforceable, it shall be automatically reformed to the
|
404 |
+
minimum extent necessary to make it enforceable. If the provision
|
405 |
+
cannot be reformed, it shall be severed from this Public License
|
406 |
+
without affecting the enforceability of the remaining terms and
|
407 |
+
conditions.
|
408 |
+
|
409 |
+
c. No term or condition of this Public License will be waived and no
|
410 |
+
failure to comply consented to unless expressly agreed to by the
|
411 |
+
Licensor.
|
412 |
+
|
413 |
+
d. Nothing in this Public License constitutes or may be interpreted
|
414 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
415 |
+
that apply to the Licensor or You, including from the legal
|
416 |
+
processes of any jurisdiction or authority.
|
417 |
+
|
418 |
+
=======================================================================
|
419 |
+
|
420 |
+
Creative Commons is not a party to its public
|
421 |
+
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
422 |
+
its public licenses to material it publishes and in those instances
|
423 |
+
will be considered the “Licensor.” The text of the Creative Commons
|
424 |
+
public licenses is dedicated to the public domain under the CC0 Public
|
425 |
+
Domain Dedication. Except for the limited purpose of indicating that
|
426 |
+
material is shared under a Creative Commons public license or as
|
427 |
+
otherwise permitted by the Creative Commons policies published at
|
428 |
+
creativecommons.org/policies, Creative Commons does not authorize the
|
429 |
+
use of the trademark "Creative Commons" or any other trademark or logo
|
430 |
+
of Creative Commons without its prior written consent including,
|
431 |
+
without limitation, in connection with any unauthorized modifications
|
432 |
+
to any of its public licenses or any other arrangements,
|
433 |
+
understandings, or agreements concerning use of licensed material. For
|
434 |
+
the avoidance of doubt, this paragraph does not form part of the
|
435 |
+
public licenses.
|
436 |
+
|
437 |
+
Creative Commons may be contacted at creativecommons.org.
|
dataset/__init__.py
ADDED
File without changes
|
dataset/range_transform.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torchvision.transforms as transforms
|
2 |
+
import util.functional as F
|
3 |
+
import numpy as np
|
4 |
+
from skimage import color
|
5 |
+
|
6 |
+
im_mean = (124, 116, 104)
|
7 |
+
|
8 |
+
im_normalization = transforms.Normalize(
|
9 |
+
mean=[0.485, 0.456, 0.406],
|
10 |
+
std=[0.229, 0.224, 0.225]
|
11 |
+
)
|
12 |
+
|
13 |
+
inv_im_trans = transforms.Normalize(
|
14 |
+
mean=[-0.485/0.229, -0.456/0.224, -0.406/0.225],
|
15 |
+
std=[1/0.229, 1/0.224, 1/0.225])
|
16 |
+
|
17 |
+
# tensor l[-1, 1] ab[-1, 1]
|
18 |
+
# numpy l[0 100] ab[-127 128]
|
19 |
+
# transforms.Normalize: x_new = (x-mean) / std
|
20 |
+
inv_lll2rgb_trans = transforms.Normalize(
|
21 |
+
mean=[-1, 0, 0],
|
22 |
+
std=[1/50., 1/110., 1/110.])
|
23 |
+
|
24 |
+
im_rgb2lab_normalization = transforms.Normalize(
|
25 |
+
mean=[50, 0, 0],
|
26 |
+
std=[50, 110, 110])
|
27 |
+
|
28 |
+
class ToTensor(object):
|
29 |
+
def __init__(self):
|
30 |
+
pass
|
31 |
+
|
32 |
+
def __call__(self, inputs):
|
33 |
+
return F.to_mytensor(inputs)
|
34 |
+
|
35 |
+
class RGB2Lab(object):
|
36 |
+
def __init__(self):
|
37 |
+
pass
|
38 |
+
|
39 |
+
def __call__(self, inputs):
|
40 |
+
# default return float64
|
41 |
+
# return color.rgb2lab(inputs)
|
42 |
+
|
43 |
+
# return float32
|
44 |
+
return np.float32(color.rgb2lab(inputs))
|
dataset/reseed.py
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import random
|
3 |
+
|
4 |
+
def reseed(seed):
|
5 |
+
random.seed(seed)
|
6 |
+
torch.manual_seed(seed)
|
dataset/static_dataset.py
ADDED
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from os import path
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from torch.utils.data.dataset import Dataset
|
6 |
+
from torchvision import transforms
|
7 |
+
from torchvision.transforms import InterpolationMode
|
8 |
+
from PIL import Image
|
9 |
+
import numpy as np
|
10 |
+
|
11 |
+
from dataset.range_transform import im_normalization, im_mean
|
12 |
+
from dataset.tps import random_tps_warp
|
13 |
+
from dataset.reseed import reseed
|
14 |
+
|
15 |
+
|
16 |
+
class StaticTransformDataset(Dataset):
|
17 |
+
"""
|
18 |
+
Generate pseudo VOS data by applying random transforms on static images.
|
19 |
+
Single-object only.
|
20 |
+
|
21 |
+
Method 0 - FSS style (class/1.jpg class/1.png)
|
22 |
+
Method 1 - Others style (XXX.jpg XXX.png)
|
23 |
+
"""
|
24 |
+
def __init__(self, parameters, num_frames=3, max_num_obj=1):
|
25 |
+
self.num_frames = num_frames
|
26 |
+
self.max_num_obj = max_num_obj
|
27 |
+
|
28 |
+
self.im_list = []
|
29 |
+
for parameter in parameters:
|
30 |
+
root, method, multiplier = parameter
|
31 |
+
if method == 0:
|
32 |
+
# Get images
|
33 |
+
classes = os.listdir(root)
|
34 |
+
for c in classes:
|
35 |
+
imgs = os.listdir(path.join(root, c))
|
36 |
+
jpg_list = [im for im in imgs if 'jpg' in im[-3:].lower()]
|
37 |
+
|
38 |
+
joint_list = [path.join(root, c, im) for im in jpg_list]
|
39 |
+
self.im_list.extend(joint_list * multiplier)
|
40 |
+
|
41 |
+
elif method == 1:
|
42 |
+
self.im_list.extend([path.join(root, im) for im in os.listdir(root) if '.jpg' in im] * multiplier)
|
43 |
+
|
44 |
+
print(f'{len(self.im_list)} images found.')
|
45 |
+
|
46 |
+
# These set of transform is the same for im/gt pairs, but different among the 3 sampled frames
|
47 |
+
self.pair_im_lone_transform = transforms.Compose([
|
48 |
+
transforms.ColorJitter(0.1, 0.05, 0.05, 0), # No hue change here as that's not realistic
|
49 |
+
])
|
50 |
+
|
51 |
+
self.pair_im_dual_transform = transforms.Compose([
|
52 |
+
transforms.RandomAffine(degrees=20, scale=(0.9,1.1), shear=10, interpolation=InterpolationMode.BICUBIC, fill=im_mean),
|
53 |
+
transforms.Resize(384, InterpolationMode.BICUBIC),
|
54 |
+
transforms.RandomCrop((384, 384), pad_if_needed=True, fill=im_mean),
|
55 |
+
])
|
56 |
+
|
57 |
+
self.pair_gt_dual_transform = transforms.Compose([
|
58 |
+
transforms.RandomAffine(degrees=20, scale=(0.9,1.1), shear=10, interpolation=InterpolationMode.BICUBIC, fill=0),
|
59 |
+
transforms.Resize(384, InterpolationMode.NEAREST),
|
60 |
+
transforms.RandomCrop((384, 384), pad_if_needed=True, fill=0),
|
61 |
+
])
|
62 |
+
|
63 |
+
|
64 |
+
# These transform are the same for all pairs in the sampled sequence
|
65 |
+
self.all_im_lone_transform = transforms.Compose([
|
66 |
+
transforms.ColorJitter(0.1, 0.05, 0.05, 0.05),
|
67 |
+
transforms.RandomGrayscale(0.05),
|
68 |
+
])
|
69 |
+
|
70 |
+
self.all_im_dual_transform = transforms.Compose([
|
71 |
+
transforms.RandomAffine(degrees=0, scale=(0.8, 1.5), fill=im_mean),
|
72 |
+
transforms.RandomHorizontalFlip(),
|
73 |
+
])
|
74 |
+
|
75 |
+
self.all_gt_dual_transform = transforms.Compose([
|
76 |
+
transforms.RandomAffine(degrees=0, scale=(0.8, 1.5), fill=0),
|
77 |
+
transforms.RandomHorizontalFlip(),
|
78 |
+
])
|
79 |
+
|
80 |
+
# Final transform without randomness
|
81 |
+
self.final_im_transform = transforms.Compose([
|
82 |
+
transforms.ToTensor(),
|
83 |
+
im_normalization,
|
84 |
+
])
|
85 |
+
|
86 |
+
self.final_gt_transform = transforms.Compose([
|
87 |
+
transforms.ToTensor(),
|
88 |
+
])
|
89 |
+
|
90 |
+
def _get_sample(self, idx):
|
91 |
+
im = Image.open(self.im_list[idx]).convert('RGB')
|
92 |
+
gt = Image.open(self.im_list[idx][:-3]+'png').convert('L')
|
93 |
+
|
94 |
+
sequence_seed = np.random.randint(2147483647)
|
95 |
+
|
96 |
+
images = []
|
97 |
+
masks = []
|
98 |
+
for _ in range(self.num_frames):
|
99 |
+
reseed(sequence_seed)
|
100 |
+
this_im = self.all_im_dual_transform(im)
|
101 |
+
this_im = self.all_im_lone_transform(this_im)
|
102 |
+
reseed(sequence_seed)
|
103 |
+
this_gt = self.all_gt_dual_transform(gt)
|
104 |
+
|
105 |
+
pairwise_seed = np.random.randint(2147483647)
|
106 |
+
reseed(pairwise_seed)
|
107 |
+
this_im = self.pair_im_dual_transform(this_im)
|
108 |
+
this_im = self.pair_im_lone_transform(this_im)
|
109 |
+
reseed(pairwise_seed)
|
110 |
+
this_gt = self.pair_gt_dual_transform(this_gt)
|
111 |
+
|
112 |
+
# Use TPS only some of the times
|
113 |
+
# Not because TPS is bad -- just that it is too slow and I need to speed up data loading
|
114 |
+
if np.random.rand() < 0.33:
|
115 |
+
this_im, this_gt = random_tps_warp(this_im, this_gt, scale=0.02)
|
116 |
+
|
117 |
+
this_im = self.final_im_transform(this_im)
|
118 |
+
this_gt = self.final_gt_transform(this_gt)
|
119 |
+
|
120 |
+
images.append(this_im)
|
121 |
+
masks.append(this_gt)
|
122 |
+
|
123 |
+
images = torch.stack(images, 0)
|
124 |
+
masks = torch.stack(masks, 0)
|
125 |
+
|
126 |
+
return images, masks.numpy()
|
127 |
+
|
128 |
+
def __getitem__(self, idx):
|
129 |
+
additional_objects = np.random.randint(self.max_num_obj)
|
130 |
+
indices = [idx, *np.random.randint(self.__len__(), size=additional_objects)]
|
131 |
+
|
132 |
+
merged_images = None
|
133 |
+
merged_masks = np.zeros((self.num_frames, 384, 384), dtype=np.int)
|
134 |
+
|
135 |
+
for i, list_id in enumerate(indices):
|
136 |
+
images, masks = self._get_sample(list_id)
|
137 |
+
if merged_images is None:
|
138 |
+
merged_images = images
|
139 |
+
else:
|
140 |
+
merged_images = merged_images*(1-masks) + images*masks
|
141 |
+
merged_masks[masks[:,0]>0.5] = (i+1)
|
142 |
+
|
143 |
+
masks = merged_masks
|
144 |
+
|
145 |
+
labels = np.unique(masks[0])
|
146 |
+
# Remove background
|
147 |
+
labels = labels[labels!=0]
|
148 |
+
target_objects = labels.tolist()
|
149 |
+
|
150 |
+
# Generate one-hot ground-truth
|
151 |
+
cls_gt = np.zeros((self.num_frames, 384, 384), dtype=np.int)
|
152 |
+
first_frame_gt = np.zeros((1, self.max_num_obj, 384, 384), dtype=np.int)
|
153 |
+
for i, l in enumerate(target_objects):
|
154 |
+
this_mask = (masks==l)
|
155 |
+
cls_gt[this_mask] = i+1
|
156 |
+
first_frame_gt[0,i] = (this_mask[0])
|
157 |
+
cls_gt = np.expand_dims(cls_gt, 1)
|
158 |
+
|
159 |
+
info = {}
|
160 |
+
info['name'] = self.im_list[idx]
|
161 |
+
info['num_objects'] = max(1, len(target_objects))
|
162 |
+
|
163 |
+
# 1 if object exist, 0 otherwise
|
164 |
+
selector = [1 if i < info['num_objects'] else 0 for i in range(self.max_num_obj)]
|
165 |
+
selector = torch.FloatTensor(selector)
|
166 |
+
|
167 |
+
data = {
|
168 |
+
'rgb': merged_images,
|
169 |
+
'first_frame_gt': first_frame_gt,
|
170 |
+
'cls_gt': cls_gt,
|
171 |
+
'selector': selector,
|
172 |
+
'info': info
|
173 |
+
}
|
174 |
+
|
175 |
+
return data
|
176 |
+
|
177 |
+
|
178 |
+
def __len__(self):
|
179 |
+
return len(self.im_list)
|
dataset/tps.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from PIL import Image
|
3 |
+
import cv2
|
4 |
+
import thinplate as tps
|
5 |
+
|
6 |
+
cv2.setNumThreads(0)
|
7 |
+
|
8 |
+
def pick_random_points(h, w, n_samples):
|
9 |
+
y_idx = np.random.choice(np.arange(h), size=n_samples, replace=False)
|
10 |
+
x_idx = np.random.choice(np.arange(w), size=n_samples, replace=False)
|
11 |
+
return y_idx/h, x_idx/w
|
12 |
+
|
13 |
+
|
14 |
+
def warp_dual_cv(img, mask, c_src, c_dst):
|
15 |
+
dshape = img.shape
|
16 |
+
theta = tps.tps_theta_from_points(c_src, c_dst, reduced=True)
|
17 |
+
grid = tps.tps_grid(theta, c_dst, dshape)
|
18 |
+
mapx, mapy = tps.tps_grid_to_remap(grid, img.shape)
|
19 |
+
return cv2.remap(img, mapx, mapy, cv2.INTER_LINEAR), cv2.remap(mask, mapx, mapy, cv2.INTER_NEAREST)
|
20 |
+
|
21 |
+
|
22 |
+
def random_tps_warp(img, mask, scale, n_ctrl_pts=12):
|
23 |
+
"""
|
24 |
+
Apply a random TPS warp of the input image and mask
|
25 |
+
Uses randomness from numpy
|
26 |
+
"""
|
27 |
+
img = np.asarray(img)
|
28 |
+
mask = np.asarray(mask)
|
29 |
+
|
30 |
+
h, w = mask.shape
|
31 |
+
points = pick_random_points(h, w, n_ctrl_pts)
|
32 |
+
c_src = np.stack(points, 1)
|
33 |
+
c_dst = c_src + np.random.normal(scale=scale, size=c_src.shape)
|
34 |
+
warp_im, warp_gt = warp_dual_cv(img, mask, c_src, c_dst)
|
35 |
+
|
36 |
+
return Image.fromarray(warp_im), Image.fromarray(warp_gt)
|
37 |
+
|
dataset/util.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
def all_to_onehot(masks, labels):
|
4 |
+
if len(masks.shape) == 3:
|
5 |
+
Ms = np.zeros((len(labels), masks.shape[0], masks.shape[1], masks.shape[2]), dtype=np.uint8)
|
6 |
+
else:
|
7 |
+
Ms = np.zeros((len(labels), masks.shape[0], masks.shape[1]), dtype=np.uint8)
|
8 |
+
|
9 |
+
for ni, l in enumerate(labels):
|
10 |
+
Ms[ni] = (masks == l).astype(np.uint8)
|
11 |
+
|
12 |
+
return Ms
|
dataset/vos_dataset.py
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from os import path, replace
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from torch.utils.data.dataset import Dataset
|
6 |
+
from torchvision import transforms
|
7 |
+
from torchvision.transforms import InterpolationMode
|
8 |
+
from PIL import Image
|
9 |
+
import numpy as np
|
10 |
+
|
11 |
+
from dataset.range_transform import im_normalization, im_mean, im_rgb2lab_normalization, ToTensor, RGB2Lab
|
12 |
+
from dataset.reseed import reseed
|
13 |
+
|
14 |
+
import util.functional as F
|
15 |
+
|
16 |
+
class VOSDataset_221128_TransColorization_batch(Dataset):
|
17 |
+
"""
|
18 |
+
Works for DAVIS/YouTubeVOS/BL30K training
|
19 |
+
For each sequence:
|
20 |
+
- Pick three frames
|
21 |
+
- Pick two objects
|
22 |
+
- Apply some random transforms that are the same for all frames
|
23 |
+
- Apply random transform to each of the frame
|
24 |
+
- The distance between frames is controlled
|
25 |
+
"""
|
26 |
+
def __init__(self, im_root, gt_root, max_jump, is_bl, subset=None, num_frames=3, max_num_obj=2, finetune=False):
|
27 |
+
self.im_root = im_root
|
28 |
+
self.gt_root = gt_root
|
29 |
+
self.max_jump = max_jump
|
30 |
+
self.is_bl = is_bl
|
31 |
+
self.num_frames = num_frames
|
32 |
+
self.max_num_obj = max_num_obj
|
33 |
+
|
34 |
+
self.videos = []
|
35 |
+
self.frames = {}
|
36 |
+
vid_list = sorted(os.listdir(self.im_root))
|
37 |
+
# Pre-filtering
|
38 |
+
for vid in vid_list:
|
39 |
+
if subset is not None:
|
40 |
+
if vid not in subset:
|
41 |
+
continue
|
42 |
+
frames = sorted(os.listdir(os.path.join(self.im_root, vid)))
|
43 |
+
if len(frames) < num_frames:
|
44 |
+
continue
|
45 |
+
self.frames[vid] = frames
|
46 |
+
self.videos.append(vid)
|
47 |
+
|
48 |
+
print('%d out of %d videos accepted in %s.' % (len(self.videos), len(vid_list), im_root))
|
49 |
+
|
50 |
+
# These set of transform is the same for im/gt pairs, but different among the 3 sampled frames
|
51 |
+
self.pair_im_lone_transform = transforms.Compose([
|
52 |
+
transforms.ColorJitter(0.01, 0.01, 0.01, 0),
|
53 |
+
])
|
54 |
+
|
55 |
+
self.pair_im_dual_transform = transforms.Compose([
|
56 |
+
transforms.RandomAffine(degrees=0 if finetune or self.is_bl else 15, shear=0 if finetune or self.is_bl else 10, interpolation=InterpolationMode.BILINEAR, fill=im_mean),
|
57 |
+
])
|
58 |
+
|
59 |
+
self.pair_gt_dual_transform = transforms.Compose([
|
60 |
+
transforms.RandomAffine(degrees=0 if finetune or self.is_bl else 15, shear=0 if finetune or self.is_bl else 10, interpolation=InterpolationMode.NEAREST, fill=0),
|
61 |
+
])
|
62 |
+
|
63 |
+
# These transform are the same for all pairs in the sampled sequence
|
64 |
+
self.all_im_lone_transform = transforms.Compose([
|
65 |
+
transforms.ColorJitter(0.1, 0.03, 0.03, 0),
|
66 |
+
# transforms.RandomGrayscale(0.05),
|
67 |
+
])
|
68 |
+
|
69 |
+
patchsz = 448 # 224
|
70 |
+
self.all_im_dual_transform = transforms.Compose([
|
71 |
+
transforms.RandomHorizontalFlip(),
|
72 |
+
transforms.RandomResizedCrop((patchsz, patchsz), scale=(0.36,1.00), interpolation=InterpolationMode.BILINEAR)
|
73 |
+
])
|
74 |
+
|
75 |
+
self.all_gt_dual_transform = transforms.Compose([
|
76 |
+
transforms.RandomHorizontalFlip(),
|
77 |
+
transforms.RandomResizedCrop((patchsz, patchsz), scale=(0.36,1.00), interpolation=InterpolationMode.NEAREST)
|
78 |
+
])
|
79 |
+
|
80 |
+
# Final transform without randomness
|
81 |
+
self.final_im_transform = transforms.Compose([
|
82 |
+
RGB2Lab(),
|
83 |
+
ToTensor(),
|
84 |
+
im_rgb2lab_normalization,
|
85 |
+
])
|
86 |
+
|
87 |
+
def __getitem__(self, idx):
|
88 |
+
video = self.videos[idx]
|
89 |
+
info = {}
|
90 |
+
info['name'] = video
|
91 |
+
|
92 |
+
vid_im_path = path.join(self.im_root, video)
|
93 |
+
vid_gt_path = path.join(self.gt_root, video)
|
94 |
+
frames = self.frames[video]
|
95 |
+
|
96 |
+
trials = 0
|
97 |
+
while trials < 5:
|
98 |
+
info['frames'] = [] # Appended with actual frames
|
99 |
+
|
100 |
+
num_frames = self.num_frames
|
101 |
+
length = len(frames)
|
102 |
+
this_max_jump = min(len(frames), self.max_jump)
|
103 |
+
|
104 |
+
# iterative sampling
|
105 |
+
frames_idx = [np.random.randint(length)]
|
106 |
+
acceptable_set = set(range(max(0, frames_idx[-1]-this_max_jump), min(length, frames_idx[-1]+this_max_jump+1))).difference(set(frames_idx))
|
107 |
+
while(len(frames_idx) < num_frames):
|
108 |
+
idx = np.random.choice(list(acceptable_set))
|
109 |
+
frames_idx.append(idx)
|
110 |
+
new_set = set(range(max(0, frames_idx[-1]-this_max_jump), min(length, frames_idx[-1]+this_max_jump+1)))
|
111 |
+
acceptable_set = acceptable_set.union(new_set).difference(set(frames_idx))
|
112 |
+
|
113 |
+
frames_idx = sorted(frames_idx)
|
114 |
+
if np.random.rand() < 0.5:
|
115 |
+
# Reverse time
|
116 |
+
frames_idx = frames_idx[::-1]
|
117 |
+
|
118 |
+
sequence_seed = np.random.randint(2147483647)
|
119 |
+
images = []
|
120 |
+
masks = []
|
121 |
+
target_objects = []
|
122 |
+
for f_idx in frames_idx:
|
123 |
+
jpg_name = frames[f_idx]
|
124 |
+
png_name = jpg_name.replace('.jpg', '.png')
|
125 |
+
info['frames'].append(jpg_name)
|
126 |
+
|
127 |
+
reseed(sequence_seed)
|
128 |
+
this_im = Image.open(path.join(vid_im_path, jpg_name)).convert('RGB')
|
129 |
+
this_im = self.all_im_dual_transform(this_im)
|
130 |
+
this_im = self.all_im_lone_transform(this_im)
|
131 |
+
|
132 |
+
reseed(sequence_seed)
|
133 |
+
this_gt = Image.open(path.join(vid_gt_path, png_name)).convert('P')
|
134 |
+
this_gt = self.all_gt_dual_transform(this_gt)
|
135 |
+
|
136 |
+
pairwise_seed = np.random.randint(2147483647)
|
137 |
+
reseed(pairwise_seed)
|
138 |
+
this_im = self.pair_im_dual_transform(this_im)
|
139 |
+
this_im = self.pair_im_lone_transform(this_im)
|
140 |
+
|
141 |
+
reseed(pairwise_seed)
|
142 |
+
this_gt = self.pair_gt_dual_transform(this_gt)
|
143 |
+
|
144 |
+
this_im = self.final_im_transform(this_im)
|
145 |
+
# print('1', torch.max(this_im[:1,:,:]), torch.min(this_im[:1,:,:]))
|
146 |
+
# print('2', torch.max(this_im[1:3,:,:]), torch.min(this_im[1:3,:,:]))
|
147 |
+
# print('3', torch.max(this_im), torch.min(this_im));assert 1==0
|
148 |
+
# print(this_im.size());assert 1==0
|
149 |
+
|
150 |
+
this_gt = np.array(this_gt)
|
151 |
+
|
152 |
+
this_im_l = this_im[:1,:,:]
|
153 |
+
this_im_ab = this_im[1:3,:,:]
|
154 |
+
# print(this_im_l.size(), this_im_ab.size());assert 1==0
|
155 |
+
|
156 |
+
# images.append(this_im_l)
|
157 |
+
# masks.append(this_im_ab)
|
158 |
+
|
159 |
+
this_im_lll = this_im_l.repeat(3,1,1)
|
160 |
+
images.append(this_im_lll)
|
161 |
+
masks.append(this_im_ab)
|
162 |
+
|
163 |
+
images = torch.stack(images, 0)
|
164 |
+
# print(images.size());assert 1==0
|
165 |
+
|
166 |
+
# target_objects = labels.tolist()
|
167 |
+
break
|
168 |
+
|
169 |
+
first_frame_gt = masks[0].unsqueeze(0)
|
170 |
+
# print(first_frame_gt.size());assert 1==0
|
171 |
+
|
172 |
+
info['num_objects'] = 2
|
173 |
+
|
174 |
+
masks = np.stack(masks, 0)
|
175 |
+
# print(np.shape(masks));assert 1==0
|
176 |
+
|
177 |
+
|
178 |
+
cls_gt = masks
|
179 |
+
|
180 |
+
# # Generate one-hot ground-truth
|
181 |
+
# cls_gt = np.zeros((self.num_frames, 384, 384), dtype=np.int)
|
182 |
+
# first_frame_gt = np.zeros((1, self.max_num_obj, 384, 384), dtype=np.int)
|
183 |
+
# for i, l in enumerate(target_objects):
|
184 |
+
# this_mask = (masks==l)
|
185 |
+
# cls_gt[this_mask] = i+1
|
186 |
+
# first_frame_gt[0,i] = (this_mask[0])
|
187 |
+
# cls_gt = np.expand_dims(cls_gt, 1)
|
188 |
+
|
189 |
+
# 1 if object exist, 0 otherwise
|
190 |
+
selector = [1 if i < info['num_objects'] else 0 for i in range(self.max_num_obj)]
|
191 |
+
|
192 |
+
# print(info['num_objects'], self.max_num_obj, selector);assert 1==0
|
193 |
+
|
194 |
+
selector = torch.FloatTensor(selector)
|
195 |
+
|
196 |
+
# print(images.size(), np.shape(first_frame_gt), np.shape(cls_gt));assert 1==0
|
197 |
+
### torch.Size([8, 3, 384, 384]) torch.Size([1, 2, 384, 384]) (8, 2, 384, 384)
|
198 |
+
|
199 |
+
data = {
|
200 |
+
'rgb': images,
|
201 |
+
'first_frame_gt': first_frame_gt,
|
202 |
+
'cls_gt': cls_gt,
|
203 |
+
'selector': selector,
|
204 |
+
'info': info,
|
205 |
+
}
|
206 |
+
|
207 |
+
return data
|
208 |
+
|
209 |
+
def __len__(self):
|
210 |
+
return len(self.videos)
|
inference/__init__.py
ADDED
File without changes
|
inference/data/__init__.py
ADDED
File without changes
|
inference/data/mask_mapper.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
|
4 |
+
from dataset.util import all_to_onehot
|
5 |
+
|
6 |
+
|
7 |
+
class MaskMapper:
|
8 |
+
"""
|
9 |
+
This class is used to convert a indexed-mask to a one-hot representation.
|
10 |
+
It also takes care of remapping non-continuous indices
|
11 |
+
It has two modes:
|
12 |
+
1. Default. Only masks with new indices are supposed to go into the remapper.
|
13 |
+
This is also the case for YouTubeVOS.
|
14 |
+
i.e., regions with index 0 are not "background", but "don't care".
|
15 |
+
|
16 |
+
2. Exhaustive. Regions with index 0 are considered "background".
|
17 |
+
Every single pixel is considered to be "labeled".
|
18 |
+
"""
|
19 |
+
def __init__(self):
|
20 |
+
self.labels = []
|
21 |
+
self.remappings = {}
|
22 |
+
|
23 |
+
# if coherent, no mapping is required
|
24 |
+
self.coherent = True
|
25 |
+
|
26 |
+
def convert_mask(self, mask, exhaustive=False):
|
27 |
+
# mask is in index representation, H*W numpy array
|
28 |
+
labels = np.unique(mask).astype(np.uint8)
|
29 |
+
labels = labels[labels!=0].tolist()
|
30 |
+
|
31 |
+
new_labels = list(set(labels) - set(self.labels))
|
32 |
+
# print('new_labels', new_labels) # [255]
|
33 |
+
if not exhaustive:
|
34 |
+
assert len(new_labels) == len(labels), 'Old labels found in non-exhaustive mode'
|
35 |
+
|
36 |
+
# add new remappings
|
37 |
+
for i, l in enumerate(new_labels):
|
38 |
+
self.remappings[l] = i+len(self.labels)+1
|
39 |
+
if self.coherent and i+len(self.labels)+1 != l:
|
40 |
+
self.coherent = False
|
41 |
+
|
42 |
+
if exhaustive:
|
43 |
+
new_mapped_labels = range(1, len(self.labels)+len(new_labels)+1)
|
44 |
+
else:
|
45 |
+
if self.coherent:
|
46 |
+
new_mapped_labels = new_labels
|
47 |
+
else:
|
48 |
+
new_mapped_labels = range(len(self.labels)+1, len(self.labels)+len(new_labels)+1)
|
49 |
+
# print(list(new_mapped_labels));assert 1==0 # [1]
|
50 |
+
|
51 |
+
self.labels.extend(new_labels)
|
52 |
+
# print(self.labels);assert 1==0 # [255]
|
53 |
+
mask = torch.from_numpy(all_to_onehot(mask, self.labels)).float()
|
54 |
+
|
55 |
+
# mask num_objects*H*W; new_mapped_labels: [num_objects]
|
56 |
+
return mask, new_mapped_labels
|
57 |
+
|
58 |
+
|
59 |
+
def remap_index_mask(self, mask):
|
60 |
+
# mask is in index representation, H*W numpy array
|
61 |
+
if self.coherent:
|
62 |
+
return mask
|
63 |
+
|
64 |
+
new_mask = np.zeros_like(mask)
|
65 |
+
for l, i in self.remappings.items():
|
66 |
+
new_mask[mask==i] = l
|
67 |
+
return new_mask
|
inference/data/test_datasets.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from os import path
|
3 |
+
import json
|
4 |
+
|
5 |
+
from inference.data.video_reader import VideoReader_221128_TransColorization
|
6 |
+
|
7 |
+
class DAVISTestDataset_221128_TransColorization_batch:
|
8 |
+
def __init__(self, data_root, imset='2017/val.txt', size=-1):
|
9 |
+
self.image_dir = data_root
|
10 |
+
self.mask_dir = imset
|
11 |
+
self.size_dir = data_root
|
12 |
+
self.size = size
|
13 |
+
|
14 |
+
self.vid_list = [clip_name for clip_name in sorted(os.listdir(data_root)) if clip_name != '.DS_Store']
|
15 |
+
|
16 |
+
# print(lst, len(lst), self.vid_list, self.vid_list_DAVIS2016, path.join(data_root, 'ImageSets', imset));assert 1==0
|
17 |
+
|
18 |
+
def get_datasets(self):
|
19 |
+
for video in self.vid_list:
|
20 |
+
# print(self.image_dir, video, path.join(self.image_dir, video));assert 1==0
|
21 |
+
yield VideoReader_221128_TransColorization(video,
|
22 |
+
path.join(self.image_dir, video),
|
23 |
+
path.join(self.mask_dir, video),
|
24 |
+
size=self.size,
|
25 |
+
size_dir=path.join(self.size_dir, video),
|
26 |
+
)
|
27 |
+
|
28 |
+
def __len__(self):
|
29 |
+
return len(self.vid_list)
|
inference/data/video_reader.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from os import path
|
3 |
+
|
4 |
+
from torch.utils.data.dataset import Dataset
|
5 |
+
from torchvision import transforms
|
6 |
+
from torchvision.transforms import InterpolationMode
|
7 |
+
import torch.nn.functional as Ff
|
8 |
+
from PIL import Image
|
9 |
+
import numpy as np
|
10 |
+
|
11 |
+
from dataset.range_transform import im_normalization, im_rgb2lab_normalization, ToTensor, RGB2Lab
|
12 |
+
|
13 |
+
class VideoReader_221128_TransColorization(Dataset):
|
14 |
+
"""
|
15 |
+
This class is used to read a video, one frame at a time
|
16 |
+
"""
|
17 |
+
def __init__(self, vid_name, image_dir, mask_dir, size=-1, to_save=None, use_all_mask=False, size_dir=None):
|
18 |
+
"""
|
19 |
+
image_dir - points to a directory of jpg images
|
20 |
+
mask_dir - points to a directory of png masks
|
21 |
+
size - resize min. side to size. Does nothing if <0.
|
22 |
+
to_save - optionally contains a list of file names without extensions
|
23 |
+
where the segmentation mask is required
|
24 |
+
use_all_mask - when true, read all available mask in mask_dir.
|
25 |
+
Default false. Set to true for YouTubeVOS validation.
|
26 |
+
"""
|
27 |
+
self.vid_name = vid_name
|
28 |
+
self.image_dir = image_dir
|
29 |
+
self.mask_dir = mask_dir
|
30 |
+
self.to_save = to_save
|
31 |
+
self.use_all_mask = use_all_mask
|
32 |
+
# print('use_all_mask', use_all_mask);assert 1==0
|
33 |
+
if size_dir is None:
|
34 |
+
self.size_dir = self.image_dir
|
35 |
+
else:
|
36 |
+
self.size_dir = size_dir
|
37 |
+
|
38 |
+
self.frames = [img for img in sorted(os.listdir(self.image_dir)) if img.endswith('.jpg') or img.endswith('.png')]
|
39 |
+
self.palette = Image.open(path.join(mask_dir, sorted(os.listdir(mask_dir))[0])).getpalette()
|
40 |
+
self.first_gt_path = path.join(self.mask_dir, sorted(os.listdir(self.mask_dir))[0])
|
41 |
+
self.suffix = self.first_gt_path.split('.')[-1]
|
42 |
+
|
43 |
+
if size < 0:
|
44 |
+
self.im_transform = transforms.Compose([
|
45 |
+
RGB2Lab(),
|
46 |
+
ToTensor(),
|
47 |
+
im_rgb2lab_normalization,
|
48 |
+
])
|
49 |
+
else:
|
50 |
+
self.im_transform = transforms.Compose([
|
51 |
+
transforms.ToTensor(),
|
52 |
+
im_normalization,
|
53 |
+
transforms.Resize(size, interpolation=InterpolationMode.BILINEAR),
|
54 |
+
])
|
55 |
+
self.size = size
|
56 |
+
|
57 |
+
|
58 |
+
def __getitem__(self, idx):
|
59 |
+
frame = self.frames[idx]
|
60 |
+
info = {}
|
61 |
+
data = {}
|
62 |
+
info['frame'] = frame
|
63 |
+
info['vid_name'] = self.vid_name
|
64 |
+
info['save'] = (self.to_save is None) or (frame[:-4] in self.to_save)
|
65 |
+
|
66 |
+
im_path = path.join(self.image_dir, frame)
|
67 |
+
img = Image.open(im_path).convert('RGB')
|
68 |
+
|
69 |
+
if self.image_dir == self.size_dir:
|
70 |
+
shape = np.array(img).shape[:2]
|
71 |
+
else:
|
72 |
+
size_path = path.join(self.size_dir, frame)
|
73 |
+
size_im = Image.open(size_path).convert('RGB')
|
74 |
+
shape = np.array(size_im).shape[:2]
|
75 |
+
|
76 |
+
gt_path = path.join(self.mask_dir, sorted(os.listdir(self.mask_dir))[idx]) if idx < len(os.listdir(self.mask_dir)) else None
|
77 |
+
|
78 |
+
img = self.im_transform(img)
|
79 |
+
img_l = img[:1,:,:]
|
80 |
+
img_lll = img_l.repeat(3,1,1)
|
81 |
+
|
82 |
+
load_mask = self.use_all_mask or (gt_path == self.first_gt_path)
|
83 |
+
if load_mask and path.exists(gt_path):
|
84 |
+
mask = Image.open(gt_path).convert('RGB')
|
85 |
+
mask = self.im_transform(mask)
|
86 |
+
mask_ab = mask[1:3,:,:]
|
87 |
+
data['mask'] = mask_ab
|
88 |
+
|
89 |
+
info['shape'] = shape
|
90 |
+
info['need_resize'] = not (self.size < 0)
|
91 |
+
data['rgb'] = img_lll
|
92 |
+
data['info'] = info
|
93 |
+
|
94 |
+
return data
|
95 |
+
|
96 |
+
def resize_mask(self, mask):
|
97 |
+
# mask transform is applied AFTER mapper, so we need to post-process it in eval.py
|
98 |
+
h, w = mask.shape[-2:]
|
99 |
+
min_hw = min(h, w)
|
100 |
+
return Ff.interpolate(mask, (int(h/min_hw*self.size), int(w/min_hw*self.size)),
|
101 |
+
mode='nearest')
|
102 |
+
|
103 |
+
def get_palette(self):
|
104 |
+
return self.palette
|
105 |
+
|
106 |
+
def __len__(self):
|
107 |
+
return len(self.frames)
|
inference/inference_core.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from inference.memory_manager import MemoryManager
|
2 |
+
from model.network import ColorMNet
|
3 |
+
from model.aggregate import aggregate
|
4 |
+
|
5 |
+
from util.tensor_util import pad_divide_by, unpad
|
6 |
+
import torch
|
7 |
+
|
8 |
+
class InferenceCore:
|
9 |
+
def __init__(self, network:ColorMNet, config):
|
10 |
+
self.config = config
|
11 |
+
self.network = network
|
12 |
+
self.mem_every = config['mem_every']
|
13 |
+
self.deep_update_every = config['deep_update_every']
|
14 |
+
self.enable_long_term = config['enable_long_term']
|
15 |
+
|
16 |
+
# if deep_update_every < 0, synchronize deep update with memory frame
|
17 |
+
self.deep_update_sync = (self.deep_update_every < 0)
|
18 |
+
|
19 |
+
self.clear_memory()
|
20 |
+
self.all_labels = None
|
21 |
+
|
22 |
+
self.last_ti_key = None
|
23 |
+
self.last_ti_value = None
|
24 |
+
|
25 |
+
def clear_memory(self):
|
26 |
+
self.curr_ti = -1
|
27 |
+
self.last_mem_ti = 0
|
28 |
+
if not self.deep_update_sync:
|
29 |
+
self.last_deep_update_ti = -self.deep_update_every
|
30 |
+
self.memory = MemoryManager(config=self.config)
|
31 |
+
|
32 |
+
def update_config(self, config):
|
33 |
+
self.mem_every = config['mem_every']
|
34 |
+
self.deep_update_every = config['deep_update_every']
|
35 |
+
self.enable_long_term = config['enable_long_term']
|
36 |
+
|
37 |
+
# if deep_update_every < 0, synchronize deep update with memory frame
|
38 |
+
self.deep_update_sync = (self.deep_update_every < 0)
|
39 |
+
self.memory.update_config(config)
|
40 |
+
|
41 |
+
def set_all_labels(self, all_labels):
|
42 |
+
# self.all_labels = [l.item() for l in all_labels]
|
43 |
+
self.all_labels = all_labels
|
44 |
+
|
45 |
+
def step(self, image, mask=None, valid_labels=None, end=False):
|
46 |
+
# image: 3*H*W
|
47 |
+
# mask: num_objects*H*W or None
|
48 |
+
self.curr_ti += 1
|
49 |
+
divide_by = 112 # 16
|
50 |
+
image, self.pad = pad_divide_by(image, divide_by)
|
51 |
+
image = image.unsqueeze(0) # add the batch dimension
|
52 |
+
|
53 |
+
is_mem_frame = ((self.curr_ti-self.last_mem_ti >= self.mem_every) or (mask is not None)) and (not end)
|
54 |
+
need_segment = (self.curr_ti > 0) and ((valid_labels is None) or (len(self.all_labels) != len(valid_labels)))
|
55 |
+
is_deep_update = (
|
56 |
+
(self.deep_update_sync and is_mem_frame) or # synchronized
|
57 |
+
(not self.deep_update_sync and self.curr_ti-self.last_deep_update_ti >= self.deep_update_every) # no-sync
|
58 |
+
) and (not end)
|
59 |
+
is_normal_update = (not self.deep_update_sync or not is_deep_update) and (not end)
|
60 |
+
|
61 |
+
key, shrinkage, selection, f16, f8, f4 = self.network.encode_key(image,
|
62 |
+
need_ek=(self.enable_long_term or need_segment),
|
63 |
+
need_sk=is_mem_frame)
|
64 |
+
multi_scale_features = (f16, f8, f4)
|
65 |
+
|
66 |
+
# segment the current frame is needed
|
67 |
+
if need_segment:
|
68 |
+
memory_readout = self.memory.match_memory(key, selection).unsqueeze(0)
|
69 |
+
|
70 |
+
# short term memory
|
71 |
+
batch, num_objects, value_dim, h, w = self.last_ti_value.shape
|
72 |
+
last_ti_value = self.last_ti_value.flatten(start_dim=1, end_dim=2)
|
73 |
+
memory_value_short, _ = self.network.short_term_attn(key, self.last_ti_key, last_ti_value, None, key.shape[-2:])
|
74 |
+
memory_value_short = memory_value_short.permute(1, 2, 0).view(batch, num_objects, value_dim, h, w)
|
75 |
+
memory_readout += memory_value_short
|
76 |
+
|
77 |
+
hidden, _, pred_prob_with_bg = self.network.segment(multi_scale_features, memory_readout,
|
78 |
+
self.memory.get_hidden(), h_out=is_normal_update, strip_bg=False)
|
79 |
+
# remove batch dim
|
80 |
+
pred_prob_with_bg = pred_prob_with_bg[0]
|
81 |
+
pred_prob_no_bg = pred_prob_with_bg
|
82 |
+
if is_normal_update:
|
83 |
+
self.memory.set_hidden(hidden)
|
84 |
+
else:
|
85 |
+
pred_prob_no_bg = pred_prob_with_bg = None
|
86 |
+
|
87 |
+
# use the input mask if any
|
88 |
+
if mask is not None:
|
89 |
+
mask, _ = pad_divide_by(mask, divide_by)
|
90 |
+
|
91 |
+
pred_prob_with_bg = mask
|
92 |
+
|
93 |
+
self.memory.create_hidden_state(2, key)
|
94 |
+
|
95 |
+
# save as memory if needed
|
96 |
+
if is_mem_frame:
|
97 |
+
value, hidden = self.network.encode_value(image, f16, self.memory.get_hidden(),
|
98 |
+
pred_prob_with_bg.unsqueeze(0), is_deep_update=is_deep_update)
|
99 |
+
|
100 |
+
self.memory.add_memory(key, shrinkage, value, self.all_labels,
|
101 |
+
selection=selection if self.enable_long_term else None)
|
102 |
+
self.last_mem_ti = self.curr_ti
|
103 |
+
|
104 |
+
self.last_ti_key = key
|
105 |
+
self.last_ti_value = value
|
106 |
+
|
107 |
+
if is_deep_update:
|
108 |
+
self.memory.set_hidden(hidden)
|
109 |
+
self.last_deep_update_ti = self.curr_ti
|
110 |
+
|
111 |
+
return unpad(pred_prob_with_bg, self.pad)
|
inference/interact/__init__.py
ADDED
File without changes
|
inference/interact/fbrs/LICENSE
ADDED
@@ -0,0 +1,373 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Mozilla Public License Version 2.0
|
2 |
+
==================================
|
3 |
+
|
4 |
+
1. Definitions
|
5 |
+
--------------
|
6 |
+
|
7 |
+
1.1. "Contributor"
|
8 |
+
means each individual or legal entity that creates, contributes to
|
9 |
+
the creation of, or owns Covered Software.
|
10 |
+
|
11 |
+
1.2. "Contributor Version"
|
12 |
+
means the combination of the Contributions of others (if any) used
|
13 |
+
by a Contributor and that particular Contributor's Contribution.
|
14 |
+
|
15 |
+
1.3. "Contribution"
|
16 |
+
means Covered Software of a particular Contributor.
|
17 |
+
|
18 |
+
1.4. "Covered Software"
|
19 |
+
means Source Code Form to which the initial Contributor has attached
|
20 |
+
the notice in Exhibit A, the Executable Form of such Source Code
|
21 |
+
Form, and Modifications of such Source Code Form, in each case
|
22 |
+
including portions thereof.
|
23 |
+
|
24 |
+
1.5. "Incompatible With Secondary Licenses"
|
25 |
+
means
|
26 |
+
|
27 |
+
(a) that the initial Contributor has attached the notice described
|
28 |
+
in Exhibit B to the Covered Software; or
|
29 |
+
|
30 |
+
(b) that the Covered Software was made available under the terms of
|
31 |
+
version 1.1 or earlier of the License, but not also under the
|
32 |
+
terms of a Secondary License.
|
33 |
+
|
34 |
+
1.6. "Executable Form"
|
35 |
+
means any form of the work other than Source Code Form.
|
36 |
+
|
37 |
+
1.7. "Larger Work"
|
38 |
+
means a work that combines Covered Software with other material, in
|
39 |
+
a separate file or files, that is not Covered Software.
|
40 |
+
|
41 |
+
1.8. "License"
|
42 |
+
means this document.
|
43 |
+
|
44 |
+
1.9. "Licensable"
|
45 |
+
means having the right to grant, to the maximum extent possible,
|
46 |
+
whether at the time of the initial grant or subsequently, any and
|
47 |
+
all of the rights conveyed by this License.
|
48 |
+
|
49 |
+
1.10. "Modifications"
|
50 |
+
means any of the following:
|
51 |
+
|
52 |
+
(a) any file in Source Code Form that results from an addition to,
|
53 |
+
deletion from, or modification of the contents of Covered
|
54 |
+
Software; or
|
55 |
+
|
56 |
+
(b) any new file in Source Code Form that contains any Covered
|
57 |
+
Software.
|
58 |
+
|
59 |
+
1.11. "Patent Claims" of a Contributor
|
60 |
+
means any patent claim(s), including without limitation, method,
|
61 |
+
process, and apparatus claims, in any patent Licensable by such
|
62 |
+
Contributor that would be infringed, but for the grant of the
|
63 |
+
License, by the making, using, selling, offering for sale, having
|
64 |
+
made, import, or transfer of either its Contributions or its
|
65 |
+
Contributor Version.
|
66 |
+
|
67 |
+
1.12. "Secondary License"
|
68 |
+
means either the GNU General Public License, Version 2.0, the GNU
|
69 |
+
Lesser General Public License, Version 2.1, the GNU Affero General
|
70 |
+
Public License, Version 3.0, or any later versions of those
|
71 |
+
licenses.
|
72 |
+
|
73 |
+
1.13. "Source Code Form"
|
74 |
+
means the form of the work preferred for making modifications.
|
75 |
+
|
76 |
+
1.14. "You" (or "Your")
|
77 |
+
means an individual or a legal entity exercising rights under this
|
78 |
+
License. For legal entities, "You" includes any entity that
|
79 |
+
controls, is controlled by, or is under common control with You. For
|
80 |
+
purposes of this definition, "control" means (a) the power, direct
|
81 |
+
or indirect, to cause the direction or management of such entity,
|
82 |
+
whether by contract or otherwise, or (b) ownership of more than
|
83 |
+
fifty percent (50%) of the outstanding shares or beneficial
|
84 |
+
ownership of such entity.
|
85 |
+
|
86 |
+
2. License Grants and Conditions
|
87 |
+
--------------------------------
|
88 |
+
|
89 |
+
2.1. Grants
|
90 |
+
|
91 |
+
Each Contributor hereby grants You a world-wide, royalty-free,
|
92 |
+
non-exclusive license:
|
93 |
+
|
94 |
+
(a) under intellectual property rights (other than patent or trademark)
|
95 |
+
Licensable by such Contributor to use, reproduce, make available,
|
96 |
+
modify, display, perform, distribute, and otherwise exploit its
|
97 |
+
Contributions, either on an unmodified basis, with Modifications, or
|
98 |
+
as part of a Larger Work; and
|
99 |
+
|
100 |
+
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
101 |
+
for sale, have made, import, and otherwise transfer either its
|
102 |
+
Contributions or its Contributor Version.
|
103 |
+
|
104 |
+
2.2. Effective Date
|
105 |
+
|
106 |
+
The licenses granted in Section 2.1 with respect to any Contribution
|
107 |
+
become effective for each Contribution on the date the Contributor first
|
108 |
+
distributes such Contribution.
|
109 |
+
|
110 |
+
2.3. Limitations on Grant Scope
|
111 |
+
|
112 |
+
The licenses granted in this Section 2 are the only rights granted under
|
113 |
+
this License. No additional rights or licenses will be implied from the
|
114 |
+
distribution or licensing of Covered Software under this License.
|
115 |
+
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
116 |
+
Contributor:
|
117 |
+
|
118 |
+
(a) for any code that a Contributor has removed from Covered Software;
|
119 |
+
or
|
120 |
+
|
121 |
+
(b) for infringements caused by: (i) Your and any other third party's
|
122 |
+
modifications of Covered Software, or (ii) the combination of its
|
123 |
+
Contributions with other software (except as part of its Contributor
|
124 |
+
Version); or
|
125 |
+
|
126 |
+
(c) under Patent Claims infringed by Covered Software in the absence of
|
127 |
+
its Contributions.
|
128 |
+
|
129 |
+
This License does not grant any rights in the trademarks, service marks,
|
130 |
+
or logos of any Contributor (except as may be necessary to comply with
|
131 |
+
the notice requirements in Section 3.4).
|
132 |
+
|
133 |
+
2.4. Subsequent Licenses
|
134 |
+
|
135 |
+
No Contributor makes additional grants as a result of Your choice to
|
136 |
+
distribute the Covered Software under a subsequent version of this
|
137 |
+
License (see Section 10.2) or under the terms of a Secondary License (if
|
138 |
+
permitted under the terms of Section 3.3).
|
139 |
+
|
140 |
+
2.5. Representation
|
141 |
+
|
142 |
+
Each Contributor represents that the Contributor believes its
|
143 |
+
Contributions are its original creation(s) or it has sufficient rights
|
144 |
+
to grant the rights to its Contributions conveyed by this License.
|
145 |
+
|
146 |
+
2.6. Fair Use
|
147 |
+
|
148 |
+
This License is not intended to limit any rights You have under
|
149 |
+
applicable copyright doctrines of fair use, fair dealing, or other
|
150 |
+
equivalents.
|
151 |
+
|
152 |
+
2.7. Conditions
|
153 |
+
|
154 |
+
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
155 |
+
in Section 2.1.
|
156 |
+
|
157 |
+
3. Responsibilities
|
158 |
+
-------------------
|
159 |
+
|
160 |
+
3.1. Distribution of Source Form
|
161 |
+
|
162 |
+
All distribution of Covered Software in Source Code Form, including any
|
163 |
+
Modifications that You create or to which You contribute, must be under
|
164 |
+
the terms of this License. You must inform recipients that the Source
|
165 |
+
Code Form of the Covered Software is governed by the terms of this
|
166 |
+
License, and how they can obtain a copy of this License. You may not
|
167 |
+
attempt to alter or restrict the recipients' rights in the Source Code
|
168 |
+
Form.
|
169 |
+
|
170 |
+
3.2. Distribution of Executable Form
|
171 |
+
|
172 |
+
If You distribute Covered Software in Executable Form then:
|
173 |
+
|
174 |
+
(a) such Covered Software must also be made available in Source Code
|
175 |
+
Form, as described in Section 3.1, and You must inform recipients of
|
176 |
+
the Executable Form how they can obtain a copy of such Source Code
|
177 |
+
Form by reasonable means in a timely manner, at a charge no more
|
178 |
+
than the cost of distribution to the recipient; and
|
179 |
+
|
180 |
+
(b) You may distribute such Executable Form under the terms of this
|
181 |
+
License, or sublicense it under different terms, provided that the
|
182 |
+
license for the Executable Form does not attempt to limit or alter
|
183 |
+
the recipients' rights in the Source Code Form under this License.
|
184 |
+
|
185 |
+
3.3. Distribution of a Larger Work
|
186 |
+
|
187 |
+
You may create and distribute a Larger Work under terms of Your choice,
|
188 |
+
provided that You also comply with the requirements of this License for
|
189 |
+
the Covered Software. If the Larger Work is a combination of Covered
|
190 |
+
Software with a work governed by one or more Secondary Licenses, and the
|
191 |
+
Covered Software is not Incompatible With Secondary Licenses, this
|
192 |
+
License permits You to additionally distribute such Covered Software
|
193 |
+
under the terms of such Secondary License(s), so that the recipient of
|
194 |
+
the Larger Work may, at their option, further distribute the Covered
|
195 |
+
Software under the terms of either this License or such Secondary
|
196 |
+
License(s).
|
197 |
+
|
198 |
+
3.4. Notices
|
199 |
+
|
200 |
+
You may not remove or alter the substance of any license notices
|
201 |
+
(including copyright notices, patent notices, disclaimers of warranty,
|
202 |
+
or limitations of liability) contained within the Source Code Form of
|
203 |
+
the Covered Software, except that You may alter any license notices to
|
204 |
+
the extent required to remedy known factual inaccuracies.
|
205 |
+
|
206 |
+
3.5. Application of Additional Terms
|
207 |
+
|
208 |
+
You may choose to offer, and to charge a fee for, warranty, support,
|
209 |
+
indemnity or liability obligations to one or more recipients of Covered
|
210 |
+
Software. However, You may do so only on Your own behalf, and not on
|
211 |
+
behalf of any Contributor. You must make it absolutely clear that any
|
212 |
+
such warranty, support, indemnity, or liability obligation is offered by
|
213 |
+
You alone, and You hereby agree to indemnify every Contributor for any
|
214 |
+
liability incurred by such Contributor as a result of warranty, support,
|
215 |
+
indemnity or liability terms You offer. You may include additional
|
216 |
+
disclaimers of warranty and limitations of liability specific to any
|
217 |
+
jurisdiction.
|
218 |
+
|
219 |
+
4. Inability to Comply Due to Statute or Regulation
|
220 |
+
---------------------------------------------------
|
221 |
+
|
222 |
+
If it is impossible for You to comply with any of the terms of this
|
223 |
+
License with respect to some or all of the Covered Software due to
|
224 |
+
statute, judicial order, or regulation then You must: (a) comply with
|
225 |
+
the terms of this License to the maximum extent possible; and (b)
|
226 |
+
describe the limitations and the code they affect. Such description must
|
227 |
+
be placed in a text file included with all distributions of the Covered
|
228 |
+
Software under this License. Except to the extent prohibited by statute
|
229 |
+
or regulation, such description must be sufficiently detailed for a
|
230 |
+
recipient of ordinary skill to be able to understand it.
|
231 |
+
|
232 |
+
5. Termination
|
233 |
+
--------------
|
234 |
+
|
235 |
+
5.1. The rights granted under this License will terminate automatically
|
236 |
+
if You fail to comply with any of its terms. However, if You become
|
237 |
+
compliant, then the rights granted under this License from a particular
|
238 |
+
Contributor are reinstated (a) provisionally, unless and until such
|
239 |
+
Contributor explicitly and finally terminates Your grants, and (b) on an
|
240 |
+
ongoing basis, if such Contributor fails to notify You of the
|
241 |
+
non-compliance by some reasonable means prior to 60 days after You have
|
242 |
+
come back into compliance. Moreover, Your grants from a particular
|
243 |
+
Contributor are reinstated on an ongoing basis if such Contributor
|
244 |
+
notifies You of the non-compliance by some reasonable means, this is the
|
245 |
+
first time You have received notice of non-compliance with this License
|
246 |
+
from such Contributor, and You become compliant prior to 30 days after
|
247 |
+
Your receipt of the notice.
|
248 |
+
|
249 |
+
5.2. If You initiate litigation against any entity by asserting a patent
|
250 |
+
infringement claim (excluding declaratory judgment actions,
|
251 |
+
counter-claims, and cross-claims) alleging that a Contributor Version
|
252 |
+
directly or indirectly infringes any patent, then the rights granted to
|
253 |
+
You by any and all Contributors for the Covered Software under Section
|
254 |
+
2.1 of this License shall terminate.
|
255 |
+
|
256 |
+
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
257 |
+
end user license agreements (excluding distributors and resellers) which
|
258 |
+
have been validly granted by You or Your distributors under this License
|
259 |
+
prior to termination shall survive termination.
|
260 |
+
|
261 |
+
************************************************************************
|
262 |
+
* *
|
263 |
+
* 6. Disclaimer of Warranty *
|
264 |
+
* ------------------------- *
|
265 |
+
* *
|
266 |
+
* Covered Software is provided under this License on an "as is" *
|
267 |
+
* basis, without warranty of any kind, either expressed, implied, or *
|
268 |
+
* statutory, including, without limitation, warranties that the *
|
269 |
+
* Covered Software is free of defects, merchantable, fit for a *
|
270 |
+
* particular purpose or non-infringing. The entire risk as to the *
|
271 |
+
* quality and performance of the Covered Software is with You. *
|
272 |
+
* Should any Covered Software prove defective in any respect, You *
|
273 |
+
* (not any Contributor) assume the cost of any necessary servicing, *
|
274 |
+
* repair, or correction. This disclaimer of warranty constitutes an *
|
275 |
+
* essential part of this License. No use of any Covered Software is *
|
276 |
+
* authorized under this License except under this disclaimer. *
|
277 |
+
* *
|
278 |
+
************************************************************************
|
279 |
+
|
280 |
+
************************************************************************
|
281 |
+
* *
|
282 |
+
* 7. Limitation of Liability *
|
283 |
+
* -------------------------- *
|
284 |
+
* *
|
285 |
+
* Under no circumstances and under no legal theory, whether tort *
|
286 |
+
* (including negligence), contract, or otherwise, shall any *
|
287 |
+
* Contributor, or anyone who distributes Covered Software as *
|
288 |
+
* permitted above, be liable to You for any direct, indirect, *
|
289 |
+
* special, incidental, or consequential damages of any character *
|
290 |
+
* including, without limitation, damages for lost profits, loss of *
|
291 |
+
* goodwill, work stoppage, computer failure or malfunction, or any *
|
292 |
+
* and all other commercial damages or losses, even if such party *
|
293 |
+
* shall have been informed of the possibility of such damages. This *
|
294 |
+
* limitation of liability shall not apply to liability for death or *
|
295 |
+
* personal injury resulting from such party's negligence to the *
|
296 |
+
* extent applicable law prohibits such limitation. Some *
|
297 |
+
* jurisdictions do not allow the exclusion or limitation of *
|
298 |
+
* incidental or consequential damages, so this exclusion and *
|
299 |
+
* limitation may not apply to You. *
|
300 |
+
* *
|
301 |
+
************************************************************************
|
302 |
+
|
303 |
+
8. Litigation
|
304 |
+
-------------
|
305 |
+
|
306 |
+
Any litigation relating to this License may be brought only in the
|
307 |
+
courts of a jurisdiction where the defendant maintains its principal
|
308 |
+
place of business and such litigation shall be governed by laws of that
|
309 |
+
jurisdiction, without reference to its conflict-of-law provisions.
|
310 |
+
Nothing in this Section shall prevent a party's ability to bring
|
311 |
+
cross-claims or counter-claims.
|
312 |
+
|
313 |
+
9. Miscellaneous
|
314 |
+
----------------
|
315 |
+
|
316 |
+
This License represents the complete agreement concerning the subject
|
317 |
+
matter hereof. If any provision of this License is held to be
|
318 |
+
unenforceable, such provision shall be reformed only to the extent
|
319 |
+
necessary to make it enforceable. Any law or regulation which provides
|
320 |
+
that the language of a contract shall be construed against the drafter
|
321 |
+
shall not be used to construe this License against a Contributor.
|
322 |
+
|
323 |
+
10. Versions of the License
|
324 |
+
---------------------------
|
325 |
+
|
326 |
+
10.1. New Versions
|
327 |
+
|
328 |
+
Mozilla Foundation is the license steward. Except as provided in Section
|
329 |
+
10.3, no one other than the license steward has the right to modify or
|
330 |
+
publish new versions of this License. Each version will be given a
|
331 |
+
distinguishing version number.
|
332 |
+
|
333 |
+
10.2. Effect of New Versions
|
334 |
+
|
335 |
+
You may distribute the Covered Software under the terms of the version
|
336 |
+
of the License under which You originally received the Covered Software,
|
337 |
+
or under the terms of any subsequent version published by the license
|
338 |
+
steward.
|
339 |
+
|
340 |
+
10.3. Modified Versions
|
341 |
+
|
342 |
+
If you create software not governed by this License, and you want to
|
343 |
+
create a new license for such software, you may create and use a
|
344 |
+
modified version of this License if you rename the license and remove
|
345 |
+
any references to the name of the license steward (except to note that
|
346 |
+
such modified license differs from this License).
|
347 |
+
|
348 |
+
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
349 |
+
Licenses
|
350 |
+
|
351 |
+
If You choose to distribute Source Code Form that is Incompatible With
|
352 |
+
Secondary Licenses under the terms of this version of the License, the
|
353 |
+
notice described in Exhibit B of this License must be attached.
|
354 |
+
|
355 |
+
Exhibit A - Source Code Form License Notice
|
356 |
+
-------------------------------------------
|
357 |
+
|
358 |
+
This Source Code Form is subject to the terms of the Mozilla Public
|
359 |
+
License, v. 2.0. If a copy of the MPL was not distributed with this
|
360 |
+
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
361 |
+
|
362 |
+
If it is not possible or desirable to put the notice in a particular
|
363 |
+
file, then You may include the notice in a location (such as a LICENSE
|
364 |
+
file in a relevant directory) where a recipient would be likely to look
|
365 |
+
for such a notice.
|
366 |
+
|
367 |
+
You may add additional accurate notices of copyright ownership.
|
368 |
+
|
369 |
+
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
370 |
+
---------------------------------------------------------
|
371 |
+
|
372 |
+
This Source Code Form is "Incompatible With Secondary Licenses", as
|
373 |
+
defined by the Mozilla Public License, v. 2.0.
|
inference/interact/fbrs/__init__.py
ADDED
File without changes
|
inference/interact/fbrs/controller.py
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
from ..fbrs.inference import clicker
|
4 |
+
from ..fbrs.inference.predictors import get_predictor
|
5 |
+
|
6 |
+
|
7 |
+
class InteractiveController:
|
8 |
+
def __init__(self, net, device, predictor_params, prob_thresh=0.5):
|
9 |
+
self.net = net.to(device)
|
10 |
+
self.prob_thresh = prob_thresh
|
11 |
+
self.clicker = clicker.Clicker()
|
12 |
+
self.states = []
|
13 |
+
self.probs_history = []
|
14 |
+
self.object_count = 0
|
15 |
+
self._result_mask = None
|
16 |
+
|
17 |
+
self.image = None
|
18 |
+
self.predictor = None
|
19 |
+
self.device = device
|
20 |
+
self.predictor_params = predictor_params
|
21 |
+
self.reset_predictor()
|
22 |
+
|
23 |
+
def set_image(self, image):
|
24 |
+
self.image = image
|
25 |
+
self._result_mask = torch.zeros(image.shape[-2:], dtype=torch.uint8)
|
26 |
+
self.object_count = 0
|
27 |
+
self.reset_last_object()
|
28 |
+
|
29 |
+
def add_click(self, x, y, is_positive):
|
30 |
+
self.states.append({
|
31 |
+
'clicker': self.clicker.get_state(),
|
32 |
+
'predictor': self.predictor.get_states()
|
33 |
+
})
|
34 |
+
|
35 |
+
click = clicker.Click(is_positive=is_positive, coords=(y, x))
|
36 |
+
self.clicker.add_click(click)
|
37 |
+
pred = self.predictor.get_prediction(self.clicker)
|
38 |
+
torch.cuda.empty_cache()
|
39 |
+
|
40 |
+
if self.probs_history:
|
41 |
+
self.probs_history.append((self.probs_history[-1][0], pred))
|
42 |
+
else:
|
43 |
+
self.probs_history.append((torch.zeros_like(pred), pred))
|
44 |
+
|
45 |
+
def undo_click(self):
|
46 |
+
if not self.states:
|
47 |
+
return
|
48 |
+
|
49 |
+
prev_state = self.states.pop()
|
50 |
+
self.clicker.set_state(prev_state['clicker'])
|
51 |
+
self.predictor.set_states(prev_state['predictor'])
|
52 |
+
self.probs_history.pop()
|
53 |
+
|
54 |
+
def partially_finish_object(self):
|
55 |
+
object_prob = self.current_object_prob
|
56 |
+
if object_prob is None:
|
57 |
+
return
|
58 |
+
|
59 |
+
self.probs_history.append((object_prob, torch.zeros_like(object_prob)))
|
60 |
+
self.states.append(self.states[-1])
|
61 |
+
|
62 |
+
self.clicker.reset_clicks()
|
63 |
+
self.reset_predictor()
|
64 |
+
|
65 |
+
def finish_object(self):
|
66 |
+
object_prob = self.current_object_prob
|
67 |
+
if object_prob is None:
|
68 |
+
return
|
69 |
+
|
70 |
+
self.object_count += 1
|
71 |
+
object_mask = object_prob > self.prob_thresh
|
72 |
+
self._result_mask[object_mask] = self.object_count
|
73 |
+
self.reset_last_object()
|
74 |
+
|
75 |
+
def reset_last_object(self):
|
76 |
+
self.states = []
|
77 |
+
self.probs_history = []
|
78 |
+
self.clicker.reset_clicks()
|
79 |
+
self.reset_predictor()
|
80 |
+
|
81 |
+
def reset_predictor(self, predictor_params=None):
|
82 |
+
if predictor_params is not None:
|
83 |
+
self.predictor_params = predictor_params
|
84 |
+
self.predictor = get_predictor(self.net, device=self.device,
|
85 |
+
**self.predictor_params)
|
86 |
+
if self.image is not None:
|
87 |
+
self.predictor.set_input_image(self.image)
|
88 |
+
|
89 |
+
@property
|
90 |
+
def current_object_prob(self):
|
91 |
+
if self.probs_history:
|
92 |
+
current_prob_total, current_prob_additive = self.probs_history[-1]
|
93 |
+
return torch.maximum(current_prob_total, current_prob_additive)
|
94 |
+
else:
|
95 |
+
return None
|
96 |
+
|
97 |
+
@property
|
98 |
+
def is_incomplete_mask(self):
|
99 |
+
return len(self.probs_history) > 0
|
100 |
+
|
101 |
+
@property
|
102 |
+
def result_mask(self):
|
103 |
+
return self._result_mask.clone()
|
inference/interact/fbrs/inference/__init__.py
ADDED
File without changes
|
inference/interact/fbrs/inference/clicker.py
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import namedtuple
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
from copy import deepcopy
|
5 |
+
from scipy.ndimage import distance_transform_edt
|
6 |
+
|
7 |
+
Click = namedtuple('Click', ['is_positive', 'coords'])
|
8 |
+
|
9 |
+
|
10 |
+
class Clicker(object):
|
11 |
+
def __init__(self, gt_mask=None, init_clicks=None, ignore_label=-1):
|
12 |
+
if gt_mask is not None:
|
13 |
+
self.gt_mask = gt_mask == 1
|
14 |
+
self.not_ignore_mask = gt_mask != ignore_label
|
15 |
+
else:
|
16 |
+
self.gt_mask = None
|
17 |
+
|
18 |
+
self.reset_clicks()
|
19 |
+
|
20 |
+
if init_clicks is not None:
|
21 |
+
for click in init_clicks:
|
22 |
+
self.add_click(click)
|
23 |
+
|
24 |
+
def make_next_click(self, pred_mask):
|
25 |
+
assert self.gt_mask is not None
|
26 |
+
click = self._get_click(pred_mask)
|
27 |
+
self.add_click(click)
|
28 |
+
|
29 |
+
def get_clicks(self, clicks_limit=None):
|
30 |
+
return self.clicks_list[:clicks_limit]
|
31 |
+
|
32 |
+
def _get_click(self, pred_mask, padding=True):
|
33 |
+
fn_mask = np.logical_and(np.logical_and(self.gt_mask, np.logical_not(pred_mask)), self.not_ignore_mask)
|
34 |
+
fp_mask = np.logical_and(np.logical_and(np.logical_not(self.gt_mask), pred_mask), self.not_ignore_mask)
|
35 |
+
|
36 |
+
if padding:
|
37 |
+
fn_mask = np.pad(fn_mask, ((1, 1), (1, 1)), 'constant')
|
38 |
+
fp_mask = np.pad(fp_mask, ((1, 1), (1, 1)), 'constant')
|
39 |
+
|
40 |
+
fn_mask_dt = distance_transform_edt(fn_mask)
|
41 |
+
fp_mask_dt = distance_transform_edt(fp_mask)
|
42 |
+
|
43 |
+
if padding:
|
44 |
+
fn_mask_dt = fn_mask_dt[1:-1, 1:-1]
|
45 |
+
fp_mask_dt = fp_mask_dt[1:-1, 1:-1]
|
46 |
+
|
47 |
+
fn_mask_dt = fn_mask_dt * self.not_clicked_map
|
48 |
+
fp_mask_dt = fp_mask_dt * self.not_clicked_map
|
49 |
+
|
50 |
+
fn_max_dist = np.max(fn_mask_dt)
|
51 |
+
fp_max_dist = np.max(fp_mask_dt)
|
52 |
+
|
53 |
+
is_positive = fn_max_dist > fp_max_dist
|
54 |
+
if is_positive:
|
55 |
+
coords_y, coords_x = np.where(fn_mask_dt == fn_max_dist) # coords is [y, x]
|
56 |
+
else:
|
57 |
+
coords_y, coords_x = np.where(fp_mask_dt == fp_max_dist) # coords is [y, x]
|
58 |
+
|
59 |
+
return Click(is_positive=is_positive, coords=(coords_y[0], coords_x[0]))
|
60 |
+
|
61 |
+
def add_click(self, click):
|
62 |
+
coords = click.coords
|
63 |
+
|
64 |
+
if click.is_positive:
|
65 |
+
self.num_pos_clicks += 1
|
66 |
+
else:
|
67 |
+
self.num_neg_clicks += 1
|
68 |
+
|
69 |
+
self.clicks_list.append(click)
|
70 |
+
if self.gt_mask is not None:
|
71 |
+
self.not_clicked_map[coords[0], coords[1]] = False
|
72 |
+
|
73 |
+
def _remove_last_click(self):
|
74 |
+
click = self.clicks_list.pop()
|
75 |
+
coords = click.coords
|
76 |
+
|
77 |
+
if click.is_positive:
|
78 |
+
self.num_pos_clicks -= 1
|
79 |
+
else:
|
80 |
+
self.num_neg_clicks -= 1
|
81 |
+
|
82 |
+
if self.gt_mask is not None:
|
83 |
+
self.not_clicked_map[coords[0], coords[1]] = True
|
84 |
+
|
85 |
+
def reset_clicks(self):
|
86 |
+
if self.gt_mask is not None:
|
87 |
+
self.not_clicked_map = np.ones_like(self.gt_mask, dtype=np.bool)
|
88 |
+
|
89 |
+
self.num_pos_clicks = 0
|
90 |
+
self.num_neg_clicks = 0
|
91 |
+
|
92 |
+
self.clicks_list = []
|
93 |
+
|
94 |
+
def get_state(self):
|
95 |
+
return deepcopy(self.clicks_list)
|
96 |
+
|
97 |
+
def set_state(self, state):
|
98 |
+
self.reset_clicks()
|
99 |
+
for click in state:
|
100 |
+
self.add_click(click)
|
101 |
+
|
102 |
+
def __len__(self):
|
103 |
+
return len(self.clicks_list)
|
inference/interact/fbrs/inference/evaluation.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from time import time
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
|
6 |
+
from ..inference import utils
|
7 |
+
from ..inference.clicker import Clicker
|
8 |
+
|
9 |
+
try:
|
10 |
+
get_ipython()
|
11 |
+
from tqdm import tqdm_notebook as tqdm
|
12 |
+
except NameError:
|
13 |
+
from tqdm import tqdm
|
14 |
+
|
15 |
+
|
16 |
+
def evaluate_dataset(dataset, predictor, oracle_eval=False, **kwargs):
|
17 |
+
all_ious = []
|
18 |
+
|
19 |
+
start_time = time()
|
20 |
+
for index in tqdm(range(len(dataset)), leave=False):
|
21 |
+
sample = dataset.get_sample(index)
|
22 |
+
item = dataset[index]
|
23 |
+
|
24 |
+
if oracle_eval:
|
25 |
+
gt_mask = torch.tensor(sample['instances_mask'], dtype=torch.float32)
|
26 |
+
gt_mask = gt_mask.unsqueeze(0).unsqueeze(0)
|
27 |
+
predictor.opt_functor.mask_loss.set_gt_mask(gt_mask)
|
28 |
+
_, sample_ious, _ = evaluate_sample(item['images'], sample['instances_mask'], predictor, **kwargs)
|
29 |
+
all_ious.append(sample_ious)
|
30 |
+
end_time = time()
|
31 |
+
elapsed_time = end_time - start_time
|
32 |
+
|
33 |
+
return all_ious, elapsed_time
|
34 |
+
|
35 |
+
|
36 |
+
def evaluate_sample(image_nd, instances_mask, predictor, max_iou_thr,
|
37 |
+
pred_thr=0.49, max_clicks=20):
|
38 |
+
clicker = Clicker(gt_mask=instances_mask)
|
39 |
+
pred_mask = np.zeros_like(instances_mask)
|
40 |
+
ious_list = []
|
41 |
+
|
42 |
+
with torch.no_grad():
|
43 |
+
predictor.set_input_image(image_nd)
|
44 |
+
|
45 |
+
for click_number in range(max_clicks):
|
46 |
+
clicker.make_next_click(pred_mask)
|
47 |
+
pred_probs = predictor.get_prediction(clicker)
|
48 |
+
pred_mask = pred_probs > pred_thr
|
49 |
+
|
50 |
+
iou = utils.get_iou(instances_mask, pred_mask)
|
51 |
+
ious_list.append(iou)
|
52 |
+
|
53 |
+
if iou >= max_iou_thr:
|
54 |
+
break
|
55 |
+
|
56 |
+
return clicker.clicks_list, np.array(ious_list, dtype=np.float32), pred_probs
|
inference/interact/fbrs/inference/predictors/__init__.py
ADDED
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .base import BasePredictor
|
2 |
+
from .brs import InputBRSPredictor, FeatureBRSPredictor, HRNetFeatureBRSPredictor
|
3 |
+
from .brs_functors import InputOptimizer, ScaleBiasOptimizer
|
4 |
+
from ..transforms import ZoomIn
|
5 |
+
from ...model.is_hrnet_model import DistMapsHRNetModel
|
6 |
+
|
7 |
+
|
8 |
+
def get_predictor(net, brs_mode, device,
|
9 |
+
prob_thresh=0.49,
|
10 |
+
with_flip=True,
|
11 |
+
zoom_in_params=dict(),
|
12 |
+
predictor_params=None,
|
13 |
+
brs_opt_func_params=None,
|
14 |
+
lbfgs_params=None):
|
15 |
+
lbfgs_params_ = {
|
16 |
+
'm': 20,
|
17 |
+
'factr': 0,
|
18 |
+
'pgtol': 1e-8,
|
19 |
+
'maxfun': 20,
|
20 |
+
}
|
21 |
+
|
22 |
+
predictor_params_ = {
|
23 |
+
'optimize_after_n_clicks': 1
|
24 |
+
}
|
25 |
+
|
26 |
+
if zoom_in_params is not None:
|
27 |
+
zoom_in = ZoomIn(**zoom_in_params)
|
28 |
+
else:
|
29 |
+
zoom_in = None
|
30 |
+
|
31 |
+
if lbfgs_params is not None:
|
32 |
+
lbfgs_params_.update(lbfgs_params)
|
33 |
+
lbfgs_params_['maxiter'] = 2 * lbfgs_params_['maxfun']
|
34 |
+
|
35 |
+
if brs_opt_func_params is None:
|
36 |
+
brs_opt_func_params = dict()
|
37 |
+
|
38 |
+
if brs_mode == 'NoBRS':
|
39 |
+
if predictor_params is not None:
|
40 |
+
predictor_params_.update(predictor_params)
|
41 |
+
predictor = BasePredictor(net, device, zoom_in=zoom_in, with_flip=with_flip, **predictor_params_)
|
42 |
+
elif brs_mode.startswith('f-BRS'):
|
43 |
+
predictor_params_.update({
|
44 |
+
'net_clicks_limit': 8,
|
45 |
+
})
|
46 |
+
if predictor_params is not None:
|
47 |
+
predictor_params_.update(predictor_params)
|
48 |
+
|
49 |
+
insertion_mode = {
|
50 |
+
'f-BRS-A': 'after_c4',
|
51 |
+
'f-BRS-B': 'after_aspp',
|
52 |
+
'f-BRS-C': 'after_deeplab'
|
53 |
+
}[brs_mode]
|
54 |
+
|
55 |
+
opt_functor = ScaleBiasOptimizer(prob_thresh=prob_thresh,
|
56 |
+
with_flip=with_flip,
|
57 |
+
optimizer_params=lbfgs_params_,
|
58 |
+
**brs_opt_func_params)
|
59 |
+
|
60 |
+
if isinstance(net, DistMapsHRNetModel):
|
61 |
+
FeaturePredictor = HRNetFeatureBRSPredictor
|
62 |
+
insertion_mode = {'after_c4': 'A', 'after_aspp': 'A', 'after_deeplab': 'C'}[insertion_mode]
|
63 |
+
else:
|
64 |
+
FeaturePredictor = FeatureBRSPredictor
|
65 |
+
|
66 |
+
predictor = FeaturePredictor(net, device,
|
67 |
+
opt_functor=opt_functor,
|
68 |
+
with_flip=with_flip,
|
69 |
+
insertion_mode=insertion_mode,
|
70 |
+
zoom_in=zoom_in,
|
71 |
+
**predictor_params_)
|
72 |
+
elif brs_mode == 'RGB-BRS' or brs_mode == 'DistMap-BRS':
|
73 |
+
use_dmaps = brs_mode == 'DistMap-BRS'
|
74 |
+
|
75 |
+
predictor_params_.update({
|
76 |
+
'net_clicks_limit': 5,
|
77 |
+
})
|
78 |
+
if predictor_params is not None:
|
79 |
+
predictor_params_.update(predictor_params)
|
80 |
+
|
81 |
+
opt_functor = InputOptimizer(prob_thresh=prob_thresh,
|
82 |
+
with_flip=with_flip,
|
83 |
+
optimizer_params=lbfgs_params_,
|
84 |
+
**brs_opt_func_params)
|
85 |
+
|
86 |
+
predictor = InputBRSPredictor(net, device,
|
87 |
+
optimize_target='dmaps' if use_dmaps else 'rgb',
|
88 |
+
opt_functor=opt_functor,
|
89 |
+
with_flip=with_flip,
|
90 |
+
zoom_in=zoom_in,
|
91 |
+
**predictor_params_)
|
92 |
+
else:
|
93 |
+
raise NotImplementedError
|
94 |
+
|
95 |
+
return predictor
|
inference/interact/fbrs/inference/predictors/base.py
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn.functional as F
|
3 |
+
|
4 |
+
from ..transforms import AddHorizontalFlip, SigmoidForPred, LimitLongestSide
|
5 |
+
|
6 |
+
|
7 |
+
class BasePredictor(object):
|
8 |
+
def __init__(self, net, device,
|
9 |
+
net_clicks_limit=None,
|
10 |
+
with_flip=False,
|
11 |
+
zoom_in=None,
|
12 |
+
max_size=None,
|
13 |
+
**kwargs):
|
14 |
+
self.net = net
|
15 |
+
self.with_flip = with_flip
|
16 |
+
self.net_clicks_limit = net_clicks_limit
|
17 |
+
self.original_image = None
|
18 |
+
self.device = device
|
19 |
+
self.zoom_in = zoom_in
|
20 |
+
|
21 |
+
self.transforms = [zoom_in] if zoom_in is not None else []
|
22 |
+
if max_size is not None:
|
23 |
+
self.transforms.append(LimitLongestSide(max_size=max_size))
|
24 |
+
self.transforms.append(SigmoidForPred())
|
25 |
+
if with_flip:
|
26 |
+
self.transforms.append(AddHorizontalFlip())
|
27 |
+
|
28 |
+
def set_input_image(self, image_nd):
|
29 |
+
for transform in self.transforms:
|
30 |
+
transform.reset()
|
31 |
+
self.original_image = image_nd.to(self.device)
|
32 |
+
if len(self.original_image.shape) == 3:
|
33 |
+
self.original_image = self.original_image.unsqueeze(0)
|
34 |
+
|
35 |
+
def get_prediction(self, clicker):
|
36 |
+
clicks_list = clicker.get_clicks()
|
37 |
+
|
38 |
+
image_nd, clicks_lists, is_image_changed = self.apply_transforms(
|
39 |
+
self.original_image, [clicks_list]
|
40 |
+
)
|
41 |
+
|
42 |
+
pred_logits = self._get_prediction(image_nd, clicks_lists, is_image_changed)
|
43 |
+
prediction = F.interpolate(pred_logits, mode='bilinear', align_corners=True,
|
44 |
+
size=image_nd.size()[2:])
|
45 |
+
|
46 |
+
for t in reversed(self.transforms):
|
47 |
+
prediction = t.inv_transform(prediction)
|
48 |
+
|
49 |
+
if self.zoom_in is not None and self.zoom_in.check_possible_recalculation():
|
50 |
+
print('zooming')
|
51 |
+
return self.get_prediction(clicker)
|
52 |
+
|
53 |
+
# return prediction.cpu().numpy()[0, 0]
|
54 |
+
return prediction
|
55 |
+
|
56 |
+
def _get_prediction(self, image_nd, clicks_lists, is_image_changed):
|
57 |
+
points_nd = self.get_points_nd(clicks_lists)
|
58 |
+
return self.net(image_nd, points_nd)['instances']
|
59 |
+
|
60 |
+
def _get_transform_states(self):
|
61 |
+
return [x.get_state() for x in self.transforms]
|
62 |
+
|
63 |
+
def _set_transform_states(self, states):
|
64 |
+
assert len(states) == len(self.transforms)
|
65 |
+
for state, transform in zip(states, self.transforms):
|
66 |
+
transform.set_state(state)
|
67 |
+
|
68 |
+
def apply_transforms(self, image_nd, clicks_lists):
|
69 |
+
is_image_changed = False
|
70 |
+
for t in self.transforms:
|
71 |
+
image_nd, clicks_lists = t.transform(image_nd, clicks_lists)
|
72 |
+
is_image_changed |= t.image_changed
|
73 |
+
|
74 |
+
return image_nd, clicks_lists, is_image_changed
|
75 |
+
|
76 |
+
def get_points_nd(self, clicks_lists):
|
77 |
+
total_clicks = []
|
78 |
+
num_pos_clicks = [sum(x.is_positive for x in clicks_list) for clicks_list in clicks_lists]
|
79 |
+
num_neg_clicks = [len(clicks_list) - num_pos for clicks_list, num_pos in zip(clicks_lists, num_pos_clicks)]
|
80 |
+
num_max_points = max(num_pos_clicks + num_neg_clicks)
|
81 |
+
if self.net_clicks_limit is not None:
|
82 |
+
num_max_points = min(self.net_clicks_limit, num_max_points)
|
83 |
+
num_max_points = max(1, num_max_points)
|
84 |
+
|
85 |
+
for clicks_list in clicks_lists:
|
86 |
+
clicks_list = clicks_list[:self.net_clicks_limit]
|
87 |
+
pos_clicks = [click.coords for click in clicks_list if click.is_positive]
|
88 |
+
pos_clicks = pos_clicks + (num_max_points - len(pos_clicks)) * [(-1, -1)]
|
89 |
+
|
90 |
+
neg_clicks = [click.coords for click in clicks_list if not click.is_positive]
|
91 |
+
neg_clicks = neg_clicks + (num_max_points - len(neg_clicks)) * [(-1, -1)]
|
92 |
+
total_clicks.append(pos_clicks + neg_clicks)
|
93 |
+
|
94 |
+
return torch.tensor(total_clicks, device=self.device)
|
95 |
+
|
96 |
+
def get_states(self):
|
97 |
+
return {'transform_states': self._get_transform_states()}
|
98 |
+
|
99 |
+
def set_states(self, states):
|
100 |
+
self._set_transform_states(states['transform_states'])
|
inference/interact/fbrs/inference/predictors/brs.py
ADDED
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn.functional as F
|
3 |
+
import numpy as np
|
4 |
+
from scipy.optimize import fmin_l_bfgs_b
|
5 |
+
|
6 |
+
from .base import BasePredictor
|
7 |
+
from ...model.is_hrnet_model import DistMapsHRNetModel
|
8 |
+
|
9 |
+
|
10 |
+
class BRSBasePredictor(BasePredictor):
|
11 |
+
def __init__(self, model, device, opt_functor, optimize_after_n_clicks=1, **kwargs):
|
12 |
+
super().__init__(model, device, **kwargs)
|
13 |
+
self.optimize_after_n_clicks = optimize_after_n_clicks
|
14 |
+
self.opt_functor = opt_functor
|
15 |
+
|
16 |
+
self.opt_data = None
|
17 |
+
self.input_data = None
|
18 |
+
|
19 |
+
def set_input_image(self, image_nd):
|
20 |
+
super().set_input_image(image_nd)
|
21 |
+
self.opt_data = None
|
22 |
+
self.input_data = None
|
23 |
+
|
24 |
+
def _get_clicks_maps_nd(self, clicks_lists, image_shape, radius=1):
|
25 |
+
pos_clicks_map = np.zeros((len(clicks_lists), 1) + image_shape, dtype=np.float32)
|
26 |
+
neg_clicks_map = np.zeros((len(clicks_lists), 1) + image_shape, dtype=np.float32)
|
27 |
+
|
28 |
+
for list_indx, clicks_list in enumerate(clicks_lists):
|
29 |
+
for click in clicks_list:
|
30 |
+
y, x = click.coords
|
31 |
+
y, x = int(round(y)), int(round(x))
|
32 |
+
y1, x1 = y - radius, x - radius
|
33 |
+
y2, x2 = y + radius + 1, x + radius + 1
|
34 |
+
|
35 |
+
if click.is_positive:
|
36 |
+
pos_clicks_map[list_indx, 0, y1:y2, x1:x2] = True
|
37 |
+
else:
|
38 |
+
neg_clicks_map[list_indx, 0, y1:y2, x1:x2] = True
|
39 |
+
|
40 |
+
with torch.no_grad():
|
41 |
+
pos_clicks_map = torch.from_numpy(pos_clicks_map).to(self.device)
|
42 |
+
neg_clicks_map = torch.from_numpy(neg_clicks_map).to(self.device)
|
43 |
+
|
44 |
+
return pos_clicks_map, neg_clicks_map
|
45 |
+
|
46 |
+
def get_states(self):
|
47 |
+
return {'transform_states': self._get_transform_states(), 'opt_data': self.opt_data}
|
48 |
+
|
49 |
+
def set_states(self, states):
|
50 |
+
self._set_transform_states(states['transform_states'])
|
51 |
+
self.opt_data = states['opt_data']
|
52 |
+
|
53 |
+
|
54 |
+
class FeatureBRSPredictor(BRSBasePredictor):
|
55 |
+
def __init__(self, model, device, opt_functor, insertion_mode='after_deeplab', **kwargs):
|
56 |
+
super().__init__(model, device, opt_functor=opt_functor, **kwargs)
|
57 |
+
self.insertion_mode = insertion_mode
|
58 |
+
self._c1_features = None
|
59 |
+
|
60 |
+
if self.insertion_mode == 'after_deeplab':
|
61 |
+
self.num_channels = model.feature_extractor.ch
|
62 |
+
elif self.insertion_mode == 'after_c4':
|
63 |
+
self.num_channels = model.feature_extractor.aspp_in_channels
|
64 |
+
elif self.insertion_mode == 'after_aspp':
|
65 |
+
self.num_channels = model.feature_extractor.ch + 32
|
66 |
+
else:
|
67 |
+
raise NotImplementedError
|
68 |
+
|
69 |
+
def _get_prediction(self, image_nd, clicks_lists, is_image_changed):
|
70 |
+
points_nd = self.get_points_nd(clicks_lists)
|
71 |
+
pos_mask, neg_mask = self._get_clicks_maps_nd(clicks_lists, image_nd.shape[2:])
|
72 |
+
|
73 |
+
num_clicks = len(clicks_lists[0])
|
74 |
+
bs = image_nd.shape[0] // 2 if self.with_flip else image_nd.shape[0]
|
75 |
+
|
76 |
+
if self.opt_data is None or self.opt_data.shape[0] // (2 * self.num_channels) != bs:
|
77 |
+
self.opt_data = np.zeros((bs * 2 * self.num_channels), dtype=np.float32)
|
78 |
+
|
79 |
+
if num_clicks <= self.net_clicks_limit or is_image_changed or self.input_data is None:
|
80 |
+
self.input_data = self._get_head_input(image_nd, points_nd)
|
81 |
+
|
82 |
+
def get_prediction_logits(scale, bias):
|
83 |
+
scale = scale.view(bs, -1, 1, 1)
|
84 |
+
bias = bias.view(bs, -1, 1, 1)
|
85 |
+
if self.with_flip:
|
86 |
+
scale = scale.repeat(2, 1, 1, 1)
|
87 |
+
bias = bias.repeat(2, 1, 1, 1)
|
88 |
+
|
89 |
+
scaled_backbone_features = self.input_data * scale
|
90 |
+
scaled_backbone_features = scaled_backbone_features + bias
|
91 |
+
if self.insertion_mode == 'after_c4':
|
92 |
+
x = self.net.feature_extractor.aspp(scaled_backbone_features)
|
93 |
+
x = F.interpolate(x, mode='bilinear', size=self._c1_features.size()[2:],
|
94 |
+
align_corners=True)
|
95 |
+
x = torch.cat((x, self._c1_features), dim=1)
|
96 |
+
scaled_backbone_features = self.net.feature_extractor.head(x)
|
97 |
+
elif self.insertion_mode == 'after_aspp':
|
98 |
+
scaled_backbone_features = self.net.feature_extractor.head(scaled_backbone_features)
|
99 |
+
|
100 |
+
pred_logits = self.net.head(scaled_backbone_features)
|
101 |
+
pred_logits = F.interpolate(pred_logits, size=image_nd.size()[2:], mode='bilinear',
|
102 |
+
align_corners=True)
|
103 |
+
return pred_logits
|
104 |
+
|
105 |
+
self.opt_functor.init_click(get_prediction_logits, pos_mask, neg_mask, self.device)
|
106 |
+
if num_clicks > self.optimize_after_n_clicks:
|
107 |
+
opt_result = fmin_l_bfgs_b(func=self.opt_functor, x0=self.opt_data,
|
108 |
+
**self.opt_functor.optimizer_params)
|
109 |
+
self.opt_data = opt_result[0]
|
110 |
+
|
111 |
+
with torch.no_grad():
|
112 |
+
if self.opt_functor.best_prediction is not None:
|
113 |
+
opt_pred_logits = self.opt_functor.best_prediction
|
114 |
+
else:
|
115 |
+
opt_data_nd = torch.from_numpy(self.opt_data).to(self.device)
|
116 |
+
opt_vars, _ = self.opt_functor.unpack_opt_params(opt_data_nd)
|
117 |
+
opt_pred_logits = get_prediction_logits(*opt_vars)
|
118 |
+
|
119 |
+
return opt_pred_logits
|
120 |
+
|
121 |
+
def _get_head_input(self, image_nd, points):
|
122 |
+
with torch.no_grad():
|
123 |
+
coord_features = self.net.dist_maps(image_nd, points)
|
124 |
+
x = self.net.rgb_conv(torch.cat((image_nd, coord_features), dim=1))
|
125 |
+
if self.insertion_mode == 'after_c4' or self.insertion_mode == 'after_aspp':
|
126 |
+
c1, _, c3, c4 = self.net.feature_extractor.backbone(x)
|
127 |
+
c1 = self.net.feature_extractor.skip_project(c1)
|
128 |
+
|
129 |
+
if self.insertion_mode == 'after_aspp':
|
130 |
+
x = self.net.feature_extractor.aspp(c4)
|
131 |
+
x = F.interpolate(x, size=c1.size()[2:], mode='bilinear', align_corners=True)
|
132 |
+
x = torch.cat((x, c1), dim=1)
|
133 |
+
backbone_features = x
|
134 |
+
else:
|
135 |
+
backbone_features = c4
|
136 |
+
self._c1_features = c1
|
137 |
+
else:
|
138 |
+
backbone_features = self.net.feature_extractor(x)[0]
|
139 |
+
|
140 |
+
return backbone_features
|
141 |
+
|
142 |
+
|
143 |
+
class HRNetFeatureBRSPredictor(BRSBasePredictor):
|
144 |
+
def __init__(self, model, device, opt_functor, insertion_mode='A', **kwargs):
|
145 |
+
super().__init__(model, device, opt_functor=opt_functor, **kwargs)
|
146 |
+
self.insertion_mode = insertion_mode
|
147 |
+
self._c1_features = None
|
148 |
+
|
149 |
+
if self.insertion_mode == 'A':
|
150 |
+
self.num_channels = sum(k * model.feature_extractor.width for k in [1, 2, 4, 8])
|
151 |
+
elif self.insertion_mode == 'C':
|
152 |
+
self.num_channels = 2 * model.feature_extractor.ocr_width
|
153 |
+
else:
|
154 |
+
raise NotImplementedError
|
155 |
+
|
156 |
+
def _get_prediction(self, image_nd, clicks_lists, is_image_changed):
|
157 |
+
points_nd = self.get_points_nd(clicks_lists)
|
158 |
+
pos_mask, neg_mask = self._get_clicks_maps_nd(clicks_lists, image_nd.shape[2:])
|
159 |
+
num_clicks = len(clicks_lists[0])
|
160 |
+
bs = image_nd.shape[0] // 2 if self.with_flip else image_nd.shape[0]
|
161 |
+
|
162 |
+
if self.opt_data is None or self.opt_data.shape[0] // (2 * self.num_channels) != bs:
|
163 |
+
self.opt_data = np.zeros((bs * 2 * self.num_channels), dtype=np.float32)
|
164 |
+
|
165 |
+
if num_clicks <= self.net_clicks_limit or is_image_changed or self.input_data is None:
|
166 |
+
self.input_data = self._get_head_input(image_nd, points_nd)
|
167 |
+
|
168 |
+
def get_prediction_logits(scale, bias):
|
169 |
+
scale = scale.view(bs, -1, 1, 1)
|
170 |
+
bias = bias.view(bs, -1, 1, 1)
|
171 |
+
if self.with_flip:
|
172 |
+
scale = scale.repeat(2, 1, 1, 1)
|
173 |
+
bias = bias.repeat(2, 1, 1, 1)
|
174 |
+
|
175 |
+
scaled_backbone_features = self.input_data * scale
|
176 |
+
scaled_backbone_features = scaled_backbone_features + bias
|
177 |
+
if self.insertion_mode == 'A':
|
178 |
+
out_aux = self.net.feature_extractor.aux_head(scaled_backbone_features)
|
179 |
+
feats = self.net.feature_extractor.conv3x3_ocr(scaled_backbone_features)
|
180 |
+
|
181 |
+
context = self.net.feature_extractor.ocr_gather_head(feats, out_aux)
|
182 |
+
feats = self.net.feature_extractor.ocr_distri_head(feats, context)
|
183 |
+
pred_logits = self.net.feature_extractor.cls_head(feats)
|
184 |
+
elif self.insertion_mode == 'C':
|
185 |
+
pred_logits = self.net.feature_extractor.cls_head(scaled_backbone_features)
|
186 |
+
else:
|
187 |
+
raise NotImplementedError
|
188 |
+
|
189 |
+
pred_logits = F.interpolate(pred_logits, size=image_nd.size()[2:], mode='bilinear',
|
190 |
+
align_corners=True)
|
191 |
+
return pred_logits
|
192 |
+
|
193 |
+
self.opt_functor.init_click(get_prediction_logits, pos_mask, neg_mask, self.device)
|
194 |
+
if num_clicks > self.optimize_after_n_clicks:
|
195 |
+
opt_result = fmin_l_bfgs_b(func=self.opt_functor, x0=self.opt_data,
|
196 |
+
**self.opt_functor.optimizer_params)
|
197 |
+
self.opt_data = opt_result[0]
|
198 |
+
|
199 |
+
with torch.no_grad():
|
200 |
+
if self.opt_functor.best_prediction is not None:
|
201 |
+
opt_pred_logits = self.opt_functor.best_prediction
|
202 |
+
else:
|
203 |
+
opt_data_nd = torch.from_numpy(self.opt_data).to(self.device)
|
204 |
+
opt_vars, _ = self.opt_functor.unpack_opt_params(opt_data_nd)
|
205 |
+
opt_pred_logits = get_prediction_logits(*opt_vars)
|
206 |
+
|
207 |
+
return opt_pred_logits
|
208 |
+
|
209 |
+
def _get_head_input(self, image_nd, points):
|
210 |
+
with torch.no_grad():
|
211 |
+
coord_features = self.net.dist_maps(image_nd, points)
|
212 |
+
x = self.net.rgb_conv(torch.cat((image_nd, coord_features), dim=1))
|
213 |
+
feats = self.net.feature_extractor.compute_hrnet_feats(x)
|
214 |
+
if self.insertion_mode == 'A':
|
215 |
+
backbone_features = feats
|
216 |
+
elif self.insertion_mode == 'C':
|
217 |
+
out_aux = self.net.feature_extractor.aux_head(feats)
|
218 |
+
feats = self.net.feature_extractor.conv3x3_ocr(feats)
|
219 |
+
|
220 |
+
context = self.net.feature_extractor.ocr_gather_head(feats, out_aux)
|
221 |
+
backbone_features = self.net.feature_extractor.ocr_distri_head(feats, context)
|
222 |
+
else:
|
223 |
+
raise NotImplementedError
|
224 |
+
|
225 |
+
return backbone_features
|
226 |
+
|
227 |
+
|
228 |
+
class InputBRSPredictor(BRSBasePredictor):
|
229 |
+
def __init__(self, model, device, opt_functor, optimize_target='rgb', **kwargs):
|
230 |
+
super().__init__(model, device, opt_functor=opt_functor, **kwargs)
|
231 |
+
self.optimize_target = optimize_target
|
232 |
+
|
233 |
+
def _get_prediction(self, image_nd, clicks_lists, is_image_changed):
|
234 |
+
points_nd = self.get_points_nd(clicks_lists)
|
235 |
+
pos_mask, neg_mask = self._get_clicks_maps_nd(clicks_lists, image_nd.shape[2:])
|
236 |
+
num_clicks = len(clicks_lists[0])
|
237 |
+
|
238 |
+
if self.opt_data is None or is_image_changed:
|
239 |
+
opt_channels = 2 if self.optimize_target == 'dmaps' else 3
|
240 |
+
bs = image_nd.shape[0] // 2 if self.with_flip else image_nd.shape[0]
|
241 |
+
self.opt_data = torch.zeros((bs, opt_channels, image_nd.shape[2], image_nd.shape[3]),
|
242 |
+
device=self.device, dtype=torch.float32)
|
243 |
+
|
244 |
+
def get_prediction_logits(opt_bias):
|
245 |
+
input_image = image_nd
|
246 |
+
if self.optimize_target == 'rgb':
|
247 |
+
input_image = input_image + opt_bias
|
248 |
+
dmaps = self.net.dist_maps(input_image, points_nd)
|
249 |
+
if self.optimize_target == 'dmaps':
|
250 |
+
dmaps = dmaps + opt_bias
|
251 |
+
|
252 |
+
x = self.net.rgb_conv(torch.cat((input_image, dmaps), dim=1))
|
253 |
+
if self.optimize_target == 'all':
|
254 |
+
x = x + opt_bias
|
255 |
+
|
256 |
+
if isinstance(self.net, DistMapsHRNetModel):
|
257 |
+
pred_logits = self.net.feature_extractor(x)[0]
|
258 |
+
else:
|
259 |
+
backbone_features = self.net.feature_extractor(x)
|
260 |
+
pred_logits = self.net.head(backbone_features[0])
|
261 |
+
pred_logits = F.interpolate(pred_logits, size=image_nd.size()[2:], mode='bilinear', align_corners=True)
|
262 |
+
|
263 |
+
return pred_logits
|
264 |
+
|
265 |
+
self.opt_functor.init_click(get_prediction_logits, pos_mask, neg_mask, self.device,
|
266 |
+
shape=self.opt_data.shape)
|
267 |
+
if num_clicks > self.optimize_after_n_clicks:
|
268 |
+
opt_result = fmin_l_bfgs_b(func=self.opt_functor, x0=self.opt_data.cpu().numpy().ravel(),
|
269 |
+
**self.opt_functor.optimizer_params)
|
270 |
+
|
271 |
+
self.opt_data = torch.from_numpy(opt_result[0]).view(self.opt_data.shape).to(self.device)
|
272 |
+
|
273 |
+
with torch.no_grad():
|
274 |
+
if self.opt_functor.best_prediction is not None:
|
275 |
+
opt_pred_logits = self.opt_functor.best_prediction
|
276 |
+
else:
|
277 |
+
opt_vars, _ = self.opt_functor.unpack_opt_params(self.opt_data)
|
278 |
+
opt_pred_logits = get_prediction_logits(*opt_vars)
|
279 |
+
|
280 |
+
return opt_pred_logits
|
inference/interact/fbrs/inference/predictors/brs_functors.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
from ...model.metrics import _compute_iou
|
5 |
+
from .brs_losses import BRSMaskLoss
|
6 |
+
|
7 |
+
|
8 |
+
class BaseOptimizer:
|
9 |
+
def __init__(self, optimizer_params,
|
10 |
+
prob_thresh=0.49,
|
11 |
+
reg_weight=1e-3,
|
12 |
+
min_iou_diff=0.01,
|
13 |
+
brs_loss=BRSMaskLoss(),
|
14 |
+
with_flip=False,
|
15 |
+
flip_average=False,
|
16 |
+
**kwargs):
|
17 |
+
self.brs_loss = brs_loss
|
18 |
+
self.optimizer_params = optimizer_params
|
19 |
+
self.prob_thresh = prob_thresh
|
20 |
+
self.reg_weight = reg_weight
|
21 |
+
self.min_iou_diff = min_iou_diff
|
22 |
+
self.with_flip = with_flip
|
23 |
+
self.flip_average = flip_average
|
24 |
+
|
25 |
+
self.best_prediction = None
|
26 |
+
self._get_prediction_logits = None
|
27 |
+
self._opt_shape = None
|
28 |
+
self._best_loss = None
|
29 |
+
self._click_masks = None
|
30 |
+
self._last_mask = None
|
31 |
+
self.device = None
|
32 |
+
|
33 |
+
def init_click(self, get_prediction_logits, pos_mask, neg_mask, device, shape=None):
|
34 |
+
self.best_prediction = None
|
35 |
+
self._get_prediction_logits = get_prediction_logits
|
36 |
+
self._click_masks = (pos_mask, neg_mask)
|
37 |
+
self._opt_shape = shape
|
38 |
+
self._last_mask = None
|
39 |
+
self.device = device
|
40 |
+
|
41 |
+
def __call__(self, x):
|
42 |
+
opt_params = torch.from_numpy(x).float().to(self.device)
|
43 |
+
opt_params.requires_grad_(True)
|
44 |
+
|
45 |
+
with torch.enable_grad():
|
46 |
+
opt_vars, reg_loss = self.unpack_opt_params(opt_params)
|
47 |
+
result_before_sigmoid = self._get_prediction_logits(*opt_vars)
|
48 |
+
result = torch.sigmoid(result_before_sigmoid)
|
49 |
+
|
50 |
+
pos_mask, neg_mask = self._click_masks
|
51 |
+
if self.with_flip and self.flip_average:
|
52 |
+
result, result_flipped = torch.chunk(result, 2, dim=0)
|
53 |
+
result = 0.5 * (result + torch.flip(result_flipped, dims=[3]))
|
54 |
+
pos_mask, neg_mask = pos_mask[:result.shape[0]], neg_mask[:result.shape[0]]
|
55 |
+
|
56 |
+
loss, f_max_pos, f_max_neg = self.brs_loss(result, pos_mask, neg_mask)
|
57 |
+
loss = loss + reg_loss
|
58 |
+
|
59 |
+
f_val = loss.detach().cpu().numpy()
|
60 |
+
if self.best_prediction is None or f_val < self._best_loss:
|
61 |
+
self.best_prediction = result_before_sigmoid.detach()
|
62 |
+
self._best_loss = f_val
|
63 |
+
|
64 |
+
if f_max_pos < (1 - self.prob_thresh) and f_max_neg < self.prob_thresh:
|
65 |
+
return [f_val, np.zeros_like(x)]
|
66 |
+
|
67 |
+
current_mask = result > self.prob_thresh
|
68 |
+
if self._last_mask is not None and self.min_iou_diff > 0:
|
69 |
+
diff_iou = _compute_iou(current_mask, self._last_mask)
|
70 |
+
if len(diff_iou) > 0 and diff_iou.mean() > 1 - self.min_iou_diff:
|
71 |
+
return [f_val, np.zeros_like(x)]
|
72 |
+
self._last_mask = current_mask
|
73 |
+
|
74 |
+
loss.backward()
|
75 |
+
f_grad = opt_params.grad.cpu().numpy().ravel().astype(np.float)
|
76 |
+
|
77 |
+
return [f_val, f_grad]
|
78 |
+
|
79 |
+
def unpack_opt_params(self, opt_params):
|
80 |
+
raise NotImplementedError
|
81 |
+
|
82 |
+
|
83 |
+
class InputOptimizer(BaseOptimizer):
|
84 |
+
def unpack_opt_params(self, opt_params):
|
85 |
+
opt_params = opt_params.view(self._opt_shape)
|
86 |
+
if self.with_flip:
|
87 |
+
opt_params_flipped = torch.flip(opt_params, dims=[3])
|
88 |
+
opt_params = torch.cat([opt_params, opt_params_flipped], dim=0)
|
89 |
+
reg_loss = self.reg_weight * torch.sum(opt_params**2)
|
90 |
+
|
91 |
+
return (opt_params,), reg_loss
|
92 |
+
|
93 |
+
|
94 |
+
class ScaleBiasOptimizer(BaseOptimizer):
|
95 |
+
def __init__(self, *args, scale_act=None, reg_bias_weight=10.0, **kwargs):
|
96 |
+
super().__init__(*args, **kwargs)
|
97 |
+
self.scale_act = scale_act
|
98 |
+
self.reg_bias_weight = reg_bias_weight
|
99 |
+
|
100 |
+
def unpack_opt_params(self, opt_params):
|
101 |
+
scale, bias = torch.chunk(opt_params, 2, dim=0)
|
102 |
+
reg_loss = self.reg_weight * (torch.sum(scale**2) + self.reg_bias_weight * torch.sum(bias**2))
|
103 |
+
|
104 |
+
if self.scale_act == 'tanh':
|
105 |
+
scale = torch.tanh(scale)
|
106 |
+
elif self.scale_act == 'sin':
|
107 |
+
scale = torch.sin(scale)
|
108 |
+
|
109 |
+
return (1 + scale, bias), reg_loss
|
inference/interact/fbrs/inference/predictors/brs_losses.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
from ...model.losses import SigmoidBinaryCrossEntropyLoss
|
4 |
+
|
5 |
+
|
6 |
+
class BRSMaskLoss(torch.nn.Module):
|
7 |
+
def __init__(self, eps=1e-5):
|
8 |
+
super().__init__()
|
9 |
+
self._eps = eps
|
10 |
+
|
11 |
+
def forward(self, result, pos_mask, neg_mask):
|
12 |
+
pos_diff = (1 - result) * pos_mask
|
13 |
+
pos_target = torch.sum(pos_diff ** 2)
|
14 |
+
pos_target = pos_target / (torch.sum(pos_mask) + self._eps)
|
15 |
+
|
16 |
+
neg_diff = result * neg_mask
|
17 |
+
neg_target = torch.sum(neg_diff ** 2)
|
18 |
+
neg_target = neg_target / (torch.sum(neg_mask) + self._eps)
|
19 |
+
|
20 |
+
loss = pos_target + neg_target
|
21 |
+
|
22 |
+
with torch.no_grad():
|
23 |
+
f_max_pos = torch.max(torch.abs(pos_diff)).item()
|
24 |
+
f_max_neg = torch.max(torch.abs(neg_diff)).item()
|
25 |
+
|
26 |
+
return loss, f_max_pos, f_max_neg
|
27 |
+
|
28 |
+
|
29 |
+
class OracleMaskLoss(torch.nn.Module):
|
30 |
+
def __init__(self):
|
31 |
+
super().__init__()
|
32 |
+
self.gt_mask = None
|
33 |
+
self.loss = SigmoidBinaryCrossEntropyLoss(from_sigmoid=True)
|
34 |
+
self.predictor = None
|
35 |
+
self.history = []
|
36 |
+
|
37 |
+
def set_gt_mask(self, gt_mask):
|
38 |
+
self.gt_mask = gt_mask
|
39 |
+
self.history = []
|
40 |
+
|
41 |
+
def forward(self, result, pos_mask, neg_mask):
|
42 |
+
gt_mask = self.gt_mask.to(result.device)
|
43 |
+
if self.predictor.object_roi is not None:
|
44 |
+
r1, r2, c1, c2 = self.predictor.object_roi[:4]
|
45 |
+
gt_mask = gt_mask[:, :, r1:r2 + 1, c1:c2 + 1]
|
46 |
+
gt_mask = torch.nn.functional.interpolate(gt_mask, result.size()[2:], mode='bilinear', align_corners=True)
|
47 |
+
|
48 |
+
if result.shape[0] == 2:
|
49 |
+
gt_mask_flipped = torch.flip(gt_mask, dims=[3])
|
50 |
+
gt_mask = torch.cat([gt_mask, gt_mask_flipped], dim=0)
|
51 |
+
|
52 |
+
loss = self.loss(result, gt_mask)
|
53 |
+
self.history.append(loss.detach().cpu().numpy()[0])
|
54 |
+
|
55 |
+
if len(self.history) > 5 and abs(self.history[-5] - self.history[-1]) < 1e-5:
|
56 |
+
return 0, 0, 0
|
57 |
+
|
58 |
+
return loss, 1.0, 1.0
|
inference/interact/fbrs/inference/transforms/__init__.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .base import SigmoidForPred
|
2 |
+
from .flip import AddHorizontalFlip
|
3 |
+
from .zoom_in import ZoomIn
|
4 |
+
from .limit_longest_side import LimitLongestSide
|
5 |
+
from .crops import Crops
|
inference/interact/fbrs/inference/transforms/base.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
|
4 |
+
class BaseTransform(object):
|
5 |
+
def __init__(self):
|
6 |
+
self.image_changed = False
|
7 |
+
|
8 |
+
def transform(self, image_nd, clicks_lists):
|
9 |
+
raise NotImplementedError
|
10 |
+
|
11 |
+
def inv_transform(self, prob_map):
|
12 |
+
raise NotImplementedError
|
13 |
+
|
14 |
+
def reset(self):
|
15 |
+
raise NotImplementedError
|
16 |
+
|
17 |
+
def get_state(self):
|
18 |
+
raise NotImplementedError
|
19 |
+
|
20 |
+
def set_state(self, state):
|
21 |
+
raise NotImplementedError
|
22 |
+
|
23 |
+
|
24 |
+
class SigmoidForPred(BaseTransform):
|
25 |
+
def transform(self, image_nd, clicks_lists):
|
26 |
+
return image_nd, clicks_lists
|
27 |
+
|
28 |
+
def inv_transform(self, prob_map):
|
29 |
+
return torch.sigmoid(prob_map)
|
30 |
+
|
31 |
+
def reset(self):
|
32 |
+
pass
|
33 |
+
|
34 |
+
def get_state(self):
|
35 |
+
return None
|
36 |
+
|
37 |
+
def set_state(self, state):
|
38 |
+
pass
|
inference/interact/fbrs/inference/transforms/crops.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
from ...inference.clicker import Click
|
7 |
+
from .base import BaseTransform
|
8 |
+
|
9 |
+
|
10 |
+
class Crops(BaseTransform):
|
11 |
+
def __init__(self, crop_size=(320, 480), min_overlap=0.2):
|
12 |
+
super().__init__()
|
13 |
+
self.crop_height, self.crop_width = crop_size
|
14 |
+
self.min_overlap = min_overlap
|
15 |
+
|
16 |
+
self.x_offsets = None
|
17 |
+
self.y_offsets = None
|
18 |
+
self._counts = None
|
19 |
+
|
20 |
+
def transform(self, image_nd, clicks_lists):
|
21 |
+
assert image_nd.shape[0] == 1 and len(clicks_lists) == 1
|
22 |
+
image_height, image_width = image_nd.shape[2:4]
|
23 |
+
self._counts = None
|
24 |
+
|
25 |
+
if image_height < self.crop_height or image_width < self.crop_width:
|
26 |
+
return image_nd, clicks_lists
|
27 |
+
|
28 |
+
self.x_offsets = get_offsets(image_width, self.crop_width, self.min_overlap)
|
29 |
+
self.y_offsets = get_offsets(image_height, self.crop_height, self.min_overlap)
|
30 |
+
self._counts = np.zeros((image_height, image_width))
|
31 |
+
|
32 |
+
image_crops = []
|
33 |
+
for dy in self.y_offsets:
|
34 |
+
for dx in self.x_offsets:
|
35 |
+
self._counts[dy:dy + self.crop_height, dx:dx + self.crop_width] += 1
|
36 |
+
image_crop = image_nd[:, :, dy:dy + self.crop_height, dx:dx + self.crop_width]
|
37 |
+
image_crops.append(image_crop)
|
38 |
+
image_crops = torch.cat(image_crops, dim=0)
|
39 |
+
self._counts = torch.tensor(self._counts, device=image_nd.device, dtype=torch.float32)
|
40 |
+
|
41 |
+
clicks_list = clicks_lists[0]
|
42 |
+
clicks_lists = []
|
43 |
+
for dy in self.y_offsets:
|
44 |
+
for dx in self.x_offsets:
|
45 |
+
crop_clicks = [Click(is_positive=x.is_positive, coords=(x.coords[0] - dy, x.coords[1] - dx))
|
46 |
+
for x in clicks_list]
|
47 |
+
clicks_lists.append(crop_clicks)
|
48 |
+
|
49 |
+
return image_crops, clicks_lists
|
50 |
+
|
51 |
+
def inv_transform(self, prob_map):
|
52 |
+
if self._counts is None:
|
53 |
+
return prob_map
|
54 |
+
|
55 |
+
new_prob_map = torch.zeros((1, 1, *self._counts.shape),
|
56 |
+
dtype=prob_map.dtype, device=prob_map.device)
|
57 |
+
|
58 |
+
crop_indx = 0
|
59 |
+
for dy in self.y_offsets:
|
60 |
+
for dx in self.x_offsets:
|
61 |
+
new_prob_map[0, 0, dy:dy + self.crop_height, dx:dx + self.crop_width] += prob_map[crop_indx, 0]
|
62 |
+
crop_indx += 1
|
63 |
+
new_prob_map = torch.div(new_prob_map, self._counts)
|
64 |
+
|
65 |
+
return new_prob_map
|
66 |
+
|
67 |
+
def get_state(self):
|
68 |
+
return self.x_offsets, self.y_offsets, self._counts
|
69 |
+
|
70 |
+
def set_state(self, state):
|
71 |
+
self.x_offsets, self.y_offsets, self._counts = state
|
72 |
+
|
73 |
+
def reset(self):
|
74 |
+
self.x_offsets = None
|
75 |
+
self.y_offsets = None
|
76 |
+
self._counts = None
|
77 |
+
|
78 |
+
|
79 |
+
def get_offsets(length, crop_size, min_overlap_ratio=0.2):
|
80 |
+
if length == crop_size:
|
81 |
+
return [0]
|
82 |
+
|
83 |
+
N = (length / crop_size - min_overlap_ratio) / (1 - min_overlap_ratio)
|
84 |
+
N = math.ceil(N)
|
85 |
+
|
86 |
+
overlap_ratio = (N - length / crop_size) / (N - 1)
|
87 |
+
overlap_width = int(crop_size * overlap_ratio)
|
88 |
+
|
89 |
+
offsets = [0]
|
90 |
+
for i in range(1, N):
|
91 |
+
new_offset = offsets[-1] + crop_size - overlap_width
|
92 |
+
if new_offset + crop_size > length:
|
93 |
+
new_offset = length - crop_size
|
94 |
+
|
95 |
+
offsets.append(new_offset)
|
96 |
+
|
97 |
+
return offsets
|
inference/interact/fbrs/inference/transforms/flip.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
from ..clicker import Click
|
4 |
+
from .base import BaseTransform
|
5 |
+
|
6 |
+
|
7 |
+
class AddHorizontalFlip(BaseTransform):
|
8 |
+
def transform(self, image_nd, clicks_lists):
|
9 |
+
assert len(image_nd.shape) == 4
|
10 |
+
image_nd = torch.cat([image_nd, torch.flip(image_nd, dims=[3])], dim=0)
|
11 |
+
|
12 |
+
image_width = image_nd.shape[3]
|
13 |
+
clicks_lists_flipped = []
|
14 |
+
for clicks_list in clicks_lists:
|
15 |
+
clicks_list_flipped = [Click(is_positive=click.is_positive,
|
16 |
+
coords=(click.coords[0], image_width - click.coords[1] - 1))
|
17 |
+
for click in clicks_list]
|
18 |
+
clicks_lists_flipped.append(clicks_list_flipped)
|
19 |
+
clicks_lists = clicks_lists + clicks_lists_flipped
|
20 |
+
|
21 |
+
return image_nd, clicks_lists
|
22 |
+
|
23 |
+
def inv_transform(self, prob_map):
|
24 |
+
assert len(prob_map.shape) == 4 and prob_map.shape[0] % 2 == 0
|
25 |
+
num_maps = prob_map.shape[0] // 2
|
26 |
+
prob_map, prob_map_flipped = prob_map[:num_maps], prob_map[num_maps:]
|
27 |
+
|
28 |
+
return 0.5 * (prob_map + torch.flip(prob_map_flipped, dims=[3]))
|
29 |
+
|
30 |
+
def get_state(self):
|
31 |
+
return None
|
32 |
+
|
33 |
+
def set_state(self, state):
|
34 |
+
pass
|
35 |
+
|
36 |
+
def reset(self):
|
37 |
+
pass
|
inference/interact/fbrs/inference/transforms/limit_longest_side.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .zoom_in import ZoomIn, get_roi_image_nd
|
2 |
+
|
3 |
+
|
4 |
+
class LimitLongestSide(ZoomIn):
|
5 |
+
def __init__(self, max_size=800):
|
6 |
+
super().__init__(target_size=max_size, skip_clicks=0)
|
7 |
+
|
8 |
+
def transform(self, image_nd, clicks_lists):
|
9 |
+
assert image_nd.shape[0] == 1 and len(clicks_lists) == 1
|
10 |
+
image_max_size = max(image_nd.shape[2:4])
|
11 |
+
self.image_changed = False
|
12 |
+
|
13 |
+
if image_max_size <= self.target_size:
|
14 |
+
return image_nd, clicks_lists
|
15 |
+
self._input_image = image_nd
|
16 |
+
|
17 |
+
self._object_roi = (0, image_nd.shape[2] - 1, 0, image_nd.shape[3] - 1)
|
18 |
+
self._roi_image = get_roi_image_nd(image_nd, self._object_roi, self.target_size)
|
19 |
+
self.image_changed = True
|
20 |
+
|
21 |
+
tclicks_lists = [self._transform_clicks(clicks_lists[0])]
|
22 |
+
return self._roi_image, tclicks_lists
|
inference/interact/fbrs/inference/transforms/zoom_in.py
ADDED
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
from ..clicker import Click
|
4 |
+
from ...utils.misc import get_bbox_iou, get_bbox_from_mask, expand_bbox, clamp_bbox
|
5 |
+
from .base import BaseTransform
|
6 |
+
|
7 |
+
|
8 |
+
class ZoomIn(BaseTransform):
|
9 |
+
def __init__(self,
|
10 |
+
target_size=400,
|
11 |
+
skip_clicks=1,
|
12 |
+
expansion_ratio=1.4,
|
13 |
+
min_crop_size=200,
|
14 |
+
recompute_thresh_iou=0.5,
|
15 |
+
prob_thresh=0.50):
|
16 |
+
super().__init__()
|
17 |
+
self.target_size = target_size
|
18 |
+
self.min_crop_size = min_crop_size
|
19 |
+
self.skip_clicks = skip_clicks
|
20 |
+
self.expansion_ratio = expansion_ratio
|
21 |
+
self.recompute_thresh_iou = recompute_thresh_iou
|
22 |
+
self.prob_thresh = prob_thresh
|
23 |
+
|
24 |
+
self._input_image_shape = None
|
25 |
+
self._prev_probs = None
|
26 |
+
self._object_roi = None
|
27 |
+
self._roi_image = None
|
28 |
+
|
29 |
+
def transform(self, image_nd, clicks_lists):
|
30 |
+
assert image_nd.shape[0] == 1 and len(clicks_lists) == 1
|
31 |
+
self.image_changed = False
|
32 |
+
|
33 |
+
clicks_list = clicks_lists[0]
|
34 |
+
if len(clicks_list) <= self.skip_clicks:
|
35 |
+
return image_nd, clicks_lists
|
36 |
+
|
37 |
+
self._input_image_shape = image_nd.shape
|
38 |
+
|
39 |
+
current_object_roi = None
|
40 |
+
if self._prev_probs is not None:
|
41 |
+
current_pred_mask = (self._prev_probs > self.prob_thresh)[0, 0]
|
42 |
+
if current_pred_mask.sum() > 0:
|
43 |
+
current_object_roi = get_object_roi(current_pred_mask, clicks_list,
|
44 |
+
self.expansion_ratio, self.min_crop_size)
|
45 |
+
|
46 |
+
if current_object_roi is None:
|
47 |
+
return image_nd, clicks_lists
|
48 |
+
|
49 |
+
update_object_roi = False
|
50 |
+
if self._object_roi is None:
|
51 |
+
update_object_roi = True
|
52 |
+
elif not check_object_roi(self._object_roi, clicks_list):
|
53 |
+
update_object_roi = True
|
54 |
+
elif get_bbox_iou(current_object_roi, self._object_roi) < self.recompute_thresh_iou:
|
55 |
+
update_object_roi = True
|
56 |
+
|
57 |
+
if update_object_roi:
|
58 |
+
self._object_roi = current_object_roi
|
59 |
+
self._roi_image = get_roi_image_nd(image_nd, self._object_roi, self.target_size)
|
60 |
+
self.image_changed = True
|
61 |
+
|
62 |
+
tclicks_lists = [self._transform_clicks(clicks_list)]
|
63 |
+
return self._roi_image.to(image_nd.device), tclicks_lists
|
64 |
+
|
65 |
+
def inv_transform(self, prob_map):
|
66 |
+
if self._object_roi is None:
|
67 |
+
self._prev_probs = prob_map.cpu().numpy()
|
68 |
+
return prob_map
|
69 |
+
|
70 |
+
assert prob_map.shape[0] == 1
|
71 |
+
rmin, rmax, cmin, cmax = self._object_roi
|
72 |
+
prob_map = torch.nn.functional.interpolate(prob_map, size=(rmax - rmin + 1, cmax - cmin + 1),
|
73 |
+
mode='bilinear', align_corners=True)
|
74 |
+
|
75 |
+
if self._prev_probs is not None:
|
76 |
+
new_prob_map = torch.zeros(*self._prev_probs.shape, device=prob_map.device, dtype=prob_map.dtype)
|
77 |
+
new_prob_map[:, :, rmin:rmax + 1, cmin:cmax + 1] = prob_map
|
78 |
+
else:
|
79 |
+
new_prob_map = prob_map
|
80 |
+
|
81 |
+
self._prev_probs = new_prob_map.cpu().numpy()
|
82 |
+
|
83 |
+
return new_prob_map
|
84 |
+
|
85 |
+
def check_possible_recalculation(self):
|
86 |
+
if self._prev_probs is None or self._object_roi is not None or self.skip_clicks > 0:
|
87 |
+
return False
|
88 |
+
|
89 |
+
pred_mask = (self._prev_probs > self.prob_thresh)[0, 0]
|
90 |
+
if pred_mask.sum() > 0:
|
91 |
+
possible_object_roi = get_object_roi(pred_mask, [],
|
92 |
+
self.expansion_ratio, self.min_crop_size)
|
93 |
+
image_roi = (0, self._input_image_shape[2] - 1, 0, self._input_image_shape[3] - 1)
|
94 |
+
if get_bbox_iou(possible_object_roi, image_roi) < 0.50:
|
95 |
+
return True
|
96 |
+
return False
|
97 |
+
|
98 |
+
def get_state(self):
|
99 |
+
roi_image = self._roi_image.cpu() if self._roi_image is not None else None
|
100 |
+
return self._input_image_shape, self._object_roi, self._prev_probs, roi_image, self.image_changed
|
101 |
+
|
102 |
+
def set_state(self, state):
|
103 |
+
self._input_image_shape, self._object_roi, self._prev_probs, self._roi_image, self.image_changed = state
|
104 |
+
|
105 |
+
def reset(self):
|
106 |
+
self._input_image_shape = None
|
107 |
+
self._object_roi = None
|
108 |
+
self._prev_probs = None
|
109 |
+
self._roi_image = None
|
110 |
+
self.image_changed = False
|
111 |
+
|
112 |
+
def _transform_clicks(self, clicks_list):
|
113 |
+
if self._object_roi is None:
|
114 |
+
return clicks_list
|
115 |
+
|
116 |
+
rmin, rmax, cmin, cmax = self._object_roi
|
117 |
+
crop_height, crop_width = self._roi_image.shape[2:]
|
118 |
+
|
119 |
+
transformed_clicks = []
|
120 |
+
for click in clicks_list:
|
121 |
+
new_r = crop_height * (click.coords[0] - rmin) / (rmax - rmin + 1)
|
122 |
+
new_c = crop_width * (click.coords[1] - cmin) / (cmax - cmin + 1)
|
123 |
+
transformed_clicks.append(Click(is_positive=click.is_positive, coords=(new_r, new_c)))
|
124 |
+
return transformed_clicks
|
125 |
+
|
126 |
+
|
127 |
+
def get_object_roi(pred_mask, clicks_list, expansion_ratio, min_crop_size):
|
128 |
+
pred_mask = pred_mask.copy()
|
129 |
+
|
130 |
+
for click in clicks_list:
|
131 |
+
if click.is_positive:
|
132 |
+
pred_mask[int(click.coords[0]), int(click.coords[1])] = 1
|
133 |
+
|
134 |
+
bbox = get_bbox_from_mask(pred_mask)
|
135 |
+
bbox = expand_bbox(bbox, expansion_ratio, min_crop_size)
|
136 |
+
h, w = pred_mask.shape[0], pred_mask.shape[1]
|
137 |
+
bbox = clamp_bbox(bbox, 0, h - 1, 0, w - 1)
|
138 |
+
|
139 |
+
return bbox
|
140 |
+
|
141 |
+
|
142 |
+
def get_roi_image_nd(image_nd, object_roi, target_size):
|
143 |
+
rmin, rmax, cmin, cmax = object_roi
|
144 |
+
|
145 |
+
height = rmax - rmin + 1
|
146 |
+
width = cmax - cmin + 1
|
147 |
+
|
148 |
+
if isinstance(target_size, tuple):
|
149 |
+
new_height, new_width = target_size
|
150 |
+
else:
|
151 |
+
scale = target_size / max(height, width)
|
152 |
+
new_height = int(round(height * scale))
|
153 |
+
new_width = int(round(width * scale))
|
154 |
+
|
155 |
+
with torch.no_grad():
|
156 |
+
roi_image_nd = image_nd[:, :, rmin:rmax + 1, cmin:cmax + 1]
|
157 |
+
roi_image_nd = torch.nn.functional.interpolate(roi_image_nd, size=(new_height, new_width),
|
158 |
+
mode='bilinear', align_corners=True)
|
159 |
+
|
160 |
+
return roi_image_nd
|
161 |
+
|
162 |
+
|
163 |
+
def check_object_roi(object_roi, clicks_list):
|
164 |
+
for click in clicks_list:
|
165 |
+
if click.is_positive:
|
166 |
+
if click.coords[0] < object_roi[0] or click.coords[0] >= object_roi[1]:
|
167 |
+
return False
|
168 |
+
if click.coords[1] < object_roi[2] or click.coords[1] >= object_roi[3]:
|
169 |
+
return False
|
170 |
+
|
171 |
+
return True
|
inference/interact/fbrs/inference/utils.py
ADDED
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import timedelta
|
2 |
+
from pathlib import Path
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
from ..model.is_deeplab_model import get_deeplab_model
|
8 |
+
from ..model.is_hrnet_model import get_hrnet_model
|
9 |
+
|
10 |
+
|
11 |
+
def get_time_metrics(all_ious, elapsed_time):
|
12 |
+
n_images = len(all_ious)
|
13 |
+
n_clicks = sum(map(len, all_ious))
|
14 |
+
|
15 |
+
mean_spc = elapsed_time / n_clicks
|
16 |
+
mean_spi = elapsed_time / n_images
|
17 |
+
|
18 |
+
return mean_spc, mean_spi
|
19 |
+
|
20 |
+
|
21 |
+
def load_is_model(checkpoint, device, backbone='auto', **kwargs):
|
22 |
+
if isinstance(checkpoint, (str, Path)):
|
23 |
+
state_dict = torch.load(checkpoint, map_location='cpu')
|
24 |
+
else:
|
25 |
+
state_dict = checkpoint
|
26 |
+
|
27 |
+
if backbone == 'auto':
|
28 |
+
for k in state_dict.keys():
|
29 |
+
if 'feature_extractor.stage2.0.branches' in k:
|
30 |
+
return load_hrnet_is_model(state_dict, device, backbone, **kwargs)
|
31 |
+
return load_deeplab_is_model(state_dict, device, backbone, **kwargs)
|
32 |
+
elif 'resnet' in backbone:
|
33 |
+
return load_deeplab_is_model(state_dict, device, backbone, **kwargs)
|
34 |
+
elif 'hrnet' in backbone:
|
35 |
+
return load_hrnet_is_model(state_dict, device, backbone, **kwargs)
|
36 |
+
else:
|
37 |
+
raise NotImplementedError('Unknown backbone')
|
38 |
+
|
39 |
+
|
40 |
+
def load_hrnet_is_model(state_dict, device, backbone='auto', width=48, ocr_width=256,
|
41 |
+
small=False, cpu_dist_maps=False, norm_radius=260):
|
42 |
+
if backbone == 'auto':
|
43 |
+
num_fe_weights = len([x for x in state_dict.keys() if 'feature_extractor.' in x])
|
44 |
+
small = num_fe_weights < 1800
|
45 |
+
|
46 |
+
ocr_f_down = [v for k, v in state_dict.items() if 'object_context_block.f_down.1.0.bias' in k]
|
47 |
+
assert len(ocr_f_down) == 1
|
48 |
+
ocr_width = ocr_f_down[0].shape[0]
|
49 |
+
|
50 |
+
s2_conv1_w = [v for k, v in state_dict.items() if 'stage2.0.branches.0.0.conv1.weight' in k]
|
51 |
+
assert len(s2_conv1_w) == 1
|
52 |
+
width = s2_conv1_w[0].shape[0]
|
53 |
+
|
54 |
+
model = get_hrnet_model(width=width, ocr_width=ocr_width, small=small,
|
55 |
+
with_aux_output=False, cpu_dist_maps=cpu_dist_maps,
|
56 |
+
norm_radius=norm_radius)
|
57 |
+
|
58 |
+
model.load_state_dict(state_dict, strict=False)
|
59 |
+
for param in model.parameters():
|
60 |
+
param.requires_grad = False
|
61 |
+
model.to(device)
|
62 |
+
model.eval()
|
63 |
+
|
64 |
+
return model
|
65 |
+
|
66 |
+
|
67 |
+
def load_deeplab_is_model(state_dict, device, backbone='auto', deeplab_ch=128, aspp_dropout=0.2,
|
68 |
+
cpu_dist_maps=False, norm_radius=260):
|
69 |
+
if backbone == 'auto':
|
70 |
+
num_backbone_params = len([x for x in state_dict.keys()
|
71 |
+
if 'feature_extractor.backbone' in x and not('num_batches_tracked' in x)])
|
72 |
+
|
73 |
+
if num_backbone_params <= 181:
|
74 |
+
backbone = 'resnet34'
|
75 |
+
elif num_backbone_params <= 276:
|
76 |
+
backbone = 'resnet50'
|
77 |
+
elif num_backbone_params <= 531:
|
78 |
+
backbone = 'resnet101'
|
79 |
+
else:
|
80 |
+
raise NotImplementedError('Unknown backbone')
|
81 |
+
|
82 |
+
if 'aspp_dropout' in state_dict:
|
83 |
+
aspp_dropout = float(state_dict['aspp_dropout'].cpu().numpy())
|
84 |
+
else:
|
85 |
+
aspp_project_weight = [v for k, v in state_dict.items() if 'aspp.project.0.weight' in k][0]
|
86 |
+
deeplab_ch = aspp_project_weight.size(0)
|
87 |
+
if deeplab_ch == 256:
|
88 |
+
aspp_dropout = 0.5
|
89 |
+
|
90 |
+
model = get_deeplab_model(backbone=backbone, deeplab_ch=deeplab_ch,
|
91 |
+
aspp_dropout=aspp_dropout, cpu_dist_maps=cpu_dist_maps,
|
92 |
+
norm_radius=norm_radius)
|
93 |
+
|
94 |
+
model.load_state_dict(state_dict, strict=False)
|
95 |
+
for param in model.parameters():
|
96 |
+
param.requires_grad = False
|
97 |
+
model.to(device)
|
98 |
+
model.eval()
|
99 |
+
|
100 |
+
return model
|
101 |
+
|
102 |
+
|
103 |
+
def get_iou(gt_mask, pred_mask, ignore_label=-1):
|
104 |
+
ignore_gt_mask_inv = gt_mask != ignore_label
|
105 |
+
obj_gt_mask = gt_mask == 1
|
106 |
+
|
107 |
+
intersection = np.logical_and(np.logical_and(pred_mask, obj_gt_mask), ignore_gt_mask_inv).sum()
|
108 |
+
union = np.logical_and(np.logical_or(pred_mask, obj_gt_mask), ignore_gt_mask_inv).sum()
|
109 |
+
|
110 |
+
return intersection / union
|
111 |
+
|
112 |
+
|
113 |
+
def compute_noc_metric(all_ious, iou_thrs, max_clicks=20):
|
114 |
+
def _get_noc(iou_arr, iou_thr):
|
115 |
+
vals = iou_arr >= iou_thr
|
116 |
+
return np.argmax(vals) + 1 if np.any(vals) else max_clicks
|
117 |
+
|
118 |
+
noc_list = []
|
119 |
+
over_max_list = []
|
120 |
+
for iou_thr in iou_thrs:
|
121 |
+
scores_arr = np.array([_get_noc(iou_arr, iou_thr)
|
122 |
+
for iou_arr in all_ious], dtype=np.int)
|
123 |
+
|
124 |
+
score = scores_arr.mean()
|
125 |
+
over_max = (scores_arr == max_clicks).sum()
|
126 |
+
|
127 |
+
noc_list.append(score)
|
128 |
+
over_max_list.append(over_max)
|
129 |
+
|
130 |
+
return noc_list, over_max_list
|
131 |
+
|
132 |
+
|
133 |
+
def find_checkpoint(weights_folder, checkpoint_name):
|
134 |
+
weights_folder = Path(weights_folder)
|
135 |
+
if ':' in checkpoint_name:
|
136 |
+
model_name, checkpoint_name = checkpoint_name.split(':')
|
137 |
+
models_candidates = [x for x in weights_folder.glob(f'{model_name}*') if x.is_dir()]
|
138 |
+
assert len(models_candidates) == 1
|
139 |
+
model_folder = models_candidates[0]
|
140 |
+
else:
|
141 |
+
model_folder = weights_folder
|
142 |
+
|
143 |
+
if checkpoint_name.endswith('.pth'):
|
144 |
+
if Path(checkpoint_name).exists():
|
145 |
+
checkpoint_path = checkpoint_name
|
146 |
+
else:
|
147 |
+
checkpoint_path = weights_folder / checkpoint_name
|
148 |
+
else:
|
149 |
+
model_checkpoints = list(model_folder.rglob(f'{checkpoint_name}*.pth'))
|
150 |
+
assert len(model_checkpoints) == 1
|
151 |
+
checkpoint_path = model_checkpoints[0]
|
152 |
+
|
153 |
+
return str(checkpoint_path)
|
154 |
+
|
155 |
+
|
156 |
+
def get_results_table(noc_list, over_max_list, brs_type, dataset_name, mean_spc, elapsed_time,
|
157 |
+
n_clicks=20, model_name=None):
|
158 |
+
table_header = (f'|{"BRS Type":^13}|{"Dataset":^11}|'
|
159 |
+
f'{"NoC@80%":^9}|{"NoC@85%":^9}|{"NoC@90%":^9}|'
|
160 |
+
f'{">="+str(n_clicks)+"@85%":^9}|{">="+str(n_clicks)+"@90%":^9}|'
|
161 |
+
f'{"SPC,s":^7}|{"Time":^9}|')
|
162 |
+
row_width = len(table_header)
|
163 |
+
|
164 |
+
header = f'Eval results for model: {model_name}\n' if model_name is not None else ''
|
165 |
+
header += '-' * row_width + '\n'
|
166 |
+
header += table_header + '\n' + '-' * row_width
|
167 |
+
|
168 |
+
eval_time = str(timedelta(seconds=int(elapsed_time)))
|
169 |
+
table_row = f'|{brs_type:^13}|{dataset_name:^11}|'
|
170 |
+
table_row += f'{noc_list[0]:^9.2f}|'
|
171 |
+
table_row += f'{noc_list[1]:^9.2f}|' if len(noc_list) > 1 else f'{"?":^9}|'
|
172 |
+
table_row += f'{noc_list[2]:^9.2f}|' if len(noc_list) > 2 else f'{"?":^9}|'
|
173 |
+
table_row += f'{over_max_list[1]:^9}|' if len(noc_list) > 1 else f'{"?":^9}|'
|
174 |
+
table_row += f'{over_max_list[2]:^9}|' if len(noc_list) > 2 else f'{"?":^9}|'
|
175 |
+
table_row += f'{mean_spc:^7.3f}|{eval_time:^9}|'
|
176 |
+
|
177 |
+
return header, table_row
|
inference/interact/fbrs/model/__init__.py
ADDED
File without changes
|
inference/interact/fbrs/model/initializer.py
ADDED
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
|
6 |
+
class Initializer(object):
|
7 |
+
def __init__(self, local_init=True, gamma=None):
|
8 |
+
self.local_init = local_init
|
9 |
+
self.gamma = gamma
|
10 |
+
|
11 |
+
def __call__(self, m):
|
12 |
+
if getattr(m, '__initialized', False):
|
13 |
+
return
|
14 |
+
|
15 |
+
if isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d,
|
16 |
+
nn.InstanceNorm1d, nn.InstanceNorm2d, nn.InstanceNorm3d,
|
17 |
+
nn.GroupNorm, nn.SyncBatchNorm)) or 'BatchNorm' in m.__class__.__name__:
|
18 |
+
if m.weight is not None:
|
19 |
+
self._init_gamma(m.weight.data)
|
20 |
+
if m.bias is not None:
|
21 |
+
self._init_beta(m.bias.data)
|
22 |
+
else:
|
23 |
+
if getattr(m, 'weight', None) is not None:
|
24 |
+
self._init_weight(m.weight.data)
|
25 |
+
if getattr(m, 'bias', None) is not None:
|
26 |
+
self._init_bias(m.bias.data)
|
27 |
+
|
28 |
+
if self.local_init:
|
29 |
+
object.__setattr__(m, '__initialized', True)
|
30 |
+
|
31 |
+
def _init_weight(self, data):
|
32 |
+
nn.init.uniform_(data, -0.07, 0.07)
|
33 |
+
|
34 |
+
def _init_bias(self, data):
|
35 |
+
nn.init.constant_(data, 0)
|
36 |
+
|
37 |
+
def _init_gamma(self, data):
|
38 |
+
if self.gamma is None:
|
39 |
+
nn.init.constant_(data, 1.0)
|
40 |
+
else:
|
41 |
+
nn.init.normal_(data, 1.0, self.gamma)
|
42 |
+
|
43 |
+
def _init_beta(self, data):
|
44 |
+
nn.init.constant_(data, 0)
|
45 |
+
|
46 |
+
|
47 |
+
class Bilinear(Initializer):
|
48 |
+
def __init__(self, scale, groups, in_channels, **kwargs):
|
49 |
+
super().__init__(**kwargs)
|
50 |
+
self.scale = scale
|
51 |
+
self.groups = groups
|
52 |
+
self.in_channels = in_channels
|
53 |
+
|
54 |
+
def _init_weight(self, data):
|
55 |
+
"""Reset the weight and bias."""
|
56 |
+
bilinear_kernel = self.get_bilinear_kernel(self.scale)
|
57 |
+
weight = torch.zeros_like(data)
|
58 |
+
for i in range(self.in_channels):
|
59 |
+
if self.groups == 1:
|
60 |
+
j = i
|
61 |
+
else:
|
62 |
+
j = 0
|
63 |
+
weight[i, j] = bilinear_kernel
|
64 |
+
data[:] = weight
|
65 |
+
|
66 |
+
@staticmethod
|
67 |
+
def get_bilinear_kernel(scale):
|
68 |
+
"""Generate a bilinear upsampling kernel."""
|
69 |
+
kernel_size = 2 * scale - scale % 2
|
70 |
+
scale = (kernel_size + 1) // 2
|
71 |
+
center = scale - 0.5 * (1 + kernel_size % 2)
|
72 |
+
|
73 |
+
og = np.ogrid[:kernel_size, :kernel_size]
|
74 |
+
kernel = (1 - np.abs(og[0] - center) / scale) * (1 - np.abs(og[1] - center) / scale)
|
75 |
+
|
76 |
+
return torch.tensor(kernel, dtype=torch.float32)
|
77 |
+
|
78 |
+
|
79 |
+
class XavierGluon(Initializer):
|
80 |
+
def __init__(self, rnd_type='uniform', factor_type='avg', magnitude=3, **kwargs):
|
81 |
+
super().__init__(**kwargs)
|
82 |
+
|
83 |
+
self.rnd_type = rnd_type
|
84 |
+
self.factor_type = factor_type
|
85 |
+
self.magnitude = float(magnitude)
|
86 |
+
|
87 |
+
def _init_weight(self, arr):
|
88 |
+
fan_in, fan_out = nn.init._calculate_fan_in_and_fan_out(arr)
|
89 |
+
|
90 |
+
if self.factor_type == 'avg':
|
91 |
+
factor = (fan_in + fan_out) / 2.0
|
92 |
+
elif self.factor_type == 'in':
|
93 |
+
factor = fan_in
|
94 |
+
elif self.factor_type == 'out':
|
95 |
+
factor = fan_out
|
96 |
+
else:
|
97 |
+
raise ValueError('Incorrect factor type')
|
98 |
+
scale = np.sqrt(self.magnitude / factor)
|
99 |
+
|
100 |
+
if self.rnd_type == 'uniform':
|
101 |
+
nn.init.uniform_(arr, -scale, scale)
|
102 |
+
elif self.rnd_type == 'gaussian':
|
103 |
+
nn.init.normal_(arr, 0, scale)
|
104 |
+
else:
|
105 |
+
raise ValueError('Unknown random type')
|
inference/interact/fbrs/model/is_deeplab_model.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
|
4 |
+
from .ops import DistMaps
|
5 |
+
from .modeling.deeplab_v3 import DeepLabV3Plus
|
6 |
+
from .modeling.basic_blocks import SepConvHead
|
7 |
+
|
8 |
+
|
9 |
+
def get_deeplab_model(backbone='resnet50', deeplab_ch=256, aspp_dropout=0.5,
|
10 |
+
norm_layer=nn.BatchNorm2d, backbone_norm_layer=None,
|
11 |
+
use_rgb_conv=True, cpu_dist_maps=False,
|
12 |
+
norm_radius=260):
|
13 |
+
model = DistMapsModel(
|
14 |
+
feature_extractor=DeepLabV3Plus(backbone=backbone,
|
15 |
+
ch=deeplab_ch,
|
16 |
+
project_dropout=aspp_dropout,
|
17 |
+
norm_layer=norm_layer,
|
18 |
+
backbone_norm_layer=backbone_norm_layer),
|
19 |
+
head=SepConvHead(1, in_channels=deeplab_ch, mid_channels=deeplab_ch // 2,
|
20 |
+
num_layers=2, norm_layer=norm_layer),
|
21 |
+
use_rgb_conv=use_rgb_conv,
|
22 |
+
norm_layer=norm_layer,
|
23 |
+
norm_radius=norm_radius,
|
24 |
+
cpu_dist_maps=cpu_dist_maps
|
25 |
+
)
|
26 |
+
|
27 |
+
return model
|
28 |
+
|
29 |
+
|
30 |
+
class DistMapsModel(nn.Module):
|
31 |
+
def __init__(self, feature_extractor, head, norm_layer=nn.BatchNorm2d, use_rgb_conv=True,
|
32 |
+
cpu_dist_maps=False, norm_radius=260):
|
33 |
+
super(DistMapsModel, self).__init__()
|
34 |
+
|
35 |
+
if use_rgb_conv:
|
36 |
+
self.rgb_conv = nn.Sequential(
|
37 |
+
nn.Conv2d(in_channels=5, out_channels=8, kernel_size=1),
|
38 |
+
nn.LeakyReLU(negative_slope=0.2),
|
39 |
+
norm_layer(8),
|
40 |
+
nn.Conv2d(in_channels=8, out_channels=3, kernel_size=1),
|
41 |
+
)
|
42 |
+
else:
|
43 |
+
self.rgb_conv = None
|
44 |
+
|
45 |
+
self.dist_maps = DistMaps(norm_radius=norm_radius, spatial_scale=1.0,
|
46 |
+
cpu_mode=cpu_dist_maps)
|
47 |
+
self.feature_extractor = feature_extractor
|
48 |
+
self.head = head
|
49 |
+
|
50 |
+
def forward(self, image, points):
|
51 |
+
coord_features = self.dist_maps(image, points)
|
52 |
+
|
53 |
+
if self.rgb_conv is not None:
|
54 |
+
x = self.rgb_conv(torch.cat((image, coord_features), dim=1))
|
55 |
+
else:
|
56 |
+
c1, c2 = torch.chunk(coord_features, 2, dim=1)
|
57 |
+
c3 = torch.ones_like(c1)
|
58 |
+
coord_features = torch.cat((c1, c2, c3), dim=1)
|
59 |
+
x = 0.8 * image * coord_features + 0.2 * image
|
60 |
+
|
61 |
+
backbone_features = self.feature_extractor(x)
|
62 |
+
instance_out = self.head(backbone_features[0])
|
63 |
+
instance_out = nn.functional.interpolate(instance_out, size=image.size()[2:],
|
64 |
+
mode='bilinear', align_corners=True)
|
65 |
+
|
66 |
+
return {'instances': instance_out}
|
67 |
+
|
68 |
+
def load_weights(self, path_to_weights):
|
69 |
+
current_state_dict = self.state_dict()
|
70 |
+
new_state_dict = torch.load(path_to_weights, map_location='cpu')
|
71 |
+
current_state_dict.update(new_state_dict)
|
72 |
+
self.load_state_dict(current_state_dict)
|
73 |
+
|
74 |
+
def get_trainable_params(self):
|
75 |
+
backbone_params = nn.ParameterList()
|
76 |
+
other_params = nn.ParameterList()
|
77 |
+
|
78 |
+
for name, param in self.named_parameters():
|
79 |
+
if param.requires_grad:
|
80 |
+
if 'backbone' in name:
|
81 |
+
backbone_params.append(param)
|
82 |
+
else:
|
83 |
+
other_params.append(param)
|
84 |
+
return backbone_params, other_params
|
85 |
+
|
86 |
+
|
inference/interact/fbrs/model/is_hrnet_model.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
|
4 |
+
from .ops import DistMaps
|
5 |
+
from .modeling.hrnet_ocr import HighResolutionNet
|
6 |
+
|
7 |
+
|
8 |
+
def get_hrnet_model(width=48, ocr_width=256, small=False, norm_radius=260,
|
9 |
+
use_rgb_conv=True, with_aux_output=False, cpu_dist_maps=False,
|
10 |
+
norm_layer=nn.BatchNorm2d):
|
11 |
+
model = DistMapsHRNetModel(
|
12 |
+
feature_extractor=HighResolutionNet(width=width, ocr_width=ocr_width, small=small,
|
13 |
+
num_classes=1, norm_layer=norm_layer),
|
14 |
+
use_rgb_conv=use_rgb_conv,
|
15 |
+
with_aux_output=with_aux_output,
|
16 |
+
norm_layer=norm_layer,
|
17 |
+
norm_radius=norm_radius,
|
18 |
+
cpu_dist_maps=cpu_dist_maps
|
19 |
+
)
|
20 |
+
|
21 |
+
return model
|
22 |
+
|
23 |
+
|
24 |
+
class DistMapsHRNetModel(nn.Module):
|
25 |
+
def __init__(self, feature_extractor, use_rgb_conv=True, with_aux_output=False,
|
26 |
+
norm_layer=nn.BatchNorm2d, norm_radius=260, cpu_dist_maps=False):
|
27 |
+
super(DistMapsHRNetModel, self).__init__()
|
28 |
+
self.with_aux_output = with_aux_output
|
29 |
+
|
30 |
+
if use_rgb_conv:
|
31 |
+
self.rgb_conv = nn.Sequential(
|
32 |
+
nn.Conv2d(in_channels=5, out_channels=8, kernel_size=1),
|
33 |
+
nn.LeakyReLU(negative_slope=0.2),
|
34 |
+
norm_layer(8),
|
35 |
+
nn.Conv2d(in_channels=8, out_channels=3, kernel_size=1),
|
36 |
+
)
|
37 |
+
else:
|
38 |
+
self.rgb_conv = None
|
39 |
+
|
40 |
+
self.dist_maps = DistMaps(norm_radius=norm_radius, spatial_scale=1.0, cpu_mode=cpu_dist_maps)
|
41 |
+
self.feature_extractor = feature_extractor
|
42 |
+
|
43 |
+
def forward(self, image, points):
|
44 |
+
coord_features = self.dist_maps(image, points)
|
45 |
+
|
46 |
+
if self.rgb_conv is not None:
|
47 |
+
x = self.rgb_conv(torch.cat((image, coord_features), dim=1))
|
48 |
+
else:
|
49 |
+
c1, c2 = torch.chunk(coord_features, 2, dim=1)
|
50 |
+
c3 = torch.ones_like(c1)
|
51 |
+
coord_features = torch.cat((c1, c2, c3), dim=1)
|
52 |
+
x = 0.8 * image * coord_features + 0.2 * image
|
53 |
+
|
54 |
+
feature_extractor_out = self.feature_extractor(x)
|
55 |
+
instance_out = feature_extractor_out[0]
|
56 |
+
instance_out = nn.functional.interpolate(instance_out, size=image.size()[2:],
|
57 |
+
mode='bilinear', align_corners=True)
|
58 |
+
outputs = {'instances': instance_out}
|
59 |
+
if self.with_aux_output:
|
60 |
+
instance_aux_out = feature_extractor_out[1]
|
61 |
+
instance_aux_out = nn.functional.interpolate(instance_aux_out, size=image.size()[2:],
|
62 |
+
mode='bilinear', align_corners=True)
|
63 |
+
outputs['instances_aux'] = instance_aux_out
|
64 |
+
|
65 |
+
return outputs
|
66 |
+
|
67 |
+
def load_weights(self, path_to_weights):
|
68 |
+
current_state_dict = self.state_dict()
|
69 |
+
new_state_dict = torch.load(path_to_weights)
|
70 |
+
current_state_dict.update(new_state_dict)
|
71 |
+
self.load_state_dict(current_state_dict)
|
72 |
+
|
73 |
+
def get_trainable_params(self):
|
74 |
+
backbone_params = nn.ParameterList()
|
75 |
+
other_params = nn.ParameterList()
|
76 |
+
other_params_keys = []
|
77 |
+
nonbackbone_keywords = ['rgb_conv', 'aux_head', 'cls_head', 'conv3x3_ocr', 'ocr_distri_head']
|
78 |
+
|
79 |
+
for name, param in self.named_parameters():
|
80 |
+
if param.requires_grad:
|
81 |
+
if any(x in name for x in nonbackbone_keywords):
|
82 |
+
other_params.append(param)
|
83 |
+
other_params_keys.append(name)
|
84 |
+
else:
|
85 |
+
backbone_params.append(param)
|
86 |
+
print('Nonbackbone params:', sorted(other_params_keys))
|
87 |
+
return backbone_params, other_params
|
inference/interact/fbrs/model/losses.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import torch.nn.functional as F
|
5 |
+
|
6 |
+
from ..utils import misc
|
7 |
+
|
8 |
+
|
9 |
+
class NormalizedFocalLossSigmoid(nn.Module):
|
10 |
+
def __init__(self, axis=-1, alpha=0.25, gamma=2,
|
11 |
+
from_logits=False, batch_axis=0,
|
12 |
+
weight=None, size_average=True, detach_delimeter=True,
|
13 |
+
eps=1e-12, scale=1.0,
|
14 |
+
ignore_label=-1):
|
15 |
+
super(NormalizedFocalLossSigmoid, self).__init__()
|
16 |
+
self._axis = axis
|
17 |
+
self._alpha = alpha
|
18 |
+
self._gamma = gamma
|
19 |
+
self._ignore_label = ignore_label
|
20 |
+
self._weight = weight if weight is not None else 1.0
|
21 |
+
self._batch_axis = batch_axis
|
22 |
+
|
23 |
+
self._scale = scale
|
24 |
+
self._from_logits = from_logits
|
25 |
+
self._eps = eps
|
26 |
+
self._size_average = size_average
|
27 |
+
self._detach_delimeter = detach_delimeter
|
28 |
+
self._k_sum = 0
|
29 |
+
|
30 |
+
def forward(self, pred, label, sample_weight=None):
|
31 |
+
one_hot = label > 0
|
32 |
+
sample_weight = label != self._ignore_label
|
33 |
+
|
34 |
+
if not self._from_logits:
|
35 |
+
pred = torch.sigmoid(pred)
|
36 |
+
|
37 |
+
alpha = torch.where(one_hot, self._alpha * sample_weight, (1 - self._alpha) * sample_weight)
|
38 |
+
pt = torch.where(one_hot, pred, 1 - pred)
|
39 |
+
pt = torch.where(sample_weight, pt, torch.ones_like(pt))
|
40 |
+
|
41 |
+
beta = (1 - pt) ** self._gamma
|
42 |
+
|
43 |
+
sw_sum = torch.sum(sample_weight, dim=(-2, -1), keepdim=True)
|
44 |
+
beta_sum = torch.sum(beta, dim=(-2, -1), keepdim=True)
|
45 |
+
mult = sw_sum / (beta_sum + self._eps)
|
46 |
+
if self._detach_delimeter:
|
47 |
+
mult = mult.detach()
|
48 |
+
beta = beta * mult
|
49 |
+
|
50 |
+
ignore_area = torch.sum(label == self._ignore_label, dim=tuple(range(1, label.dim()))).cpu().numpy()
|
51 |
+
sample_mult = torch.mean(mult, dim=tuple(range(1, mult.dim()))).cpu().numpy()
|
52 |
+
if np.any(ignore_area == 0):
|
53 |
+
self._k_sum = 0.9 * self._k_sum + 0.1 * sample_mult[ignore_area == 0].mean()
|
54 |
+
|
55 |
+
loss = -alpha * beta * torch.log(torch.min(pt + self._eps, torch.ones(1, dtype=torch.float).to(pt.device)))
|
56 |
+
loss = self._weight * (loss * sample_weight)
|
57 |
+
|
58 |
+
if self._size_average:
|
59 |
+
bsum = torch.sum(sample_weight, dim=misc.get_dims_with_exclusion(sample_weight.dim(), self._batch_axis))
|
60 |
+
loss = torch.sum(loss, dim=misc.get_dims_with_exclusion(loss.dim(), self._batch_axis)) / (bsum + self._eps)
|
61 |
+
else:
|
62 |
+
loss = torch.sum(loss, dim=misc.get_dims_with_exclusion(loss.dim(), self._batch_axis))
|
63 |
+
|
64 |
+
return self._scale * loss
|
65 |
+
|
66 |
+
def log_states(self, sw, name, global_step):
|
67 |
+
sw.add_scalar(tag=name + '_k', value=self._k_sum, global_step=global_step)
|
68 |
+
|
69 |
+
|
70 |
+
class FocalLoss(nn.Module):
|
71 |
+
def __init__(self, axis=-1, alpha=0.25, gamma=2,
|
72 |
+
from_logits=False, batch_axis=0,
|
73 |
+
weight=None, num_class=None,
|
74 |
+
eps=1e-9, size_average=True, scale=1.0):
|
75 |
+
super(FocalLoss, self).__init__()
|
76 |
+
self._axis = axis
|
77 |
+
self._alpha = alpha
|
78 |
+
self._gamma = gamma
|
79 |
+
self._weight = weight if weight is not None else 1.0
|
80 |
+
self._batch_axis = batch_axis
|
81 |
+
|
82 |
+
self._scale = scale
|
83 |
+
self._num_class = num_class
|
84 |
+
self._from_logits = from_logits
|
85 |
+
self._eps = eps
|
86 |
+
self._size_average = size_average
|
87 |
+
|
88 |
+
def forward(self, pred, label, sample_weight=None):
|
89 |
+
if not self._from_logits:
|
90 |
+
pred = F.sigmoid(pred)
|
91 |
+
|
92 |
+
one_hot = label > 0
|
93 |
+
pt = torch.where(one_hot, pred, 1 - pred)
|
94 |
+
|
95 |
+
t = label != -1
|
96 |
+
alpha = torch.where(one_hot, self._alpha * t, (1 - self._alpha) * t)
|
97 |
+
beta = (1 - pt) ** self._gamma
|
98 |
+
|
99 |
+
loss = -alpha * beta * torch.log(torch.min(pt + self._eps, torch.ones(1, dtype=torch.float).to(pt.device)))
|
100 |
+
sample_weight = label != -1
|
101 |
+
|
102 |
+
loss = self._weight * (loss * sample_weight)
|
103 |
+
|
104 |
+
if self._size_average:
|
105 |
+
tsum = torch.sum(label == 1, dim=misc.get_dims_with_exclusion(label.dim(), self._batch_axis))
|
106 |
+
loss = torch.sum(loss, dim=misc.get_dims_with_exclusion(loss.dim(), self._batch_axis)) / (tsum + self._eps)
|
107 |
+
else:
|
108 |
+
loss = torch.sum(loss, dim=misc.get_dims_with_exclusion(loss.dim(), self._batch_axis))
|
109 |
+
|
110 |
+
return self._scale * loss
|
111 |
+
|
112 |
+
|
113 |
+
class SigmoidBinaryCrossEntropyLoss(nn.Module):
|
114 |
+
def __init__(self, from_sigmoid=False, weight=None, batch_axis=0, ignore_label=-1):
|
115 |
+
super(SigmoidBinaryCrossEntropyLoss, self).__init__()
|
116 |
+
self._from_sigmoid = from_sigmoid
|
117 |
+
self._ignore_label = ignore_label
|
118 |
+
self._weight = weight if weight is not None else 1.0
|
119 |
+
self._batch_axis = batch_axis
|
120 |
+
|
121 |
+
def forward(self, pred, label):
|
122 |
+
label = label.view(pred.size())
|
123 |
+
sample_weight = label != self._ignore_label
|
124 |
+
label = torch.where(sample_weight, label, torch.zeros_like(label))
|
125 |
+
|
126 |
+
if not self._from_sigmoid:
|
127 |
+
loss = torch.relu(pred) - pred * label + F.softplus(-torch.abs(pred))
|
128 |
+
else:
|
129 |
+
eps = 1e-12
|
130 |
+
loss = -(torch.log(pred + eps) * label
|
131 |
+
+ torch.log(1. - pred + eps) * (1. - label))
|
132 |
+
|
133 |
+
loss = self._weight * (loss * sample_weight)
|
134 |
+
return torch.mean(loss, dim=misc.get_dims_with_exclusion(loss.dim(), self._batch_axis))
|
inference/interact/fbrs/model/metrics.py
ADDED
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
from ..utils import misc
|
5 |
+
|
6 |
+
|
7 |
+
class TrainMetric(object):
|
8 |
+
def __init__(self, pred_outputs, gt_outputs):
|
9 |
+
self.pred_outputs = pred_outputs
|
10 |
+
self.gt_outputs = gt_outputs
|
11 |
+
|
12 |
+
def update(self, *args, **kwargs):
|
13 |
+
raise NotImplementedError
|
14 |
+
|
15 |
+
def get_epoch_value(self):
|
16 |
+
raise NotImplementedError
|
17 |
+
|
18 |
+
def reset_epoch_stats(self):
|
19 |
+
raise NotImplementedError
|
20 |
+
|
21 |
+
def log_states(self, sw, tag_prefix, global_step):
|
22 |
+
pass
|
23 |
+
|
24 |
+
@property
|
25 |
+
def name(self):
|
26 |
+
return type(self).__name__
|
27 |
+
|
28 |
+
|
29 |
+
class AdaptiveIoU(TrainMetric):
|
30 |
+
def __init__(self, init_thresh=0.4, thresh_step=0.025, thresh_beta=0.99, iou_beta=0.9,
|
31 |
+
ignore_label=-1, from_logits=True,
|
32 |
+
pred_output='instances', gt_output='instances'):
|
33 |
+
super().__init__(pred_outputs=(pred_output,), gt_outputs=(gt_output,))
|
34 |
+
self._ignore_label = ignore_label
|
35 |
+
self._from_logits = from_logits
|
36 |
+
self._iou_thresh = init_thresh
|
37 |
+
self._thresh_step = thresh_step
|
38 |
+
self._thresh_beta = thresh_beta
|
39 |
+
self._iou_beta = iou_beta
|
40 |
+
self._ema_iou = 0.0
|
41 |
+
self._epoch_iou_sum = 0.0
|
42 |
+
self._epoch_batch_count = 0
|
43 |
+
|
44 |
+
def update(self, pred, gt):
|
45 |
+
gt_mask = gt > 0
|
46 |
+
if self._from_logits:
|
47 |
+
pred = torch.sigmoid(pred)
|
48 |
+
|
49 |
+
gt_mask_area = torch.sum(gt_mask, dim=(1, 2)).detach().cpu().numpy()
|
50 |
+
if np.all(gt_mask_area == 0):
|
51 |
+
return
|
52 |
+
|
53 |
+
ignore_mask = gt == self._ignore_label
|
54 |
+
max_iou = _compute_iou(pred > self._iou_thresh, gt_mask, ignore_mask).mean()
|
55 |
+
best_thresh = self._iou_thresh
|
56 |
+
for t in [best_thresh - self._thresh_step, best_thresh + self._thresh_step]:
|
57 |
+
temp_iou = _compute_iou(pred > t, gt_mask, ignore_mask).mean()
|
58 |
+
if temp_iou > max_iou:
|
59 |
+
max_iou = temp_iou
|
60 |
+
best_thresh = t
|
61 |
+
|
62 |
+
self._iou_thresh = self._thresh_beta * self._iou_thresh + (1 - self._thresh_beta) * best_thresh
|
63 |
+
self._ema_iou = self._iou_beta * self._ema_iou + (1 - self._iou_beta) * max_iou
|
64 |
+
self._epoch_iou_sum += max_iou
|
65 |
+
self._epoch_batch_count += 1
|
66 |
+
|
67 |
+
def get_epoch_value(self):
|
68 |
+
if self._epoch_batch_count > 0:
|
69 |
+
return self._epoch_iou_sum / self._epoch_batch_count
|
70 |
+
else:
|
71 |
+
return 0.0
|
72 |
+
|
73 |
+
def reset_epoch_stats(self):
|
74 |
+
self._epoch_iou_sum = 0.0
|
75 |
+
self._epoch_batch_count = 0
|
76 |
+
|
77 |
+
def log_states(self, sw, tag_prefix, global_step):
|
78 |
+
sw.add_scalar(tag=tag_prefix + '_ema_iou', value=self._ema_iou, global_step=global_step)
|
79 |
+
sw.add_scalar(tag=tag_prefix + '_iou_thresh', value=self._iou_thresh, global_step=global_step)
|
80 |
+
|
81 |
+
@property
|
82 |
+
def iou_thresh(self):
|
83 |
+
return self._iou_thresh
|
84 |
+
|
85 |
+
|
86 |
+
def _compute_iou(pred_mask, gt_mask, ignore_mask=None, keep_ignore=False):
|
87 |
+
if ignore_mask is not None:
|
88 |
+
pred_mask = torch.where(ignore_mask, torch.zeros_like(pred_mask), pred_mask)
|
89 |
+
|
90 |
+
reduction_dims = misc.get_dims_with_exclusion(gt_mask.dim(), 0)
|
91 |
+
union = torch.mean((pred_mask | gt_mask).float(), dim=reduction_dims).detach().cpu().numpy()
|
92 |
+
intersection = torch.mean((pred_mask & gt_mask).float(), dim=reduction_dims).detach().cpu().numpy()
|
93 |
+
nonzero = union > 0
|
94 |
+
|
95 |
+
iou = intersection[nonzero] / union[nonzero]
|
96 |
+
if not keep_ignore:
|
97 |
+
return iou
|
98 |
+
else:
|
99 |
+
result = np.full_like(intersection, -1)
|
100 |
+
result[nonzero] = iou
|
101 |
+
return result
|
inference/interact/fbrs/model/modeling/__init__.py
ADDED
File without changes
|
inference/interact/fbrs/model/modeling/basic_blocks.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
|
3 |
+
from ...model import ops
|
4 |
+
|
5 |
+
|
6 |
+
class ConvHead(nn.Module):
|
7 |
+
def __init__(self, out_channels, in_channels=32, num_layers=1,
|
8 |
+
kernel_size=3, padding=1,
|
9 |
+
norm_layer=nn.BatchNorm2d):
|
10 |
+
super(ConvHead, self).__init__()
|
11 |
+
convhead = []
|
12 |
+
|
13 |
+
for i in range(num_layers):
|
14 |
+
convhead.extend([
|
15 |
+
nn.Conv2d(in_channels, in_channels, kernel_size, padding=padding),
|
16 |
+
nn.ReLU(),
|
17 |
+
norm_layer(in_channels) if norm_layer is not None else nn.Identity()
|
18 |
+
])
|
19 |
+
convhead.append(nn.Conv2d(in_channels, out_channels, 1, padding=0))
|
20 |
+
|
21 |
+
self.convhead = nn.Sequential(*convhead)
|
22 |
+
|
23 |
+
def forward(self, *inputs):
|
24 |
+
return self.convhead(inputs[0])
|
25 |
+
|
26 |
+
|
27 |
+
class SepConvHead(nn.Module):
|
28 |
+
def __init__(self, num_outputs, in_channels, mid_channels, num_layers=1,
|
29 |
+
kernel_size=3, padding=1, dropout_ratio=0.0, dropout_indx=0,
|
30 |
+
norm_layer=nn.BatchNorm2d):
|
31 |
+
super(SepConvHead, self).__init__()
|
32 |
+
|
33 |
+
sepconvhead = []
|
34 |
+
|
35 |
+
for i in range(num_layers):
|
36 |
+
sepconvhead.append(
|
37 |
+
SeparableConv2d(in_channels=in_channels if i == 0 else mid_channels,
|
38 |
+
out_channels=mid_channels,
|
39 |
+
dw_kernel=kernel_size, dw_padding=padding,
|
40 |
+
norm_layer=norm_layer, activation='relu')
|
41 |
+
)
|
42 |
+
if dropout_ratio > 0 and dropout_indx == i:
|
43 |
+
sepconvhead.append(nn.Dropout(dropout_ratio))
|
44 |
+
|
45 |
+
sepconvhead.append(
|
46 |
+
nn.Conv2d(in_channels=mid_channels, out_channels=num_outputs, kernel_size=1, padding=0)
|
47 |
+
)
|
48 |
+
|
49 |
+
self.layers = nn.Sequential(*sepconvhead)
|
50 |
+
|
51 |
+
def forward(self, *inputs):
|
52 |
+
x = inputs[0]
|
53 |
+
|
54 |
+
return self.layers(x)
|
55 |
+
|
56 |
+
|
57 |
+
class SeparableConv2d(nn.Module):
|
58 |
+
def __init__(self, in_channels, out_channels, dw_kernel, dw_padding, dw_stride=1,
|
59 |
+
activation=None, use_bias=False, norm_layer=None):
|
60 |
+
super(SeparableConv2d, self).__init__()
|
61 |
+
_activation = ops.select_activation_function(activation)
|
62 |
+
self.body = nn.Sequential(
|
63 |
+
nn.Conv2d(in_channels, in_channels, kernel_size=dw_kernel, stride=dw_stride,
|
64 |
+
padding=dw_padding, bias=use_bias, groups=in_channels),
|
65 |
+
nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, bias=use_bias),
|
66 |
+
norm_layer(out_channels) if norm_layer is not None else nn.Identity(),
|
67 |
+
_activation()
|
68 |
+
)
|
69 |
+
|
70 |
+
def forward(self, x):
|
71 |
+
return self.body(x)
|
inference/interact/fbrs/model/modeling/deeplab_v3.py
ADDED
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from contextlib import ExitStack
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
import torch.nn.functional as F
|
6 |
+
|
7 |
+
from .basic_blocks import SeparableConv2d
|
8 |
+
from .resnet import ResNetBackbone
|
9 |
+
from ...model import ops
|
10 |
+
|
11 |
+
|
12 |
+
class DeepLabV3Plus(nn.Module):
|
13 |
+
def __init__(self, backbone='resnet50', norm_layer=nn.BatchNorm2d,
|
14 |
+
backbone_norm_layer=None,
|
15 |
+
ch=256,
|
16 |
+
project_dropout=0.5,
|
17 |
+
inference_mode=False,
|
18 |
+
**kwargs):
|
19 |
+
super(DeepLabV3Plus, self).__init__()
|
20 |
+
if backbone_norm_layer is None:
|
21 |
+
backbone_norm_layer = norm_layer
|
22 |
+
|
23 |
+
self.backbone_name = backbone
|
24 |
+
self.norm_layer = norm_layer
|
25 |
+
self.backbone_norm_layer = backbone_norm_layer
|
26 |
+
self.inference_mode = False
|
27 |
+
self.ch = ch
|
28 |
+
self.aspp_in_channels = 2048
|
29 |
+
self.skip_project_in_channels = 256 # layer 1 out_channels
|
30 |
+
|
31 |
+
self._kwargs = kwargs
|
32 |
+
if backbone == 'resnet34':
|
33 |
+
self.aspp_in_channels = 512
|
34 |
+
self.skip_project_in_channels = 64
|
35 |
+
|
36 |
+
self.backbone = ResNetBackbone(backbone=self.backbone_name, pretrained_base=False,
|
37 |
+
norm_layer=self.backbone_norm_layer, **kwargs)
|
38 |
+
|
39 |
+
self.head = _DeepLabHead(in_channels=ch + 32, mid_channels=ch, out_channels=ch,
|
40 |
+
norm_layer=self.norm_layer)
|
41 |
+
self.skip_project = _SkipProject(self.skip_project_in_channels, 32, norm_layer=self.norm_layer)
|
42 |
+
self.aspp = _ASPP(in_channels=self.aspp_in_channels,
|
43 |
+
atrous_rates=[12, 24, 36],
|
44 |
+
out_channels=ch,
|
45 |
+
project_dropout=project_dropout,
|
46 |
+
norm_layer=self.norm_layer)
|
47 |
+
|
48 |
+
if inference_mode:
|
49 |
+
self.set_prediction_mode()
|
50 |
+
|
51 |
+
def load_pretrained_weights(self):
|
52 |
+
pretrained = ResNetBackbone(backbone=self.backbone_name, pretrained_base=True,
|
53 |
+
norm_layer=self.backbone_norm_layer, **self._kwargs)
|
54 |
+
backbone_state_dict = self.backbone.state_dict()
|
55 |
+
pretrained_state_dict = pretrained.state_dict()
|
56 |
+
|
57 |
+
backbone_state_dict.update(pretrained_state_dict)
|
58 |
+
self.backbone.load_state_dict(backbone_state_dict)
|
59 |
+
|
60 |
+
if self.inference_mode:
|
61 |
+
for param in self.backbone.parameters():
|
62 |
+
param.requires_grad = False
|
63 |
+
|
64 |
+
def set_prediction_mode(self):
|
65 |
+
self.inference_mode = True
|
66 |
+
self.eval()
|
67 |
+
|
68 |
+
def forward(self, x):
|
69 |
+
with ExitStack() as stack:
|
70 |
+
if self.inference_mode:
|
71 |
+
stack.enter_context(torch.no_grad())
|
72 |
+
|
73 |
+
c1, _, c3, c4 = self.backbone(x)
|
74 |
+
c1 = self.skip_project(c1)
|
75 |
+
|
76 |
+
x = self.aspp(c4)
|
77 |
+
x = F.interpolate(x, c1.size()[2:], mode='bilinear', align_corners=True)
|
78 |
+
x = torch.cat((x, c1), dim=1)
|
79 |
+
x = self.head(x)
|
80 |
+
|
81 |
+
return x,
|
82 |
+
|
83 |
+
|
84 |
+
class _SkipProject(nn.Module):
|
85 |
+
def __init__(self, in_channels, out_channels, norm_layer=nn.BatchNorm2d):
|
86 |
+
super(_SkipProject, self).__init__()
|
87 |
+
_activation = ops.select_activation_function("relu")
|
88 |
+
|
89 |
+
self.skip_project = nn.Sequential(
|
90 |
+
nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),
|
91 |
+
norm_layer(out_channels),
|
92 |
+
_activation()
|
93 |
+
)
|
94 |
+
|
95 |
+
def forward(self, x):
|
96 |
+
return self.skip_project(x)
|
97 |
+
|
98 |
+
|
99 |
+
class _DeepLabHead(nn.Module):
|
100 |
+
def __init__(self, out_channels, in_channels, mid_channels=256, norm_layer=nn.BatchNorm2d):
|
101 |
+
super(_DeepLabHead, self).__init__()
|
102 |
+
|
103 |
+
self.block = nn.Sequential(
|
104 |
+
SeparableConv2d(in_channels=in_channels, out_channels=mid_channels, dw_kernel=3,
|
105 |
+
dw_padding=1, activation='relu', norm_layer=norm_layer),
|
106 |
+
SeparableConv2d(in_channels=mid_channels, out_channels=mid_channels, dw_kernel=3,
|
107 |
+
dw_padding=1, activation='relu', norm_layer=norm_layer),
|
108 |
+
nn.Conv2d(in_channels=mid_channels, out_channels=out_channels, kernel_size=1)
|
109 |
+
)
|
110 |
+
|
111 |
+
def forward(self, x):
|
112 |
+
return self.block(x)
|
113 |
+
|
114 |
+
|
115 |
+
class _ASPP(nn.Module):
|
116 |
+
def __init__(self, in_channels, atrous_rates, out_channels=256,
|
117 |
+
project_dropout=0.5, norm_layer=nn.BatchNorm2d):
|
118 |
+
super(_ASPP, self).__init__()
|
119 |
+
|
120 |
+
b0 = nn.Sequential(
|
121 |
+
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, bias=False),
|
122 |
+
norm_layer(out_channels),
|
123 |
+
nn.ReLU()
|
124 |
+
)
|
125 |
+
|
126 |
+
rate1, rate2, rate3 = tuple(atrous_rates)
|
127 |
+
b1 = _ASPPConv(in_channels, out_channels, rate1, norm_layer)
|
128 |
+
b2 = _ASPPConv(in_channels, out_channels, rate2, norm_layer)
|
129 |
+
b3 = _ASPPConv(in_channels, out_channels, rate3, norm_layer)
|
130 |
+
b4 = _AsppPooling(in_channels, out_channels, norm_layer=norm_layer)
|
131 |
+
|
132 |
+
self.concurent = nn.ModuleList([b0, b1, b2, b3, b4])
|
133 |
+
|
134 |
+
project = [
|
135 |
+
nn.Conv2d(in_channels=5*out_channels, out_channels=out_channels,
|
136 |
+
kernel_size=1, bias=False),
|
137 |
+
norm_layer(out_channels),
|
138 |
+
nn.ReLU()
|
139 |
+
]
|
140 |
+
if project_dropout > 0:
|
141 |
+
project.append(nn.Dropout(project_dropout))
|
142 |
+
self.project = nn.Sequential(*project)
|
143 |
+
|
144 |
+
def forward(self, x):
|
145 |
+
x = torch.cat([block(x) for block in self.concurent], dim=1)
|
146 |
+
|
147 |
+
return self.project(x)
|
148 |
+
|
149 |
+
|
150 |
+
class _AsppPooling(nn.Module):
|
151 |
+
def __init__(self, in_channels, out_channels, norm_layer):
|
152 |
+
super(_AsppPooling, self).__init__()
|
153 |
+
|
154 |
+
self.gap = nn.Sequential(
|
155 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
156 |
+
nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
|
157 |
+
kernel_size=1, bias=False),
|
158 |
+
norm_layer(out_channels),
|
159 |
+
nn.ReLU()
|
160 |
+
)
|
161 |
+
|
162 |
+
def forward(self, x):
|
163 |
+
pool = self.gap(x)
|
164 |
+
return F.interpolate(pool, x.size()[2:], mode='bilinear', align_corners=True)
|
165 |
+
|
166 |
+
|
167 |
+
def _ASPPConv(in_channels, out_channels, atrous_rate, norm_layer):
|
168 |
+
block = nn.Sequential(
|
169 |
+
nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
|
170 |
+
kernel_size=3, padding=atrous_rate,
|
171 |
+
dilation=atrous_rate, bias=False),
|
172 |
+
norm_layer(out_channels),
|
173 |
+
nn.ReLU()
|
174 |
+
)
|
175 |
+
|
176 |
+
return block
|
inference/interact/fbrs/model/modeling/hrnet_ocr.py
ADDED
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
import torch._utils
|
6 |
+
import torch.nn.functional as F
|
7 |
+
from .ocr import SpatialOCR_Module, SpatialGather_Module
|
8 |
+
from .resnetv1b import BasicBlockV1b, BottleneckV1b
|
9 |
+
|
10 |
+
relu_inplace = True
|
11 |
+
|
12 |
+
|
13 |
+
class HighResolutionModule(nn.Module):
|
14 |
+
def __init__(self, num_branches, blocks, num_blocks, num_inchannels,
|
15 |
+
num_channels, fuse_method,multi_scale_output=True,
|
16 |
+
norm_layer=nn.BatchNorm2d, align_corners=True):
|
17 |
+
super(HighResolutionModule, self).__init__()
|
18 |
+
self._check_branches(num_branches, num_blocks, num_inchannels, num_channels)
|
19 |
+
|
20 |
+
self.num_inchannels = num_inchannels
|
21 |
+
self.fuse_method = fuse_method
|
22 |
+
self.num_branches = num_branches
|
23 |
+
self.norm_layer = norm_layer
|
24 |
+
self.align_corners = align_corners
|
25 |
+
|
26 |
+
self.multi_scale_output = multi_scale_output
|
27 |
+
|
28 |
+
self.branches = self._make_branches(
|
29 |
+
num_branches, blocks, num_blocks, num_channels)
|
30 |
+
self.fuse_layers = self._make_fuse_layers()
|
31 |
+
self.relu = nn.ReLU(inplace=relu_inplace)
|
32 |
+
|
33 |
+
def _check_branches(self, num_branches, num_blocks, num_inchannels, num_channels):
|
34 |
+
if num_branches != len(num_blocks):
|
35 |
+
error_msg = 'NUM_BRANCHES({}) <> NUM_BLOCKS({})'.format(
|
36 |
+
num_branches, len(num_blocks))
|
37 |
+
raise ValueError(error_msg)
|
38 |
+
|
39 |
+
if num_branches != len(num_channels):
|
40 |
+
error_msg = 'NUM_BRANCHES({}) <> NUM_CHANNELS({})'.format(
|
41 |
+
num_branches, len(num_channels))
|
42 |
+
raise ValueError(error_msg)
|
43 |
+
|
44 |
+
if num_branches != len(num_inchannels):
|
45 |
+
error_msg = 'NUM_BRANCHES({}) <> NUM_INCHANNELS({})'.format(
|
46 |
+
num_branches, len(num_inchannels))
|
47 |
+
raise ValueError(error_msg)
|
48 |
+
|
49 |
+
def _make_one_branch(self, branch_index, block, num_blocks, num_channels,
|
50 |
+
stride=1):
|
51 |
+
downsample = None
|
52 |
+
if stride != 1 or \
|
53 |
+
self.num_inchannels[branch_index] != num_channels[branch_index] * block.expansion:
|
54 |
+
downsample = nn.Sequential(
|
55 |
+
nn.Conv2d(self.num_inchannels[branch_index],
|
56 |
+
num_channels[branch_index] * block.expansion,
|
57 |
+
kernel_size=1, stride=stride, bias=False),
|
58 |
+
self.norm_layer(num_channels[branch_index] * block.expansion),
|
59 |
+
)
|
60 |
+
|
61 |
+
layers = []
|
62 |
+
layers.append(block(self.num_inchannels[branch_index],
|
63 |
+
num_channels[branch_index], stride,
|
64 |
+
downsample=downsample, norm_layer=self.norm_layer))
|
65 |
+
self.num_inchannels[branch_index] = \
|
66 |
+
num_channels[branch_index] * block.expansion
|
67 |
+
for i in range(1, num_blocks[branch_index]):
|
68 |
+
layers.append(block(self.num_inchannels[branch_index],
|
69 |
+
num_channels[branch_index],
|
70 |
+
norm_layer=self.norm_layer))
|
71 |
+
|
72 |
+
return nn.Sequential(*layers)
|
73 |
+
|
74 |
+
def _make_branches(self, num_branches, block, num_blocks, num_channels):
|
75 |
+
branches = []
|
76 |
+
|
77 |
+
for i in range(num_branches):
|
78 |
+
branches.append(
|
79 |
+
self._make_one_branch(i, block, num_blocks, num_channels))
|
80 |
+
|
81 |
+
return nn.ModuleList(branches)
|
82 |
+
|
83 |
+
def _make_fuse_layers(self):
|
84 |
+
if self.num_branches == 1:
|
85 |
+
return None
|
86 |
+
|
87 |
+
num_branches = self.num_branches
|
88 |
+
num_inchannels = self.num_inchannels
|
89 |
+
fuse_layers = []
|
90 |
+
for i in range(num_branches if self.multi_scale_output else 1):
|
91 |
+
fuse_layer = []
|
92 |
+
for j in range(num_branches):
|
93 |
+
if j > i:
|
94 |
+
fuse_layer.append(nn.Sequential(
|
95 |
+
nn.Conv2d(in_channels=num_inchannels[j],
|
96 |
+
out_channels=num_inchannels[i],
|
97 |
+
kernel_size=1,
|
98 |
+
bias=False),
|
99 |
+
self.norm_layer(num_inchannels[i])))
|
100 |
+
elif j == i:
|
101 |
+
fuse_layer.append(None)
|
102 |
+
else:
|
103 |
+
conv3x3s = []
|
104 |
+
for k in range(i - j):
|
105 |
+
if k == i - j - 1:
|
106 |
+
num_outchannels_conv3x3 = num_inchannels[i]
|
107 |
+
conv3x3s.append(nn.Sequential(
|
108 |
+
nn.Conv2d(num_inchannels[j],
|
109 |
+
num_outchannels_conv3x3,
|
110 |
+
kernel_size=3, stride=2, padding=1, bias=False),
|
111 |
+
self.norm_layer(num_outchannels_conv3x3)))
|
112 |
+
else:
|
113 |
+
num_outchannels_conv3x3 = num_inchannels[j]
|
114 |
+
conv3x3s.append(nn.Sequential(
|
115 |
+
nn.Conv2d(num_inchannels[j],
|
116 |
+
num_outchannels_conv3x3,
|
117 |
+
kernel_size=3, stride=2, padding=1, bias=False),
|
118 |
+
self.norm_layer(num_outchannels_conv3x3),
|
119 |
+
nn.ReLU(inplace=relu_inplace)))
|
120 |
+
fuse_layer.append(nn.Sequential(*conv3x3s))
|
121 |
+
fuse_layers.append(nn.ModuleList(fuse_layer))
|
122 |
+
|
123 |
+
return nn.ModuleList(fuse_layers)
|
124 |
+
|
125 |
+
def get_num_inchannels(self):
|
126 |
+
return self.num_inchannels
|
127 |
+
|
128 |
+
def forward(self, x):
|
129 |
+
if self.num_branches == 1:
|
130 |
+
return [self.branches[0](x[0])]
|
131 |
+
|
132 |
+
for i in range(self.num_branches):
|
133 |
+
x[i] = self.branches[i](x[i])
|
134 |
+
|
135 |
+
x_fuse = []
|
136 |
+
for i in range(len(self.fuse_layers)):
|
137 |
+
y = x[0] if i == 0 else self.fuse_layers[i][0](x[0])
|
138 |
+
for j in range(1, self.num_branches):
|
139 |
+
if i == j:
|
140 |
+
y = y + x[j]
|
141 |
+
elif j > i:
|
142 |
+
width_output = x[i].shape[-1]
|
143 |
+
height_output = x[i].shape[-2]
|
144 |
+
y = y + F.interpolate(
|
145 |
+
self.fuse_layers[i][j](x[j]),
|
146 |
+
size=[height_output, width_output],
|
147 |
+
mode='bilinear', align_corners=self.align_corners)
|
148 |
+
else:
|
149 |
+
y = y + self.fuse_layers[i][j](x[j])
|
150 |
+
x_fuse.append(self.relu(y))
|
151 |
+
|
152 |
+
return x_fuse
|
153 |
+
|
154 |
+
|
155 |
+
class HighResolutionNet(nn.Module):
|
156 |
+
def __init__(self, width, num_classes, ocr_width=256, small=False,
|
157 |
+
norm_layer=nn.BatchNorm2d, align_corners=True):
|
158 |
+
super(HighResolutionNet, self).__init__()
|
159 |
+
self.norm_layer = norm_layer
|
160 |
+
self.width = width
|
161 |
+
self.ocr_width = ocr_width
|
162 |
+
self.align_corners = align_corners
|
163 |
+
|
164 |
+
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False)
|
165 |
+
self.bn1 = norm_layer(64)
|
166 |
+
self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1, bias=False)
|
167 |
+
self.bn2 = norm_layer(64)
|
168 |
+
self.relu = nn.ReLU(inplace=relu_inplace)
|
169 |
+
|
170 |
+
num_blocks = 2 if small else 4
|
171 |
+
|
172 |
+
stage1_num_channels = 64
|
173 |
+
self.layer1 = self._make_layer(BottleneckV1b, 64, stage1_num_channels, blocks=num_blocks)
|
174 |
+
stage1_out_channel = BottleneckV1b.expansion * stage1_num_channels
|
175 |
+
|
176 |
+
self.stage2_num_branches = 2
|
177 |
+
num_channels = [width, 2 * width]
|
178 |
+
num_inchannels = [
|
179 |
+
num_channels[i] * BasicBlockV1b.expansion for i in range(len(num_channels))]
|
180 |
+
self.transition1 = self._make_transition_layer(
|
181 |
+
[stage1_out_channel], num_inchannels)
|
182 |
+
self.stage2, pre_stage_channels = self._make_stage(
|
183 |
+
BasicBlockV1b, num_inchannels=num_inchannels, num_modules=1, num_branches=self.stage2_num_branches,
|
184 |
+
num_blocks=2 * [num_blocks], num_channels=num_channels)
|
185 |
+
|
186 |
+
self.stage3_num_branches = 3
|
187 |
+
num_channels = [width, 2 * width, 4 * width]
|
188 |
+
num_inchannels = [
|
189 |
+
num_channels[i] * BasicBlockV1b.expansion for i in range(len(num_channels))]
|
190 |
+
self.transition2 = self._make_transition_layer(
|
191 |
+
pre_stage_channels, num_inchannels)
|
192 |
+
self.stage3, pre_stage_channels = self._make_stage(
|
193 |
+
BasicBlockV1b, num_inchannels=num_inchannels,
|
194 |
+
num_modules=3 if small else 4, num_branches=self.stage3_num_branches,
|
195 |
+
num_blocks=3 * [num_blocks], num_channels=num_channels)
|
196 |
+
|
197 |
+
self.stage4_num_branches = 4
|
198 |
+
num_channels = [width, 2 * width, 4 * width, 8 * width]
|
199 |
+
num_inchannels = [
|
200 |
+
num_channels[i] * BasicBlockV1b.expansion for i in range(len(num_channels))]
|
201 |
+
self.transition3 = self._make_transition_layer(
|
202 |
+
pre_stage_channels, num_inchannels)
|
203 |
+
self.stage4, pre_stage_channels = self._make_stage(
|
204 |
+
BasicBlockV1b, num_inchannels=num_inchannels, num_modules=2 if small else 3,
|
205 |
+
num_branches=self.stage4_num_branches,
|
206 |
+
num_blocks=4 * [num_blocks], num_channels=num_channels)
|
207 |
+
|
208 |
+
last_inp_channels = np.int(np.sum(pre_stage_channels))
|
209 |
+
ocr_mid_channels = 2 * ocr_width
|
210 |
+
ocr_key_channels = ocr_width
|
211 |
+
|
212 |
+
self.conv3x3_ocr = nn.Sequential(
|
213 |
+
nn.Conv2d(last_inp_channels, ocr_mid_channels,
|
214 |
+
kernel_size=3, stride=1, padding=1),
|
215 |
+
norm_layer(ocr_mid_channels),
|
216 |
+
nn.ReLU(inplace=relu_inplace),
|
217 |
+
)
|
218 |
+
self.ocr_gather_head = SpatialGather_Module(num_classes)
|
219 |
+
|
220 |
+
self.ocr_distri_head = SpatialOCR_Module(in_channels=ocr_mid_channels,
|
221 |
+
key_channels=ocr_key_channels,
|
222 |
+
out_channels=ocr_mid_channels,
|
223 |
+
scale=1,
|
224 |
+
dropout=0.05,
|
225 |
+
norm_layer=norm_layer,
|
226 |
+
align_corners=align_corners)
|
227 |
+
self.cls_head = nn.Conv2d(
|
228 |
+
ocr_mid_channels, num_classes, kernel_size=1, stride=1, padding=0, bias=True)
|
229 |
+
|
230 |
+
self.aux_head = nn.Sequential(
|
231 |
+
nn.Conv2d(last_inp_channels, last_inp_channels,
|
232 |
+
kernel_size=1, stride=1, padding=0),
|
233 |
+
norm_layer(last_inp_channels),
|
234 |
+
nn.ReLU(inplace=relu_inplace),
|
235 |
+
nn.Conv2d(last_inp_channels, num_classes,
|
236 |
+
kernel_size=1, stride=1, padding=0, bias=True)
|
237 |
+
)
|
238 |
+
|
239 |
+
def _make_transition_layer(
|
240 |
+
self, num_channels_pre_layer, num_channels_cur_layer):
|
241 |
+
num_branches_cur = len(num_channels_cur_layer)
|
242 |
+
num_branches_pre = len(num_channels_pre_layer)
|
243 |
+
|
244 |
+
transition_layers = []
|
245 |
+
for i in range(num_branches_cur):
|
246 |
+
if i < num_branches_pre:
|
247 |
+
if num_channels_cur_layer[i] != num_channels_pre_layer[i]:
|
248 |
+
transition_layers.append(nn.Sequential(
|
249 |
+
nn.Conv2d(num_channels_pre_layer[i],
|
250 |
+
num_channels_cur_layer[i],
|
251 |
+
kernel_size=3,
|
252 |
+
stride=1,
|
253 |
+
padding=1,
|
254 |
+
bias=False),
|
255 |
+
self.norm_layer(num_channels_cur_layer[i]),
|
256 |
+
nn.ReLU(inplace=relu_inplace)))
|
257 |
+
else:
|
258 |
+
transition_layers.append(None)
|
259 |
+
else:
|
260 |
+
conv3x3s = []
|
261 |
+
for j in range(i + 1 - num_branches_pre):
|
262 |
+
inchannels = num_channels_pre_layer[-1]
|
263 |
+
outchannels = num_channels_cur_layer[i] \
|
264 |
+
if j == i - num_branches_pre else inchannels
|
265 |
+
conv3x3s.append(nn.Sequential(
|
266 |
+
nn.Conv2d(inchannels, outchannels,
|
267 |
+
kernel_size=3, stride=2, padding=1, bias=False),
|
268 |
+
self.norm_layer(outchannels),
|
269 |
+
nn.ReLU(inplace=relu_inplace)))
|
270 |
+
transition_layers.append(nn.Sequential(*conv3x3s))
|
271 |
+
|
272 |
+
return nn.ModuleList(transition_layers)
|
273 |
+
|
274 |
+
def _make_layer(self, block, inplanes, planes, blocks, stride=1):
|
275 |
+
downsample = None
|
276 |
+
if stride != 1 or inplanes != planes * block.expansion:
|
277 |
+
downsample = nn.Sequential(
|
278 |
+
nn.Conv2d(inplanes, planes * block.expansion,
|
279 |
+
kernel_size=1, stride=stride, bias=False),
|
280 |
+
self.norm_layer(planes * block.expansion),
|
281 |
+
)
|
282 |
+
|
283 |
+
layers = []
|
284 |
+
layers.append(block(inplanes, planes, stride,
|
285 |
+
downsample=downsample, norm_layer=self.norm_layer))
|
286 |
+
inplanes = planes * block.expansion
|
287 |
+
for i in range(1, blocks):
|
288 |
+
layers.append(block(inplanes, planes, norm_layer=self.norm_layer))
|
289 |
+
|
290 |
+
return nn.Sequential(*layers)
|
291 |
+
|
292 |
+
def _make_stage(self, block, num_inchannels,
|
293 |
+
num_modules, num_branches, num_blocks, num_channels,
|
294 |
+
fuse_method='SUM',
|
295 |
+
multi_scale_output=True):
|
296 |
+
modules = []
|
297 |
+
for i in range(num_modules):
|
298 |
+
# multi_scale_output is only used last module
|
299 |
+
if not multi_scale_output and i == num_modules - 1:
|
300 |
+
reset_multi_scale_output = False
|
301 |
+
else:
|
302 |
+
reset_multi_scale_output = True
|
303 |
+
modules.append(
|
304 |
+
HighResolutionModule(num_branches,
|
305 |
+
block,
|
306 |
+
num_blocks,
|
307 |
+
num_inchannels,
|
308 |
+
num_channels,
|
309 |
+
fuse_method,
|
310 |
+
reset_multi_scale_output,
|
311 |
+
norm_layer=self.norm_layer,
|
312 |
+
align_corners=self.align_corners)
|
313 |
+
)
|
314 |
+
num_inchannels = modules[-1].get_num_inchannels()
|
315 |
+
|
316 |
+
return nn.Sequential(*modules), num_inchannels
|
317 |
+
|
318 |
+
def forward(self, x):
|
319 |
+
feats = self.compute_hrnet_feats(x)
|
320 |
+
out_aux = self.aux_head(feats)
|
321 |
+
feats = self.conv3x3_ocr(feats)
|
322 |
+
|
323 |
+
context = self.ocr_gather_head(feats, out_aux)
|
324 |
+
feats = self.ocr_distri_head(feats, context)
|
325 |
+
out = self.cls_head(feats)
|
326 |
+
|
327 |
+
return [out, out_aux]
|
328 |
+
|
329 |
+
def compute_hrnet_feats(self, x):
|
330 |
+
x = self.conv1(x)
|
331 |
+
x = self.bn1(x)
|
332 |
+
x = self.relu(x)
|
333 |
+
x = self.conv2(x)
|
334 |
+
x = self.bn2(x)
|
335 |
+
x = self.relu(x)
|
336 |
+
x = self.layer1(x)
|
337 |
+
|
338 |
+
x_list = []
|
339 |
+
for i in range(self.stage2_num_branches):
|
340 |
+
if self.transition1[i] is not None:
|
341 |
+
x_list.append(self.transition1[i](x))
|
342 |
+
else:
|
343 |
+
x_list.append(x)
|
344 |
+
y_list = self.stage2(x_list)
|
345 |
+
|
346 |
+
x_list = []
|
347 |
+
for i in range(self.stage3_num_branches):
|
348 |
+
if self.transition2[i] is not None:
|
349 |
+
if i < self.stage2_num_branches:
|
350 |
+
x_list.append(self.transition2[i](y_list[i]))
|
351 |
+
else:
|
352 |
+
x_list.append(self.transition2[i](y_list[-1]))
|
353 |
+
else:
|
354 |
+
x_list.append(y_list[i])
|
355 |
+
y_list = self.stage3(x_list)
|
356 |
+
|
357 |
+
x_list = []
|
358 |
+
for i in range(self.stage4_num_branches):
|
359 |
+
if self.transition3[i] is not None:
|
360 |
+
if i < self.stage3_num_branches:
|
361 |
+
x_list.append(self.transition3[i](y_list[i]))
|
362 |
+
else:
|
363 |
+
x_list.append(self.transition3[i](y_list[-1]))
|
364 |
+
else:
|
365 |
+
x_list.append(y_list[i])
|
366 |
+
x = self.stage4(x_list)
|
367 |
+
|
368 |
+
# Upsampling
|
369 |
+
x0_h, x0_w = x[0].size(2), x[0].size(3)
|
370 |
+
x1 = F.interpolate(x[1], size=(x0_h, x0_w),
|
371 |
+
mode='bilinear', align_corners=self.align_corners)
|
372 |
+
x2 = F.interpolate(x[2], size=(x0_h, x0_w),
|
373 |
+
mode='bilinear', align_corners=self.align_corners)
|
374 |
+
x3 = F.interpolate(x[3], size=(x0_h, x0_w),
|
375 |
+
mode='bilinear', align_corners=self.align_corners)
|
376 |
+
|
377 |
+
return torch.cat([x[0], x1, x2, x3], 1)
|
378 |
+
|
379 |
+
def load_pretrained_weights(self, pretrained_path=''):
|
380 |
+
model_dict = self.state_dict()
|
381 |
+
|
382 |
+
if not os.path.exists(pretrained_path):
|
383 |
+
print(f'\nFile "{pretrained_path}" does not exist.')
|
384 |
+
print('You need to specify the correct path to the pre-trained weights.\n'
|
385 |
+
'You can download the weights for HRNet from the repository:\n'
|
386 |
+
'https://github.com/HRNet/HRNet-Image-Classification')
|
387 |
+
exit(1)
|
388 |
+
pretrained_dict = torch.load(pretrained_path, map_location={'cuda:0': 'cpu'})
|
389 |
+
pretrained_dict = {k.replace('last_layer', 'aux_head').replace('model.', ''): v for k, v in
|
390 |
+
pretrained_dict.items()}
|
391 |
+
|
392 |
+
print('model_dict-pretrained_dict:', sorted(list(set(model_dict) - set(pretrained_dict))))
|
393 |
+
print('pretrained_dict-model_dict:', sorted(list(set(pretrained_dict) - set(model_dict))))
|
394 |
+
|
395 |
+
pretrained_dict = {k: v for k, v in pretrained_dict.items()
|
396 |
+
if k in model_dict.keys()}
|
397 |
+
|
398 |
+
model_dict.update(pretrained_dict)
|
399 |
+
self.load_state_dict(model_dict)
|
inference/interact/fbrs/model/modeling/ocr.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch._utils
|
4 |
+
import torch.nn.functional as F
|
5 |
+
|
6 |
+
|
7 |
+
class SpatialGather_Module(nn.Module):
|
8 |
+
"""
|
9 |
+
Aggregate the context features according to the initial
|
10 |
+
predicted probability distribution.
|
11 |
+
Employ the soft-weighted method to aggregate the context.
|
12 |
+
"""
|
13 |
+
|
14 |
+
def __init__(self, cls_num=0, scale=1):
|
15 |
+
super(SpatialGather_Module, self).__init__()
|
16 |
+
self.cls_num = cls_num
|
17 |
+
self.scale = scale
|
18 |
+
|
19 |
+
def forward(self, feats, probs):
|
20 |
+
batch_size, c, h, w = probs.size(0), probs.size(1), probs.size(2), probs.size(3)
|
21 |
+
probs = probs.view(batch_size, c, -1)
|
22 |
+
feats = feats.view(batch_size, feats.size(1), -1)
|
23 |
+
feats = feats.permute(0, 2, 1) # batch x hw x c
|
24 |
+
probs = F.softmax(self.scale * probs, dim=2) # batch x k x hw
|
25 |
+
ocr_context = torch.matmul(probs, feats) \
|
26 |
+
.permute(0, 2, 1).unsqueeze(3) # batch x k x c
|
27 |
+
return ocr_context
|
28 |
+
|
29 |
+
|
30 |
+
class SpatialOCR_Module(nn.Module):
|
31 |
+
"""
|
32 |
+
Implementation of the OCR module:
|
33 |
+
We aggregate the global object representation to update the representation for each pixel.
|
34 |
+
"""
|
35 |
+
|
36 |
+
def __init__(self,
|
37 |
+
in_channels,
|
38 |
+
key_channels,
|
39 |
+
out_channels,
|
40 |
+
scale=1,
|
41 |
+
dropout=0.1,
|
42 |
+
norm_layer=nn.BatchNorm2d,
|
43 |
+
align_corners=True):
|
44 |
+
super(SpatialOCR_Module, self).__init__()
|
45 |
+
self.object_context_block = ObjectAttentionBlock2D(in_channels, key_channels, scale,
|
46 |
+
norm_layer, align_corners)
|
47 |
+
_in_channels = 2 * in_channels
|
48 |
+
|
49 |
+
self.conv_bn_dropout = nn.Sequential(
|
50 |
+
nn.Conv2d(_in_channels, out_channels, kernel_size=1, padding=0, bias=False),
|
51 |
+
nn.Sequential(norm_layer(out_channels), nn.ReLU(inplace=True)),
|
52 |
+
nn.Dropout2d(dropout)
|
53 |
+
)
|
54 |
+
|
55 |
+
def forward(self, feats, proxy_feats):
|
56 |
+
context = self.object_context_block(feats, proxy_feats)
|
57 |
+
|
58 |
+
output = self.conv_bn_dropout(torch.cat([context, feats], 1))
|
59 |
+
|
60 |
+
return output
|
61 |
+
|
62 |
+
|
63 |
+
class ObjectAttentionBlock2D(nn.Module):
|
64 |
+
'''
|
65 |
+
The basic implementation for object context block
|
66 |
+
Input:
|
67 |
+
N X C X H X W
|
68 |
+
Parameters:
|
69 |
+
in_channels : the dimension of the input feature map
|
70 |
+
key_channels : the dimension after the key/query transform
|
71 |
+
scale : choose the scale to downsample the input feature maps (save memory cost)
|
72 |
+
bn_type : specify the bn type
|
73 |
+
Return:
|
74 |
+
N X C X H X W
|
75 |
+
'''
|
76 |
+
|
77 |
+
def __init__(self,
|
78 |
+
in_channels,
|
79 |
+
key_channels,
|
80 |
+
scale=1,
|
81 |
+
norm_layer=nn.BatchNorm2d,
|
82 |
+
align_corners=True):
|
83 |
+
super(ObjectAttentionBlock2D, self).__init__()
|
84 |
+
self.scale = scale
|
85 |
+
self.in_channels = in_channels
|
86 |
+
self.key_channels = key_channels
|
87 |
+
self.align_corners = align_corners
|
88 |
+
|
89 |
+
self.pool = nn.MaxPool2d(kernel_size=(scale, scale))
|
90 |
+
self.f_pixel = nn.Sequential(
|
91 |
+
nn.Conv2d(in_channels=self.in_channels, out_channels=self.key_channels,
|
92 |
+
kernel_size=1, stride=1, padding=0, bias=False),
|
93 |
+
nn.Sequential(norm_layer(self.key_channels), nn.ReLU(inplace=True)),
|
94 |
+
nn.Conv2d(in_channels=self.key_channels, out_channels=self.key_channels,
|
95 |
+
kernel_size=1, stride=1, padding=0, bias=False),
|
96 |
+
nn.Sequential(norm_layer(self.key_channels), nn.ReLU(inplace=True))
|
97 |
+
)
|
98 |
+
self.f_object = nn.Sequential(
|
99 |
+
nn.Conv2d(in_channels=self.in_channels, out_channels=self.key_channels,
|
100 |
+
kernel_size=1, stride=1, padding=0, bias=False),
|
101 |
+
nn.Sequential(norm_layer(self.key_channels), nn.ReLU(inplace=True)),
|
102 |
+
nn.Conv2d(in_channels=self.key_channels, out_channels=self.key_channels,
|
103 |
+
kernel_size=1, stride=1, padding=0, bias=False),
|
104 |
+
nn.Sequential(norm_layer(self.key_channels), nn.ReLU(inplace=True))
|
105 |
+
)
|
106 |
+
self.f_down = nn.Sequential(
|
107 |
+
nn.Conv2d(in_channels=self.in_channels, out_channels=self.key_channels,
|
108 |
+
kernel_size=1, stride=1, padding=0, bias=False),
|
109 |
+
nn.Sequential(norm_layer(self.key_channels), nn.ReLU(inplace=True))
|
110 |
+
)
|
111 |
+
self.f_up = nn.Sequential(
|
112 |
+
nn.Conv2d(in_channels=self.key_channels, out_channels=self.in_channels,
|
113 |
+
kernel_size=1, stride=1, padding=0, bias=False),
|
114 |
+
nn.Sequential(norm_layer(self.in_channels), nn.ReLU(inplace=True))
|
115 |
+
)
|
116 |
+
|
117 |
+
def forward(self, x, proxy):
|
118 |
+
batch_size, h, w = x.size(0), x.size(2), x.size(3)
|
119 |
+
if self.scale > 1:
|
120 |
+
x = self.pool(x)
|
121 |
+
|
122 |
+
query = self.f_pixel(x).view(batch_size, self.key_channels, -1)
|
123 |
+
query = query.permute(0, 2, 1)
|
124 |
+
key = self.f_object(proxy).view(batch_size, self.key_channels, -1)
|
125 |
+
value = self.f_down(proxy).view(batch_size, self.key_channels, -1)
|
126 |
+
value = value.permute(0, 2, 1)
|
127 |
+
|
128 |
+
sim_map = torch.matmul(query, key)
|
129 |
+
sim_map = (self.key_channels ** -.5) * sim_map
|
130 |
+
sim_map = F.softmax(sim_map, dim=-1)
|
131 |
+
|
132 |
+
# add bg context ...
|
133 |
+
context = torch.matmul(sim_map, value)
|
134 |
+
context = context.permute(0, 2, 1).contiguous()
|
135 |
+
context = context.view(batch_size, self.key_channels, *x.size()[2:])
|
136 |
+
context = self.f_up(context)
|
137 |
+
if self.scale > 1:
|
138 |
+
context = F.interpolate(input=context, size=(h, w),
|
139 |
+
mode='bilinear', align_corners=self.align_corners)
|
140 |
+
|
141 |
+
return context
|
inference/interact/fbrs/model/modeling/resnet.py
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from .resnetv1b import resnet34_v1b, resnet50_v1s, resnet101_v1s, resnet152_v1s
|
3 |
+
|
4 |
+
|
5 |
+
class ResNetBackbone(torch.nn.Module):
|
6 |
+
def __init__(self, backbone='resnet50', pretrained_base=True, dilated=True, **kwargs):
|
7 |
+
super(ResNetBackbone, self).__init__()
|
8 |
+
|
9 |
+
if backbone == 'resnet34':
|
10 |
+
pretrained = resnet34_v1b(pretrained=pretrained_base, dilated=dilated, **kwargs)
|
11 |
+
elif backbone == 'resnet50':
|
12 |
+
pretrained = resnet50_v1s(pretrained=pretrained_base, dilated=dilated, **kwargs)
|
13 |
+
elif backbone == 'resnet101':
|
14 |
+
pretrained = resnet101_v1s(pretrained=pretrained_base, dilated=dilated, **kwargs)
|
15 |
+
elif backbone == 'resnet152':
|
16 |
+
pretrained = resnet152_v1s(pretrained=pretrained_base, dilated=dilated, **kwargs)
|
17 |
+
else:
|
18 |
+
raise RuntimeError(f'unknown backbone: {backbone}')
|
19 |
+
|
20 |
+
self.conv1 = pretrained.conv1
|
21 |
+
self.bn1 = pretrained.bn1
|
22 |
+
self.relu = pretrained.relu
|
23 |
+
self.maxpool = pretrained.maxpool
|
24 |
+
self.layer1 = pretrained.layer1
|
25 |
+
self.layer2 = pretrained.layer2
|
26 |
+
self.layer3 = pretrained.layer3
|
27 |
+
self.layer4 = pretrained.layer4
|
28 |
+
|
29 |
+
def forward(self, x):
|
30 |
+
x = self.conv1(x)
|
31 |
+
x = self.bn1(x)
|
32 |
+
x = self.relu(x)
|
33 |
+
x = self.maxpool(x)
|
34 |
+
c1 = self.layer1(x)
|
35 |
+
c2 = self.layer2(c1)
|
36 |
+
c3 = self.layer3(c2)
|
37 |
+
c4 = self.layer4(c3)
|
38 |
+
|
39 |
+
return c1, c2, c3, c4
|
inference/interact/fbrs/model/modeling/resnetv1b.py
ADDED
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
GLUON_RESNET_TORCH_HUB = 'rwightman/pytorch-pretrained-gluonresnet'
|
4 |
+
|
5 |
+
|
6 |
+
class BasicBlockV1b(nn.Module):
|
7 |
+
expansion = 1
|
8 |
+
|
9 |
+
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None,
|
10 |
+
previous_dilation=1, norm_layer=nn.BatchNorm2d):
|
11 |
+
super(BasicBlockV1b, self).__init__()
|
12 |
+
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride,
|
13 |
+
padding=dilation, dilation=dilation, bias=False)
|
14 |
+
self.bn1 = norm_layer(planes)
|
15 |
+
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1,
|
16 |
+
padding=previous_dilation, dilation=previous_dilation, bias=False)
|
17 |
+
self.bn2 = norm_layer(planes)
|
18 |
+
|
19 |
+
self.relu = nn.ReLU(inplace=True)
|
20 |
+
self.downsample = downsample
|
21 |
+
self.stride = stride
|
22 |
+
|
23 |
+
def forward(self, x):
|
24 |
+
residual = x
|
25 |
+
|
26 |
+
out = self.conv1(x)
|
27 |
+
out = self.bn1(out)
|
28 |
+
out = self.relu(out)
|
29 |
+
|
30 |
+
out = self.conv2(out)
|
31 |
+
out = self.bn2(out)
|
32 |
+
|
33 |
+
if self.downsample is not None:
|
34 |
+
residual = self.downsample(x)
|
35 |
+
|
36 |
+
out = out + residual
|
37 |
+
out = self.relu(out)
|
38 |
+
|
39 |
+
return out
|
40 |
+
|
41 |
+
|
42 |
+
class BottleneckV1b(nn.Module):
|
43 |
+
expansion = 4
|
44 |
+
|
45 |
+
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None,
|
46 |
+
previous_dilation=1, norm_layer=nn.BatchNorm2d):
|
47 |
+
super(BottleneckV1b, self).__init__()
|
48 |
+
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
|
49 |
+
self.bn1 = norm_layer(planes)
|
50 |
+
|
51 |
+
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
|
52 |
+
padding=dilation, dilation=dilation, bias=False)
|
53 |
+
self.bn2 = norm_layer(planes)
|
54 |
+
|
55 |
+
self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)
|
56 |
+
self.bn3 = norm_layer(planes * self.expansion)
|
57 |
+
|
58 |
+
self.relu = nn.ReLU(inplace=True)
|
59 |
+
self.downsample = downsample
|
60 |
+
self.stride = stride
|
61 |
+
|
62 |
+
def forward(self, x):
|
63 |
+
residual = x
|
64 |
+
|
65 |
+
out = self.conv1(x)
|
66 |
+
out = self.bn1(out)
|
67 |
+
out = self.relu(out)
|
68 |
+
|
69 |
+
out = self.conv2(out)
|
70 |
+
out = self.bn2(out)
|
71 |
+
out = self.relu(out)
|
72 |
+
|
73 |
+
out = self.conv3(out)
|
74 |
+
out = self.bn3(out)
|
75 |
+
|
76 |
+
if self.downsample is not None:
|
77 |
+
residual = self.downsample(x)
|
78 |
+
|
79 |
+
out = out + residual
|
80 |
+
out = self.relu(out)
|
81 |
+
|
82 |
+
return out
|
83 |
+
|
84 |
+
|
85 |
+
class ResNetV1b(nn.Module):
|
86 |
+
""" Pre-trained ResNetV1b Model, which produces the strides of 8 featuremaps at conv5.
|
87 |
+
|
88 |
+
Parameters
|
89 |
+
----------
|
90 |
+
block : Block
|
91 |
+
Class for the residual block. Options are BasicBlockV1, BottleneckV1.
|
92 |
+
layers : list of int
|
93 |
+
Numbers of layers in each block
|
94 |
+
classes : int, default 1000
|
95 |
+
Number of classification classes.
|
96 |
+
dilated : bool, default False
|
97 |
+
Applying dilation strategy to pretrained ResNet yielding a stride-8 model,
|
98 |
+
typically used in Semantic Segmentation.
|
99 |
+
norm_layer : object
|
100 |
+
Normalization layer used (default: :class:`nn.BatchNorm2d`)
|
101 |
+
deep_stem : bool, default False
|
102 |
+
Whether to replace the 7x7 conv1 with 3 3x3 convolution layers.
|
103 |
+
avg_down : bool, default False
|
104 |
+
Whether to use average pooling for projection skip connection between stages/downsample.
|
105 |
+
final_drop : float, default 0.0
|
106 |
+
Dropout ratio before the final classification layer.
|
107 |
+
|
108 |
+
Reference:
|
109 |
+
- He, Kaiming, et al. "Deep residual learning for image recognition."
|
110 |
+
Proceedings of the IEEE conference on computer vision and pattern recognition. 2016.
|
111 |
+
|
112 |
+
- Yu, Fisher, and Vladlen Koltun. "Multi-scale context aggregation by dilated convolutions."
|
113 |
+
"""
|
114 |
+
def __init__(self, block, layers, classes=1000, dilated=True, deep_stem=False, stem_width=32,
|
115 |
+
avg_down=False, final_drop=0.0, norm_layer=nn.BatchNorm2d):
|
116 |
+
self.inplanes = stem_width*2 if deep_stem else 64
|
117 |
+
super(ResNetV1b, self).__init__()
|
118 |
+
if not deep_stem:
|
119 |
+
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
|
120 |
+
else:
|
121 |
+
self.conv1 = nn.Sequential(
|
122 |
+
nn.Conv2d(3, stem_width, kernel_size=3, stride=2, padding=1, bias=False),
|
123 |
+
norm_layer(stem_width),
|
124 |
+
nn.ReLU(True),
|
125 |
+
nn.Conv2d(stem_width, stem_width, kernel_size=3, stride=1, padding=1, bias=False),
|
126 |
+
norm_layer(stem_width),
|
127 |
+
nn.ReLU(True),
|
128 |
+
nn.Conv2d(stem_width, 2*stem_width, kernel_size=3, stride=1, padding=1, bias=False)
|
129 |
+
)
|
130 |
+
self.bn1 = norm_layer(self.inplanes)
|
131 |
+
self.relu = nn.ReLU(True)
|
132 |
+
self.maxpool = nn.MaxPool2d(3, stride=2, padding=1)
|
133 |
+
self.layer1 = self._make_layer(block, 64, layers[0], avg_down=avg_down,
|
134 |
+
norm_layer=norm_layer)
|
135 |
+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2, avg_down=avg_down,
|
136 |
+
norm_layer=norm_layer)
|
137 |
+
if dilated:
|
138 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=1, dilation=2,
|
139 |
+
avg_down=avg_down, norm_layer=norm_layer)
|
140 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=1, dilation=4,
|
141 |
+
avg_down=avg_down, norm_layer=norm_layer)
|
142 |
+
else:
|
143 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
|
144 |
+
avg_down=avg_down, norm_layer=norm_layer)
|
145 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
|
146 |
+
avg_down=avg_down, norm_layer=norm_layer)
|
147 |
+
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
|
148 |
+
self.drop = None
|
149 |
+
if final_drop > 0.0:
|
150 |
+
self.drop = nn.Dropout(final_drop)
|
151 |
+
self.fc = nn.Linear(512 * block.expansion, classes)
|
152 |
+
|
153 |
+
def _make_layer(self, block, planes, blocks, stride=1, dilation=1,
|
154 |
+
avg_down=False, norm_layer=nn.BatchNorm2d):
|
155 |
+
downsample = None
|
156 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
157 |
+
downsample = []
|
158 |
+
if avg_down:
|
159 |
+
if dilation == 1:
|
160 |
+
downsample.append(
|
161 |
+
nn.AvgPool2d(kernel_size=stride, stride=stride, ceil_mode=True, count_include_pad=False)
|
162 |
+
)
|
163 |
+
else:
|
164 |
+
downsample.append(
|
165 |
+
nn.AvgPool2d(kernel_size=1, stride=1, ceil_mode=True, count_include_pad=False)
|
166 |
+
)
|
167 |
+
downsample.extend([
|
168 |
+
nn.Conv2d(self.inplanes, out_channels=planes * block.expansion,
|
169 |
+
kernel_size=1, stride=1, bias=False),
|
170 |
+
norm_layer(planes * block.expansion)
|
171 |
+
])
|
172 |
+
downsample = nn.Sequential(*downsample)
|
173 |
+
else:
|
174 |
+
downsample = nn.Sequential(
|
175 |
+
nn.Conv2d(self.inplanes, out_channels=planes * block.expansion,
|
176 |
+
kernel_size=1, stride=stride, bias=False),
|
177 |
+
norm_layer(planes * block.expansion)
|
178 |
+
)
|
179 |
+
|
180 |
+
layers = []
|
181 |
+
if dilation in (1, 2):
|
182 |
+
layers.append(block(self.inplanes, planes, stride, dilation=1, downsample=downsample,
|
183 |
+
previous_dilation=dilation, norm_layer=norm_layer))
|
184 |
+
elif dilation == 4:
|
185 |
+
layers.append(block(self.inplanes, planes, stride, dilation=2, downsample=downsample,
|
186 |
+
previous_dilation=dilation, norm_layer=norm_layer))
|
187 |
+
else:
|
188 |
+
raise RuntimeError("=> unknown dilation size: {}".format(dilation))
|
189 |
+
|
190 |
+
self.inplanes = planes * block.expansion
|
191 |
+
for _ in range(1, blocks):
|
192 |
+
layers.append(block(self.inplanes, planes, dilation=dilation,
|
193 |
+
previous_dilation=dilation, norm_layer=norm_layer))
|
194 |
+
|
195 |
+
return nn.Sequential(*layers)
|
196 |
+
|
197 |
+
def forward(self, x):
|
198 |
+
x = self.conv1(x)
|
199 |
+
x = self.bn1(x)
|
200 |
+
x = self.relu(x)
|
201 |
+
x = self.maxpool(x)
|
202 |
+
|
203 |
+
x = self.layer1(x)
|
204 |
+
x = self.layer2(x)
|
205 |
+
x = self.layer3(x)
|
206 |
+
x = self.layer4(x)
|
207 |
+
|
208 |
+
x = self.avgpool(x)
|
209 |
+
x = x.view(x.size(0), -1)
|
210 |
+
if self.drop is not None:
|
211 |
+
x = self.drop(x)
|
212 |
+
x = self.fc(x)
|
213 |
+
|
214 |
+
return x
|
215 |
+
|
216 |
+
|
217 |
+
def _safe_state_dict_filtering(orig_dict, model_dict_keys):
|
218 |
+
filtered_orig_dict = {}
|
219 |
+
for k, v in orig_dict.items():
|
220 |
+
if k in model_dict_keys:
|
221 |
+
filtered_orig_dict[k] = v
|
222 |
+
else:
|
223 |
+
print(f"[ERROR] Failed to load <{k}> in backbone")
|
224 |
+
return filtered_orig_dict
|
225 |
+
|
226 |
+
|
227 |
+
def resnet34_v1b(pretrained=False, **kwargs):
|
228 |
+
model = ResNetV1b(BasicBlockV1b, [3, 4, 6, 3], **kwargs)
|
229 |
+
if pretrained:
|
230 |
+
model_dict = model.state_dict()
|
231 |
+
filtered_orig_dict = _safe_state_dict_filtering(
|
232 |
+
torch.hub.load(GLUON_RESNET_TORCH_HUB, 'gluon_resnet34_v1b', pretrained=True).state_dict(),
|
233 |
+
model_dict.keys()
|
234 |
+
)
|
235 |
+
model_dict.update(filtered_orig_dict)
|
236 |
+
model.load_state_dict(model_dict)
|
237 |
+
return model
|
238 |
+
|
239 |
+
|
240 |
+
def resnet50_v1s(pretrained=False, **kwargs):
|
241 |
+
model = ResNetV1b(BottleneckV1b, [3, 4, 6, 3], deep_stem=True, stem_width=64, **kwargs)
|
242 |
+
if pretrained:
|
243 |
+
model_dict = model.state_dict()
|
244 |
+
filtered_orig_dict = _safe_state_dict_filtering(
|
245 |
+
torch.hub.load(GLUON_RESNET_TORCH_HUB, 'gluon_resnet50_v1s', pretrained=True).state_dict(),
|
246 |
+
model_dict.keys()
|
247 |
+
)
|
248 |
+
model_dict.update(filtered_orig_dict)
|
249 |
+
model.load_state_dict(model_dict)
|
250 |
+
return model
|
251 |
+
|
252 |
+
|
253 |
+
def resnet101_v1s(pretrained=False, **kwargs):
|
254 |
+
model = ResNetV1b(BottleneckV1b, [3, 4, 23, 3], deep_stem=True, stem_width=64, **kwargs)
|
255 |
+
if pretrained:
|
256 |
+
model_dict = model.state_dict()
|
257 |
+
filtered_orig_dict = _safe_state_dict_filtering(
|
258 |
+
torch.hub.load(GLUON_RESNET_TORCH_HUB, 'gluon_resnet101_v1s', pretrained=True).state_dict(),
|
259 |
+
model_dict.keys()
|
260 |
+
)
|
261 |
+
model_dict.update(filtered_orig_dict)
|
262 |
+
model.load_state_dict(model_dict)
|
263 |
+
return model
|
264 |
+
|
265 |
+
|
266 |
+
def resnet152_v1s(pretrained=False, **kwargs):
|
267 |
+
model = ResNetV1b(BottleneckV1b, [3, 8, 36, 3], deep_stem=True, stem_width=64, **kwargs)
|
268 |
+
if pretrained:
|
269 |
+
model_dict = model.state_dict()
|
270 |
+
filtered_orig_dict = _safe_state_dict_filtering(
|
271 |
+
torch.hub.load(GLUON_RESNET_TORCH_HUB, 'gluon_resnet152_v1s', pretrained=True).state_dict(),
|
272 |
+
model_dict.keys()
|
273 |
+
)
|
274 |
+
model_dict.update(filtered_orig_dict)
|
275 |
+
model.load_state_dict(model_dict)
|
276 |
+
return model
|
inference/interact/fbrs/model/ops.py
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn as nn
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
from . import initializer as initializer
|
6 |
+
from ..utils.cython import get_dist_maps
|
7 |
+
|
8 |
+
|
9 |
+
def select_activation_function(activation):
|
10 |
+
if isinstance(activation, str):
|
11 |
+
if activation.lower() == 'relu':
|
12 |
+
return nn.ReLU
|
13 |
+
elif activation.lower() == 'softplus':
|
14 |
+
return nn.Softplus
|
15 |
+
else:
|
16 |
+
raise ValueError(f"Unknown activation type {activation}")
|
17 |
+
elif isinstance(activation, nn.Module):
|
18 |
+
return activation
|
19 |
+
else:
|
20 |
+
raise ValueError(f"Unknown activation type {activation}")
|
21 |
+
|
22 |
+
|
23 |
+
class BilinearConvTranspose2d(nn.ConvTranspose2d):
|
24 |
+
def __init__(self, in_channels, out_channels, scale, groups=1):
|
25 |
+
kernel_size = 2 * scale - scale % 2
|
26 |
+
self.scale = scale
|
27 |
+
|
28 |
+
super().__init__(
|
29 |
+
in_channels, out_channels,
|
30 |
+
kernel_size=kernel_size,
|
31 |
+
stride=scale,
|
32 |
+
padding=1,
|
33 |
+
groups=groups,
|
34 |
+
bias=False)
|
35 |
+
|
36 |
+
self.apply(initializer.Bilinear(scale=scale, in_channels=in_channels, groups=groups))
|
37 |
+
|
38 |
+
|
39 |
+
class DistMaps(nn.Module):
|
40 |
+
def __init__(self, norm_radius, spatial_scale=1.0, cpu_mode=False):
|
41 |
+
super(DistMaps, self).__init__()
|
42 |
+
self.spatial_scale = spatial_scale
|
43 |
+
self.norm_radius = norm_radius
|
44 |
+
self.cpu_mode = cpu_mode
|
45 |
+
|
46 |
+
def get_coord_features(self, points, batchsize, rows, cols):
|
47 |
+
if self.cpu_mode:
|
48 |
+
coords = []
|
49 |
+
for i in range(batchsize):
|
50 |
+
norm_delimeter = self.spatial_scale * self.norm_radius
|
51 |
+
coords.append(get_dist_maps(points[i].cpu().float().numpy(), rows, cols,
|
52 |
+
norm_delimeter))
|
53 |
+
coords = torch.from_numpy(np.stack(coords, axis=0)).to(points.device).float()
|
54 |
+
else:
|
55 |
+
num_points = points.shape[1] // 2
|
56 |
+
points = points.view(-1, 2)
|
57 |
+
invalid_points = torch.max(points, dim=1, keepdim=False)[0] < 0
|
58 |
+
row_array = torch.arange(start=0, end=rows, step=1, dtype=torch.float32, device=points.device)
|
59 |
+
col_array = torch.arange(start=0, end=cols, step=1, dtype=torch.float32, device=points.device)
|
60 |
+
|
61 |
+
coord_rows, coord_cols = torch.meshgrid(row_array, col_array)
|
62 |
+
coords = torch.stack((coord_rows, coord_cols), dim=0).unsqueeze(0).repeat(points.size(0), 1, 1, 1)
|
63 |
+
|
64 |
+
add_xy = (points * self.spatial_scale).view(points.size(0), points.size(1), 1, 1)
|
65 |
+
coords.add_(-add_xy)
|
66 |
+
coords.div_(self.norm_radius * self.spatial_scale)
|
67 |
+
coords.mul_(coords)
|
68 |
+
|
69 |
+
coords[:, 0] += coords[:, 1]
|
70 |
+
coords = coords[:, :1]
|
71 |
+
|
72 |
+
coords[invalid_points, :, :, :] = 1e6
|
73 |
+
|
74 |
+
coords = coords.view(-1, num_points, 1, rows, cols)
|
75 |
+
coords = coords.min(dim=1)[0] # -> (bs * num_masks * 2) x 1 x h x w
|
76 |
+
coords = coords.view(-1, 2, rows, cols)
|
77 |
+
|
78 |
+
coords.sqrt_().mul_(2).tanh_()
|
79 |
+
|
80 |
+
return coords
|
81 |
+
|
82 |
+
def forward(self, x, coords):
|
83 |
+
return self.get_coord_features(coords, x.shape[0], x.shape[2], x.shape[3])
|
inference/interact/fbrs/model/syncbn/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2018 Tamaki Kojima
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
inference/interact/fbrs/model/syncbn/README.md
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# pytorch-syncbn
|
2 |
+
|
3 |
+
Tamaki Kojima(tamakoji@gmail.com)
|
4 |
+
|
5 |
+
## Announcement
|
6 |
+
|
7 |
+
**Pytorch 1.0 support**
|
8 |
+
|
9 |
+
## Overview
|
10 |
+
This is alternative implementation of "Synchronized Multi-GPU Batch Normalization" which computes global stats across gpus instead of locally computed. SyncBN are getting important for those input image is large, and must use multi-gpu to increase the minibatch-size for the training.
|
11 |
+
|
12 |
+
The code was inspired by [Pytorch-Encoding](https://github.com/zhanghang1989/PyTorch-Encoding) and [Inplace-ABN](https://github.com/mapillary/inplace_abn)
|
13 |
+
|
14 |
+
## Remarks
|
15 |
+
- Unlike [Pytorch-Encoding](https://github.com/zhanghang1989/PyTorch-Encoding), you don't need custom `nn.DataParallel`
|
16 |
+
- Unlike [Inplace-ABN](https://github.com/mapillary/inplace_abn), you can just replace your `nn.BatchNorm2d` to this module implementation, since it will not mark for inplace operation
|
17 |
+
- You can plug into arbitrary module written in PyTorch to enable Synchronized BatchNorm
|
18 |
+
- Backward computation is rewritten and tested against behavior of `nn.BatchNorm2d`
|
19 |
+
|
20 |
+
## Requirements
|
21 |
+
For PyTorch, please refer to https://pytorch.org/
|
22 |
+
|
23 |
+
NOTE : The code is tested only with PyTorch v1.0.0, CUDA10/CuDNN7.4.2 on ubuntu18.04
|
24 |
+
|
25 |
+
It utilize Pytorch JIT mechanism to compile seamlessly, using ninja. Please install ninja-build before use.
|
26 |
+
|
27 |
+
```
|
28 |
+
sudo apt-get install ninja-build
|
29 |
+
```
|
30 |
+
|
31 |
+
Also install all dependencies for python. For pip, run:
|
32 |
+
|
33 |
+
|
34 |
+
```
|
35 |
+
pip install -U -r requirements.txt
|
36 |
+
```
|
37 |
+
|
38 |
+
## Build
|
39 |
+
|
40 |
+
There is no need to build. just run and JIT will take care.
|
41 |
+
JIT and cpp extensions are supported after PyTorch0.4, however it is highly recommended to use PyTorch > 1.0 due to huge design changes.
|
42 |
+
|
43 |
+
## Usage
|
44 |
+
|
45 |
+
Please refer to [`test.py`](./test.py) for testing the difference between `nn.BatchNorm2d` and `modules.nn.BatchNorm2d`
|
46 |
+
|
47 |
+
```
|
48 |
+
import torch
|
49 |
+
from modules import nn as NN
|
50 |
+
num_gpu = torch.cuda.device_count()
|
51 |
+
model = nn.Sequential(
|
52 |
+
nn.Conv2d(3, 3, 1, 1, bias=False),
|
53 |
+
NN.BatchNorm2d(3),
|
54 |
+
nn.ReLU(inplace=True),
|
55 |
+
nn.Conv2d(3, 3, 1, 1, bias=False),
|
56 |
+
NN.BatchNorm2d(3),
|
57 |
+
).cuda()
|
58 |
+
model = nn.DataParallel(model, device_ids=range(num_gpu))
|
59 |
+
x = torch.rand(num_gpu, 3, 2, 2).cuda()
|
60 |
+
z = model(x)
|
61 |
+
```
|
62 |
+
|
63 |
+
## Math
|
64 |
+
|
65 |
+
### Forward
|
66 |
+
1. compute <img src="https://latex.codecogs.com/gif.latex?\sum{x_i},\sum{x_i^2}"/> in each gpu
|
67 |
+
2. gather all <img src="https://latex.codecogs.com/gif.latex?\sum{x_i},\sum{x_i^2}"/> from workers to master and compute <img src="https://latex.codecogs.com/gif.latex?\mu,\sigma"/> where
|
68 |
+
|
69 |
+
<img src="https://latex.codecogs.com/gif.latex?\mu=\frac{\sum{x_i}}{N}"/>
|
70 |
+
|
71 |
+
and
|
72 |
+
|
73 |
+
<img src="https://latex.codecogs.com/gif.latex?\sigma^2=\frac{\sum{x_i^2}-\mu\sum{x_i}}{N}"/></a>
|
74 |
+
|
75 |
+
and then above global stats to be shared to all gpus, update running_mean and running_var by moving average using global stats.
|
76 |
+
|
77 |
+
3. forward batchnorm using global stats by
|
78 |
+
|
79 |
+
<img src="https://latex.codecogs.com/gif.latex?\hat{x_i}=\frac{x_i-\mu}{\sqrt{\sigma^2+\epsilon}}"/>
|
80 |
+
|
81 |
+
and then
|
82 |
+
|
83 |
+
<img src="https://latex.codecogs.com/gif.latex?y_i=\gamma\cdot\hat{x_i}+\beta"/>
|
84 |
+
|
85 |
+
where <img src="https://latex.codecogs.com/gif.latex?\gamma"/> is weight parameter and <img src="https://latex.codecogs.com/gif.latex?\beta"/> is bias parameter.
|
86 |
+
|
87 |
+
4. save <img src="https://latex.codecogs.com/gif.latex?x,&space;\gamma\&space;\beta,&space;\mu,&space;\sigma^2"/> for backward
|
88 |
+
|
89 |
+
### Backward
|
90 |
+
|
91 |
+
1. Restore saved <img src="https://latex.codecogs.com/gif.latex?x,&space;\gamma\&space;\beta,&space;\mu,&space;\sigma^2"/>
|
92 |
+
|
93 |
+
2. Compute below sums on each gpu
|
94 |
+
|
95 |
+
<img src="https://latex.codecogs.com/gif.latex?\sum_{i=1}^{N_j}(\frac{dJ}{dy_i})"/>
|
96 |
+
|
97 |
+
and
|
98 |
+
|
99 |
+
<img src="https://latex.codecogs.com/gif.latex?\sum_{i=1}^{N_j}(\frac{dJ}{dy_i}\cdot\hat{x_i})"/>
|
100 |
+
|
101 |
+
where <img src="https://latex.codecogs.com/gif.latex?j\in[0,1,....,num\_gpu]"/>
|
102 |
+
|
103 |
+
then gather them at master node to sum up global, and normalize with N where N is total number of elements for each channels. Global sums are then shared among all gpus.
|
104 |
+
|
105 |
+
3. compute gradients using global stats
|
106 |
+
|
107 |
+
<img src="https://latex.codecogs.com/gif.latex?\frac{dJ}{dx_i},&space;\frac{dJ}{d\gamma},&space;\frac{dJ}{d\beta}&space;"/>
|
108 |
+
|
109 |
+
where
|
110 |
+
|
111 |
+
<img src="https://latex.codecogs.com/gif.latex?\frac{dJ}{d\gamma}=\sum_{i=1}^{N}(\frac{dJ}{dy_i}\cdot\hat{x_i})"/>
|
112 |
+
|
113 |
+
and
|
114 |
+
|
115 |
+
<img src="https://latex.codecogs.com/gif.latex?\frac{dJ}{d\beta}=\sum_{i=1}^{N}(\frac{dJ}{dy_i})"/>
|
116 |
+
|
117 |
+
and finally,
|
118 |
+
|
119 |
+
<img src="https://latex.codecogs.com/gif.latex?\frac{dJ}{dx_i}=\frac{dJ}{d\hat{x_i}}\frac{d\hat{x_i}}{dx_i}+\frac{dJ}{d\mu_i}\frac{d\mu_i}{dx_i}+\frac{dJ}{d\sigma^2_i}\frac{d\sigma^2_i}{dx_i}"/>
|
120 |
+
|
121 |
+
<img src="https://latex.codecogs.com/gif.latex?=\frac{1}{N\sqrt{(\sigma^2+\epsilon)}}(N\frac{dJ}{d\hat{x_i}}-\sum_{j=1}^{N}(\frac{dJ}{d\hat{x_j}})-\hat{x_i}\sum_{j=1}^{N}(\frac{dJ}{d\hat{x_j}}\hat{x_j}))"/>
|
122 |
+
|
123 |
+
<img src="https://latex.codecogs.com/gif.latex?=\frac{\gamma}{N\sqrt{(\sigma^2+\epsilon)}}(N\frac{dJ}{dy_i}-\sum_{j=1}^{N}(\frac{dJ}{dy_j})-\hat{x_i}\sum_{j=1}^{N}(\frac{dJ}{dy_j}\hat{x_j}))"/>
|
124 |
+
|
125 |
+
Note that in the implementation, normalization with N is performed at step (2) and above equation and implementation is not exactly the same, but mathematically is same.
|
126 |
+
|
127 |
+
You can go deeper on above explanation at [Kevin Zakka's Blog](https://kevinzakka.github.io/2016/09/14/batch_normalization/)
|