Publish SigLIP2 NMPZ checkpoints and climate experiment
Browse filesUpdate the model card, inference modules, and bilingual Gradio demo. Publish standalone checkpoint files and the regional climate comparison.
- LICENSE +21 -0
- LICENSE-SigLIP2 +202 -0
- README.md +33 -10
- configs/streetgeo_siglip2_nmpz.json +13 -0
- evaluation/climate-ablation.json +286 -0
- huggingface_demo/README.md +7 -8
- huggingface_demo/app.py +3 -11
- huggingface_demo/streetgeo/core/__init__.py +6 -0
- huggingface_demo/streetgeo/core/checkpoints.py +11 -5
- huggingface_demo/streetgeo/core/config.py +116 -71
- huggingface_demo/streetgeo/core/model.py +65 -23
- huggingface_demo/streetgeo/datasets/images.py +27 -7
- huggingface_demo/streetgeo/inference/predict.py +3 -2
- streetgeo/core/__init__.py +11 -5
- streetgeo/core/checkpoints.py +85 -79
- streetgeo/core/config.py +46 -1
- streetgeo/core/model.py +312 -270
- streetgeo/datasets/images.py +191 -171
- streetgeo/inference/predict.py +60 -59
- weights/siglip2-nmpz-climate-aux-0.1.pt +3 -0
- weights/siglip2-nmpz-climate-control.pt +3 -0
- weights/siglip2-nmpz-last-block.pt +3 -0
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Chenxi Wang
|
| 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.
|
LICENSE-SigLIP2
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
README.md
CHANGED
|
@@ -1,34 +1,57 @@
|
|
| 1 |
---
|
|
|
|
|
|
|
|
|
|
| 2 |
tags:
|
| 3 |
-
- pytorch
|
| 4 |
- geolocation
|
| 5 |
- street-view
|
| 6 |
- transformer
|
| 7 |
- geoguessr
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
# Street-View Geolocation Transformer (S.V.G.T.)
|
| 11 |
|
| 12 |
-
S.V.G.T. estimates latitude and longitude from street-view images. The
|
| 13 |
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
|
| 17 |
-
|
| 18 |
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
## Local inference
|
| 22 |
|
| 23 |
-
|
| 24 |
|
| 25 |
```bash
|
| 26 |
python -m pip install -r requirements.txt
|
| 27 |
-
python -m streetgeo.inference.predict street_view.jpg --checkpoint /
|
| 28 |
```
|
| 29 |
|
| 30 |
-
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
|
| 33 |
|
| 34 |
-
The
|
|
|
|
| 1 |
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
library_name: pytorch
|
| 4 |
+
base_model: google/siglip2-base-patch16-224
|
| 5 |
tags:
|
|
|
|
| 6 |
- geolocation
|
| 7 |
- street-view
|
| 8 |
- transformer
|
| 9 |
- geoguessr
|
| 10 |
+
- nmpz
|
| 11 |
---
|
| 12 |
|
| 13 |
# Street-View Geolocation Transformer (S.V.G.T.)
|
| 14 |
|
| 15 |
+
S.V.G.T. estimates latitude and longitude from street-view images. The SigLIP2 NMPZ model takes one fixed perspective image, ranks geographic cells, and predicts a coordinate within each candidate cell. It uses Google's SigLIP2 Base/16/224 vision encoder with four learned pooling queries and a hierarchical geolocation head.
|
| 16 |
|
| 17 |
+
[Training source and instructions](https://github.com/TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer/tree/df4be555419cec5efce7a8085afd742cfff396c8) · [Upstream SigLIP2](https://huggingface.co/google/siglip2-base-patch16-224) · [Gradio demo](huggingface_demo/README.md)
|
| 18 |
|
| 19 |
+
## Model downloads
|
| 20 |
|
| 21 |
+
Each file is a standalone S.V.G.T. PyTorch checkpoint of approximately 394 MiB. The files include the architecture and preprocessing configuration. Download one checkpoint and select it in a compatible S.V.G.T. client, or pass it to the inference command below.
|
| 22 |
|
| 23 |
+
| Checkpoint | Use |
|
| 24 |
+
| --- | --- |
|
| 25 |
+
| [SigLIP2 NMPZ, last-block fine-tune](https://huggingface.co/TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer/resolve/main/weights/siglip2-nmpz-last-block.pt) | Default for the Gradio demo. One fixed view and hard geographic labels. |
|
| 26 |
+
| [Climate control, weight `0`](https://huggingface.co/TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer/resolve/main/weights/siglip2-nmpz-climate-control.pt) | Frozen encoder and control for the climate experiment. |
|
| 27 |
+
| [Climate auxiliary, weight `0.1`](https://huggingface.co/TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer/resolve/main/weights/siglip2-nmpz-climate-aux-0.1.pt) | Experimental Köppen–Geiger supervision with a frozen encoder. |
|
| 28 |
+
|
| 29 |
+
## Climate experiment
|
| 30 |
+
|
| 31 |
+
Training labels are the five major climate classes, with 80% raster confidence required. The auxiliary head was trained jointly with geolocation. Predictions use the geographic head. [Beck 1991–2020 climate raster](https://doi.org/10.6084/m9.figshare.21937568.v1)
|
| 32 |
+
|
| 33 |
+
| Climate loss weight | Top-1 median ↓ | P90 distance ↓ | Within 25 km ↑ | True cell in Top 5 ↑ |
|
| 34 |
+
| --- | ---: | ---: | ---: | ---: |
|
| 35 |
+
| `0` | 949 km | 3,501 km | 3.64% | 30.55% |
|
| 36 |
+
| `0.1` | 1,178 km | 3,602 km | 3.64% | 25.82% |
|
| 37 |
+
|
| 38 |
+
The two validation-selected checkpoints were evaluated on the same 275 held-out Mapillary images from North and Central America. Both runs used a frozen SigLIP2 encoder, four epochs, seed 1337, and hard geographic labels. At the matched final step (1,100), median distance was 926 km for `0` and 969 km for `0.1`. This is a single regional split with one training seed. The test set had valid climate labels for A, C, and D. The climate loss defaults to `0`.
|
| 39 |
+
|
| 40 |
+
The sample coverage is regional. These results do not establish global localization accuracy. The [evaluation data](evaluation/climate-ablation.json) include test metrics, support counts, and the raster fingerprint.
|
| 41 |
|
| 42 |
## Local inference
|
| 43 |
|
| 44 |
+
From this repository's root, install its inference dependencies and run the CLI with a local checkpoint and one perspective street-view image.
|
| 45 |
|
| 46 |
```bash
|
| 47 |
python -m pip install -r requirements.txt
|
| 48 |
+
python -m streetgeo.inference.predict street_view.jpg --checkpoint weights/siglip2-nmpz-last-block.pt --device auto --top-k 5 --json
|
| 49 |
```
|
| 50 |
|
| 51 |
+
The output contains ranked coordinates, model grid probabilities, and Google Maps links. `--google-coverage-only` enables an optional country and region approximation using the [bundled map sources](assets/maps/un_map_sources.json). The same CLI can load compatible original S.V.G.T. checkpoints with up to four views of one location.
|
| 52 |
+
|
| 53 |
+
The [bilingual Gradio demo](huggingface_demo/README.md) can run locally or be deployed as a Space. It downloads the default single-view checkpoint on the first prediction. Set `SVGT_CHECKPOINT` to use a local model file instead.
|
| 54 |
|
| 55 |
+
## Licenses
|
| 56 |
|
| 57 |
+
The SigLIP2-derived weights incorporate Google's pretrained vision weights. S.V.G.T. adapts the encoder for geographic localization and fine-tunes the last vision block in the demo checkpoint. The weight files are distributed under [Apache 2.0](LICENSE-SigLIP2). The inference source is covered by the project's [MIT license](LICENSE).
|
configs/streetgeo_siglip2_nmpz.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"vision_backbone": "siglip2_base_patch16_224",
|
| 3 |
+
"image_size": 224,
|
| 4 |
+
"patch_size": 16,
|
| 5 |
+
"n_embed": 768,
|
| 6 |
+
"n_head": 12,
|
| 7 |
+
"n_layer": 12,
|
| 8 |
+
"fusion_layers": 0,
|
| 9 |
+
"view_queries": 4,
|
| 10 |
+
"max_views": 1,
|
| 11 |
+
"geo_smoothing": 0.0,
|
| 12 |
+
"geo_smoothing_km": 250.0
|
| 13 |
+
}
|
evaluation/climate-ablation.json
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"training_images": 2197,
|
| 3 |
+
"validation_images": 275,
|
| 4 |
+
"test_images": 275,
|
| 5 |
+
"dataset": "Existing geographically partitioned Mapillary split, North and Central America",
|
| 6 |
+
"protocol": "Frozen SigLIP2, seed 1337, 4 epochs, batch 8, geo smoothing off, no climate reranking",
|
| 7 |
+
"raster": {
|
| 8 |
+
"recipe": "beck2023_1991_2020_5classes_v1",
|
| 9 |
+
"source": "https://doi.org/10.6084/m9.figshare.21937568.v1",
|
| 10 |
+
"sha256": "0a858822dba6b9d50dfb59d29b17a46ab7f421664fb0d0a5ef97971463988f29",
|
| 11 |
+
"minimum_confidence": 80.0
|
| 12 |
+
},
|
| 13 |
+
"train_climate_label_counts": {
|
| 14 |
+
"A": 61,
|
| 15 |
+
"B": 240,
|
| 16 |
+
"C": 537,
|
| 17 |
+
"D": 607,
|
| 18 |
+
"E": 0,
|
| 19 |
+
"unknown": 752
|
| 20 |
+
},
|
| 21 |
+
"validation_climate_label_counts": {
|
| 22 |
+
"A": 0,
|
| 23 |
+
"B": 0,
|
| 24 |
+
"C": 0,
|
| 25 |
+
"D": 137,
|
| 26 |
+
"E": 0,
|
| 27 |
+
"unknown": 138
|
| 28 |
+
},
|
| 29 |
+
"comparisons": {
|
| 30 |
+
"validation_selected": {
|
| 31 |
+
"control_lambda_0": {
|
| 32 |
+
"checkpoint": "climate_control.pt",
|
| 33 |
+
"selected_step": 825,
|
| 34 |
+
"validation": {
|
| 35 |
+
"loss": 11.405800265190043,
|
| 36 |
+
"mean_km": 1565.047410680905,
|
| 37 |
+
"median_km": 1100.5936303130002,
|
| 38 |
+
"p90_km": 3231.168957640679,
|
| 39 |
+
"p95_km": 4251.478284747716,
|
| 40 |
+
"p99_km": 5430.64721725348,
|
| 41 |
+
"within_1km": 0.0,
|
| 42 |
+
"within_25km": 0.04363636363636364,
|
| 43 |
+
"within_100km": 0.08727272727272728,
|
| 44 |
+
"within_200km": 0.09454545454545454,
|
| 45 |
+
"within_750km": 0.3563636363636364,
|
| 46 |
+
"within_2500km": 0.7672727272727272
|
| 47 |
+
},
|
| 48 |
+
"test_images": 275,
|
| 49 |
+
"top1_median_km": 948.768125058314,
|
| 50 |
+
"top1_p90_km": 3500.6204172028715,
|
| 51 |
+
"within_25km": 0.03636363636363636,
|
| 52 |
+
"true_cell_top5": 0.3054545454545455,
|
| 53 |
+
"mean_geoguessr_score": 2592.778181818182,
|
| 54 |
+
"test_climate_label_counts": {
|
| 55 |
+
"A": 23,
|
| 56 |
+
"B": 0,
|
| 57 |
+
"C": 73,
|
| 58 |
+
"D": 48,
|
| 59 |
+
"E": 0,
|
| 60 |
+
"unknown": 131
|
| 61 |
+
},
|
| 62 |
+
"test_climate_metrics": null,
|
| 63 |
+
"download": "weights/siglip2-nmpz-climate-control.pt"
|
| 64 |
+
},
|
| 65 |
+
"climate_lambda_0_1": {
|
| 66 |
+
"checkpoint": "climate_aux_01.pt",
|
| 67 |
+
"selected_step": 825,
|
| 68 |
+
"validation": {
|
| 69 |
+
"loss": 11.313465884148467,
|
| 70 |
+
"mean_km": 1448.6996928664153,
|
| 71 |
+
"median_km": 1008.8419858865409,
|
| 72 |
+
"p90_km": 3025.7540200793387,
|
| 73 |
+
"p95_km": 3444.2398593919693,
|
| 74 |
+
"p99_km": 6791.949583472109,
|
| 75 |
+
"within_1km": 0.0,
|
| 76 |
+
"within_25km": 0.03636363636363636,
|
| 77 |
+
"within_100km": 0.10181818181818182,
|
| 78 |
+
"within_200km": 0.10909090909090909,
|
| 79 |
+
"within_750km": 0.36,
|
| 80 |
+
"within_2500km": 0.8181818181818182,
|
| 81 |
+
"climate": {
|
| 82 |
+
"labeled": 137,
|
| 83 |
+
"accuracy": 0.8321167883211679,
|
| 84 |
+
"macro_f1": 0.9083665609359741,
|
| 85 |
+
"support": {
|
| 86 |
+
"A": 0,
|
| 87 |
+
"B": 0,
|
| 88 |
+
"C": 0,
|
| 89 |
+
"D": 137,
|
| 90 |
+
"E": 0
|
| 91 |
+
},
|
| 92 |
+
"confusion": [
|
| 93 |
+
[
|
| 94 |
+
0,
|
| 95 |
+
0,
|
| 96 |
+
0,
|
| 97 |
+
0,
|
| 98 |
+
0
|
| 99 |
+
],
|
| 100 |
+
[
|
| 101 |
+
0,
|
| 102 |
+
0,
|
| 103 |
+
0,
|
| 104 |
+
0,
|
| 105 |
+
0
|
| 106 |
+
],
|
| 107 |
+
[
|
| 108 |
+
0,
|
| 109 |
+
0,
|
| 110 |
+
0,
|
| 111 |
+
0,
|
| 112 |
+
0
|
| 113 |
+
],
|
| 114 |
+
[
|
| 115 |
+
0,
|
| 116 |
+
1,
|
| 117 |
+
22,
|
| 118 |
+
114,
|
| 119 |
+
0
|
| 120 |
+
],
|
| 121 |
+
[
|
| 122 |
+
0,
|
| 123 |
+
0,
|
| 124 |
+
0,
|
| 125 |
+
0,
|
| 126 |
+
0
|
| 127 |
+
]
|
| 128 |
+
]
|
| 129 |
+
}
|
| 130 |
+
},
|
| 131 |
+
"test_images": 275,
|
| 132 |
+
"top1_median_km": 1177.740279280977,
|
| 133 |
+
"top1_p90_km": 3602.1230740860938,
|
| 134 |
+
"within_25km": 0.03636363636363636,
|
| 135 |
+
"true_cell_top5": 0.2581818181818182,
|
| 136 |
+
"mean_geoguessr_score": 2387.181818181818,
|
| 137 |
+
"test_climate_label_counts": {
|
| 138 |
+
"A": 23,
|
| 139 |
+
"B": 0,
|
| 140 |
+
"C": 73,
|
| 141 |
+
"D": 48,
|
| 142 |
+
"E": 0,
|
| 143 |
+
"unknown": 131
|
| 144 |
+
},
|
| 145 |
+
"test_climate_metrics": {
|
| 146 |
+
"labeled": 144,
|
| 147 |
+
"accuracy": 0.625,
|
| 148 |
+
"macro_f1": 0.4706411361694336,
|
| 149 |
+
"support": {
|
| 150 |
+
"A": 23,
|
| 151 |
+
"B": 0,
|
| 152 |
+
"C": 73,
|
| 153 |
+
"D": 48,
|
| 154 |
+
"E": 0
|
| 155 |
+
},
|
| 156 |
+
"confusion": [
|
| 157 |
+
[
|
| 158 |
+
1,
|
| 159 |
+
0,
|
| 160 |
+
22,
|
| 161 |
+
0,
|
| 162 |
+
0
|
| 163 |
+
],
|
| 164 |
+
[
|
| 165 |
+
0,
|
| 166 |
+
0,
|
| 167 |
+
0,
|
| 168 |
+
0,
|
| 169 |
+
0
|
| 170 |
+
],
|
| 171 |
+
[
|
| 172 |
+
1,
|
| 173 |
+
0,
|
| 174 |
+
62,
|
| 175 |
+
10,
|
| 176 |
+
0
|
| 177 |
+
],
|
| 178 |
+
[
|
| 179 |
+
0,
|
| 180 |
+
0,
|
| 181 |
+
21,
|
| 182 |
+
27,
|
| 183 |
+
0
|
| 184 |
+
],
|
| 185 |
+
[
|
| 186 |
+
0,
|
| 187 |
+
0,
|
| 188 |
+
0,
|
| 189 |
+
0,
|
| 190 |
+
0
|
| 191 |
+
]
|
| 192 |
+
]
|
| 193 |
+
},
|
| 194 |
+
"download": "weights/siglip2-nmpz-climate-aux-0.1.pt"
|
| 195 |
+
}
|
| 196 |
+
},
|
| 197 |
+
"matched_final_step": {
|
| 198 |
+
"control_lambda_0": {
|
| 199 |
+
"selected_step": 1100,
|
| 200 |
+
"validation": null,
|
| 201 |
+
"test_images": 275,
|
| 202 |
+
"top1_median_km": 925.6453633025363,
|
| 203 |
+
"top1_p90_km": 3324.659665485002,
|
| 204 |
+
"within_25km": 0.04363636363636364,
|
| 205 |
+
"true_cell_top5": 0.3236363636363636,
|
| 206 |
+
"mean_geoguessr_score": 2667.050909090909,
|
| 207 |
+
"test_climate_label_counts": {
|
| 208 |
+
"A": 23,
|
| 209 |
+
"B": 0,
|
| 210 |
+
"C": 73,
|
| 211 |
+
"D": 48,
|
| 212 |
+
"E": 0,
|
| 213 |
+
"unknown": 131
|
| 214 |
+
},
|
| 215 |
+
"test_climate_metrics": null
|
| 216 |
+
},
|
| 217 |
+
"climate_lambda_0_1": {
|
| 218 |
+
"selected_step": 1100,
|
| 219 |
+
"validation": null,
|
| 220 |
+
"test_images": 275,
|
| 221 |
+
"top1_median_km": 969.1316424422124,
|
| 222 |
+
"top1_p90_km": 3513.356858446386,
|
| 223 |
+
"within_25km": 0.04,
|
| 224 |
+
"true_cell_top5": 0.32,
|
| 225 |
+
"mean_geoguessr_score": 2610.68,
|
| 226 |
+
"test_climate_label_counts": {
|
| 227 |
+
"A": 23,
|
| 228 |
+
"B": 0,
|
| 229 |
+
"C": 73,
|
| 230 |
+
"D": 48,
|
| 231 |
+
"E": 0,
|
| 232 |
+
"unknown": 131
|
| 233 |
+
},
|
| 234 |
+
"test_climate_metrics": {
|
| 235 |
+
"labeled": 144,
|
| 236 |
+
"accuracy": 0.6111111111111112,
|
| 237 |
+
"macro_f1": 0.46213462948799133,
|
| 238 |
+
"support": {
|
| 239 |
+
"A": 23,
|
| 240 |
+
"B": 0,
|
| 241 |
+
"C": 73,
|
| 242 |
+
"D": 48,
|
| 243 |
+
"E": 0
|
| 244 |
+
},
|
| 245 |
+
"confusion": [
|
| 246 |
+
[
|
| 247 |
+
1,
|
| 248 |
+
0,
|
| 249 |
+
22,
|
| 250 |
+
0,
|
| 251 |
+
0
|
| 252 |
+
],
|
| 253 |
+
[
|
| 254 |
+
0,
|
| 255 |
+
0,
|
| 256 |
+
0,
|
| 257 |
+
0,
|
| 258 |
+
0
|
| 259 |
+
],
|
| 260 |
+
[
|
| 261 |
+
1,
|
| 262 |
+
0,
|
| 263 |
+
60,
|
| 264 |
+
12,
|
| 265 |
+
0
|
| 266 |
+
],
|
| 267 |
+
[
|
| 268 |
+
0,
|
| 269 |
+
1,
|
| 270 |
+
20,
|
| 271 |
+
27,
|
| 272 |
+
0
|
| 273 |
+
],
|
| 274 |
+
[
|
| 275 |
+
0,
|
| 276 |
+
0,
|
| 277 |
+
0,
|
| 278 |
+
0,
|
| 279 |
+
0
|
| 280 |
+
]
|
| 281 |
+
]
|
| 282 |
+
}
|
| 283 |
+
}
|
| 284 |
+
}
|
| 285 |
+
}
|
| 286 |
+
}
|
huggingface_demo/README.md
CHANGED
|
@@ -14,39 +14,38 @@ models:
|
|
| 14 |
|
| 15 |
# Street-View Geolocation Transformer (S.V.G.T.)
|
| 16 |
|
| 17 |
-
|
| 18 |
|
| 19 |
-
Upload
|
| 20 |
|
| 21 |
## 本地运行 / Run locally
|
| 22 |
|
| 23 |
-
在本目录
|
| 24 |
|
| 25 |
```powershell
|
| 26 |
python -m pip install -r requirements.txt
|
| 27 |
-
$env:SVGT_CHECKPOINT = 'C:\path\to\model.pt'
|
| 28 |
python app.py
|
| 29 |
```
|
| 30 |
|
| 31 |
```bash
|
| 32 |
python -m pip install -r requirements.txt
|
| 33 |
-
|
| 34 |
```
|
| 35 |
|
| 36 |
打开终端显示的本地地址。Open the local URL printed by Gradio.
|
| 37 |
|
| 38 |
## 部署到 Hugging Face Spaces / Deploy to Hugging Face Spaces
|
| 39 |
|
| 40 |
-
将本目录的内容放在 Gradio Space 的仓库根目录。
|
| 41 |
|
| 42 |
| 变量 / Variable | 用法 / Usage |
|
| 43 |
| --- | --- |
|
| 44 |
-
| `SVGT_MODEL_FILE` |
|
| 45 |
| `SVGT_MODEL_REPO` | 可选。默认使用本项目的模型仓库。 / Optional model repository ID. Defaults to the project's model repository. |
|
| 46 |
| `SVGT_MODEL_REVISION` | 可选。可指定模型仓库的提交版本。 / Optional revision to pin the checkpoint. |
|
| 47 |
| `HF_TOKEN` | 私有或受限仓库所需的读取令牌,请添加为 Secret。 / Add a read token as a Secret for private or gated weights. |
|
| 48 |
|
| 49 |
-
模型权重通过 Hugging Face Hub 单独下载。
|
| 50 |
|
| 51 |
[模型仓库 / Model repository](https://huggingface.co/TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer) · [Gradio Spaces](https://huggingface.co/docs/hub/spaces-sdks-gradio)
|
| 52 |
|
|
|
|
| 14 |
|
| 15 |
# Street-View Geolocation Transformer (S.V.G.T.)
|
| 16 |
|
| 17 |
+
默认 SigLIP2 NMPZ 模型接受一张街景图片,输出经纬度、地理网格概率和 Google Maps 链接。加载旧版模型时可上传同地点的多张图。
|
| 18 |
|
| 19 |
+
Upload one perspective street-view image with the default SigLIP2 NMPZ checkpoint. Legacy checkpoints can accept multiple images of the same location.
|
| 20 |
|
| 21 |
## 本地运行 / Run locally
|
| 22 |
|
| 23 |
+
在本目录运行。默认在首次预测时下载模型,也可用 `SVGT_CHECKPOINT` 指定本地权重。Run from this folder. The default checkpoint downloads on the first prediction. Set `SVGT_CHECKPOINT` to load a local file.
|
| 24 |
|
| 25 |
```powershell
|
| 26 |
python -m pip install -r requirements.txt
|
|
|
|
| 27 |
python app.py
|
| 28 |
```
|
| 29 |
|
| 30 |
```bash
|
| 31 |
python -m pip install -r requirements.txt
|
| 32 |
+
python app.py
|
| 33 |
```
|
| 34 |
|
| 35 |
打开终端显示的本地地址。Open the local URL printed by Gradio.
|
| 36 |
|
| 37 |
## 部署到 Hugging Face Spaces / Deploy to Hugging Face Spaces
|
| 38 |
|
| 39 |
+
将本目录的内容放在 Gradio Space 的仓库根目录。可在 **Settings → Variables and secrets** 切换权重。Place the contents of this folder at the root of a Gradio Space. You can override the default model in **Settings → Variables and secrets**.
|
| 40 |
|
| 41 |
| 变量 / Variable | 用法 / Usage |
|
| 42 |
| --- | --- |
|
| 43 |
+
| `SVGT_MODEL_FILE` | 可选。默认 `weights/siglip2-nmpz-last-block.pt`。 / Optional checkpoint path relative to the model repository root. Defaults to `weights/siglip2-nmpz-last-block.pt`. |
|
| 44 |
| `SVGT_MODEL_REPO` | 可选。默认使用本项目的模型仓库。 / Optional model repository ID. Defaults to the project's model repository. |
|
| 45 |
| `SVGT_MODEL_REVISION` | 可选。可指定模型仓库的提交版本。 / Optional revision to pin the checkpoint. |
|
| 46 |
| `HF_TOKEN` | 私有或受限仓库所需的读取令牌,请添加为 Secret。 / Add a read token as a Secret for private or gated weights. |
|
| 47 |
|
| 48 |
+
模型权重通过 Hugging Face Hub 单独下载。首次预测时会加载模型。The demo downloads model weights separately from the Hub on the first prediction.
|
| 49 |
|
| 50 |
[模型仓库 / Model repository](https://huggingface.co/TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer) · [Gradio Spaces](https://huggingface.co/docs/hub/spaces-sdks-gradio)
|
| 51 |
|
huggingface_demo/app.py
CHANGED
|
@@ -13,7 +13,7 @@ from streetgeo import PROJECT_TITLE
|
|
| 13 |
MODEL_REPO = "TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer"
|
| 14 |
MODEL_URL = f"https://huggingface.co/{MODEL_REPO}"
|
| 15 |
LOCAL_CHECKPOINT = os.environ.get("SVGT_CHECKPOINT")
|
| 16 |
-
HUB_CHECKPOINT = os.environ.get("SVGT_MODEL_FILE")
|
| 17 |
LOGGER = logging.getLogger(__name__)
|
| 18 |
|
| 19 |
|
|
@@ -37,8 +37,6 @@ def get_model():
|
|
| 37 |
def predict(image_paths, top_k):
|
| 38 |
if not image_paths or len(image_paths) > 4:
|
| 39 |
return "请上传同一地点的 1–4 张街景图。 / Upload 1–4 views of the same location."
|
| 40 |
-
if not (LOCAL_CHECKPOINT or HUB_CHECKPOINT):
|
| 41 |
-
return "请先配置模型权重。 / Configure a model checkpoint first."
|
| 42 |
|
| 43 |
from streetgeo.inference.predict import predict_images
|
| 44 |
|
|
@@ -69,16 +67,10 @@ def predict(image_paths, top_k):
|
|
| 69 |
with gr.Blocks(title=PROJECT_TITLE, delete_cache=(3600, 3600)) as demo:
|
| 70 |
gr.Markdown(
|
| 71 |
f"# {PROJECT_TITLE}\n"
|
| 72 |
-
"
|
| 73 |
-
"
|
| 74 |
f"[模型仓库 / Model repository]({MODEL_URL})"
|
| 75 |
)
|
| 76 |
-
if not (LOCAL_CHECKPOINT or HUB_CHECKPOINT):
|
| 77 |
-
gr.Markdown(
|
| 78 |
-
"**模型尚未配置 / Checkpoint not configured**\n\n"
|
| 79 |
-
"本地运行时设置 `SVGT_CHECKPOINT`。部署到 Space 后可设置 `SVGT_MODEL_FILE`。\n\n"
|
| 80 |
-
"Set `SVGT_CHECKPOINT` locally or `SVGT_MODEL_FILE` in the Space settings."
|
| 81 |
-
)
|
| 82 |
with gr.Row():
|
| 83 |
with gr.Column():
|
| 84 |
images = gr.File(
|
|
|
|
| 13 |
MODEL_REPO = "TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer"
|
| 14 |
MODEL_URL = f"https://huggingface.co/{MODEL_REPO}"
|
| 15 |
LOCAL_CHECKPOINT = os.environ.get("SVGT_CHECKPOINT")
|
| 16 |
+
HUB_CHECKPOINT = os.environ.get("SVGT_MODEL_FILE") or "weights/siglip2-nmpz-last-block.pt"
|
| 17 |
LOGGER = logging.getLogger(__name__)
|
| 18 |
|
| 19 |
|
|
|
|
| 37 |
def predict(image_paths, top_k):
|
| 38 |
if not image_paths or len(image_paths) > 4:
|
| 39 |
return "请上传同一地点的 1–4 张街景图。 / Upload 1–4 views of the same location."
|
|
|
|
|
|
|
| 40 |
|
| 41 |
from streetgeo.inference.predict import predict_images
|
| 42 |
|
|
|
|
| 67 |
with gr.Blocks(title=PROJECT_TITLE, delete_cache=(3600, 3600)) as demo:
|
| 68 |
gr.Markdown(
|
| 69 |
f"# {PROJECT_TITLE}\n"
|
| 70 |
+
"默认 SigLIP2 NMPZ 模型接受一张透视街景图。旧版模型可接受同地点的多张图。\n\n"
|
| 71 |
+
"The default SigLIP2 NMPZ model takes one perspective street-view image. Legacy models support multiple views of the same location. "
|
| 72 |
f"[模型仓库 / Model repository]({MODEL_URL})"
|
| 73 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
with gr.Row():
|
| 75 |
with gr.Column():
|
| 76 |
images = gr.File(
|
huggingface_demo/streetgeo/core/__init__.py
CHANGED
|
@@ -3,3 +3,9 @@
|
|
| 3 |
|
| 4 |
class EmptyPredictionDomainError(ValueError):
|
| 5 |
"""No model-generated coordinate satisfies the selected prediction domain."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
class EmptyPredictionDomainError(ValueError):
|
| 5 |
"""No model-generated coordinate satisfies the selected prediction domain."""
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class UnsupportedViewCountError(ValueError):
|
| 9 |
+
def __init__(self, maximum):
|
| 10 |
+
self.maximum = maximum
|
| 11 |
+
super().__init__(f"provide 1..{maximum} images of the SAME location")
|
huggingface_demo/streetgeo/core/checkpoints.py
CHANGED
|
@@ -9,11 +9,13 @@ import tempfile
|
|
| 9 |
|
| 10 |
import torch
|
| 11 |
|
| 12 |
-
from streetgeo.core.config import ModelConfig
|
| 13 |
from streetgeo.core.model import StreetGeoModel
|
| 14 |
from streetgeo.paths import validate_checkpoint_path
|
| 15 |
|
| 16 |
ARCHITECTURE = "streetview_hierarchical_vit_v1"
|
|
|
|
|
|
|
| 17 |
|
| 18 |
|
| 19 |
def resolve_device(name="auto"):
|
|
@@ -32,7 +34,7 @@ def save_checkpoint(model, path, *, training_state=None, keep_previous=False):
|
|
| 32 |
descriptor, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
|
| 33 |
try:
|
| 34 |
with os.fdopen(descriptor, "wb") as stream:
|
| 35 |
-
torch.save({"architecture":
|
| 36 |
"model_state_dict": model.state_dict(),
|
| 37 |
"training_state": training_state or {}}, stream)
|
| 38 |
stream.flush()
|
|
@@ -64,10 +66,14 @@ def restore_rng_state(state):
|
|
| 64 |
torch.cuda.set_rng_state_all([value.cpu() for value in state["cuda"]])
|
| 65 |
|
| 66 |
|
| 67 |
-
def read_checkpoint(path):
|
| 68 |
-
checkpoint = torch.load(path, map_location=
|
| 69 |
-
if not isinstance(checkpoint, dict) or checkpoint.get("architecture")
|
| 70 |
raise ValueError("Expected an S.V.G.T. visual checkpoint; old text GPT weights are incompatible")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
return checkpoint
|
| 72 |
|
| 73 |
|
|
|
|
| 9 |
|
| 10 |
import torch
|
| 11 |
|
| 12 |
+
from streetgeo.core.config import LEGACY_BACKBONE, SIGLIP2_BACKBONE, ModelConfig
|
| 13 |
from streetgeo.core.model import StreetGeoModel
|
| 14 |
from streetgeo.paths import validate_checkpoint_path
|
| 15 |
|
| 16 |
ARCHITECTURE = "streetview_hierarchical_vit_v1"
|
| 17 |
+
SIGLIP2_ARCHITECTURE = "streetview_siglip2_nmpz_v2"
|
| 18 |
+
ARCHITECTURES = {LEGACY_BACKBONE: ARCHITECTURE, SIGLIP2_BACKBONE: SIGLIP2_ARCHITECTURE}
|
| 19 |
|
| 20 |
|
| 21 |
def resolve_device(name="auto"):
|
|
|
|
| 34 |
descriptor, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
|
| 35 |
try:
|
| 36 |
with os.fdopen(descriptor, "wb") as stream:
|
| 37 |
+
torch.save({"architecture": ARCHITECTURES[model.config.vision_backbone], "model_config": asdict(model.config),
|
| 38 |
"model_state_dict": model.state_dict(),
|
| 39 |
"training_state": training_state or {}}, stream)
|
| 40 |
stream.flush()
|
|
|
|
| 66 |
torch.cuda.set_rng_state_all([value.cpu() for value in state["cuda"]])
|
| 67 |
|
| 68 |
|
| 69 |
+
def read_checkpoint(path, *, map_location="cpu"):
|
| 70 |
+
checkpoint = torch.load(path, map_location=map_location, weights_only=True)
|
| 71 |
+
if not isinstance(checkpoint, dict) or checkpoint.get("architecture") not in ARCHITECTURES.values():
|
| 72 |
raise ValueError("Expected an S.V.G.T. visual checkpoint; old text GPT weights are incompatible")
|
| 73 |
+
config = checkpoint.get("model_config")
|
| 74 |
+
if (not isinstance(config, dict)
|
| 75 |
+
or ARCHITECTURES.get(config.get("vision_backbone", LEGACY_BACKBONE)) != checkpoint["architecture"]):
|
| 76 |
+
raise ValueError("Checkpoint architecture and model config disagree")
|
| 77 |
return checkpoint
|
| 78 |
|
| 79 |
|
huggingface_demo/streetgeo/core/config.py
CHANGED
|
@@ -1,71 +1,116 @@
|
|
| 1 |
-
"""Configuration shared by training, inference and saved checkpoints."""
|
| 2 |
-
|
| 3 |
-
from dataclasses import dataclass
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration shared by training, inference and saved checkpoints."""
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
import math
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
LEGACY_BACKBONE = "svgt_vit"
|
| 8 |
+
SIGLIP2_BACKBONE = "siglip2_base_patch16_224"
|
| 9 |
+
SIGLIP2_REPO = "google/siglip2-base-patch16-224"
|
| 10 |
+
SIGLIP2_REVISION = "75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2"
|
| 11 |
+
LEGACY_PREPROCESSING = "svgt_letterbox_v1"
|
| 12 |
+
SIGLIP2_PREPROCESSING = "siglip2_resize_v1"
|
| 13 |
+
SIGLIP2_CONFIG_PATH = "configs/streetgeo_siglip2_nmpz.json"
|
| 14 |
+
SIGLIP2_MODEL_PATH = "checkpoints/streetgeo_siglip2_nmpz/best.pt"
|
| 15 |
+
SIGLIP2_WEIGHTS_PATH = "checkpoints/pretrained/siglip2-base-patch16-224/model.safetensors"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass
|
| 19 |
+
class ModelConfig:
|
| 20 |
+
image_size: int = 224
|
| 21 |
+
patch_size: int = 16
|
| 22 |
+
n_embed: int = 1024
|
| 23 |
+
n_head: int = 16
|
| 24 |
+
n_layer: int = 28
|
| 25 |
+
fusion_layers: int = 2
|
| 26 |
+
view_queries: int = 4
|
| 27 |
+
max_views: int = 4
|
| 28 |
+
mlp_ratio: int = 4
|
| 29 |
+
dropout: float = 0.1
|
| 30 |
+
coarse_lat_bins: int = 18
|
| 31 |
+
coarse_lon_bins: int = 36
|
| 32 |
+
fine_bins: int = 4
|
| 33 |
+
cell_embed_dim: int = 128
|
| 34 |
+
offset_loss_weight: float = 1.0
|
| 35 |
+
spherical_loss_weight: float = 1.0
|
| 36 |
+
vision_backbone: str = LEGACY_BACKBONE
|
| 37 |
+
backbone_revision: str | None = None
|
| 38 |
+
preprocessing: str | None = None
|
| 39 |
+
geo_smoothing: float = 0.0
|
| 40 |
+
geo_smoothing_km: float = 250.0
|
| 41 |
+
|
| 42 |
+
def __post_init__(self):
|
| 43 |
+
integer_fields = (
|
| 44 |
+
"image_size", "patch_size", "n_embed", "n_head", "n_layer",
|
| 45 |
+
"view_queries", "max_views", "mlp_ratio",
|
| 46 |
+
"coarse_lat_bins", "coarse_lon_bins", "fine_bins", "cell_embed_dim",
|
| 47 |
+
)
|
| 48 |
+
for name in integer_fields:
|
| 49 |
+
value = getattr(self, name)
|
| 50 |
+
if type(value) is not int or value <= 0:
|
| 51 |
+
raise ValueError(f"{name} must be a positive integer")
|
| 52 |
+
if self.image_size % self.patch_size:
|
| 53 |
+
raise ValueError("image_size must be divisible by patch_size")
|
| 54 |
+
if self.n_embed % self.n_head:
|
| 55 |
+
raise ValueError("n_embed must be divisible by n_head")
|
| 56 |
+
if not 0 <= self.dropout < 1:
|
| 57 |
+
raise ValueError("dropout must be in [0, 1)")
|
| 58 |
+
if self.offset_loss_weight < 0 or self.spherical_loss_weight < 0:
|
| 59 |
+
raise ValueError("loss weights cannot be negative")
|
| 60 |
+
if not 0 <= self.geo_smoothing <= 0.5:
|
| 61 |
+
raise ValueError("geo_smoothing must be in [0, 0.5]")
|
| 62 |
+
if not math.isfinite(self.geo_smoothing_km) or self.geo_smoothing_km <= 0:
|
| 63 |
+
raise ValueError("geo_smoothing_km must be positive and finite")
|
| 64 |
+
if type(self.fusion_layers) is not int:
|
| 65 |
+
raise ValueError("fusion_layers must be an integer")
|
| 66 |
+
if self.vision_backbone == SIGLIP2_BACKBONE:
|
| 67 |
+
shape = (self.image_size, self.patch_size, self.n_embed, self.n_head, self.n_layer,
|
| 68 |
+
self.fusion_layers, self.view_queries, self.max_views, self.mlp_ratio)
|
| 69 |
+
if shape != (224, 16, 768, 12, 12, 0, 4, 1, 4):
|
| 70 |
+
raise ValueError("SigLIP2 NMPZ requires Base/16/224, four queries and one view without fusion")
|
| 71 |
+
if self.backbone_revision not in (None, SIGLIP2_REVISION):
|
| 72 |
+
raise ValueError("Unsupported SigLIP2 backbone revision")
|
| 73 |
+
self.backbone_revision = SIGLIP2_REVISION
|
| 74 |
+
expected_preprocessing = SIGLIP2_PREPROCESSING
|
| 75 |
+
elif self.vision_backbone == LEGACY_BACKBONE:
|
| 76 |
+
if self.fusion_layers <= 0 or self.backbone_revision is not None:
|
| 77 |
+
raise ValueError("The original visual encoder requires fusion layers and no backbone revision")
|
| 78 |
+
expected_preprocessing = LEGACY_PREPROCESSING
|
| 79 |
+
else:
|
| 80 |
+
raise ValueError(f"Unsupported vision backbone: {self.vision_backbone}")
|
| 81 |
+
if self.preprocessing not in (None, expected_preprocessing):
|
| 82 |
+
raise ValueError("Preprocessing does not match the vision backbone")
|
| 83 |
+
self.preprocessing = expected_preprocessing
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def is_siglip2(self):
|
| 87 |
+
return self.vision_backbone == SIGLIP2_BACKBONE
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def coarse_cells(self):
|
| 91 |
+
return self.coarse_lat_bins * self.coarse_lon_bins
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def children_per_cell(self):
|
| 95 |
+
return self.fine_bins ** 2
|
| 96 |
+
|
| 97 |
+
@property
|
| 98 |
+
def total_cells(self):
|
| 99 |
+
return self.coarse_cells * self.children_per_cell
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@dataclass
|
| 103 |
+
class TrainConfig:
|
| 104 |
+
batch_size: int = 32
|
| 105 |
+
epochs: int = 4
|
| 106 |
+
learning_rate: float = 3e-4
|
| 107 |
+
weight_decay: float = 0.1
|
| 108 |
+
grad_clip: float = 1.0
|
| 109 |
+
warmup_steps: int = 1000
|
| 110 |
+
num_workers: int = 4
|
| 111 |
+
device: str = "auto"
|
| 112 |
+
seed: int = 1337
|
| 113 |
+
model_path: str = "checkpoints/streetgeo_400m_mapillary/best.pt"
|
| 114 |
+
save_every_steps: int = 500
|
| 115 |
+
save_every_seconds: float = 300.0
|
| 116 |
+
log_every_steps: int = 10
|
huggingface_demo/streetgeo/core/model.py
CHANGED
|
@@ -4,14 +4,14 @@ Images must be preprocessed with streetgeo.datasets.images.load_image; optional
|
|
| 4 |
clockwise from north. This module never downloads weights or training data.
|
| 5 |
"""
|
| 6 |
|
| 7 |
-
from dataclasses import dataclass
|
| 8 |
import torch
|
| 9 |
from torch import nn
|
| 10 |
from torch.nn import functional as F
|
| 11 |
|
| 12 |
from streetgeo.core import EmptyPredictionDomainError
|
| 13 |
from streetgeo.core.config import ModelConfig
|
| 14 |
-
from streetgeo.core.geography import HierarchicalGeoGrid, LocationPrediction, coordinates_to_unit_vectors
|
| 15 |
|
| 16 |
|
| 17 |
class MultiHeadAttention(nn.Module):
|
|
@@ -41,13 +41,13 @@ class MultiHeadAttention(nn.Module):
|
|
| 41 |
class Block(nn.Module):
|
| 42 |
"""Preserve the original pre-norm Transformer residual structure."""
|
| 43 |
|
| 44 |
-
def __init__(self, config):
|
| 45 |
super().__init__()
|
| 46 |
-
self.ln1 = nn.LayerNorm(config.n_embed)
|
| 47 |
self.attention = MultiHeadAttention(config)
|
| 48 |
-
self.ln2 = nn.LayerNorm(config.n_embed)
|
| 49 |
self.ffn = nn.Sequential(
|
| 50 |
-
nn.Linear(config.n_embed, config.mlp_ratio * config.n_embed), nn.GELU(),
|
| 51 |
nn.Linear(config.mlp_ratio * config.n_embed, config.n_embed),
|
| 52 |
nn.Dropout(config.dropout),
|
| 53 |
)
|
|
@@ -66,18 +66,40 @@ class StreetViewEncoder(nn.Module):
|
|
| 66 |
3, config.n_embed, kernel_size=config.patch_size, stride=config.patch_size,
|
| 67 |
)
|
| 68 |
self.position_embedding = nn.Parameter(torch.zeros(1, patches, config.n_embed))
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
self.pool_queries = nn.Parameter(torch.zeros(1, config.view_queries, config.n_embed))
|
| 72 |
self.pool_attention = nn.MultiheadAttention(
|
| 73 |
config.n_embed, config.n_head, dropout=config.dropout, batch_first=True,
|
| 74 |
)
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
def forward(self, images, view_mask=None, headings=None):
|
| 83 |
if images.ndim == 4:
|
|
@@ -101,14 +123,13 @@ class StreetViewEncoder(nn.Module):
|
|
| 101 |
valid_images = images[view_mask]
|
| 102 |
if not torch.isfinite(valid_images).all():
|
| 103 |
raise ValueError("valid images must contain finite values")
|
| 104 |
-
x = self.
|
| 105 |
-
x = x + self.position_embedding
|
| 106 |
-
for block in self.visual_blocks:
|
| 107 |
-
x = block(x)
|
| 108 |
-
x = self.visual_norm(x)
|
| 109 |
queries = self.pool_queries.expand(x.shape[0], -1, -1)
|
| 110 |
pooled, _ = self.pool_attention(queries, x, x, need_weights=False)
|
| 111 |
pooled = pooled + queries
|
|
|
|
|
|
|
|
|
|
| 112 |
tokens = pooled.new_zeros(batch, views, self.config.view_queries, self.config.n_embed)
|
| 113 |
tokens[view_mask] = pooled
|
| 114 |
if headings is None:
|
|
@@ -150,6 +171,10 @@ class StreetGeoModel(nn.Module):
|
|
| 150 |
self.config = config or ModelConfig()
|
| 151 |
cfg = self.config
|
| 152 |
self.grid = HierarchicalGeoGrid(cfg)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
self.encoder = StreetViewEncoder(cfg)
|
| 154 |
self.coarse_head = nn.Linear(cfg.n_embed, cfg.coarse_cells)
|
| 155 |
self.fine_head = nn.Linear(cfg.n_embed, cfg.total_cells)
|
|
@@ -159,10 +184,24 @@ class StreetGeoModel(nn.Module):
|
|
| 159 |
nn.Linear(cfg.n_embed, 2), nn.Tanh(),
|
| 160 |
)
|
| 161 |
self.apply(self._init_weights)
|
| 162 |
-
|
| 163 |
-
|
|
|
|
|
|
|
| 164 |
nn.init.trunc_normal_(parameter, std=0.02)
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
@staticmethod
|
| 167 |
def _init_weights(module):
|
| 168 |
if isinstance(module, (nn.Linear, nn.Conv2d, nn.Embedding)):
|
|
@@ -246,8 +285,11 @@ class StreetGeoModel(nn.Module):
|
|
| 246 |
"offset": F.smooth_l1_loss(offsets, target_offsets),
|
| 247 |
"spherical": torch.linalg.vector_norm(predicted_xyz - target_xyz, dim=-1).mean(),
|
| 248 |
}
|
| 249 |
-
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
| 251 |
+ self.config.spherical_loss_weight * losses["spherical"])
|
| 252 |
return GeolocationOutput(coordinates[:, 0], coordinates, values.exp(), cell_ids,
|
| 253 |
coarse, fine, F.normalize(embedding, dim=-1), loss, losses)
|
|
|
|
| 4 |
clockwise from north. This module never downloads weights or training data.
|
| 5 |
"""
|
| 6 |
|
| 7 |
+
from dataclasses import dataclass, replace
|
| 8 |
import torch
|
| 9 |
from torch import nn
|
| 10 |
from torch.nn import functional as F
|
| 11 |
|
| 12 |
from streetgeo.core import EmptyPredictionDomainError
|
| 13 |
from streetgeo.core.config import ModelConfig
|
| 14 |
+
from streetgeo.core.geography import HierarchicalGeoGrid, LocationPrediction, coordinates_to_unit_vectors, haversine_km
|
| 15 |
|
| 16 |
|
| 17 |
class MultiHeadAttention(nn.Module):
|
|
|
|
| 41 |
class Block(nn.Module):
|
| 42 |
"""Preserve the original pre-norm Transformer residual structure."""
|
| 43 |
|
| 44 |
+
def __init__(self, config, *, layer_norm_eps=1e-5, gelu_approximation="none"):
|
| 45 |
super().__init__()
|
| 46 |
+
self.ln1 = nn.LayerNorm(config.n_embed, eps=layer_norm_eps)
|
| 47 |
self.attention = MultiHeadAttention(config)
|
| 48 |
+
self.ln2 = nn.LayerNorm(config.n_embed, eps=layer_norm_eps)
|
| 49 |
self.ffn = nn.Sequential(
|
| 50 |
+
nn.Linear(config.n_embed, config.mlp_ratio * config.n_embed), nn.GELU(approximate=gelu_approximation),
|
| 51 |
nn.Linear(config.mlp_ratio * config.n_embed, config.n_embed),
|
| 52 |
nn.Dropout(config.dropout),
|
| 53 |
)
|
|
|
|
| 66 |
3, config.n_embed, kernel_size=config.patch_size, stride=config.patch_size,
|
| 67 |
)
|
| 68 |
self.position_embedding = nn.Parameter(torch.zeros(1, patches, config.n_embed))
|
| 69 |
+
# SigLIP2 FixRes uses the SigLIP vision blocks with zero dropout,
|
| 70 |
+
# tanh-approximate GELU and a different LayerNorm epsilon.
|
| 71 |
+
vision = replace(config, dropout=0.0) if config.is_siglip2 else config
|
| 72 |
+
epsilon = 1e-6 if config.is_siglip2 else 1e-5
|
| 73 |
+
activation = "tanh" if config.is_siglip2 else "none"
|
| 74 |
+
self.visual_blocks = nn.ModuleList([
|
| 75 |
+
Block(vision, layer_norm_eps=epsilon, gelu_approximation=activation) for _ in range(config.n_layer)
|
| 76 |
+
])
|
| 77 |
+
self.visual_norm = nn.LayerNorm(config.n_embed, eps=epsilon)
|
| 78 |
self.pool_queries = nn.Parameter(torch.zeros(1, config.view_queries, config.n_embed))
|
| 79 |
self.pool_attention = nn.MultiheadAttention(
|
| 80 |
config.n_embed, config.n_head, dropout=config.dropout, batch_first=True,
|
| 81 |
)
|
| 82 |
+
if config.is_siglip2:
|
| 83 |
+
self.pool_projection = nn.Linear(config.view_queries * config.n_embed, config.n_embed)
|
| 84 |
+
self.pool_mlp = nn.Sequential(
|
| 85 |
+
nn.LayerNorm(config.n_embed),
|
| 86 |
+
nn.Linear(config.n_embed, 2 * config.n_embed), nn.GELU(),
|
| 87 |
+
nn.Linear(2 * config.n_embed, config.n_embed),
|
| 88 |
+
)
|
| 89 |
+
self.pool_norm = nn.LayerNorm(config.n_embed)
|
| 90 |
+
else:
|
| 91 |
+
# No view-index embedding: unordered views remain permutation invariant.
|
| 92 |
+
self.heading_embedding = nn.Sequential(nn.Linear(3, config.n_embed), nn.GELU(),
|
| 93 |
+
nn.Linear(config.n_embed, config.n_embed))
|
| 94 |
+
self.geo_token = nn.Parameter(torch.zeros(1, 1, config.n_embed))
|
| 95 |
+
self.fusion_blocks = nn.ModuleList([Block(config) for _ in range(config.fusion_layers)])
|
| 96 |
+
self.fusion_norm = nn.LayerNorm(config.n_embed)
|
| 97 |
+
|
| 98 |
+
def visual_tokens(self, images):
|
| 99 |
+
x = self.patch_embedding(images).flatten(2).transpose(1, 2) + self.position_embedding
|
| 100 |
+
for block in self.visual_blocks:
|
| 101 |
+
x = block(x)
|
| 102 |
+
return self.visual_norm(x)
|
| 103 |
|
| 104 |
def forward(self, images, view_mask=None, headings=None):
|
| 105 |
if images.ndim == 4:
|
|
|
|
| 123 |
valid_images = images[view_mask]
|
| 124 |
if not torch.isfinite(valid_images).all():
|
| 125 |
raise ValueError("valid images must contain finite values")
|
| 126 |
+
x = self.visual_tokens(valid_images)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
queries = self.pool_queries.expand(x.shape[0], -1, -1)
|
| 128 |
pooled, _ = self.pool_attention(queries, x, x, need_weights=False)
|
| 129 |
pooled = pooled + queries
|
| 130 |
+
if self.config.is_siglip2:
|
| 131 |
+
projected = self.pool_projection(pooled.flatten(1))
|
| 132 |
+
return self.pool_norm(projected + self.pool_mlp(projected))
|
| 133 |
tokens = pooled.new_zeros(batch, views, self.config.view_queries, self.config.n_embed)
|
| 134 |
tokens[view_mask] = pooled
|
| 135 |
if headings is None:
|
|
|
|
| 171 |
self.config = config or ModelConfig()
|
| 172 |
cfg = self.config
|
| 173 |
self.grid = HierarchicalGeoGrid(cfg)
|
| 174 |
+
if cfg.geo_smoothing:
|
| 175 |
+
cell_ids = torch.arange(cfg.total_cells)
|
| 176 |
+
centers = self.grid.decode(cell_ids, torch.zeros(cfg.total_cells, 2))
|
| 177 |
+
self.register_buffer("cell_centers", centers, persistent=False)
|
| 178 |
self.encoder = StreetViewEncoder(cfg)
|
| 179 |
self.coarse_head = nn.Linear(cfg.n_embed, cfg.coarse_cells)
|
| 180 |
self.fine_head = nn.Linear(cfg.n_embed, cfg.total_cells)
|
|
|
|
| 184 |
nn.Linear(cfg.n_embed, 2), nn.Tanh(),
|
| 185 |
)
|
| 186 |
self.apply(self._init_weights)
|
| 187 |
+
parameters = (self.encoder.position_embedding, self.encoder.pool_queries)
|
| 188 |
+
if not cfg.is_siglip2:
|
| 189 |
+
parameters += (self.encoder.geo_token,)
|
| 190 |
+
for parameter in parameters:
|
| 191 |
nn.init.trunc_normal_(parameter, std=0.02)
|
| 192 |
|
| 193 |
+
def _smooth_cell_loss(self, log_probs, targets, true_ids):
|
| 194 |
+
with torch.no_grad():
|
| 195 |
+
temperature = self.config.geo_smoothing_km
|
| 196 |
+
distance = haversine_km(targets[:, None, :], self.cell_centers)
|
| 197 |
+
# Restrict the soft target to a local neighborhood. Always retain
|
| 198 |
+
# the true cell, including when its center is outside the radius.
|
| 199 |
+
excluded = (distance > 3 * temperature).scatter_(1, true_ids[:, None], False)
|
| 200 |
+
local_distance = distance.masked_fill(excluded, torch.inf)
|
| 201 |
+
relative = local_distance - local_distance.amin(dim=-1, keepdim=True)
|
| 202 |
+
weights = (-relative / temperature).float().softmax(dim=-1)
|
| 203 |
+
return -(weights * log_probs).sum(dim=-1).mean()
|
| 204 |
+
|
| 205 |
@staticmethod
|
| 206 |
def _init_weights(module):
|
| 207 |
if isinstance(module, (nn.Linear, nn.Conv2d, nn.Embedding)):
|
|
|
|
| 285 |
"offset": F.smooth_l1_loss(offsets, target_offsets),
|
| 286 |
"spherical": torch.linalg.vector_norm(predicted_xyz - target_xyz, dim=-1).mean(),
|
| 287 |
}
|
| 288 |
+
classification = losses["coarse"] + losses["fine"]
|
| 289 |
+
if self.config.geo_smoothing:
|
| 290 |
+
losses["geo_smoothing"] = self._smooth_cell_loss(log_probs, targets, true_ids)
|
| 291 |
+
classification = torch.lerp(classification, losses["geo_smoothing"], self.config.geo_smoothing)
|
| 292 |
+
loss = (classification + self.config.offset_loss_weight * losses["offset"]
|
| 293 |
+ self.config.spherical_loss_weight * losses["spherical"])
|
| 294 |
return GeolocationOutput(coordinates[:, 0], coordinates, values.exp(), cell_ids,
|
| 295 |
coarse, fine, F.normalize(embedding, dim=-1), loss, losses)
|
huggingface_demo/streetgeo/datasets/images.py
CHANGED
|
@@ -8,13 +8,20 @@ import torch
|
|
| 8 |
from PIL import Image, ImageOps
|
| 9 |
from torch.utils.data import Dataset
|
| 10 |
|
| 11 |
-
from streetgeo.core.config import ModelConfig
|
| 12 |
from streetgeo.datasets.policy import require_mapillary_row
|
| 13 |
from streetgeo.datasets.road_mask import RoadMask, MASK_FILL
|
| 14 |
|
| 15 |
IMAGE_MEAN = (0.485, 0.456, 0.406)
|
| 16 |
IMAGE_STD = (0.229, 0.224, 0.225)
|
| 17 |
IMAGE_FILL = MASK_FILL
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
|
| 20 |
def manifest_lines(path):
|
|
@@ -24,11 +31,14 @@ def manifest_lines(path):
|
|
| 24 |
|
| 25 |
|
| 26 |
def load_image(path, image_size=224, *, road_mask=None, mask_bottom_third=False):
|
| 27 |
-
"""RGB
|
| 28 |
|
| 29 |
Avoid random horizontal flips: they can reverse driving-side/sign clues.
|
| 30 |
Training and inference always use exactly the same preprocessing.
|
| 31 |
"""
|
|
|
|
|
|
|
|
|
|
| 32 |
with Image.open(path) as source:
|
| 33 |
image = ImageOps.exif_transpose(source).convert("RGB")
|
| 34 |
if road_mask is not None and mask_bottom_third:
|
|
@@ -38,12 +48,16 @@ def load_image(path, image_size=224, *, road_mask=None, mask_bottom_third=False)
|
|
| 38 |
if mask_bottom_third:
|
| 39 |
# Retained only to resume checkpoints created with recipe version 1.
|
| 40 |
image.paste(IMAGE_FILL, (0, image.height * 2 // 3, image.width, image.height))
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
pixels = torch.frombuffer(bytearray(image.tobytes()), dtype=torch.uint8)
|
| 44 |
pixels = pixels.reshape(image_size, image_size, 3).permute(2, 0, 1).float() / 255
|
| 45 |
-
mean =
|
| 46 |
-
|
|
|
|
| 47 |
return (pixels - mean) / std
|
| 48 |
|
| 49 |
|
|
@@ -65,6 +79,7 @@ class StreetViewDataset(Dataset):
|
|
| 65 |
self.legacy_environment_mask = legacy_environment_mask
|
| 66 |
manifest = Path(manifest_path).resolve()
|
| 67 |
self.samples = []
|
|
|
|
| 68 |
self.source_counts = {}
|
| 69 |
self.geographic_bounds = {"south": 90.0, "north": -90.0, "west": 180.0, "east": -180.0}
|
| 70 |
for line_number, line in manifest_lines(manifest):
|
|
@@ -123,7 +138,7 @@ class StreetViewDataset(Dataset):
|
|
| 123 |
# a dataset created before these shape attributes existed.
|
| 124 |
legacy = getattr(self, "legacy_environment_mask", True)
|
| 125 |
sample = {
|
| 126 |
-
"images": torch.stack([load_image(path, self.config
|
| 127 |
road_mask=self.road_mask if phase == 1 and not legacy else None,
|
| 128 |
mask_bottom_third=phase == 1 and legacy) for path in paths]),
|
| 129 |
"coordinates": torch.tensor(coordinates, dtype=torch.float32),
|
|
@@ -131,6 +146,9 @@ class StreetViewDataset(Dataset):
|
|
| 131 |
}
|
| 132 |
if phase is not None:
|
| 133 |
sample["training_phase"] = phase
|
|
|
|
|
|
|
|
|
|
| 134 |
return sample
|
| 135 |
|
| 136 |
|
|
@@ -163,6 +181,8 @@ def collate_streetviews(samples):
|
|
| 163 |
headings[index, :count] = sample["headings"]
|
| 164 |
result = {"images": images, "view_mask": mask, "headings": headings,
|
| 165 |
"targets": torch.stack([sample["coordinates"] for sample in samples])}
|
|
|
|
|
|
|
| 166 |
phases = {sample.get("training_phase") for sample in samples}
|
| 167 |
if len(phases) != 1:
|
| 168 |
raise ValueError("a batch must contain exactly one training phase")
|
|
|
|
| 8 |
from PIL import Image, ImageOps
|
| 9 |
from torch.utils.data import Dataset
|
| 10 |
|
| 11 |
+
from streetgeo.core.config import SIGLIP2_PREPROCESSING, ModelConfig
|
| 12 |
from streetgeo.datasets.policy import require_mapillary_row
|
| 13 |
from streetgeo.datasets.road_mask import RoadMask, MASK_FILL
|
| 14 |
|
| 15 |
IMAGE_MEAN = (0.485, 0.456, 0.406)
|
| 16 |
IMAGE_STD = (0.229, 0.224, 0.225)
|
| 17 |
IMAGE_FILL = MASK_FILL
|
| 18 |
+
SIGLIP2_MEAN_STD = (0.5, 0.5, 0.5)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def image_statistics(preprocessing):
|
| 22 |
+
if preprocessing == SIGLIP2_PREPROCESSING:
|
| 23 |
+
return SIGLIP2_MEAN_STD, SIGLIP2_MEAN_STD
|
| 24 |
+
return IMAGE_MEAN, IMAGE_STD
|
| 25 |
|
| 26 |
|
| 27 |
def manifest_lines(path):
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
def load_image(path, image_size=224, *, road_mask=None, mask_bottom_third=False):
|
| 34 |
+
"""RGB and EXIF orientation, then the checkpoint's resize and normalization.
|
| 35 |
|
| 36 |
Avoid random horizontal flips: they can reverse driving-side/sign clues.
|
| 37 |
Training and inference always use exactly the same preprocessing.
|
| 38 |
"""
|
| 39 |
+
preprocessing = None
|
| 40 |
+
if isinstance(image_size, ModelConfig):
|
| 41 |
+
preprocessing, image_size = image_size.preprocessing, image_size.image_size
|
| 42 |
with Image.open(path) as source:
|
| 43 |
image = ImageOps.exif_transpose(source).convert("RGB")
|
| 44 |
if road_mask is not None and mask_bottom_third:
|
|
|
|
| 48 |
if mask_bottom_third:
|
| 49 |
# Retained only to resume checkpoints created with recipe version 1.
|
| 50 |
image.paste(IMAGE_FILL, (0, image.height * 2 // 3, image.width, image.height))
|
| 51 |
+
if preprocessing == SIGLIP2_PREPROCESSING:
|
| 52 |
+
image = image.resize((image_size, image_size), resample=Image.Resampling.BILINEAR)
|
| 53 |
+
else:
|
| 54 |
+
image = ImageOps.pad(image, (image_size, image_size),
|
| 55 |
+
method=Image.Resampling.BICUBIC, color=IMAGE_FILL)
|
| 56 |
pixels = torch.frombuffer(bytearray(image.tobytes()), dtype=torch.uint8)
|
| 57 |
pixels = pixels.reshape(image_size, image_size, 3).permute(2, 0, 1).float() / 255
|
| 58 |
+
mean, std = image_statistics(preprocessing)
|
| 59 |
+
mean = pixels.new_tensor(mean).view(3, 1, 1)
|
| 60 |
+
std = pixels.new_tensor(std).view(3, 1, 1)
|
| 61 |
return (pixels - mean) / std
|
| 62 |
|
| 63 |
|
|
|
|
| 79 |
self.legacy_environment_mask = legacy_environment_mask
|
| 80 |
manifest = Path(manifest_path).resolve()
|
| 81 |
self.samples = []
|
| 82 |
+
self.climate_targets = None
|
| 83 |
self.source_counts = {}
|
| 84 |
self.geographic_bounds = {"south": 90.0, "north": -90.0, "west": 180.0, "east": -180.0}
|
| 85 |
for line_number, line in manifest_lines(manifest):
|
|
|
|
| 138 |
# a dataset created before these shape attributes existed.
|
| 139 |
legacy = getattr(self, "legacy_environment_mask", True)
|
| 140 |
sample = {
|
| 141 |
+
"images": torch.stack([load_image(path, self.config,
|
| 142 |
road_mask=self.road_mask if phase == 1 and not legacy else None,
|
| 143 |
mask_bottom_third=phase == 1 and legacy) for path in paths]),
|
| 144 |
"coordinates": torch.tensor(coordinates, dtype=torch.float32),
|
|
|
|
| 146 |
}
|
| 147 |
if phase is not None:
|
| 148 |
sample["training_phase"] = phase
|
| 149 |
+
climate_targets = getattr(self, "climate_targets", None)
|
| 150 |
+
if climate_targets is not None:
|
| 151 |
+
sample["climate_target"] = climate_targets[index]
|
| 152 |
return sample
|
| 153 |
|
| 154 |
|
|
|
|
| 181 |
headings[index, :count] = sample["headings"]
|
| 182 |
result = {"images": images, "view_mask": mask, "headings": headings,
|
| 183 |
"targets": torch.stack([sample["coordinates"] for sample in samples])}
|
| 184 |
+
if "climate_target" in samples[0]:
|
| 185 |
+
result["climate_targets"] = torch.tensor([sample["climate_target"] for sample in samples], dtype=torch.long)
|
| 186 |
phases = {sample.get("training_phase") for sample in samples}
|
| 187 |
if len(phases) != 1:
|
| 188 |
raise ValueError("a batch must contain exactly one training phase")
|
huggingface_demo/streetgeo/inference/predict.py
CHANGED
|
@@ -6,6 +6,7 @@ import math
|
|
| 6 |
|
| 7 |
import torch
|
| 8 |
|
|
|
|
| 9 |
from streetgeo.core.checkpoints import load_model
|
| 10 |
from streetgeo.core.config import TrainConfig
|
| 11 |
from streetgeo.datasets.images import load_image
|
|
@@ -13,9 +14,9 @@ from streetgeo.datasets.images import load_image
|
|
| 13 |
|
| 14 |
def predict_images(model, image_paths, *, headings=None, top_k=5, google_coverage_only=False):
|
| 15 |
if not 1 <= len(image_paths) <= model.config.max_views:
|
| 16 |
-
raise
|
| 17 |
device = next(model.parameters()).device
|
| 18 |
-
images = torch.stack([load_image(path, model.config
|
| 19 |
direction_tensor = None
|
| 20 |
if headings is not None:
|
| 21 |
if len(headings) != len(image_paths):
|
|
|
|
| 6 |
|
| 7 |
import torch
|
| 8 |
|
| 9 |
+
from streetgeo.core import UnsupportedViewCountError
|
| 10 |
from streetgeo.core.checkpoints import load_model
|
| 11 |
from streetgeo.core.config import TrainConfig
|
| 12 |
from streetgeo.datasets.images import load_image
|
|
|
|
| 14 |
|
| 15 |
def predict_images(model, image_paths, *, headings=None, top_k=5, google_coverage_only=False):
|
| 16 |
if not 1 <= len(image_paths) <= model.config.max_views:
|
| 17 |
+
raise UnsupportedViewCountError(model.config.max_views)
|
| 18 |
device = next(model.parameters()).device
|
| 19 |
+
images = torch.stack([load_image(path, model.config) for path in image_paths])
|
| 20 |
direction_tensor = None
|
| 21 |
if headings is not None:
|
| 22 |
if len(headings) != len(image_paths):
|
streetgeo/core/__init__.py
CHANGED
|
@@ -1,5 +1,11 @@
|
|
| 1 |
-
"""S.V.G.T. application package."""
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
class EmptyPredictionDomainError(ValueError):
|
| 5 |
-
"""No model-generated coordinate satisfies the selected prediction domain."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""S.V.G.T. application package."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class EmptyPredictionDomainError(ValueError):
|
| 5 |
+
"""No model-generated coordinate satisfies the selected prediction domain."""
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class UnsupportedViewCountError(ValueError):
|
| 9 |
+
def __init__(self, maximum):
|
| 10 |
+
self.maximum = maximum
|
| 11 |
+
super().__init__(f"provide 1..{maximum} images of the SAME location")
|
streetgeo/core/checkpoints.py
CHANGED
|
@@ -1,79 +1,85 @@
|
|
| 1 |
-
"""Versioned checkpoints carry the architecture, not just tensor weights."""
|
| 2 |
-
|
| 3 |
-
from dataclasses import asdict
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
import os
|
| 6 |
-
import random
|
| 7 |
-
import shutil
|
| 8 |
-
import tempfile
|
| 9 |
-
|
| 10 |
-
import torch
|
| 11 |
-
|
| 12 |
-
from streetgeo.core.config import ModelConfig
|
| 13 |
-
from streetgeo.core.model import StreetGeoModel
|
| 14 |
-
from streetgeo.paths import validate_checkpoint_path
|
| 15 |
-
|
| 16 |
-
ARCHITECTURE = "streetview_hierarchical_vit_v1"
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned checkpoints carry the architecture, not just tensor weights."""
|
| 2 |
+
|
| 3 |
+
from dataclasses import asdict
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import shutil
|
| 8 |
+
import tempfile
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
from streetgeo.core.config import LEGACY_BACKBONE, SIGLIP2_BACKBONE, ModelConfig
|
| 13 |
+
from streetgeo.core.model import StreetGeoModel
|
| 14 |
+
from streetgeo.paths import validate_checkpoint_path
|
| 15 |
+
|
| 16 |
+
ARCHITECTURE = "streetview_hierarchical_vit_v1"
|
| 17 |
+
SIGLIP2_ARCHITECTURE = "streetview_siglip2_nmpz_v2"
|
| 18 |
+
ARCHITECTURES = {LEGACY_BACKBONE: ARCHITECTURE, SIGLIP2_BACKBONE: SIGLIP2_ARCHITECTURE}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def resolve_device(name="auto"):
|
| 22 |
+
if name == "auto":
|
| 23 |
+
name = "cuda" if torch.cuda.is_available() else "cpu"
|
| 24 |
+
device = torch.device(name)
|
| 25 |
+
if device.type == "cuda" and not torch.cuda.is_available():
|
| 26 |
+
raise ValueError("CUDA was requested but is unavailable; use --device cpu")
|
| 27 |
+
return device
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def save_checkpoint(model, path, *, training_state=None, keep_previous=False):
|
| 31 |
+
"""Commit by atomic rename; a failed write leaves the old file usable."""
|
| 32 |
+
path = validate_checkpoint_path(path)
|
| 33 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 34 |
+
descriptor, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
|
| 35 |
+
try:
|
| 36 |
+
with os.fdopen(descriptor, "wb") as stream:
|
| 37 |
+
torch.save({"architecture": ARCHITECTURES[model.config.vision_backbone], "model_config": asdict(model.config),
|
| 38 |
+
"model_state_dict": model.state_dict(),
|
| 39 |
+
"training_state": training_state or {}}, stream)
|
| 40 |
+
stream.flush()
|
| 41 |
+
os.fsync(stream.fileno())
|
| 42 |
+
if keep_previous and path.exists():
|
| 43 |
+
previous = path.with_name(path.stem + ".previous" + path.suffix)
|
| 44 |
+
backup = str(temporary) + ".backup"
|
| 45 |
+
try:
|
| 46 |
+
shutil.copyfile(path, backup)
|
| 47 |
+
os.replace(backup, previous)
|
| 48 |
+
finally:
|
| 49 |
+
Path(backup).unlink(missing_ok=True)
|
| 50 |
+
os.replace(temporary, path)
|
| 51 |
+
finally:
|
| 52 |
+
Path(temporary).unlink(missing_ok=True)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def capture_rng_state():
|
| 56 |
+
return {"python": random.getstate(), "torch": torch.get_rng_state(),
|
| 57 |
+
"cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else []}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def restore_rng_state(state):
|
| 61 |
+
random.setstate(state["python"])
|
| 62 |
+
torch.set_rng_state(state["torch"].cpu())
|
| 63 |
+
if state["cuda"] and torch.cuda.is_available():
|
| 64 |
+
if len(state["cuda"]) != torch.cuda.device_count():
|
| 65 |
+
raise ValueError("CUDA device count changed; use the same devices for exact resume")
|
| 66 |
+
torch.cuda.set_rng_state_all([value.cpu() for value in state["cuda"]])
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def read_checkpoint(path, *, map_location="cpu"):
|
| 70 |
+
checkpoint = torch.load(path, map_location=map_location, weights_only=True)
|
| 71 |
+
if not isinstance(checkpoint, dict) or checkpoint.get("architecture") not in ARCHITECTURES.values():
|
| 72 |
+
raise ValueError("Expected an S.V.G.T. visual checkpoint; old text GPT weights are incompatible")
|
| 73 |
+
config = checkpoint.get("model_config")
|
| 74 |
+
if (not isinstance(config, dict)
|
| 75 |
+
or ARCHITECTURES.get(config.get("vision_backbone", LEGACY_BACKBONE)) != checkpoint["architecture"]):
|
| 76 |
+
raise ValueError("Checkpoint architecture and model config disagree")
|
| 77 |
+
return checkpoint
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def load_model(path, device="auto"):
|
| 81 |
+
device = resolve_device(device)
|
| 82 |
+
checkpoint = read_checkpoint(path)
|
| 83 |
+
model = StreetGeoModel(ModelConfig(**checkpoint["model_config"]))
|
| 84 |
+
model.load_state_dict(checkpoint["model_state_dict"], strict=True)
|
| 85 |
+
return model.to(device).eval()
|
streetgeo/core/config.py
CHANGED
|
@@ -1,6 +1,18 @@
|
|
| 1 |
"""Configuration shared by training, inference and saved checkpoints."""
|
| 2 |
|
| 3 |
from dataclasses import dataclass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
@dataclass
|
|
@@ -21,11 +33,16 @@ class ModelConfig:
|
|
| 21 |
cell_embed_dim: int = 128
|
| 22 |
offset_loss_weight: float = 1.0
|
| 23 |
spherical_loss_weight: float = 1.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
def __post_init__(self):
|
| 26 |
integer_fields = (
|
| 27 |
"image_size", "patch_size", "n_embed", "n_head", "n_layer",
|
| 28 |
-
"
|
| 29 |
"coarse_lat_bins", "coarse_lon_bins", "fine_bins", "cell_embed_dim",
|
| 30 |
)
|
| 31 |
for name in integer_fields:
|
|
@@ -40,6 +57,34 @@ class ModelConfig:
|
|
| 40 |
raise ValueError("dropout must be in [0, 1)")
|
| 41 |
if self.offset_loss_weight < 0 or self.spherical_loss_weight < 0:
|
| 42 |
raise ValueError("loss weights cannot be negative")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
@property
|
| 45 |
def coarse_cells(self):
|
|
|
|
| 1 |
"""Configuration shared by training, inference and saved checkpoints."""
|
| 2 |
|
| 3 |
from dataclasses import dataclass
|
| 4 |
+
import math
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
LEGACY_BACKBONE = "svgt_vit"
|
| 8 |
+
SIGLIP2_BACKBONE = "siglip2_base_patch16_224"
|
| 9 |
+
SIGLIP2_REPO = "google/siglip2-base-patch16-224"
|
| 10 |
+
SIGLIP2_REVISION = "75de2d55ec2d0b4efc50b3e9ad70dba96a7b2fa2"
|
| 11 |
+
LEGACY_PREPROCESSING = "svgt_letterbox_v1"
|
| 12 |
+
SIGLIP2_PREPROCESSING = "siglip2_resize_v1"
|
| 13 |
+
SIGLIP2_CONFIG_PATH = "configs/streetgeo_siglip2_nmpz.json"
|
| 14 |
+
SIGLIP2_MODEL_PATH = "checkpoints/streetgeo_siglip2_nmpz/best.pt"
|
| 15 |
+
SIGLIP2_WEIGHTS_PATH = "checkpoints/pretrained/siglip2-base-patch16-224/model.safetensors"
|
| 16 |
|
| 17 |
|
| 18 |
@dataclass
|
|
|
|
| 33 |
cell_embed_dim: int = 128
|
| 34 |
offset_loss_weight: float = 1.0
|
| 35 |
spherical_loss_weight: float = 1.0
|
| 36 |
+
vision_backbone: str = LEGACY_BACKBONE
|
| 37 |
+
backbone_revision: str | None = None
|
| 38 |
+
preprocessing: str | None = None
|
| 39 |
+
geo_smoothing: float = 0.0
|
| 40 |
+
geo_smoothing_km: float = 250.0
|
| 41 |
|
| 42 |
def __post_init__(self):
|
| 43 |
integer_fields = (
|
| 44 |
"image_size", "patch_size", "n_embed", "n_head", "n_layer",
|
| 45 |
+
"view_queries", "max_views", "mlp_ratio",
|
| 46 |
"coarse_lat_bins", "coarse_lon_bins", "fine_bins", "cell_embed_dim",
|
| 47 |
)
|
| 48 |
for name in integer_fields:
|
|
|
|
| 57 |
raise ValueError("dropout must be in [0, 1)")
|
| 58 |
if self.offset_loss_weight < 0 or self.spherical_loss_weight < 0:
|
| 59 |
raise ValueError("loss weights cannot be negative")
|
| 60 |
+
if not 0 <= self.geo_smoothing <= 0.5:
|
| 61 |
+
raise ValueError("geo_smoothing must be in [0, 0.5]")
|
| 62 |
+
if not math.isfinite(self.geo_smoothing_km) or self.geo_smoothing_km <= 0:
|
| 63 |
+
raise ValueError("geo_smoothing_km must be positive and finite")
|
| 64 |
+
if type(self.fusion_layers) is not int:
|
| 65 |
+
raise ValueError("fusion_layers must be an integer")
|
| 66 |
+
if self.vision_backbone == SIGLIP2_BACKBONE:
|
| 67 |
+
shape = (self.image_size, self.patch_size, self.n_embed, self.n_head, self.n_layer,
|
| 68 |
+
self.fusion_layers, self.view_queries, self.max_views, self.mlp_ratio)
|
| 69 |
+
if shape != (224, 16, 768, 12, 12, 0, 4, 1, 4):
|
| 70 |
+
raise ValueError("SigLIP2 NMPZ requires Base/16/224, four queries and one view without fusion")
|
| 71 |
+
if self.backbone_revision not in (None, SIGLIP2_REVISION):
|
| 72 |
+
raise ValueError("Unsupported SigLIP2 backbone revision")
|
| 73 |
+
self.backbone_revision = SIGLIP2_REVISION
|
| 74 |
+
expected_preprocessing = SIGLIP2_PREPROCESSING
|
| 75 |
+
elif self.vision_backbone == LEGACY_BACKBONE:
|
| 76 |
+
if self.fusion_layers <= 0 or self.backbone_revision is not None:
|
| 77 |
+
raise ValueError("The original visual encoder requires fusion layers and no backbone revision")
|
| 78 |
+
expected_preprocessing = LEGACY_PREPROCESSING
|
| 79 |
+
else:
|
| 80 |
+
raise ValueError(f"Unsupported vision backbone: {self.vision_backbone}")
|
| 81 |
+
if self.preprocessing not in (None, expected_preprocessing):
|
| 82 |
+
raise ValueError("Preprocessing does not match the vision backbone")
|
| 83 |
+
self.preprocessing = expected_preprocessing
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def is_siglip2(self):
|
| 87 |
+
return self.vision_backbone == SIGLIP2_BACKBONE
|
| 88 |
|
| 89 |
@property
|
| 90 |
def coarse_cells(self):
|
streetgeo/core/model.py
CHANGED
|
@@ -1,270 +1,312 @@
|
|
| 1 |
-
"""Street-view images -> hierarchical location hypotheses -> numeric coordinates.
|
| 2 |
-
|
| 3 |
-
Images must be preprocessed with streetgeo.datasets.images.load_image; optional headings are degrees
|
| 4 |
-
clockwise from north. This module never downloads weights or training data.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
from dataclasses import dataclass
|
| 8 |
-
import torch
|
| 9 |
-
from torch import nn
|
| 10 |
-
from torch.nn import functional as F
|
| 11 |
-
|
| 12 |
-
from streetgeo.core import EmptyPredictionDomainError
|
| 13 |
-
from streetgeo.core.config import ModelConfig
|
| 14 |
-
from streetgeo.core.geography import HierarchicalGeoGrid, LocationPrediction, coordinates_to_unit_vectors
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
class MultiHeadAttention(nn.Module):
|
| 18 |
-
"""Bidirectional self-attention; True in valid_mask means a real token."""
|
| 19 |
-
|
| 20 |
-
def __init__(self, config):
|
| 21 |
-
super().__init__()
|
| 22 |
-
self.n_head = config.n_head
|
| 23 |
-
self.head_size = config.n_embed // config.n_head
|
| 24 |
-
self.qkv = nn.Linear(config.n_embed, 3 * config.n_embed)
|
| 25 |
-
self.proj = nn.Linear(config.n_embed, config.n_embed)
|
| 26 |
-
self.dropout = config.dropout
|
| 27 |
-
|
| 28 |
-
def forward(self, x, valid_mask=None):
|
| 29 |
-
batch, length, width = x.shape
|
| 30 |
-
qkv = self.qkv(x).reshape(batch, length, 3, self.n_head, self.head_size)
|
| 31 |
-
q, k, v = qkv.permute(2, 0, 3, 1, 4).unbind(0)
|
| 32 |
-
mask = None if valid_mask is None else valid_mask[:, None, None, :]
|
| 33 |
-
attended = F.scaled_dot_product_attention(
|
| 34 |
-
q, k, v, attn_mask=mask, is_causal=False,
|
| 35 |
-
dropout_p=self.dropout if self.training else 0.0,
|
| 36 |
-
)
|
| 37 |
-
attended = attended.transpose(1, 2).reshape(batch, length, width)
|
| 38 |
-
return F.dropout(self.proj(attended), self.dropout, self.training)
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
class Block(nn.Module):
|
| 42 |
-
"""Preserve the original pre-norm Transformer residual structure."""
|
| 43 |
-
|
| 44 |
-
def __init__(self, config):
|
| 45 |
-
super().__init__()
|
| 46 |
-
self.ln1 = nn.LayerNorm(config.n_embed)
|
| 47 |
-
self.attention = MultiHeadAttention(config)
|
| 48 |
-
self.ln2 = nn.LayerNorm(config.n_embed)
|
| 49 |
-
self.ffn = nn.Sequential(
|
| 50 |
-
nn.Linear(config.n_embed, config.mlp_ratio * config.n_embed), nn.GELU(),
|
| 51 |
-
nn.Linear(config.mlp_ratio * config.n_embed, config.n_embed),
|
| 52 |
-
nn.Dropout(config.dropout),
|
| 53 |
-
)
|
| 54 |
-
|
| 55 |
-
def forward(self, x, valid_mask=None):
|
| 56 |
-
x = x + self.attention(self.ln1(x), valid_mask)
|
| 57 |
-
return x + self.ffn(self.ln2(x))
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
class StreetViewEncoder(nn.Module):
|
| 61 |
-
def __init__(self, config):
|
| 62 |
-
super().__init__()
|
| 63 |
-
self.config = config
|
| 64 |
-
patches = (config.image_size // config.patch_size) ** 2
|
| 65 |
-
self.patch_embedding = nn.Conv2d(
|
| 66 |
-
3, config.n_embed, kernel_size=config.patch_size, stride=config.patch_size,
|
| 67 |
-
)
|
| 68 |
-
self.position_embedding = nn.Parameter(torch.zeros(1, patches, config.n_embed))
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
self.
|
| 79 |
-
self.
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
x =
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
self.
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Street-view images -> hierarchical location hypotheses -> numeric coordinates.
|
| 2 |
+
|
| 3 |
+
Images must be preprocessed with streetgeo.datasets.images.load_image; optional headings are degrees
|
| 4 |
+
clockwise from north. This module never downloads weights or training data.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from dataclasses import dataclass, replace
|
| 8 |
+
import torch
|
| 9 |
+
from torch import nn
|
| 10 |
+
from torch.nn import functional as F
|
| 11 |
+
|
| 12 |
+
from streetgeo.core import EmptyPredictionDomainError
|
| 13 |
+
from streetgeo.core.config import ModelConfig
|
| 14 |
+
from streetgeo.core.geography import HierarchicalGeoGrid, LocationPrediction, coordinates_to_unit_vectors, haversine_km
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class MultiHeadAttention(nn.Module):
|
| 18 |
+
"""Bidirectional self-attention; True in valid_mask means a real token."""
|
| 19 |
+
|
| 20 |
+
def __init__(self, config):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.n_head = config.n_head
|
| 23 |
+
self.head_size = config.n_embed // config.n_head
|
| 24 |
+
self.qkv = nn.Linear(config.n_embed, 3 * config.n_embed)
|
| 25 |
+
self.proj = nn.Linear(config.n_embed, config.n_embed)
|
| 26 |
+
self.dropout = config.dropout
|
| 27 |
+
|
| 28 |
+
def forward(self, x, valid_mask=None):
|
| 29 |
+
batch, length, width = x.shape
|
| 30 |
+
qkv = self.qkv(x).reshape(batch, length, 3, self.n_head, self.head_size)
|
| 31 |
+
q, k, v = qkv.permute(2, 0, 3, 1, 4).unbind(0)
|
| 32 |
+
mask = None if valid_mask is None else valid_mask[:, None, None, :]
|
| 33 |
+
attended = F.scaled_dot_product_attention(
|
| 34 |
+
q, k, v, attn_mask=mask, is_causal=False,
|
| 35 |
+
dropout_p=self.dropout if self.training else 0.0,
|
| 36 |
+
)
|
| 37 |
+
attended = attended.transpose(1, 2).reshape(batch, length, width)
|
| 38 |
+
return F.dropout(self.proj(attended), self.dropout, self.training)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Block(nn.Module):
|
| 42 |
+
"""Preserve the original pre-norm Transformer residual structure."""
|
| 43 |
+
|
| 44 |
+
def __init__(self, config, *, layer_norm_eps=1e-5, gelu_approximation="none"):
|
| 45 |
+
super().__init__()
|
| 46 |
+
self.ln1 = nn.LayerNorm(config.n_embed, eps=layer_norm_eps)
|
| 47 |
+
self.attention = MultiHeadAttention(config)
|
| 48 |
+
self.ln2 = nn.LayerNorm(config.n_embed, eps=layer_norm_eps)
|
| 49 |
+
self.ffn = nn.Sequential(
|
| 50 |
+
nn.Linear(config.n_embed, config.mlp_ratio * config.n_embed), nn.GELU(approximate=gelu_approximation),
|
| 51 |
+
nn.Linear(config.mlp_ratio * config.n_embed, config.n_embed),
|
| 52 |
+
nn.Dropout(config.dropout),
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def forward(self, x, valid_mask=None):
|
| 56 |
+
x = x + self.attention(self.ln1(x), valid_mask)
|
| 57 |
+
return x + self.ffn(self.ln2(x))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class StreetViewEncoder(nn.Module):
|
| 61 |
+
def __init__(self, config):
|
| 62 |
+
super().__init__()
|
| 63 |
+
self.config = config
|
| 64 |
+
patches = (config.image_size // config.patch_size) ** 2
|
| 65 |
+
self.patch_embedding = nn.Conv2d(
|
| 66 |
+
3, config.n_embed, kernel_size=config.patch_size, stride=config.patch_size,
|
| 67 |
+
)
|
| 68 |
+
self.position_embedding = nn.Parameter(torch.zeros(1, patches, config.n_embed))
|
| 69 |
+
# SigLIP2 FixRes uses the SigLIP vision blocks with zero dropout,
|
| 70 |
+
# tanh-approximate GELU and a different LayerNorm epsilon.
|
| 71 |
+
vision = replace(config, dropout=0.0) if config.is_siglip2 else config
|
| 72 |
+
epsilon = 1e-6 if config.is_siglip2 else 1e-5
|
| 73 |
+
activation = "tanh" if config.is_siglip2 else "none"
|
| 74 |
+
self.visual_blocks = nn.ModuleList([
|
| 75 |
+
Block(vision, layer_norm_eps=epsilon, gelu_approximation=activation) for _ in range(config.n_layer)
|
| 76 |
+
])
|
| 77 |
+
self.visual_norm = nn.LayerNorm(config.n_embed, eps=epsilon)
|
| 78 |
+
self.pool_queries = nn.Parameter(torch.zeros(1, config.view_queries, config.n_embed))
|
| 79 |
+
self.pool_attention = nn.MultiheadAttention(
|
| 80 |
+
config.n_embed, config.n_head, dropout=config.dropout, batch_first=True,
|
| 81 |
+
)
|
| 82 |
+
if config.is_siglip2:
|
| 83 |
+
self.pool_projection = nn.Linear(config.view_queries * config.n_embed, config.n_embed)
|
| 84 |
+
self.pool_mlp = nn.Sequential(
|
| 85 |
+
nn.LayerNorm(config.n_embed),
|
| 86 |
+
nn.Linear(config.n_embed, 2 * config.n_embed), nn.GELU(),
|
| 87 |
+
nn.Linear(2 * config.n_embed, config.n_embed),
|
| 88 |
+
)
|
| 89 |
+
self.pool_norm = nn.LayerNorm(config.n_embed)
|
| 90 |
+
else:
|
| 91 |
+
# No view-index embedding: unordered views remain permutation invariant.
|
| 92 |
+
self.heading_embedding = nn.Sequential(nn.Linear(3, config.n_embed), nn.GELU(),
|
| 93 |
+
nn.Linear(config.n_embed, config.n_embed))
|
| 94 |
+
self.geo_token = nn.Parameter(torch.zeros(1, 1, config.n_embed))
|
| 95 |
+
self.fusion_blocks = nn.ModuleList([Block(config) for _ in range(config.fusion_layers)])
|
| 96 |
+
self.fusion_norm = nn.LayerNorm(config.n_embed)
|
| 97 |
+
|
| 98 |
+
def visual_tokens(self, images):
|
| 99 |
+
x = self.patch_embedding(images).flatten(2).transpose(1, 2) + self.position_embedding
|
| 100 |
+
for block in self.visual_blocks:
|
| 101 |
+
x = block(x)
|
| 102 |
+
return self.visual_norm(x)
|
| 103 |
+
|
| 104 |
+
def forward(self, images, view_mask=None, headings=None):
|
| 105 |
+
if images.ndim == 4:
|
| 106 |
+
images = images.unsqueeze(1)
|
| 107 |
+
size = self.config.image_size
|
| 108 |
+
if images.ndim != 5 or tuple(images.shape[2:]) != (3, size, size):
|
| 109 |
+
raise ValueError(f"images must have shape (B, 3, {size}, {size}) or (B, V, 3, {size}, {size})")
|
| 110 |
+
batch, views = images.shape[:2]
|
| 111 |
+
if batch == 0 or not 1 <= views <= self.config.max_views:
|
| 112 |
+
raise ValueError(f"nonempty batch and 1..{self.config.max_views} views required")
|
| 113 |
+
if not images.is_floating_point():
|
| 114 |
+
raise ValueError("images must be normalized floating-point RGB tensors")
|
| 115 |
+
if view_mask is None:
|
| 116 |
+
view_mask = torch.ones(batch, views, dtype=torch.bool, device=images.device)
|
| 117 |
+
elif view_mask.shape != (batch, views) or view_mask.dtype != torch.bool:
|
| 118 |
+
raise ValueError("view_mask must be boolean with shape (B, V)")
|
| 119 |
+
view_mask = view_mask.to(images.device)
|
| 120 |
+
if not view_mask.any(dim=1).all():
|
| 121 |
+
raise ValueError("every sample needs at least one valid view")
|
| 122 |
+
# Only valid views are encoded, so padding cannot contaminate gradients.
|
| 123 |
+
valid_images = images[view_mask]
|
| 124 |
+
if not torch.isfinite(valid_images).all():
|
| 125 |
+
raise ValueError("valid images must contain finite values")
|
| 126 |
+
x = self.visual_tokens(valid_images)
|
| 127 |
+
queries = self.pool_queries.expand(x.shape[0], -1, -1)
|
| 128 |
+
pooled, _ = self.pool_attention(queries, x, x, need_weights=False)
|
| 129 |
+
pooled = pooled + queries
|
| 130 |
+
if self.config.is_siglip2:
|
| 131 |
+
projected = self.pool_projection(pooled.flatten(1))
|
| 132 |
+
return self.pool_norm(projected + self.pool_mlp(projected))
|
| 133 |
+
tokens = pooled.new_zeros(batch, views, self.config.view_queries, self.config.n_embed)
|
| 134 |
+
tokens[view_mask] = pooled
|
| 135 |
+
if headings is None:
|
| 136 |
+
headings = torch.full((batch, views), float("nan"), device=images.device)
|
| 137 |
+
elif headings.shape != (batch, views):
|
| 138 |
+
raise ValueError("headings must have shape (B, V); NaN means unknown")
|
| 139 |
+
headings = headings.to(device=images.device, dtype=torch.float32)
|
| 140 |
+
if torch.isinf(headings[view_mask]).any():
|
| 141 |
+
raise ValueError("headings must be finite or NaN (unknown)")
|
| 142 |
+
known = torch.isfinite(headings) & view_mask
|
| 143 |
+
angle = torch.deg2rad(torch.where(known, headings, 0.0).remainder(360))
|
| 144 |
+
features = torch.stack((angle.sin() * known, angle.cos() * known, known.float()), -1)
|
| 145 |
+
tokens = tokens + self.heading_embedding(features).unsqueeze(2)
|
| 146 |
+
tokens = tokens.flatten(1, 2)
|
| 147 |
+
x = torch.cat((self.geo_token.expand(batch, -1, -1), tokens), dim=1)
|
| 148 |
+
valid = torch.cat((torch.ones(batch, 1, dtype=torch.bool, device=images.device),
|
| 149 |
+
view_mask.repeat_interleave(self.config.view_queries, dim=1)), dim=1)
|
| 150 |
+
for block in self.fusion_blocks:
|
| 151 |
+
x = block(x, valid)
|
| 152 |
+
return self.fusion_norm(x[:, 0])
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@dataclass
|
| 156 |
+
class GeolocationOutput:
|
| 157 |
+
coordinates: torch.Tensor # (B, 2), highest-probability candidate
|
| 158 |
+
candidate_coordinates: torch.Tensor # (B, K, 2)
|
| 159 |
+
candidate_probabilities: torch.Tensor # (B, K), probabilities over ALL cells
|
| 160 |
+
candidate_cell_ids: torch.Tensor # (B, K)
|
| 161 |
+
coarse_logits: torch.Tensor # (B, coarse_cells)
|
| 162 |
+
fine_logits: torch.Tensor # (B, coarse_cells, children_per_cell)
|
| 163 |
+
embedding: torch.Tensor # (B, n_embed), for future retrieval
|
| 164 |
+
loss: torch.Tensor | None
|
| 165 |
+
loss_components: dict[str, torch.Tensor]
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class StreetGeoModel(nn.Module):
|
| 169 |
+
def __init__(self, config=None):
|
| 170 |
+
super().__init__()
|
| 171 |
+
self.config = config or ModelConfig()
|
| 172 |
+
cfg = self.config
|
| 173 |
+
self.grid = HierarchicalGeoGrid(cfg)
|
| 174 |
+
if cfg.geo_smoothing:
|
| 175 |
+
cell_ids = torch.arange(cfg.total_cells)
|
| 176 |
+
centers = self.grid.decode(cell_ids, torch.zeros(cfg.total_cells, 2))
|
| 177 |
+
self.register_buffer("cell_centers", centers, persistent=False)
|
| 178 |
+
self.encoder = StreetViewEncoder(cfg)
|
| 179 |
+
self.coarse_head = nn.Linear(cfg.n_embed, cfg.coarse_cells)
|
| 180 |
+
self.fine_head = nn.Linear(cfg.n_embed, cfg.total_cells)
|
| 181 |
+
self.cell_embedding = nn.Embedding(cfg.total_cells, cfg.cell_embed_dim)
|
| 182 |
+
self.offset_head = nn.Sequential(
|
| 183 |
+
nn.Linear(cfg.n_embed + cfg.cell_embed_dim, cfg.n_embed), nn.GELU(),
|
| 184 |
+
nn.Linear(cfg.n_embed, 2), nn.Tanh(),
|
| 185 |
+
)
|
| 186 |
+
self.apply(self._init_weights)
|
| 187 |
+
parameters = (self.encoder.position_embedding, self.encoder.pool_queries)
|
| 188 |
+
if not cfg.is_siglip2:
|
| 189 |
+
parameters += (self.encoder.geo_token,)
|
| 190 |
+
for parameter in parameters:
|
| 191 |
+
nn.init.trunc_normal_(parameter, std=0.02)
|
| 192 |
+
|
| 193 |
+
def _smooth_cell_loss(self, log_probs, targets, true_ids):
|
| 194 |
+
with torch.no_grad():
|
| 195 |
+
temperature = self.config.geo_smoothing_km
|
| 196 |
+
distance = haversine_km(targets[:, None, :], self.cell_centers)
|
| 197 |
+
# Restrict the soft target to a local neighborhood. Always retain
|
| 198 |
+
# the true cell, including when its center is outside the radius.
|
| 199 |
+
excluded = (distance > 3 * temperature).scatter_(1, true_ids[:, None], False)
|
| 200 |
+
local_distance = distance.masked_fill(excluded, torch.inf)
|
| 201 |
+
relative = local_distance - local_distance.amin(dim=-1, keepdim=True)
|
| 202 |
+
weights = (-relative / temperature).float().softmax(dim=-1)
|
| 203 |
+
return -(weights * log_probs).sum(dim=-1).mean()
|
| 204 |
+
|
| 205 |
+
@staticmethod
|
| 206 |
+
def _init_weights(module):
|
| 207 |
+
if isinstance(module, (nn.Linear, nn.Conv2d, nn.Embedding)):
|
| 208 |
+
nn.init.trunc_normal_(module.weight, std=0.02)
|
| 209 |
+
if getattr(module, "bias", None) is not None:
|
| 210 |
+
nn.init.zeros_(module.bias)
|
| 211 |
+
|
| 212 |
+
def _offsets(self, embedding, cell_ids):
|
| 213 |
+
visual = embedding.unsqueeze(1).expand(-1, cell_ids.shape[1], -1)
|
| 214 |
+
return self.offset_head(torch.cat((visual, self.cell_embedding(cell_ids)), dim=-1))
|
| 215 |
+
|
| 216 |
+
def _rank_candidates(self, embedding, log_probs, top_k, coordinate_filter=None):
|
| 217 |
+
if coordinate_filter is None:
|
| 218 |
+
values, cell_ids = log_probs.topk(top_k, dim=-1)
|
| 219 |
+
coordinates = self.grid.decode(cell_ids, self._offsets(embedding, cell_ids))
|
| 220 |
+
return values, cell_ids, coordinates
|
| 221 |
+
# Scan in probability order with bounded offset-head memory. Filtering the
|
| 222 |
+
# original top five alone could miss every valid lower-ranked candidate.
|
| 223 |
+
order = log_probs.argsort(dim=-1, descending=True, stable=True)
|
| 224 |
+
selected_ids, selected_coordinates = [], []
|
| 225 |
+
for sample in range(embedding.shape[0]):
|
| 226 |
+
kept_ids, kept_coordinates = [], []
|
| 227 |
+
count = 0
|
| 228 |
+
for start in range(0, order.shape[1], 256):
|
| 229 |
+
ids = order[sample:sample + 1, start:start + 256]
|
| 230 |
+
coordinates = self.grid.decode(ids, self._offsets(embedding[sample:sample + 1], ids))
|
| 231 |
+
mask = torch.as_tensor(coordinate_filter(coordinates[0].detach().cpu().numpy()),
|
| 232 |
+
dtype=torch.bool, device=ids.device)
|
| 233 |
+
if mask.shape != ids[0].shape:
|
| 234 |
+
raise ValueError("coordinate filter must return one boolean per coordinate")
|
| 235 |
+
kept_ids.append(ids[0, mask])
|
| 236 |
+
kept_coordinates.append(coordinates[0, mask])
|
| 237 |
+
count += int(mask.sum())
|
| 238 |
+
if count >= top_k:
|
| 239 |
+
break
|
| 240 |
+
if not count:
|
| 241 |
+
raise EmptyPredictionDomainError("No predicted coordinates fall inside the selected coverage domain")
|
| 242 |
+
selected_ids.append(torch.cat(kept_ids)[:top_k])
|
| 243 |
+
selected_coordinates.append(torch.cat(kept_coordinates)[:top_k])
|
| 244 |
+
# Tiny/custom grids can have fewer than top_k eligible locations.
|
| 245 |
+
size = min(len(ids) for ids in selected_ids)
|
| 246 |
+
ids = torch.stack([ids[:size] for ids in selected_ids])
|
| 247 |
+
coordinates = torch.stack([coords[:size] for coords in selected_coordinates])
|
| 248 |
+
return log_probs.gather(1, ids), ids, coordinates
|
| 249 |
+
|
| 250 |
+
def forward(self, images, targets=None, *, view_mask=None, headings=None, top_k=5,
|
| 251 |
+
coordinate_filter=None):
|
| 252 |
+
if type(top_k) is not int or not 1 <= top_k <= self.config.total_cells:
|
| 253 |
+
raise ValueError(f"top_k must be an integer in [1, {self.config.total_cells}]")
|
| 254 |
+
embedding = self.encoder(images, view_mask, headings)
|
| 255 |
+
return self.forward_embedding(embedding, targets, top_k=top_k, coordinate_filter=coordinate_filter)
|
| 256 |
+
|
| 257 |
+
def forward_embedding(self, embedding, targets=None, *, top_k=5, coordinate_filter=None):
|
| 258 |
+
"""Run the geographic heads on features from this model's frozen encoder."""
|
| 259 |
+
if type(top_k) is not int or not 1 <= top_k <= self.config.total_cells:
|
| 260 |
+
raise ValueError(f"top_k must be an integer in [1, {self.config.total_cells}]")
|
| 261 |
+
if embedding.ndim != 2 or embedding.shape[1] != self.config.n_embed:
|
| 262 |
+
raise ValueError("embedding must have shape [batch, n_embed]")
|
| 263 |
+
batch = embedding.shape[0]
|
| 264 |
+
coarse = self.coarse_head(embedding)
|
| 265 |
+
fine = self.fine_head(embedding).reshape(batch, self.config.coarse_cells, -1)
|
| 266 |
+
# Exact joint probabilities over all leaves, without pruning coarse cells.
|
| 267 |
+
log_probs = F.log_softmax(coarse.float(), -1).unsqueeze(-1)
|
| 268 |
+
log_probs = (log_probs + F.log_softmax(fine.float(), -1)).flatten(1)
|
| 269 |
+
values, cell_ids, coordinates = self._rank_candidates(embedding, log_probs, top_k, coordinate_filter)
|
| 270 |
+
losses = {}
|
| 271 |
+
loss = None
|
| 272 |
+
if targets is not None:
|
| 273 |
+
if targets.shape != (batch, 2):
|
| 274 |
+
raise ValueError("targets must have shape (B, 2): latitude, longitude")
|
| 275 |
+
targets = targets.to(device=embedding.device, dtype=torch.float32)
|
| 276 |
+
parent, child, target_offsets = self.grid.encode(targets)
|
| 277 |
+
true_ids = parent * self.config.children_per_cell + child
|
| 278 |
+
# Teacher forcing trains the true cell even when classification is wrong.
|
| 279 |
+
offsets = self._offsets(embedding, true_ids.unsqueeze(1)).squeeze(1).float()
|
| 280 |
+
predicted_xyz = self.grid.unit_vectors(true_ids, offsets)
|
| 281 |
+
target_xyz = coordinates_to_unit_vectors(targets)
|
| 282 |
+
losses = {
|
| 283 |
+
"coarse": F.cross_entropy(coarse.float(), parent),
|
| 284 |
+
"fine": F.cross_entropy(fine[torch.arange(batch, device=embedding.device), parent].float(), child),
|
| 285 |
+
"offset": F.smooth_l1_loss(offsets, target_offsets),
|
| 286 |
+
"spherical": torch.linalg.vector_norm(predicted_xyz - target_xyz, dim=-1).mean(),
|
| 287 |
+
}
|
| 288 |
+
classification = losses["coarse"] + losses["fine"]
|
| 289 |
+
if self.config.geo_smoothing:
|
| 290 |
+
losses["geo_smoothing"] = self._smooth_cell_loss(log_probs, targets, true_ids)
|
| 291 |
+
classification = torch.lerp(classification, losses["geo_smoothing"], self.config.geo_smoothing)
|
| 292 |
+
loss = (classification + self.config.offset_loss_weight * losses["offset"]
|
| 293 |
+
+ self.config.spherical_loss_weight * losses["spherical"])
|
| 294 |
+
return GeolocationOutput(coordinates[:, 0], coordinates, values.exp(), cell_ids,
|
| 295 |
+
coarse, fine, F.normalize(embedding, dim=-1), loss, losses)
|
| 296 |
+
|
| 297 |
+
@torch.inference_mode()
|
| 298 |
+
def predict(self, images, *, view_mask=None, headings=None, top_k=5, coordinate_filter=None):
|
| 299 |
+
"""One ranked list per sample. Restores the caller's train/eval state."""
|
| 300 |
+
was_training = self.training
|
| 301 |
+
self.eval()
|
| 302 |
+
try:
|
| 303 |
+
output = self(images, view_mask=view_mask, headings=headings, top_k=top_k,
|
| 304 |
+
coordinate_filter=coordinate_filter)
|
| 305 |
+
coords = output.candidate_coordinates.cpu().tolist()
|
| 306 |
+
probs = output.candidate_probabilities.cpu().tolist()
|
| 307 |
+
ids = output.candidate_cell_ids.cpu().tolist()
|
| 308 |
+
return [[LocationPrediction(lat, lon, prob, cell)
|
| 309 |
+
for (lat, lon), prob, cell in zip(sample, scores, cells)]
|
| 310 |
+
for sample, scores, cells in zip(coords, probs, ids)]
|
| 311 |
+
finally:
|
| 312 |
+
self.train(was_training)
|
streetgeo/datasets/images.py
CHANGED
|
@@ -1,171 +1,191 @@
|
|
| 1 |
-
"""Local image preprocessing and JSONL manifests. No network access."""
|
| 2 |
-
|
| 3 |
-
import json
|
| 4 |
-
import math
|
| 5 |
-
from pathlib import Path
|
| 6 |
-
|
| 7 |
-
import torch
|
| 8 |
-
from PIL import Image, ImageOps
|
| 9 |
-
from torch.utils.data import Dataset
|
| 10 |
-
|
| 11 |
-
from streetgeo.core.config import ModelConfig
|
| 12 |
-
from streetgeo.datasets.policy import require_mapillary_row
|
| 13 |
-
from streetgeo.datasets.road_mask import RoadMask, MASK_FILL
|
| 14 |
-
|
| 15 |
-
IMAGE_MEAN = (0.485, 0.456, 0.406)
|
| 16 |
-
IMAGE_STD = (0.229, 0.224, 0.225)
|
| 17 |
-
IMAGE_FILL = MASK_FILL
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
if not isinstance(
|
| 93 |
-
raise ValueError("
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
(
|
| 101 |
-
))
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
if
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
if
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local image preprocessing and JSONL manifests. No network access."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from PIL import Image, ImageOps
|
| 9 |
+
from torch.utils.data import Dataset
|
| 10 |
+
|
| 11 |
+
from streetgeo.core.config import SIGLIP2_PREPROCESSING, ModelConfig
|
| 12 |
+
from streetgeo.datasets.policy import require_mapillary_row
|
| 13 |
+
from streetgeo.datasets.road_mask import RoadMask, MASK_FILL
|
| 14 |
+
|
| 15 |
+
IMAGE_MEAN = (0.485, 0.456, 0.406)
|
| 16 |
+
IMAGE_STD = (0.229, 0.224, 0.225)
|
| 17 |
+
IMAGE_FILL = MASK_FILL
|
| 18 |
+
SIGLIP2_MEAN_STD = (0.5, 0.5, 0.5)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def image_statistics(preprocessing):
|
| 22 |
+
if preprocessing == SIGLIP2_PREPROCESSING:
|
| 23 |
+
return SIGLIP2_MEAN_STD, SIGLIP2_MEAN_STD
|
| 24 |
+
return IMAGE_MEAN, IMAGE_STD
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def manifest_lines(path):
|
| 28 |
+
"""Stream large imported datasets instead of keeping another full text copy."""
|
| 29 |
+
with path.open(encoding="utf-8-sig") as stream:
|
| 30 |
+
yield from enumerate(stream, 1)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def load_image(path, image_size=224, *, road_mask=None, mask_bottom_third=False):
|
| 34 |
+
"""RGB and EXIF orientation, then the checkpoint's resize and normalization.
|
| 35 |
+
|
| 36 |
+
Avoid random horizontal flips: they can reverse driving-side/sign clues.
|
| 37 |
+
Training and inference always use exactly the same preprocessing.
|
| 38 |
+
"""
|
| 39 |
+
preprocessing = None
|
| 40 |
+
if isinstance(image_size, ModelConfig):
|
| 41 |
+
preprocessing, image_size = image_size.preprocessing, image_size.image_size
|
| 42 |
+
with Image.open(path) as source:
|
| 43 |
+
image = ImageOps.exif_transpose(source).convert("RGB")
|
| 44 |
+
if road_mask is not None and mask_bottom_third:
|
| 45 |
+
raise ValueError("choose one environment mask shape")
|
| 46 |
+
if road_mask is not None:
|
| 47 |
+
image = road_mask.apply(image)
|
| 48 |
+
if mask_bottom_third:
|
| 49 |
+
# Retained only to resume checkpoints created with recipe version 1.
|
| 50 |
+
image.paste(IMAGE_FILL, (0, image.height * 2 // 3, image.width, image.height))
|
| 51 |
+
if preprocessing == SIGLIP2_PREPROCESSING:
|
| 52 |
+
image = image.resize((image_size, image_size), resample=Image.Resampling.BILINEAR)
|
| 53 |
+
else:
|
| 54 |
+
image = ImageOps.pad(image, (image_size, image_size),
|
| 55 |
+
method=Image.Resampling.BICUBIC, color=IMAGE_FILL)
|
| 56 |
+
pixels = torch.frombuffer(bytearray(image.tobytes()), dtype=torch.uint8)
|
| 57 |
+
pixels = pixels.reshape(image_size, image_size, 3).permute(2, 0, 1).float() / 255
|
| 58 |
+
mean, std = image_statistics(preprocessing)
|
| 59 |
+
mean = pixels.new_tensor(mean).view(3, 1, 1)
|
| 60 |
+
std = pixels.new_tensor(std).view(3, 1, 1)
|
| 61 |
+
return (pixels - mean) / std
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class StreetViewDataset(Dataset):
|
| 65 |
+
"""Each JSONL row is one location with 1..max_views local image paths.
|
| 66 |
+
|
| 67 |
+
{"images": ["front.jpg", "back.jpg"], "latitude": 34.0,
|
| 68 |
+
"longitude": -118.0, "headings": [0, 180]}
|
| 69 |
+
|
| 70 |
+
A single view may use "image": "front.jpg". Headings are optional and may
|
| 71 |
+
contain null for unknown directions. Relative paths resolve beside JSONL.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(self, manifest_path, config=None, *, mapillary_only=False, environment_specialist=False,
|
| 75 |
+
road_mask=None, legacy_environment_mask=False):
|
| 76 |
+
self.config = config or ModelConfig()
|
| 77 |
+
self.environment_specialist = environment_specialist
|
| 78 |
+
self.road_mask = road_mask if road_mask is not None else RoadMask()
|
| 79 |
+
self.legacy_environment_mask = legacy_environment_mask
|
| 80 |
+
manifest = Path(manifest_path).resolve()
|
| 81 |
+
self.samples = []
|
| 82 |
+
self.climate_targets = None
|
| 83 |
+
self.source_counts = {}
|
| 84 |
+
self.geographic_bounds = {"south": 90.0, "north": -90.0, "west": 180.0, "east": -180.0}
|
| 85 |
+
for line_number, line in manifest_lines(manifest):
|
| 86 |
+
if not line.strip():
|
| 87 |
+
continue
|
| 88 |
+
try:
|
| 89 |
+
row = json.loads(line)
|
| 90 |
+
if mapillary_only:
|
| 91 |
+
require_mapillary_row(row)
|
| 92 |
+
if not isinstance(row, dict):
|
| 93 |
+
raise ValueError("each row must be a JSON object")
|
| 94 |
+
if "images" in row and "image" in row:
|
| 95 |
+
raise ValueError("use either image or images")
|
| 96 |
+
paths = row.get("images", [row["image"]] if "image" in row else [])
|
| 97 |
+
if not isinstance(paths, list) or not 1 <= len(paths) <= self.config.max_views:
|
| 98 |
+
raise ValueError(f"provide 1..{self.config.max_views} image paths")
|
| 99 |
+
if not all(isinstance(path, str) and path for path in paths):
|
| 100 |
+
raise ValueError("image paths must be nonempty strings")
|
| 101 |
+
latitude, longitude = float(row["latitude"]), float(row["longitude"])
|
| 102 |
+
if not math.isfinite(latitude) or not -90 <= latitude <= 90:
|
| 103 |
+
raise ValueError("latitude must be finite and in [-90, 90]")
|
| 104 |
+
if not math.isfinite(longitude) or not -180 <= longitude <= 180:
|
| 105 |
+
raise ValueError("longitude must be finite and in [-180, 180]")
|
| 106 |
+
headings = row.get("headings", [None] * len(paths))
|
| 107 |
+
if not isinstance(headings, list) or len(headings) != len(paths):
|
| 108 |
+
raise ValueError("headings must match the number of images")
|
| 109 |
+
headings = [float("nan") if value is None else float(value) for value in headings]
|
| 110 |
+
for original, value in zip(row.get("headings", [None] * len(paths)), headings):
|
| 111 |
+
if original is not None and not math.isfinite(value):
|
| 112 |
+
raise ValueError("headings must be finite numbers or null")
|
| 113 |
+
self.samples.append((
|
| 114 |
+
[manifest.parent / path for path in paths],
|
| 115 |
+
(latitude, longitude), headings,
|
| 116 |
+
))
|
| 117 |
+
source = str(row.get("source", "Mapillary" if "mapillary_id" in row else "custom"))
|
| 118 |
+
self.source_counts[source] = self.source_counts.get(source, 0) + 1
|
| 119 |
+
bounds = self.geographic_bounds
|
| 120 |
+
bounds["south"], bounds["north"] = min(bounds["south"], latitude), max(bounds["north"], latitude)
|
| 121 |
+
bounds["west"], bounds["east"] = min(bounds["west"], longitude), max(bounds["east"], longitude)
|
| 122 |
+
except (ValueError, TypeError, KeyError) as error:
|
| 123 |
+
raise ValueError(f"{manifest}:{line_number}: {error}") from error
|
| 124 |
+
if not self.samples:
|
| 125 |
+
raise ValueError("manifest contains no samples")
|
| 126 |
+
|
| 127 |
+
def __len__(self):
|
| 128 |
+
return len(self.samples)
|
| 129 |
+
|
| 130 |
+
def __getitem__(self, index):
|
| 131 |
+
phase = None
|
| 132 |
+
if isinstance(index, tuple):
|
| 133 |
+
index, phase = index
|
| 134 |
+
if not self.environment_specialist or phase not in (0, 1):
|
| 135 |
+
raise ValueError("invalid environment training phase")
|
| 136 |
+
paths, coordinates, headings = self.samples[index]
|
| 137 |
+
# Workers spawned by an already-running version-1 trainer may unpickle
|
| 138 |
+
# a dataset created before these shape attributes existed.
|
| 139 |
+
legacy = getattr(self, "legacy_environment_mask", True)
|
| 140 |
+
sample = {
|
| 141 |
+
"images": torch.stack([load_image(path, self.config,
|
| 142 |
+
road_mask=self.road_mask if phase == 1 and not legacy else None,
|
| 143 |
+
mask_bottom_third=phase == 1 and legacy) for path in paths]),
|
| 144 |
+
"coordinates": torch.tensor(coordinates, dtype=torch.float32),
|
| 145 |
+
"headings": torch.tensor(headings, dtype=torch.float32),
|
| 146 |
+
}
|
| 147 |
+
if phase is not None:
|
| 148 |
+
sample["training_phase"] = phase
|
| 149 |
+
climate_targets = getattr(self, "climate_targets", None)
|
| 150 |
+
if climate_targets is not None:
|
| 151 |
+
sample["climate_target"] = climate_targets[index]
|
| 152 |
+
return sample
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class EnvironmentViewDataset(Dataset):
|
| 156 |
+
"""Reuse a validated dataset for masked evaluation without copying its metadata."""
|
| 157 |
+
def __init__(self, dataset):
|
| 158 |
+
self.dataset = dataset
|
| 159 |
+
|
| 160 |
+
def __len__(self):
|
| 161 |
+
return len(self.dataset)
|
| 162 |
+
|
| 163 |
+
def __getitem__(self, index):
|
| 164 |
+
return self.dataset[index, 1]
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def collate_streetviews(samples):
|
| 168 |
+
"""Pad view counts and explicitly mask padded views."""
|
| 169 |
+
if not samples:
|
| 170 |
+
raise ValueError("cannot collate an empty batch")
|
| 171 |
+
views = max(sample["images"].shape[0] for sample in samples)
|
| 172 |
+
batch = len(samples)
|
| 173 |
+
shape = samples[0]["images"].shape[1:]
|
| 174 |
+
images = samples[0]["images"].new_zeros(batch, views, *shape)
|
| 175 |
+
mask = torch.zeros(batch, views, dtype=torch.bool)
|
| 176 |
+
headings = torch.full((batch, views), float("nan"))
|
| 177 |
+
for index, sample in enumerate(samples):
|
| 178 |
+
count = sample["images"].shape[0]
|
| 179 |
+
images[index, :count] = sample["images"]
|
| 180 |
+
mask[index, :count] = True
|
| 181 |
+
headings[index, :count] = sample["headings"]
|
| 182 |
+
result = {"images": images, "view_mask": mask, "headings": headings,
|
| 183 |
+
"targets": torch.stack([sample["coordinates"] for sample in samples])}
|
| 184 |
+
if "climate_target" in samples[0]:
|
| 185 |
+
result["climate_targets"] = torch.tensor([sample["climate_target"] for sample in samples], dtype=torch.long)
|
| 186 |
+
phases = {sample.get("training_phase") for sample in samples}
|
| 187 |
+
if len(phases) != 1:
|
| 188 |
+
raise ValueError("a batch must contain exactly one training phase")
|
| 189 |
+
if phases != {None}:
|
| 190 |
+
result["training_phase"] = torch.tensor(phases.pop())
|
| 191 |
+
return result
|
streetgeo/inference/predict.py
CHANGED
|
@@ -1,59 +1,60 @@
|
|
| 1 |
-
"""Predict one location from one or more local street-view images."""
|
| 2 |
-
|
| 3 |
-
import argparse
|
| 4 |
-
import json
|
| 5 |
-
import math
|
| 6 |
-
|
| 7 |
-
import torch
|
| 8 |
-
|
| 9 |
-
from streetgeo.core
|
| 10 |
-
from streetgeo.core.
|
| 11 |
-
from streetgeo.
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
parser
|
| 37 |
-
parser.add_argument("
|
| 38 |
-
parser.add_argument("--
|
| 39 |
-
parser.add_argument("--
|
| 40 |
-
parser.add_argument("--
|
| 41 |
-
parser.add_argument("--
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
"
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
| 1 |
+
"""Predict one location from one or more local street-view images."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import math
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
from streetgeo.core import UnsupportedViewCountError
|
| 10 |
+
from streetgeo.core.checkpoints import load_model
|
| 11 |
+
from streetgeo.core.config import TrainConfig
|
| 12 |
+
from streetgeo.datasets.images import load_image
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def predict_images(model, image_paths, *, headings=None, top_k=5, google_coverage_only=False):
|
| 16 |
+
if not 1 <= len(image_paths) <= model.config.max_views:
|
| 17 |
+
raise UnsupportedViewCountError(model.config.max_views)
|
| 18 |
+
device = next(model.parameters()).device
|
| 19 |
+
images = torch.stack([load_image(path, model.config) for path in image_paths])
|
| 20 |
+
direction_tensor = None
|
| 21 |
+
if headings is not None:
|
| 22 |
+
if len(headings) != len(image_paths):
|
| 23 |
+
raise ValueError("provide one heading per image")
|
| 24 |
+
if not all(value is None or math.isfinite(float(value)) for value in headings):
|
| 25 |
+
raise ValueError("headings must be finite numbers or None")
|
| 26 |
+
direction_tensor = torch.tensor([[float("nan") if value is None else value
|
| 27 |
+
for value in headings]], device=device)
|
| 28 |
+
options = {}
|
| 29 |
+
if google_coverage_only:
|
| 30 |
+
from streetgeo.inference.coverage import google_coverage_mask
|
| 31 |
+
options["coordinate_filter"] = google_coverage_mask
|
| 32 |
+
return model.predict(images.unsqueeze(0).to(device), headings=direction_tensor, top_k=top_k, **options)[0]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def main():
|
| 36 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 37 |
+
parser.add_argument("images", nargs="+", help="1..max_views images of the same location")
|
| 38 |
+
parser.add_argument("--checkpoint", default=TrainConfig().model_path)
|
| 39 |
+
parser.add_argument("--headings", nargs="+", type=float, help="degrees clockwise from north")
|
| 40 |
+
parser.add_argument("--top-k", type=int, default=1)
|
| 41 |
+
parser.add_argument("--device", default="auto")
|
| 42 |
+
parser.add_argument("--google-coverage-only", action="store_true",
|
| 43 |
+
help="restrict coordinates to the offline Google Street View country/region allowlist (not road-level coverage)")
|
| 44 |
+
parser.add_argument("--json", action="store_true", help="include candidate scores and Maps URLs")
|
| 45 |
+
args = parser.parse_args()
|
| 46 |
+
model = load_model(args.checkpoint, args.device)
|
| 47 |
+
predictions = predict_images(model, args.images, headings=args.headings, top_k=args.top_k,
|
| 48 |
+
google_coverage_only=args.google_coverage_only)
|
| 49 |
+
if args.json:
|
| 50 |
+
print(json.dumps([{"coordinates": p.coordinates, "latitude": p.latitude,
|
| 51 |
+
"longitude": p.longitude, "cell_probability": p.probability,
|
| 52 |
+
"cell_id": p.cell_id, "maps_url": p.maps_url}
|
| 53 |
+
for p in predictions], ensure_ascii=False, indent=2))
|
| 54 |
+
else:
|
| 55 |
+
for prediction in predictions:
|
| 56 |
+
print(prediction.coordinates)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
if __name__ == "__main__":
|
| 60 |
+
main()
|
weights/siglip2-nmpz-climate-aux-0.1.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:84b08f8db51fe5d085b67b208ada303782d080bd3f0fd5d4a50d78a31b014e63
|
| 3 |
+
size 413589498
|
weights/siglip2-nmpz-climate-control.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c5020d921efea6085f91c19474b0203e6abc53605018cb641cb10ec6f0f894bb
|
| 3 |
+
size 413570661
|
weights/siglip2-nmpz-last-block.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:91a63dfc68950b50db41eaafa14dc68eac82c0642717d3fc5d44e49e9eab1c60
|
| 3 |
+
size 413570597
|