AnirudhShashikumar commited on
Commit
2407511
·
1 Parent(s): 613b18f

Deploy SatQuery AI ZeroGPU bridge

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -34
  2. .gitignore +12 -0
  3. README.md +68 -7
  4. app.py +176 -0
  5. backend.py +1836 -0
  6. changerex_local/README.md +99 -0
  7. changerex_local/__init__.py +15 -0
  8. changerex_local/__main__.py +4 -0
  9. changerex_local/architecture.py +39 -0
  10. changerex_local/backbone.py +82 -0
  11. changerex_local/checkpoint.py +143 -0
  12. changerex_local/cli.py +112 -0
  13. changerex_local/config.py +38 -0
  14. changerex_local/decoder.py +100 -0
  15. changerex_local/diagnostics.py +168 -0
  16. changerex_local/inference.py +171 -0
  17. changerex_local/interaction.py +51 -0
  18. changerex_local/lifecycle.py +229 -0
  19. changerex_local/parity.py +110 -0
  20. changerex_local/postprocessing.py +94 -0
  21. changerex_local/preprocessing.py +125 -0
  22. changerex_local/requirements-macos.txt +4 -0
  23. changerex_local/schemas.py +110 -0
  24. models/MODEL_MANIFEST.json +104 -0
  25. models/changerex/ChangerEx_r18-512x512_40k_levircd_20221223_120511.pth +3 -0
  26. models/grounding_dino_tiny/.gitattributes +35 -0
  27. models/grounding_dino_tiny/README.md +69 -0
  28. models/grounding_dino_tiny/added_tokens.json +7 -0
  29. models/grounding_dino_tiny/config.json +77 -0
  30. models/grounding_dino_tiny/model.safetensors +3 -0
  31. models/grounding_dino_tiny/preprocessor_config.json +25 -0
  32. models/grounding_dino_tiny/special_tokens_map.json +7 -0
  33. models/grounding_dino_tiny/tokenizer.json +0 -0
  34. models/grounding_dino_tiny/tokenizer_config.json +56 -0
  35. models/grounding_dino_tiny/vocab.txt +0 -0
  36. models/grounding_specialist_v1_1/architecture.json +34 -0
  37. models/grounding_specialist_v1_1/model_card.json +30 -0
  38. models/grounding_specialist_v1_1/sha256.json +6 -0
  39. models/grounding_specialist_v1_1/validation_results.json +611 -0
  40. models/rsvqa_specialist_v1/integration_contract.json +40 -0
  41. models/rsvqa_specialist_v1/model_card.json +76 -0
  42. models/rsvqa_specialist_v1/preprocessing.json +53 -0
  43. models/rsvqa_specialist_v1/sha256.json +10 -0
  44. models/rsvqa_specialist_v1/sha256.txt +8 -0
  45. models/rsvqa_specialist_v1/task_answer_vocab.json +657 -0
  46. models/rsvqa_specialist_v1/training_history.json +234 -0
  47. models/rsvqa_specialist_v1/validation_metrics.json +30 -0
  48. models/rsvqa_specialist_v1/validation_predictions.csv +0 -0
  49. models/satquery_vision_encoder_v1/baseline_vs_adapted.json +29 -0
  50. models/satquery_vision_encoder_v1/model_card.json +64 -0
.gitattributes CHANGED
@@ -1,35 +1,5 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  *.safetensors filter=lfs diff=lfs merge=lfs -text
2
+ *.pth filter=lfs diff=lfs merge=lfs -text
3
+ *.pt filter=lfs diff=lfs merge=lfs -text
4
+ *.tif filter=lfs diff=lfs merge=lfs -text
5
+ *.tiff filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .cache/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .DS_Store
5
+
6
+ # The resolver downloads these six verified private artifacts at runtime.
7
+ models/satquery_vision_encoder_v1/satquery_vision_encoder_v1_adapter.pt
8
+ models/rsvqa_specialist_v1/rsvqa_specialist_v1_head.pt
9
+ models/grounding_specialist_v1_1/grounding_specialist_v1_1_head.pt
10
+ pix2pix_gen_180.pth
11
+ models/checkpoints/sarfusionformer_256_decoder_best.pt
12
+ models/checkpoints/color_corrector_256_best.pt
README.md CHANGED
@@ -1,14 +1,75 @@
1
  ---
2
  title: SatQuery AI
3
- emoji: 🐨
4
- colorFrom: indigo
5
- colorTo: pink
6
  sdk: gradio
7
- sdk_version: 6.28.0
8
- python_version: '3.12'
9
  app_file: app.py
 
10
  pinned: false
11
- short_description: Evidence-grounded multimodal remote sensing analysis for
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: SatQuery AI
3
+ emoji: "🛰️"
4
+ colorFrom: blue
5
+ colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 6.16.0
8
+ python_version: 3.10.13
9
  app_file: app.py
10
+ startup_duration_timeout: 1h
11
  pinned: false
 
12
  ---
13
 
14
+ # SatQuery AI — ZeroGPU bridge
15
+
16
+ This Space is the deployment bridge for the existing SatQuery AI Vercel interface. It does not replace the product UI and it does not reimplement SatQuery's scientific pipeline.
17
+
18
+ The Space uses Python 3.10.13, Gradio 6.16.0, and PyTorch 2.8.0. Gradio 6.16.0 is the newest compatible release before Gradio's Hugging Face Hub 1.x requirement conflicts with SatQuery's pinned Transformers 4.48.3 / Hub 0.36.2 model runtime; upgrading that scientific dependency stack is intentionally outside this deployment-only package.
19
+
20
+ ## Runtime contract
21
+
22
+ The named Gradio APIs are:
23
+
24
+ - `/single_image` — one optical, multispectral, or SAR image plus a natural-language query.
25
+ - `/optical_sar` — paired optical and SAR observations plus a query.
26
+ - `/bitemporal` — earlier/later observations, dates, modality, and a query.
27
+ - `/health` — CPU-only readiness and model lifecycle state.
28
+ - `/contract` — CPU-only bridge metadata.
29
+
30
+ Each inference API returns three outputs: a result envelope containing the unchanged SatQuery `AgentResponse`, an artifact manifest, and a Gradio file list. The manifest's zero-based `index` maps an original `/api/agent/previews/...` reference to the corresponding file result.
31
+
32
+ Model construction and CUDA placement occur once during module initialization, as required by ZeroGPU CUDA emulation. Only the three inference handlers use `@spaces.GPU`; health and contract calls never request a GPU. The requested maximum durations are 90 seconds for single-image, 75 seconds for optical + SAR, and 90 seconds for bi-temporal. Requests are serialized per replica so process-wide model singletons and bounded caches are reused safely.
33
+
34
+ ## Model artifacts
35
+
36
+ The public Grounding DINO Tiny bundle and ChangerEx checkpoint are committed to this Space. The six SatQuery-owned/adapted weights are deliberately absent. On a missing private artifact, the existing resolver:
37
+
38
+ 1. accepts only an allowlisted path in `AnirudhShashikumar/SatQuery_AI_Models`;
39
+ 2. requires the `HF_TOKEN` Space secret;
40
+ 3. downloads into the running Space's local model tree;
41
+ 4. verifies the pinned SHA-256 before publishing the file; and
42
+ 5. reuses the verified file and process-wide model singleton for that live replica.
43
+
44
+ Space storage is ephemeral unless persistent storage is separately enabled. A cold rebuild or replacement replica can therefore download the private and public upstream artifacts again. No access token is written to logs or returned by an API.
45
+
46
+ Required Space setting: select **ZeroGPU** hardware and add a private `HF_TOKEN` secret with read access to `AnirudhShashikumar/SatQuery_AI_Models`.
47
+
48
+ ## Vercel integration boundary
49
+
50
+ The existing frontend posts multipart data to `/api/agent/query`; that is not the Gradio queue protocol. Preserve the frontend by adding a Vercel server-side proxy that:
51
+
52
+ 1. accepts the existing `/health` and `/api/agent/query` contracts;
53
+ 2. uploads image files to the Space and invokes the matching named endpoint;
54
+ 3. polls the Gradio event result;
55
+ 4. unwraps `result_envelope.response`; and
56
+ 5. rewrites preview references using `artifact_manifest` and `artifact_files`.
57
+
58
+ Authenticated ZeroGPU quota attribution requires the Hugging Face token to remain in the Vercel server environment. Never expose it through a `NEXT_PUBLIC_*` variable or browser bundle. Anonymous public calls are possible but receive the smaller unauthenticated ZeroGPU quota and lower scheduling priority.
59
+
60
+ ## Push this staging directory
61
+
62
+ After local validation, clone the existing Space, replace its working-tree contents with this directory—not the parent repository—and push normally. Large committed model files require Git LFS.
63
+
64
+ ```bash
65
+ hf auth login
66
+ git lfs install
67
+ git clone https://huggingface.co/spaces/AnirudhShashikumar/SatQuery-AI SatQuery-AI-space
68
+ rsync -a --delete --exclude .git hf_space/ SatQuery-AI-space/
69
+ cd SatQuery-AI-space
70
+ git add .
71
+ git commit -m "Deploy SatQuery AI ZeroGPU bridge"
72
+ git push origin main
73
+ ```
74
+
75
+ Run the `rsync` command from the parent repository directory, or substitute absolute paths. Inspect `git status` in the clone before committing. Do not use a browser-visible token in the remote URL; authenticate through the Hugging Face CLI or Git credential helper.
app.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hugging Face ZeroGPU entrypoint for SatQuery AI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gradio as gr
6
+ import spaces
7
+
8
+ from satquery_space_bridge import (
9
+ api_contract,
10
+ preload_models,
11
+ run_bitemporal,
12
+ run_optical_sar,
13
+ run_single_image,
14
+ space_health,
15
+ )
16
+
17
+
18
+ # ZeroGPU provides CUDA emulation during module initialization. Keep model
19
+ # construction here and inference inside the decorated request handlers below.
20
+ preload_models()
21
+
22
+
23
+ @spaces.GPU(duration=90)
24
+ def single_image_api(
25
+ primary_image: str | None,
26
+ query: str,
27
+ primary_modality: str,
28
+ primary_image_modality: str,
29
+ use_cache: bool,
30
+ force_rerun: bool,
31
+ ):
32
+ return run_single_image(
33
+ primary_image,
34
+ query,
35
+ primary_modality,
36
+ primary_image_modality,
37
+ use_cache,
38
+ force_rerun,
39
+ )
40
+
41
+
42
+ @spaces.GPU(duration=75)
43
+ def optical_sar_api(
44
+ optical_image: str | None,
45
+ sar_image: str | None,
46
+ query: str,
47
+ use_cache: bool,
48
+ force_rerun: bool,
49
+ ):
50
+ return run_optical_sar(optical_image, sar_image, query, use_cache, force_rerun)
51
+
52
+
53
+ @spaces.GPU(duration=90)
54
+ def bitemporal_api(
55
+ earlier_image: str | None,
56
+ later_image: str | None,
57
+ query: str,
58
+ primary_date: str,
59
+ secondary_date: str,
60
+ primary_modality: str,
61
+ use_cache: bool,
62
+ force_rerun: bool,
63
+ ):
64
+ return run_bitemporal(
65
+ earlier_image,
66
+ later_image,
67
+ query,
68
+ primary_date,
69
+ secondary_date,
70
+ primary_modality,
71
+ use_cache,
72
+ force_rerun,
73
+ )
74
+
75
+
76
+ def _outputs():
77
+ return [
78
+ gr.JSON(label="Result envelope"),
79
+ gr.JSON(label="Artifact manifest"),
80
+ gr.File(label="Evidence files", file_count="multiple"),
81
+ ]
82
+
83
+
84
+ with gr.Blocks(title="SatQuery AI ZeroGPU Bridge") as demo:
85
+ gr.Markdown(
86
+ "# SatQuery AI API bridge\n"
87
+ "This minimal Space exposes the existing SatQuery workflows as named Gradio APIs. "
88
+ "Use **View API** for the generated client contract."
89
+ )
90
+
91
+ with gr.Tab("Single Image"):
92
+ single_file = gr.File(label="Image", type="filepath")
93
+ single_query = gr.Textbox(label="Query", value="Describe this satellite image.")
94
+ single_modality = gr.Dropdown(
95
+ ["optical", "multispectral", "sar", "unknown"], value="optical", label="Modality"
96
+ )
97
+ single_image_modality = gr.Dropdown(
98
+ [
99
+ "auto",
100
+ "optical_rgb",
101
+ "optical_grayscale",
102
+ "panchromatic",
103
+ "sar_preview",
104
+ "sar_vv",
105
+ "sar_vh",
106
+ "sar_vv_vh",
107
+ "multispectral",
108
+ "unknown",
109
+ ],
110
+ value="auto",
111
+ label="Image modality",
112
+ )
113
+ single_cache = gr.Checkbox(value=True, label="Use cache")
114
+ single_rerun = gr.Checkbox(value=False, label="Force rerun")
115
+ single_submit = gr.Button("Run single-image workflow", variant="primary")
116
+ single_submit.click(
117
+ single_image_api,
118
+ [single_file, single_query, single_modality, single_image_modality, single_cache, single_rerun],
119
+ _outputs(),
120
+ api_name="single_image",
121
+ )
122
+
123
+ with gr.Tab("Optical + SAR"):
124
+ optical_file = gr.File(label="Optical image", type="filepath")
125
+ sar_file = gr.File(label="SAR image", type="filepath")
126
+ cross_query = gr.Textbox(label="Query", value="Compare the optical and SAR observations.")
127
+ cross_cache = gr.Checkbox(value=True, label="Use cache")
128
+ cross_rerun = gr.Checkbox(value=False, label="Force rerun")
129
+ cross_submit = gr.Button("Run optical + SAR workflow", variant="primary")
130
+ cross_submit.click(
131
+ optical_sar_api,
132
+ [optical_file, sar_file, cross_query, cross_cache, cross_rerun],
133
+ _outputs(),
134
+ api_name="optical_sar",
135
+ )
136
+
137
+ with gr.Tab("Bi-temporal"):
138
+ earlier_file = gr.File(label="Earlier image", type="filepath")
139
+ later_file = gr.File(label="Later image", type="filepath")
140
+ temporal_query = gr.Textbox(label="Query", value="What changed between these images?")
141
+ earlier_date = gr.Textbox(label="Earlier date", placeholder="YYYY-MM-DD")
142
+ later_date = gr.Textbox(label="Later date", placeholder="YYYY-MM-DD")
143
+ temporal_modality = gr.Dropdown(
144
+ ["optical", "multispectral", "sar", "unknown"], value="optical", label="Modality"
145
+ )
146
+ temporal_cache = gr.Checkbox(value=True, label="Use cache")
147
+ temporal_rerun = gr.Checkbox(value=False, label="Force rerun")
148
+ temporal_submit = gr.Button("Run bi-temporal workflow", variant="primary")
149
+ temporal_submit.click(
150
+ bitemporal_api,
151
+ [
152
+ earlier_file,
153
+ later_file,
154
+ temporal_query,
155
+ earlier_date,
156
+ later_date,
157
+ temporal_modality,
158
+ temporal_cache,
159
+ temporal_rerun,
160
+ ],
161
+ _outputs(),
162
+ api_name="bitemporal",
163
+ )
164
+
165
+ with gr.Tab("Readiness"):
166
+ readiness_output = gr.JSON(label="Health")
167
+ contract_output = gr.JSON(label="Contract")
168
+ gr.Button("Health (CPU only)").click(space_health, outputs=readiness_output, api_name="health")
169
+ gr.Button("Contract (CPU only)").click(api_contract, outputs=contract_output, api_name="contract")
170
+
171
+
172
+ demo.queue(default_concurrency_limit=1, max_size=8)
173
+
174
+
175
+ if __name__ == "__main__":
176
+ demo.launch()
backend.py ADDED
@@ -0,0 +1,1836 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI inference service for independent SAR-to-optical models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import hashlib
7
+ import io
8
+ import json
9
+ import logging
10
+ import os
11
+ import re
12
+ import sys
13
+ import time
14
+ import uuid
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Any, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn.functional as F
22
+ from fastapi import FastAPI, File, Form, HTTPException, UploadFile
23
+ from fastapi.middleware.cors import CORSMiddleware
24
+ from fastapi.responses import JSONResponse, StreamingResponse
25
+ from starlette.concurrency import run_in_threadpool
26
+ from pydantic import BaseModel, Field
27
+ from PIL import Image, UnidentifiedImageError
28
+ from skimage.metrics import peak_signal_noise_ratio, structural_similarity
29
+ from starlette.datastructures import Headers
30
+
31
+ APP_DIR = Path(__file__).resolve().parent
32
+ ROOT_DIR = APP_DIR.parent
33
+
34
+ # Keep imports stable when the API is run from the repository root (Render),
35
+ # from this directory (local Uvicorn), or through an import-based test runner.
36
+ for import_path in (ROOT_DIR, APP_DIR):
37
+ if str(import_path) not in sys.path:
38
+ sys.path.insert(0, str(import_path))
39
+
40
+ from sarfusionformer import SARFusionFormer, lab_to_rgb
41
+ from src.pix2pix import Pix2Pix
42
+ from provider_settings import ProviderSettingsError, ProviderSettingsStore
43
+ from vision_analysis import ImageAnalysisService, VisionAnalysisError, VisionSettings
44
+ from satquery_agent import router as satquery_router
45
+ from satquery_agent.api import agent_image_query
46
+ from satquery_agent.comparison import (
47
+ hash_bytes,
48
+ record_model_result,
49
+ store_model_preview,
50
+ utc_now as comparison_utc_now,
51
+ )
52
+ from satquery_agent.models import (
53
+ AgentResponse,
54
+ ComparisonTask,
55
+ ImageModality,
56
+ InputMode,
57
+ Modality,
58
+ QuestionCategory,
59
+ )
60
+ from satquery_agent.entity_registry import (
61
+ get_remote_sensing_entity,
62
+ grounding_prompt_for,
63
+ normalize_entity_text,
64
+ )
65
+ from satquery_agent.services.sve_service import SVECall, get_sve_service
66
+ from satquery_agent.services.sar_translation_service import (
67
+ COLOR_CORRECTOR_CHECKPOINT,
68
+ PIX2PIX_CHECKPOINT,
69
+ SARFUSIONFORMER_CHECKPOINT,
70
+ get_sar_translation_service,
71
+ resolve_sar_translation_checkpoint,
72
+ )
73
+ from satquery_agent.specialists.grounder import GrounderError, get_grounder, normalize_grounding_target
74
+ from satquery_agent.specialists.rsvqa_specialist import (
75
+ MODEL_USED as RSVQA_MODEL_USED,
76
+ RSVQASpecialistError,
77
+ get_rsvqa_specialist,
78
+ )
79
+ from satquery_agent.specialists.vqa import (
80
+ QuestionIntent,
81
+ get_vqa,
82
+ is_groundable_count_target,
83
+ normalize_benchmark_answer,
84
+ )
85
+ from satquery_agent.sve_artifacts import SVEError
86
+
87
+ logging.basicConfig(level=logging.INFO)
88
+ LOGGER = logging.getLogger("sar-colorization")
89
+
90
+ MAX_UPLOAD_BYTES = 20 * 1024 * 1024
91
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
92
+
93
+
94
+ app = FastAPI(title="SAR-to-Optical Colorization API", version="2.0.0")
95
+ app.include_router(satquery_router)
96
+
97
+
98
+ def load_optional_sve_on_startup() -> None:
99
+ if os.getenv("SVE_LOAD_ON_STARTUP", "false").strip().lower() not in {"1", "true", "yes", "on"}:
100
+ return
101
+ try:
102
+ get_sve_service().load()
103
+ except SVEError as error:
104
+ LOGGER.warning("Optional SatQuery Vision Encoder startup load was skipped: %s", error.public_message)
105
+
106
+
107
+ def load_rsvqa_specialist_on_startup() -> None:
108
+ if os.getenv("RSVQA_LOAD_ON_STARTUP", "true").strip().lower() not in {"1", "true", "yes", "on"}:
109
+ return
110
+ try:
111
+ get_rsvqa_specialist().load()
112
+ except RSVQASpecialistError as error:
113
+ LOGGER.warning("RSVQA Specialist v1 startup load failed; heuristic fallback remains available: %s", error)
114
+
115
+
116
+ def verify_grounding_specialist_on_startup() -> None:
117
+ """Warm and smoke-verify the complete offline grounding pipeline for demo readiness."""
118
+ if os.getenv("SATQUERY_GROUNDER_LOAD_ON_STARTUP", "true").strip().lower() not in {"1", "true", "yes", "on"}:
119
+ return
120
+ try:
121
+ health = get_grounder().smoke_verify()
122
+ if health.status != "ready" or not health.smoke_verified:
123
+ LOGGER.warning("Grounding specialist startup smoke did not reach ready state: %s", health.error)
124
+ except GrounderError as error:
125
+ LOGGER.warning("Grounding specialist startup smoke failed [%s]: %s", error.code, error.message)
126
+
127
+
128
+ app.add_event_handler("startup", load_optional_sve_on_startup)
129
+ app.add_event_handler("startup", load_rsvqa_specialist_on_startup)
130
+ app.add_event_handler("startup", verify_grounding_specialist_on_startup)
131
+ CORS_ORIGINS = [origin.strip() for origin in os.getenv(
132
+ "CORS_ORIGINS",
133
+ "http://127.0.0.1:3000,http://localhost:3000,http://127.0.0.1:8520,http://localhost:8520",
134
+ ).split(",") if origin.strip()]
135
+ app.add_middleware(
136
+ CORSMiddleware,
137
+ allow_origins=CORS_ORIGINS,
138
+ allow_credentials=False,
139
+ allow_methods=["GET", "POST", "DELETE"],
140
+ allow_headers=["*"],
141
+ )
142
+
143
+
144
+ class ColorCorrectionNet(torch.nn.Module):
145
+ def __init__(self, hidden_channels: int = 32) -> None:
146
+ super().__init__()
147
+ self.net = torch.nn.Sequential(
148
+ torch.nn.Conv2d(3, hidden_channels, kernel_size=1),
149
+ torch.nn.SiLU(inplace=True),
150
+ torch.nn.Conv2d(hidden_channels, hidden_channels, kernel_size=1),
151
+ torch.nn.SiLU(inplace=True),
152
+ torch.nn.Conv2d(hidden_channels, 3, kernel_size=1),
153
+ )
154
+
155
+ def forward(self, coarse_rgb: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
156
+ correction = 0.10 * torch.tanh(self.net(coarse_rgb))
157
+ return torch.clamp(coarse_rgb + correction, 0.0, 1.0), correction
158
+
159
+
160
+ def load_pix2pix() -> Pix2Pix:
161
+ checkpoint_path = resolve_sar_translation_checkpoint("pix2pix")
162
+ model = Pix2Pix(c_in=3, c_out=3, is_train=False).to(DEVICE)
163
+ model.gen.load_state_dict(
164
+ torch.load(checkpoint_path, map_location=DEVICE, weights_only=True),
165
+ strict=True,
166
+ )
167
+ return model.eval()
168
+
169
+
170
+ def load_sarfusionformer() -> SARFusionFormer:
171
+ checkpoint_path = resolve_sar_translation_checkpoint("sarfusionformer")
172
+ model = SARFusionFormer(
173
+ input_channels=2,
174
+ output_channels=3,
175
+ base_channels=48,
176
+ transformer_depth=4,
177
+ attention_heads=6,
178
+ window_size=8,
179
+ dropout=0.0,
180
+ ).to(DEVICE)
181
+ checkpoint = torch.load(
182
+ checkpoint_path, map_location=DEVICE, weights_only=True
183
+ )
184
+ model.load_state_dict(checkpoint["model"], strict=True)
185
+ return model.eval()
186
+
187
+
188
+ def load_color_corrector() -> ColorCorrectionNet:
189
+ checkpoint_path = resolve_sar_translation_checkpoint("color_corrector")
190
+ model = ColorCorrectionNet().to(DEVICE)
191
+ checkpoint = torch.load(
192
+ checkpoint_path, map_location=DEVICE, weights_only=True
193
+ )
194
+ model.load_state_dict(checkpoint["color_corrector"], strict=True)
195
+ return model.eval()
196
+
197
+
198
+ def try_load(name: str, loader):
199
+ try:
200
+ model = loader()
201
+ LOGGER.info("%s loaded successfully on %s", name, DEVICE)
202
+ return model, None
203
+ except Exception as error:
204
+ LOGGER.warning("%s unavailable: %s", name, error)
205
+ return None, str(error)
206
+
207
+
208
+ PIX2PIX_MODEL, PIX2PIX_ERROR = try_load("Pix2Pix", load_pix2pix)
209
+ SARFUSIONFORMER_MODEL, SARFUSIONFORMER_ERROR = try_load(
210
+ "SARFusionFormer", load_sarfusionformer
211
+ )
212
+ COLOR_CORRECTOR, COLOR_CORRECTOR_ERROR = try_load(
213
+ "Color corrector", load_color_corrector
214
+ )
215
+ get_sar_translation_service().register_external_models(
216
+ pix2pix=PIX2PIX_MODEL,
217
+ sarfusionformer=SARFUSIONFORMER_MODEL,
218
+ color_corrector=COLOR_CORRECTOR,
219
+ pix2pix_error=PIX2PIX_ERROR,
220
+ sarfusionformer_error=SARFUSIONFORMER_ERROR,
221
+ color_error=COLOR_CORRECTOR_ERROR,
222
+ device=str(DEVICE),
223
+ )
224
+ VISION_ANALYSIS = ImageAnalysisService()
225
+ PROVIDER_SETTINGS = ProviderSettingsStore()
226
+ LATEST_BENCHMARKS: Dict[str, Dict[str, Any]] = {
227
+ "pix2pix": {},
228
+ "sarfusionformer": {},
229
+ }
230
+
231
+
232
+ def sync_vision_settings() -> None:
233
+ """Refresh the analysis service after a key is changed in Settings."""
234
+ credentials = PROVIDER_SETTINGS.credentials()
235
+ VISION_ANALYSIS.settings = VisionSettings(
236
+ provider=credentials.provider,
237
+ api_key=credentials.api_key,
238
+ model=credentials.model or ("gemini-2.5-flash" if credentials.provider == "gemini" else "gpt-4.1-mini"),
239
+ )
240
+
241
+
242
+ sync_vision_settings()
243
+
244
+
245
+ class ProviderConfigurationRequest(BaseModel):
246
+ provider: str
247
+ api_key: str
248
+ model: Optional[str] = None
249
+ privacy_acknowledged: bool = False
250
+
251
+
252
+ class ImageAnalysisEndpointResponse(BaseModel):
253
+ """Document the legacy image-review fields and additive VQA benchmark fields."""
254
+
255
+ report: Dict[str, Any]
256
+ provider: str
257
+ model: str
258
+ cached: bool
259
+ request_id: Optional[str] = None
260
+ debug: Optional[Dict[str, Any]] = None
261
+ answer: Optional[str] = None
262
+ confidence: Optional[float] = Field(default=None, ge=0.0, le=1.0)
263
+ confidence_details: Optional[Dict[str, Any]] = None
264
+ caption: Optional[str] = None
265
+ evidence: Optional[List[Dict[str, Any]]] = None
266
+ execution_trace: Optional[List[Dict[str, Any]]] = None
267
+ task: Optional[str] = None
268
+ model_used: Optional[str] = None
269
+ processing_time_ms: Optional[int] = Field(default=None, ge=0)
270
+ question: Optional[str] = None
271
+ routed_question: Optional[str] = None
272
+ status: Optional[str] = None
273
+ result_status: Optional[str] = None
274
+ warnings: Optional[List[str]] = None
275
+ vqa_details: Optional[Dict[str, Any]] = None
276
+ grounding_result: Optional[Dict[str, Any]] = None
277
+ sve_result: Optional[Dict[str, Any]] = None
278
+
279
+
280
+ def model_status(model: Optional[torch.nn.Module], error: Optional[str], checkpoint: Path) -> Dict[str, Any]:
281
+ return {
282
+ "available": model is not None,
283
+ "checkpoint": checkpoint.name,
284
+ "error": error,
285
+ }
286
+
287
+
288
+ def require_model(model: Optional[torch.nn.Module], error: Optional[str], name: str):
289
+ if model is None:
290
+ raise HTTPException(
291
+ status_code=503,
292
+ detail="{} is unavailable. {}".format(name, error or "Check the checkpoint path."),
293
+ )
294
+ return model
295
+
296
+
297
+ def read_upload(upload: UploadFile) -> bytes:
298
+ contents = upload.file.read()
299
+ if not contents:
300
+ raise ValueError("The uploaded file is empty.")
301
+ if len(contents) > MAX_UPLOAD_BYTES:
302
+ raise ValueError("Files must be 20 MB or smaller.")
303
+ return contents
304
+
305
+
306
+ def decode_rgb(image_bytes: bytes) -> Image.Image:
307
+ try:
308
+ image = Image.open(io.BytesIO(image_bytes))
309
+ image.load()
310
+ except (UnidentifiedImageError, OSError) as error:
311
+ raise ValueError("Upload a valid PNG, JPEG, or TIFF image.") from error
312
+ return image.convert("RGB")
313
+
314
+
315
+ def decode_grayscale(image_bytes: bytes, filename: str) -> np.ndarray:
316
+ suffix = Path(filename or "").suffix.lower()
317
+ try:
318
+ if suffix == ".npy":
319
+ array = np.load(io.BytesIO(image_bytes), allow_pickle=False)
320
+ else:
321
+ image = Image.open(io.BytesIO(image_bytes))
322
+ image.load()
323
+ array = np.asarray(image)
324
+ except (UnidentifiedImageError, OSError, ValueError) as error:
325
+ raise ValueError("Upload a valid .npy, TIFF, PNG, or JPEG single-channel image.") from error
326
+
327
+ array = np.asarray(array)
328
+ if array.ndim == 3 and array.shape[-1] == 1:
329
+ array = array[..., 0]
330
+ if array.ndim != 2:
331
+ raise ValueError("VV and VH inputs must be single-channel two-dimensional arrays.")
332
+ return array.astype(np.float32, copy=False)
333
+
334
+
335
+ def load_combined_sar_npy(image_bytes: bytes) -> Tuple[np.ndarray, np.ndarray, str, Tuple[int, ...]]:
336
+ """Load a two-channel VV/VH NumPy array in channel-first or channel-last form."""
337
+ try:
338
+ array = np.asarray(np.load(io.BytesIO(image_bytes), allow_pickle=False))
339
+ except (ValueError, OSError) as error:
340
+ raise ValueError("Upload a valid combined VV/VH NumPy (.npy) file.") from error
341
+
342
+ detected_shape = tuple(array.shape)
343
+ if array.dtype == object or not np.issubdtype(array.dtype, np.number):
344
+ raise ValueError("Combined SAR arrays must contain numeric, non-object values.")
345
+ if np.iscomplexobj(array):
346
+ raise ValueError("Combined SAR arrays must contain real-valued VV and VH channels.")
347
+ if array.ndim == 4 and array.shape[0] == 1:
348
+ array = array[0]
349
+ if array.ndim != 3:
350
+ raise ValueError(
351
+ "Expected a 3D two-channel SAR array, got shape {}".format(detected_shape)
352
+ )
353
+
354
+ is_chw = array.shape[0] == 2
355
+ is_hwc = array.shape[-1] == 2
356
+ if is_chw and is_hwc:
357
+ raise ValueError(
358
+ "Ambiguous two-channel SAR layout in shape {}. Use an unambiguous CHW or HWC array."
359
+ .format(detected_shape)
360
+ )
361
+ if is_chw:
362
+ sar = array
363
+ layout = "CHW"
364
+ elif is_hwc:
365
+ sar = np.moveaxis(array, -1, 0)
366
+ layout = "HWC"
367
+ else:
368
+ raise ValueError(
369
+ "Could not find exactly two SAR channels in shape {}".format(detected_shape)
370
+ )
371
+
372
+ sar = sar.astype(np.float32, copy=False)
373
+ if not np.isfinite(sar).any():
374
+ raise ValueError("Combined SAR input contains no finite values.")
375
+ return sar[0], sar[1], layout, detected_shape
376
+
377
+
378
+ def normalize_channel(array: np.ndarray) -> np.ndarray:
379
+ """Apply the exact per-channel percentile normalization used in training."""
380
+ low, high = np.percentile(array, [1, 99])
381
+ if high - low <= np.finfo(np.float32).eps:
382
+ return np.zeros_like(array, dtype=np.float32)
383
+ return np.clip((array - low) / (high - low), 0.0, 1.0).astype(np.float32)
384
+
385
+
386
+ def image_to_base64(image: Image.Image) -> str:
387
+ buffer = io.BytesIO()
388
+ image.save(buffer, format="PNG")
389
+ return base64.b64encode(buffer.getvalue()).decode("ascii")
390
+
391
+
392
+ def tensor_to_image(tensor: torch.Tensor) -> Image.Image:
393
+ array = tensor.detach().clamp(0, 1).permute(1, 2, 0).cpu().numpy()
394
+ return rgb_float_to_png(array)
395
+
396
+
397
+ def rgb_float_to_png(rgb: np.ndarray) -> Image.Image:
398
+ """Encode an RGB float image without changing its radiometric values first."""
399
+ rgb = np.asarray(rgb, dtype=np.float32)
400
+ if rgb.ndim != 3 or rgb.shape[-1] != 3:
401
+ raise ValueError("RGB output must have shape [height, width, 3].")
402
+ encoded = (np.clip(rgb, 0.0, 1.0) * 255).round().astype(np.uint8)
403
+ return Image.fromarray(encoded, mode="RGB")
404
+
405
+
406
+ def contrast_stretch_rgb(rgb: np.ndarray) -> np.ndarray:
407
+ """Global display-only 2nd/98th percentile stretch that preserves RGB balance."""
408
+ rgb = np.asarray(rgb, dtype=np.float32)
409
+ rgb = np.nan_to_num(rgb, nan=0.0, posinf=1.0, neginf=0.0)
410
+ rgb = np.clip(rgb, 0.0, 1.0)
411
+
412
+ low = float(np.percentile(rgb, 2))
413
+ high = float(np.percentile(rgb, 98))
414
+ if not np.isfinite(low) or not np.isfinite(high) or high <= low:
415
+ return rgb.copy()
416
+
417
+ stretched = (rgb - low) / (high - low)
418
+ return np.clip(stretched, 0.0, 1.0).astype(np.float32)
419
+
420
+
421
+ def array_diagnostics(array: np.ndarray, prefix: str) -> Dict[str, Any]:
422
+ array = np.asarray(array, dtype=np.float32)
423
+ return {
424
+ "{}_min".format(prefix): float(array.min()),
425
+ "{}_max".format(prefix): float(array.max()),
426
+ "{}_mean".format(prefix): float(array.mean()),
427
+ "{}_std".format(prefix): float(array.std()),
428
+ }
429
+
430
+
431
+ def rgb_diagnostics(rgb: np.ndarray, prefix: str) -> Dict[str, Any]:
432
+ rgb = np.asarray(rgb, dtype=np.float32)
433
+ if rgb.ndim != 3 or rgb.shape[-1] != 3:
434
+ raise ValueError("RGB diagnostics require a [height, width, 3] array.")
435
+ return {
436
+ **array_diagnostics(rgb, prefix),
437
+ "{}_channel_mean".format(prefix): [float(value) for value in rgb.mean(axis=(0, 1))],
438
+ "{}_channel_std".format(prefix): [float(value) for value in rgb.std(axis=(0, 1))],
439
+ }
440
+
441
+
442
+ def display_representation(rgb: np.ndarray) -> Tuple[np.ndarray, Dict[str, Any], Optional[str]]:
443
+ """Return a visual-only representation and diagnostics for one raw RGB image."""
444
+ rgb = np.asarray(rgb, dtype=np.float32)
445
+ finite_rgb = np.nan_to_num(rgb, nan=0.0, posinf=1.0, neginf=0.0).clip(0.0, 1.0)
446
+ low = float(np.percentile(finite_rgb, 2))
447
+ high = float(np.percentile(finite_rgb, 98))
448
+ raw_std = float(finite_rgb.std())
449
+ warning = None
450
+ if raw_std < 0.001:
451
+ # Do not turn a nearly constant scientific result into apparent detail.
452
+ display_rgb = finite_rgb.copy()
453
+ warning = (
454
+ "Raw RGB standard deviation is below 0.001; contrast enhancement was skipped. "
455
+ "Review the model input and checkpoint rather than interpreting amplified noise."
456
+ )
457
+ else:
458
+ display_rgb = contrast_stretch_rgb(finite_rgb)
459
+ diagnostics = {
460
+ **rgb_diagnostics(finite_rgb, "raw_rgb"),
461
+ **rgb_diagnostics(display_rgb, "display_rgb"),
462
+ "stretch_low": low,
463
+ "stretch_high": high,
464
+ "stretch_applied": warning is None and high > low,
465
+ }
466
+ return display_rgb, diagnostics, warning
467
+
468
+
469
+ def channel_preview(channel: np.ndarray) -> Image.Image:
470
+ return Image.fromarray((channel.clip(0, 1) * 255).round().astype(np.uint8), mode="L")
471
+
472
+
473
+ def prepare_sarfusionformer_input(
474
+ vv_array: np.ndarray, vh_array: np.ndarray
475
+ ) -> Tuple[torch.Tensor, Dict[str, Image.Image]]:
476
+ """Produce the exact [1, 2, 256, 256] float32 tensor used during training."""
477
+ if vv_array.shape != vh_array.shape:
478
+ raise ValueError("VV and VH inputs must have matching spatial dimensions.")
479
+ if vv_array.ndim != 2:
480
+ raise ValueError("VV and VH inputs must be two-dimensional SAR channels.")
481
+
482
+ # Keep this order aligned with the training pipeline: stack, replace invalid
483
+ # values, normalize each channel independently, then resize to model resolution.
484
+ source_sar = np.stack([vv_array, vh_array], axis=0).astype(np.float32, copy=False)
485
+ if not np.isfinite(source_sar).any():
486
+ raise ValueError("SAR array contains no finite values.")
487
+ source_sar = np.nan_to_num(source_sar, nan=0.0, posinf=0.0, neginf=0.0)
488
+ normalized_sar = np.stack(
489
+ [normalize_channel(source_sar[0]), normalize_channel(source_sar[1])], axis=0
490
+ ).astype(np.float32, copy=False)
491
+
492
+ sar_tensor = torch.from_numpy(normalized_sar).unsqueeze(0)
493
+ sar_tensor = F.interpolate(
494
+ sar_tensor, size=(256, 256), mode="bilinear", align_corners=False
495
+ ).to(dtype=torch.float32)
496
+ preview_sar = sar_tensor[0].numpy()
497
+
498
+ # SAR is not an RGB image. A neutral intensity composite avoids falsely
499
+ # presenting VV/VH as red/green/blue colours.
500
+ combined_preview = channel_preview(preview_sar.mean(axis=0)).convert("RGB")
501
+ return sar_tensor.to(DEVICE, dtype=torch.float32), {
502
+ "vv": channel_preview(preview_sar[0]),
503
+ "vh": channel_preview(preview_sar[1]),
504
+ "sar": combined_preview,
505
+ }
506
+
507
+
508
+ def calculate_metrics(
509
+ prediction: Union[Image.Image, np.ndarray], ground_truth: Image.Image
510
+ ) -> Dict[str, Optional[float]]:
511
+ """Calculate metrics from raw radiometric RGB, never display-enhanced RGB."""
512
+ if isinstance(prediction, Image.Image):
513
+ prediction_array = np.asarray(prediction.convert("RGB"), dtype=np.float32) / 255.0
514
+ else:
515
+ prediction_array = np.asarray(prediction, dtype=np.float32)
516
+ if prediction_array.ndim != 3 or prediction_array.shape[-1] != 3:
517
+ raise ValueError("Metric prediction must have shape [height, width, 3].")
518
+ prediction_array = np.nan_to_num(
519
+ prediction_array, nan=0.0, posinf=1.0, neginf=0.0
520
+ ).clip(0.0, 1.0)
521
+ target = ground_truth.convert("RGB").resize(
522
+ (prediction_array.shape[1], prediction_array.shape[0]), Image.Resampling.BICUBIC
523
+ )
524
+ target_array = np.asarray(target, dtype=np.float32) / 255.0
525
+ psnr = peak_signal_noise_ratio(target_array, prediction_array, data_range=1.0)
526
+ return {
527
+ "psnr": None if not np.isfinite(psnr) else float(psnr),
528
+ "ssim": float(
529
+ structural_similarity(target_array, prediction_array, channel_axis=2, data_range=1.0)
530
+ ),
531
+ "rgb_l1": float(np.mean(np.abs(target_array - prediction_array))),
532
+ }
533
+
534
+
535
+ def pix2pix_generate(image: Image.Image) -> Tuple[Image.Image, float]:
536
+ model = require_model(PIX2PIX_MODEL, PIX2PIX_ERROR, "Pix2Pix")
537
+ resized = image.resize((256, 256), Image.Resampling.BICUBIC)
538
+ input_array = np.asarray(resized, dtype=np.float32) / 255.0
539
+ input_tensor = torch.from_numpy(input_array).permute(2, 0, 1)
540
+ input_tensor = ((input_tensor - 0.5) / 0.5).unsqueeze(0).to(DEVICE)
541
+ LOGGER.info("Pix2Pix input shape: %s", tuple(input_tensor.shape))
542
+ start = time.perf_counter()
543
+ with torch.inference_mode():
544
+ output = ((model(input_tensor)[0] + 1.0) / 2.0).clamp(0, 1)
545
+ duration_ms = (time.perf_counter() - start) * 1000
546
+ LOGGER.info("Pix2Pix inference duration: %.2f ms", duration_ms)
547
+ return tensor_to_image(output), duration_ms
548
+
549
+
550
+ def sarfusionformer_generate(
551
+ vv_array: np.ndarray, vh_array: np.ndarray, apply_color_correction: bool = False
552
+ ) -> Dict[str, Any]:
553
+ model = require_model(
554
+ SARFUSIONFORMER_MODEL, SARFUSIONFORMER_ERROR, "SARFusionFormer"
555
+ )
556
+ sar, previews = prepare_sarfusionformer_input(vv_array, vh_array)
557
+ LOGGER.info(
558
+ "SARFusionFormer input shape=%s dtype=%s range=[%.6f, %.6f]",
559
+ tuple(sar.shape),
560
+ sar.dtype,
561
+ sar.amin().item(),
562
+ sar.amax().item(),
563
+ )
564
+ start = time.perf_counter()
565
+ with torch.inference_mode():
566
+ prediction_lab = model(sar)["lab"]
567
+ if not torch.isfinite(prediction_lab).all():
568
+ raise ValueError("SARFusionFormer produced non-finite LAB values.")
569
+ raw_rgb = lab_to_rgb(prediction_lab.float()).clamp(0, 1)
570
+ if not torch.isfinite(raw_rgb).all():
571
+ raise ValueError("LAB-to-RGB conversion produced non-finite RGB values.")
572
+
573
+ # This is the scientific prediction. The display path receives an
574
+ # independent copy and is checked below so it can never overwrite it.
575
+ raw_rgb_hwc = raw_rgb[0].detach().cpu().permute(1, 2, 0).numpy().copy()
576
+ raw_rgb_before_display = raw_rgb_hwc.copy()
577
+ display_rgb_hwc, diagnostics, warning = display_representation(raw_rgb_hwc.copy())
578
+ if not np.array_equal(raw_rgb_hwc, raw_rgb_before_display):
579
+ raise RuntimeError("Display processing modified the raw RGB prediction.")
580
+ diagnostics.update(
581
+ array_diagnostics(prediction_lab[0].detach().cpu().numpy(), "prediction_lab")
582
+ )
583
+ diagnostics.update(
584
+ {
585
+ "prediction_shape": list(raw_rgb.shape),
586
+ "prediction_dtype": str(raw_rgb.dtype),
587
+ "lab_finite": True,
588
+ "rgb_finite": True,
589
+ "raw_prediction_preserved": True,
590
+ "inference_successful": True,
591
+ }
592
+ )
593
+ if diagnostics["raw_rgb_max"] - diagnostics["raw_rgb_min"] < 0.1:
594
+ narrow_range_message = (
595
+ "Model inference succeeded. The prediction has a narrow radiometric range, "
596
+ "so the raw image appears dark."
597
+ )
598
+ warning = (
599
+ narrow_range_message if warning is None else "{} {}".format(warning, narrow_range_message)
600
+ )
601
+ LOGGER.info("Loaded checkpoint: %s", SARFUSIONFORMER_CHECKPOINT.name)
602
+ LOGGER.info("Prediction shape: %s", tuple(raw_rgb.shape))
603
+ LOGGER.info("Prediction dtype: %s", raw_rgb.dtype)
604
+ LOGGER.info(
605
+ "Prediction min/max: %.6f / %.6f; Prediction mean/std: %.6f / %.6f",
606
+ diagnostics["raw_rgb_min"],
607
+ diagnostics["raw_rgb_max"],
608
+ diagnostics["raw_rgb_mean"],
609
+ diagnostics["raw_rgb_std"],
610
+ )
611
+ LOGGER.info(
612
+ "RGB image range: [%.6f, %.6f]; Enhanced image range: [%.6f, %.6f]",
613
+ diagnostics["raw_rgb_min"],
614
+ diagnostics["raw_rgb_max"],
615
+ diagnostics["display_rgb_min"],
616
+ diagnostics["display_rgb_max"],
617
+ )
618
+ LOGGER.info("Lab-to-RGB conversion: completed; Inference successful: True")
619
+ LOGGER.info(
620
+ "SARFusionFormer Lab min=%.6f max=%.6f mean=%.6f std=%.6f; "
621
+ "raw RGB min=%.6f max=%.6f mean=%.6f std=%.6f; stretch=[%.6f, %.6f]",
622
+ diagnostics["prediction_lab_min"],
623
+ diagnostics["prediction_lab_max"],
624
+ diagnostics["prediction_lab_mean"],
625
+ diagnostics["prediction_lab_std"],
626
+ diagnostics["raw_rgb_min"],
627
+ diagnostics["raw_rgb_max"],
628
+ diagnostics["raw_rgb_mean"],
629
+ diagnostics["raw_rgb_std"],
630
+ diagnostics["stretch_low"],
631
+ diagnostics["stretch_high"],
632
+ )
633
+ corrected_rgb = None
634
+ corrected_raw_hwc = None
635
+ corrected_display_hwc = None
636
+ corrected_diagnostics = None
637
+ if apply_color_correction and COLOR_CORRECTOR is not None:
638
+ corrected_rgb, _ = COLOR_CORRECTOR(raw_rgb)
639
+ corrected_raw_hwc = corrected_rgb[0].detach().cpu().permute(1, 2, 0).numpy()
640
+ corrected_display_hwc, corrected_diagnostics, corrected_warning = display_representation(
641
+ corrected_raw_hwc
642
+ )
643
+ if corrected_warning:
644
+ warning = corrected_warning if warning is None else "{} {}".format(warning, corrected_warning)
645
+ elif apply_color_correction:
646
+ correction_warning = COLOR_CORRECTOR_ERROR or "Color corrector is unavailable."
647
+ warning = correction_warning if warning is None else "{} {}".format(warning, correction_warning)
648
+ duration_ms = (time.perf_counter() - start) * 1000
649
+ LOGGER.info("SARFusionFormer inference duration: %.2f ms", duration_ms)
650
+
651
+ return {
652
+ "raw_rgb": raw_rgb_hwc,
653
+ "display_rgb": display_rgb_hwc,
654
+ "corrected_raw_rgb": corrected_raw_hwc,
655
+ "corrected_display_rgb": corrected_display_hwc,
656
+ "previews": previews,
657
+ "duration_ms": duration_ms,
658
+ "warning": warning,
659
+ "diagnostics": diagnostics,
660
+ "corrected_diagnostics": corrected_diagnostics,
661
+ }
662
+
663
+
664
+ def pix2pix_payload(
665
+ input_bytes: bytes, ground_truth_bytes: Optional[bytes] = None
666
+ ) -> Dict[str, Any]:
667
+ source = decode_rgb(input_bytes)
668
+ output, duration_ms = pix2pix_generate(source)
669
+ target = decode_rgb(ground_truth_bytes) if ground_truth_bytes else None
670
+ payload = {
671
+ "input_preview": image_to_base64(source),
672
+ "output": image_to_base64(output),
673
+ "metrics": calculate_metrics(output, target) if target else None,
674
+ "inference_time_ms": round(duration_ms, 2),
675
+ "checkpoint": PIX2PIX_CHECKPOINT.name,
676
+ }
677
+ LATEST_BENCHMARKS["pix2pix"] = {
678
+ "metrics": payload["metrics"],
679
+ "inference_time_ms": payload["inference_time_ms"],
680
+ "sample": "current_sample",
681
+ }
682
+ return payload
683
+
684
+
685
+ def checkpoint_size_mb(checkpoint: Path) -> Optional[float]:
686
+ if not checkpoint.is_file():
687
+ return None
688
+ return round(checkpoint.stat().st_size / (1024 * 1024), 2)
689
+
690
+
691
+ def benchmark_model_payload(name: str, checkpoint: Path) -> Dict[str, Any]:
692
+ latest = LATEST_BENCHMARKS[name]
693
+ metrics = latest.get("metrics") or {}
694
+ return {
695
+ "metrics": {
696
+ "psnr": metrics.get("psnr"),
697
+ "ssim": metrics.get("ssim"),
698
+ "rgb_l1": metrics.get("rgb_l1"),
699
+ "inference_time_ms": latest.get("inference_time_ms"),
700
+ "model_size_mb": checkpoint_size_mb(checkpoint),
701
+ "gpu_memory_mb": latest.get("gpu_memory_mb"),
702
+ },
703
+ "sample": latest.get("sample"),
704
+ "checkpoint": checkpoint.name,
705
+ }
706
+
707
+
708
+ @app.get("/health")
709
+ def health() -> Dict[str, Any]:
710
+ return {
711
+ "status": "ready",
712
+ "device": str(DEVICE),
713
+ "models": {
714
+ "pix2pix": model_status(PIX2PIX_MODEL, PIX2PIX_ERROR, PIX2PIX_CHECKPOINT),
715
+ "sarfusionformer": model_status(
716
+ SARFUSIONFORMER_MODEL, SARFUSIONFORMER_ERROR, SARFUSIONFORMER_CHECKPOINT
717
+ ),
718
+ "color_corrector": model_status(
719
+ COLOR_CORRECTOR, COLOR_CORRECTOR_ERROR, COLOR_CORRECTOR_CHECKPOINT
720
+ ),
721
+ "sar_translation_service": get_sar_translation_service().health_payload(),
722
+ },
723
+ "vision_analysis": {**VISION_ANALYSIS.status(), **PROVIDER_SETTINGS.public_status()},
724
+ }
725
+
726
+
727
+ @app.get("/api/benchmark")
728
+ def benchmark() -> Dict[str, Any]:
729
+ """Return real checkpoint metadata and the latest in-memory measured sample."""
730
+ return {
731
+ "models": {
732
+ "pix2pix": benchmark_model_payload("pix2pix", PIX2PIX_CHECKPOINT),
733
+ "sarfusionformer": benchmark_model_payload("sarfusionformer", SARFUSIONFORMER_CHECKPOINT),
734
+ }
735
+ }
736
+
737
+
738
+ @app.post("/predict")
739
+ async def predict(file: UploadFile = File(...)) -> StreamingResponse:
740
+ """Legacy Pix2Pix endpoint retained for existing clients."""
741
+ try:
742
+ payload = pix2pix_payload(read_upload(file))
743
+ output_bytes = base64.b64decode(payload["output"])
744
+ return StreamingResponse(io.BytesIO(output_bytes), media_type="image/png")
745
+ except ValueError as error:
746
+ raise HTTPException(status_code=400, detail=str(error)) from error
747
+
748
+
749
+ @app.post("/evaluate")
750
+ async def evaluate(
751
+ sar_file: UploadFile = File(...), optical_file: UploadFile = File(...)
752
+ ) -> StreamingResponse:
753
+ """Legacy Pix2Pix evaluation endpoint retained for existing clients."""
754
+ try:
755
+ payload = pix2pix_payload(read_upload(sar_file), read_upload(optical_file))
756
+ output_bytes = base64.b64decode(payload["output"])
757
+ metrics = payload["metrics"] or {}
758
+ return StreamingResponse(
759
+ io.BytesIO(output_bytes),
760
+ media_type="image/png",
761
+ headers={
762
+ "X-PSNR": "{:.2f}".format(metrics["psnr"]) if metrics["psnr"] is not None else "N/A",
763
+ "X-SSIM": "{:.4f}".format(metrics["ssim"]) if metrics["ssim"] is not None else "N/A",
764
+ },
765
+ )
766
+ except ValueError as error:
767
+ raise HTTPException(status_code=400, detail=str(error)) from error
768
+
769
+
770
+ @app.post("/api/pix2pix/infer")
771
+ async def pix2pix_infer(
772
+ file: UploadFile = File(...), ground_truth: Optional[UploadFile] = File(None)
773
+ ) -> JSONResponse:
774
+ try:
775
+ target = read_upload(ground_truth) if ground_truth else None
776
+ input_bytes = read_upload(file)
777
+ payload = pix2pix_payload(input_bytes, target)
778
+ request_id = str(uuid.uuid4())
779
+ input_image = decode_rgb(input_bytes)
780
+ output_bytes = base64.b64decode(payload["output"])
781
+ output_image = decode_rgb(output_bytes)
782
+ input_preview = store_model_preview(input_image, "SAR input", "input", Modality.SAR)
783
+ output_preview = store_model_preview(output_image, "Pix2Pix optical reconstruction", "output", Modality.OPTICAL)
784
+ record_model_result(
785
+ task=ComparisonTask.PIX2PIX,
786
+ request_id=request_id,
787
+ primary_hash=hash_bytes(input_bytes),
788
+ component_hashes=(),
789
+ input_previews=[input_preview],
790
+ output_previews=[output_preview],
791
+ output_hashes=[hash_bytes(output_bytes)],
792
+ statistics={"reconstruction": payload["metrics"] or {}},
793
+ execution_duration_ms=payload["inference_time_ms"],
794
+ device=str(DEVICE),
795
+ provenance={"model": "Pix2Pix", "checkpoint": PIX2PIX_CHECKPOINT.name, "method": "SAR-to-optical reconstruction"},
796
+ warnings=[],
797
+ safe_parameters={"ground_truth_available": target is not None},
798
+ )
799
+ payload.update({"request_id": request_id, "created_at": comparison_utc_now()})
800
+ return JSONResponse(payload)
801
+ except ValueError as error:
802
+ raise HTTPException(status_code=400, detail=str(error)) from error
803
+
804
+
805
+ @app.post("/api/sarfusionformer/infer")
806
+ async def sarfusionformer_infer(
807
+ combined_file: Optional[UploadFile] = File(None),
808
+ vv_file: Optional[UploadFile] = File(None),
809
+ vh_file: Optional[UploadFile] = File(None),
810
+ ground_truth: Optional[UploadFile] = File(None),
811
+ apply_color_correction: bool = Form(False),
812
+ ) -> JSONResponse:
813
+ try:
814
+ primary_hash: str
815
+ component_hashes: list[str]
816
+ source_mode: str
817
+ if combined_file is not None:
818
+ if Path(combined_file.filename or "").suffix.lower() != ".npy":
819
+ raise ValueError("Combined VV/VH input must be a NumPy (.npy) file.")
820
+ combined_bytes = read_upload(combined_file)
821
+ vv, vh, channel_layout, detected_shape = load_combined_sar_npy(
822
+ combined_bytes
823
+ )
824
+ primary_hash = hash_bytes(combined_bytes)
825
+ component_hashes = []
826
+ source_mode = "combined_vv_vh"
827
+ elif vv_file is not None and vh_file is not None:
828
+ vv_bytes = read_upload(vv_file)
829
+ vh_bytes = read_upload(vh_file)
830
+ vv = decode_grayscale(vv_bytes, vv_file.filename or "")
831
+ vh = decode_grayscale(vh_bytes, vh_file.filename or "")
832
+ channel_layout = "Separate VV and VH files"
833
+ detected_shape = tuple(vv.shape)
834
+ primary_hash = hash_bytes(vv_bytes)
835
+ component_hashes = [hash_bytes(vv_bytes), hash_bytes(vh_bytes)]
836
+ source_mode = "separate_vv_vh"
837
+ elif vv_file is None:
838
+ raise ValueError("Provide a combined VV/VH .npy file or upload a VV file.")
839
+ else:
840
+ raise ValueError("Provide a combined VV/VH .npy file or upload a VH file.")
841
+ result = sarfusionformer_generate(
842
+ vv, vh, apply_color_correction=apply_color_correction
843
+ )
844
+ target_bytes = read_upload(ground_truth) if ground_truth else None
845
+ target = decode_rgb(target_bytes) if target_bytes else None
846
+ raw_metrics = calculate_metrics(result["raw_rgb"], target) if target else None
847
+ corrected_metrics = (
848
+ calculate_metrics(result["corrected_raw_rgb"], target)
849
+ if target and result["corrected_raw_rgb"] is not None
850
+ else None
851
+ )
852
+ LATEST_BENCHMARKS["sarfusionformer"] = {
853
+ "metrics": raw_metrics,
854
+ "inference_time_ms": round(result["duration_ms"], 2),
855
+ "sample": "current_sample",
856
+ }
857
+ payload = {
858
+ "raw_output": image_to_base64(rgb_float_to_png(result["raw_rgb"])),
859
+ "display_output": image_to_base64(rgb_float_to_png(result["display_rgb"])),
860
+ "corrected_raw_output": (
861
+ image_to_base64(rgb_float_to_png(result["corrected_raw_rgb"]))
862
+ if result["corrected_raw_rgb"] is not None
863
+ else None
864
+ ),
865
+ "corrected_display_output": (
866
+ image_to_base64(rgb_float_to_png(result["corrected_display_rgb"]))
867
+ if result["corrected_display_rgb"] is not None
868
+ else None
869
+ ),
870
+ "vv_preview": image_to_base64(result["previews"]["vv"]),
871
+ "vh_preview": image_to_base64(result["previews"]["vh"]),
872
+ "sar_preview": image_to_base64(result["previews"]["sar"]),
873
+ "metrics_raw": raw_metrics,
874
+ "metrics_corrected": corrected_metrics,
875
+ "inference_time_ms": round(result["duration_ms"], 2),
876
+ "detected_shape": list(detected_shape),
877
+ "channel_layout": channel_layout,
878
+ "checkpoint": SARFUSIONFORMER_CHECKPOINT.name,
879
+ "color_checkpoint": (
880
+ COLOR_CORRECTOR_CHECKPOINT.name
881
+ if result["corrected_raw_rgb"] is not None
882
+ else None
883
+ ),
884
+ "warning": result["warning"],
885
+ "diagnostics": result["diagnostics"],
886
+ "corrected_diagnostics": result["corrected_diagnostics"],
887
+ }
888
+ request_id = str(uuid.uuid4())
889
+ input_previews = [
890
+ store_model_preview(result["previews"]["vv"], "VV input", "input", Modality.SAR),
891
+ store_model_preview(result["previews"]["vh"], "VH input", "input", Modality.SAR),
892
+ store_model_preview(result["previews"]["sar"], "Combined SAR input", "input", Modality.SAR),
893
+ ]
894
+ raw_image = rgb_float_to_png(result["raw_rgb"])
895
+ display_image = rgb_float_to_png(result["display_rgb"])
896
+ if get_sve_service().enabled:
897
+ raw_buffer = io.BytesIO()
898
+ raw_image.save(raw_buffer, format="PNG")
899
+ generated_hash = hash_bytes(raw_buffer.getvalue())
900
+ if target is not None and target_bytes is not None:
901
+ sve_call = await run_in_threadpool(
902
+ get_sve_service().compare,
903
+ target,
904
+ hash_bytes(target_bytes),
905
+ raw_image,
906
+ generated_hash,
907
+ label="Optical-to-generated-RGB semantic consistency",
908
+ disclaimer=(
909
+ "This is supporting scene-level semantic evidence only; it does not establish sensor-native "
910
+ "equivalence, physical accuracy, or registration accuracy."
911
+ ),
912
+ )
913
+ else:
914
+ sve_call = await run_in_threadpool(
915
+ get_sve_service().analyze,
916
+ raw_image,
917
+ generated_hash,
918
+ )
919
+ sve_call = SVECall(
920
+ result=sve_call.result.model_copy(update={
921
+ "warning": "Scene priors were computed from SARFusionFormer-generated RGB-like imagery, not raw SAR or reference optical imagery."
922
+ }),
923
+ trace=sve_call.trace,
924
+ )
925
+ payload["sve_result"] = sve_call.result.model_dump(mode="json")
926
+ else:
927
+ payload["sve_result"] = None
928
+ output_previews = [
929
+ store_model_preview(raw_image, "Raw optical reconstruction", "output", Modality.OPTICAL),
930
+ store_model_preview(display_image, "Enhanced display reconstruction", "output", Modality.OPTICAL),
931
+ ]
932
+ if result["corrected_raw_rgb"] is not None:
933
+ output_previews.append(store_model_preview(rgb_float_to_png(result["corrected_raw_rgb"]), "Color-corrected raw reconstruction", "output", Modality.OPTICAL))
934
+ encoded_outputs = [base64.b64decode(payload["raw_output"]), base64.b64decode(payload["display_output"])]
935
+ if payload["corrected_raw_output"]:
936
+ encoded_outputs.append(base64.b64decode(payload["corrected_raw_output"]))
937
+ record_model_result(
938
+ task=ComparisonTask.SARFUSIONFORMER,
939
+ request_id=request_id,
940
+ primary_hash=primary_hash,
941
+ component_hashes=component_hashes,
942
+ input_previews=input_previews,
943
+ output_previews=output_previews,
944
+ output_hashes=[hash_bytes(value) for value in encoded_outputs],
945
+ statistics={"raw_metrics": raw_metrics or {}, "corrected_metrics": corrected_metrics or {}, "detected_shape": list(detected_shape), "sve_result": payload.get("sve_result") or {}},
946
+ execution_duration_ms=result["duration_ms"],
947
+ device=str(DEVICE),
948
+ provenance={"model": "SARFusionFormer", "checkpoint": SARFUSIONFORMER_CHECKPOINT.name, "color_checkpoint": COLOR_CORRECTOR_CHECKPOINT.name if result["corrected_raw_rgb"] is not None else None, "method": "structure-preserving SAR-to-optical reconstruction"},
949
+ warnings=[result["warning"]] if result["warning"] else [],
950
+ safe_parameters={"source_mode": source_mode, "color_correction_requested": apply_color_correction, "ground_truth_available": target is not None},
951
+ )
952
+ payload.update({"request_id": request_id, "created_at": comparison_utc_now()})
953
+ return JSONResponse(payload)
954
+ except ValueError as error:
955
+ raise HTTPException(status_code=400, detail=str(error)) from error
956
+
957
+
958
+ @app.post("/api/compare")
959
+ async def compare(
960
+ pix2pix_output: UploadFile = File(...),
961
+ sarfusionformer_output: UploadFile = File(...),
962
+ ground_truth: UploadFile = File(...),
963
+ ) -> JSONResponse:
964
+ try:
965
+ target = decode_rgb(read_upload(ground_truth))
966
+ pix_metrics = calculate_metrics(decode_rgb(read_upload(pix2pix_output)), target)
967
+ sar_metrics = calculate_metrics(decode_rgb(read_upload(sarfusionformer_output)), target)
968
+ LATEST_BENCHMARKS["pix2pix"] = {"metrics": pix_metrics, "sample": "current_comparison"}
969
+ LATEST_BENCHMARKS["sarfusionformer"] = {"metrics": sar_metrics, "sample": "current_comparison"}
970
+ return JSONResponse({"pix2pix": pix_metrics, "sarfusionformer": sar_metrics})
971
+ except ValueError as error:
972
+ raise HTTPException(status_code=400, detail=str(error)) from error
973
+
974
+
975
+ def _agent_upload(image_bytes: bytes) -> UploadFile:
976
+ """Create an in-memory upload for the existing SatQuery multipart pipeline."""
977
+ return UploadFile(
978
+ file=io.BytesIO(image_bytes),
979
+ filename="rsvqa-image.png",
980
+ headers=Headers({"content-type": "image/png"}),
981
+ )
982
+
983
+
984
+ def _rsvqa_routed_question(question: str) -> str:
985
+ """Map common RSVQA wording onto the existing controlled VQA taxonomy."""
986
+ normalized = re.sub(r"\s+", " ", question.strip().lower())
987
+ presence_terms = ("is there", "visible", "present", "contain", "show", "can you see")
988
+ if "water" not in normalized and any(term in normalized for term in ("river", "lake", "reservoir")):
989
+ if any(term in normalized for term in presence_terms):
990
+ return "Is a water body visible?"
991
+ if "urban" in normalized and normalized.startswith(("is this urban", "is the scene urban")):
992
+ return "Is this mainly urban or rural?"
993
+ return question.strip()
994
+
995
+
996
+ def _count_grounding_query(question: str) -> Optional[Tuple[str, str]]:
997
+ """Convert a controlled count target into a validated localization request."""
998
+ intent = get_vqa().classify_question(question)
999
+ if intent.category != QuestionCategory.COUNT_VQA or not is_groundable_count_target(intent.target):
1000
+ return None
1001
+ candidate = grounding_prompt_for(intent.raw_target or intent.target or "")
1002
+ if candidate is None:
1003
+ return None
1004
+ try:
1005
+ target = normalize_grounding_target(f"Locate the {candidate}.")
1006
+ except GrounderError:
1007
+ return None
1008
+ return f"Locate the {target}.", target
1009
+
1010
+
1011
+ def _grounding_query_for_concept(
1012
+ target: Optional[str],
1013
+ raw_target: Optional[str] = None,
1014
+ *,
1015
+ require_count: bool = True,
1016
+ ) -> Optional[Tuple[str, str]]:
1017
+ """Build a Grounding DINO request only for a supported controlled concept."""
1018
+ entity = get_remote_sensing_entity(target)
1019
+ if entity is None or not entity.grounding_prompts or (require_count and not entity.count_meaningful):
1020
+ return None
1021
+ prompt = grounding_prompt_for(raw_target or target or "")
1022
+ if prompt is None:
1023
+ return None
1024
+ try:
1025
+ canonical = normalize_grounding_target(f"Locate the {prompt}.")
1026
+ except GrounderError:
1027
+ return None
1028
+ return f"Locate the {canonical}.", canonical
1029
+
1030
+
1031
+ async def _agent_single_image_query(image_bytes: bytes, query: str) -> AgentResponse:
1032
+ """Reuse the authoritative SatQuery single-image execution entry point."""
1033
+ return await agent_image_query(
1034
+ query=query,
1035
+ input_mode=InputMode.SINGLE,
1036
+ primary_modality=Modality.OPTICAL,
1037
+ primary_image_modality=ImageModality.OPTICAL_RGB,
1038
+ primary_image=_agent_upload(image_bytes),
1039
+ secondary_modality=None,
1040
+ secondary_image=None,
1041
+ primary_date=None,
1042
+ secondary_date=None,
1043
+ use_cache=False,
1044
+ force_rerun=True,
1045
+ )
1046
+
1047
+
1048
+ async def _run_satquery_vqa(
1049
+ image_bytes: bytes,
1050
+ question: str,
1051
+ ) -> Tuple[AgentResponse, AgentResponse, Dict[str, AgentResponse], str, QuestionIntent]:
1052
+ """Reuse caption/VQA execution and add accepted-region support when required."""
1053
+ intent = get_vqa().classify_question(question)
1054
+ benchmark_categories = {
1055
+ QuestionCategory.RURAL_URBAN_CLASSIFICATION,
1056
+ QuestionCategory.PRESENCE_VQA,
1057
+ QuestionCategory.COUNT_VQA,
1058
+ QuestionCategory.COMPARISON_VQA,
1059
+ }
1060
+ # The existing alias helper remains available to legacy callers, but the
1061
+ # controlled parser must see the original wording to retain the exact RSVQA
1062
+ # family and entity information.
1063
+ routed_question = question.strip() if intent.category in benchmark_categories else _rsvqa_routed_question(question)
1064
+ caption_response = await _agent_single_image_query(image_bytes, "Describe this image")
1065
+ response = await _agent_single_image_query(image_bytes, routed_question)
1066
+ grounding_responses: Dict[str, AgentResponse] = {}
1067
+ targets: list[Tuple[str, Optional[str], Optional[str]]] = []
1068
+ if intent.category == QuestionCategory.PRESENCE_VQA:
1069
+ targets = [("target", intent.target, intent.raw_target)]
1070
+ elif intent.category == QuestionCategory.COUNT_VQA and intent.spatial_relation is None:
1071
+ targets = [("target", intent.target, intent.raw_target)]
1072
+ elif intent.category == QuestionCategory.COMPARISON_VQA:
1073
+ targets = [
1074
+ ("target", intent.target, intent.raw_target),
1075
+ ("secondary_target", intent.secondary_target, intent.raw_secondary_target),
1076
+ ]
1077
+ response_by_query: Dict[str, AgentResponse] = {}
1078
+ for key, target, raw_target in targets:
1079
+ grounding_request = _grounding_query_for_concept(
1080
+ target,
1081
+ raw_target,
1082
+ require_count=intent.category != QuestionCategory.PRESENCE_VQA,
1083
+ )
1084
+ if grounding_request is None:
1085
+ continue
1086
+ grounding_query, _ = grounding_request
1087
+ if grounding_query not in response_by_query:
1088
+ response_by_query[grounding_query] = await _agent_single_image_query(image_bytes, grounding_query)
1089
+ grounding_responses[key] = response_by_query[grounding_query]
1090
+ return caption_response, response, grounding_responses, routed_question, intent
1091
+
1092
+
1093
+ _BENCHMARK_VQA_CATEGORIES = {
1094
+ QuestionCategory.RURAL_URBAN_CLASSIFICATION,
1095
+ QuestionCategory.PRESENCE_VQA,
1096
+ QuestionCategory.COUNT_VQA,
1097
+ QuestionCategory.COMPARISON_VQA,
1098
+ }
1099
+ _COUNT_LIMITATION = (
1100
+ "Count reflects accepted localized regions, not calibrated object totals. "
1101
+ "Grounding DINO regions are supporting localization evidence, not ground truth."
1102
+ )
1103
+
1104
+
1105
+ def _grounding_region_total(response: Optional[AgentResponse]) -> Optional[int]:
1106
+ if response is None or response.grounding_result is None:
1107
+ return None
1108
+ return len(response.grounding_result.detections)
1109
+
1110
+
1111
+ def _accepted_region_count(response: Optional[AgentResponse]) -> Optional[int]:
1112
+ """Return only positive accepted-region evidence; zero is unconfirmed."""
1113
+ total = _grounding_region_total(response)
1114
+ return total if total is not None and total > 0 else None
1115
+
1116
+
1117
+ @dataclass(frozen=True)
1118
+ class CountEvidence:
1119
+ count: Optional[int]
1120
+ reason_code: str
1121
+ evidence_source: Optional[str]
1122
+ accepted_region_total: Optional[int]
1123
+
1124
+
1125
+ @dataclass(frozen=True)
1126
+ class BenchmarkVQADecision:
1127
+ answer: Optional[str]
1128
+ confidence_response: AgentResponse
1129
+ limitation: Optional[str]
1130
+ answer_source: Optional[str]
1131
+ reason_code: str
1132
+ details: Dict[str, Any]
1133
+ trace_stage: str
1134
+
1135
+
1136
+ def _count_evidence(
1137
+ target: Optional[str],
1138
+ response: Optional[AgentResponse],
1139
+ *,
1140
+ spatial_relation: Optional[str] = None,
1141
+ ) -> CountEvidence:
1142
+ entity = get_remote_sensing_entity(target)
1143
+ if spatial_relation:
1144
+ return CountEvidence(None, "spatial_relation_unsupported", None, _grounding_region_total(response))
1145
+ if entity is None or not entity.count_meaningful or not entity.grounding_prompts:
1146
+ return CountEvidence(None, "unsupported_count_target", None, _grounding_region_total(response))
1147
+ total = _grounding_region_total(response)
1148
+ if total is None:
1149
+ return CountEvidence(None, "grounding_unavailable", None, None)
1150
+ if total == 0:
1151
+ return CountEvidence(None, "zero_regions_unconfirmed", "Grounding DINO", 0)
1152
+ return CountEvidence(total, "accepted_regions", "Grounding DINO accepted regions", total)
1153
+
1154
+
1155
+ def _compare_count_evidence(
1156
+ first: CountEvidence,
1157
+ second: CountEvidence,
1158
+ relation: Optional[str],
1159
+ ) -> Tuple[Optional[str], bool, List[str], str]:
1160
+ unavailable = [name for name, item in (("entity_a", first), ("entity_b", second)) if item.count is None]
1161
+ comparable = (
1162
+ not unavailable
1163
+ and first.evidence_source is not None
1164
+ and first.evidence_source == second.evidence_source
1165
+ )
1166
+ if unavailable:
1167
+ return None, False, unavailable, "comparison_operand_unavailable"
1168
+ if not comparable:
1169
+ return None, False, [], "incomparable_evidence"
1170
+ operation = {
1171
+ "less": first.count < second.count,
1172
+ "more": first.count > second.count,
1173
+ "equal": first.count == second.count,
1174
+ }.get(relation)
1175
+ if operation is None:
1176
+ return None, True, [], "comparison_logic_unavailable"
1177
+ return "yes" if operation else "no", True, [], "comparison_logic_applied"
1178
+
1179
+
1180
+ def _sve_presence_signal(response: AgentResponse, target: Optional[str]) -> Tuple[Optional[str], Dict[str, Any]]:
1181
+ entity = get_remote_sensing_entity(target)
1182
+ sve = response.sve_result
1183
+ if entity is None or not entity.presence_uses_semantics or sve is None or not sve.available:
1184
+ return None, {"available": False, "matched_labels": []}
1185
+ labels = [prior.label for prior in sve.scene_priors]
1186
+ ranks = [labels.index(label) for label in entity.scene_prior_labels if label in labels]
1187
+ matched = [label for label in entity.scene_prior_labels if label in labels]
1188
+ if ranks and min(ranks) <= 2:
1189
+ return "yes", {"available": True, "matched_labels": matched, "best_rank": min(ranks) + 1}
1190
+ if labels and not ranks:
1191
+ return "no", {"available": True, "matched_labels": [], "top_labels_checked": len(labels)}
1192
+ return None, {"available": bool(labels), "matched_labels": matched, "best_rank": min(ranks) + 1 if ranks else None}
1193
+
1194
+
1195
+ def _caption_presence_signal(caption: str, target: Optional[str]) -> Tuple[Optional[str], Dict[str, Any]]:
1196
+ entity = get_remote_sensing_entity(target)
1197
+ normalized = normalize_entity_text(caption)
1198
+ if entity is None or not entity.presence_uses_semantics or not normalized:
1199
+ return None, {"available": False, "matched_terms": []}
1200
+ aliases = sorted({normalize_entity_text(alias) for alias in entity.aliases}, key=len, reverse=True)
1201
+ matched = [alias for alias in aliases if re.search(rf"\b{re.escape(alias)}\b", normalized)]
1202
+ negative = any(
1203
+ re.search(rf"\b(?:no|without|lacks?|absent)\s+(?:visible\s+)?{re.escape(alias)}\b", normalized)
1204
+ or re.search(rf"\b(?:does not|doesn t|not)\s+(?:contain|show|include)\s+(?:any\s+)?{re.escape(alias)}\b", normalized)
1205
+ for alias in aliases
1206
+ )
1207
+ if negative:
1208
+ return "no", {"available": True, "matched_terms": matched, "explicit_absence": True}
1209
+ if matched:
1210
+ return "yes", {"available": True, "matched_terms": matched[:3], "explicit_absence": False}
1211
+ return None, {"available": True, "matched_terms": []}
1212
+
1213
+
1214
+ def _presence_decision(
1215
+ intent: QuestionIntent,
1216
+ question_response: AgentResponse,
1217
+ caption_response: AgentResponse,
1218
+ grounding_response: Optional[AgentResponse],
1219
+ ) -> Tuple[Optional[str], str, Optional[str], Dict[str, Any], AgentResponse]:
1220
+ entity = get_remote_sensing_entity(intent.target)
1221
+ if entity is None:
1222
+ return None, "unsupported_target", None, {"evidence_sources": {}}, question_response
1223
+
1224
+ grounding_total = _grounding_region_total(grounding_response)
1225
+ signals: Dict[str, Optional[str]] = {
1226
+ "grounding": "yes" if grounding_total is not None and grounding_total > 0 else None,
1227
+ }
1228
+ sve_signal, sve_details = _sve_presence_signal(question_response, intent.target)
1229
+ caption_signal, caption_details = _caption_presence_signal(caption_response.answer or "", intent.target)
1230
+ deterministic_signal = normalize_benchmark_answer(question_response.answer, "yes_no")
1231
+ signals.update({"scene_prior": sve_signal, "caption": caption_signal, "deterministic": deterministic_signal})
1232
+ details = {
1233
+ "evidence_sources": signals,
1234
+ "grounding_region_total": grounding_total,
1235
+ "scene_prior": sve_details,
1236
+ "caption": caption_details,
1237
+ }
1238
+ if signals["grounding"] == "yes":
1239
+ return "yes", "positive_grounding", "Grounding DINO accepted regions", details, grounding_response or question_response
1240
+ positives = [name for name, signal in signals.items() if signal == "yes"]
1241
+ negatives = [name for name, signal in signals.items() if signal == "no"]
1242
+ if positives and negatives:
1243
+ return None, "conflicting_evidence", None, details, question_response
1244
+ if positives:
1245
+ preferred = next(name for name in ("scene_prior", "caption", "deterministic") if name in positives)
1246
+ reason = {"scene_prior": "positive_scene_prior", "caption": "positive_caption", "deterministic": "positive_scene_prior"}[preferred]
1247
+ source = {"scene_prior": "SatQuery Vision Encoder scene priors", "caption": "caption semantic evidence", "deterministic": "existing deterministic scene evidence"}[preferred]
1248
+ return "yes", reason, source, details, question_response
1249
+ if len(negatives) >= 2:
1250
+ return "no", "multi_source_absence", "consistent multi-source absence evidence", details, question_response
1251
+ return None, "insufficient_evidence", None, details, question_response
1252
+
1253
+
1254
+ def _rural_urban_evidence_fusion(
1255
+ question_response: AgentResponse,
1256
+ caption_response: AgentResponse,
1257
+ ) -> Tuple[Optional[str], str, Dict[str, Any]]:
1258
+ """Fuse bounded source scores; returned scores are not probabilities."""
1259
+ urban_labels = {"urban or built-up area", "industrial area", "residential area", "road network"}
1260
+ rural_labels = {"agricultural land", "arable land", "pasture", "forest", "grassland", "vegetation"}
1261
+ source_scores: Dict[str, Dict[str, float]] = {}
1262
+ evidence_terms: Dict[str, List[str]] = {"urban": [], "rural": []}
1263
+
1264
+ sve = question_response.sve_result
1265
+ if sve is not None and sve.available and sve.scene_priors:
1266
+ labels = [prior.label for prior in sve.scene_priors]
1267
+ urban_matches = [(label, 1.0 / (index + 1)) for index, label in enumerate(labels) if label in urban_labels]
1268
+ rural_matches = [(label, 1.0 / (index + 1)) for index, label in enumerate(labels) if label in rural_labels]
1269
+ source_scores["scene_prior"] = {
1270
+ "urban": max((score for _, score in urban_matches), default=0.0),
1271
+ "rural": max((score for _, score in rural_matches), default=0.0),
1272
+ }
1273
+ evidence_terms["urban"].extend(label for label, _ in urban_matches)
1274
+ evidence_terms["rural"].extend(label for label, _ in rural_matches)
1275
+
1276
+ caption = normalize_entity_text(caption_response.answer or "")
1277
+ if caption:
1278
+ caption_urban = [term for term in ("urban", "built up", "residential", "industrial", "dense buildings", "dense road") if term in caption]
1279
+ caption_rural = [term for term in ("rural", "agricultural", "arable", "pasture", "forest", "grassland", "farmland", "sparse development") if term in caption]
1280
+ if caption_urban or caption_rural:
1281
+ source_scores["caption"] = {"urban": min(1.0, len(caption_urban) / 2.0), "rural": min(1.0, len(caption_rural) / 2.0)}
1282
+ evidence_terms["urban"].extend(caption_urban)
1283
+ evidence_terms["rural"].extend(caption_rural)
1284
+
1285
+ statistics = question_response.vqa_details.statistics_used if question_response.vqa_details else {}
1286
+ built = statistics.get("built_up_support_percent")
1287
+ rural_support = statistics.get("rural_support_percent")
1288
+ if isinstance(built, (int, float)) and isinstance(rural_support, (int, float)):
1289
+ source_scores["scene_evidence"] = {
1290
+ "urban": max(0.0, min(1.0, float(built) / 100.0)),
1291
+ "rural": max(0.0, min(1.0, float(rural_support) / 100.0)),
1292
+ }
1293
+
1294
+ weights = {"scene_prior": 0.55, "caption": 0.20, "scene_evidence": 0.25}
1295
+ available_weight = sum(weights[source] for source in source_scores)
1296
+ if available_weight <= 0:
1297
+ return None, "insufficient_evidence", {"urban_score": 0.0, "rural_score": 0.0, "margin": 0.0, "evidence_terms": evidence_terms, "source_scores": {}}
1298
+ urban_score = sum(weights[source] * scores["urban"] for source, scores in source_scores.items()) / available_weight
1299
+ rural_score = sum(weights[source] * scores["rural"] for source, scores in source_scores.items()) / available_weight
1300
+ signed_margin = urban_score - rural_score
1301
+ margin = abs(signed_margin)
1302
+ details = {
1303
+ "urban_score": round(urban_score, 6),
1304
+ "rural_score": round(rural_score, 6),
1305
+ "margin": round(margin, 6),
1306
+ "minimum_margin": 0.12,
1307
+ "scores_are_calibrated_probabilities": False,
1308
+ "source_weights": {source: weights[source] for source in source_scores},
1309
+ "source_scores": source_scores,
1310
+ "evidence_terms": evidence_terms,
1311
+ }
1312
+ if margin < 0.12:
1313
+ return None, "insufficient_evidence", details
1314
+ return ("urban" if signed_margin > 0 else "rural"), "weighted_evidence_margin", details
1315
+
1316
+
1317
+ def _benchmark_vqa_result(
1318
+ intent: QuestionIntent,
1319
+ question_response: AgentResponse,
1320
+ caption_response: AgentResponse,
1321
+ grounding_responses: Dict[str, AgentResponse],
1322
+ ) -> BenchmarkVQADecision:
1323
+ """Fuse existing specialist outputs into a normalized benchmark answer.
1324
+
1325
+ Returns ``answer, confidence_source, limitation, answer_source``. No model
1326
+ is invoked here; this is a controlled adapter over the authoritative agent
1327
+ responses produced above.
1328
+ """
1329
+ category = intent.category
1330
+ if category == QuestionCategory.RURAL_URBAN_CLASSIFICATION:
1331
+ answer, reason, details = _rural_urban_evidence_fusion(question_response, caption_response)
1332
+ answer = normalize_benchmark_answer(answer, "rural_urban")
1333
+ return BenchmarkVQADecision(answer, question_response, None, "bounded rural/urban evidence fusion" if answer else None, reason, details, "vqa_rural_urban_evidence_fusion")
1334
+ if category == QuestionCategory.PRESENCE_VQA:
1335
+ answer, reason, source, details, response = _presence_decision(
1336
+ intent, question_response, caption_response, grounding_responses.get("target")
1337
+ )
1338
+ return BenchmarkVQADecision(normalize_benchmark_answer(answer, "yes_no"), response, None, source, reason, details, "vqa_presence_evidence_fusion")
1339
+ if category == QuestionCategory.COUNT_VQA:
1340
+ evidence_response = grounding_responses.get("target")
1341
+ count = _count_evidence(intent.target, evidence_response, spatial_relation=intent.spatial_relation)
1342
+ answer = normalize_benchmark_answer(str(count.count) if count.count is not None else None, "integer")
1343
+ return BenchmarkVQADecision(answer, evidence_response or question_response, _COUNT_LIMITATION, count.evidence_source, count.reason_code, {
1344
+ "canonical_target": intent.target,
1345
+ "accepted_region_count": count.accepted_region_total,
1346
+ "spatial_relation": intent.spatial_relation,
1347
+ }, "vqa_count_evidence_validation")
1348
+ if category == QuestionCategory.COMPARISON_VQA:
1349
+ first_response = grounding_responses.get("target")
1350
+ second_response = grounding_responses.get("secondary_target")
1351
+ first = _count_evidence(intent.target, first_response)
1352
+ second = _count_evidence(intent.secondary_target, second_response)
1353
+ raw_answer, comparable, unavailable, comparison_reason = _compare_count_evidence(
1354
+ first, second, intent.comparison_relation
1355
+ )
1356
+ details = {
1357
+ "entity_a": intent.target,
1358
+ "count_a": first.count,
1359
+ "entity_b": intent.secondary_target,
1360
+ "count_b": second.count,
1361
+ "relation": intent.comparison_relation,
1362
+ "comparable_evidence": comparable,
1363
+ "unavailable_operands": unavailable,
1364
+ "operand_reason_codes": {"entity_a": first.reason_code, "entity_b": second.reason_code},
1365
+ }
1366
+ response = first_response or second_response or question_response
1367
+ answer = normalize_benchmark_answer(raw_answer, "yes_no")
1368
+ return BenchmarkVQADecision(
1369
+ answer,
1370
+ response,
1371
+ _COUNT_LIMITATION,
1372
+ "Grounding DINO accepted-region evidence" if answer is not None else None,
1373
+ comparison_reason,
1374
+ details,
1375
+ "vqa_comparison_operand_resolution",
1376
+ )
1377
+ return BenchmarkVQADecision(question_response.answer, question_response, None, None, "legacy_vqa", {}, "vqa_answer_normalization")
1378
+
1379
+
1380
+ def _numeric_confidence(response: AgentResponse) -> float:
1381
+ if response.confidence.score is not None:
1382
+ return max(0.0, min(1.0, float(response.confidence.score)))
1383
+ return {
1384
+ "high": 0.75,
1385
+ "moderate": 0.50,
1386
+ "low": 0.25,
1387
+ "unavailable": 0.0,
1388
+ }.get(response.confidence.level.value, 0.0)
1389
+
1390
+
1391
+ def _trace(response: AgentResponse, pipeline_stage: str) -> List[Dict[str, Any]]:
1392
+ return [
1393
+ {**step.model_dump(mode="json"), "pipeline_stage": pipeline_stage}
1394
+ for step in response.execution.steps
1395
+ ]
1396
+
1397
+
1398
+ def _selected_models(*responses: Optional[AgentResponse]) -> str:
1399
+ selected: List[str] = []
1400
+ for response in responses:
1401
+ if response is None:
1402
+ continue
1403
+ if response.sve_result is not None and response.sve_result.available:
1404
+ selected.append("satquery_vision_encoder_v1")
1405
+ selected.extend(tool for tool in response.execution.selected_tools if tool != "input_validator")
1406
+ return " + ".join(dict.fromkeys(selected)) or "satquery-agent"
1407
+
1408
+
1409
+ def _vqa_compatibility_report(
1410
+ caption: str,
1411
+ answer: Optional[str],
1412
+ confidence_level: str,
1413
+ warnings: List[str],
1414
+ ) -> Dict[str, Any]:
1415
+ """Retain the legacy report shape without invoking an external provider."""
1416
+ legacy_confidence = {
1417
+ "high": "high",
1418
+ "moderate": "medium",
1419
+ "low": "low",
1420
+ "unavailable": "low",
1421
+ }.get(confidence_level, "low")
1422
+ return {
1423
+ "executive_summary": caption,
1424
+ "terrain": [],
1425
+ "structural_and_human_features": [],
1426
+ "vegetation_and_water": [],
1427
+ "image_quality": [],
1428
+ "possible_artifacts": [],
1429
+ "notes": [answer] if answer else [],
1430
+ "limitations": warnings,
1431
+ "recommended_actions": ["Review the returned evidence, execution trace, and specialist limitations."],
1432
+ "confidence": legacy_confidence,
1433
+ "disclaimer": "SatQuery outputs are supporting model and heuristic evidence, not ground truth.",
1434
+ }
1435
+
1436
+
1437
+ async def _direct_rsvqa_endpoint_result(
1438
+ image: Image.Image,
1439
+ image_bytes: bytes,
1440
+ question: str,
1441
+ request_id: str,
1442
+ endpoint_started: float,
1443
+ ) -> Optional[Dict[str, Any]]:
1444
+ """Use the trained specialist as the primary RSVQA answer source when available."""
1445
+ intent = get_vqa().classify_question(question)
1446
+ if intent.category not in _BENCHMARK_VQA_CATEGORIES:
1447
+ return None
1448
+ try:
1449
+ prediction = await run_in_threadpool(
1450
+ get_rsvqa_specialist().predict,
1451
+ image,
1452
+ question,
1453
+ content_hash=hashlib.sha256(image_bytes).hexdigest(),
1454
+ )
1455
+ except RSVQASpecialistError as error:
1456
+ LOGGER.warning(
1457
+ "RSVQA Specialist v1 inference failed; using heuristic fallback: request_id=%s error=%s",
1458
+ request_id,
1459
+ error,
1460
+ )
1461
+ return None
1462
+
1463
+ answer = str(prediction["answer"])
1464
+ confidence = max(0.0, min(1.0, float(prediction["confidence"])))
1465
+ task = str(prediction["task"])
1466
+ level = "high" if confidence >= 0.75 else "moderate" if confidence >= 0.50 else "low"
1467
+ limitations = [
1468
+ "Softmax confidence is not calibrated.",
1469
+ "Count outputs are learned RSVQA labels rather than physical object inventories.",
1470
+ "Captioning, SVE scene evidence, and Grounding DINO are optional supporting evidence and were not required for this prediction.",
1471
+ ]
1472
+ return {
1473
+ "report": _vqa_compatibility_report(
1474
+ "RSVQA Specialist v1 produced the primary visual-question answer.",
1475
+ answer,
1476
+ level,
1477
+ limitations,
1478
+ ),
1479
+ "provider": "satquery",
1480
+ "model": RSVQA_MODEL_USED,
1481
+ "cached": False,
1482
+ "request_id": request_id,
1483
+ "answer": answer,
1484
+ "confidence": confidence,
1485
+ "confidence_details": {
1486
+ "level": level,
1487
+ "score": confidence,
1488
+ "reason": "Maximum exported task-head softmax score; not calibrated.",
1489
+ },
1490
+ "caption": None,
1491
+ "evidence": [],
1492
+ "execution_trace": [
1493
+ {
1494
+ "tool": "query_routing",
1495
+ "status": "success",
1496
+ "duration_ms": 0,
1497
+ "parameters": {"primary_prediction_source": "rsvqa_vqa_specialist"},
1498
+ "pipeline_stage": "routing",
1499
+ },
1500
+ {
1501
+ "tool": "sve_shared_encoder",
1502
+ "status": "success",
1503
+ "duration_ms": int(prediction["encoder"].get("runtime_ms", 0)),
1504
+ "parameters": {
1505
+ "model_reused": prediction["encoder"].get("model_reused"),
1506
+ "image_cache_hit": prediction["encoder"].get("image_cache_hit"),
1507
+ "text_cache_hit": prediction["encoder"].get("text_cache_hit"),
1508
+ "device": prediction["encoder"].get("device"),
1509
+ },
1510
+ "pipeline_stage": "shared_encoder",
1511
+ },
1512
+ {
1513
+ "tool": "rsvqa_vqa_specialist",
1514
+ "status": "success",
1515
+ "duration_ms": int(prediction.get("runtime_ms", 0)),
1516
+ "parameters": {"task_head": task, "confidence_calibrated": False},
1517
+ "pipeline_stage": "primary_prediction",
1518
+ },
1519
+ ],
1520
+ "task": task,
1521
+ "model_used": RSVQA_MODEL_USED,
1522
+ "processing_time_ms": max(0, round((time.perf_counter() - endpoint_started) * 1000)),
1523
+ "question": question,
1524
+ "routed_question": question.strip(),
1525
+ "status": "success",
1526
+ "result_status": "COMPLETED",
1527
+ "warnings": limitations,
1528
+ "vqa_details": {
1529
+ "question_category": intent.category.value,
1530
+ "answer_source": RSVQA_MODEL_USED,
1531
+ "task": task,
1532
+ "logits": prediction["logits"],
1533
+ "probabilities": prediction["probabilities"],
1534
+ "confidence_calibrated": False,
1535
+ },
1536
+ "grounding_result": None,
1537
+ "sve_result": None,
1538
+ }
1539
+
1540
+
1541
+ @app.post("/api/analysis/image", response_model=ImageAnalysisEndpointResponse)
1542
+ async def analyze_image(
1543
+ image: UploadFile = File(...),
1544
+ analysis_type: str = Form(...),
1545
+ model_name: str = Form(...),
1546
+ checkpoint_name: Optional[str] = Form(None),
1547
+ display_mode: Optional[str] = Form(None),
1548
+ metrics_json: Optional[str] = Form(None),
1549
+ metadata_json: Optional[str] = Form(None),
1550
+ # Legacy field retained for existing clients during migration.
1551
+ metadata: Optional[str] = Form(None),
1552
+ question: Optional[str] = Form(
1553
+ None,
1554
+ min_length=1,
1555
+ max_length=2000,
1556
+ description="Optional RSVQA question. Omit it to preserve the legacy qualitative image-review response.",
1557
+ ),
1558
+ ) -> JSONResponse:
1559
+ """Qualitatively review an image and optionally run benchmarkable SatQuery VQA."""
1560
+ endpoint_started = time.perf_counter()
1561
+ request_id = uuid.uuid4().hex[:12]
1562
+ try:
1563
+ uploaded_mime = (image.content_type or "").lower()
1564
+ if uploaded_mime not in {"image/png", "image/jpeg", "image/webp"}:
1565
+ raise VisionAnalysisError("The generated image could not be prepared for analysis.", "INVALID_IMAGE")
1566
+ image_bytes = read_upload(image)
1567
+ if not image_bytes:
1568
+ raise VisionAnalysisError("The generated image is empty.", "INVALID_IMAGE")
1569
+ if len(image_bytes) > MAX_UPLOAD_BYTES:
1570
+ raise VisionAnalysisError("The generated image exceeds the AI Analysis upload limit.", "IMAGE_TOO_LARGE")
1571
+ if question is None and model_name.strip() != (VISION_ANALYSIS.settings.model or "").strip():
1572
+ raise VisionAnalysisError("The selected Gemini model is unavailable. Choose a supported model in Settings.", "UNSUPPORTED_MODEL")
1573
+ metadata_object: Dict[str, Any] = {
1574
+ "model_name": model_name.strip(), "checkpoint_name": checkpoint_name,
1575
+ "display_mode": display_mode,
1576
+ }
1577
+ for raw_value, label in ((metrics_json, "metrics_json"), (metadata_json or metadata, "metadata_json")):
1578
+ if not raw_value:
1579
+ continue
1580
+ parsed = json.loads(raw_value)
1581
+ if not isinstance(parsed, dict):
1582
+ raise ValueError("{} must be a JSON object.".format(label))
1583
+ metadata_object[label] = parsed
1584
+ LOGGER.info(
1585
+ "AI analysis request: request_id=%s endpoint=/api/analysis/image type=%s model=%s bytes=%d mime=%s checkpoint=%s display_mode=%s",
1586
+ request_id, analysis_type, model_name, len(image_bytes), uploaded_mime,
1587
+ checkpoint_name or "none", display_mode or "none",
1588
+ )
1589
+ decoded = decode_rgb(image_bytes)
1590
+ buffer = io.BytesIO()
1591
+ decoded.save(buffer, format="PNG")
1592
+ normalized_png = buffer.getvalue()
1593
+ if question is None:
1594
+ # This is the original endpoint behavior. Do not route through SatQuery or
1595
+ # alter the provider response when the optional question is absent.
1596
+ result = VISION_ANALYSIS.analyze_image(normalized_png, "image/png", analysis_type, metadata_object)
1597
+ result["request_id"] = request_id
1598
+ else:
1599
+ direct_result = await _direct_rsvqa_endpoint_result(
1600
+ decoded,
1601
+ normalized_png,
1602
+ question,
1603
+ request_id,
1604
+ endpoint_started,
1605
+ )
1606
+ if direct_result is not None:
1607
+ LOGGER.info(
1608
+ "AI analysis completed: request_id=%s provider=satquery model=%s cached=false vqa=true",
1609
+ request_id,
1610
+ RSVQA_MODEL_USED,
1611
+ )
1612
+ return JSONResponse(direct_result)
1613
+ caption_response, question_response, grounding_responses, routed_question, intent = await _run_satquery_vqa(
1614
+ normalized_png,
1615
+ question,
1616
+ )
1617
+ decision = _benchmark_vqa_result(
1618
+ intent,
1619
+ question_response,
1620
+ caption_response,
1621
+ grounding_responses,
1622
+ )
1623
+ answer = decision.answer
1624
+ answer_response = decision.confidence_response
1625
+ benchmark_limitation = decision.limitation
1626
+ answer_source = decision.answer_source
1627
+ evidence = [item.model_dump(mode="json") for item in question_response.evidence]
1628
+ for grounding_response in grounding_responses.values():
1629
+ evidence.extend(item.model_dump(mode="json") for item in grounding_response.evidence)
1630
+ trace = _trace(caption_response, "captioning") + _trace(question_response, "vqa")
1631
+ for grounding_response in grounding_responses.values():
1632
+ trace.extend(_trace(grounding_response, "grounding_support"))
1633
+ trace.append({
1634
+ "tool": "vqa_evidence_fusion",
1635
+ "status": "success",
1636
+ "duration_ms": 0,
1637
+ "parameters": {
1638
+ "evidence_items": len(evidence),
1639
+ "grounding_used": bool(grounding_responses),
1640
+ "benchmark_category": intent.category.value,
1641
+ },
1642
+ "pipeline_stage": "evidence_fusion",
1643
+ })
1644
+ if intent.category in _BENCHMARK_VQA_CATEGORIES:
1645
+ trace.extend([
1646
+ {
1647
+ "tool": "vqa_target_resolution",
1648
+ "status": "success",
1649
+ "duration_ms": 0,
1650
+ "parameters": {
1651
+ "canonical_target": intent.target,
1652
+ "canonical_secondary_target": intent.secondary_target,
1653
+ },
1654
+ "pipeline_stage": "vqa_target_resolution",
1655
+ },
1656
+ {
1657
+ "tool": decision.trace_stage,
1658
+ "status": "success" if answer is not None else "partial",
1659
+ "duration_ms": 0,
1660
+ "parameters": {
1661
+ "evidence_sources": sorted({
1662
+ source for source in (
1663
+ decision.answer_source,
1664
+ *(decision.details.get("evidence_sources", {}).keys()),
1665
+ ) if source
1666
+ }),
1667
+ "reason_code": decision.reason_code,
1668
+ "comparable_evidence": decision.details.get("comparable_evidence"),
1669
+ },
1670
+ "pipeline_stage": decision.trace_stage,
1671
+ },
1672
+ {
1673
+ "tool": "vqa_answer_normalization",
1674
+ "status": "success" if answer is not None else "partial",
1675
+ "duration_ms": 0,
1676
+ "parameters": {
1677
+ "normalized_answer": answer,
1678
+ "reason_code": decision.reason_code,
1679
+ },
1680
+ "pipeline_stage": "vqa_answer_normalization",
1681
+ },
1682
+ ])
1683
+ satquery_models = _selected_models(caption_response, question_response, *grounding_responses.values())
1684
+ caption = caption_response.answer or "The local remote-sensing captioner did not produce a caption for this image."
1685
+ warnings = list(dict.fromkeys(
1686
+ caption_response.warnings
1687
+ + question_response.warnings
1688
+ + [warning for response in grounding_responses.values() for warning in response.warnings]
1689
+ ))
1690
+ insufficient = intent.category in _BENCHMARK_VQA_CATEGORIES and answer is None
1691
+ if insufficient:
1692
+ warnings.append(
1693
+ "Evidence was insufficient for a normalized benchmark answer; no answer was fabricated."
1694
+ )
1695
+ warnings = list(dict.fromkeys(warnings))
1696
+ confidence_details = answer_response.confidence.model_dump(mode="json")
1697
+ if benchmark_limitation:
1698
+ confidence_details["limitation"] = benchmark_limitation
1699
+ if insufficient:
1700
+ confidence_details["reason"] = (
1701
+ f"{confidence_details.get('reason', 'No usable specialist evidence was returned.')} "
1702
+ "The endpoint therefore returned null rather than guessing."
1703
+ )
1704
+ vqa_details = question_response.vqa_details.model_dump(mode="json") if question_response.vqa_details else None
1705
+ if vqa_details is not None and intent.category in _BENCHMARK_VQA_CATEGORIES:
1706
+ vqa_details.update({
1707
+ "benchmark_answer_source": answer_source,
1708
+ "benchmark_answer_normalization": "yes_no" if intent.category in {QuestionCategory.PRESENCE_VQA, QuestionCategory.COMPARISON_VQA} else "rural_urban" if intent.category == QuestionCategory.RURAL_URBAN_CLASSIFICATION else "integer",
1709
+ "benchmark_answer": answer,
1710
+ "reason_code": decision.reason_code,
1711
+ "evidence_fusion": decision.details,
1712
+ })
1713
+ if intent.category == QuestionCategory.COMPARISON_VQA:
1714
+ vqa_details["comparison"] = decision.details
1715
+ if benchmark_limitation:
1716
+ vqa_details["counting_limitation"] = benchmark_limitation
1717
+ endpoint_task = intent.category.value if intent.category in _BENCHMARK_VQA_CATEGORIES else question_response.task.value
1718
+ result = {
1719
+ "report": _vqa_compatibility_report(caption, answer, answer_response.confidence.level.value, warnings),
1720
+ "provider": "satquery",
1721
+ "model": satquery_models,
1722
+ "cached": False,
1723
+ "request_id": request_id,
1724
+ }
1725
+ result.update(
1726
+ {
1727
+ "answer": answer,
1728
+ "confidence": _numeric_confidence(answer_response),
1729
+ "confidence_details": confidence_details,
1730
+ "caption": caption,
1731
+ "evidence": evidence,
1732
+ "execution_trace": trace,
1733
+ "task": endpoint_task,
1734
+ "model_used": satquery_models,
1735
+ "processing_time_ms": max(0, round((time.perf_counter() - endpoint_started) * 1000)),
1736
+ "question": question,
1737
+ "routed_question": routed_question,
1738
+ "status": "insufficient_evidence" if insufficient else answer_response.status.value,
1739
+ "result_status": "INSUFFICIENT_EVIDENCE" if insufficient else answer_response.result_status,
1740
+ "warnings": warnings,
1741
+ "vqa_details": vqa_details,
1742
+ "grounding_result": next(
1743
+ (response.grounding_result.model_dump(mode="json") for response in grounding_responses.values() if response.grounding_result),
1744
+ None,
1745
+ ),
1746
+ "sve_result": question_response.sve_result.model_dump(mode="json") if question_response.sve_result else None,
1747
+ }
1748
+ )
1749
+ LOGGER.info(
1750
+ "AI analysis completed: request_id=%s provider=%s model=%s cached=%s vqa=%s",
1751
+ request_id, result["provider"], result["model"], result["cached"], question is not None,
1752
+ )
1753
+ return JSONResponse(result)
1754
+ except json.JSONDecodeError as error:
1755
+ LOGGER.exception("AI analysis metadata parsing failed: request_id=%s", request_id)
1756
+ raise HTTPException(status_code=400, detail={"code": "INVALID_IMAGE", "message": "Analysis metadata must be valid JSON."}) from error
1757
+ except ValueError as error:
1758
+ LOGGER.exception("AI analysis input validation failed: request_id=%s", request_id)
1759
+ raise HTTPException(status_code=400, detail={"code": "INVALID_IMAGE", "message": str(error)}) from error
1760
+ except VisionAnalysisError as error:
1761
+ LOGGER.exception("AI analysis provider failed: request_id=%s code=%s", request_id, error.code)
1762
+ status_code = 503 if error.transient else 400
1763
+ raise HTTPException(status_code=status_code, detail={"code": error.code, "message": str(error), "request_id": request_id}) from error
1764
+
1765
+
1766
+ @app.get("/api/settings/provider")
1767
+ @app.get("/api/settings/ai-provider")
1768
+ def get_provider_settings() -> JSONResponse:
1769
+ """Return non-sensitive provider status for the Settings UI."""
1770
+ return JSONResponse(PROVIDER_SETTINGS.public_status())
1771
+
1772
+
1773
+ @app.get("/api/settings/ai-provider/models")
1774
+ def get_provider_models(provider: str = "gemini") -> JSONResponse:
1775
+ try:
1776
+ return JSONResponse(PROVIDER_SETTINGS.supported_models(provider))
1777
+ except ProviderSettingsError as error:
1778
+ raise HTTPException(status_code=400, detail=str(error)) from error
1779
+
1780
+
1781
+ def _test_saved_provider() -> Dict[str, Any]:
1782
+ result = VISION_ANALYSIS.test_connection()
1783
+ if result.get("success"):
1784
+ PROVIDER_SETTINGS.record_connection("connected", result.get("latency_ms"))
1785
+ elif result.get("status") == "invalid":
1786
+ PROVIDER_SETTINGS.record_connection("invalid")
1787
+ elif result.get("status") == "temporarily_unavailable":
1788
+ PROVIDER_SETTINGS.record_connection("temporarily_unavailable")
1789
+ sync_vision_settings()
1790
+ return result
1791
+
1792
+
1793
+ @app.post("/api/settings/provider")
1794
+ @app.post("/api/settings/ai-provider")
1795
+ def save_provider_settings(configuration: ProviderConfigurationRequest) -> JSONResponse:
1796
+ """Verify first, then persist only a masked, server-side Gemini configuration."""
1797
+ try:
1798
+ provider = configuration.provider.strip().lower()
1799
+ LOGGER.info("Gemini configuration request: provider=%s model=%s key_length=%d endpoint=/api/settings/ai-provider", provider, (configuration.model or "").strip(), len(configuration.api_key.strip()))
1800
+ if provider != "gemini":
1801
+ raise ProviderSettingsError("Google Gemini is the currently supported provider in this configuration flow.")
1802
+ if not configuration.api_key.strip() or "\n" in configuration.api_key or "\r" in configuration.api_key:
1803
+ raise ProviderSettingsError("Enter a complete Gemini API key on one line.")
1804
+ if not (configuration.model or "").strip():
1805
+ raise ProviderSettingsError("Select a Gemini vision model.")
1806
+ supported_model_ids = {item["id"] for item in PROVIDER_SETTINGS.supported_models("gemini")["models"]}
1807
+ if configuration.model.strip() not in supported_model_ids:
1808
+ raise ProviderSettingsError("Choose a Gemini model supported by this application.")
1809
+ if provider == "gemini" and not configuration.privacy_acknowledged:
1810
+ raise ProviderSettingsError("Confirm the privacy acknowledgement before connecting Gemini.")
1811
+ candidate = ImageAnalysisService(VisionSettings(provider=provider, api_key=configuration.api_key.strip(), model=(configuration.model or "").strip()))
1812
+ checked = candidate.test_connection()
1813
+ if not checked.get("success"):
1814
+ raise ProviderSettingsError(str(checked.get("message") or "Connection test failed."))
1815
+ status = PROVIDER_SETTINGS.save(provider, configuration.api_key, configuration.model)
1816
+ sync_vision_settings()
1817
+ return JSONResponse({"success": True, "message": "Google Gemini connected successfully." if provider == "gemini" else "Configuration saved successfully.", **status, "latency_ms": checked.get("latency_ms")})
1818
+ except ProviderSettingsError as error:
1819
+ raise HTTPException(status_code=400, detail=str(error)) from error
1820
+
1821
+
1822
+ @app.delete("/api/settings/provider")
1823
+ @app.delete("/api/settings/ai-provider")
1824
+ def delete_provider_settings() -> JSONResponse:
1825
+ try:
1826
+ status = PROVIDER_SETTINGS.delete()
1827
+ sync_vision_settings()
1828
+ return JSONResponse({"success": True, "message": "Gemini configuration removed.", **status})
1829
+ except ProviderSettingsError as error:
1830
+ raise HTTPException(status_code=400, detail=str(error)) from error
1831
+
1832
+
1833
+ @app.post("/api/settings/test")
1834
+ @app.post("/api/settings/ai-provider/test")
1835
+ def test_provider_settings() -> JSONResponse:
1836
+ return JSONResponse(_test_saved_provider())
changerex_local/README.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Standalone ChangerEx for macOS
2
+
3
+ This package runs the official LEVIR-CD ChangerEx ResNet-18 checkpoint using
4
+ only PyTorch, NumPy, and Pillow. It is isolated from the SatQuery production
5
+ agent and does not import Open-CD, MMCV, MMSegmentation, MMDetection,
6
+ MMPretrain, FastAPI, or any SatQuery module.
7
+
8
+ ## Provenance
9
+
10
+ - Model: ChangerEx with IA-ResNetV1c-18
11
+ - Official config: `configs/changer/changer_ex_r18_512x512_40k_levircd.py`
12
+ - Open-CD: v1.1.0, commit `09c03eb1077f06191c5448ea1fcf2f2f88ec98c2`
13
+ - Checkpoint: `ChangerEx_r18-512x512_40k_levircd_20221223_120511.pth`
14
+ - Required SHA-256: `da3f569306dadd1fac5b64abc2a3d484571cd0ecf6410e1f152275cfe49a3618`
15
+ - Classes: `unchanged` (0), `changed` (1)
16
+
17
+ Architecture math and module layout were adapted from the Apache-2.0 licensed
18
+ Open-CD project, particularly:
19
+
20
+ - `opencd/models/backbones/interaction_resnet.py`
21
+ - `opencd/models/utils/interaction_layer.py`
22
+ - `opencd/models/decode_heads/changer.py`
23
+ - `opencd/models/necks/feature_fusion.py`
24
+ - MMSegmentation's ResNet implementation used by the pinned Open-CD release
25
+
26
+ Only the selected inference graph is reproduced. The original projects and
27
+ their license/copyright notices remain authoritative.
28
+
29
+ ## Install in a new isolated environment
30
+
31
+ Do not install into the SatQuery production environment.
32
+
33
+ ```bash
34
+ python3.11 -m venv .venv-changerex
35
+ source .venv-changerex/bin/activate
36
+ python -m pip install -r changerex_local/requirements-macos.txt
37
+ ```
38
+
39
+ ## CLI
40
+
41
+ ```bash
42
+ python -m changerex_local \
43
+ --earlier /path/to/before.png \
44
+ --later /path/to/after.png \
45
+ --checkpoint /path/to/ChangerEx_r18-512x512_40k_levircd_20221223_120511.pth \
46
+ --output-dir /path/to/output \
47
+ --device auto \
48
+ --threshold 0.5 \
49
+ --warmup-runs 1 \
50
+ --benchmark-runs 5
51
+ ```
52
+
53
+ `auto` verifies MPS with a real tensor operation and selects it when usable;
54
+ otherwise it records a warning and selects CPU. An explicit `--device mps`
55
+ fails if MPS cannot be verified. CPU fallback for an explicit MPS request is
56
+ only permitted with `--allow-device-fallback`.
57
+
58
+ The CLI writes the probability array and visualization artifacts plus a strict
59
+ checkpoint report, environment report, regions, JSON result, and benchmark
60
+ report. An error is emitted as bounded JSON on stderr and returns a non-zero
61
+ status.
62
+
63
+ ## Python API
64
+
65
+ Configure the immutable, process-wide lifecycle once, then predict repeatedly:
66
+
67
+ ```python
68
+ from changerex_local import configure_lifecycle, predict_change
69
+
70
+ configure_lifecycle("/path/to/checkpoint.pth", device="auto")
71
+ result = predict_change("before.png", "after.png", device="auto", threshold=0.5)
72
+ print(result.changed_percentage, result.selected_device)
73
+ ```
74
+
75
+ The checkpoint is hashed and loaded on CPU before the model moves to the
76
+ selected device. Loading is lazy, thread-safe, strict, and sticky on failure.
77
+ Checkpoint and device configuration cannot change after the singleton is
78
+ created.
79
+
80
+ ## Preprocessing and outputs
81
+
82
+ Pillow decodes both inputs directly to RGB. Channels are concatenated as
83
+ earlier RGB followed by later RGB, kept in float32 `[0, 255]`, resized with
84
+ aspect ratio preserved so the longest side is 1024 by default, normalized by
85
+ ImageNet mean `[123.675, 116.28, 103.53]` and standard deviation
86
+ `[58.395, 57.12, 57.375]` for each time point, then padded on the right/bottom
87
+ with normalized-space zeros to a multiple of 32. This reproduces the official
88
+ test resize/data-preprocessor path without its training augmentations.
89
+
90
+ The two-class logits are bilinearly restored to the processed image size.
91
+ Class-1 softmax is the change probability. Probability is bilinearly restored
92
+ to source dimensions; the thresholded binary mask is restored with nearest
93
+ neighbor. Connected components are 8-connected and use exclusive `(x2, y2)`
94
+ bounds. No morphology is applied.
95
+
96
+ The images must have identical dimensions and be geometrically co-registered.
97
+ Outputs are predictions, not ground truth. LEVIR-CD is building-change focused,
98
+ so performance on fire, flooding, vegetation, or other domains is not implied
99
+ by a successful operational smoke test.
changerex_local/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone pure-PyTorch ChangerEx inference package."""
2
+
3
+ from .config import CHECKPOINT_SHA256, MODEL_NAME
4
+ from .inference import ChangerExInferenceError, predict_change
5
+ from .lifecycle import configure_lifecycle
6
+ from .schemas import ChangerExResult
7
+
8
+ __all__ = [
9
+ "CHECKPOINT_SHA256",
10
+ "MODEL_NAME",
11
+ "ChangerExInferenceError",
12
+ "ChangerExResult",
13
+ "configure_lifecycle",
14
+ "predict_change",
15
+ ]
changerex_local/__main__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .cli import main
2
+
3
+
4
+ raise SystemExit(main())
changerex_local/architecture.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Strict checkpoint-compatible standalone ChangerEx model."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as functional
8
+
9
+ from .backbone import IAResNetV1c18
10
+ from .decoder import ChangerDecoder
11
+
12
+
13
+ class ChangerEx(nn.Module):
14
+ """ChangerEx with names and tensor shapes matching the official checkpoint."""
15
+
16
+ def __init__(self) -> None:
17
+ super().__init__()
18
+ self.backbone = IAResNetV1c18()
19
+ self.decode_head = ChangerDecoder()
20
+
21
+ def forward_quarter_resolution(self, pair: torch.Tensor) -> torch.Tensor:
22
+ if pair.ndim != 4 or pair.shape[1] != 6:
23
+ raise ValueError("ChangerEx expects an NCHW tensor with six RGB-pair channels")
24
+ earlier, later = torch.chunk(pair, 2, dim=1)
25
+ return self.decode_head(self.backbone(earlier, later))
26
+
27
+ def forward(self, pair: torch.Tensor) -> torch.Tensor:
28
+ logits = self.forward_quarter_resolution(pair)
29
+ return functional.interpolate(
30
+ logits, size=pair.shape[-2:], mode="bilinear", align_corners=False
31
+ )
32
+
33
+
34
+ def build_model() -> ChangerEx:
35
+ return ChangerEx()
36
+
37
+
38
+ def model_parameter_count(model: nn.Module) -> int:
39
+ return sum(parameter.numel() for parameter in model.parameters())
changerex_local/backbone.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure-PyTorch IA-ResNetV1c-18 backbone for ChangerEx.
2
+
3
+ Module names intentionally match the official Open-CD checkpoint. Architecture
4
+ is adapted from Apache-2.0 licensed Open-CD and MMSegmentation ResNet sources.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import torch
10
+ from torch import nn
11
+
12
+ from .interaction import ChannelExchange, SpatialExchange, TwoIdentity
13
+
14
+
15
+ class BasicBlock(nn.Module):
16
+ expansion = 1
17
+
18
+ def __init__(self, in_channels: int, out_channels: int, stride: int = 1) -> None:
19
+ super().__init__()
20
+ self.conv1 = nn.Conv2d(in_channels, out_channels, 3, stride=stride, padding=1, bias=False)
21
+ self.bn1 = nn.SyncBatchNorm(out_channels)
22
+ self.relu = nn.ReLU(inplace=True)
23
+ self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False)
24
+ self.bn2 = nn.SyncBatchNorm(out_channels)
25
+ self.downsample: nn.Module | None = None
26
+ if stride != 1 or in_channels != out_channels:
27
+ self.downsample = nn.Sequential(
28
+ nn.Conv2d(in_channels, out_channels, 1, stride=stride, bias=False),
29
+ nn.SyncBatchNorm(out_channels),
30
+ )
31
+
32
+ def forward(self, tensor: torch.Tensor) -> torch.Tensor:
33
+ identity = tensor if self.downsample is None else self.downsample(tensor)
34
+ output = self.relu(self.bn1(self.conv1(tensor)))
35
+ output = self.bn2(self.conv2(output))
36
+ return self.relu(output + identity)
37
+
38
+
39
+ class IAResNetV1c18(nn.Module):
40
+ """Exact four-stage, deep-stem interaction ResNet-18."""
41
+
42
+ def __init__(self) -> None:
43
+ super().__init__()
44
+ self.stem = nn.Sequential(
45
+ nn.Conv2d(3, 32, 3, stride=2, padding=1, bias=False),
46
+ nn.SyncBatchNorm(32),
47
+ nn.ReLU(inplace=True),
48
+ nn.Conv2d(32, 32, 3, padding=1, bias=False),
49
+ nn.SyncBatchNorm(32),
50
+ nn.ReLU(inplace=True),
51
+ nn.Conv2d(32, 64, 3, padding=1, bias=False),
52
+ nn.SyncBatchNorm(64),
53
+ nn.ReLU(inplace=True),
54
+ )
55
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
56
+ self.layer1 = self._make_layer(64, 64, 1)
57
+ self.layer2 = self._make_layer(64, 128, 2)
58
+ self.layer3 = self._make_layer(128, 256, 2)
59
+ self.layer4 = self._make_layer(256, 512, 2)
60
+ self.ccs = nn.ModuleList(
61
+ [TwoIdentity(), SpatialExchange(0.5), ChannelExchange(0.5), ChannelExchange(0.5)]
62
+ )
63
+
64
+ @staticmethod
65
+ def _make_layer(in_channels: int, out_channels: int, stride: int) -> nn.Sequential:
66
+ return nn.Sequential(
67
+ BasicBlock(in_channels, out_channels, stride),
68
+ BasicBlock(out_channels, out_channels),
69
+ )
70
+
71
+ def forward(self, first: torch.Tensor, second: torch.Tensor) -> tuple[torch.Tensor, ...]:
72
+ first = self.maxpool(self.stem(first))
73
+ second = self.maxpool(self.stem(second))
74
+ outputs: list[torch.Tensor] = []
75
+ for layer, interaction in zip(
76
+ (self.layer1, self.layer2, self.layer3, self.layer4), self.ccs
77
+ ):
78
+ first = layer(first)
79
+ second = layer(second)
80
+ first, second = interaction(first, second)
81
+ outputs.append(torch.cat((first, second), dim=1))
82
+ return tuple(outputs)
changerex_local/checkpoint.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Strict verification and loading for the pinned official checkpoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Any, Mapping
9
+
10
+ import torch
11
+ from torch import nn
12
+
13
+ from .architecture import model_parameter_count
14
+ from .config import CHECKPOINT_SHA256
15
+ from .schemas import CheckpointVerificationReport
16
+
17
+
18
+ class CheckpointError(RuntimeError):
19
+ """Base class for safe checkpoint failures."""
20
+
21
+
22
+ class CheckpointVerificationError(CheckpointError):
23
+ pass
24
+
25
+
26
+ class CheckpointCompatibilityError(CheckpointError):
27
+ pass
28
+
29
+
30
+ def sha256_file(path: str | Path, chunk_size: int = 1024 * 1024) -> str:
31
+ digest = hashlib.sha256()
32
+ with Path(path).open("rb") as handle:
33
+ while chunk := handle.read(chunk_size):
34
+ digest.update(chunk)
35
+ return digest.hexdigest()
36
+
37
+
38
+ def _bounded_metadata(value: Any, *, depth: int = 0) -> Any:
39
+ """Produce a JSON-safe, bounded metadata representation."""
40
+ if depth > 4:
41
+ return "<maximum-depth>"
42
+ if value is None or isinstance(value, (bool, int, float)):
43
+ return value
44
+ if isinstance(value, str):
45
+ return value if len(value) <= 2000 else value[:2000] + "…"
46
+ if isinstance(value, Mapping):
47
+ items = list(value.items())[:100]
48
+ result = {str(key): _bounded_metadata(item, depth=depth + 1) for key, item in items}
49
+ if len(value) > 100:
50
+ result["<truncated-items>"] = len(value) - 100
51
+ return result
52
+ if isinstance(value, (list, tuple)):
53
+ result = [_bounded_metadata(item, depth=depth + 1) for item in value[:100]]
54
+ if len(value) > 100:
55
+ result.append(f"<truncated-items:{len(value) - 100}>")
56
+ return result
57
+ if isinstance(value, torch.Tensor):
58
+ return {"tensor_shape": list(value.shape), "dtype": str(value.dtype)}
59
+ text = repr(value)
60
+ return text if len(text) <= 500 else text[:500] + "…"
61
+
62
+
63
+ def _load_verified_payload(path: Path, expected_sha256: str) -> tuple[dict[str, Any], int, str]:
64
+ if not path.is_file():
65
+ raise CheckpointVerificationError(f"Checkpoint file does not exist: {path}")
66
+ file_size = path.stat().st_size
67
+ digest = sha256_file(path)
68
+ if digest.lower() != expected_sha256.lower():
69
+ raise CheckpointVerificationError(
70
+ f"Checkpoint SHA-256 mismatch: expected {expected_sha256}, received {digest}"
71
+ )
72
+ try:
73
+ payload = torch.load(path, map_location="cpu", weights_only=False)
74
+ except Exception as error:
75
+ raise CheckpointVerificationError(f"Verified checkpoint could not be decoded: {error}") from error
76
+ if not isinstance(payload, dict):
77
+ raise CheckpointVerificationError("Checkpoint top level must be a dictionary")
78
+ return payload, file_size, digest
79
+
80
+
81
+ def inspect_checkpoint(
82
+ path: str | Path, *, expected_sha256: str = CHECKPOINT_SHA256
83
+ ) -> tuple[dict[str, torch.Tensor], CheckpointVerificationReport]:
84
+ checkpoint_path = Path(path).expanduser().resolve()
85
+ payload, file_size, digest = _load_verified_payload(checkpoint_path, expected_sha256)
86
+ state_dict = payload.get("state_dict")
87
+ if not isinstance(state_dict, Mapping) or not state_dict:
88
+ raise CheckpointVerificationError("Checkpoint does not contain a non-empty 'state_dict'")
89
+ if not all(isinstance(key, str) and isinstance(value, torch.Tensor) for key, value in state_dict.items()):
90
+ raise CheckpointVerificationError("Checkpoint state_dict contains non-tensor entries")
91
+
92
+ # The official file already uses exact model-relative keys. No prefix
93
+ # normalization is performed; any mismatch is an incompatibility.
94
+ normalized = dict(state_dict)
95
+ metadata = _bounded_metadata(payload.get("meta", {}))
96
+ try:
97
+ json.dumps(metadata)
98
+ except TypeError as error: # defensive invariant for diagnostics output
99
+ raise CheckpointVerificationError("Checkpoint metadata is not serializable") from error
100
+ report = CheckpointVerificationReport(
101
+ path=str(checkpoint_path),
102
+ file_size=file_size,
103
+ sha256=digest,
104
+ top_level_keys=tuple(sorted(str(key) for key in payload)),
105
+ tensor_count=len(normalized),
106
+ parameter_count=0,
107
+ missing_keys=(),
108
+ unexpected_keys=(),
109
+ key_transformations=(),
110
+ checkpoint_metadata=metadata,
111
+ )
112
+ return normalized, report
113
+
114
+
115
+ def load_checkpoint_strict(
116
+ model: nn.Module,
117
+ path: str | Path,
118
+ *,
119
+ expected_sha256: str = CHECKPOINT_SHA256,
120
+ ) -> CheckpointVerificationReport:
121
+ state_dict, report = inspect_checkpoint(path, expected_sha256=expected_sha256)
122
+ try:
123
+ incompatible = model.load_state_dict(state_dict, strict=True)
124
+ except RuntimeError as error:
125
+ raise CheckpointCompatibilityError(f"Strict state-dict loading failed: {error}") from error
126
+ missing = tuple(incompatible.missing_keys)
127
+ unexpected = tuple(incompatible.unexpected_keys)
128
+ if missing or unexpected:
129
+ raise CheckpointCompatibilityError(
130
+ f"Strict state-dict loading reported missing={missing}, unexpected={unexpected}"
131
+ )
132
+ return CheckpointVerificationReport(
133
+ path=report.path,
134
+ file_size=report.file_size,
135
+ sha256=report.sha256,
136
+ top_level_keys=report.top_level_keys,
137
+ tensor_count=report.tensor_count,
138
+ parameter_count=model_parameter_count(model),
139
+ missing_keys=missing,
140
+ unexpected_keys=unexpected,
141
+ key_transformations=report.key_transformations,
142
+ checkpoint_metadata=report.checkpoint_metadata,
143
+ )
changerex_local/cli.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Command-line interface for standalone ChangerEx inference."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+
12
+ from .config import DEFAULT_MAXIMUM_DIMENSION, DEFAULT_THRESHOLD
13
+ from .diagnostics import benchmark_summary, save_artifacts
14
+ from .inference import ChangerExInferenceError, predict_change
15
+ from .lifecycle import configure_lifecycle
16
+ from .preprocessing import load_rgb_image
17
+
18
+
19
+ def build_parser() -> argparse.ArgumentParser:
20
+ parser = argparse.ArgumentParser(description="Standalone pure-PyTorch ChangerEx inference")
21
+ parser.add_argument("--earlier", required=True, help="Earlier RGB image")
22
+ parser.add_argument("--later", required=True, help="Later RGB image")
23
+ parser.add_argument("--checkpoint", required=True, help="Official ChangerEx checkpoint")
24
+ parser.add_argument("--output-dir", required=True, help="Artifact output directory")
25
+ parser.add_argument("--device", choices=("auto", "mps", "cpu"), default="auto")
26
+ parser.add_argument("--threshold", type=float, default=DEFAULT_THRESHOLD)
27
+ parser.add_argument("--allow-device-fallback", action="store_true")
28
+ parser.add_argument("--warmup-runs", type=int, default=0)
29
+ parser.add_argument("--benchmark-runs", type=int, default=1)
30
+ parser.add_argument("--maximum-dimension", type=int, default=DEFAULT_MAXIMUM_DIMENSION)
31
+ parser.add_argument("--save-probability-npy", action="store_true")
32
+ return parser
33
+
34
+
35
+ def _validate_args(args: argparse.Namespace) -> None:
36
+ if not 0.0 <= args.threshold <= 1.0:
37
+ raise ValueError("--threshold must be within [0, 1]")
38
+ if args.maximum_dimension <= 0:
39
+ raise ValueError("--maximum-dimension must be positive")
40
+ if args.warmup_runs < 0 or args.benchmark_runs < 0:
41
+ raise ValueError("--warmup-runs and --benchmark-runs cannot be negative")
42
+
43
+
44
+ def run(args: argparse.Namespace) -> dict[str, object]:
45
+ _validate_args(args)
46
+ configure_lifecycle(
47
+ args.checkpoint,
48
+ device=args.device,
49
+ allow_device_fallback=args.allow_device_fallback,
50
+ )
51
+ prediction_kwargs = {
52
+ "device": args.device,
53
+ "threshold": args.threshold,
54
+ "maximum_dimension": args.maximum_dimension,
55
+ "allow_device_fallback": args.allow_device_fallback,
56
+ }
57
+ result = predict_change(args.earlier, args.later, **prediction_kwargs)
58
+ first_runtime = result.runtime
59
+ first_was_reused = result.load_reuse_status.get("was_reused")
60
+ baseline_probability = result.probability_map.copy()
61
+ for _ in range(args.warmup_runs):
62
+ result = predict_change(args.earlier, args.later, **prediction_kwargs)
63
+ benchmark_times: list[float] = []
64
+ repeat_difference: float | None = None
65
+ for _ in range(args.benchmark_runs):
66
+ result = predict_change(args.earlier, args.later, **prediction_kwargs)
67
+ assert result.runtime is not None
68
+ benchmark_times.append(result.runtime.model_seconds)
69
+ repeat_difference = float(np.max(np.abs(result.probability_map - baseline_probability)))
70
+ benchmark = benchmark_summary(
71
+ benchmark_times, repeat_max_abs_difference=repeat_difference
72
+ )
73
+ benchmark.update(
74
+ {
75
+ "first_total_seconds": first_runtime.inference_seconds if first_runtime else None,
76
+ "first_model_seconds": first_runtime.model_seconds if first_runtime else None,
77
+ "first_was_reused": first_was_reused,
78
+ }
79
+ )
80
+ later = load_rgb_image(args.later)
81
+ paths = save_artifacts(
82
+ result,
83
+ later,
84
+ args.output_dir,
85
+ benchmark=benchmark,
86
+ # Required artifacts always include the NPY. The flag remains accepted
87
+ # for an explicit caller contract and backward-compatible scripting.
88
+ save_probability_npy=True,
89
+ )
90
+ summary = result.summary()
91
+ summary["benchmark"] = benchmark
92
+ summary["artifacts"] = paths
93
+ return summary
94
+
95
+
96
+ def main(argv: list[str] | None = None) -> int:
97
+ parser = build_parser()
98
+ try:
99
+ args = parser.parse_args(argv)
100
+ summary = run(args)
101
+ print(json.dumps(summary, indent=2))
102
+ return 0
103
+ except (ChangerExInferenceError, ValueError, RuntimeError, OSError) as error:
104
+ print(
105
+ json.dumps({"ok": False, "error": f"{type(error).__name__}: {error}"[:1000]}),
106
+ file=sys.stderr,
107
+ )
108
+ return 1
109
+
110
+
111
+ if __name__ == "__main__":
112
+ raise SystemExit(main())
changerex_local/config.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pinned configuration for the standalone ChangerEx extraction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ MODEL_NAME = "ChangerEx IA-ResNetV1c-18 (LEVIR-CD)"
9
+ MODEL_CONFIG = "configs/changer/changer_ex_r18_512x512_40k_levircd.py"
10
+ OPENCD_VERSION = "v1.1.0"
11
+ OPENCD_COMMIT = "09c03eb1077f06191c5448ea1fcf2f2f88ec98c2"
12
+ CHECKPOINT_FILENAME = "ChangerEx_r18-512x512_40k_levircd_20221223_120511.pth"
13
+ CHECKPOINT_SHA256 = "da3f569306dadd1fac5b64abc2a3d484571cd0ecf6410e1f152275cfe49a3618"
14
+ CHECKPOINT_URL = "https://drive.google.com/file/d/1SZ8DBgBryJ63X9AU0AQvaJ2ZH3oQHQHe/view"
15
+
16
+ RGB_MEAN = (123.675, 116.28, 103.53)
17
+ RGB_STD = (58.395, 57.12, 57.375)
18
+ SIZE_DIVISOR = 32
19
+ DEFAULT_MAXIMUM_DIMENSION = 1024
20
+ DEFAULT_THRESHOLD = 0.5
21
+ CLASS_NAMES = ("unchanged", "changed")
22
+ PARAMETER_COUNT = 11_390_946
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class ModelProvenance:
27
+ model_name: str = MODEL_NAME
28
+ config: str = MODEL_CONFIG
29
+ opencd_version: str = OPENCD_VERSION
30
+ opencd_commit: str = OPENCD_COMMIT
31
+ checkpoint_filename: str = CHECKPOINT_FILENAME
32
+ checkpoint_sha256: str = CHECKPOINT_SHA256
33
+ checkpoint_url: str = CHECKPOINT_URL
34
+ training_dataset: str = "LEVIR-CD"
35
+ classes: tuple[str, str] = CLASS_NAMES
36
+
37
+
38
+ PROVENANCE = ModelProvenance()
changerex_local/decoder.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure-PyTorch Changer decoder head.
2
+
3
+ Adapted from Open-CD's Apache-2.0 licensed
4
+ ``opencd/models/decode_heads/changer.py`` at the pinned commit.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import torch
10
+ from torch import nn
11
+ from torch.nn import functional as functional
12
+
13
+
14
+ class ConvModule(nn.Module):
15
+ def __init__(self, in_channels: int, out_channels: int) -> None:
16
+ super().__init__()
17
+ self.conv = nn.Conv2d(in_channels, out_channels, 1, bias=False)
18
+ self.bn = nn.SyncBatchNorm(out_channels)
19
+ self.activate = nn.ReLU(inplace=True)
20
+
21
+ def forward(self, tensor: torch.Tensor) -> torch.Tensor:
22
+ return self.activate(self.bn(self.conv(tensor)))
23
+
24
+
25
+ class FDAF(nn.Module):
26
+ def __init__(self) -> None:
27
+ super().__init__()
28
+ self.flow_make = nn.Sequential(
29
+ nn.Conv2d(128, 128, 5, padding=2, groups=128, bias=True),
30
+ nn.InstanceNorm2d(128),
31
+ nn.GELU(),
32
+ nn.Conv2d(128, 4, 1, bias=False),
33
+ )
34
+
35
+ @staticmethod
36
+ def warp(tensor: torch.Tensor, flow: torch.Tensor) -> torch.Tensor:
37
+ batch, _, height, width = tensor.shape
38
+ norm = tensor.new_tensor([width, height]).view(1, 1, 1, 2)
39
+ column = torch.linspace(-1.0, 1.0, height, device=tensor.device, dtype=tensor.dtype)
40
+ column = column.view(-1, 1).repeat(1, width)
41
+ row = torch.linspace(-1.0, 1.0, width, device=tensor.device, dtype=tensor.dtype)
42
+ row = row.repeat(height, 1)
43
+ grid = torch.stack((row, column), dim=2).repeat(batch, 1, 1, 1)
44
+ return functional.grid_sample(
45
+ tensor, grid + flow.permute(0, 2, 3, 1) / norm, align_corners=True
46
+ )
47
+
48
+ def forward(self, first: torch.Tensor, second: torch.Tensor) -> torch.Tensor:
49
+ first_flow, second_flow = torch.chunk(
50
+ self.flow_make(torch.cat((first, second), dim=1)), 2, dim=1
51
+ )
52
+ first_difference = self.warp(first, first_flow) - second
53
+ second_difference = self.warp(second, second_flow) - first
54
+ return torch.cat((first_difference, second_difference), dim=1)
55
+
56
+
57
+ class MixFFN(nn.Module):
58
+ def __init__(self) -> None:
59
+ super().__init__()
60
+ self.layers = nn.Sequential(
61
+ nn.Conv2d(128, 128, 1, bias=True),
62
+ nn.Conv2d(128, 128, 3, padding=1, groups=128, bias=True),
63
+ nn.GELU(),
64
+ nn.Dropout(0.0),
65
+ nn.Conv2d(128, 128, 1, bias=True),
66
+ nn.Dropout(0.0),
67
+ )
68
+ self.dropout_layer = nn.Identity()
69
+
70
+ def forward(self, tensor: torch.Tensor) -> torch.Tensor:
71
+ return tensor + self.dropout_layer(self.layers(tensor))
72
+
73
+
74
+ class ChangerDecoder(nn.Module):
75
+ def __init__(self) -> None:
76
+ super().__init__()
77
+ self.conv_seg = nn.Conv2d(128, 2, 1)
78
+ self.convs = nn.ModuleList([ConvModule(channels, 128) for channels in (64, 128, 256, 512)])
79
+ self.fusion_conv = ConvModule(512, 64)
80
+ self.neck_layer = FDAF()
81
+ self.discriminator = MixFFN()
82
+
83
+ def _base_forward(self, features: tuple[torch.Tensor, ...]) -> torch.Tensor:
84
+ target_size = features[0].shape[-2:]
85
+ projections = []
86
+ for projection, feature in zip(self.convs, features):
87
+ projected = projection(feature)
88
+ if projected.shape[-2:] != target_size:
89
+ projected = functional.interpolate(
90
+ projected, size=target_size, mode="bilinear", align_corners=False
91
+ )
92
+ projections.append(projected)
93
+ return self.fusion_conv(torch.cat(projections, dim=1))
94
+
95
+ def forward(self, inputs: tuple[torch.Tensor, ...]) -> torch.Tensor:
96
+ split = [torch.chunk(feature, 2, dim=1) for feature in inputs]
97
+ first = tuple(item[0] for item in split)
98
+ second = tuple(item[1] for item in split)
99
+ aligned = self.neck_layer(self._base_forward(first), self._base_forward(second))
100
+ return self.conv_seg(self.discriminator(aligned))
changerex_local/diagnostics.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Artifact writing and environment diagnostics for standalone runs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import platform
7
+ import statistics
8
+ import sys
9
+ from dataclasses import asdict
10
+ from pathlib import Path
11
+ from typing import Any, Sequence
12
+
13
+ import numpy as np
14
+ import torch
15
+ from PIL import Image
16
+
17
+ from .config import OPENCD_COMMIT, OPENCD_VERSION
18
+ from .postprocessing import make_display_mask, make_overlay
19
+ from .schemas import ChangerExResult
20
+
21
+
22
+ def environment_report() -> dict[str, Any]:
23
+ return {
24
+ "platform": platform.platform(),
25
+ "macos_version": platform.mac_ver()[0],
26
+ "architecture": platform.machine(),
27
+ "python": sys.version,
28
+ "torch": torch.__version__,
29
+ "numpy": np.__version__,
30
+ "pillow": Image.__version__,
31
+ "mps_built": bool(torch.backends.mps.is_built()),
32
+ "mps_available": bool(torch.backends.mps.is_available()),
33
+ "cuda_required": False,
34
+ "opencd_runtime_required": False,
35
+ "opencd_reference_version": OPENCD_VERSION,
36
+ "opencd_reference_commit": OPENCD_COMMIT,
37
+ }
38
+
39
+
40
+ def _percentile(values: Sequence[float], percentile: float) -> float | None:
41
+ if not values:
42
+ return None
43
+ return float(np.percentile(np.asarray(values, dtype=np.float64), percentile))
44
+
45
+
46
+ def benchmark_summary(
47
+ inference_seconds: Sequence[float], *, repeat_max_abs_difference: float | None = None
48
+ ) -> dict[str, Any]:
49
+ values = [float(value) for value in inference_seconds]
50
+ return {
51
+ "runs": len(values),
52
+ "seconds": values,
53
+ "mean_seconds": statistics.fmean(values) if values else None,
54
+ "median_seconds": statistics.median(values) if values else None,
55
+ "p95_seconds": _percentile(values, 95),
56
+ "repeat_max_abs_probability_difference": repeat_max_abs_difference,
57
+ "deterministic_repeatability": (
58
+ repeat_max_abs_difference == 0.0 if repeat_max_abs_difference is not None else None
59
+ ),
60
+ }
61
+
62
+
63
+ def save_artifacts(
64
+ result: ChangerExResult,
65
+ later_image: Image.Image,
66
+ output_dir: str | Path,
67
+ *,
68
+ benchmark: dict[str, Any] | None = None,
69
+ save_probability_npy: bool = True,
70
+ smoke_source: dict[str, Any] | None = None,
71
+ ) -> dict[str, str]:
72
+ output = Path(output_dir).expanduser().resolve()
73
+ output.mkdir(parents=True, exist_ok=True)
74
+ paths = {
75
+ "probability_map": str(output / "probability_map.npy"),
76
+ "probability_png": str(output / "probability_map.png"),
77
+ "binary_mask": str(output / "binary_mask.png"),
78
+ "display_mask": str(output / "display_mask.png"),
79
+ "overlay": str(output / "overlay.png"),
80
+ "regions": str(output / "regions.json"),
81
+ "result": str(output / "result.json"),
82
+ "checkpoint_verification": str(output / "checkpoint_verification.json"),
83
+ "environment": str(output / "environment.json"),
84
+ "benchmark_report": str(output / "benchmark_report.md"),
85
+ }
86
+ if save_probability_npy:
87
+ np.save(paths["probability_map"], result.probability_map, allow_pickle=False)
88
+ probability_u16 = np.rint(np.clip(result.probability_map, 0, 1) * 65535).astype(np.uint16)
89
+ Image.fromarray(probability_u16).save(paths["probability_png"])
90
+ Image.fromarray((result.binary_mask * 255).astype(np.uint8)).save(paths["binary_mask"])
91
+ make_display_mask(result.binary_mask).save(paths["display_mask"])
92
+ make_overlay(later_image, result.binary_mask).save(paths["overlay"])
93
+
94
+ regions = [asdict(region) for region in result.regions]
95
+ Path(paths["regions"]).write_text(json.dumps(regions, indent=2), encoding="utf-8")
96
+ summary = result.summary()
97
+ summary["benchmark"] = benchmark
98
+ summary["smoke_source"] = smoke_source
99
+ summary["artifacts"] = paths
100
+ Path(paths["result"]).write_text(json.dumps(summary, indent=2), encoding="utf-8")
101
+
102
+ verification = result.checkpoint_provenance.get("verification_report") or {
103
+ key: result.checkpoint_provenance.get(key)
104
+ for key in (
105
+ "verified_path",
106
+ "verified_sha256",
107
+ "strict_missing_keys",
108
+ "strict_unexpected_keys",
109
+ "key_transformations",
110
+ )
111
+ }
112
+ verification["provenance"] = {
113
+ key: result.checkpoint_provenance.get(key)
114
+ for key in ("checkpoint_filename", "checkpoint_url", "opencd_version", "opencd_commit")
115
+ }
116
+ Path(paths["checkpoint_verification"]).write_text(
117
+ json.dumps(verification, indent=2), encoding="utf-8"
118
+ )
119
+ Path(paths["environment"]).write_text(
120
+ json.dumps(environment_report(), indent=2), encoding="utf-8"
121
+ )
122
+
123
+ benchmark = benchmark or {}
124
+ source_lines = []
125
+ if smoke_source:
126
+ source_lines = [
127
+ f"- Imagery source: {smoke_source.get('source', 'unspecified')}",
128
+ f"- Source URL: {smoke_source.get('url', 'unspecified')}",
129
+ f"- License/use basis: {smoke_source.get('license', 'unspecified')}",
130
+ ]
131
+ report = "\n".join(
132
+ [
133
+ "# ChangerEx standalone benchmark report",
134
+ "",
135
+ "> The binary mask and overlay are model predictions, not ground truth. This operational smoke run does not measure accuracy.",
136
+ "",
137
+ "## Input and output",
138
+ "",
139
+ f"- Source dimensions: {result.source_width} × {result.source_height}",
140
+ f"- Model input dimensions: {result.model_input_width} × {result.model_input_height}",
141
+ f"- Device: {result.selected_device}",
142
+ f"- Threshold: {result.threshold}",
143
+ f"- Probability range: {float(result.probability_map.min()):.8f}–{float(result.probability_map.max()):.8f}",
144
+ f"- Changed percentage: {result.changed_percentage:.6f}%",
145
+ f"- Connected regions: {result.connected_component_count}",
146
+ *source_lines,
147
+ "",
148
+ "## Runtime",
149
+ "",
150
+ f"- Model load: {result.runtime.load_seconds if result.runtime else None} s",
151
+ f"- First inference: {benchmark.get('first_total_seconds', result.runtime.inference_seconds if result.runtime else None)} s",
152
+ f"- First model forward: {benchmark.get('first_model_seconds')} s",
153
+ f"- Benchmark runs: {benchmark.get('runs')}",
154
+ f"- Mean: {benchmark.get('mean_seconds')} s",
155
+ f"- Median: {benchmark.get('median_seconds')} s",
156
+ f"- P95: {benchmark.get('p95_seconds')} s",
157
+ f"- Peak memory: {result.runtime.peak_memory_mb if result.runtime else None} MB",
158
+ f"- Reuse count: {result.load_reuse_status.get('reuse_count')}",
159
+ f"- Deterministic repeatability: {benchmark.get('deterministic_repeatability')}",
160
+ "",
161
+ "## Limitations",
162
+ "",
163
+ *[f"- {item}" for item in result.limitations],
164
+ "",
165
+ ]
166
+ )
167
+ Path(paths["benchmark_report"]).write_text(report, encoding="utf-8")
168
+ return paths
changerex_local/inference.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Public inference API for standalone ChangerEx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from dataclasses import asdict
7
+
8
+ import numpy as np
9
+ import torch
10
+ from torch.nn import functional as functional
11
+
12
+ from .config import DEFAULT_MAXIMUM_DIMENSION, PROVENANCE
13
+ from .lifecycle import get_lifecycle, peak_memory_mb
14
+ from .postprocessing import connected_components, threshold_probability, validate_probability_map
15
+ from .preprocessing import ImageInput, preprocess_pair
16
+ from .schemas import ChangerExResult, RuntimeStats
17
+
18
+
19
+ class ChangerExInferenceError(RuntimeError):
20
+ pass
21
+
22
+
23
+ def _synchronize(device: str) -> None:
24
+ if device == "mps":
25
+ torch.mps.synchronize()
26
+
27
+
28
+ def predict_change(
29
+ earlier_image: ImageInput,
30
+ later_image: ImageInput,
31
+ *,
32
+ device: str = "auto",
33
+ threshold: float = 0.5,
34
+ maximum_dimension: int = DEFAULT_MAXIMUM_DIMENSION,
35
+ allow_device_fallback: bool = False,
36
+ ) -> ChangerExResult:
37
+ """Predict changed pixels for an ordered, co-registered RGB image pair."""
38
+ total_started = time.perf_counter()
39
+ try:
40
+ if not 0.0 <= threshold <= 1.0:
41
+ raise ValueError("threshold must be within [0, 1]")
42
+ preprocessing_started = time.perf_counter()
43
+ pair, preprocessing, _ = preprocess_pair(
44
+ earlier_image, later_image, maximum_dimension=maximum_dimension
45
+ )
46
+ preprocessing_seconds = time.perf_counter() - preprocessing_started
47
+
48
+ lifecycle = get_lifecycle(
49
+ device=device, allow_device_fallback=allow_device_fallback
50
+ )
51
+ model, was_reused = lifecycle.ensure_loaded()
52
+ selected = lifecycle.selected_device
53
+ assert selected is not None
54
+ pair = pair.to(device=selected, dtype=torch.float32)
55
+
56
+ _synchronize(selected)
57
+ model_started = time.perf_counter()
58
+ with torch.inference_mode():
59
+ logits = model(pair)
60
+ _synchronize(selected)
61
+ model_seconds = time.perf_counter() - model_started
62
+
63
+ probability_started = time.perf_counter()
64
+ with torch.inference_mode():
65
+ changed_probability = torch.softmax(logits, dim=1)[:, 1:2]
66
+ _synchronize(selected)
67
+ probability_seconds = time.perf_counter() - probability_started
68
+
69
+ postprocessing_started = time.perf_counter()
70
+ resized_width, resized_height = preprocessing.resized_size
71
+ source_width, source_height = preprocessing.source_size
72
+ changed_probability = changed_probability[..., :resized_height, :resized_width]
73
+ threshold_started = time.perf_counter()
74
+ resized_mask = (changed_probability >= threshold).to(dtype=torch.float32)
75
+ _synchronize(selected)
76
+ threshold_seconds = time.perf_counter() - threshold_started
77
+ restoration_started = time.perf_counter()
78
+ if (resized_height, resized_width) != (source_height, source_width):
79
+ restored_probability = functional.interpolate(
80
+ changed_probability,
81
+ size=(source_height, source_width),
82
+ mode="bilinear",
83
+ align_corners=False,
84
+ )
85
+ restored_mask = functional.interpolate(
86
+ resized_mask, size=(source_height, source_width), mode="nearest"
87
+ )
88
+ else:
89
+ restored_probability = changed_probability
90
+ restored_mask = resized_mask
91
+ probability_map = restored_probability[0, 0].detach().cpu().numpy().astype(np.float32)
92
+ probability_map = validate_probability_map(probability_map)
93
+ binary_mask = restored_mask[0, 0].detach().cpu().numpy().astype(np.uint8)
94
+ # Ensure threshold semantics are identical when no restoration occurred.
95
+ if (resized_height, resized_width) == (source_height, source_width):
96
+ binary_mask = threshold_probability(probability_map, threshold)
97
+ restoration_seconds = time.perf_counter() - restoration_started
98
+ components_started = time.perf_counter()
99
+ regions = connected_components(binary_mask)
100
+ components_seconds = time.perf_counter() - components_started
101
+ changed_pixel_count = int(binary_mask.sum())
102
+ changed_percentage = 100.0 * changed_pixel_count / binary_mask.size
103
+ postprocessing_seconds = time.perf_counter() - postprocessing_started
104
+ total_seconds = time.perf_counter() - total_started
105
+ lifecycle.record_inference(total_seconds)
106
+ status = lifecycle.status()
107
+ report = lifecycle.checkpoint_report
108
+ provenance = asdict(PROVENANCE)
109
+ if report:
110
+ provenance.update(
111
+ {
112
+ "verified_path": report.path,
113
+ "verified_sha256": report.sha256,
114
+ "strict_missing_keys": list(report.missing_keys),
115
+ "strict_unexpected_keys": list(report.unexpected_keys),
116
+ "key_transformations": list(report.key_transformations),
117
+ "verification_report": report.to_dict(),
118
+ }
119
+ )
120
+ return ChangerExResult(
121
+ source_width=source_width,
122
+ source_height=source_height,
123
+ model_input_width=preprocessing.padded_size[0],
124
+ model_input_height=preprocessing.padded_size[1],
125
+ selected_device=selected,
126
+ probability_map=probability_map,
127
+ binary_mask=binary_mask,
128
+ changed_pixel_count=changed_pixel_count,
129
+ changed_percentage=changed_percentage,
130
+ connected_component_count=len(regions),
131
+ largest_component_size=regions[0].area if regions else 0,
132
+ component_bounding_boxes=[region.bbox_xyxy for region in regions],
133
+ regions=regions,
134
+ preprocessing=preprocessing,
135
+ threshold=threshold,
136
+ checkpoint_provenance=provenance,
137
+ runtime=RuntimeStats(
138
+ load_seconds=lifecycle.load_time,
139
+ inference_seconds=total_seconds,
140
+ preprocessing_seconds=preprocessing_seconds,
141
+ model_seconds=model_seconds,
142
+ postprocessing_seconds=postprocessing_seconds,
143
+ peak_memory_mb=peak_memory_mb(selected),
144
+ ),
145
+ load_reuse_status={
146
+ "was_reused": was_reused,
147
+ "load_count": status["load_count"],
148
+ "reuse_count": status["reuse_count"],
149
+ "inference_count": status["inference_count"],
150
+ "state": status["state"],
151
+ },
152
+ stage_durations_ms={
153
+ "preprocessing": max(0, round(preprocessing_seconds * 1000)),
154
+ "inference": max(0, round(model_seconds * 1000)),
155
+ "probability_extraction": max(0, round(probability_seconds * 1000)),
156
+ "thresholding": max(0, round(threshold_seconds * 1000)),
157
+ "source_restoration": max(0, round(restoration_seconds * 1000)),
158
+ "connected_components": max(0, round(components_seconds * 1000)),
159
+ },
160
+ warnings=list(status["warnings"]),
161
+ limitations=[
162
+ "The output is a model prediction, not ground truth.",
163
+ "LEVIR-CD primarily represents building change and may not generalize to all land-cover changes.",
164
+ "Inputs must be geometrically co-registered; misregistration can appear as change.",
165
+ ],
166
+ )
167
+ except Exception as error:
168
+ if isinstance(error, ChangerExInferenceError):
169
+ raise
170
+ message = f"{type(error).__name__}: {error}".replace("\n", " ")[:500]
171
+ raise ChangerExInferenceError(message) from error
changerex_local/interaction.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Changer feature-exchange layers.
2
+
3
+ Adapted from Open-CD's Apache-2.0 licensed
4
+ ``opencd/models/utils/interaction_layer.py`` at the pinned commit.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import torch
10
+ from torch import nn
11
+
12
+
13
+ class TwoIdentity(nn.Module):
14
+ def forward(self, first: torch.Tensor, second: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
15
+ return first, second
16
+
17
+
18
+ class SpatialExchange(nn.Module):
19
+ def __init__(self, p: float = 0.5) -> None:
20
+ super().__init__()
21
+ if not 0 < p <= 1:
22
+ raise ValueError("p must be in (0, 1]")
23
+ self.period = int(1 / p)
24
+
25
+ def forward(self, first: torch.Tensor, second: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
26
+ mask = torch.arange(first.shape[-1], device=first.device) % self.period == 0
27
+ output_first = torch.zeros_like(first)
28
+ output_second = torch.zeros_like(second)
29
+ output_first[..., ~mask] = first[..., ~mask]
30
+ output_second[..., ~mask] = second[..., ~mask]
31
+ output_first[..., mask] = second[..., mask]
32
+ output_second[..., mask] = first[..., mask]
33
+ return output_first, output_second
34
+
35
+
36
+ class ChannelExchange(nn.Module):
37
+ def __init__(self, p: float = 0.5) -> None:
38
+ super().__init__()
39
+ if not 0 < p <= 1:
40
+ raise ValueError("p must be in (0, 1]")
41
+ self.period = int(1 / p)
42
+
43
+ def forward(self, first: torch.Tensor, second: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
44
+ mask = torch.arange(first.shape[1], device=first.device) % self.period == 0
45
+ output_first = torch.zeros_like(first)
46
+ output_second = torch.zeros_like(second)
47
+ output_first[:, ~mask] = first[:, ~mask]
48
+ output_second[:, ~mask] = second[:, ~mask]
49
+ output_first[:, mask] = second[:, mask]
50
+ output_second[:, mask] = first[:, mask]
51
+ return output_first, output_second
changerex_local/lifecycle.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Thread-safe, lazy, single-model lifecycle for ChangerEx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import platform
7
+ import resource
8
+ import threading
9
+ import time
10
+ from dataclasses import asdict
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import torch
15
+
16
+ from .architecture import ChangerEx, build_model, model_parameter_count
17
+ from .checkpoint import load_checkpoint_strict
18
+ from .config import PARAMETER_COUNT
19
+ from .schemas import CheckpointVerificationReport
20
+
21
+
22
+ class DeviceSelectionError(RuntimeError):
23
+ pass
24
+
25
+
26
+ class LifecycleError(RuntimeError):
27
+ pass
28
+
29
+
30
+ def _mps_is_verified() -> bool:
31
+ if not torch.backends.mps.is_built() or not torch.backends.mps.is_available():
32
+ return False
33
+ try:
34
+ test = torch.ones(1, device="mps") + 1
35
+ torch.mps.synchronize()
36
+ return float(test.cpu().item()) == 2.0
37
+ except Exception:
38
+ return False
39
+
40
+
41
+ def select_device(requested: str, *, allow_fallback: bool = False) -> tuple[str, list[str]]:
42
+ requested = requested.lower().strip()
43
+ if requested not in {"auto", "mps", "cpu"}:
44
+ raise DeviceSelectionError("device must be one of: auto, mps, cpu")
45
+ warnings: list[str] = []
46
+ if requested == "cpu":
47
+ return "cpu", warnings
48
+ if _mps_is_verified():
49
+ return "mps", warnings
50
+ if requested == "auto":
51
+ warnings.append("MPS was unavailable or failed verification; auto selected CPU.")
52
+ return "cpu", warnings
53
+ if allow_fallback:
54
+ warnings.append("Explicit MPS request could not be satisfied; CPU fallback was explicitly allowed.")
55
+ return "cpu", warnings
56
+ raise DeviceSelectionError(
57
+ "MPS was requested but is unavailable or failed verification. "
58
+ "Use --allow-device-fallback to permit CPU fallback."
59
+ )
60
+
61
+
62
+ def peak_memory_mb(device: str | None = None) -> float | None:
63
+ try:
64
+ if device == "mps" and hasattr(torch, "mps"):
65
+ return float(torch.mps.driver_allocated_memory() / (1024 * 1024))
66
+ value = float(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
67
+ # macOS reports bytes; Linux reports KiB.
68
+ return value / (1024 * 1024) if platform.system() == "Darwin" else value / 1024
69
+ except Exception:
70
+ return None
71
+
72
+
73
+ class ChangerExLifecycle:
74
+ """A sticky lifecycle. Failed instances are not retried in-process."""
75
+
76
+ def __init__(
77
+ self,
78
+ checkpoint_path: str | Path,
79
+ *,
80
+ device: str = "auto",
81
+ allow_device_fallback: bool = False,
82
+ ) -> None:
83
+ self.checkpoint_path = str(Path(checkpoint_path).expanduser().resolve())
84
+ self.requested_device = device
85
+ self.allow_device_fallback = allow_device_fallback
86
+ self.state = "unloaded"
87
+ self.selected_device: str | None = None
88
+ self.checkpoint_verified = False
89
+ self.load_count = 0
90
+ self.reuse_count = 0
91
+ self.inference_count = 0
92
+ self.load_time = 0.0
93
+ self.last_inference_time = 0.0
94
+ self.safe_error: str | None = None
95
+ self.model_parameter_count = 0
96
+ self.warnings: list[str] = []
97
+ self.checkpoint_report: CheckpointVerificationReport | None = None
98
+ self._model: ChangerEx | None = None
99
+ self._lock = threading.RLock()
100
+
101
+ @staticmethod
102
+ def _safe_error(error: BaseException) -> str:
103
+ message = f"{type(error).__name__}: {error}".replace("\n", " ")
104
+ return message[:500]
105
+
106
+ def ensure_loaded(self) -> tuple[ChangerEx, bool]:
107
+ with self._lock:
108
+ if self.state == "ready":
109
+ self.reuse_count += 1
110
+ assert self._model is not None
111
+ return self._model, True
112
+ if self.state == "failed":
113
+ raise LifecycleError(f"ChangerEx lifecycle is in sticky failed state: {self.safe_error}")
114
+ if self.state == "loading":
115
+ raise LifecycleError("Reentrant ChangerEx loading was detected")
116
+ self.state = "loading"
117
+ started = time.perf_counter()
118
+ try:
119
+ selected, warnings = select_device(
120
+ self.requested_device, allow_fallback=self.allow_device_fallback
121
+ )
122
+ model = build_model()
123
+ report = load_checkpoint_strict(model, self.checkpoint_path)
124
+ if model_parameter_count(model) != PARAMETER_COUNT:
125
+ raise LifecycleError(
126
+ f"Architecture parameter count mismatch: expected {PARAMETER_COUNT}, "
127
+ f"received {model_parameter_count(model)}"
128
+ )
129
+ model.eval().to(device=selected, dtype=torch.float32)
130
+ self.selected_device = selected
131
+ self.warnings.extend(warnings)
132
+ self.checkpoint_report = report
133
+ self.checkpoint_verified = True
134
+ self.model_parameter_count = model_parameter_count(model)
135
+ self._model = model
136
+ self.load_count += 1
137
+ self.state = "ready"
138
+ self.load_time = time.perf_counter() - started
139
+ return model, False
140
+ except Exception as error:
141
+ self.state = "failed"
142
+ self.safe_error = self._safe_error(error)
143
+ self.load_time = time.perf_counter() - started
144
+ self._model = None
145
+ raise LifecycleError(self.safe_error) from error
146
+
147
+ def record_inference(self, elapsed: float) -> None:
148
+ with self._lock:
149
+ self.inference_count += 1
150
+ self.last_inference_time = elapsed
151
+
152
+ def status(self) -> dict[str, Any]:
153
+ with self._lock:
154
+ return {
155
+ "state": self.state,
156
+ "requested_device": self.requested_device,
157
+ "selected_device": self.selected_device,
158
+ "checkpoint_verified": self.checkpoint_verified,
159
+ "load_count": self.load_count,
160
+ "reuse_count": self.reuse_count,
161
+ "inference_count": self.inference_count,
162
+ "load_time": self.load_time,
163
+ "last_inference_time": self.last_inference_time,
164
+ "safe_error": self.safe_error,
165
+ "model_parameter_count": self.model_parameter_count,
166
+ "peak_memory_mb": peak_memory_mb(self.selected_device),
167
+ "warnings": list(self.warnings),
168
+ "checkpoint_report": asdict(self.checkpoint_report) if self.checkpoint_report else None,
169
+ }
170
+
171
+
172
+ _singleton_lock = threading.RLock()
173
+ _singleton: ChangerExLifecycle | None = None
174
+
175
+
176
+ def configure_lifecycle(
177
+ checkpoint_path: str | Path,
178
+ *,
179
+ device: str = "auto",
180
+ allow_device_fallback: bool = False,
181
+ ) -> ChangerExLifecycle:
182
+ """Configure the one process-wide lifecycle without loading it yet."""
183
+ global _singleton
184
+ resolved = str(Path(checkpoint_path).expanduser().resolve())
185
+ with _singleton_lock:
186
+ if _singleton is None:
187
+ _singleton = ChangerExLifecycle(
188
+ resolved, device=device, allow_device_fallback=allow_device_fallback
189
+ )
190
+ return _singleton
191
+ if (
192
+ _singleton.checkpoint_path != resolved
193
+ or _singleton.requested_device != device
194
+ or _singleton.allow_device_fallback != allow_device_fallback
195
+ ):
196
+ raise LifecycleError(
197
+ "ChangerEx is already configured in this process; checkpoint and device are immutable"
198
+ )
199
+ return _singleton
200
+
201
+
202
+ def get_lifecycle(
203
+ *, device: str = "auto", allow_device_fallback: bool = False
204
+ ) -> ChangerExLifecycle:
205
+ global _singleton
206
+ with _singleton_lock:
207
+ if _singleton is not None:
208
+ if device != "auto" and _singleton.requested_device not in {"auto", device}:
209
+ raise LifecycleError(
210
+ f"ChangerEx is configured for {_singleton.requested_device}, not {device}"
211
+ )
212
+ return _singleton
213
+ checkpoint = os.environ.get("CHANGEREX_CHECKPOINT")
214
+ if not checkpoint:
215
+ raise LifecycleError(
216
+ "ChangerEx is not configured. Call configure_lifecycle(checkpoint_path, ...) "
217
+ "or set CHANGEREX_CHECKPOINT."
218
+ )
219
+ _singleton = ChangerExLifecycle(
220
+ checkpoint, device=device, allow_device_fallback=allow_device_fallback
221
+ )
222
+ return _singleton
223
+
224
+
225
+ def _reset_lifecycle_for_tests() -> None:
226
+ """Test-only reset; production callers must treat failure as sticky."""
227
+ global _singleton
228
+ with _singleton_lock:
229
+ _singleton = None
changerex_local/parity.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Strict comparison helpers for official-reference parity artifacts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import asdict, dataclass
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class ParityThresholds:
14
+ binary_mask_agreement_minimum: float = 0.999
15
+ mask_iou_minimum: float = 0.998
16
+ changed_percentage_difference_maximum: float = 0.1
17
+ probability_max_absolute_difference_maximum: float = 1e-4
18
+ probability_mean_absolute_difference_maximum: float = 1e-5
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ParityResult:
23
+ probability_shape_match: bool
24
+ mask_shape_match: bool
25
+ probability_max_absolute_difference: float
26
+ probability_mean_absolute_difference: float
27
+ binary_mask_agreement: float
28
+ mask_iou: float
29
+ changed_percentage_difference: float
30
+ floating_probability_pass: bool
31
+ mask_pass: bool
32
+ accepted: bool
33
+
34
+ def to_dict(self) -> dict[str, object]:
35
+ return asdict(self)
36
+
37
+
38
+ def compare_outputs(
39
+ extracted_probability: np.ndarray,
40
+ extracted_mask: np.ndarray,
41
+ reference_probability: np.ndarray,
42
+ reference_mask: np.ndarray,
43
+ *,
44
+ thresholds: ParityThresholds = ParityThresholds(),
45
+ ) -> ParityResult:
46
+ probability_shape_match = extracted_probability.shape == reference_probability.shape
47
+ mask_shape_match = extracted_mask.shape == reference_mask.shape
48
+ if not probability_shape_match or not mask_shape_match:
49
+ return ParityResult(
50
+ probability_shape_match,
51
+ mask_shape_match,
52
+ float("inf"),
53
+ float("inf"),
54
+ 0.0,
55
+ 0.0,
56
+ float("inf"),
57
+ False,
58
+ False,
59
+ False,
60
+ )
61
+ extracted_probability = np.asarray(extracted_probability, dtype=np.float64)
62
+ reference_probability = np.asarray(reference_probability, dtype=np.float64)
63
+ extracted_mask = np.asarray(extracted_mask).astype(bool)
64
+ reference_mask = np.asarray(reference_mask).astype(bool)
65
+ difference = np.abs(extracted_probability - reference_probability)
66
+ agreement = float(np.mean(extracted_mask == reference_mask))
67
+ intersection = int(np.logical_and(extracted_mask, reference_mask).sum())
68
+ union = int(np.logical_or(extracted_mask, reference_mask).sum())
69
+ iou = 1.0 if union == 0 else intersection / union
70
+ extracted_changed = 100.0 * float(extracted_mask.mean())
71
+ reference_changed = 100.0 * float(reference_mask.mean())
72
+ changed_difference = abs(extracted_changed - reference_changed)
73
+ maximum = float(difference.max()) if difference.size else 0.0
74
+ mean = float(difference.mean()) if difference.size else 0.0
75
+ floating_pass = (
76
+ maximum <= thresholds.probability_max_absolute_difference_maximum
77
+ and mean <= thresholds.probability_mean_absolute_difference_maximum
78
+ )
79
+ mask_pass = (
80
+ agreement >= thresholds.binary_mask_agreement_minimum
81
+ and iou >= thresholds.mask_iou_minimum
82
+ and changed_difference <= thresholds.changed_percentage_difference_maximum
83
+ )
84
+ return ParityResult(
85
+ probability_shape_match=True,
86
+ mask_shape_match=True,
87
+ probability_max_absolute_difference=maximum,
88
+ probability_mean_absolute_difference=mean,
89
+ binary_mask_agreement=agreement,
90
+ mask_iou=iou,
91
+ changed_percentage_difference=changed_difference,
92
+ floating_probability_pass=floating_pass,
93
+ mask_pass=mask_pass,
94
+ accepted=floating_pass and mask_pass,
95
+ )
96
+
97
+
98
+ def save_parity_report(
99
+ path: str | Path,
100
+ result: ParityResult,
101
+ *,
102
+ thresholds: ParityThresholds = ParityThresholds(),
103
+ metadata: dict[str, object] | None = None,
104
+ ) -> None:
105
+ payload = {
106
+ "result": result.to_dict(),
107
+ "thresholds": asdict(thresholds),
108
+ "metadata": metadata or {},
109
+ }
110
+ Path(path).write_text(json.dumps(payload, indent=2), encoding="utf-8")
changerex_local/postprocessing.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dependency-free ChangerEx probability and mask postprocessing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import deque
6
+
7
+ import numpy as np
8
+ from PIL import Image
9
+
10
+ from .schemas import Region
11
+
12
+
13
+ class ProbabilityValidationError(ValueError):
14
+ pass
15
+
16
+
17
+ def validate_probability_map(probability_map: np.ndarray) -> np.ndarray:
18
+ array = np.asarray(probability_map, dtype=np.float32)
19
+ if array.ndim != 2 or not array.size:
20
+ raise ProbabilityValidationError("Probability map must be a non-empty 2D array")
21
+ if not np.isfinite(array).all():
22
+ raise ProbabilityValidationError("Probability map contains non-finite values")
23
+ minimum = float(array.min())
24
+ maximum = float(array.max())
25
+ if minimum < -1e-6 or maximum > 1.0 + 1e-6:
26
+ raise ProbabilityValidationError(
27
+ f"Probability values must be within [0, 1]; received [{minimum}, {maximum}]"
28
+ )
29
+ return np.clip(array, 0.0, 1.0)
30
+
31
+
32
+ def threshold_probability(probability_map: np.ndarray, threshold: float = 0.5) -> np.ndarray:
33
+ if not 0.0 <= threshold <= 1.0:
34
+ raise ValueError("threshold must be within [0, 1]")
35
+ return (validate_probability_map(probability_map) >= threshold).astype(np.uint8)
36
+
37
+
38
+ def connected_components(mask: np.ndarray, *, minimum_area: int = 1) -> list[Region]:
39
+ """Compute 8-connected regions; bboxes use exclusive x2/y2 coordinates."""
40
+ if minimum_area < 1:
41
+ raise ValueError("minimum_area must be at least one")
42
+ binary = np.asarray(mask)
43
+ if binary.ndim != 2:
44
+ raise ValueError("Binary mask must be 2D")
45
+ binary = binary.astype(bool, copy=False)
46
+ height, width = binary.shape
47
+ visited = np.zeros_like(binary, dtype=bool)
48
+ regions: list[Region] = []
49
+ label = 0
50
+ for start_y, start_x in np.argwhere(binary):
51
+ y0 = int(start_y)
52
+ x0 = int(start_x)
53
+ if visited[y0, x0]:
54
+ continue
55
+ label += 1
56
+ queue: deque[tuple[int, int]] = deque([(y0, x0)])
57
+ visited[y0, x0] = True
58
+ area = 0
59
+ min_x = max_x = x0
60
+ min_y = max_y = y0
61
+ while queue:
62
+ y, x = queue.popleft()
63
+ area += 1
64
+ min_x, max_x = min(min_x, x), max(max_x, x)
65
+ min_y, max_y = min(min_y, y), max(max_y, y)
66
+ for next_y in range(max(0, y - 1), min(height, y + 2)):
67
+ for next_x in range(max(0, x - 1), min(width, x + 2)):
68
+ if binary[next_y, next_x] and not visited[next_y, next_x]:
69
+ visited[next_y, next_x] = True
70
+ queue.append((next_y, next_x))
71
+ if area >= minimum_area:
72
+ regions.append(Region(label=label, area=area, bbox_xyxy=(min_x, min_y, max_x + 1, max_y + 1)))
73
+ regions.sort(key=lambda region: region.area, reverse=True)
74
+ return regions
75
+
76
+
77
+ def make_display_mask(mask: np.ndarray) -> Image.Image:
78
+ binary = (np.asarray(mask).astype(bool) * 255).astype(np.uint8)
79
+ red = np.zeros((*binary.shape, 3), dtype=np.uint8)
80
+ red[..., 0] = binary
81
+ return Image.fromarray(red)
82
+
83
+
84
+ def make_overlay(later_image: Image.Image, mask: np.ndarray, alpha: float = 0.45) -> Image.Image:
85
+ if not 0.0 <= alpha <= 1.0:
86
+ raise ValueError("alpha must be within [0, 1]")
87
+ base = np.asarray(later_image.convert("RGB"), dtype=np.float32).copy()
88
+ binary = np.asarray(mask).astype(bool)
89
+ if binary.shape != base.shape[:2]:
90
+ raise ValueError("Overlay mask and later image dimensions must match")
91
+ red = np.zeros_like(base)
92
+ red[..., 0] = 255.0
93
+ base[binary] = (1.0 - alpha) * base[binary] + alpha * red[binary]
94
+ return Image.fromarray(np.clip(base, 0, 255).astype(np.uint8))
changerex_local/preprocessing.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Official ChangerEx test preprocessing without Open-CD runtime dependencies."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Union
7
+
8
+ import numpy as np
9
+ import torch
10
+ from PIL import Image
11
+ from torch.nn import functional as functional
12
+
13
+ from .config import DEFAULT_MAXIMUM_DIMENSION, RGB_MEAN, RGB_STD, SIZE_DIVISOR
14
+ from .schemas import PreprocessingDetails
15
+
16
+
17
+ ImageInput = Union[str, Path, Image.Image, np.ndarray]
18
+
19
+
20
+ class ImageValidationError(ValueError):
21
+ pass
22
+
23
+
24
+ def load_rgb_image(image: ImageInput) -> Image.Image:
25
+ if isinstance(image, (str, Path)):
26
+ path = Path(image).expanduser()
27
+ if not path.is_file():
28
+ raise ImageValidationError(f"Image file does not exist: {path}")
29
+ with Image.open(path) as opened:
30
+ return opened.convert("RGB").copy()
31
+ if isinstance(image, Image.Image):
32
+ return image.convert("RGB").copy()
33
+ if isinstance(image, np.ndarray):
34
+ array = np.asarray(image)
35
+ if array.ndim != 3 or array.shape[2] not in (3, 4):
36
+ raise ImageValidationError("NumPy images must have shape HxWx3 or HxWx4")
37
+ if array.dtype != np.uint8:
38
+ if not np.issubdtype(array.dtype, np.number) or not np.isfinite(array).all():
39
+ raise ImageValidationError("Image array must contain finite numeric values")
40
+ if array.min() < 0 or array.max() > 255:
41
+ raise ImageValidationError("Image array values must be within [0, 255]")
42
+ array = array.astype(np.uint8)
43
+ return Image.fromarray(array[..., :3])
44
+ raise ImageValidationError(f"Unsupported image type: {type(image).__name__}")
45
+
46
+
47
+ def _image_to_tensor(image: Image.Image) -> torch.Tensor:
48
+ array = np.asarray(image, dtype=np.uint8).copy()
49
+ return torch.from_numpy(array).permute(2, 0, 1).to(dtype=torch.float32)
50
+
51
+
52
+ def _official_resize_shape(width: int, height: int, maximum_dimension: int) -> tuple[int, int, float]:
53
+ if maximum_dimension <= 0:
54
+ raise ImageValidationError("maximum_dimension must be a positive integer")
55
+ scale = maximum_dimension / max(width, height)
56
+ resized_width = max(1, int(width * scale + 0.5))
57
+ resized_height = max(1, int(height * scale + 0.5))
58
+ return resized_width, resized_height, scale
59
+
60
+
61
+ def preprocess_pair(
62
+ earlier_image: ImageInput,
63
+ later_image: ImageInput,
64
+ *,
65
+ maximum_dimension: int = DEFAULT_MAXIMUM_DIMENSION,
66
+ ) -> tuple[torch.Tensor, PreprocessingDetails, Image.Image]:
67
+ """Return normalized NCHW pair, details, and the source-sized later image."""
68
+ earlier = load_rgb_image(earlier_image)
69
+ later = load_rgb_image(later_image)
70
+ if earlier.size != later.size:
71
+ raise ImageValidationError(
72
+ f"Paired images must have identical dimensions; got {earlier.size} and {later.size}"
73
+ )
74
+ width, height = earlier.size
75
+ if width < 1 or height < 1:
76
+ raise ImageValidationError("Images must have non-zero dimensions")
77
+
78
+ resized_width, resized_height, scale = _official_resize_shape(
79
+ width, height, maximum_dimension
80
+ )
81
+ pair = torch.cat((_image_to_tensor(earlier), _image_to_tensor(later)), dim=0).unsqueeze(0)
82
+ if (resized_height, resized_width) != (height, width):
83
+ pair = functional.interpolate(
84
+ pair, size=(resized_height, resized_width), mode="bilinear", align_corners=False
85
+ )
86
+
87
+ mean = pair.new_tensor(RGB_MEAN * 2).view(1, 6, 1, 1)
88
+ std = pair.new_tensor(RGB_STD * 2).view(1, 6, 1, 1)
89
+ pair = (pair - mean) / std
90
+
91
+ padded_width = ((resized_width + SIZE_DIVISOR - 1) // SIZE_DIVISOR) * SIZE_DIVISOR
92
+ padded_height = ((resized_height + SIZE_DIVISOR - 1) // SIZE_DIVISOR) * SIZE_DIVISOR
93
+ pad_right = padded_width - resized_width
94
+ pad_bottom = padded_height - resized_height
95
+ if pad_right or pad_bottom:
96
+ pair = functional.pad(pair, (0, pad_right, 0, pad_bottom), value=0.0)
97
+
98
+ details = PreprocessingDetails(
99
+ source_size=(width, height),
100
+ resized_size=(resized_width, resized_height),
101
+ padded_size=(padded_width, padded_height),
102
+ scale=scale,
103
+ channel_order="RGB",
104
+ pair_order="earlier RGB, then later RGB",
105
+ input_range="float32 source values in [0, 255] before normalization",
106
+ mean=RGB_MEAN,
107
+ std=RGB_STD,
108
+ resize_interpolation="bilinear, align_corners=False",
109
+ pad=(0, 0, pad_right, pad_bottom),
110
+ size_divisor=SIZE_DIVISOR,
111
+ )
112
+ return pair.contiguous(), details, later
113
+
114
+
115
+ def preprocessing_tensor_summary(tensor: torch.Tensor) -> dict[str, object]:
116
+ data = tensor.detach().cpu().contiguous()
117
+ return {
118
+ "shape": list(data.shape),
119
+ "dtype": str(data.dtype),
120
+ "sum": float(data.sum()),
121
+ "mean": float(data.mean()),
122
+ "std": float(data.std()),
123
+ "min": float(data.min()),
124
+ "max": float(data.max()),
125
+ }
changerex_local/requirements-macos.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Standalone runtime only; Open-CD/MMCV/MMSeg are intentionally absent.
2
+ torch>=2.8,<2.9
3
+ numpy>=1.26,<3
4
+ Pillow>=11,<12
changerex_local/schemas.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dataclasses returned by the standalone ChangerEx package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict, dataclass, field
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class PreprocessingDetails:
13
+ source_size: tuple[int, int]
14
+ resized_size: tuple[int, int]
15
+ padded_size: tuple[int, int]
16
+ scale: float
17
+ channel_order: str
18
+ pair_order: str
19
+ input_range: str
20
+ mean: tuple[float, float, float]
21
+ std: tuple[float, float, float]
22
+ resize_interpolation: str
23
+ pad: tuple[int, int, int, int]
24
+ size_divisor: int
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Region:
29
+ label: int
30
+ area: int
31
+ bbox_xyxy: tuple[int, int, int, int]
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class RuntimeStats:
36
+ load_seconds: float
37
+ inference_seconds: float
38
+ preprocessing_seconds: float
39
+ model_seconds: float
40
+ postprocessing_seconds: float
41
+ peak_memory_mb: float | None
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class CheckpointVerificationReport:
46
+ path: str
47
+ file_size: int
48
+ sha256: str
49
+ top_level_keys: tuple[str, ...]
50
+ tensor_count: int
51
+ parameter_count: int
52
+ missing_keys: tuple[str, ...]
53
+ unexpected_keys: tuple[str, ...]
54
+ key_transformations: tuple[str, ...]
55
+ checkpoint_metadata: dict[str, Any]
56
+
57
+ def to_dict(self) -> dict[str, Any]:
58
+ return asdict(self)
59
+
60
+
61
+ @dataclass
62
+ class ChangerExResult:
63
+ source_width: int
64
+ source_height: int
65
+ model_input_width: int
66
+ model_input_height: int
67
+ selected_device: str
68
+ probability_map: np.ndarray = field(repr=False)
69
+ binary_mask: np.ndarray = field(repr=False)
70
+ changed_pixel_count: int = 0
71
+ changed_percentage: float = 0.0
72
+ connected_component_count: int = 0
73
+ largest_component_size: int = 0
74
+ component_bounding_boxes: list[tuple[int, int, int, int]] = field(default_factory=list)
75
+ regions: list[Region] = field(default_factory=list)
76
+ preprocessing: PreprocessingDetails | None = None
77
+ threshold: float = 0.5
78
+ checkpoint_provenance: dict[str, Any] = field(default_factory=dict)
79
+ runtime: RuntimeStats | None = None
80
+ load_reuse_status: dict[str, Any] = field(default_factory=dict)
81
+ warnings: list[str] = field(default_factory=list)
82
+ limitations: list[str] = field(default_factory=list)
83
+ stage_durations_ms: dict[str, int] = field(default_factory=dict)
84
+
85
+ def summary(self) -> dict[str, Any]:
86
+ """Return a JSON-safe summary without embedding full raster arrays."""
87
+ return {
88
+ "source_width": self.source_width,
89
+ "source_height": self.source_height,
90
+ "model_input_width": self.model_input_width,
91
+ "model_input_height": self.model_input_height,
92
+ "selected_device": self.selected_device,
93
+ "probability_shape": list(self.probability_map.shape),
94
+ "probability_min": float(self.probability_map.min()),
95
+ "probability_max": float(self.probability_map.max()),
96
+ "binary_mask_shape": list(self.binary_mask.shape),
97
+ "changed_pixel_count": self.changed_pixel_count,
98
+ "changed_percentage": self.changed_percentage,
99
+ "connected_component_count": self.connected_component_count,
100
+ "largest_component_size": self.largest_component_size,
101
+ "component_bounding_boxes": [list(box) for box in self.component_bounding_boxes],
102
+ "preprocessing": asdict(self.preprocessing) if self.preprocessing else None,
103
+ "threshold": self.threshold,
104
+ "checkpoint_provenance": self.checkpoint_provenance,
105
+ "runtime": asdict(self.runtime) if self.runtime else None,
106
+ "load_reuse_status": self.load_reuse_status,
107
+ "stage_durations_ms": self.stage_durations_ms,
108
+ "warnings": self.warnings,
109
+ "limitations": self.limitations,
110
+ }
models/MODEL_MANIFEST.json ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "project": "SatQuery AI",
3
+ "team": "CodeBlueX",
4
+ "competition": "Smart India Hackathon 2026",
5
+ "problem_statement_id": "26167",
6
+ "organization": "ISRO / Department of Space",
7
+ "model_repository": "AnirudhShashikumar/SatQuery_AI_Models",
8
+ "repository_visibility": "private",
9
+
10
+ "public_upstream_dependencies": [
11
+ {
12
+ "name": "OpenCLIP ViT-L-14 laion2b_s32b_b82k",
13
+ "repository": "laion/CLIP-ViT-L-14-laion2B-s32B-b82K",
14
+ "revision": "1627032197142fbe2a7cfec626f4ced3ae60d07a",
15
+ "artifact": "open_clip_pytorch_model.safetensors",
16
+ "visibility": "public",
17
+ "codebluex_trained": false,
18
+ "used_by": "SatQuery Vision Encoder v1 reconstruction"
19
+ },
20
+ {
21
+ "name": "BLIP image-captioning base RSICD fine-tune",
22
+ "repository": "Gurveer05/blip-image-captioning-base-rscid-finetuned",
23
+ "revision": "57c4f0ff06264d374131637ce7c1e8dea079d589",
24
+ "visibility": "public",
25
+ "codebluex_trained": false,
26
+ "used_by": "RSICD captioner"
27
+ }
28
+ ],
29
+
30
+ "codebluex_artifacts": [
31
+ {
32
+ "name": "SatQuery Vision Encoder v1 Adapter",
33
+ "path": "satquery_vision_encoder_v1/satquery_vision_encoder_v1_adapter.pt",
34
+ "sha256": "a99c0bf0fb44044988ef1698483888c8a2e3a047d2d2d56478837575cf7626ea",
35
+ "provenance": "CodeBlueX remote-sensing adaptation",
36
+ "base_architecture": "OpenCLIP ViT-L/14"
37
+ },
38
+ {
39
+ "name": "RSVQA Specialist v1 Head",
40
+ "path": "rsvqa_specialist_v1/rsvqa_specialist_v1_head.pt",
41
+ "sha256": "71c0ab56ee650813bd495e8a3bc777353b6907a097af860e417f60523efe56ad",
42
+ "provenance": "CodeBlueX trained/adapted specialist head",
43
+ "benchmark": {
44
+ "dataset": "RSVQA-LR official test split",
45
+ "samples": 10004,
46
+ "exact_accuracy_percent": 71.05,
47
+ "overflow_aware_accuracy_percent": 74.31
48
+ }
49
+ },
50
+ {
51
+ "name": "Grounding Specialist v1.1 Head",
52
+ "path": "grounding_specialist_v1_1/grounding_specialist_v1_1_head.pt",
53
+ "sha256": "5e8db30becadb1d063fc0154614ee2a2a4b7a2c2923db3fce4ff036c65007342",
54
+ "provenance": "CodeBlueX trained/adapted grounding specialist head",
55
+ "benchmark": {
56
+ "dataset": "VRSBench validation",
57
+ "samples": 16146,
58
+ "miou": 0.2348,
59
+ "accuracy_at_0_50_percent": 25.05
60
+ }
61
+ },
62
+ {
63
+ "name": "Pix2Pix SAR Reconstruction Checkpoint",
64
+ "path": "sar_translation/pix2pix/pix2pix_gen_180.pth",
65
+ "local_path": "../pix2pix_gen_180.pth",
66
+ "sha256": "5bdc6bf9b29986860d6537265280bb47b74f85ebe1222256ddc59acce3a743b3",
67
+ "provenance": "CodeBlueX SatQuery SAR reconstruction pipeline",
68
+ "architecture": "Pix2Pix"
69
+ },
70
+ {
71
+ "name": "SARFusionFormer SAR Reconstruction Checkpoint",
72
+ "path": "sar_translation/sarfusionformer/sarfusionformer_256_decoder_best.pt",
73
+ "local_path": "../models/checkpoints/sarfusionformer_256_decoder_best.pt",
74
+ "sha256": "6c8ac2d482b66877a910a9c95e6398f9e0586f13f786d0243c736a2d10b30548",
75
+ "provenance": "CodeBlueX SatQuery SAR reconstruction pipeline",
76
+ "architecture": "SARFusionFormer"
77
+ },
78
+ {
79
+ "name": "SARFusionFormer Color Corrector",
80
+ "path": "sar_translation/sarfusionformer/color_corrector_256_best.pt",
81
+ "local_path": "../models/checkpoints/color_corrector_256_best.pt",
82
+ "sha256": "15298976fbffe93c16d81716c40fe3c7a09499e63e649edd4de9a1fd70ec675d",
83
+ "provenance": "CodeBlueX SatQuery SAR reconstruction pipeline",
84
+ "architecture": "ColorCorrectionNet"
85
+ }
86
+ ],
87
+
88
+ "third_party_components": [
89
+ {
90
+ "name": "Grounding DINO Tiny",
91
+ "local_path": "models/grounding_dino_tiny/model.safetensors",
92
+ "sha256": "1a2412ef99bd74bcd3c2a246fa1e48581f8889a1300c9051974741314fc042f3",
93
+ "provenance": "Third-party pretrained base model",
94
+ "codebluex_trained": false
95
+ },
96
+ {
97
+ "name": "ChangerEx",
98
+ "local_path": "models/changerex/ChangerEx_r18-512x512_40k_levircd_20221223_120511.pth",
99
+ "sha256": "da3f569306dadd1fac5b64abc2a3d484571cd0ecf6410e1f152275cfe49a3618",
100
+ "provenance": "Third-party pretrained checkpoint",
101
+ "codebluex_trained": false
102
+ }
103
+ ]
104
+ }
models/changerex/ChangerEx_r18-512x512_40k_levircd_20221223_120511.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da3f569306dadd1fac5b64abc2a3d484571cd0ecf6410e1f152275cfe49a3618
3
+ size 136880383
models/grounding_dino_tiny/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
models/grounding_dino_tiny/README.md ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ tags:
4
+ - vision
5
+ inference: false
6
+ pipeline_tag: zero-shot-object-detection
7
+ ---
8
+
9
+ # Grounding DINO model (tiny variant)
10
+
11
+ The Grounding DINO model was proposed in [Grounding DINO: Marrying DINO with Grounded Pre-Training for Open-Set Object Detection](https://arxiv.org/abs/2303.05499) by Shilong Liu, Zhaoyang Zeng, Tianhe Ren, Feng Li, Hao Zhang, Jie Yang, Chunyuan Li, Jianwei Yang, Hang Su, Jun Zhu, Lei Zhang. Grounding DINO extends a closed-set object detection model with a text encoder, enabling open-set object detection. The model achieves remarkable results, such as 52.5 AP on COCO zero-shot.
12
+
13
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/grouding_dino_architecture.png"
14
+ alt="drawing" width="600"/>
15
+
16
+ <small> Grounding DINO overview. Taken from the <a href="https://arxiv.org/abs/2303.05499">original paper</a>. </small>
17
+
18
+ ## Intended uses & limitations
19
+
20
+ You can use the raw model for zero-shot object detection (the task of detecting things in an image out-of-the-box without labeled data).
21
+
22
+ ### How to use
23
+
24
+ Here's how to use the model for zero-shot object detection:
25
+
26
+ ```python
27
+ import requests
28
+
29
+ import torch
30
+ from PIL import Image
31
+ from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection
32
+
33
+ model_id = "IDEA-Research/grounding-dino-tiny"
34
+ device = "cuda" if torch.cuda.is_available() else "cpu"
35
+
36
+ processor = AutoProcessor.from_pretrained(model_id)
37
+ model = AutoModelForZeroShotObjectDetection.from_pretrained(model_id).to(device)
38
+
39
+ image_url = "http://images.cocodataset.org/val2017/000000039769.jpg"
40
+ image = Image.open(requests.get(image_url, stream=True).raw)
41
+ # Check for cats and remote controls
42
+ # VERY important: text queries need to be lowercased + end with a dot
43
+ text = "a cat. a remote control."
44
+
45
+ inputs = processor(images=image, text=text, return_tensors="pt").to(device)
46
+ with torch.no_grad():
47
+ outputs = model(**inputs)
48
+
49
+ results = processor.post_process_grounded_object_detection(
50
+ outputs,
51
+ inputs.input_ids,
52
+ box_threshold=0.4,
53
+ text_threshold=0.3,
54
+ target_sizes=[image.size[::-1]]
55
+ )
56
+ ```
57
+
58
+ ### BibTeX entry and citation info
59
+
60
+ ```bibtex
61
+ @misc{liu2023grounding,
62
+ title={Grounding DINO: Marrying DINO with Grounded Pre-Training for Open-Set Object Detection},
63
+ author={Shilong Liu and Zhaoyang Zeng and Tianhe Ren and Feng Li and Hao Zhang and Jie Yang and Chunyuan Li and Jianwei Yang and Hang Su and Jun Zhu and Lei Zhang},
64
+ year={2023},
65
+ eprint={2303.05499},
66
+ archivePrefix={arXiv},
67
+ primaryClass={cs.CV}
68
+ }
69
+ ```
models/grounding_dino_tiny/added_tokens.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "[CLS]": 101,
3
+ "[MASK]": 103,
4
+ "[PAD]": 0,
5
+ "[SEP]": 102,
6
+ "[UNK]": 100
7
+ }
models/grounding_dino_tiny/config.json ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_dropout": 0.0,
3
+ "activation_function": "relu",
4
+ "architectures": [
5
+ "GroundingDinoForObjectDetection"
6
+ ],
7
+ "attention_dropout": 0.0,
8
+ "auxiliary_loss": false,
9
+ "backbone": null,
10
+ "backbone_config": {
11
+ "depths": [
12
+ 2,
13
+ 2,
14
+ 6,
15
+ 2
16
+ ],
17
+ "model_type": "swin",
18
+ "num_heads": [
19
+ 3,
20
+ 6,
21
+ 12,
22
+ 24
23
+ ],
24
+ "out_features": [
25
+ "stage2",
26
+ "stage3",
27
+ "stage4"
28
+ ],
29
+ "out_indices": [
30
+ 2,
31
+ 3,
32
+ 4
33
+ ]
34
+ },
35
+ "backbone_kwargs": null,
36
+ "bbox_cost": 5.0,
37
+ "bbox_loss_coefficient": 5.0,
38
+ "class_cost": 1.0,
39
+ "d_model": 256,
40
+ "decoder_attention_heads": 8,
41
+ "decoder_bbox_embed_share": true,
42
+ "decoder_ffn_dim": 2048,
43
+ "decoder_layers": 6,
44
+ "decoder_n_points": 4,
45
+ "disable_custom_kernels": false,
46
+ "dropout": 0.1,
47
+ "embedding_init_target": true,
48
+ "encoder_attention_heads": 8,
49
+ "encoder_ffn_dim": 2048,
50
+ "encoder_layers": 6,
51
+ "encoder_n_points": 4,
52
+ "focal_alpha": 0.25,
53
+ "fusion_dropout": 0.0,
54
+ "fusion_droppath": 0.1,
55
+ "giou_cost": 2.0,
56
+ "giou_loss_coefficient": 2.0,
57
+ "init_std": 0.02,
58
+ "is_encoder_decoder": true,
59
+ "layer_norm_eps": 1e-05,
60
+ "max_text_len": 256,
61
+ "model_type": "grounding-dino",
62
+ "num_feature_levels": 4,
63
+ "num_queries": 900,
64
+ "position_embedding_type": "sine",
65
+ "positional_embedding_temperature": 20,
66
+ "query_dim": 4,
67
+ "text_config": {
68
+ "model_type": "bert"
69
+ },
70
+ "text_enhancer_dropout": 0.0,
71
+ "torch_dtype": "float32",
72
+ "transformers_version": "4.40.0.dev0",
73
+ "two_stage": true,
74
+ "two_stage_bbox_embed_share": false,
75
+ "use_pretrained_backbone": false,
76
+ "use_timm_backbone": false
77
+ }
models/grounding_dino_tiny/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a2412ef99bd74bcd3c2a246fa1e48581f8889a1300c9051974741314fc042f3
3
+ size 689359096
models/grounding_dino_tiny/preprocessor_config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_normalize": true,
3
+ "do_pad": true,
4
+ "do_rescale": true,
5
+ "do_resize": true,
6
+ "format": "coco_detection",
7
+ "image_mean": [
8
+ 0.485,
9
+ 0.456,
10
+ 0.406
11
+ ],
12
+ "image_processor_type": "GroundingDinoImageProcessor",
13
+ "image_std": [
14
+ 0.229,
15
+ 0.224,
16
+ 0.225
17
+ ],
18
+ "processor_class": "GroundingDinoProcessor",
19
+ "resample": 2,
20
+ "rescale_factor": 0.00392156862745098,
21
+ "size": {
22
+ "longest_edge": 1333,
23
+ "shortest_edge": 800
24
+ }
25
+ }
models/grounding_dino_tiny/special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
models/grounding_dino_tiny/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
models/grounding_dino_tiny/tokenizer_config.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": true,
47
+ "mask_token": "[MASK]",
48
+ "model_max_length": 512,
49
+ "pad_token": "[PAD]",
50
+ "processor_class": "GroundingDinoProcessor",
51
+ "sep_token": "[SEP]",
52
+ "strip_accents": null,
53
+ "tokenize_chinese_chars": true,
54
+ "tokenizer_class": "BertTokenizer",
55
+ "unk_token": "[UNK]"
56
+ }
models/grounding_dino_tiny/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
models/grounding_specialist_v1_1/architecture.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "SatQuery Grounding Specialist v1.1",
3
+ "base_model": "IDEA-Research/grounding-dino-tiny",
4
+ "base_model_frozen": true,
5
+ "checkpoint_step": 600,
6
+ "specialist_head": {
7
+ "hidden_dim": 256,
8
+ "intermediate_dim": 256,
9
+ "max_box_delta": 0.15,
10
+ "query_scorer": [
11
+ "LayerNorm(256)",
12
+ "Linear(256,256)",
13
+ "GELU",
14
+ "Dropout(0.1)",
15
+ "Linear(256,1)"
16
+ ],
17
+ "box_refiner": [
18
+ "LayerNorm(256)",
19
+ "Linear(256,256)",
20
+ "GELU",
21
+ "Dropout(0.1)",
22
+ "Linear(256,4)",
23
+ "Tanh"
24
+ ]
25
+ },
26
+ "prediction_policy": {
27
+ "selection": "highest specialist query logit",
28
+ "confidence": "sigmoid(selected query logit)",
29
+ "box_format_internal": "normalized cxcywh",
30
+ "box_format_output": "normalized xyxy",
31
+ "oracle_selection": false,
32
+ "old_reliability_gate": false
33
+ }
34
+ }
models/grounding_specialist_v1_1/model_card.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "SatQuery Grounding Specialist v1.1",
3
+ "status": "benchmark-validated",
4
+ "training_dataset": "VRSBench grounding_v2",
5
+ "training_records": 36277,
6
+ "validation_records": 16146,
7
+ "trainable_parameters": 133893,
8
+ "training_recipe": {
9
+ "balanced_sampling": true,
10
+ "area_regularization_weight": 0.05,
11
+ "query_entropy_weight": 0.01,
12
+ "best_step": 600
13
+ },
14
+ "full_validation": {
15
+ "mean_iou": 0.23478312188203337,
16
+ "accuracy_at_025": 0.32484825963086833,
17
+ "accuracy_at_050": 0.2505264461786201,
18
+ "accuracy_at_075": 0.1434410999628391,
19
+ "unique_queries_used": 796,
20
+ "top_1_query_usage": 0.1013873405177753,
21
+ "top_5_query_coverage": 0.28130806391675955,
22
+ "query_collapse_detected": false
23
+ },
24
+ "limitations": [
25
+ "Confidence scores are not calibrated probabilities.",
26
+ "The model always selects one query unless inference fails.",
27
+ "Performance is weak for some classes including windmill, tennis-court, bridge and harbor.",
28
+ "Benchmark results apply to the verified VRSBench validation pipeline."
29
+ ]
30
+ }
models/grounding_specialist_v1_1/sha256.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "grounding_specialist_v1_1_head.pt": "5e8db30becadb1d063fc0154614ee2a2a4b7a2c2923db3fce4ff036c65007342",
3
+ "validation_results.json": "870ba9d7608e5f950c73e4b92b901f714d64b530eb2b2e0ed5d380aac214da7e",
4
+ "architecture.json": "f18e1e1a77cc340ccd432a068fcc2d587911d453812bec857f4b6a1a91022d7f",
5
+ "model_card.json": "710eef4a1875f0768e7556c527fca5944d0d09cf770acc3fba3f33ae365d2409"
6
+ }
models/grounding_specialist_v1_1/validation_results.json ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "SatQuery Grounding Specialist v1.1",
3
+ "base_model": "IDEA-Research/grounding-dino-tiny",
4
+ "checkpoint": "/content/drive/MyDrive/SatQuery_Benchmarks/VRSBench/checkpoints/grounding_specialist_v1_1/grounding_specialist_v1_1_best_accuracy50.pt",
5
+ "checkpoint_step": 600,
6
+ "training_recipe_version": "v1.1",
7
+ "balanced_sampling": true,
8
+ "area_regularization_weight": 0.05,
9
+ "query_entropy_weight": 0.01,
10
+ "overall": {
11
+ "samples": 16146,
12
+ "mean_iou": 0.23478312188203337,
13
+ "median_iou": 7.23072917026002e-05,
14
+ "accuracy_at_025": 0.32484825963086833,
15
+ "accuracy_at_050": 0.2505264461786201,
16
+ "accuracy_at_075": 0.1434410999628391,
17
+ "average_confidence": 0.027266551232900782,
18
+ "average_predicted_box_area": 0.11250199105038895,
19
+ "average_ground_truth_box_area": 0.0730425927419267,
20
+ "median_area_ratio": 1.1552188779221426,
21
+ "oversized_prediction_rate": 0.3325281803542673,
22
+ "undersized_prediction_rate": 0.18165489904620338,
23
+ "average_latency_ms": 34.829105900159504,
24
+ "median_latency_ms": 34.59407400009695,
25
+ "p95_latency_ms": 36.226647249804955,
26
+ "runtime_seconds": 572.4572219848633,
27
+ "throughput_samples_per_second": 28.20472758473982,
28
+ "peak_gpu_memory_gib": 8.177523136138916,
29
+ "unique_queries_used": 796,
30
+ "top_1_query_usage": 0.1013873405177753,
31
+ "top_5_query_coverage": 0.28130806391675955,
32
+ "top_10_query_coverage": 0.38127090301003347
33
+ },
34
+ "per_class": {
35
+ "airplane": {
36
+ "samples": 1461,
37
+ "mean_iou": 0.3597279780967033,
38
+ "median_iou": 0.19315439462661743,
39
+ "accuracy_at_025": 0.4921286789869952,
40
+ "accuracy_at_050": 0.4188911704312115,
41
+ "accuracy_at_075": 0.2511978097193703,
42
+ "average_confidence": 0.027473842840537194,
43
+ "average_predicted_box_area": 0.09921906843461668,
44
+ "average_ground_truth_box_area": 0.11158446286157797
45
+ },
46
+ "airport": {
47
+ "samples": 195,
48
+ "mean_iou": 0.2730574051942079,
49
+ "median_iou": 0.10743331909179688,
50
+ "accuracy_at_025": 0.4153846153846154,
51
+ "accuracy_at_050": 0.26153846153846155,
52
+ "accuracy_at_075": 0.1076923076923077,
53
+ "average_confidence": 0.01601272412360861,
54
+ "average_predicted_box_area": 0.3009397933793923,
55
+ "average_ground_truth_box_area": 0.261754360781887
56
+ },
57
+ "baseball-diamond": {
58
+ "samples": 712,
59
+ "mean_iou": 0.42733569959520457,
60
+ "median_iou": 0.33201999962329865,
61
+ "accuracy_at_025": 0.523876404494382,
62
+ "accuracy_at_050": 0.4592696629213483,
63
+ "accuracy_at_075": 0.37359550561797755,
64
+ "average_confidence": 0.026822201530919985,
65
+ "average_predicted_box_area": 0.12179664975362327,
66
+ "average_ground_truth_box_area": 0.0992990173156644
67
+ },
68
+ "basketball-court": {
69
+ "samples": 345,
70
+ "mean_iou": 0.34086754165532446,
71
+ "median_iou": 0.2325267195701599,
72
+ "accuracy_at_025": 0.48405797101449277,
73
+ "accuracy_at_050": 0.30144927536231886,
74
+ "accuracy_at_075": 0.24347826086956523,
75
+ "average_confidence": 0.023409667258839244,
76
+ "average_predicted_box_area": 0.18712133020997737,
77
+ "average_ground_truth_box_area": 0.09824289885025633
78
+ },
79
+ "bridge": {
80
+ "samples": 842,
81
+ "mean_iou": 0.08984673703459375,
82
+ "median_iou": 0.0,
83
+ "accuracy_at_025": 0.13539192399049882,
84
+ "accuracy_at_050": 0.07957244655581948,
85
+ "accuracy_at_075": 0.027315914489311165,
86
+ "average_confidence": 0.013355846396777912,
87
+ "average_predicted_box_area": 0.2468838420096196,
88
+ "average_ground_truth_box_area": 0.06925985712909455
89
+ },
90
+ "chimney": {
91
+ "samples": 170,
92
+ "mean_iou": 0.312518068401636,
93
+ "median_iou": 0.20457249879837036,
94
+ "accuracy_at_025": 0.4470588235294118,
95
+ "accuracy_at_050": 0.2823529411764706,
96
+ "accuracy_at_075": 0.2,
97
+ "average_confidence": 0.02287785421289942,
98
+ "average_predicted_box_area": 0.13555735370199032,
99
+ "average_ground_truth_box_area": 0.21658411786124548
100
+ },
101
+ "container-crane": {
102
+ "samples": 12,
103
+ "mean_iou": 0.05488635729610299,
104
+ "median_iou": 0.0,
105
+ "accuracy_at_025": 0.08333333333333333,
106
+ "accuracy_at_050": 0.08333333333333333,
107
+ "accuracy_at_075": 0.0,
108
+ "average_confidence": 0.02736458523819844,
109
+ "average_predicted_box_area": 0.02312685774328808,
110
+ "average_ground_truth_box_area": 0.020058332942426205
111
+ },
112
+ "dam": {
113
+ "samples": 146,
114
+ "mean_iou": 0.30230051299002125,
115
+ "median_iou": 0.17744417488574982,
116
+ "accuracy_at_025": 0.4520547945205479,
117
+ "accuracy_at_050": 0.2808219178082192,
118
+ "accuracy_at_075": 0.14383561643835616,
119
+ "average_confidence": 0.013906163364419178,
120
+ "average_predicted_box_area": 0.23309909771272294,
121
+ "average_ground_truth_box_area": 0.21097260373261795
122
+ },
123
+ "expressway-service-area": {
124
+ "samples": 234,
125
+ "mean_iou": 0.28987817760580814,
126
+ "median_iou": 0.09838071465492249,
127
+ "accuracy_at_025": 0.3888888888888889,
128
+ "accuracy_at_050": 0.2692307692307692,
129
+ "accuracy_at_075": 0.18803418803418803,
130
+ "average_confidence": 0.01726636887153881,
131
+ "average_predicted_box_area": 0.1819596702221017,
132
+ "average_ground_truth_box_area": 0.34976922907134217
133
+ },
134
+ "expressway-toll-station": {
135
+ "samples": 170,
136
+ "mean_iou": 0.32300687543705436,
137
+ "median_iou": 0.08204669877886772,
138
+ "accuracy_at_025": 0.40588235294117647,
139
+ "accuracy_at_050": 0.3764705882352941,
140
+ "accuracy_at_075": 0.24705882352941178,
141
+ "average_confidence": 0.017145012056126313,
142
+ "average_predicted_box_area": 0.19531105996712167,
143
+ "average_ground_truth_box_area": 0.04483176540234126
144
+ },
145
+ "golffield": {
146
+ "samples": 121,
147
+ "mean_iou": 0.2192738639721878,
148
+ "median_iou": 0.02965187281370163,
149
+ "accuracy_at_025": 0.2892561983471074,
150
+ "accuracy_at_050": 0.19834710743801653,
151
+ "accuracy_at_075": 0.12396694214876033,
152
+ "average_confidence": 0.017121939023202363,
153
+ "average_predicted_box_area": 0.19735577314743802,
154
+ "average_ground_truth_box_area": 0.3817371927386473
155
+ },
156
+ "ground-track-field": {
157
+ "samples": 446,
158
+ "mean_iou": 0.387990548667073,
159
+ "median_iou": 0.16819574683904648,
160
+ "accuracy_at_025": 0.49551569506726456,
161
+ "accuracy_at_050": 0.4349775784753363,
162
+ "accuracy_at_075": 0.31614349775784756,
163
+ "average_confidence": 0.01861189407998103,
164
+ "average_predicted_box_area": 0.2590268112258618,
165
+ "average_ground_truth_box_area": 0.18185246652937098
166
+ },
167
+ "harbor": {
168
+ "samples": 1089,
169
+ "mean_iou": 0.13102694278629914,
170
+ "median_iou": 0.0,
171
+ "accuracy_at_025": 0.18365472910927455,
172
+ "accuracy_at_050": 0.13314967860422405,
173
+ "accuracy_at_075": 0.06244260789715335,
174
+ "average_confidence": 0.020545302757683754,
175
+ "average_predicted_box_area": 0.08653664571868891,
176
+ "average_ground_truth_box_area": 0.08334077103624694
177
+ },
178
+ "helicopter": {
179
+ "samples": 56,
180
+ "mean_iou": 0.34682301378675867,
181
+ "median_iou": 0.4261343777179718,
182
+ "accuracy_at_025": 0.5892857142857143,
183
+ "accuracy_at_050": 0.42857142857142855,
184
+ "accuracy_at_075": 0.08928571428571429,
185
+ "average_confidence": 0.030129729079947407,
186
+ "average_predicted_box_area": 0.056593962797446044,
187
+ "average_ground_truth_box_area": 0.0760125004890142
188
+ },
189
+ "helipad": {
190
+ "samples": 1,
191
+ "mean_iou": 0.9450750946998596,
192
+ "median_iou": 0.9450750946998596,
193
+ "accuracy_at_025": 1.0,
194
+ "accuracy_at_050": 1.0,
195
+ "accuracy_at_075": 1.0,
196
+ "average_confidence": 0.028649896383285522,
197
+ "average_predicted_box_area": 0.02542923204600811,
198
+ "average_ground_truth_box_area": 0.02550000324845314
199
+ },
200
+ "overpass": {
201
+ "samples": 419,
202
+ "mean_iou": 0.2212844229557733,
203
+ "median_iou": 0.049665417522192,
204
+ "accuracy_at_025": 0.36515513126491644,
205
+ "accuracy_at_050": 0.20047732696897375,
206
+ "accuracy_at_075": 0.057279236276849645,
207
+ "average_confidence": 0.01520532596331792,
208
+ "average_predicted_box_area": 0.2884094356464751,
209
+ "average_ground_truth_box_area": 0.16339188615663275
210
+ },
211
+ "roundabout": {
212
+ "samples": 195,
213
+ "mean_iou": 0.1751746525737242,
214
+ "median_iou": 0.0,
215
+ "accuracy_at_025": 0.24615384615384617,
216
+ "accuracy_at_050": 0.2153846153846154,
217
+ "accuracy_at_075": 0.12307692307692308,
218
+ "average_confidence": 0.020347264136832494,
219
+ "average_predicted_box_area": 0.1028806919294696,
220
+ "average_ground_truth_box_area": 0.013191794797193068
221
+ },
222
+ "ship": {
223
+ "samples": 1687,
224
+ "mean_iou": 0.2935679919757769,
225
+ "median_iou": 0.03491714224219322,
226
+ "accuracy_at_025": 0.3971547125074096,
227
+ "accuracy_at_050": 0.3254297569650267,
228
+ "accuracy_at_075": 0.20569057498518079,
229
+ "average_confidence": 0.031152534243116894,
230
+ "average_predicted_box_area": 0.07624637726825804,
231
+ "average_ground_truth_box_area": 0.04625328988895134
232
+ },
233
+ "soccer-ball-field": {
234
+ "samples": 148,
235
+ "mean_iou": 0.22712934121876527,
236
+ "median_iou": 0.014034277759492397,
237
+ "accuracy_at_025": 0.34459459459459457,
238
+ "accuracy_at_050": 0.21621621621621623,
239
+ "accuracy_at_075": 0.13513513513513514,
240
+ "average_confidence": 0.019322898518923368,
241
+ "average_predicted_box_area": 0.1425413428815601,
242
+ "average_ground_truth_box_area": 0.17779662140457878
243
+ },
244
+ "stadium": {
245
+ "samples": 248,
246
+ "mean_iou": 0.5795737827617314,
247
+ "median_iou": 0.6175024211406708,
248
+ "accuracy_at_025": 0.7862903225806451,
249
+ "accuracy_at_050": 0.592741935483871,
250
+ "accuracy_at_075": 0.4314516129032258,
251
+ "average_confidence": 0.028954924223193478,
252
+ "average_predicted_box_area": 0.17039768686968712,
253
+ "average_ground_truth_box_area": 0.2661592762752046
254
+ },
255
+ "storage-tank": {
256
+ "samples": 765,
257
+ "mean_iou": 0.2619862561070001,
258
+ "median_iou": 0.0,
259
+ "accuracy_at_025": 0.3254901960784314,
260
+ "accuracy_at_050": 0.3084967320261438,
261
+ "accuracy_at_075": 0.2326797385620915,
262
+ "average_confidence": 0.029307614662532323,
263
+ "average_predicted_box_area": 0.06816578596758845,
264
+ "average_ground_truth_box_area": 0.04120130704377635
265
+ },
266
+ "swimming-pool": {
267
+ "samples": 269,
268
+ "mean_iou": 0.16948257309737785,
269
+ "median_iou": 0.0,
270
+ "accuracy_at_025": 0.241635687732342,
271
+ "accuracy_at_050": 0.21189591078066913,
272
+ "accuracy_at_075": 0.08550185873605948,
273
+ "average_confidence": 0.024318190731218978,
274
+ "average_predicted_box_area": 0.046836348929408064,
275
+ "average_ground_truth_box_area": 0.007615613100902466
276
+ },
277
+ "tennis-court": {
278
+ "samples": 1132,
279
+ "mean_iou": 0.1472395561079025,
280
+ "median_iou": 0.10357014089822769,
281
+ "accuracy_at_025": 0.16166077738515902,
282
+ "accuracy_at_050": 0.05565371024734982,
283
+ "accuracy_at_075": 0.044169611307420496,
284
+ "average_confidence": 0.0199406504278917,
285
+ "average_predicted_box_area": 0.2845098280493647,
286
+ "average_ground_truth_box_area": 0.07138118404292834
287
+ },
288
+ "trainstation": {
289
+ "samples": 216,
290
+ "mean_iou": 0.24465397653586007,
291
+ "median_iou": 0.09666387736797333,
292
+ "accuracy_at_025": 0.37037037037037035,
293
+ "accuracy_at_050": 0.21296296296296297,
294
+ "accuracy_at_075": 0.10185185185185185,
295
+ "average_confidence": 0.0178874749237568,
296
+ "average_predicted_box_area": 0.15698605154142975,
297
+ "average_ground_truth_box_area": 0.13693426099295417
298
+ },
299
+ "vehicle": {
300
+ "samples": 4538,
301
+ "mean_iou": 0.1765532892185647,
302
+ "median_iou": 0.0,
303
+ "accuracy_at_025": 0.2626707800793301,
304
+ "accuracy_at_050": 0.22058175407668576,
305
+ "accuracy_at_075": 0.08461877479065667,
306
+ "average_confidence": 0.036800941344536924,
307
+ "average_predicted_box_area": 0.02330136883764677,
308
+ "average_ground_truth_box_area": 0.006635698607539586
309
+ },
310
+ "windmill": {
311
+ "samples": 529,
312
+ "mean_iou": 0.12284335871830068,
313
+ "median_iou": 0.025742182508111,
314
+ "accuracy_at_025": 0.21172022684310018,
315
+ "accuracy_at_050": 0.04158790170132325,
316
+ "accuracy_at_075": 0.00945179584120983,
317
+ "average_confidence": 0.029422531629752346,
318
+ "average_predicted_box_area": 0.046007696557209064,
319
+ "average_ground_truth_box_area": 0.013714744964420742
320
+ }
321
+ },
322
+ "clipped_vs_unclipped": {
323
+ "clipped": {
324
+ "samples": 4398,
325
+ "mean_iou": 0.2973502303371232,
326
+ "median_iou": 0.08430524542927742,
327
+ "accuracy_at_025": 0.4047294224647567,
328
+ "accuracy_at_050": 0.29763528876762163,
329
+ "accuracy_at_075": 0.18917689859026832,
330
+ "average_confidence": 0.022049783585760818,
331
+ "average_predicted_box_area": 0.17824670297269407,
332
+ "average_ground_truth_box_area": 0.1688265579334311
333
+ },
334
+ "unclipped": {
335
+ "samples": 11748,
336
+ "mean_iou": 0.21136039946243132,
337
+ "median_iou": 0.0,
338
+ "accuracy_at_025": 0.2949438202247191,
339
+ "accuracy_at_050": 0.23289070480081717,
340
+ "accuracy_at_075": 0.12631937351038475,
341
+ "average_confidence": 0.02921950868200885,
342
+ "average_predicted_box_area": 0.08788969593340752,
343
+ "average_ground_truth_box_area": 0.03718475490465769
344
+ }
345
+ },
346
+ "query_analysis": {
347
+ "unique_queries_used": 796,
348
+ "top_1_query_usage": 0.1013873405177753,
349
+ "top_5_query_coverage": 0.28130806391675955,
350
+ "top_10_query_coverage": 0.38127090301003347,
351
+ "collapse_detected": false,
352
+ "most_frequent_queries": [
353
+ {
354
+ "query_index": 0,
355
+ "count": 1637,
356
+ "coverage": 0.1013873405177753
357
+ },
358
+ {
359
+ "query_index": 1,
360
+ "count": 1096,
361
+ "coverage": 0.06788058961972006
362
+ },
363
+ {
364
+ "query_index": 2,
365
+ "count": 780,
366
+ "coverage": 0.04830917874396135
367
+ },
368
+ {
369
+ "query_index": 3,
370
+ "count": 546,
371
+ "coverage": 0.033816425120772944
372
+ },
373
+ {
374
+ "query_index": 4,
375
+ "count": 483,
376
+ "coverage": 0.029914529914529916
377
+ },
378
+ {
379
+ "query_index": 6,
380
+ "count": 371,
381
+ "coverage": 0.022977827325653413
382
+ },
383
+ {
384
+ "query_index": 5,
385
+ "count": 361,
386
+ "coverage": 0.02235847888021801
387
+ },
388
+ {
389
+ "query_index": 7,
390
+ "count": 341,
391
+ "coverage": 0.021119781989347206
392
+ },
393
+ {
394
+ "query_index": 8,
395
+ "count": 288,
396
+ "coverage": 0.017837235228539576
397
+ },
398
+ {
399
+ "query_index": 9,
400
+ "count": 253,
401
+ "coverage": 0.01566951566951567
402
+ },
403
+ {
404
+ "query_index": 10,
405
+ "count": 224,
406
+ "coverage": 0.013873405177753003
407
+ },
408
+ {
409
+ "query_index": 11,
410
+ "count": 220,
411
+ "coverage": 0.013625665799578843
412
+ },
413
+ {
414
+ "query_index": 14,
415
+ "count": 219,
416
+ "coverage": 0.013563730955035302
417
+ },
418
+ {
419
+ "query_index": 12,
420
+ "count": 218,
421
+ "coverage": 0.013501796110491763
422
+ },
423
+ {
424
+ "query_index": 13,
425
+ "count": 216,
426
+ "coverage": 0.013377926421404682
427
+ },
428
+ {
429
+ "query_index": 15,
430
+ "count": 196,
431
+ "coverage": 0.012139229530533879
432
+ },
433
+ {
434
+ "query_index": 16,
435
+ "count": 182,
436
+ "coverage": 0.011272141706924315
437
+ },
438
+ {
439
+ "query_index": 17,
440
+ "count": 162,
441
+ "coverage": 0.010033444816053512
442
+ },
443
+ {
444
+ "query_index": 19,
445
+ "count": 158,
446
+ "coverage": 0.009785705437879351
447
+ },
448
+ {
449
+ "query_index": 22,
450
+ "count": 146,
451
+ "coverage": 0.00904248730335687
452
+ },
453
+ {
454
+ "query_index": 25,
455
+ "count": 140,
456
+ "coverage": 0.008670878236095627
457
+ },
458
+ {
459
+ "query_index": 18,
460
+ "count": 136,
461
+ "coverage": 0.008423138857921467
462
+ },
463
+ {
464
+ "query_index": 20,
465
+ "count": 130,
466
+ "coverage": 0.008051529790660225
467
+ },
468
+ {
469
+ "query_index": 24,
470
+ "count": 129,
471
+ "coverage": 0.007989594946116686
472
+ },
473
+ {
474
+ "query_index": 23,
475
+ "count": 127,
476
+ "coverage": 0.007865725257029605
477
+ }
478
+ ]
479
+ },
480
+ "geometry_analysis": {
481
+ "average_predicted_box_area": 0.11250199105038895,
482
+ "average_ground_truth_box_area": 0.0730425927419267,
483
+ "median_area_ratio": 1.1552188779221426,
484
+ "oversized_prediction_rate": 0.3325281803542673,
485
+ "undersized_prediction_rate": 0.18165489904620338
486
+ },
487
+ "best_classes_at_050": [
488
+ {
489
+ "class": "helipad",
490
+ "samples": 1,
491
+ "mean_iou": 0.9450750946998596,
492
+ "median_iou": 0.9450750946998596,
493
+ "accuracy_at_025": 1.0,
494
+ "accuracy_at_050": 1.0,
495
+ "accuracy_at_075": 1.0,
496
+ "average_confidence": 0.028649896383285522,
497
+ "average_predicted_box_area": 0.02542923204600811,
498
+ "average_ground_truth_box_area": 0.02550000324845314
499
+ },
500
+ {
501
+ "class": "stadium",
502
+ "samples": 248,
503
+ "mean_iou": 0.5795737827617314,
504
+ "median_iou": 0.6175024211406708,
505
+ "accuracy_at_025": 0.7862903225806451,
506
+ "accuracy_at_050": 0.592741935483871,
507
+ "accuracy_at_075": 0.4314516129032258,
508
+ "average_confidence": 0.028954924223193478,
509
+ "average_predicted_box_area": 0.17039768686968712,
510
+ "average_ground_truth_box_area": 0.2661592762752046
511
+ },
512
+ {
513
+ "class": "baseball-diamond",
514
+ "samples": 712,
515
+ "mean_iou": 0.42733569959520457,
516
+ "median_iou": 0.33201999962329865,
517
+ "accuracy_at_025": 0.523876404494382,
518
+ "accuracy_at_050": 0.4592696629213483,
519
+ "accuracy_at_075": 0.37359550561797755,
520
+ "average_confidence": 0.026822201530919985,
521
+ "average_predicted_box_area": 0.12179664975362327,
522
+ "average_ground_truth_box_area": 0.0992990173156644
523
+ },
524
+ {
525
+ "class": "ground-track-field",
526
+ "samples": 446,
527
+ "mean_iou": 0.387990548667073,
528
+ "median_iou": 0.16819574683904648,
529
+ "accuracy_at_025": 0.49551569506726456,
530
+ "accuracy_at_050": 0.4349775784753363,
531
+ "accuracy_at_075": 0.31614349775784756,
532
+ "average_confidence": 0.01861189407998103,
533
+ "average_predicted_box_area": 0.2590268112258618,
534
+ "average_ground_truth_box_area": 0.18185246652937098
535
+ },
536
+ {
537
+ "class": "helicopter",
538
+ "samples": 56,
539
+ "mean_iou": 0.34682301378675867,
540
+ "median_iou": 0.4261343777179718,
541
+ "accuracy_at_025": 0.5892857142857143,
542
+ "accuracy_at_050": 0.42857142857142855,
543
+ "accuracy_at_075": 0.08928571428571429,
544
+ "average_confidence": 0.030129729079947407,
545
+ "average_predicted_box_area": 0.056593962797446044,
546
+ "average_ground_truth_box_area": 0.0760125004890142
547
+ }
548
+ ],
549
+ "worst_classes_at_050": [
550
+ {
551
+ "class": "windmill",
552
+ "samples": 529,
553
+ "mean_iou": 0.12284335871830068,
554
+ "median_iou": 0.025742182508111,
555
+ "accuracy_at_025": 0.21172022684310018,
556
+ "accuracy_at_050": 0.04158790170132325,
557
+ "accuracy_at_075": 0.00945179584120983,
558
+ "average_confidence": 0.029422531629752346,
559
+ "average_predicted_box_area": 0.046007696557209064,
560
+ "average_ground_truth_box_area": 0.013714744964420742
561
+ },
562
+ {
563
+ "class": "tennis-court",
564
+ "samples": 1132,
565
+ "mean_iou": 0.1472395561079025,
566
+ "median_iou": 0.10357014089822769,
567
+ "accuracy_at_025": 0.16166077738515902,
568
+ "accuracy_at_050": 0.05565371024734982,
569
+ "accuracy_at_075": 0.044169611307420496,
570
+ "average_confidence": 0.0199406504278917,
571
+ "average_predicted_box_area": 0.2845098280493647,
572
+ "average_ground_truth_box_area": 0.07138118404292834
573
+ },
574
+ {
575
+ "class": "bridge",
576
+ "samples": 842,
577
+ "mean_iou": 0.08984673703459375,
578
+ "median_iou": 0.0,
579
+ "accuracy_at_025": 0.13539192399049882,
580
+ "accuracy_at_050": 0.07957244655581948,
581
+ "accuracy_at_075": 0.027315914489311165,
582
+ "average_confidence": 0.013355846396777912,
583
+ "average_predicted_box_area": 0.2468838420096196,
584
+ "average_ground_truth_box_area": 0.06925985712909455
585
+ },
586
+ {
587
+ "class": "container-crane",
588
+ "samples": 12,
589
+ "mean_iou": 0.05488635729610299,
590
+ "median_iou": 0.0,
591
+ "accuracy_at_025": 0.08333333333333333,
592
+ "accuracy_at_050": 0.08333333333333333,
593
+ "accuracy_at_075": 0.0,
594
+ "average_confidence": 0.02736458523819844,
595
+ "average_predicted_box_area": 0.02312685774328808,
596
+ "average_ground_truth_box_area": 0.020058332942426205
597
+ },
598
+ {
599
+ "class": "harbor",
600
+ "samples": 1089,
601
+ "mean_iou": 0.13102694278629914,
602
+ "median_iou": 0.0,
603
+ "accuracy_at_025": 0.18365472910927455,
604
+ "accuracy_at_050": 0.13314967860422405,
605
+ "accuracy_at_075": 0.06244260789715335,
606
+ "average_confidence": 0.020545302757683754,
607
+ "average_predicted_box_area": 0.08653664571868891,
608
+ "average_ground_truth_box_area": 0.08334077103624694
609
+ }
610
+ ]
611
+ }
models/rsvqa_specialist_v1/integration_contract.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "registry_name": "rsvqa_vqa_specialist",
3
+ "display_name": "SatQuery RSVQA Specialist v1",
4
+ "supported_question_types": [
5
+ "presence",
6
+ "comp",
7
+ "rural_urban",
8
+ "count"
9
+ ],
10
+ "input": {
11
+ "image_tensor_shape": [
12
+ "batch",
13
+ 3,
14
+ 224,
15
+ 224
16
+ ],
17
+ "question_token_shape": [
18
+ "batch",
19
+ 77
20
+ ],
21
+ "task_id_mapping": {
22
+ "presence": 0,
23
+ "comp": 1,
24
+ "rural_urban": 2,
25
+ "count": 3
26
+ }
27
+ },
28
+ "output": {
29
+ "answer": "yes, no, rural, urban, integer string, 201+, or null",
30
+ "confidence": "maximum task-head softmax score",
31
+ "task": "presence, comp, rural_urban, or count",
32
+ "model_used": "SatQuery RSVQA Specialist v1"
33
+ },
34
+ "routing_priority": {
35
+ "single_image_rsvqa_style_vqa": "primary",
36
+ "captioner": "supporting evidence",
37
+ "satquery_vision_encoder": "supporting evidence",
38
+ "grounding_dino": "optional visual evidence only; not the source of benchmark count answers"
39
+ }
40
+ }
models/rsvqa_specialist_v1/model_card.json ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "SatQuery RSVQA Specialist v1",
3
+ "version": "1.0.0",
4
+ "task": "Single-image remote-sensing visual question answering",
5
+ "intended_use": [
6
+ "RSVQA-LR-style presence questions",
7
+ "RSVQA-LR-style comparison questions",
8
+ "RSVQA-LR rural-versus-urban classification",
9
+ "RSVQA-LR count-answer classification",
10
+ "SatQuery AI single-image VQA routing"
11
+ ],
12
+ "architecture": {
13
+ "vision_language_backbone": "OpenCLIP ViT-L-14",
14
+ "pretrained_weights": "laion2b_s32b_b82k",
15
+ "remote_sensing_adapter": "SatQuery Vision Encoder v1",
16
+ "backbone_state": "frozen during specialist training",
17
+ "fusion": "projected image and text features, elementwise product, and absolute difference",
18
+ "task_heads": {
19
+ "presence": 2,
20
+ "comparison": 2,
21
+ "rural_urban": 2,
22
+ "count": 202
23
+ },
24
+ "trainable_parameters": 4297936,
25
+ "question_context_length": 77
26
+ },
27
+ "training_data": {
28
+ "dataset": "RSVQA-LR official training split",
29
+ "training_questions": 57223,
30
+ "training_images": 572,
31
+ "validation_questions": 10005,
32
+ "validation_images": 100
33
+ },
34
+ "training_configuration": {
35
+ "epochs": 8,
36
+ "batch_size": 128,
37
+ "optimizer": "AdamW",
38
+ "initial_learning_rate": 0.0002,
39
+ "minimum_learning_rate": 1e-05,
40
+ "weight_decay": 0.0001,
41
+ "precision": "BF16",
42
+ "balanced_task_sampling": true,
43
+ "gradient_clipping": 1.0
44
+ },
45
+ "selected_checkpoint": {
46
+ "epoch": 8,
47
+ "reason": "Epoch-7 full checkpoints were corrupted during Google Drive writes. Epoch-8 specialist head was recovered and verified from the live in-memory model."
48
+ },
49
+ "validation_results": {
50
+ "overall_accuracy": 0.751024487756122,
51
+ "macro_accuracy": 0.7735176468969363,
52
+ "presence_accuracy": 0.9085303186022611,
53
+ "comparison_accuracy": 0.9099502487562189,
54
+ "rural_urban_accuracy": 0.9,
55
+ "count_accuracy": 0.375590020229265,
56
+ "validation_samples": 10005,
57
+ "best_observed_overall_accuracy": 0.7537231384307846,
58
+ "best_observed_macro_accuracy": 0.7756275001335271
59
+ },
60
+ "limitations": [
61
+ "Trained specifically on RSVQA-LR and may not generalize to unrelated VQA datasets.",
62
+ "Count accuracy is substantially lower than the other task families.",
63
+ "Counts are learned benchmark labels and are not guaranteed physical object inventories.",
64
+ "The 201+ label represents an overflow class rather than an exact count.",
65
+ "The model is intended for optical or rendered RGB imagery, not raw SAR.",
66
+ "Confidence scores are softmax values and are not calibrated probabilities.",
67
+ "The model does not produce spatial grounding or segmentation.",
68
+ "The model should not replace geospatial measurement or human analysis."
69
+ ],
70
+ "deployment_dependencies": {
71
+ "generic_backbone": "OpenCLIP ViT-L-14 laion2b_s32b_b82k",
72
+ "vision_adapter": "SatQuery Vision Encoder v1 adapter",
73
+ "specialist_checkpoint": "rsvqa_specialist_v1_head.pt",
74
+ "task_vocabulary": "task_answer_vocab.json"
75
+ }
76
+ }
models/rsvqa_specialist_v1/preprocessing.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "input_scope": {
3
+ "supported_modalities": [
4
+ "optical_rgb",
5
+ "multispectral_rendered_rgb"
6
+ ],
7
+ "unsupported_modalities": [
8
+ "raw_sar",
9
+ "single_band_sar",
10
+ "unrendered_multispectral_tensor"
11
+ ],
12
+ "supported_formats_after_ingestion": [
13
+ "PNG",
14
+ "JPEG",
15
+ "WEBP",
16
+ "TIFF",
17
+ "GeoTIFF"
18
+ ]
19
+ },
20
+ "image_preprocessing": {
21
+ "bands": "first three image bands interpreted as RGB",
22
+ "display_conversion": "per-band 2nd to 98th percentile stretch, clipped to [0,1], converted to uint8 RGB",
23
+ "openclip_transform": "OpenCLIP ViT-L-14 validation transform",
24
+ "input_size": [
25
+ 3,
26
+ 224,
27
+ 224
28
+ ]
29
+ },
30
+ "question_preprocessing": {
31
+ "tokenizer": "OpenCLIP ViT-L-14 tokenizer",
32
+ "context_length": 77,
33
+ "truncation": true
34
+ },
35
+ "answer_normalization": {
36
+ "presence": [
37
+ "no",
38
+ "yes"
39
+ ],
40
+ "comparison": [
41
+ "no",
42
+ "yes"
43
+ ],
44
+ "rural_urban": [
45
+ "rural",
46
+ "urban"
47
+ ],
48
+ "count": {
49
+ "exact_classes": "0 through 200",
50
+ "overflow_class": "201+"
51
+ }
52
+ }
53
+ }
models/rsvqa_specialist_v1/sha256.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "rsvqa_specialist_v1_head.pt": "71c0ab56ee650813bd495e8a3bc777353b6907a097af860e417f60523efe56ad",
3
+ "task_answer_vocab.json": "220543c5093cea514e1fb74e470f4d5e8d9dfe06bb83f63b3fa20b957b316d9d",
4
+ "preprocessing.json": "5e71e826a18962f665a70826e9986d1ed5a46c0c989ae7603eee6340754e84cf",
5
+ "model_card.json": "0d75f8e5f9b5c77c977eea91845356f344f101f379f4765971eeb726ec564f58",
6
+ "integration_contract.json": "d6bc9587118498f23876fffd4fd782444a61d3c3c1be4ce4ea0433199bcb224b",
7
+ "validation_metrics.json": "8c83efc28be12d749499ecfab84f689cb79c9da066903670bb6925755de47909",
8
+ "training_history.json": "c5151e89d3caa153aae66d748ffe51fe96fbb541fe4d222a1566479c70a7fb3d",
9
+ "validation_predictions.csv": "551c13b8c8dff3560bd41adeb9598d28946094337c3455c2f505a54d93bd7189"
10
+ }
models/rsvqa_specialist_v1/sha256.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ 71c0ab56ee650813bd495e8a3bc777353b6907a097af860e417f60523efe56ad rsvqa_specialist_v1_head.pt
2
+ 220543c5093cea514e1fb74e470f4d5e8d9dfe06bb83f63b3fa20b957b316d9d task_answer_vocab.json
3
+ 5e71e826a18962f665a70826e9986d1ed5a46c0c989ae7603eee6340754e84cf preprocessing.json
4
+ 0d75f8e5f9b5c77c977eea91845356f344f101f379f4765971eeb726ec564f58 model_card.json
5
+ d6bc9587118498f23876fffd4fd782444a61d3c3c1be4ce4ea0433199bcb224b integration_contract.json
6
+ 8c83efc28be12d749499ecfab84f689cb79c9da066903670bb6925755de47909 validation_metrics.json
7
+ c5151e89d3caa153aae66d748ffe51fe96fbb541fe4d222a1566479c70a7fb3d training_history.json
8
+ 551c13b8c8dff3560bd41adeb9598d28946094337c3455c2f505a54d93bd7189 validation_predictions.csv
models/rsvqa_specialist_v1/task_answer_vocab.json ADDED
@@ -0,0 +1,657 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "task_labels": {
3
+ "presence": [
4
+ "no",
5
+ "yes"
6
+ ],
7
+ "comp": [
8
+ "no",
9
+ "yes"
10
+ ],
11
+ "rural_urban": [
12
+ "rural",
13
+ "urban"
14
+ ],
15
+ "count": [
16
+ "0",
17
+ "1",
18
+ "2",
19
+ "3",
20
+ "4",
21
+ "5",
22
+ "6",
23
+ "7",
24
+ "8",
25
+ "9",
26
+ "10",
27
+ "11",
28
+ "12",
29
+ "13",
30
+ "14",
31
+ "15",
32
+ "16",
33
+ "17",
34
+ "18",
35
+ "19",
36
+ "20",
37
+ "21",
38
+ "22",
39
+ "23",
40
+ "24",
41
+ "25",
42
+ "26",
43
+ "27",
44
+ "28",
45
+ "29",
46
+ "30",
47
+ "31",
48
+ "32",
49
+ "33",
50
+ "34",
51
+ "35",
52
+ "36",
53
+ "37",
54
+ "38",
55
+ "39",
56
+ "40",
57
+ "41",
58
+ "42",
59
+ "43",
60
+ "44",
61
+ "45",
62
+ "46",
63
+ "47",
64
+ "48",
65
+ "49",
66
+ "50",
67
+ "51",
68
+ "52",
69
+ "53",
70
+ "54",
71
+ "55",
72
+ "56",
73
+ "57",
74
+ "58",
75
+ "59",
76
+ "60",
77
+ "61",
78
+ "62",
79
+ "63",
80
+ "64",
81
+ "65",
82
+ "66",
83
+ "67",
84
+ "68",
85
+ "69",
86
+ "70",
87
+ "71",
88
+ "72",
89
+ "73",
90
+ "74",
91
+ "75",
92
+ "76",
93
+ "77",
94
+ "78",
95
+ "79",
96
+ "80",
97
+ "81",
98
+ "82",
99
+ "83",
100
+ "84",
101
+ "85",
102
+ "86",
103
+ "87",
104
+ "88",
105
+ "89",
106
+ "90",
107
+ "91",
108
+ "92",
109
+ "93",
110
+ "94",
111
+ "95",
112
+ "96",
113
+ "97",
114
+ "98",
115
+ "99",
116
+ "100",
117
+ "101",
118
+ "102",
119
+ "103",
120
+ "104",
121
+ "105",
122
+ "106",
123
+ "107",
124
+ "108",
125
+ "109",
126
+ "110",
127
+ "111",
128
+ "112",
129
+ "113",
130
+ "114",
131
+ "115",
132
+ "116",
133
+ "117",
134
+ "118",
135
+ "119",
136
+ "120",
137
+ "121",
138
+ "122",
139
+ "123",
140
+ "124",
141
+ "125",
142
+ "126",
143
+ "127",
144
+ "128",
145
+ "129",
146
+ "130",
147
+ "131",
148
+ "132",
149
+ "133",
150
+ "134",
151
+ "135",
152
+ "136",
153
+ "137",
154
+ "138",
155
+ "139",
156
+ "140",
157
+ "141",
158
+ "142",
159
+ "143",
160
+ "144",
161
+ "145",
162
+ "146",
163
+ "147",
164
+ "148",
165
+ "149",
166
+ "150",
167
+ "151",
168
+ "152",
169
+ "153",
170
+ "154",
171
+ "155",
172
+ "156",
173
+ "157",
174
+ "158",
175
+ "159",
176
+ "160",
177
+ "161",
178
+ "162",
179
+ "163",
180
+ "164",
181
+ "165",
182
+ "166",
183
+ "167",
184
+ "168",
185
+ "169",
186
+ "170",
187
+ "171",
188
+ "172",
189
+ "173",
190
+ "174",
191
+ "175",
192
+ "176",
193
+ "177",
194
+ "178",
195
+ "179",
196
+ "180",
197
+ "181",
198
+ "182",
199
+ "183",
200
+ "184",
201
+ "185",
202
+ "186",
203
+ "187",
204
+ "188",
205
+ "189",
206
+ "190",
207
+ "191",
208
+ "192",
209
+ "193",
210
+ "194",
211
+ "195",
212
+ "196",
213
+ "197",
214
+ "198",
215
+ "199",
216
+ "200",
217
+ "201+"
218
+ ]
219
+ },
220
+ "answer_to_id": {
221
+ "presence": {
222
+ "no": 0,
223
+ "yes": 1
224
+ },
225
+ "comp": {
226
+ "no": 0,
227
+ "yes": 1
228
+ },
229
+ "rural_urban": {
230
+ "rural": 0,
231
+ "urban": 1
232
+ },
233
+ "count": {
234
+ "0": 0,
235
+ "1": 1,
236
+ "2": 2,
237
+ "3": 3,
238
+ "4": 4,
239
+ "5": 5,
240
+ "6": 6,
241
+ "7": 7,
242
+ "8": 8,
243
+ "9": 9,
244
+ "10": 10,
245
+ "11": 11,
246
+ "12": 12,
247
+ "13": 13,
248
+ "14": 14,
249
+ "15": 15,
250
+ "16": 16,
251
+ "17": 17,
252
+ "18": 18,
253
+ "19": 19,
254
+ "20": 20,
255
+ "21": 21,
256
+ "22": 22,
257
+ "23": 23,
258
+ "24": 24,
259
+ "25": 25,
260
+ "26": 26,
261
+ "27": 27,
262
+ "28": 28,
263
+ "29": 29,
264
+ "30": 30,
265
+ "31": 31,
266
+ "32": 32,
267
+ "33": 33,
268
+ "34": 34,
269
+ "35": 35,
270
+ "36": 36,
271
+ "37": 37,
272
+ "38": 38,
273
+ "39": 39,
274
+ "40": 40,
275
+ "41": 41,
276
+ "42": 42,
277
+ "43": 43,
278
+ "44": 44,
279
+ "45": 45,
280
+ "46": 46,
281
+ "47": 47,
282
+ "48": 48,
283
+ "49": 49,
284
+ "50": 50,
285
+ "51": 51,
286
+ "52": 52,
287
+ "53": 53,
288
+ "54": 54,
289
+ "55": 55,
290
+ "56": 56,
291
+ "57": 57,
292
+ "58": 58,
293
+ "59": 59,
294
+ "60": 60,
295
+ "61": 61,
296
+ "62": 62,
297
+ "63": 63,
298
+ "64": 64,
299
+ "65": 65,
300
+ "66": 66,
301
+ "67": 67,
302
+ "68": 68,
303
+ "69": 69,
304
+ "70": 70,
305
+ "71": 71,
306
+ "72": 72,
307
+ "73": 73,
308
+ "74": 74,
309
+ "75": 75,
310
+ "76": 76,
311
+ "77": 77,
312
+ "78": 78,
313
+ "79": 79,
314
+ "80": 80,
315
+ "81": 81,
316
+ "82": 82,
317
+ "83": 83,
318
+ "84": 84,
319
+ "85": 85,
320
+ "86": 86,
321
+ "87": 87,
322
+ "88": 88,
323
+ "89": 89,
324
+ "90": 90,
325
+ "91": 91,
326
+ "92": 92,
327
+ "93": 93,
328
+ "94": 94,
329
+ "95": 95,
330
+ "96": 96,
331
+ "97": 97,
332
+ "98": 98,
333
+ "99": 99,
334
+ "100": 100,
335
+ "101": 101,
336
+ "102": 102,
337
+ "103": 103,
338
+ "104": 104,
339
+ "105": 105,
340
+ "106": 106,
341
+ "107": 107,
342
+ "108": 108,
343
+ "109": 109,
344
+ "110": 110,
345
+ "111": 111,
346
+ "112": 112,
347
+ "113": 113,
348
+ "114": 114,
349
+ "115": 115,
350
+ "116": 116,
351
+ "117": 117,
352
+ "118": 118,
353
+ "119": 119,
354
+ "120": 120,
355
+ "121": 121,
356
+ "122": 122,
357
+ "123": 123,
358
+ "124": 124,
359
+ "125": 125,
360
+ "126": 126,
361
+ "127": 127,
362
+ "128": 128,
363
+ "129": 129,
364
+ "130": 130,
365
+ "131": 131,
366
+ "132": 132,
367
+ "133": 133,
368
+ "134": 134,
369
+ "135": 135,
370
+ "136": 136,
371
+ "137": 137,
372
+ "138": 138,
373
+ "139": 139,
374
+ "140": 140,
375
+ "141": 141,
376
+ "142": 142,
377
+ "143": 143,
378
+ "144": 144,
379
+ "145": 145,
380
+ "146": 146,
381
+ "147": 147,
382
+ "148": 148,
383
+ "149": 149,
384
+ "150": 150,
385
+ "151": 151,
386
+ "152": 152,
387
+ "153": 153,
388
+ "154": 154,
389
+ "155": 155,
390
+ "156": 156,
391
+ "157": 157,
392
+ "158": 158,
393
+ "159": 159,
394
+ "160": 160,
395
+ "161": 161,
396
+ "162": 162,
397
+ "163": 163,
398
+ "164": 164,
399
+ "165": 165,
400
+ "166": 166,
401
+ "167": 167,
402
+ "168": 168,
403
+ "169": 169,
404
+ "170": 170,
405
+ "171": 171,
406
+ "172": 172,
407
+ "173": 173,
408
+ "174": 174,
409
+ "175": 175,
410
+ "176": 176,
411
+ "177": 177,
412
+ "178": 178,
413
+ "179": 179,
414
+ "180": 180,
415
+ "181": 181,
416
+ "182": 182,
417
+ "183": 183,
418
+ "184": 184,
419
+ "185": 185,
420
+ "186": 186,
421
+ "187": 187,
422
+ "188": 188,
423
+ "189": 189,
424
+ "190": 190,
425
+ "191": 191,
426
+ "192": 192,
427
+ "193": 193,
428
+ "194": 194,
429
+ "195": 195,
430
+ "196": 196,
431
+ "197": 197,
432
+ "198": 198,
433
+ "199": 199,
434
+ "200": 200,
435
+ "201+": 201
436
+ }
437
+ },
438
+ "id_to_answer": {
439
+ "presence": {
440
+ "0": "no",
441
+ "1": "yes"
442
+ },
443
+ "comp": {
444
+ "0": "no",
445
+ "1": "yes"
446
+ },
447
+ "rural_urban": {
448
+ "0": "rural",
449
+ "1": "urban"
450
+ },
451
+ "count": {
452
+ "0": "0",
453
+ "1": "1",
454
+ "2": "2",
455
+ "3": "3",
456
+ "4": "4",
457
+ "5": "5",
458
+ "6": "6",
459
+ "7": "7",
460
+ "8": "8",
461
+ "9": "9",
462
+ "10": "10",
463
+ "11": "11",
464
+ "12": "12",
465
+ "13": "13",
466
+ "14": "14",
467
+ "15": "15",
468
+ "16": "16",
469
+ "17": "17",
470
+ "18": "18",
471
+ "19": "19",
472
+ "20": "20",
473
+ "21": "21",
474
+ "22": "22",
475
+ "23": "23",
476
+ "24": "24",
477
+ "25": "25",
478
+ "26": "26",
479
+ "27": "27",
480
+ "28": "28",
481
+ "29": "29",
482
+ "30": "30",
483
+ "31": "31",
484
+ "32": "32",
485
+ "33": "33",
486
+ "34": "34",
487
+ "35": "35",
488
+ "36": "36",
489
+ "37": "37",
490
+ "38": "38",
491
+ "39": "39",
492
+ "40": "40",
493
+ "41": "41",
494
+ "42": "42",
495
+ "43": "43",
496
+ "44": "44",
497
+ "45": "45",
498
+ "46": "46",
499
+ "47": "47",
500
+ "48": "48",
501
+ "49": "49",
502
+ "50": "50",
503
+ "51": "51",
504
+ "52": "52",
505
+ "53": "53",
506
+ "54": "54",
507
+ "55": "55",
508
+ "56": "56",
509
+ "57": "57",
510
+ "58": "58",
511
+ "59": "59",
512
+ "60": "60",
513
+ "61": "61",
514
+ "62": "62",
515
+ "63": "63",
516
+ "64": "64",
517
+ "65": "65",
518
+ "66": "66",
519
+ "67": "67",
520
+ "68": "68",
521
+ "69": "69",
522
+ "70": "70",
523
+ "71": "71",
524
+ "72": "72",
525
+ "73": "73",
526
+ "74": "74",
527
+ "75": "75",
528
+ "76": "76",
529
+ "77": "77",
530
+ "78": "78",
531
+ "79": "79",
532
+ "80": "80",
533
+ "81": "81",
534
+ "82": "82",
535
+ "83": "83",
536
+ "84": "84",
537
+ "85": "85",
538
+ "86": "86",
539
+ "87": "87",
540
+ "88": "88",
541
+ "89": "89",
542
+ "90": "90",
543
+ "91": "91",
544
+ "92": "92",
545
+ "93": "93",
546
+ "94": "94",
547
+ "95": "95",
548
+ "96": "96",
549
+ "97": "97",
550
+ "98": "98",
551
+ "99": "99",
552
+ "100": "100",
553
+ "101": "101",
554
+ "102": "102",
555
+ "103": "103",
556
+ "104": "104",
557
+ "105": "105",
558
+ "106": "106",
559
+ "107": "107",
560
+ "108": "108",
561
+ "109": "109",
562
+ "110": "110",
563
+ "111": "111",
564
+ "112": "112",
565
+ "113": "113",
566
+ "114": "114",
567
+ "115": "115",
568
+ "116": "116",
569
+ "117": "117",
570
+ "118": "118",
571
+ "119": "119",
572
+ "120": "120",
573
+ "121": "121",
574
+ "122": "122",
575
+ "123": "123",
576
+ "124": "124",
577
+ "125": "125",
578
+ "126": "126",
579
+ "127": "127",
580
+ "128": "128",
581
+ "129": "129",
582
+ "130": "130",
583
+ "131": "131",
584
+ "132": "132",
585
+ "133": "133",
586
+ "134": "134",
587
+ "135": "135",
588
+ "136": "136",
589
+ "137": "137",
590
+ "138": "138",
591
+ "139": "139",
592
+ "140": "140",
593
+ "141": "141",
594
+ "142": "142",
595
+ "143": "143",
596
+ "144": "144",
597
+ "145": "145",
598
+ "146": "146",
599
+ "147": "147",
600
+ "148": "148",
601
+ "149": "149",
602
+ "150": "150",
603
+ "151": "151",
604
+ "152": "152",
605
+ "153": "153",
606
+ "154": "154",
607
+ "155": "155",
608
+ "156": "156",
609
+ "157": "157",
610
+ "158": "158",
611
+ "159": "159",
612
+ "160": "160",
613
+ "161": "161",
614
+ "162": "162",
615
+ "163": "163",
616
+ "164": "164",
617
+ "165": "165",
618
+ "166": "166",
619
+ "167": "167",
620
+ "168": "168",
621
+ "169": "169",
622
+ "170": "170",
623
+ "171": "171",
624
+ "172": "172",
625
+ "173": "173",
626
+ "174": "174",
627
+ "175": "175",
628
+ "176": "176",
629
+ "177": "177",
630
+ "178": "178",
631
+ "179": "179",
632
+ "180": "180",
633
+ "181": "181",
634
+ "182": "182",
635
+ "183": "183",
636
+ "184": "184",
637
+ "185": "185",
638
+ "186": "186",
639
+ "187": "187",
640
+ "188": "188",
641
+ "189": "189",
642
+ "190": "190",
643
+ "191": "191",
644
+ "192": "192",
645
+ "193": "193",
646
+ "194": "194",
647
+ "195": "195",
648
+ "196": "196",
649
+ "197": "197",
650
+ "198": "198",
651
+ "199": "199",
652
+ "200": "200",
653
+ "201": "201+"
654
+ }
655
+ },
656
+ "count_overflow_threshold": 200
657
+ }
models/rsvqa_specialist_v1/training_history.json ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "epoch": 1,
4
+ "train_loss": 0.9040762519409726,
5
+ "train_task_loss": {
6
+ "presence": 0.24200891785040266,
7
+ "comp": 0.4735380026451427,
8
+ "rural_urban": 0.16482951582911565,
9
+ "count": 2.735928573597731
10
+ },
11
+ "validation": {
12
+ "overall_accuracy": 0.7096451774112944,
13
+ "macro_accuracy": 0.7416685793081097,
14
+ "per_task_accuracy": {
15
+ "presence": 0.9184652278177458,
16
+ "comp": 0.7945273631840796,
17
+ "rural_urban": 0.87,
18
+ "count": 0.38368172623061364
19
+ },
20
+ "per_task_loss": {
21
+ "presence": 0.19103567339479924,
22
+ "comp": 0.3943806283175945,
23
+ "rural_urban": 0.6170307386592657,
24
+ "count": 2.76060329079628
25
+ },
26
+ "samples": 10005
27
+ },
28
+ "seconds": 907.784505367279,
29
+ "learning_rate": 0.00019276855558857255
30
+ },
31
+ {
32
+ "epoch": 2,
33
+ "train_loss": 0.7770693339490784,
34
+ "train_task_loss": {
35
+ "presence": 0.2065310961081411,
36
+ "comp": 0.37312249642623885,
37
+ "rural_urban": 0.0422607656452785,
38
+ "count": 2.4863629821162894
39
+ },
40
+ "validation": {
41
+ "overall_accuracy": 0.7293353323338331,
42
+ "macro_accuracy": 0.7537389551988147,
43
+ "per_task_accuracy": {
44
+ "presence": 0.9174374785885577,
45
+ "comp": 0.8455223880597015,
46
+ "rural_urban": 0.87,
47
+ "count": 0.38199595414699933
48
+ },
49
+ "per_task_loss": {
50
+ "presence": 0.19188057761639357,
51
+ "comp": 0.315645045414567,
52
+ "rural_urban": 0.7340985408641129,
53
+ "count": 2.7683646082878113
54
+ },
55
+ "samples": 10005
56
+ },
57
+ "seconds": 836.6654961109161,
58
+ "learning_rate": 0.0001721751442127221
59
+ },
60
+ {
61
+ "epoch": 3,
62
+ "train_loss": 0.7081310226346555,
63
+ "train_task_loss": {
64
+ "presence": 0.18294498176882731,
65
+ "comp": 0.31299563397297125,
66
+ "rural_urban": 0.010043482891413756,
67
+ "count": 2.326539993286133
68
+ },
69
+ "validation": {
70
+ "overall_accuracy": 0.7386306846576711,
71
+ "macro_accuracy": 0.7660547278145375,
72
+ "per_task_accuracy": {
73
+ "presence": 0.9099006509078451,
74
+ "comp": 0.8763681592039801,
75
+ "rural_urban": 0.9,
76
+ "count": 0.377950101146325
77
+ },
78
+ "per_task_loss": {
79
+ "presence": 0.21662022899836303,
80
+ "comp": 0.2589996611699462,
81
+ "rural_urban": 0.5397858969932037,
82
+ "count": 2.7714633464813234
83
+ },
84
+ "samples": 10005
85
+ },
86
+ "seconds": 912.1458468437195,
87
+ "learning_rate": 0.0001413549260746838
88
+ },
89
+ {
90
+ "epoch": 4,
91
+ "train_loss": 0.665155304624997,
92
+ "train_task_loss": {
93
+ "presence": 0.16808538061152034,
94
+ "comp": 0.28150772880054425,
95
+ "rural_urban": 0.0024487690138741253,
96
+ "count": 2.208579342370599
97
+ },
98
+ "validation": {
99
+ "overall_accuracy": 0.7475262368815592,
100
+ "macro_accuracy": 0.7726662331272507,
101
+ "per_task_accuracy": {
102
+ "presence": 0.9194929770469339,
103
+ "comp": 0.8868159203980099,
104
+ "rural_urban": 0.9,
105
+ "count": 0.38435603506405935
106
+ },
107
+ "per_task_loss": {
108
+ "presence": 0.19547599479556083,
109
+ "comp": 0.24273387556895615,
110
+ "rural_urban": 0.4020405195311608,
111
+ "count": 2.750892424583435
112
+ },
113
+ "samples": 10005
114
+ },
115
+ "seconds": 915.7053153514862,
116
+ "learning_rate": 0.00010500000000000098
117
+ },
118
+ {
119
+ "epoch": 5,
120
+ "train_loss": 0.6276509310441796,
121
+ "train_task_loss": {
122
+ "presence": 0.1404477608842271,
123
+ "comp": 0.2525271267298884,
124
+ "rural_urban": 0.0010683072635888197,
125
+ "count": 2.116560530342512
126
+ },
127
+ "validation": {
128
+ "overall_accuracy": 0.7488255872063968,
129
+ "macro_accuracy": 0.7700509280682458,
130
+ "per_task_accuracy": {
131
+ "presence": 0.9160671462829736,
132
+ "comp": 0.9012437810945274,
133
+ "rural_urban": 0.89,
134
+ "count": 0.3728927848954821
135
+ },
136
+ "per_task_loss": {
137
+ "presence": 0.2274293196387589,
138
+ "comp": 0.2305498892441392,
139
+ "rural_urban": 0.5528060982225597,
140
+ "count": 2.7818245232105254
141
+ },
142
+ "samples": 10005
143
+ },
144
+ "seconds": 917.0492331981659,
145
+ "learning_rate": 6.864507392531715e-05
146
+ },
147
+ {
148
+ "epoch": 6,
149
+ "train_loss": 0.5894078906350488,
150
+ "train_task_loss": {
151
+ "presence": 0.1340527039258772,
152
+ "comp": 0.220110914392826,
153
+ "rural_urban": 0.00035132088400360373,
154
+ "count": 2.003116623400575
155
+ },
156
+ "validation": {
157
+ "overall_accuracy": 0.7477261369315342,
158
+ "macro_accuracy": 0.7688062167403873,
159
+ "per_task_accuracy": {
160
+ "presence": 0.9140116478245974,
161
+ "comp": 0.9047263681592039,
162
+ "rural_urban": 0.89,
163
+ "count": 0.3664868509777478
164
+ },
165
+ "per_task_loss": {
166
+ "presence": 0.2209703566506505,
167
+ "comp": 0.22379308473318815,
168
+ "rural_urban": 0.590618708482875,
169
+ "count": 2.8006011068820955
170
+ },
171
+ "samples": 10005
172
+ },
173
+ "seconds": 910.4166288375854,
174
+ "learning_rate": 3.782485578727853e-05
175
+ },
176
+ {
177
+ "epoch": 7,
178
+ "train_loss": 0.5566184824745127,
179
+ "train_task_loss": {
180
+ "presence": 0.11622604055192647,
181
+ "comp": 0.2070962954687592,
182
+ "rural_urban": 0.0002745905598248298,
183
+ "count": 1.9028770104884034
184
+ },
185
+ "validation": {
186
+ "overall_accuracy": 0.7537231384307846,
187
+ "macro_accuracy": 0.7756275001335271,
188
+ "per_task_accuracy": {
189
+ "presence": 0.9112709832134293,
190
+ "comp": 0.9119402985074627,
191
+ "rural_urban": 0.9,
192
+ "count": 0.3792987188132165
193
+ },
194
+ "per_task_loss": {
195
+ "presence": 0.23160626096650958,
196
+ "comp": 0.21087181204929947,
197
+ "rural_urban": 0.6776243234865211,
198
+ "count": 2.810155588388443
199
+ },
200
+ "samples": 10005
201
+ },
202
+ "seconds": 861.3801686763763,
203
+ "learning_rate": 1.7231444411428036e-05
204
+ },
205
+ {
206
+ "epoch": 8,
207
+ "train_loss": 0.5352830394802478,
208
+ "train_task_loss": {
209
+ "presence": 0.11673450028894665,
210
+ "comp": 0.19678494090035192,
211
+ "rural_urban": 0.00029948013635095464,
212
+ "count": 1.827313233141931
213
+ },
214
+ "validation": {
215
+ "overall_accuracy": 0.751024487756122,
216
+ "macro_accuracy": 0.7735176468969363,
217
+ "per_task_accuracy": {
218
+ "presence": 0.9085303186022611,
219
+ "comp": 0.9099502487562189,
220
+ "rural_urban": 0.9,
221
+ "count": 0.375590020229265
222
+ },
223
+ "per_task_loss": {
224
+ "presence": 0.23717375751584768,
225
+ "comp": 0.2084472465328872,
226
+ "rural_urban": 0.7192498920481574,
227
+ "count": 2.813879978656769
228
+ },
229
+ "samples": 10005
230
+ },
231
+ "seconds": 920.020387172699,
232
+ "learning_rate": 1e-05
233
+ }
234
+ ]
models/rsvqa_specialist_v1/validation_metrics.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "recovery_status": "recovered_from_in_memory_epoch_8",
3
+ "selected_epoch": 8,
4
+ "note": "Original Drive checkpoints were corrupted. The compact specialist checkpoint was recovered from the live epoch-8 model.",
5
+ "final_validation": {
6
+ "overall_accuracy": 0.751024487756122,
7
+ "macro_accuracy": 0.7735176468969363,
8
+ "per_task_accuracy": {
9
+ "presence": 0.9085303186022611,
10
+ "comp": 0.9099502487562189,
11
+ "rural_urban": 0.9,
12
+ "count": 0.375590020229265
13
+ },
14
+ "per_task_loss": {
15
+ "presence": 0.23717375751584768,
16
+ "comp": 0.2084472465328872,
17
+ "rural_urban": 0.7192498920481574,
18
+ "count": 2.813879978656769
19
+ },
20
+ "samples": 10005
21
+ },
22
+ "best_observed_epoch": 7,
23
+ "best_observed_macro_accuracy": 0.7756275001335271,
24
+ "best_observed_overall_accuracy": 0.7537231384307846,
25
+ "selected_checkpoint_macro_accuracy": 0.7735176468969363,
26
+ "selected_checkpoint_overall_accuracy": 0.751024487756122,
27
+ "epochs_completed": 8,
28
+ "total_training_seconds": 7181.1675815582275,
29
+ "peak_gpu_memory_gib": 5.155579566955566
30
+ }
models/rsvqa_specialist_v1/validation_predictions.csv ADDED
The diff for this file is too large to render. See raw diff
 
models/satquery_vision_encoder_v1/baseline_vs_adapted.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "generic_openclip": {
3
+ "loss": 4.8016743659973145,
4
+ "image_to_text_r1": 0.0021824531722813845,
5
+ "text_to_image_r1": 0.0008729812107048929,
6
+ "image_to_text_r5": 0.010039283894002438,
7
+ "text_to_image_r5": 0.004364906344562769,
8
+ "image_to_text_r10": 0.021388040855526924,
9
+ "text_to_image_r10": 0.00654735928401351
10
+ },
11
+ "satquery_vision_encoder_v1": {
12
+ "loss": 4.120570659637451,
13
+ "image_to_text_r1": 0.005674378015100956,
14
+ "text_to_image_r1": 0.006110868416726589,
15
+ "image_to_text_r5": 0.022697512060403824,
16
+ "text_to_image_r5": 0.03491925075650215,
17
+ "image_to_text_r10": 0.050632912665605545,
18
+ "text_to_image_r10": 0.05805325135588646
19
+ },
20
+ "difference": {
21
+ "loss": -0.6811037063598633,
22
+ "image_to_text_r1": 0.0034919248428195715,
23
+ "text_to_image_r1": 0.005237887206021696,
24
+ "image_to_text_r5": 0.012658228166401386,
25
+ "text_to_image_r5": 0.030554344411939383,
26
+ "image_to_text_r10": 0.02924487181007862,
27
+ "text_to_image_r10": 0.05150589207187295
28
+ }
29
+ }
models/satquery_vision_encoder_v1/model_card.json ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "SatQuery Vision Encoder v1",
3
+ "version": "1.0.0",
4
+ "type": "remote-sensing-adapted vision-language encoder",
5
+ "backbone": "OpenCLIP ViT-L-14",
6
+ "pretrained_weights": "laion2b_s32b_b82k",
7
+ "embedding_dimension": 768,
8
+ "adaptation_dataset": "BigEarthNet.txt",
9
+ "image_source": "BigEarthNet v2 Lithuania Summer",
10
+ "training_pairs": 4008,
11
+ "validation_pairs": 2291,
12
+ "test_pairs": 2053,
13
+ "input": {
14
+ "mode": "RGB",
15
+ "sentinel_2_bands": [
16
+ "B04",
17
+ "B03",
18
+ "B02"
19
+ ],
20
+ "input_size": [
21
+ 224,
22
+ 224
23
+ ]
24
+ },
25
+ "supported_uses": [
26
+ "Earth-observation image embeddings",
27
+ "image-text similarity",
28
+ "caption reranking",
29
+ "scene-prior evidence",
30
+ "retrieval",
31
+ "agent routing support"
32
+ ],
33
+ "unsupported_claims": [
34
+ "pixel-level segmentation",
35
+ "object grounding",
36
+ "calibrated probability",
37
+ "semantic change detection"
38
+ ],
39
+ "limitations": [
40
+ "Training subset is geographically limited to Lithuania",
41
+ "Training subset contains summer imagery only",
42
+ "Version 1 supports RGB imagery only",
43
+ "Retrieval metrics remain low in absolute terms",
44
+ "Outputs must not be treated as ground truth"
45
+ ],
46
+ "validation_metrics": {
47
+ "loss": 4.120570659637451,
48
+ "image_to_text_r1": 0.005674378015100956,
49
+ "text_to_image_r1": 0.006110868416726589,
50
+ "image_to_text_r5": 0.022697512060403824,
51
+ "text_to_image_r5": 0.03491925075650215,
52
+ "image_to_text_r10": 0.050632912665605545,
53
+ "text_to_image_r10": 0.05805325135588646
54
+ },
55
+ "generic_openclip_baseline": {
56
+ "loss": 4.8016743659973145,
57
+ "image_to_text_r1": 0.0021824531722813845,
58
+ "text_to_image_r1": 0.0008729812107048929,
59
+ "image_to_text_r5": 0.010039283894002438,
60
+ "text_to_image_r5": 0.004364906344562769,
61
+ "image_to_text_r10": 0.021388040855526924,
62
+ "text_to_image_r10": 0.00654735928401351
63
+ }
64
+ }