Spaces:
Running on Zero
Running on Zero
Commit ·
17aade5
1
Parent(s): b710eca
Enhance GPU processing and batching capabilities; update README for clarity on test-time augmentation and batch sizes
Browse files- README.md +2 -1
- app.py +45 -15
- infer/engine.py +167 -53
- infer/predict.py +7 -2
- models/tta.py +42 -0
- predict_image.py +2 -1
- tests/test_engine.py +95 -0
README.md
CHANGED
|
@@ -25,7 +25,8 @@ numbers. A georeferenced GeoTIFF carries its own resolution; leave the field at
|
|
| 25 |
its default to use that, or set it to override.
|
| 26 |
|
| 27 |
Optional **test-time augmentation** flip-averages the prediction. It is steadier
|
| 28 |
-
on noisy input
|
|
|
|
| 29 |
|
| 30 |
## What comes back
|
| 31 |
|
|
|
|
| 25 |
its default to use that, or set it to override.
|
| 26 |
|
| 27 |
Optional **test-time augmentation** flip-averages the prediction. It is steadier
|
| 28 |
+
on noisy input; all 8 views of each tile run in a single GPU batch, so it costs
|
| 29 |
+
8× the compute but far less than 8× the wall time on a large GPU.
|
| 30 |
|
| 31 |
## What comes back
|
| 32 |
|
app.py
CHANGED
|
@@ -348,8 +348,38 @@ def _safe_stem(image_path: str) -> str:
|
|
| 348 |
# So: only the forward pass is decorated, the durations are sized to it, and
|
| 349 |
# TTA (~4x the work) gets its own longer window instead of everyone paying for
|
| 350 |
# the worst case.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
_GPU_DURATION = 45
|
| 352 |
_GPU_DURATION_TTA = 120
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
|
| 354 |
|
| 355 |
def _run_model(rgb, gsd_m, tta: bool):
|
|
@@ -365,12 +395,12 @@ def _run_model(rgb, gsd_m, tta: bool):
|
|
| 365 |
else None
|
| 366 |
)
|
| 367 |
try:
|
| 368 |
-
# the class map rides along on the same forward pass (
|
| 369 |
-
#
|
| 370 |
height, seg = predict_scene(
|
| 371 |
model, rgb, gsd_m, spec, device,
|
| 372 |
-
tta=bool(tta), amp_dtype=amp_dtype, overlap=
|
| 373 |
-
want_seg=True,
|
| 374 |
)
|
| 375 |
finally:
|
| 376 |
# hand the card back clean; the next reservation is a fresh attach
|
|
@@ -380,8 +410,8 @@ def _run_model(rgb, gsd_m, tta: bool):
|
|
| 380 |
return height, seg.astype(np.uint8)
|
| 381 |
|
| 382 |
|
| 383 |
-
|
| 384 |
-
|
| 385 |
|
| 386 |
|
| 387 |
# Outputs of `predict`, in order — kept as a tuple factory so every return
|
|
@@ -405,11 +435,10 @@ def predict(image_path: str | None, gsd: float, tta: bool = False):
|
|
| 405 |
image_path,
|
| 406 |
user_gsd_m=float(gsd or 0),
|
| 407 |
assumed_gsd_m=spec.canonical_gsd_m,
|
| 408 |
-
max_side=
|
| 409 |
)
|
| 410 |
|
| 411 |
-
|
| 412 |
-
height, seg = runner(rgb, scene_meta.gsd_m, bool(tta))
|
| 413 |
|
| 414 |
height = _sanitise(height)
|
| 415 |
# Objects are an extra, never a reason to lose the height map: a failure
|
|
@@ -517,9 +546,9 @@ def predict(image_path: str | None, gsd: float, tta: bool = False):
|
|
| 517 |
# not a model failure: the caller's ZeroGPU allowance ran out
|
| 518 |
return _result(status=(
|
| 519 |
"Your ZeroGPU quota for today is used up. Sign in to Hugging "
|
| 520 |
-
"Face for a larger allowance, turn TTA off (it asks for
|
| 521 |
-
f"{_GPU_DURATION_TTA} s
|
| 522 |
-
"or retry after the quota resets."
|
| 523 |
))
|
| 524 |
return _result(status=f"Inference failed: {exc}")
|
| 525 |
|
|
@@ -569,9 +598,10 @@ with gr.Blocks(title="Single View Height Estimator", css=_CSS, js=_FORCE_DARK_JS
|
|
| 569 |
)
|
| 570 |
tta = gr.Checkbox(
|
| 571 |
value=False, label="Higher quality (slower)",
|
| 572 |
-
info=f"
|
| 573 |
-
f"
|
| 574 |
-
"
|
|
|
|
| 575 |
)
|
| 576 |
with gr.Row():
|
| 577 |
run = gr.Button("Estimate height", variant="primary")
|
|
|
|
| 348 |
# So: only the forward pass is decorated, the durations are sized to it, and
|
| 349 |
# TTA (~4x the work) gets its own longer window instead of everyone paying for
|
| 350 |
# the worst case.
|
| 351 |
+
#
|
| 352 |
+
# Those two are floors. A large scene is no longer shrunk to 1600 px — it is
|
| 353 |
+
# cut into 512 px windows at full resolution and batched through the GPU — so
|
| 354 |
+
# the window grows with the number of tiles (see `_gpu_duration`).
|
| 355 |
_GPU_DURATION = 45
|
| 356 |
_GPU_DURATION_TTA = 120
|
| 357 |
+
_GPU_DURATION_MAX = int(os.environ.get("DW_GPU_MAX_DURATION", "300"))
|
| 358 |
+
# Seconds of GPU per tile forward (8 of them per tile under TTA), padded well
|
| 359 |
+
# above what a batched ViT-L/512 pass costs on an H200 or an RTX Blackwell.
|
| 360 |
+
_GPU_SECONDS_PER_VIEW = 0.02
|
| 361 |
+
|
| 362 |
+
# Long side above which a scene is downsampled before inference. This used to
|
| 363 |
+
# be 1600, which threw away most of a large GeoTIFF's resolution; the tiler has
|
| 364 |
+
# no size limit of its own, so the cap is now only a host-memory guard. It
|
| 365 |
+
# matches the frontend's in-browser GeoTIFF decode limit.
|
| 366 |
+
_MAX_SIDE = int(os.environ.get("DW_MAX_SIDE", "8192"))
|
| 367 |
+
# Tiles per forward pass; 0 sizes it from free GPU memory.
|
| 368 |
+
_TILE_BATCH = int(os.environ.get("DW_TILE_BATCH", "0"))
|
| 369 |
+
_OVERLAP = 0.5
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def _gpu_duration(rgb, gsd_m, tta: bool) -> int:
|
| 373 |
+
"""ZeroGPU window for this scene, sized to its tile count."""
|
| 374 |
+
from infer.engine import count_tiles
|
| 375 |
+
from models.tta import n_views
|
| 376 |
+
|
| 377 |
+
floor = _GPU_DURATION_TTA if tta else _GPU_DURATION
|
| 378 |
+
if MODEL_SPEC is None:
|
| 379 |
+
return floor
|
| 380 |
+
tiles = count_tiles(rgb.shape[0], rgb.shape[1], gsd_m, MODEL_SPEC, _OVERLAP)
|
| 381 |
+
need = 20 + tiles * (n_views() if tta else 1) * _GPU_SECONDS_PER_VIEW
|
| 382 |
+
return int(min(_GPU_DURATION_MAX, max(floor, need)))
|
| 383 |
|
| 384 |
|
| 385 |
def _run_model(rgb, gsd_m, tta: bool):
|
|
|
|
| 395 |
else None
|
| 396 |
)
|
| 397 |
try:
|
| 398 |
+
# the class map rides along on the same forward pass (under TTA it is
|
| 399 |
+
# read off the identity view, so it costs no extra pass either)
|
| 400 |
height, seg = predict_scene(
|
| 401 |
model, rgb, gsd_m, spec, device,
|
| 402 |
+
tta=bool(tta), amp_dtype=amp_dtype, overlap=_OVERLAP,
|
| 403 |
+
batch_tiles=_TILE_BATCH, want_seg=True,
|
| 404 |
)
|
| 405 |
finally:
|
| 406 |
# hand the card back clean; the next reservation is a fresh attach
|
|
|
|
| 410 |
return height, seg.astype(np.uint8)
|
| 411 |
|
| 412 |
|
| 413 |
+
# `duration` may be a callable taking the same arguments as the function
|
| 414 |
+
_run_model_gpu = spaces.GPU(duration=_gpu_duration)(_run_model)
|
| 415 |
|
| 416 |
|
| 417 |
# Outputs of `predict`, in order — kept as a tuple factory so every return
|
|
|
|
| 435 |
image_path,
|
| 436 |
user_gsd_m=float(gsd or 0),
|
| 437 |
assumed_gsd_m=spec.canonical_gsd_m,
|
| 438 |
+
max_side=_MAX_SIDE,
|
| 439 |
)
|
| 440 |
|
| 441 |
+
height, seg = _run_model_gpu(rgb, scene_meta.gsd_m, bool(tta))
|
|
|
|
| 442 |
|
| 443 |
height = _sanitise(height)
|
| 444 |
# Objects are an extra, never a reason to lose the height map: a failure
|
|
|
|
| 546 |
# not a model failure: the caller's ZeroGPU allowance ran out
|
| 547 |
return _result(status=(
|
| 548 |
"Your ZeroGPU quota for today is used up. Sign in to Hugging "
|
| 549 |
+
"Face for a larger allowance, turn TTA off (it asks for at "
|
| 550 |
+
f"least {_GPU_DURATION_TTA} s instead of {_GPU_DURATION} s, "
|
| 551 |
+
"more for a large scene), or retry after the quota resets."
|
| 552 |
))
|
| 553 |
return _result(status=f"Inference failed: {exc}")
|
| 554 |
|
|
|
|
| 598 |
)
|
| 599 |
tta = gr.Checkbox(
|
| 600 |
value=False, label="Higher quality (slower)",
|
| 601 |
+
info=f"8 views per tile, all run in one GPU batch; reserves at "
|
| 602 |
+
f"least {_GPU_DURATION_TTA} s of GPU quota instead of "
|
| 603 |
+
f"{_GPU_DURATION} s. The usual cause of a quota error — leave "
|
| 604 |
+
"off unless you need it.",
|
| 605 |
)
|
| 606 |
with gr.Row():
|
| 607 |
run = gr.Button("Estimate height", variant="primary")
|
infer/engine.py
CHANGED
|
@@ -15,9 +15,10 @@ Contract in / out
|
|
| 15 |
-> height_m (H, W) float32, nDSM in metres, on the SAME grid as the input
|
| 16 |
|
| 17 |
Internally: scene stretch -> resample to `spec.canonical_gsd_m` -> overlapping
|
| 18 |
-
`spec.tile_size` windows
|
| 19 |
-
|
| 20 |
-
|
|
|
|
| 21 |
"""
|
| 22 |
|
| 23 |
from __future__ import annotations
|
|
@@ -30,16 +31,81 @@ from dwdata.preprocess import (
|
|
| 30 |
PreprocSpec, gsd_to_shape, hann2d, resize, stretch_scene, tile_origins,
|
| 31 |
)
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
@torch.no_grad()
|
| 35 |
def predict_canonical(
|
| 36 |
model, rgb_canon_u8: np.ndarray, spec: PreprocSpec, device,
|
| 37 |
*, tta: bool = False, tta_scales=(1.0,), amp_dtype=None,
|
| 38 |
-
overlap: float = 0.25, batch_tiles: int =
|
| 39 |
progress=None,
|
| 40 |
):
|
| 41 |
-
"""Sliding-window prediction over an image already at the canonical GSD.
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
S = spec.tile_size
|
| 45 |
H, W = rgb_canon_u8.shape[:2]
|
|
@@ -51,56 +117,92 @@ def predict_canonical(
|
|
| 51 |
Hp, Wp = rgb_canon_u8.shape[:2]
|
| 52 |
|
| 53 |
ys, xs = tile_origins(Hp, S, overlap), tile_origins(Wp, S, overlap)
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
# Labels cannot be averaged, so each pixel keeps the label from the tile it
|
| 58 |
# sits most centrally in (largest Hann weight). Last-write-wins put a
|
| 59 |
# visible seam at every tile edge, where the head has the least context.
|
| 60 |
seg_acc = seg_best = None
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
for
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
if seg is not None:
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
|
| 106 |
def _autocast(device, amp_dtype):
|
|
@@ -111,13 +213,25 @@ def _autocast(device, amp_dtype):
|
|
| 111 |
return torch.autocast("cuda", dtype=amp_dtype)
|
| 112 |
|
| 113 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
@torch.no_grad()
|
| 115 |
def predict_scene(
|
| 116 |
model, rgb_u8: np.ndarray, src_gsd_m: float, spec: PreprocSpec, device,
|
| 117 |
*, tta: bool = False, tta_scales=(1.0,), amp_dtype=None, overlap: float = 0.25,
|
| 118 |
-
batch_tiles: int =
|
| 119 |
):
|
| 120 |
-
"""RGB at any GSD -> nDSM in metres on the input grid (+ optional class map).
|
|
|
|
|
|
|
|
|
|
| 121 |
H, W = rgb_u8.shape[:2]
|
| 122 |
rgb_s = stretch_scene(rgb_u8, spec)
|
| 123 |
canon_hw = gsd_to_shape(H, W, src_gsd_m, spec.canonical_gsd_m)
|
|
|
|
| 15 |
-> height_m (H, W) float32, nDSM in metres, on the SAME grid as the input
|
| 16 |
|
| 17 |
Internally: scene stretch -> resample to `spec.canonical_gsd_m` -> overlapping
|
| 18 |
+
`spec.tile_size` windows, batched through the net in parallel -> optional D4 TTA
|
| 19 |
+
(all views in the same batch) -> Hann-weighted blend -> resample the height map
|
| 20 |
+
back to the input grid. Heights are metres, so the round trip does not rescale
|
| 21 |
+
them.
|
| 22 |
"""
|
| 23 |
|
| 24 |
from __future__ import annotations
|
|
|
|
| 31 |
PreprocSpec, gsd_to_shape, hann2d, resize, stretch_scene, tile_origins,
|
| 32 |
)
|
| 33 |
|
| 34 |
+
# Rough inference footprint of one 512 px tile through the ViT-L encoder, the
|
| 35 |
+
# DPT trunk and the full-resolution heads under bf16. Deliberately generous:
|
| 36 |
+
# it only seeds the batch size, and an OOM halves it and retries anyway.
|
| 37 |
+
_TILE_BYTES_512 = 640 * 2**20
|
| 38 |
+
_MAX_FORWARD_BATCH = 64
|
| 39 |
+
# The canvas (source RGB + blend buffers, ~17 B/px) stays on the GPU while it
|
| 40 |
+
# takes at most this share of free memory; bigger scenes blend on the host.
|
| 41 |
+
_CANVAS_SHARE = 0.35
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def auto_forward_batch(device, tile_size: int, reserve_frac: float = 0.15) -> int:
|
| 45 |
+
"""How many tiles one forward pass can take on `device` right now."""
|
| 46 |
+
if device.type != "cuda":
|
| 47 |
+
return 4
|
| 48 |
+
free, _total = torch.cuda.mem_get_info(device)
|
| 49 |
+
per_tile = _TILE_BYTES_512 * (tile_size / 512) ** 2
|
| 50 |
+
return int(max(1, min(_MAX_FORWARD_BATCH, free * (1 - reserve_frac) // per_tile)))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class _Forward:
|
| 54 |
+
"""Model call with autocast, memory-sized chunking and OOM back-off.
|
| 55 |
+
|
| 56 |
+
The chunk size is shared state: once a batch has hit OOM, later batches
|
| 57 |
+
start at the size that worked instead of rediscovering the limit each time.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def __init__(self, model, device, amp_dtype, max_batch: int, want_seg: bool):
|
| 61 |
+
self.model, self.device, self.amp_dtype = model, device, amp_dtype
|
| 62 |
+
self.max_batch, self.want_seg = max(1, int(max_batch)), want_seg
|
| 63 |
+
|
| 64 |
+
def __call__(self, x):
|
| 65 |
+
preds, segs, i = [], [], 0
|
| 66 |
+
while i < x.shape[0]:
|
| 67 |
+
n = self.max_batch
|
| 68 |
+
try:
|
| 69 |
+
with _autocast(self.device, self.amp_dtype):
|
| 70 |
+
out = self.model(x[i:i + n])
|
| 71 |
+
except torch.cuda.OutOfMemoryError:
|
| 72 |
+
if n == 1:
|
| 73 |
+
raise
|
| 74 |
+
self.max_batch = max(1, n // 2)
|
| 75 |
+
if self.device.type == "cuda":
|
| 76 |
+
torch.cuda.empty_cache()
|
| 77 |
+
print(f"[engine] OOM at {n} tiles/forward; retrying at {self.max_batch}")
|
| 78 |
+
continue
|
| 79 |
+
preds.append(out["fused"].float())
|
| 80 |
+
if self.want_seg:
|
| 81 |
+
# the ignore channel is a training target, never a prediction
|
| 82 |
+
segs.append(out["seg"][:, :SEG_IGNORE_INDEX].float().argmax(1))
|
| 83 |
+
del out
|
| 84 |
+
i += n
|
| 85 |
+
return torch.cat(preds), (torch.cat(segs) if self.want_seg else None)
|
| 86 |
+
|
| 87 |
|
| 88 |
@torch.no_grad()
|
| 89 |
def predict_canonical(
|
| 90 |
model, rgb_canon_u8: np.ndarray, spec: PreprocSpec, device,
|
| 91 |
*, tta: bool = False, tta_scales=(1.0,), amp_dtype=None,
|
| 92 |
+
overlap: float = 0.25, batch_tiles: int = 0, want_seg: bool = False,
|
| 93 |
progress=None,
|
| 94 |
):
|
| 95 |
+
"""Sliding-window prediction over an image already at the canonical GSD.
|
| 96 |
+
|
| 97 |
+
Every overlapping `tile_size` window is independent, so they go through the
|
| 98 |
+
network as large batches: `batch_tiles=0` sizes the forward batch from free
|
| 99 |
+
GPU memory (a big card takes dozens of tiles per pass), and under TTA all 8
|
| 100 |
+
D4 views of those tiles ride in the same batch rather than 8 passes in a row.
|
| 101 |
+
|
| 102 |
+
When the scene fits, the source image and the blend buffers live on the GPU:
|
| 103 |
+
tiles are cut and normalised there and blended in place, so the loop only
|
| 104 |
+
queues kernels and never waits on a device->host copy. A scene too large
|
| 105 |
+
for that blends on the host, with the next batch cut on a worker thread
|
| 106 |
+
while the GPU runs the current one.
|
| 107 |
+
"""
|
| 108 |
+
from models.tta import n_views, tta_predict_parallel
|
| 109 |
|
| 110 |
S = spec.tile_size
|
| 111 |
H, W = rgb_canon_u8.shape[:2]
|
|
|
|
| 117 |
Hp, Wp = rgb_canon_u8.shape[:2]
|
| 118 |
|
| 119 |
ys, xs = tile_origins(Hp, S, overlap), tile_origins(Wp, S, overlap)
|
| 120 |
+
coords = [(y, x) for y in ys for x in xs]
|
| 121 |
+
total = len(coords)
|
| 122 |
+
|
| 123 |
+
canvas_dev = device
|
| 124 |
+
if device.type == "cuda":
|
| 125 |
+
torch.backends.cudnn.benchmark = True # every batch is (N, 3, S, S)
|
| 126 |
+
free, _total = torch.cuda.mem_get_info(device)
|
| 127 |
+
if Hp * Wp * (3 + 8 + (6 if want_seg else 0)) > free * _CANVAS_SHARE:
|
| 128 |
+
canvas_dev = torch.device("cpu")
|
| 129 |
+
on_device = canvas_dev.type == device.type
|
| 130 |
+
|
| 131 |
+
src = torch.from_numpy(np.ascontiguousarray(rgb_canon_u8))
|
| 132 |
+
if on_device:
|
| 133 |
+
src = src.to(device) # one upload; every tile is a view of it
|
| 134 |
+
mean = torch.tensor(spec.mean, dtype=torch.float32, device=device).view(1, 3, 1, 1)
|
| 135 |
+
std = torch.tensor(spec.std, dtype=torch.float32, device=device).view(1, 3, 1, 1)
|
| 136 |
+
win = torch.from_numpy(hann2d(S)).to(canvas_dev)
|
| 137 |
+
acc = torch.zeros((Hp, Wp), dtype=torch.float32, device=canvas_dev)
|
| 138 |
+
wsum = torch.zeros((Hp, Wp), dtype=torch.float32, device=canvas_dev)
|
| 139 |
# Labels cannot be averaged, so each pixel keeps the label from the tile it
|
| 140 |
# sits most centrally in (largest Hann weight). Last-write-wins put a
|
| 141 |
# visible seam at every tile edge, where the head has the least context.
|
| 142 |
seg_acc = seg_best = None
|
| 143 |
+
if want_seg:
|
| 144 |
+
seg_acc = torch.zeros((Hp, Wp), dtype=torch.int16, device=canvas_dev)
|
| 145 |
+
seg_best = torch.zeros((Hp, Wp), dtype=torch.float32, device=canvas_dev)
|
| 146 |
+
|
| 147 |
+
views = n_views(tta_scales) if tta else 1
|
| 148 |
+
fwd = _Forward(
|
| 149 |
+
model, device, amp_dtype,
|
| 150 |
+
batch_tiles * views if batch_tiles > 0 else auto_forward_batch(device, S),
|
| 151 |
+
want_seg,
|
| 152 |
+
)
|
| 153 |
+
step = max(1, fwd.max_batch // views) # tiles per step; TTA multiplies them
|
| 154 |
+
|
| 155 |
+
def cut(chunk):
|
| 156 |
+
"""(B, S, S, 3) uint8 on the device, ready to normalise."""
|
| 157 |
+
tiles = torch.stack([src[y:y + S, x:x + S] for y, x in chunk])
|
| 158 |
+
if not on_device and device.type == "cuda":
|
| 159 |
+
tiles = tiles.pin_memory()
|
| 160 |
+
return tiles.to(device, non_blocking=True)
|
| 161 |
+
|
| 162 |
+
chunks = [coords[b0:b0 + step] for b0 in range(0, total, step)]
|
| 163 |
+
pool = pending = None
|
| 164 |
+
if not on_device and len(chunks) > 1:
|
| 165 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 166 |
+
|
| 167 |
+
pool = ThreadPoolExecutor(max_workers=1)
|
| 168 |
+
pending = pool.submit(cut, chunks[0])
|
| 169 |
+
done = 0
|
| 170 |
+
try:
|
| 171 |
+
for ci, chunk in enumerate(chunks):
|
| 172 |
+
if pool is not None:
|
| 173 |
+
tiles = pending.result()
|
| 174 |
+
if ci + 1 < len(chunks):
|
| 175 |
+
pending = pool.submit(cut, chunks[ci + 1])
|
| 176 |
+
else:
|
| 177 |
+
tiles = cut(chunk)
|
| 178 |
+
t = (tiles.permute(0, 3, 1, 2).float().div_(255.0) - mean) / std
|
| 179 |
+
if tta:
|
| 180 |
+
pred, seg = tta_predict_parallel(fwd, t, tuple(tta_scales), patch=spec.patch)
|
| 181 |
+
else:
|
| 182 |
+
pred, seg = fwd(t)
|
| 183 |
+
pred = pred[:, 0].to(canvas_dev)
|
| 184 |
if seg is not None:
|
| 185 |
+
seg = seg.to(device=canvas_dev, dtype=torch.int16)
|
| 186 |
+
|
| 187 |
+
for i, (y, x) in enumerate(chunk):
|
| 188 |
+
acc[y:y + S, x:x + S] += pred[i] * win
|
| 189 |
+
wsum[y:y + S, x:x + S] += win
|
| 190 |
+
if seg is not None:
|
| 191 |
+
best = seg_best[y:y + S, x:x + S]
|
| 192 |
+
better = win > best
|
| 193 |
+
seg_acc[y:y + S, x:x + S] = torch.where(
|
| 194 |
+
better, seg[i], seg_acc[y:y + S, x:x + S])
|
| 195 |
+
seg_best[y:y + S, x:x + S] = torch.where(better, win, best)
|
| 196 |
+
done += len(chunk)
|
| 197 |
+
if progress:
|
| 198 |
+
progress(done, total)
|
| 199 |
+
finally:
|
| 200 |
+
if pool is not None:
|
| 201 |
+
pool.shutdown(wait=True)
|
| 202 |
+
|
| 203 |
+
height = (acc / wsum.clamp_min(1e-6))[:H, :W].cpu().numpy()
|
| 204 |
+
seg_out = seg_acc[:H, :W].cpu().numpy() if seg_acc is not None else None
|
| 205 |
+
return height.astype(np.float32), seg_out
|
| 206 |
|
| 207 |
|
| 208 |
def _autocast(device, amp_dtype):
|
|
|
|
| 213 |
return torch.autocast("cuda", dtype=amp_dtype)
|
| 214 |
|
| 215 |
|
| 216 |
+
def count_tiles(h: int, w: int, src_gsd_m: float, spec: PreprocSpec,
|
| 217 |
+
overlap: float = 0.25) -> int:
|
| 218 |
+
"""Windows `predict_scene` will run for an (h, w) scene — for budgeting."""
|
| 219 |
+
ch, cw = gsd_to_shape(h, w, src_gsd_m, spec.canonical_gsd_m)
|
| 220 |
+
S = spec.tile_size
|
| 221 |
+
return (len(tile_origins(max(ch, S), S, overlap))
|
| 222 |
+
* len(tile_origins(max(cw, S), S, overlap)))
|
| 223 |
+
|
| 224 |
+
|
| 225 |
@torch.no_grad()
|
| 226 |
def predict_scene(
|
| 227 |
model, rgb_u8: np.ndarray, src_gsd_m: float, spec: PreprocSpec, device,
|
| 228 |
*, tta: bool = False, tta_scales=(1.0,), amp_dtype=None, overlap: float = 0.25,
|
| 229 |
+
batch_tiles: int = 0, want_seg: bool = False, progress=None,
|
| 230 |
):
|
| 231 |
+
"""RGB at any GSD -> nDSM in metres on the input grid (+ optional class map).
|
| 232 |
+
|
| 233 |
+
`batch_tiles=0` lets the engine size its batches from free GPU memory.
|
| 234 |
+
"""
|
| 235 |
H, W = rgb_u8.shape[:2]
|
| 236 |
rgb_s = stretch_scene(rgb_u8, spec)
|
| 237 |
canon_hw = gsd_to_shape(H, W, src_gsd_m, spec.canonical_gsd_m)
|
infer/predict.py
CHANGED
|
@@ -183,7 +183,8 @@ def main() -> None:
|
|
| 183 |
help="fallback when the input carries no scale (default: the "
|
| 184 |
"model's canonical GSD, i.e. treat 1 px as 0.5 m)")
|
| 185 |
ap.add_argument("--overlap", type=float, default=0.25)
|
| 186 |
-
ap.add_argument("--batch-tiles", type=int, default=
|
|
|
|
| 187 |
ap.add_argument("--tta", action="store_true", help="8x dihedral TTA (~8x slower)")
|
| 188 |
ap.add_argument("--tta-scales", default="1.0")
|
| 189 |
ap.add_argument("--dem", default="", help="coarse DEM (SRTM/Copernicus) -> absolute DSM")
|
|
@@ -216,8 +217,12 @@ def main() -> None:
|
|
| 216 |
amp_dt = torch.bfloat16 if (device.type == "cuda" and cfg.amp_dtype == "bf16") \
|
| 217 |
else (torch.float16 if device.type == "cuda" else None)
|
| 218 |
|
|
|
|
|
|
|
| 219 |
def prog(done, total):
|
| 220 |
-
|
|
|
|
|
|
|
| 221 |
print(f" tiles {done}/{total}", flush=True)
|
| 222 |
|
| 223 |
height, _ = predict_scene(
|
|
|
|
| 183 |
help="fallback when the input carries no scale (default: the "
|
| 184 |
"model's canonical GSD, i.e. treat 1 px as 0.5 m)")
|
| 185 |
ap.add_argument("--overlap", type=float, default=0.25)
|
| 186 |
+
ap.add_argument("--batch-tiles", type=int, default=0,
|
| 187 |
+
help="tiles per forward pass; 0 = size from free GPU memory")
|
| 188 |
ap.add_argument("--tta", action="store_true", help="8x dihedral TTA (~8x slower)")
|
| 189 |
ap.add_argument("--tta-scales", default="1.0")
|
| 190 |
ap.add_argument("--dem", default="", help="coarse DEM (SRTM/Copernicus) -> absolute DSM")
|
|
|
|
| 217 |
amp_dt = torch.bfloat16 if (device.type == "cuda" and cfg.amp_dtype == "bf16") \
|
| 218 |
else (torch.float16 if device.type == "cuda" else None)
|
| 219 |
|
| 220 |
+
shown = [-1]
|
| 221 |
+
|
| 222 |
def prog(done, total):
|
| 223 |
+
decile = done * 10 // max(1, total)
|
| 224 |
+
if decile != shown[0]:
|
| 225 |
+
shown[0] = decile
|
| 226 |
print(f" tiles {done}/{total}", flush=True)
|
| 227 |
|
| 228 |
height, _ = predict_scene(
|
models/tta.py
CHANGED
|
@@ -50,3 +50,45 @@ def tta_predict(model, image, scales=(1.0,), key: str = "fused",
|
|
| 50 |
acc += pred
|
| 51 |
n += 1
|
| 52 |
return acc / max(1, n)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
acc += pred
|
| 51 |
n += 1
|
| 52 |
return acc / max(1, n)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def n_views(scales=(1.0,)) -> int:
|
| 56 |
+
"""Forward passes per tile under `tta_predict_parallel`."""
|
| 57 |
+
return len(_D4) * max(1, len(scales))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@torch.no_grad()
|
| 61 |
+
def tta_predict_parallel(forward, image, scales=(1.0,), patch: int = 16):
|
| 62 |
+
"""`tta_predict`, but every D4 view of the batch goes through the net *together*.
|
| 63 |
+
|
| 64 |
+
The sequential version runs 8 small forwards per batch, which leaves a large
|
| 65 |
+
GPU mostly idle. A square tile keeps its shape under rot90/flip, so the 8
|
| 66 |
+
views stack along the batch axis and `forward` sees one (8B, 3, S, S) batch
|
| 67 |
+
per scale; it is free to split that into whatever fits in memory.
|
| 68 |
+
|
| 69 |
+
`forward(x) -> (pred (N, 1, h, w) float32, seg (N, h, w) long | None)`.
|
| 70 |
+
Returns the view-averaged height and the class map of the identity view, so
|
| 71 |
+
the class map no longer costs its own extra pass.
|
| 72 |
+
"""
|
| 73 |
+
b, _, h, w = image.shape
|
| 74 |
+
acc = torch.zeros((b, 1, h, w), device=image.device, dtype=torch.float32)
|
| 75 |
+
seg_id, n = None, 0
|
| 76 |
+
for s in scales:
|
| 77 |
+
if abs(s - 1.0) < 1e-6:
|
| 78 |
+
img_s = image
|
| 79 |
+
else:
|
| 80 |
+
nh = max(patch, int(round(h * s / patch)) * patch)
|
| 81 |
+
nw = max(patch, int(round(w * s / patch)) * patch)
|
| 82 |
+
img_s = F.interpolate(image, size=(nh, nw), mode="bilinear", align_corners=False)
|
| 83 |
+
views = torch.cat([_apply(img_s, k, flip) for k, flip in _D4])
|
| 84 |
+
pred, seg = forward(views)
|
| 85 |
+
for i, (k, flip) in enumerate(_D4):
|
| 86 |
+
p = _invert(pred[i * b:(i + 1) * b], k, flip)
|
| 87 |
+
if p.shape[-2:] != (h, w):
|
| 88 |
+
p = F.interpolate(p, size=(h, w), mode="bilinear", align_corners=False)
|
| 89 |
+
acc += p
|
| 90 |
+
n += 1
|
| 91 |
+
# _D4[0] is the identity; only the full-resolution pass supplies labels
|
| 92 |
+
if seg is not None and seg_id is None and img_s is image:
|
| 93 |
+
seg_id = seg[:b]
|
| 94 |
+
return acc / max(1, n), seg_id
|
predict_image.py
CHANGED
|
@@ -161,7 +161,8 @@ def main() -> None:
|
|
| 161 |
ap.add_argument("--tta-scales", default="1.0")
|
| 162 |
ap.add_argument("--overlap", type=float, default=0.5,
|
| 163 |
help="tile overlap; 0.5 gives a smoother Hann blend than eval's 0.25")
|
| 164 |
-
ap.add_argument("--batch-tiles", type=int, default=
|
|
|
|
| 165 |
ap.add_argument("--max-side", type=int, default=0, help="downsample huge scenes first")
|
| 166 |
ap.add_argument("--clip-pct", default="0.5,99.5",
|
| 167 |
help="percentiles for the display ramp (use 0,100 for raw min/max)")
|
|
|
|
| 161 |
ap.add_argument("--tta-scales", default="1.0")
|
| 162 |
ap.add_argument("--overlap", type=float, default=0.5,
|
| 163 |
help="tile overlap; 0.5 gives a smoother Hann blend than eval's 0.25")
|
| 164 |
+
ap.add_argument("--batch-tiles", type=int, default=0,
|
| 165 |
+
help="tiles per forward pass; 0 = size from free GPU memory")
|
| 166 |
ap.add_argument("--max-side", type=int, default=0, help="downsample huge scenes first")
|
| 167 |
ap.add_argument("--clip-pct", default="0.5,99.5",
|
| 168 |
help="percentiles for the display ramp (use 0,100 for raw min/max)")
|
tests/test_engine.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""`infer/engine.py` tiling, batching and parallel TTA against a model whose
|
| 2 |
+
answer is known.
|
| 3 |
+
|
| 4 |
+
The stand-in model is pointwise (each output pixel depends only on the same
|
| 5 |
+
input pixel), so it is exactly D4-equivariant and translation-invariant: the
|
| 6 |
+
Hann-blended mosaic of overlapping tiles, at any batch size, with or without
|
| 7 |
+
TTA, must reproduce the model applied to the whole scene in one go. Runs on
|
| 8 |
+
the CPU in a second; no checkpoint needed.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pytest
|
| 15 |
+
|
| 16 |
+
torch = pytest.importorskip("torch")
|
| 17 |
+
|
| 18 |
+
from config import N_SEG_CLASSES # noqa: E402
|
| 19 |
+
from dwdata.preprocess import PreprocSpec # noqa: E402
|
| 20 |
+
from infer.engine import count_tiles, predict_canonical # noqa: E402
|
| 21 |
+
|
| 22 |
+
SPEC = PreprocSpec(tile_size=64, patch=16)
|
| 23 |
+
CPU = torch.device("cpu")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Pointwise:
|
| 27 |
+
"""height = sum of channels; class = 1 where channel 0 > 0 else 0."""
|
| 28 |
+
|
| 29 |
+
def __init__(self, oom_above: int | None = None):
|
| 30 |
+
self.oom_above = oom_above
|
| 31 |
+
self.batches: list[int] = []
|
| 32 |
+
|
| 33 |
+
def __call__(self, x):
|
| 34 |
+
if self.oom_above is not None and x.shape[0] > self.oom_above:
|
| 35 |
+
raise torch.cuda.OutOfMemoryError("simulated")
|
| 36 |
+
self.batches.append(x.shape[0])
|
| 37 |
+
fused = x.sum(1, keepdim=True)
|
| 38 |
+
seg = torch.zeros((x.shape[0], N_SEG_CLASSES, *x.shape[-2:]))
|
| 39 |
+
seg[:, 1] = (x[:, 0] > 0).float()
|
| 40 |
+
seg[:, 0] = 0.5
|
| 41 |
+
return {"fused": fused, "seg": seg}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def scene(h, w, seed=0):
|
| 45 |
+
return np.random.default_rng(seed).integers(0, 256, (h, w, 3), dtype=np.uint8)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def reference(rgb):
|
| 49 |
+
x = SPEC.normalise(rgb)
|
| 50 |
+
return x.sum(0), (x[0] > 0).astype(np.int16)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@pytest.mark.parametrize("batch_tiles", [0, 1, 3, 50])
|
| 54 |
+
def test_tiled_mosaic_matches_whole_scene(batch_tiles):
|
| 55 |
+
rgb = scene(150, 211)
|
| 56 |
+
height, seg = predict_canonical(
|
| 57 |
+
Pointwise(), rgb, SPEC, CPU, overlap=0.5, batch_tiles=batch_tiles, want_seg=True,
|
| 58 |
+
)
|
| 59 |
+
ref_h, ref_s = reference(rgb)
|
| 60 |
+
assert height.shape == (150, 211) and seg.shape == (150, 211)
|
| 61 |
+
np.testing.assert_allclose(height, ref_h, atol=1e-4)
|
| 62 |
+
np.testing.assert_array_equal(seg, ref_s)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def test_parallel_tta_stacks_all_views_in_one_batch():
|
| 66 |
+
rgb = scene(100, 130, seed=1)
|
| 67 |
+
model = Pointwise()
|
| 68 |
+
height, seg = predict_canonical(
|
| 69 |
+
model, rgb, SPEC, CPU, tta=True, overlap=0.25, batch_tiles=2, want_seg=True,
|
| 70 |
+
)
|
| 71 |
+
ref_h, ref_s = reference(rgb)
|
| 72 |
+
np.testing.assert_allclose(height, ref_h, atol=1e-4)
|
| 73 |
+
np.testing.assert_array_equal(seg, ref_s)
|
| 74 |
+
# 2 tiles x 8 views per forward, not 8 forwards of 2
|
| 75 |
+
assert max(model.batches) == 16
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_oom_halves_the_batch_and_finishes():
|
| 79 |
+
rgb = scene(150, 211, seed=2)
|
| 80 |
+
model = Pointwise(oom_above=3)
|
| 81 |
+
height, _ = predict_canonical(model, rgb, SPEC, CPU, overlap=0.5, batch_tiles=8)
|
| 82 |
+
np.testing.assert_allclose(height, reference(rgb)[0], atol=1e-4)
|
| 83 |
+
assert max(model.batches) <= 3
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_scene_smaller_than_a_tile_is_padded_and_cropped():
|
| 87 |
+
rgb = scene(40, 30, seed=3)
|
| 88 |
+
height, seg = predict_canonical(Pointwise(), rgb, SPEC, CPU, want_seg=True)
|
| 89 |
+
assert height.shape == (40, 30) and seg.shape == (40, 30)
|
| 90 |
+
np.testing.assert_allclose(height, reference(rgb)[0], atol=1e-4)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def test_count_tiles_matches_the_grid():
|
| 94 |
+
# 150 x 211 at the canonical GSD, 64 px tiles at 50 % overlap -> 4 x 6
|
| 95 |
+
assert count_tiles(150, 211, SPEC.canonical_gsd_m, SPEC, 0.5) == 4 * 6
|