Spaces:
Running on Zero
Running on Zero
cuDNN-first attention in api.predict; review fixes; unified evaluation code
Browse files- README.md +19 -14
- app.py +2 -2
- ldpt/SUBSET.txt +2 -1
- ldpt/models/l_dpt/api.py +43 -34
- ldpt/models/l_dpt/convert.py +3 -3
- ldpt/models/l_dpt/l_dpt_v1m1_base.py +84 -99
- ldpt/models/l_dpt/modules.py +16 -13
- ldpt/models/l_dpt/presets.py +6 -6
- ldpt/models/losses/depth.py +90 -174
- ldpt/models/utils/depth.py +57 -16
- ldpt/utils/sdpa.py +58 -0
- space_utils.py +4 -3
README.md
CHANGED
|
@@ -16,20 +16,21 @@ pinned: false
|
|
| 16 |
|
| 17 |
# L-DPT: relative depth at a photo's native resolution
|
| 18 |
|
| 19 |
-
[ [Project](https://xywu.me/l-dpt) ] [ [Code](
|
| 20 |
|
| 21 |
Upload a photo and get its relative depth from L-DPT Large (zero-shot), computed on every
|
| 22 |
-
pixel of the photo
|
| 23 |
ViT-7B/16 encoder with a latent DPT decoder trained on 768 x 768 crops only, with no
|
| 24 |
high-resolution training data. The model
|
| 25 |
([`l-dpt_large_depth_zeroshot.pth`](https://huggingface.co/pointcept-bot/L-DPT)) is
|
| 26 |
trained on synthetic and multi-view data only.
|
| 27 |
|
| 28 |
**GPU time** on this Space, at native resolution: 1.7 s at 2 MP, 8.3 s at 8 MP, 87 s at
|
| 29 |
-
32 MP. 100 MP was not measured here; we estimate 750 s.
|
| 30 |
-
|
| 31 |
-
free account has), so large photos
|
| 32 |
-
app below has no such limit.
|
|
|
|
| 33 |
|
| 34 |
**Output.** Relative depth: larger = farther, defined up to a scale and a shift. It is
|
| 35 |
shown as in all L-DPT figures and scripts: log depth, near is warm, far is cool,
|
|
@@ -47,7 +48,7 @@ redistribute: request access on the
|
|
| 47 |
(27 GB).
|
| 48 |
|
| 49 |
```bash
|
| 50 |
-
git clone
|
| 51 |
pip install -e ".[demo,app]"
|
| 52 |
export LDPT_DINOV3=/path/to/dinov3 # the DINOv3 file or Hugging Face folder
|
| 53 |
python demo/hf_space/app.py # loads the model, then serves http://127.0.0.1:7860
|
|
@@ -55,8 +56,9 @@ python demo/hf_space/app.py # loads the model, then serves http://127.0
|
|
| 55 |
|
| 56 |
Without `LDPT_DINOV3` the app downloads the gated repository itself, with the `HF_TOKEN`
|
| 57 |
of an account that has access. `--host 0.0.0.0`, `--port` or `--share` serve it from a
|
| 58 |
-
remote machine, and `--examples DIR` adds a gallery
|
| 59 |
-
|
|
|
|
| 60 |
|
| 61 |
## Duplicate this Space
|
| 62 |
|
|
@@ -65,9 +67,10 @@ At startup the Space downloads Meta's gated repo
|
|
| 65 |
(transformers format, 27 GB), which needs the **`HF_TOKEN` secret**: a read token of an
|
| 66 |
account that Meta has granted access. The L-DPT weights file is public and pinned in
|
| 67 |
`models.json`, which can list more weights files (e.g. `l-dpt_large_depth_mixed.pth`);
|
| 68 |
-
with more than one the UI offers a choice. The example photos
|
| 69 |
-
|
| 70 |
-
|
|
|
|
| 71 |
|
| 72 |
Optional variables:
|
| 73 |
|
|
@@ -87,9 +90,11 @@ Optional variables:
|
|
| 87 |
|
| 88 |
## License
|
| 89 |
|
| 90 |
-
The L-DPT code
|
| 91 |
[CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/). The DINOv3 encoder is
|
| 92 |
-
Meta's, under the DINOv3 License, and is not redistributed.
|
|
|
|
|
|
|
| 93 |
|
| 94 |
## Citation
|
| 95 |
|
|
|
|
| 16 |
|
| 17 |
# L-DPT: relative depth at a photo's native resolution
|
| 18 |
|
| 19 |
+
[ [Project](https://xywu.me/l-dpt) ] [ [Code](https://github.com/Pointcept/L-DPT) ] [ [Weights](https://huggingface.co/pointcept-bot/L-DPT) ] [ [Training data](https://huggingface.co/datasets/pointcept-bot/DepthHybrid) ] [ [Examples](https://huggingface.co/datasets/pointcept-bot/L-DPT-examples) ]
|
| 20 |
|
| 21 |
Upload a photo and get its relative depth from L-DPT Large (zero-shot), computed on every
|
| 22 |
+
pixel of the photo. The Space accepts photos of up to 105 MP. L-DPT pairs a frozen DINOv3
|
| 23 |
ViT-7B/16 encoder with a latent DPT decoder trained on 768 x 768 crops only, with no
|
| 24 |
high-resolution training data. The model
|
| 25 |
([`l-dpt_large_depth_zeroshot.pth`](https://huggingface.co/pointcept-bot/L-DPT)) is
|
| 26 |
trained on synthetic and multi-view data only.
|
| 27 |
|
| 28 |
**GPU time** on this Space, at native resolution: 1.7 s at 2 MP, 8.3 s at 8 MP, 87 s at
|
| 29 |
+
32 MP. 100 MP was not measured here; we estimate 750 s. A request reserves its expected
|
| 30 |
+
time plus a margin from your daily ZeroGPU quota before it starts (990 s for a 100 MP
|
| 31 |
+
photo, more than a free account has), so large photos need a Hugging Face PRO account
|
| 32 |
+
here; the app on your own GPU (below) has no such limit. Each example shows a
|
| 33 |
+
precomputed result at once.
|
| 34 |
|
| 35 |
**Output.** Relative depth: larger = farther, defined up to a scale and a shift. It is
|
| 36 |
shown as in all L-DPT figures and scripts: log depth, near is warm, far is cool,
|
|
|
|
| 48 |
(27 GB).
|
| 49 |
|
| 50 |
```bash
|
| 51 |
+
git clone https://github.com/Pointcept/L-DPT.git && cd L-DPT
|
| 52 |
pip install -e ".[demo,app]"
|
| 53 |
export LDPT_DINOV3=/path/to/dinov3 # the DINOv3 file or Hugging Face folder
|
| 54 |
python demo/hf_space/app.py # loads the model, then serves http://127.0.0.1:7860
|
|
|
|
| 56 |
|
| 57 |
Without `LDPT_DINOV3` the app downloads the gated repository itself, with the `HF_TOKEN`
|
| 58 |
of an account that has access. `--host 0.0.0.0`, `--port` or `--share` serve it from a
|
| 59 |
+
remote machine, and `--examples DIR` adds a gallery: your photos, or a download of
|
| 60 |
+
[pointcept-bot/L-DPT-examples](https://huggingface.co/datasets/pointcept-bot/L-DPT-examples)
|
| 61 |
+
(`docs/inference.md` of the code).
|
| 62 |
|
| 63 |
## Duplicate this Space
|
| 64 |
|
|
|
|
| 67 |
(transformers format, 27 GB), which needs the **`HF_TOKEN` secret**: a read token of an
|
| 68 |
account that Meta has granted access. The L-DPT weights file is public and pinned in
|
| 69 |
`models.json`, which can list more weights files (e.g. `l-dpt_large_depth_mixed.pth`);
|
| 70 |
+
with more than one the UI offers a choice. The example photos and their precomputed
|
| 71 |
+
depth are the dataset [pointcept-bot/L-DPT-examples](https://huggingface.co/datasets/pointcept-bot/L-DPT-examples):
|
| 72 |
+
set the variable `LDPT_EXAMPLES_REPO=pointcept-bot/L-DPT-examples` to give a copy the
|
| 73 |
+
same gallery. Without it, a copy starts without a gallery.
|
| 74 |
|
| 75 |
Optional variables:
|
| 76 |
|
|
|
|
| 90 |
|
| 91 |
## License
|
| 92 |
|
| 93 |
+
The L-DPT code, the weights and this Space are released under
|
| 94 |
[CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/). The DINOv3 encoder is
|
| 95 |
+
Meta's, under the DINOv3 License, and is not redistributed. The example photos are not
|
| 96 |
+
covered: they keep their owners' rights
|
| 97 |
+
([pointcept-bot/L-DPT-examples](https://huggingface.co/datasets/pointcept-bot/L-DPT-examples)).
|
| 98 |
|
| 99 |
## Citation
|
| 100 |
|
app.py
CHANGED
|
@@ -78,8 +78,8 @@ def _on_gpu(fn):
|
|
| 78 |
|
| 79 |
predict_on_gpu = _on_gpu(_predict)
|
| 80 |
|
| 81 |
-
#
|
| 82 |
-
CODE_URL = "
|
| 83 |
LINKS = (
|
| 84 |
("Project", "https://xywu.me/l-dpt"),
|
| 85 |
("Code", CODE_URL),
|
|
|
|
| 78 |
|
| 79 |
predict_on_gpu = _on_gpu(_predict)
|
| 80 |
|
| 81 |
+
# The code repository, shown as the Code link of the hero
|
| 82 |
+
CODE_URL = "https://github.com/Pointcept/L-DPT"
|
| 83 |
LINKS = (
|
| 84 |
("Project", "https://xywu.me/l-dpt"),
|
| 85 |
("Code", CODE_URL),
|
ldpt/SUBSET.txt
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# ldpt inference subset for the Space: written by demo/hf_space/sync_ldpt.sh
|
| 2 |
-
# source:
|
| 3 |
ldpt/models/__init__.py
|
| 4 |
ldpt/models/builder.py
|
| 5 |
ldpt/models/dinov3/__init__.py
|
|
@@ -30,3 +30,4 @@ ldpt/utils/__init__.py
|
|
| 30 |
ldpt/utils/depth_image.py
|
| 31 |
ldpt/utils/misc.py
|
| 32 |
ldpt/utils/registry.py
|
|
|
|
|
|
| 1 |
# ldpt inference subset for the Space: written by demo/hf_space/sync_ldpt.sh
|
| 2 |
+
# source: 1624b79
|
| 3 |
ldpt/models/__init__.py
|
| 4 |
ldpt/models/builder.py
|
| 5 |
ldpt/models/dinov3/__init__.py
|
|
|
|
| 30 |
ldpt/utils/depth_image.py
|
| 31 |
ldpt/utils/misc.py
|
| 32 |
ldpt/utils/registry.py
|
| 33 |
+
ldpt/utils/sdpa.py
|
ldpt/models/l_dpt/api.py
CHANGED
|
@@ -19,27 +19,24 @@ Hugging Face on first use; a local copy loads by path
|
|
| 19 |
(``api.load("l-dpt_large_depth_zeroshot.pth", ...)``), with ``weights=`` or with
|
| 20 |
``$LDPT_CKPT_LARGE_DEPTH_ZEROSHOT``.
|
| 21 |
|
| 22 |
-
``load`` builds the model on the meta device
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
(
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
``load`` builds the model as its release file or preset states it (decoder precision
|
| 41 |
-
too, unless ``precision`` is passed) and refuses weights that were trained with another
|
| 42 |
-
architecture than the preset describes (_ARCH_KEYS: the options that change the output).
|
| 43 |
|
| 44 |
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
|
| 45 |
Please cite our work if the code is helpful to you.
|
|
@@ -50,7 +47,7 @@ import logging
|
|
| 50 |
import os
|
| 51 |
import time
|
| 52 |
from pathlib import Path
|
| 53 |
-
from typing import Any, Dict, Iterable, Mapping, Optional, Union
|
| 54 |
|
| 55 |
import numpy as np
|
| 56 |
import torch
|
|
@@ -58,6 +55,8 @@ import torch.nn as nn
|
|
| 58 |
import torch.nn.functional as F
|
| 59 |
from torch import Tensor
|
| 60 |
|
|
|
|
|
|
|
| 61 |
from .convert import FORMATS, build_meta, check_decoder_state, load_release
|
| 62 |
from .l_dpt_v1m1_base import PRECISIONS, LatentDPT, _resolve_attn_dtype
|
| 63 |
from .modules import check_choice
|
|
@@ -78,7 +77,7 @@ from .weights import (
|
|
| 78 |
read_checkpoint,
|
| 79 |
)
|
| 80 |
|
| 81 |
-
__all__ = ["NATIVE_MEMORY", "load", "predict"]
|
| 82 |
|
| 83 |
log = logging.getLogger(__name__)
|
| 84 |
|
|
@@ -108,9 +107,8 @@ def load(
|
|
| 108 |
(``"l-dpt_large_depth_zeroshot"``, ``"l-dpt_large_depth_mixed"``; their
|
| 109 |
files are downloaded from Hugging Face on first use, or read from
|
| 110 |
``$LDPT_CKPT_LARGE_DEPTH_ZEROSHOT`` / ``$LDPT_CKPT_LARGE_DEPTH_MIXED``),
|
| 111 |
-
or a release file written by convert.py (it carries its config;
|
| 112 |
-
name stored in
|
| 113 |
-
one).
|
| 114 |
encoder_weights: the official DINOv3 file (default ``$LDPT_DINOV3``); its sha256
|
| 115 |
prefix is checked once (``verify``). Or a folder in the transformers format
|
| 116 |
(a download of Meta's gated Hugging Face repo, e.g.
|
|
@@ -303,6 +301,7 @@ def predict(
|
|
| 303 |
*,
|
| 304 |
size: Union[int, str, None] = "auto",
|
| 305 |
flip: bool = False,
|
|
|
|
| 306 |
) -> Union[np.ndarray, Tensor]:
|
| 307 |
"""Relative depth of one image: positive, larger = farther, affine-invariant (the
|
| 308 |
metric depth is about s * depth + t, s > 0, per image); in [exp(-30), exp(30)] with
|
|
@@ -317,6 +316,17 @@ def predict(
|
|
| 317 |
caller passed them) that are still at their LatentDPT default, and restores
|
| 318 |
them after the call; a model built otherwise runs as it is.
|
| 319 |
flip: also run the horizontally flipped image and average (the eval TTA).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
|
| 321 |
Shapes:
|
| 322 |
image: [H, W, 3] -> [H, W] float32 (numpy for numpy input, else a tensor on
|
|
@@ -327,6 +337,7 @@ def predict(
|
|
| 327 |
f"predict returns relative depth; this model's task is {model.task!r}: "
|
| 328 |
f"use model.infer(normalised [B, 3, H, W] image)"
|
| 329 |
)
|
|
|
|
| 330 |
device = _model_device(model)
|
| 331 |
x = _to_image(image, device) # [1, 3, H, W] in [0, 1]
|
| 332 |
H, W = x.shape[-2:]
|
|
@@ -344,12 +355,11 @@ def predict(
|
|
| 344 |
try:
|
| 345 |
for k, v in memory.items():
|
| 346 |
setattr(model, k, v)
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
dim=1
|
| 352 |
-
)
|
| 353 |
finally:
|
| 354 |
for k, v in saved.items():
|
| 355 |
setattr(model, k, v)
|
|
@@ -526,8 +536,7 @@ def _storage_dtypes(model: LatentDPT) -> Dict[str, torch.dtype]:
|
|
| 526 |
# / rescale), init values, the criterion, and what the caller picks per load (precision,
|
| 527 |
# dec_pos_embed_rope_normalize_coords: api.load uses "min", selection_impl,
|
| 528 |
# chunk_tokens, encoder_weight_dtype: bit-identical under the frozen encoder's bf16
|
| 529 |
-
# autocast, and api.load stores a frozen encoder in bf16 unless overridden
|
| 530 |
-
# the training configs (bf16) or the presets (None) state).
|
| 531 |
_ARCH_KEYS = (
|
| 532 |
"encoder",
|
| 533 |
"encoder_inter_layers",
|
|
|
|
| 19 |
(``api.load("l-dpt_large_depth_zeroshot.pth", ...)``), with ``weights=`` or with
|
| 20 |
``$LDPT_CKPT_LARGE_DEPTH_ZEROSHOT``.
|
| 21 |
|
| 22 |
+
``load`` builds the model on the meta device and assigns the memory-mapped checkpoint
|
| 23 |
+
tensors on the target device (the 7B encoder stored in bf16 by default), so no fp32
|
| 24 |
+
copy of the encoder is made. It builds the model as its release file or preset states
|
| 25 |
+
it (decoder precision too, unless ``precision`` is passed) and refuses weights of
|
| 26 |
+
another architecture (_ARCH_KEYS: the options that change the output). The decoder RoPE
|
| 27 |
+
normalises token coordinates by the short side
|
| 28 |
+
(``dec_pos_embed_rope_normalize_coords="min"``), which keeps the token spacing of the
|
| 29 |
+
square training crops on any aspect ratio (``"separate"`` scales each axis to [-1, 1]
|
| 30 |
+
and squeezes the long side). Needs torch and numpy only (huggingface_hub to download
|
| 31 |
+
weights).
|
| 32 |
+
|
| 33 |
+
``predict`` uses the validation preprocessing (short side to the preset's INPUT_SIZE,
|
| 34 |
+
bicubic, ImageNet normalisation) and resizes the output back to the input size;
|
| 35 |
+
``size=None`` runs at the native resolution with NATIVE_MEMORY for the call (see
|
| 36 |
+
``predict``). It runs the model with cuDNN attention first (SDPA_ORDER of
|
| 37 |
+
ldpt/utils/sdpa.py, the order of the training option ``sdpa_backends``;
|
| 38 |
+
``sdpa_backends=None`` keeps PyTorch's order, which evaluation uses). Every option, and
|
| 39 |
+
the time and memory of native-resolution inference: docs/inference.md.
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
|
| 42 |
Please cite our work if the code is helpful to you.
|
|
|
|
| 47 |
import os
|
| 48 |
import time
|
| 49 |
from pathlib import Path
|
| 50 |
+
from typing import Any, Dict, Iterable, Mapping, Optional, Sequence, Union
|
| 51 |
|
| 52 |
import numpy as np
|
| 53 |
import torch
|
|
|
|
| 55 |
import torch.nn.functional as F
|
| 56 |
from torch import Tensor
|
| 57 |
|
| 58 |
+
from ldpt.utils.sdpa import SDPA_ORDER, sdpa_context
|
| 59 |
+
|
| 60 |
from .convert import FORMATS, build_meta, check_decoder_state, load_release
|
| 61 |
from .l_dpt_v1m1_base import PRECISIONS, LatentDPT, _resolve_attn_dtype
|
| 62 |
from .modules import check_choice
|
|
|
|
| 77 |
read_checkpoint,
|
| 78 |
)
|
| 79 |
|
| 80 |
+
__all__ = ["NATIVE_MEMORY", "SDPA_ORDER", "load", "predict"]
|
| 81 |
|
| 82 |
log = logging.getLogger(__name__)
|
| 83 |
|
|
|
|
| 107 |
(``"l-dpt_large_depth_zeroshot"``, ``"l-dpt_large_depth_mixed"``; their
|
| 108 |
files are downloaded from Hugging Face on first use, or read from
|
| 109 |
``$LDPT_CKPT_LARGE_DEPTH_ZEROSHOT`` / ``$LDPT_CKPT_LARGE_DEPTH_MIXED``),
|
| 110 |
+
or a release file written by convert.py (it carries its config; a short
|
| 111 |
+
preset name of LEGACY_PRESETS stored in it is read as the current name).
|
|
|
|
| 112 |
encoder_weights: the official DINOv3 file (default ``$LDPT_DINOV3``); its sha256
|
| 113 |
prefix is checked once (``verify``). Or a folder in the transformers format
|
| 114 |
(a download of Meta's gated Hugging Face repo, e.g.
|
|
|
|
| 301 |
*,
|
| 302 |
size: Union[int, str, None] = "auto",
|
| 303 |
flip: bool = False,
|
| 304 |
+
sdpa_backends: Union[Sequence[str], str, None] = SDPA_ORDER,
|
| 305 |
) -> Union[np.ndarray, Tensor]:
|
| 306 |
"""Relative depth of one image: positive, larger = farther, affine-invariant (the
|
| 307 |
metric depth is about s * depth + t, s > 0, per image); in [exp(-30), exp(30)] with
|
|
|
|
| 316 |
caller passed them) that are still at their LatentDPT default, and restores
|
| 317 |
them after the call; a model built otherwise runs as it is.
|
| 318 |
flip: also run the horizontally flipped image and average (the eval TTA).
|
| 319 |
+
sdpa_backends: the scaled-dot-product attention backends tried, in this order,
|
| 320 |
+
while the model runs (names of ldpt.utils.sdpa.SDPA_BACKENDS: "cudnn",
|
| 321 |
+
"flash", "efficient", "math"; the others are disabled for the call).
|
| 322 |
+
Default SDPA_ORDER (that of the training option ``sdpa_backends``):
|
| 323 |
+
cuDNN attention first, then FlashAttention, memory-efficient, math; a
|
| 324 |
+
backend the device or the dtype cannot use is skipped (the fp32 attention
|
| 325 |
+
of the release models' last decoder stage runs the memory-efficient
|
| 326 |
+
kernel; on the CPU and MPS the order changes nothing). None (or ``[]``)
|
| 327 |
+
keeps PyTorch's order (FlashAttention first in torch 2.8), as
|
| 328 |
+
scripts/evaluate.py runs; the kernels differ at the bf16 rounding level.
|
| 329 |
+
The flags are process-wide while the call runs and are restored after it.
|
| 330 |
|
| 331 |
Shapes:
|
| 332 |
image: [H, W, 3] -> [H, W] float32 (numpy for numpy input, else a tensor on
|
|
|
|
| 337 |
f"predict returns relative depth; this model's task is {model.task!r}: "
|
| 338 |
f"use model.infer(normalised [B, 3, H, W] image)"
|
| 339 |
)
|
| 340 |
+
attention = sdpa_context(sdpa_backends) # an unknown name raises here
|
| 341 |
device = _model_device(model)
|
| 342 |
x = _to_image(image, device) # [1, 3, H, W] in [0, 1]
|
| 343 |
H, W = x.shape[-2:]
|
|
|
|
| 355 |
try:
|
| 356 |
for k, v in memory.items():
|
| 357 |
setattr(model, k, v)
|
| 358 |
+
with attention:
|
| 359 |
+
pred = model.infer(x)
|
| 360 |
+
if flip:
|
| 361 |
+
flipped = torch.flip(model.infer(torch.flip(x, dims=[-1])), dims=[-1])
|
| 362 |
+
pred = torch.stack([pred, flipped], dim=1).mean(dim=1)
|
|
|
|
| 363 |
finally:
|
| 364 |
for k, v in saved.items():
|
| 365 |
setattr(model, k, v)
|
|
|
|
| 536 |
# / rescale), init values, the criterion, and what the caller picks per load (precision,
|
| 537 |
# dec_pos_embed_rope_normalize_coords: api.load uses "min", selection_impl,
|
| 538 |
# chunk_tokens, encoder_weight_dtype: bit-identical under the frozen encoder's bf16
|
| 539 |
+
# autocast, and api.load stores a frozen encoder in bf16 unless overridden).
|
|
|
|
| 540 |
_ARCH_KEYS = (
|
| 541 |
"encoder",
|
| 542 |
"encoder_inter_layers",
|
ldpt/models/l_dpt/convert.py
CHANGED
|
@@ -4,8 +4,8 @@ Training checkpoint -> L-DPT release file, and back.
|
|
| 4 |
A release file (``torch.save``, loadable with ``weights_only=True``) holds:
|
| 5 |
format "l-dpt-release/2"
|
| 6 |
model "L-DPT-v1m1"
|
| 7 |
-
preset preset name or None (the names of LEGACY_PRESETS,
|
| 8 |
-
|
| 9 |
config the LatentDPT kwargs without the training loss (a preset dict, or the
|
| 10 |
``model`` of a config file, minus ``criterion``)
|
| 11 |
state_dict decoder keys only (no ``module.`` prefix, no frozen encoder, no loss
|
|
@@ -52,7 +52,7 @@ __all__ = [
|
|
| 52 |
]
|
| 53 |
|
| 54 |
FORMAT = "l-dpt-release/2" # written; config without the criterion
|
| 55 |
-
# read: /1
|
| 56 |
FORMATS = (FORMAT, "l-dpt-release/1")
|
| 57 |
MODEL = "L-DPT-v1m1"
|
| 58 |
|
|
|
|
| 4 |
A release file (``torch.save``, loadable with ``weights_only=True``) holds:
|
| 5 |
format "l-dpt-release/2"
|
| 6 |
model "L-DPT-v1m1"
|
| 7 |
+
preset preset name or None (the short names of LEGACY_PRESETS, as the
|
| 8 |
+
published files store them, are read as the current ones)
|
| 9 |
config the LatentDPT kwargs without the training loss (a preset dict, or the
|
| 10 |
``model`` of a config file, minus ``criterion``)
|
| 11 |
state_dict decoder keys only (no ``module.`` prefix, no frozen encoder, no loss
|
|
|
|
| 52 |
]
|
| 53 |
|
| 54 |
FORMAT = "l-dpt-release/2" # written; config without the criterion
|
| 55 |
+
# read: /1 also stores the training criterion in the config (dropped on load)
|
| 56 |
FORMATS = (FORMAT, "l-dpt-release/1")
|
| 57 |
MODEL = "L-DPT-v1m1"
|
| 58 |
|
ldpt/models/l_dpt/l_dpt_v1m1_base.py
CHANGED
|
@@ -7,23 +7,22 @@ checkpoints (rope.periods, neck_blocks.{s} | neck_block, dec_blocks.{s}.{i}.*,
|
|
| 7 |
unpatchfy.0.proj, seg_head), so they load strictly. rope.periods is a persistent buffer
|
| 8 |
only because those checkpoints hold it.
|
| 9 |
|
| 10 |
-
Parts (one module, flat attributes, so the keys
|
| 11 |
- encoder adapter: frozen DINOv3, tapped layers concatenated, input padded to the patch
|
| 12 |
grid, optional bf16 weight storage (pad, encode);
|
| 13 |
- latent decoder: per-stage linear selection of the encoder features, added to a latent
|
| 14 |
grid (zero at stage 0) and refined by RoPE self-attention blocks (select, decode);
|
| 15 |
encode_select streams the selection layer by layer (no concatenation; high-res input);
|
| 16 |
- pixel readout: k x k conv + pixel shuffle back to the input resolution (decode);
|
| 17 |
-
- task heads:
|
| 18 |
-
depth
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
- the attention residual is added to the *normalised* tensor (x = norm1(x); x = x + attn(x)),
|
| 22 |
not to the block input as in a standard pre-LN block;
|
| 23 |
- in training, the decoder RoPE coordinate augmentation (jitter / rescale) is re-sampled
|
| 24 |
for every block, not once per forward;
|
| 25 |
-
- relative depth is a sigmoid output, aligned to the GT by a per-image scale and shift in
|
| 26 |
-
depth space (see losses/depth.py);
|
| 27 |
- by default the frozen encoder follows model.train(), so the DINOv3 RoPE rescale
|
| 28 |
augmentation is active on the encoder during training (encoder_train_mode).
|
| 29 |
|
|
@@ -94,110 +93,96 @@ class LatentDPT(nn.Module):
|
|
| 94 |
"""L-DPT: frozen ViT encoder + latent decoder + light readout.
|
| 95 |
|
| 96 |
A zero-initialised latent grid (one token per patch) is decoded in stages. Stage s
|
| 97 |
-
adds a linear selection of the concatenated encoder layers
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
| 100 |
|
| 101 |
Building does no device or data work beyond the encoder storage cast: build under
|
| 102 |
``torch.device("meta")`` and ``load_state_dict(..., assign=True)`` (api.load does).
|
|
|
|
| 103 |
|
| 104 |
-
Args (beyond the decoder sizes
|
|
|
|
| 105 |
encoder: registry cfg of the encoder (``dict(type="dinov3_vit7b")``) or a module
|
| 106 |
with ``patch_size``, ``embed_dim`` and ``get_intermediate_layers``.
|
| 107 |
encoder_inter_layers: encoder blocks to tap, one per decoder stage.
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
criterion: relative_depth: one loss cfg, default (None)
|
| 111 |
dict(type="relative_depth_loss"); semseg: a list of loss cfgs for
|
| 112 |
build_criteria. False: inference only, no loss built (release files,
|
| 113 |
-
api.load): self.criterion is None,
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
attn_fp32: None (default), "last" (the last decoder block), "last_stage" (the
|
| 126 |
-
|
| 127 |
-
projections, RoPE, SDPA, out_proj) runs in fp32 with autocast off
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
the
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
= min((sqrt(head_dim) / 3) exp(30 rho_h), dec_qk_tau_max) with one learned
|
| 143 |
-
rho_h per head (key dec_blocks.{s}.{i}.attn.logit_scale, zeros at init: the
|
| 144 |
-
logit scale of the unnormalised attention at init). |logit| <=
|
| 145 |
-
dec_qk_tau_max for any weights (bf16 operands: x (1 + 2^-8)^2). Off: no
|
| 146 |
-
parameter, no branch, the RNG stream unchanged. A model trained with it
|
| 147 |
-
needs it at inference (a strict load without it fails on the key). Raises
|
| 148 |
-
with dec_qk_bound; composes with attn_fp32 / block_fp32.
|
| 149 |
-
dec_qk_tau_max: the temperature cap of dec_qk_norm (default 200.0, the bf16
|
| 150 |
-
softmax resolution limit); not in the state dict.
|
| 151 |
dec_conv_mixer: None (default), "last" or "last_stage": those blocks mix
|
| 152 |
-
tokens with LocalMix (3x3 depthwise conv on the token grid
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
compile_blocks (eager: the fp32 convolution's backward stays fp32).
|
| 160 |
-
encoder_train_mode: True keeps the old behaviour (the frozen encoder follows
|
| 161 |
-
model.train(), so its RoPE augmentation is active in training); False keeps
|
| 162 |
-
the encoder in eval mode.
|
| 163 |
-
head: "sigmoid" (default, as trained: depth = sigmoid(u) of the readout logit
|
| 164 |
-
u) or "exp" (the L-DPT depth loss: depth = exp(clamp(u, -30, 30))). No
|
| 165 |
-
parameters, same state dict. relative_depth only; a criterion with a head
|
| 166 |
-
attribute must name the same head.
|
| 167 |
-
readout_fp32: False (default) or True: the readout (conv + pixel shuffle) runs
|
| 168 |
-
outside the autocast on the fp32 copy of the decoder output (the L-DPT
|
| 169 |
-
depth loss), so the logit is not rounded to bf16. Without an autocast the
|
| 170 |
-
same math.
|
| 171 |
dec_pos_embed_rope_eval_scale: None (default) or r > 0: in eval mode the
|
| 172 |
-
decoder RoPE coordinates
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
bitwise the model without it.
|
| 178 |
-
encoder_weight_dtype: None or "bf16". With a frozen encoder, store its
|
| 179 |
-
Linear / Conv2d weights in bf16 (the encoder already runs under bf16
|
| 180 |
-
autocast, so outputs are bit-identical); norms, LayerScale, tokens and RoPE
|
| 181 |
-
stay fp32. Re-applied after every load_state_dict.
|
| 182 |
-
tap_bn: False (default) or True: a learned BatchNorm (affine, momentum 0.1,
|
| 183 |
-
eps 1e-5) on each tapped encoder layer, after the encoder's final LayerNorm
|
| 184 |
-
and before the selection (DINOv3's segmentation heads), over the C_enc
|
| 185 |
-
channels of every token, in fp32 with autocast off; both encode paths
|
| 186 |
-
(concat and stream). Keys tap_bn.{i}.{weight, bias, running_mean,
|
| 187 |
-
running_var, num_batches_tracked}, i = tap index (+2 L C_enc parameters,
|
| 188 |
-
in the decoder's optimizer group). The trainer's sync_bn converts them to
|
| 189 |
-
SyncBatchNorm. Off: no module, no branch, bitwise the old model.
|
| 190 |
-
|
| 191 |
-
Inference memory (no parameters; attributes, may be changed after building):
|
| 192 |
-
selection_impl: "concat" (default, as trained: tapped layers concatenated to
|
| 193 |
[B, N, L * C_enc], one Linear) or "stream" (encode_select: each layer is
|
| 194 |
projected by its slice of the selection weights as the encoder yields it,
|
| 195 |
-
summed in fp32 and freed;
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
math unchanged, matrix products over fewer rows may round differently.
|
| 201 |
"""
|
| 202 |
|
| 203 |
def __init__(
|
|
@@ -692,7 +677,7 @@ class LatentDPT(nn.Module):
|
|
| 692 |
else:
|
| 693 |
query = blk(query, rope=rope, chunk_tokens=chunk_tokens, **kw)
|
| 694 |
b, _, c = query.shape
|
| 695 |
-
# [B, N, C] -> [B, C, h, w]
|
| 696 |
query = query.reshape(b, h, w, c).permute(0, 3, 1, 2)
|
| 697 |
if not self.readout_fp32:
|
| 698 |
pred = self.unpatchfy(query)
|
|
@@ -741,7 +726,7 @@ class LatentDPT(nn.Module):
|
|
| 741 |
prediction is resized bilinearly to H' x W' for the loss
|
| 742 |
data_dict["segment"] (semseg): [B, 1, H, W] int, -1 = ignore
|
| 743 |
data_dict["name"]: B sample names, passed to a loss that uses them
|
| 744 |
-
(relative_depth_loss with grad_exclude)
|
| 745 |
-> dict(loss, ...) when the target is given (and the model has a loss);
|
| 746 |
in eval also pred_depth [B, 1, H, W] or pred_segment
|
| 747 |
[B, num_classes, H, W]
|
|
@@ -771,8 +756,8 @@ class LatentDPT(nn.Module):
|
|
| 771 |
pred = F.interpolate(
|
| 772 |
pred, size=gt_depth.shape[-2:], mode="bilinear", align_corners=False
|
| 773 |
)
|
| 774 |
-
# a loss with per-dataset rules (relative_depth_loss
|
| 775 |
-
# sample names
|
| 776 |
kwargs = {}
|
| 777 |
if getattr(self.criterion, "uses_names", False):
|
| 778 |
kwargs["names"] = data_dict.get("name")
|
|
|
|
| 7 |
unpatchfy.0.proj, seg_head), so they load strictly. rope.periods is a persistent buffer
|
| 8 |
only because those checkpoints hold it.
|
| 9 |
|
| 10 |
+
Parts (one module, flat attributes, so the state-dict keys match the checkpoints):
|
| 11 |
- encoder adapter: frozen DINOv3, tapped layers concatenated, input padded to the patch
|
| 12 |
grid, optional bf16 weight storage (pad, encode);
|
| 13 |
- latent decoder: per-stage linear selection of the encoder features, added to a latent
|
| 14 |
grid (zero at stage 0) and refined by RoPE self-attention blocks (select, decode);
|
| 15 |
encode_select streams the selection layer by layer (no concatenation; high-res input);
|
| 16 |
- pixel readout: k x k conv + pixel shuffle back to the input resolution (decode);
|
| 17 |
+
- task heads: relative depth sigmoid(u) (default) or exp(clamp(u, -30, 30))
|
| 18 |
+
(head="exp", the released depth models) of the readout logit u, or 1x1 seg_head
|
| 19 |
+
logits (infer); losses (forward).
|
| 20 |
|
| 21 |
+
Behaviours the trained checkpoints depend on (keep them):
|
| 22 |
- the attention residual is added to the *normalised* tensor (x = norm1(x); x = x + attn(x)),
|
| 23 |
not to the block input as in a standard pre-LN block;
|
| 24 |
- in training, the decoder RoPE coordinate augmentation (jitter / rescale) is re-sampled
|
| 25 |
for every block, not once per forward;
|
|
|
|
|
|
|
| 26 |
- by default the frozen encoder follows model.train(), so the DINOv3 RoPE rescale
|
| 27 |
augmentation is active on the encoder during training (encoder_train_mode).
|
| 28 |
|
|
|
|
| 93 |
"""L-DPT: frozen ViT encoder + latent decoder + light readout.
|
| 94 |
|
| 95 |
A zero-initialised latent grid (one token per patch) is decoded in stages. Stage s
|
| 96 |
+
adds a linear selection of the concatenated encoder layers and runs
|
| 97 |
+
dec_num_layers[s] RoPE self-attention blocks; a k x k conv + pixel shuffle reads
|
| 98 |
+
out to pixels. The released depth models are this class with presets.RELEASE_L.
|
| 99 |
+
AGENTS.md ("Model") gives an overview of the options, docs/inference.md the
|
| 100 |
+
inference memory options.
|
| 101 |
|
| 102 |
Building does no device or data work beyond the encoder storage cast: build under
|
| 103 |
``torch.device("meta")`` and ``load_state_dict(..., assign=True)`` (api.load does).
|
| 104 |
+
An option that is off by default is bitwise the model without it when off.
|
| 105 |
|
| 106 |
+
Args (beyond the decoder sizes dec_dim, dec_num_heads, dec_num_layers,
|
| 107 |
+
dec_attn_downscale, dec_ffn_ratio and the decoder RoPE options):
|
| 108 |
encoder: registry cfg of the encoder (``dict(type="dinov3_vit7b")``) or a module
|
| 109 |
with ``patch_size``, ``embed_dim`` and ``get_intermediate_layers``.
|
| 110 |
encoder_inter_layers: encoder blocks to tap, one per decoder stage.
|
| 111 |
+
freeze_encoder: True (default): the encoder gets no gradient and runs under
|
| 112 |
+
bf16 autocast.
|
| 113 |
+
encoder_train_mode: True (default): the frozen encoder follows model.train(),
|
| 114 |
+
so its RoPE augmentation is active in training (the released checkpoints
|
| 115 |
+
were trained this way); False keeps the encoder in eval mode.
|
| 116 |
+
encoder_weight_dtype: None (default) or "bf16" (the released models; needs
|
| 117 |
+
freeze_encoder): the encoder's Linear / Conv2d weights are stored in bf16
|
| 118 |
+
(it runs under bf16 autocast, so outputs are bit-identical); norms,
|
| 119 |
+
LayerScale, tokens and RoPE stay fp32. Re-applied after every
|
| 120 |
+
load_state_dict.
|
| 121 |
+
task: "relative_depth" (one channel, see head) or "semseg" (out_dim pixel
|
| 122 |
+
features + a 1x1 seg_head with num_classes outputs).
|
| 123 |
criterion: relative_depth: one loss cfg, default (None)
|
| 124 |
dict(type="relative_depth_loss"); semseg: a list of loss cfgs for
|
| 125 |
build_criteria. False: inference only, no loss built (release files,
|
| 126 |
+
api.load): self.criterion is None, a forward in eval returns the
|
| 127 |
+
prediction without a loss even when the target is given, and a training
|
| 128 |
+
forward raises. No loss has state-dict keys, so the same checkpoints load
|
| 129 |
+
either way.
|
| 130 |
+
head: relative depth from the readout logit u: "sigmoid" (default, depth =
|
| 131 |
+
sigmoid(u)) or "exp" (depth = exp(clamp(u, -30, 30)), the released
|
| 132 |
+
models). No parameters. A criterion with a head attribute must name the
|
| 133 |
+
same head.
|
| 134 |
+
readout_fp32: False (default) or True (the released models): the readout
|
| 135 |
+
(conv + pixel shuffle) runs outside the autocast on the fp32 decoder
|
| 136 |
+
output, so the logit is not rounded to bf16.
|
| 137 |
+
selection: "stage" (default: one Linear per stage) or "shared" (one Linear for
|
| 138 |
+
all stages, key 'neck_block').
|
| 139 |
+
readout_kernel_size: 3 (default, the released weights) or 1 (a linear
|
| 140 |
+
projection).
|
| 141 |
+
precision: "fp32" (default) or "bf16" (the released models): selection,
|
| 142 |
+
decoder blocks and readout conv under bf16 autocast; readout output, heads
|
| 143 |
+
and loss in fp32. "fp32" adds no autocast, so an autocast the caller
|
| 144 |
+
entered (trainer enable_amp) still applies.
|
| 145 |
+
attn_dtype: "fp32" (default) or "bf16" (the released models: q / k / v cast
|
| 146 |
+
to bf16 for SDPA). attn_impl ("auto" / "flash") is the legacy name of the
|
| 147 |
+
same choice.
|
| 148 |
attn_fp32: None (default), "last" (the last decoder block), "last_stage" (the
|
| 149 |
+
released models) or "all": the attention of those blocks (q / k / v
|
| 150 |
+
projections, RoPE, SDPA, out_proj) runs in fp32 with autocast off.
|
| 151 |
+
block_fp32: None (default), "last" or "last_stage": those whole blocks run in
|
| 152 |
+
fp32 with autocast off. Without an autocast, attn_fp32 and block_fp32 are
|
| 153 |
+
the same math as without them.
|
| 154 |
+
dec_qk_bound: None (default) or a logit bound B > 0 (the released models:
|
| 155 |
+
1000): in every decoder attention q and k are clipped per head and token
|
| 156 |
+
to an L2 norm of at most sqrt(B sqrt(head_dim)) before RoPE, so |q.k| /
|
| 157 |
+
sqrt(head_dim) <= B. No parameters. Active in training and eval: a model
|
| 158 |
+
trained with it needs it at inference. The strings "None" / "null" / ""
|
| 159 |
+
(from --options) turn it off.
|
| 160 |
+
Experimental, used by no released model (details: modules.py and the tests):
|
| 161 |
+
dec_qk_norm (+ dec_qk_tau_max, default 200.0): cosine attention with a
|
| 162 |
+
learned temperature per head, capped at dec_qk_tau_max (Attention
|
| 163 |
+
qk_norm); one key dec_blocks.{s}.{i}.attn.logit_scale per block; raises
|
| 164 |
+
with dec_qk_bound.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
dec_conv_mixer: None (default), "last" or "last_stage": those blocks mix
|
| 166 |
+
tokens with LocalMix (3x3 depthwise conv on the token grid) instead of
|
| 167 |
+
self-attention; keys local.* replace attn.*, every other parameter and the
|
| 168 |
+
RNG stream stay as without it. attn_fp32 does not apply to them,
|
| 169 |
+
block_fp32 does; compile_blocks leaves them eager.
|
| 170 |
+
tap_bn: False (default) or True: a BatchNorm on each tapped encoder layer
|
| 171 |
+
before the selection, in fp32 (keys tap_bn.{i}.*; the trainer's sync_bn
|
| 172 |
+
converts them to SyncBatchNorm).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
dec_pos_embed_rope_eval_scale: None (default) or r > 0: in eval mode the
|
| 174 |
+
decoder RoPE coordinates are multiplied by r (training unchanged); r > 1
|
| 175 |
+
spreads the tokens of a large input toward the trained token spacing.
|
| 176 |
+
|
| 177 |
+
Inference memory (attributes, may be changed after building; same math):
|
| 178 |
+
selection_impl: "concat" (default: the tapped layers concatenated to
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
[B, N, L * C_enc], one Linear) or "stream" (encode_select: each layer is
|
| 180 |
projected by its slice of the selection weights as the encoder yields it,
|
| 181 |
+
summed in fp32 and freed; another summation order).
|
| 182 |
+
chunk_tokens: None (default) or a token count: in eval without autograd the
|
| 183 |
+
encoder blocks and the decoder FFN run on chunks of this many tokens;
|
| 184 |
+
per-token math unchanged, matrix products over fewer rows may round
|
| 185 |
+
differently.
|
|
|
|
| 186 |
"""
|
| 187 |
|
| 188 |
def __init__(
|
|
|
|
| 677 |
else:
|
| 678 |
query = blk(query, rope=rope, chunk_tokens=chunk_tokens, **kw)
|
| 679 |
b, _, c = query.shape
|
| 680 |
+
# [B, N, C] -> [B, C, h, w] as a view, no copy (channels-last strides)
|
| 681 |
query = query.reshape(b, h, w, c).permute(0, 3, 1, 2)
|
| 682 |
if not self.readout_fp32:
|
| 683 |
pred = self.unpatchfy(query)
|
|
|
|
| 726 |
prediction is resized bilinearly to H' x W' for the loss
|
| 727 |
data_dict["segment"] (semseg): [B, 1, H, W] int, -1 = ignore
|
| 728 |
data_dict["name"]: B sample names, passed to a loss that uses them
|
| 729 |
+
(relative_depth_loss with label_types or grad_exclude)
|
| 730 |
-> dict(loss, ...) when the target is given (and the model has a loss);
|
| 731 |
in eval also pred_depth [B, 1, H, W] or pred_segment
|
| 732 |
[B, num_classes, H, W]
|
|
|
|
| 756 |
pred = F.interpolate(
|
| 757 |
pred, size=gt_depth.shape[-2:], mode="bilinear", align_corners=False
|
| 758 |
)
|
| 759 |
+
# a loss with per-dataset rules (relative_depth_loss label_types / grad_exclude)
|
| 760 |
+
# gets the sample names
|
| 761 |
kwargs = {}
|
| 762 |
if getattr(self.criterion, "uses_names", False):
|
| 763 |
kwargs["names"] = data_dict.get("name")
|
ldpt/models/l_dpt/modules.py
CHANGED
|
@@ -29,7 +29,8 @@ __all__ = [
|
|
| 29 |
# attention dtype -> the dtype q / k / v are cast to for SDPA (None: the input dtype)
|
| 30 |
ATTN_DTYPES = {"fp32": None, "bf16": torch.bfloat16}
|
| 31 |
# qk_norm (LatentDPT dec_qk_norm): tau_h = min(tau_init exp(QK_TAU_GAIN rho_h), tau_max);
|
| 32 |
-
# the gain lets Adam (a step of at most lr on rho) move tau by x9 in 4000 warm-up
|
|
|
|
| 33 |
QK_TAU_GAIN = 30.0
|
| 34 |
QK_TAU_MAX = 200.0
|
| 35 |
QK_NORM_EPS = 1e-6
|
|
@@ -63,7 +64,7 @@ class Attention(nn.Module):
|
|
| 63 |
"""Self-attention with 2D RoPE; q / k / v project dim -> dim // downscale.
|
| 64 |
|
| 65 |
attn_dtype="bf16" casts q / k / v to bf16 for SDPA and the output back to the input
|
| 66 |
-
dtype
|
| 67 |
force_fp32 (LatentDPT attn_fp32, an fp32 island in a bf16 decoder): q / k / v
|
| 68 |
projections, RoPE, SDPA and out_proj run in fp32 on x.float() with autocast off,
|
| 69 |
whatever the caller's autocast and attn_dtype; the output is fp32 (fp32_forward,
|
|
@@ -72,7 +73,7 @@ class Attention(nn.Module):
|
|
| 72 |
the key of each token are clipped to an L2 norm of at most r = sqrt(B sqrt(d))
|
| 73 |
before RoPE (q <- q min(1, r / |q|), in fp32), so |q.k| / sqrt(d) <= B for every
|
| 74 |
pair (RoPE is a rotation). bf16 operands (SDPA in bf16) round each entry by up to
|
| 75 |
-
2^-8: at most B (1 + 2^-8)^2 = 1.0078 B (201.57 at B = 200
|
| 76 |
No parameters; q / k below r are bitwise unchanged. In qkv, so the fp32 island and
|
| 77 |
every SDPA backend see the bounded q / k.
|
| 78 |
qk_norm (LatentDPT dec_qk_norm, cosine attention with a learned capped temperature,
|
|
@@ -283,13 +284,14 @@ class LocalMix(nn.Module):
|
|
| 283 |
|
| 284 |
|
| 285 |
class Block(nn.Module):
|
| 286 |
-
"""Decoder block.
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
|
|
|
| 293 |
|
| 294 |
Shapes:
|
| 295 |
x: [B, N, dim]; rope: (sin, cos), each [N, head_dim]; hw: (h, w), h * w = N
|
|
@@ -354,7 +356,8 @@ class Block(nn.Module):
|
|
| 354 |
chunk_tokens: Optional[int] = None,
|
| 355 |
hw: Optional[Tuple[int, int]] = None,
|
| 356 |
) -> Tensor:
|
| 357 |
-
# residual on the normalised tensor (
|
|
|
|
| 358 |
x = self.norm1(x)
|
| 359 |
if self.mixer == "conv":
|
| 360 |
x = x + self.ls1(self.local(x, hw))
|
|
@@ -398,6 +401,6 @@ class PixelReadout(nn.Module):
|
|
| 398 |
)
|
| 399 |
|
| 400 |
def forward(self, x: Tensor) -> Tensor:
|
| 401 |
-
# contiguous NCHW
|
| 402 |
-
#
|
| 403 |
return F.pixel_shuffle(self.proj(x), self.patch_size).contiguous()
|
|
|
|
| 29 |
# attention dtype -> the dtype q / k / v are cast to for SDPA (None: the input dtype)
|
| 30 |
ATTN_DTYPES = {"fp32": None, "bf16": torch.bfloat16}
|
| 31 |
# qk_norm (LatentDPT dec_qk_norm): tau_h = min(tau_init exp(QK_TAU_GAIN rho_h), tau_max);
|
| 32 |
+
# the gain lets Adam (a step of at most lr on rho) move tau by x9 in 4000 warm-up
|
| 33 |
+
# iterations
|
| 34 |
QK_TAU_GAIN = 30.0
|
| 35 |
QK_TAU_MAX = 200.0
|
| 36 |
QK_NORM_EPS = 1e-6
|
|
|
|
| 64 |
"""Self-attention with 2D RoPE; q / k / v project dim -> dim // downscale.
|
| 65 |
|
| 66 |
attn_dtype="bf16" casts q / k / v to bf16 for SDPA and the output back to the input
|
| 67 |
+
dtype; "fp32" runs SDPA in the input dtype.
|
| 68 |
force_fp32 (LatentDPT attn_fp32, an fp32 island in a bf16 decoder): q / k / v
|
| 69 |
projections, RoPE, SDPA and out_proj run in fp32 on x.float() with autocast off,
|
| 70 |
whatever the caller's autocast and attn_dtype; the output is fp32 (fp32_forward,
|
|
|
|
| 73 |
the key of each token are clipped to an L2 norm of at most r = sqrt(B sqrt(d))
|
| 74 |
before RoPE (q <- q min(1, r / |q|), in fp32), so |q.k| / sqrt(d) <= B for every
|
| 75 |
pair (RoPE is a rotation). bf16 operands (SDPA in bf16) round each entry by up to
|
| 76 |
+
2^-8: at most B (1 + 2^-8)^2 = 1.0078 B (201.57 at B = 200).
|
| 77 |
No parameters; q / k below r are bitwise unchanged. In qkv, so the fp32 island and
|
| 78 |
every SDPA backend see the bounded q / k.
|
| 79 |
qk_norm (LatentDPT dec_qk_norm, cosine attention with a learned capped temperature,
|
|
|
|
| 284 |
|
| 285 |
|
| 286 |
class Block(nn.Module):
|
| 287 |
+
"""Decoder block. The attention residual is added to the *normalised* tensor
|
| 288 |
+
(x = norm1(x); x = x + attn(x)), not to the block input as in a standard pre-LN
|
| 289 |
+
block: the released checkpoints depend on it. chunk_tokens (no autograd only) runs
|
| 290 |
+
the FFN on token chunks. attn_fp32: the attention is an fp32 island (Attention
|
| 291 |
+
force_fp32); qk_bound / qk_norm / qk_tau_max: Attention's. convert_mixer_ replaces
|
| 292 |
+
the attention by LocalMix (mixer "conv", LatentDPT dec_conv_mixer): x = norm1(x);
|
| 293 |
+
x = x + ls1(local(x, hw)); the FFN as in an attention block. Such a block needs
|
| 294 |
+
the token grid hw and ignores rope.
|
| 295 |
|
| 296 |
Shapes:
|
| 297 |
x: [B, N, dim]; rope: (sin, cos), each [N, head_dim]; hw: (h, w), h * w = N
|
|
|
|
| 356 |
chunk_tokens: Optional[int] = None,
|
| 357 |
hw: Optional[Tuple[int, int]] = None,
|
| 358 |
) -> Tensor:
|
| 359 |
+
# residual on the normalised tensor (the checkpoints depend on it), not on the
|
| 360 |
+
# block input
|
| 361 |
x = self.norm1(x)
|
| 362 |
if self.mixer == "conv":
|
| 363 |
x = x + self.ls1(self.local(x, hw))
|
|
|
|
| 401 |
)
|
| 402 |
|
| 403 |
def forward(self, x: Tensor) -> Tensor:
|
| 404 |
+
# contiguous NCHW output (the conv ran on a channels-last view): a no-op for
|
| 405 |
+
# one output channel, and it keeps the semseg 1x1 head bit-exact
|
| 406 |
return F.pixel_shuffle(self.proj(x), self.patch_size).contiguous()
|
ldpt/models/l_dpt/presets.py
CHANGED
|
@@ -22,9 +22,9 @@ training losses live in the configs. In a config:
|
|
| 22 |
WEIGHTS pins the released decoder checkpoints (Hugging Face repo, revision, file,
|
| 23 |
sha256, and the variable naming a local copy); DINOv3 weights are not
|
| 24 |
redistributed: weights.encoder_weights() takes a local file and checks the sha256 prefix
|
| 25 |
-
in its official name. LEGACY_PRESETS maps the preset names
|
| 26 |
-
|
| 27 |
-
|
| 28 |
|
| 29 |
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
|
| 30 |
Please cite our work if the code is helpful to you.
|
|
@@ -94,8 +94,8 @@ PRESETS: Dict[str, Dict[str, Any]] = {
|
|
| 94 |
"l-dpt_large_depth_mixed": RELEASE_L,
|
| 95 |
}
|
| 96 |
|
| 97 |
-
# the preset names
|
| 98 |
-
#
|
| 99 |
LEGACY_PRESETS: Dict[str, str] = {
|
| 100 |
"l-zs": "l-dpt_large_depth_zeroshot",
|
| 101 |
"l-mix": "l-dpt_large_depth_mixed",
|
|
@@ -117,7 +117,7 @@ DINOV3_SHA256_PREFIX: Dict[str, str] = {
|
|
| 117 |
}
|
| 118 |
|
| 119 |
|
| 120 |
-
TBD = "TBD" # a WeightSource field
|
| 121 |
|
| 122 |
|
| 123 |
@dataclass(frozen=True)
|
|
|
|
| 22 |
WEIGHTS pins the released decoder checkpoints (Hugging Face repo, revision, file,
|
| 23 |
sha256, and the variable naming a local copy); DINOv3 weights are not
|
| 24 |
redistributed: weights.encoder_weights() takes a local file and checks the sha256 prefix
|
| 25 |
+
in its official name. LEGACY_PRESETS maps the short preset names that the published
|
| 26 |
+
release files store ("l-zs", "l-mix") to the current names. This module imports no
|
| 27 |
+
torch.
|
| 28 |
|
| 29 |
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
|
| 30 |
Please cite our work if the code is helpful to you.
|
|
|
|
| 94 |
"l-dpt_large_depth_mixed": RELEASE_L,
|
| 95 |
}
|
| 96 |
|
| 97 |
+
# the short preset names stored in the published release files (their "preset"
|
| 98 |
+
# field): read as the current names, never accepted as a preset
|
| 99 |
LEGACY_PRESETS: Dict[str, str] = {
|
| 100 |
"l-zs": "l-dpt_large_depth_zeroshot",
|
| 101 |
"l-mix": "l-dpt_large_depth_mixed",
|
|
|
|
| 117 |
}
|
| 118 |
|
| 119 |
|
| 120 |
+
TBD = "TBD" # the value of a WeightSource field that is not pinned
|
| 121 |
|
| 122 |
|
| 123 |
@dataclass(frozen=True)
|
ldpt/models/losses/depth.py
CHANGED
|
@@ -135,8 +135,8 @@ def gradient_pyramid(
|
|
| 135 |
Gaussian pyramid: per image and level, the sum of sum_k |kernel_k * R| over the
|
| 136 |
level's mask and the mask's pixel count, ([B, num_scales], [B, num_scales]).
|
| 137 |
|
| 138 |
-
grad_mask="center":
|
| 139 |
-
|
| 140 |
grad_mask="erode": G_k = erode_3x3(M_k) at level k and M_k+1 =
|
| 141 |
AND_2x2(erode_5x5(M_k)), so no invalid pixel (nor the zero padding) ever
|
| 142 |
enters a kernel; R is zeroed off the mask, so the values there cannot matter.
|
|
@@ -167,7 +167,7 @@ def mage_loss(
|
|
| 167 |
) -> Tensor:
|
| 168 |
"""Multi-scale Absolute Gradient Error: Scharr-gradient L1 over a Gaussian pyramid.
|
| 169 |
|
| 170 |
-
grad_mask: "center" (default
|
| 171 |
the residual pred - gt, pooled over the batch's pixels per level)."""
|
| 172 |
if grad_mask != "center":
|
| 173 |
kernels = _scharr_kernels(pred.device, pred.dtype)
|
|
@@ -542,174 +542,90 @@ def weighted_gradient_pyramid(
|
|
| 542 |
|
| 543 |
@LOSSES.register_module("relative_depth_loss")
|
| 544 |
class RelativeDepthLoss(nn.Module):
|
| 545 |
-
"""
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 551 |
loss = MSE + mage_weight * MAGE + male_weight * MALE + lpips_weight * LPIPS.
|
| 552 |
-
MAGE / MALE are multi-scale Scharr / Laplacian L1 terms on the aligned depth
|
| 553 |
-
LPIPS (optional) is computed on the *unaligned*
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
floor does not bind.
|
| 586 |
-
reduction: "pixel" (default: mean over all valid pixels of the batch) or
|
| 587 |
-
"image" (mean per image, then over the images: a sparse image weighs as
|
| 588 |
-
much as a dense one).
|
| 589 |
-
min_valid: images with fewer valid pixels are skipped (fit and every term).
|
| 590 |
-
normalize and reduction apply to the MSE term only: MAGE / MALE stay L1 in metres
|
| 591 |
-
on the aligned depth, pooled over the valid pixels of the batch (weight 0 in the
|
| 592 |
-
L configs); LPIPS is unchanged.
|
| 593 |
-
|
| 594 |
-
Normalised-fit options (research, off by default; need solver="centered"):
|
| 595 |
-
fit_normalized (needs normalize="target_mad"): the target is normalised first,
|
| 596 |
-
g' = (g - median g) / target_mad, and the scale and shift are fitted to g'
|
| 597 |
-
(the same least-squares fit up to rounding, as the fit is affine
|
| 598 |
-
equivariant), so clamp_scale is in units of the target spread: a scale
|
| 599 |
-
s means the prediction's spread is 1 / s of the target's. MAGE / MALE
|
| 600 |
-
then act on the normalised aligned depth (dimensionless, comparable
|
| 601 |
-
across scenes), as the gradient-matching term of MiDaS / DA v2.
|
| 602 |
-
clamp_shift: "stale" (default, as trained) or "refit": the shift of the
|
| 603 |
-
clamped scale (``compute_scale_and_shift2``). With "refit" the loss is
|
| 604 |
-
bounded by the target variance for every image (the clamp only stretches
|
| 605 |
-
a too-flat prediction and asks it to widen), instead of the (s - hi) *
|
| 606 |
-
mean(p) offset that spikes the trained loss to 1e4..1e7 m^2.
|
| 607 |
-
nonpositive="clamp" (needs clamp_scale, clamp_shift="refit"): a degenerate
|
| 608 |
-
fit or a scale <= 0 is clamped to clamp_scale[0] (small, bounded loss),
|
| 609 |
-
no fallback and no drop; the diagnostic ``clamp_frac`` counts the images
|
| 610 |
-
whose least-squares scale was replaced or clamped (either bound).
|
| 611 |
-
Suggested preset: solver="centered", normalize="target_mad",
|
| 612 |
-
fit_normalized=True, clamp_scale=(1e-2, 1e2), clamp_shift="refit",
|
| 613 |
-
nonpositive="clamp", reduction="image", min_valid=1000.
|
| 614 |
-
|
| 615 |
-
Robust-fit options (the normalised fit made robust, a trimmed MAE and MiDaS's
|
| 616 |
-
gradient matching; research, defaults = the least-squares loss; the ``v4_options``
|
| 617 |
-
group):
|
| 618 |
-
detach_fit: True (default, as trained: s, t are constants of the backward)
|
| 619 |
-
or False (needs nonpositive="clamp"): the final s, t are recomputed
|
| 620 |
-
inside autograd from centred fp64 moments of the fitted pixels (the kept
|
| 621 |
-
set and the clamp decision come from the detached fit, so the values
|
| 622 |
-
are the same), as the MiDaS reference loss does. The loss is then
|
| 623 |
-
exactly invariant to an offset and a stretch of each image's prediction
|
| 624 |
-
and so is its gradient: no push along the sigmoid's mean or spread. A
|
| 625 |
-
clamped or replaced scale stays constant, its shift mean g' - s mean p
|
| 626 |
-
stays in the graph (the clamp's widening force). With "mse" the
|
| 627 |
-
data-term gradient is the same either way (envelope theorem); with "l1"
|
| 628 |
-
the detached one is biased by s mean(sign r) / |K| per pixel, which
|
| 629 |
-
narrows the sigmoid on far scenes, so "l1" needs detach_fit=False.
|
| 630 |
-
trim: 0.0 (default) or a fraction in [0, 0.5) (needs solver="centered",
|
| 631 |
-
clamp_shift="refit", nonpositive="clamp"): two-pass trimmed fit. Pass 1
|
| 632 |
-
fits every valid pixel; the k = ceil((1 - trim) N) pixels with the
|
| 633 |
-
smallest relative error |s p + t - g| / g of the aligned depth are kept
|
| 634 |
-
(exactly k, ties at the threshold by pixel order; with fit_normalized
|
| 635 |
-
the error is |s p + t - g'| * spread / g); pass 2 refits on them with
|
| 636 |
-
the same rule, and the data term is the mean over the kept pixels.
|
| 637 |
-
Relative, as the evaluator's trim5: an absolute error in depth would
|
| 638 |
-
mostly drop far, clean pixels. Trimmed pixels get no data-term gradient
|
| 639 |
-
but stay in the gradient-matching term.
|
| 640 |
-
residual: "mse" (default) or "l1" (needs detach_fit=False): the data term.
|
| 641 |
-
"l1" of a flat prediction is mean_K |g' - mean_K g'| <= 2 / (1 - trim)
|
| 642 |
-
in the units of the target spread (typically ~1; a fitted prediction
|
| 643 |
-
scores lower).
|
| 644 |
-
grad_mask: "center" (default, as trained: the pyramid's kernels and blur read
|
| 645 |
-
invalid neighbours, so MAGE / MALE depend on the values of invalid GT
|
| 646 |
-
pixels) or "erode" (3x3 erosion per level, AND_2x2(erode_5x5) between
|
| 647 |
-
levels: no invalid pixel enters a kernel; an image whose level-0 mask
|
| 648 |
-
has fewer than min_valid pixels is left out of the term). Erosion does
|
| 649 |
-
not remove sparse GT that the train Resize upsampled by nearest
|
| 650 |
-
replication (a KITTI LiDAR return becomes a block of pixels): use
|
| 651 |
-
grad_exclude for such datasets.
|
| 652 |
grad_reduction: "pixel" (default: MAGE / MALE pooled over the batch's pixels
|
| 653 |
-
per level) or "image" (per image, then the mean over the images
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
over the valid pixels (fp32): ``logit_mean`` / ``logit_std`` (median
|
| 674 |
-
over the images of the per-image mean / std) and ``logit_absmax`` (max |z|
|
| 675 |
-
of the batch).
|
| 676 |
-
|
| 677 |
-
The L-DPT depth loss (align="roe", docs/depth_loss.md; default "lsq" = everything
|
| 678 |
-
above):
|
| 679 |
-
MoGe's objective on an exponential head: per image an exact ROE fit
|
| 680 |
-
(truncated 1/z-weighted L1, ``roe_fit_sample``) on roe_points sampled valid
|
| 681 |
-
pixels, a trim per label type, one weighted least-squares refit inside
|
| 682 |
-
autograd (fp64), the global term (mean 1/z-weighted error of the kept
|
| 683 |
-
pixels, weights min(1 / g, weight_cap / h), h the harmonic-mean depth), local
|
| 684 |
-
shift terms per label type over rotated image cells x log-depth bins, and a
|
| 685 |
-
1/z-weighted gradient term on grad_types. Every image weighs the same; the
|
| 686 |
-
rank's loss is depth_loss + aux_scale * (local_weight * local_loss +
|
| 687 |
-
mage_weight * mage_loss). Options: head ("sigmoid" | "exp", diagnostics
|
| 688 |
-
only), roe_points (>= 16), roe_trunc (> 0), weight_cap (> 1), refit_floor
|
| 689 |
-
(> 0), label_types (required: dict type -> sample-name prefixes, needs the
|
| 690 |
-
names), type_trim (dict over every type, [0, 0.5)), local_levels (dict type
|
| 691 |
-
-> positive alphas), local_weight, local_cell (pixels of a cell at alpha =
|
| 692 |
-
1), local_pred_ratio (probability of the prediction as the bin reference),
|
| 693 |
-
grad_types, aux_scale (the warm-up's key; 0: local and gradient terms under
|
| 694 |
-
no_grad, logged only). align="roe" raises if an alignment / term option of
|
| 695 |
-
the "lsq" family is off its default; align="lsq" raises if one of these is.
|
| 696 |
-
Keys:
|
| 697 |
-
ROE_KEYS (+ the logit stats, log(p) with head="exp").
|
| 698 |
-
|
| 699 |
-
The dict also holds detached diagnostics (logged by InformationWriter like the
|
| 700 |
-
losses, per rank), which change neither the loss nor its gradient:
|
| 701 |
-
``fallback_frac`` (nonpositive="fallback"), ``drop_frac`` ("drop") or
|
| 702 |
-
``clamp_frac`` ("clamp"), the fraction of the batch's images whose least-squares
|
| 703 |
-
fit was rejected (or clamped), and ``depth_loss_max``, the largest per-image data
|
| 704 |
-
term (normalised with normalize; a heuristic, not a bound: a flat prediction on
|
| 705 |
-
a bimodal scene reaches ~1.3, at most 2 / (1 - trim) with "l1"). With a robust-fit
|
| 706 |
-
option (any of detach_fit, trim, residual, grad_mask, grad_reduction,
|
| 707 |
-
grad_exclude off its default) also ``scale_median`` (median fitted scale s_i),
|
| 708 |
-
``spread_median`` (median per-image std of the prediction over its valid
|
| 709 |
-
pixels), ``saturation_frac`` (valid pixels with p < 0.0025 or p > 0.9975, i.e.
|
| 710 |
-
|logit| > 6), ``gm_image_frac`` (share of the batch's images in the
|
| 711 |
-
gradient-matching term) and, with trim > 0, ``trim_thresh_median`` (median
|
| 712 |
-
pass-1 trim threshold: the relative error of the aligned depth at rank k).
|
| 713 |
|
| 714 |
Shapes:
|
| 715 |
pred, target, mask: [B, 1, H, W] or [B, H, W] -> dict of scalar losses
|
|
@@ -952,7 +868,7 @@ class RelativeDepthLoss(nn.Module):
|
|
| 952 |
|
| 953 |
@staticmethod
|
| 954 |
def _v4_off_default(**options) -> List[str]:
|
| 955 |
-
"""Names of the
|
| 956 |
defaults = dict(
|
| 957 |
solver="sum",
|
| 958 |
nonpositive="fallback",
|
|
@@ -1227,7 +1143,7 @@ class RelativeDepthLoss(nn.Module):
|
|
| 1227 |
rel = res / torch.where(mask, depth, 1.0)
|
| 1228 |
keep = torch.zeros_like(mask)
|
| 1229 |
thresh = res.new_zeros(pred.shape[0])
|
| 1230 |
-
for b in range(pred.shape[0]): #
|
| 1231 |
e = rel[b][mask[b]]
|
| 1232 |
keep[b][mask[b]], thresh[b] = smallest_k(e, num_kept(e.numel(), self.trim))
|
| 1233 |
return keep, thresh
|
|
@@ -1241,7 +1157,7 @@ class RelativeDepthLoss(nn.Module):
|
|
| 1241 |
and self.residual == "mse"
|
| 1242 |
and keep is None
|
| 1243 |
):
|
| 1244 |
-
# the
|
| 1245 |
depth_loss = F.mse_loss(pred[mask], target[mask], reduction="mean")
|
| 1246 |
with torch.no_grad():
|
| 1247 |
sq = torch.where(mask, (pred - target).square(), 0.0).flatten(1)
|
|
@@ -1270,7 +1186,7 @@ class RelativeDepthLoss(nn.Module):
|
|
| 1270 |
self, kind, pred, target, mask, allowed=None
|
| 1271 |
) -> Tuple[Tensor, Optional[Tensor]]:
|
| 1272 |
"""MAGE or MALE of the aligned prediction and the images [B] that take part
|
| 1273 |
-
(None on the
|
| 1274 |
pixels (with grad_mask="center" every fitted image has enough) or not
|
| 1275 |
allowed (grad_exclude) take no part."""
|
| 1276 |
if (
|
|
@@ -1278,7 +1194,7 @@ class RelativeDepthLoss(nn.Module):
|
|
| 1278 |
and self.grad_reduction == "pixel"
|
| 1279 |
and allowed is None
|
| 1280 |
):
|
| 1281 |
-
#
|
| 1282 |
if kind == "mage":
|
| 1283 |
value = mage_loss(
|
| 1284 |
pred, target, mask, num_scales=self.mage_num_scales, eps=self.eps
|
|
|
|
| 135 |
Gaussian pyramid: per image and level, the sum of sum_k |kernel_k * R| over the
|
| 136 |
level's mask and the mask's pixel count, ([B, num_scales], [B, num_scales]).
|
| 137 |
|
| 138 |
+
grad_mask="center": a pixel counts when it is valid (_down2_mask between levels);
|
| 139 |
+
invalid neighbours enter the kernels and the blur;
|
| 140 |
grad_mask="erode": G_k = erode_3x3(M_k) at level k and M_k+1 =
|
| 141 |
AND_2x2(erode_5x5(M_k)), so no invalid pixel (nor the zero padding) ever
|
| 142 |
enters a kernel; R is zeroed off the mask, so the values there cannot matter.
|
|
|
|
| 167 |
) -> Tensor:
|
| 168 |
"""Multi-scale Absolute Gradient Error: Scharr-gradient L1 over a Gaussian pyramid.
|
| 169 |
|
| 170 |
+
grad_mask: "center" (default) or "erode" (see gradient_pyramid; on
|
| 171 |
the residual pred - gt, pooled over the batch's pixels per level)."""
|
| 172 |
if grad_mask != "center":
|
| 173 |
kernels = _scharr_kernels(pred.device, pred.dtype)
|
|
|
|
| 542 |
|
| 543 |
@LOSSES.register_module("relative_depth_loss")
|
| 544 |
class RelativeDepthLoss(nn.Module):
|
| 545 |
+
"""Relative depth loss: the prediction, defined up to a scale and a shift per
|
| 546 |
+
image, is aligned to the ground truth and compared with it. Two families, chosen
|
| 547 |
+
by ``align``; both run in fp32 with autocast off, whatever the caller's precision
|
| 548 |
+
(fp32 inputs are used as they are), and skip images with fewer than ``min_valid``
|
| 549 |
+
valid pixels.
|
| 550 |
+
|
| 551 |
+
align="roe": the L-DPT depth loss, the loss of the released depth models
|
| 552 |
+
(configs/hybrid/*.py); docs/depth_loss.md is its specification. Per image: an
|
| 553 |
+
exact ROE fit (truncated 1/z-weighted L1, ``roe_fit_sample``) on roe_points
|
| 554 |
+
sampled valid pixels, a trim per label type, one weighted least-squares refit
|
| 555 |
+
inside autograd (fp64), the global term (mean 1/z-weighted error of the kept
|
| 556 |
+
pixels, weights min(1 / g, weight_cap / h), h the harmonic-mean depth), local
|
| 557 |
+
shift terms per label type over rotated image cells x log-depth bins, and a
|
| 558 |
+
1/z-weighted gradient term on grad_types. Every image weighs the same;
|
| 559 |
+
loss = depth_loss + aux_scale * (local_weight * local_loss
|
| 560 |
+
+ mage_weight * mage_loss).
|
| 561 |
+
Options: head ("sigmoid" | "exp": the model's head; it only selects the logged
|
| 562 |
+
logit statistics), roe_points (>= 16), roe_trunc (> 0), weight_cap (> 1),
|
| 563 |
+
refit_floor (> 0), label_types (required: dict type -> sample-name prefixes; the
|
| 564 |
+
model passes the batch's names), type_trim (dict over every type, values in
|
| 565 |
+
[0, 0.5)), local_levels (dict type -> positive integers alpha), local_weight,
|
| 566 |
+
local_cell (pixels of a cell at alpha = 1), local_pred_ratio (probability that
|
| 567 |
+
the prediction is the bin reference), grad_types, aux_scale (set by
|
| 568 |
+
CriterionWeightWarmup; at 0 the local and gradient terms run under no_grad and
|
| 569 |
+
are logged only). The returned keys are ROE_KEYS.
|
| 570 |
+
|
| 571 |
+
align="lsq" (the default): an affine-invariant least-squares loss. Per image a
|
| 572 |
+
closed-form least-squares scale and shift in *depth* space (no gradient through
|
| 573 |
+
the fit, ``compute_scale_and_shift``), then
|
| 574 |
loss = MSE + mage_weight * MAGE + male_weight * MALE + lpips_weight * LPIPS.
|
| 575 |
+
MAGE / MALE are multi-scale Scharr / Laplacian L1 terms on the aligned depth;
|
| 576 |
+
LPIPS (optional, needs the lpips package) is computed on the *unaligned*
|
| 577 |
+
prediction. The default options are pinned bit for bit by tests/test_depth_loss.py
|
| 578 |
+
and tests/test_l_dpt_golden.py; every other value below is opt-in.
|
| 579 |
+
solver: "sum" (default: one-pass fp32 sums) or "centered" (centred fp64
|
| 580 |
+
moments, ``compute_scale_and_shift2``: no cancellation for a
|
| 581 |
+
near-constant prediction).
|
| 582 |
+
clamp_scale: (lo, hi), default (1e-3, 1e3), or None (no clamp).
|
| 583 |
+
clamp_shift: "stale" (default: the shift of the *unclamped* scale, which
|
| 584 |
+
moves a clamped image off its target) or "refit" (the least-squares
|
| 585 |
+
shift of the clamped scale; needs solver="centered").
|
| 586 |
+
nonpositive: a degenerate fit or a scale <= 0 gets "fallback" (default:
|
| 587 |
+
median / MAD matching), "drop" (the image adds no loss) or "clamp"
|
| 588 |
+
(scale = clamp_scale[0]; needs clamp_scale and clamp_shift="refit").
|
| 589 |
+
normalize: None (default: MSE in metres) or "target_mad": residuals divided
|
| 590 |
+
per image by ``target_mad``, so the MSE does not grow with the depth range.
|
| 591 |
+
fit_normalized (needs normalize="target_mad", solver="centered"): the fit is
|
| 592 |
+
made on the normalised target (g - median g) / target_mad, so clamp_scale
|
| 593 |
+
is in units of the target spread; MAGE / MALE act on that depth too.
|
| 594 |
+
reduction: "pixel" (default: mean over the valid pixels of the batch) or
|
| 595 |
+
"image" (mean per image, then over the images); MSE term only.
|
| 596 |
+
detach_fit: True (default: scale and shift are constants of the backward) or
|
| 597 |
+
False (they are recomputed inside autograd, as in MiDaS's loss, so the
|
| 598 |
+
loss and its gradient are invariant to an offset and a stretch of the
|
| 599 |
+
prediction; needs nonpositive="clamp").
|
| 600 |
+
trim: 0.0 (default) or a fraction in [0, 0.5): a two-pass fit that keeps the
|
| 601 |
+
ceil((1 - trim) N) pixels with the smallest relative error of the
|
| 602 |
+
aligned depth (``trim_mask``); needs solver="centered",
|
| 603 |
+
clamp_shift="refit", nonpositive="clamp".
|
| 604 |
+
residual: the data term, "mse" (default) or "l1" (needs detach_fit=False).
|
| 605 |
+
grad_mask: "center" (default: a valid pixel counts, so invalid neighbours
|
| 606 |
+
enter the kernels and the blur) or "erode" (no invalid pixel enters a
|
| 607 |
+
kernel, see ``gradient_pyramid``).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 608 |
grad_reduction: "pixel" (default: MAGE / MALE pooled over the batch's pixels
|
| 609 |
+
per level) or "image" (per image, then the mean over the images).
|
| 610 |
+
grad_exclude: sample-name prefixes (the part before "/", e.g. ["kitti"]):
|
| 611 |
+
images of these datasets take no part in MAGE / MALE (sparse ground
|
| 612 |
+
truth that Resize turns into blocks); needs the batch's names.
|
| 613 |
+
MAGE is the mean over its levels of each level's mean |Scharr / 32 * R|; MiDaS
|
| 614 |
+
sums its K levels and halves its data term, so MiDaS's alpha = 0.5 corresponds
|
| 615 |
+
to mage_weight = 0.5 * 4 * 2 = 4 here.
|
| 616 |
+
align="roe" raises when an option of the "lsq" family (male_weight and
|
| 617 |
+
lpips_weight included) is off its default, and align="lsq" raises when an option
|
| 618 |
+
of align="roe" is.
|
| 619 |
+
|
| 620 |
+
log_logit_stats=True also logs ``logit_mean`` / ``logit_std`` / ``logit_absmax``
|
| 621 |
+
of the head's logit over the valid pixels (logit(p), or log(p) with head="exp").
|
| 622 |
+
The dict also holds detached diagnostics, logged like the losses and without
|
| 623 |
+
effect on the gradient: ``fallback_frac`` / ``drop_frac`` / ``clamp_frac`` (the
|
| 624 |
+
share of the batch's images whose fit was rejected or clamped),
|
| 625 |
+
``depth_loss_max`` (the largest per-image data term) and, when detach_fit, trim,
|
| 626 |
+
residual, grad_mask, grad_reduction or grad_exclude is off its default,
|
| 627 |
+
``scale_median``, ``spread_median``, ``saturation_frac``, ``gm_image_frac`` and
|
| 628 |
+
(trim > 0) ``trim_thresh_median``.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 629 |
|
| 630 |
Shapes:
|
| 631 |
pred, target, mask: [B, 1, H, W] or [B, H, W] -> dict of scalar losses
|
|
|
|
| 868 |
|
| 869 |
@staticmethod
|
| 870 |
def _v4_off_default(**options) -> List[str]:
|
| 871 |
+
"""Names of the align="lsq" options that are off their default."""
|
| 872 |
defaults = dict(
|
| 873 |
solver="sum",
|
| 874 |
nonpositive="fallback",
|
|
|
|
| 1143 |
rel = res / torch.where(mask, depth, 1.0)
|
| 1144 |
keep = torch.zeros_like(mask)
|
| 1145 |
thresh = res.new_zeros(pred.shape[0])
|
| 1146 |
+
for b in range(pred.shape[0]): # the per-GPU batch is small: a short loop
|
| 1147 |
e = rel[b][mask[b]]
|
| 1148 |
keep[b][mask[b]], thresh[b] = smallest_k(e, num_kept(e.numel(), self.trim))
|
| 1149 |
return keep, thresh
|
|
|
|
| 1157 |
and self.residual == "mse"
|
| 1158 |
and keep is None
|
| 1159 |
):
|
| 1160 |
+
# the default path, kept bit-identical; per-image values only for logging
|
| 1161 |
depth_loss = F.mse_loss(pred[mask], target[mask], reduction="mean")
|
| 1162 |
with torch.no_grad():
|
| 1163 |
sq = torch.where(mask, (pred - target).square(), 0.0).flatten(1)
|
|
|
|
| 1186 |
self, kind, pred, target, mask, allowed=None
|
| 1187 |
) -> Tuple[Tensor, Optional[Tensor]]:
|
| 1188 |
"""MAGE or MALE of the aligned prediction and the images [B] that take part
|
| 1189 |
+
(None on the default path). Images with fewer than min_valid level-0 mask
|
| 1190 |
pixels (with grad_mask="center" every fitted image has enough) or not
|
| 1191 |
allowed (grad_exclude) take no part."""
|
| 1192 |
if (
|
|
|
|
| 1194 |
and self.grad_reduction == "pixel"
|
| 1195 |
and allowed is None
|
| 1196 |
):
|
| 1197 |
+
# the default path, kept bit-identical
|
| 1198 |
if kind == "mage":
|
| 1199 |
value = mage_loss(
|
| 1200 |
pred, target, mask, num_scales=self.mage_num_scales, eps=self.eps
|
ldpt/models/utils/depth.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
"""
|
| 2 |
Depth alignment utilities
|
| 3 |
|
| 4 |
-
Per-image least
|
| 5 |
-
the GT
|
|
|
|
| 6 |
|
| 7 |
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
|
| 8 |
Please cite our work if the code is helpful to you.
|
|
@@ -75,11 +76,14 @@ def compute_scale_and_shift(
|
|
| 75 |
"""Least-squares (scale, shift, valid) per image, from one-pass sums in pred dtype.
|
| 76 |
|
| 77 |
Images whose fit is degenerate or gives scale <= 0 fall back to median / MAD
|
| 78 |
-
matching.
|
|
|
|
|
|
|
| 79 |
|
| 80 |
clamp_scale: (lo, hi) clamp of the scale (None: no clamp). The shift of a clamped
|
| 81 |
-
least-squares fit stays the shift of the unclamped scale
|
| 82 |
-
|
|
|
|
| 83 |
nonpositive: "fallback" (median / MAD matching, default) or "drop": images whose
|
| 84 |
fit is degenerate or gives scale <= 0 get valid=False (scale / shift NaN).
|
| 85 |
("clamp" exists only in compute_scale_and_shift2.)
|
|
@@ -178,7 +182,7 @@ def compute_scale_and_shift2(
|
|
| 178 |
clamp_scale, nonpositive and return_unfit as in compute_scale_and_shift.
|
| 179 |
Degenerate: var(p) <= eps (sum over the valid pixels).
|
| 180 |
|
| 181 |
-
clamp_shift: "stale" (default
|
| 182 |
so a clamped image is moved off its target by (s - s_clamped) * mean(p);
|
| 183 |
"refit": shift = mean(g) - s_clamped * mean(p), the least-squares shift for the
|
| 184 |
clamped scale (the residual keeps a zero mean; the loss is then the plain MSE
|
|
@@ -236,7 +240,7 @@ def compute_scale_and_shift2(
|
|
| 236 |
s = cov_pg / denom
|
| 237 |
t = mean_g - s * mean_p
|
| 238 |
|
| 239 |
-
#
|
| 240 |
solvable = (var_p > eps) & (s > 0)
|
| 241 |
vidx = torch.where(valid)[0]
|
| 242 |
unfit = torch.zeros_like(valid)
|
|
@@ -318,6 +322,42 @@ def nonneg_lsq_scale_and_shift(pred, target, mask, min_valid: int = 10):
|
|
| 318 |
return scale, shift, valid, rejected
|
| 319 |
|
| 320 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
def _median(x: Tensor) -> Tensor:
|
| 322 |
"""np.median of a 1-D tensor: the mean of the two middle values for an even count
|
| 323 |
(torch.median takes the lower one)."""
|
|
@@ -634,21 +674,22 @@ def roe_fit_sample(
|
|
| 634 |
) -> Tuple[Tensor, Tensor, bool]:
|
| 635 |
"""ROE fit of one image's sampled pixels (prediction x, target y, weights w,
|
| 636 |
1-D) on conditioned inputs (docs/depth_loss.md section 4.1): in fp64,
|
| 637 |
-
x' = (x - median x) /
|
| 638 |
-
|
|
|
|
| 639 |
s = s' h / spread, t = h t' - s median. Equal in exact arithmetic (the objective is
|
| 640 |
equivariant), and the 1e-7 guards of the search stay meaningful for any offset of
|
| 641 |
x.
|
| 642 |
-
Returns (s, t, ok): fp64 0-d tensors, ok False for a constant x (
|
| 643 |
-
|
| 644 |
0, t = y: the horizontal optimum, found without the search), a support pair
|
| 645 |
closer than 1e-6 in conditioned x (s = 0), a non-finite result or s <= 0."""
|
| 646 |
x, y, w = x.double(), y.double(), w.double()
|
| 647 |
h = torch.as_tensor(h, dtype=torch.float64, device=x.device)
|
| 648 |
med = x.median()
|
| 649 |
-
# robust spread
|
| 650 |
-
#
|
| 651 |
-
#
|
| 652 |
dev = (x - med).abs()
|
| 653 |
spread = dev.median()
|
| 654 |
if not bool(spread > 0):
|
|
@@ -663,11 +704,11 @@ def roe_fit_sample(
|
|
| 663 |
return torch.zeros_like(nan), h * ys[0], False
|
| 664 |
# A sample whose conditioned x spans more than 1e4 (one extreme logit, say)
|
| 665 |
# would swamp the search's cumulative sums in fp32; such rare samples are
|
| 666 |
-
# searched in fp64
|
| 667 |
dt = search_dtype if bool(xs.abs().max() <= 1e4) else torch.float64
|
| 668 |
i1, i2 = _roe_support(xs.to(dt), ys.to(dt), ws.to(dt), trunc)
|
| 669 |
# (s', t') from the two support points, in fp64 on the conditioned values. A
|
| 670 |
-
# pair closer than 1e-6 in x (units of the
|
| 671 |
# any real slope's support; an exact tie in the search dtype is returned as
|
| 672 |
# i2 = i1 by _roe_support) is a horizontal line: s' = 0, the image is dropped.
|
| 673 |
x1, x2, y1, y2 = xs[i1], xs[i2], ys[i1], ys[i2]
|
|
|
|
| 1 |
"""
|
| 2 |
Depth alignment utilities
|
| 3 |
|
| 4 |
+
Per-image affine alignment (least squares, trimmed, RANSAC, ROE) of a relative depth
|
| 5 |
+
prediction to the GT, used by relative_depth_loss, the depth evaluator and the
|
| 6 |
+
visualizer.
|
| 7 |
|
| 8 |
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
|
| 9 |
Please cite our work if the code is helpful to you.
|
|
|
|
| 76 |
"""Least-squares (scale, shift, valid) per image, from one-pass sums in pred dtype.
|
| 77 |
|
| 78 |
Images whose fit is degenerate or gives scale <= 0 fall back to median / MAD
|
| 79 |
+
matching. The solver of relative_depth_loss(align="lsq", solver="sum") and of the
|
| 80 |
+
evaluator's align_solver="sum"; the L-DPT depth loss (align="roe") uses
|
| 81 |
+
roe_fit_sample instead.
|
| 82 |
|
| 83 |
clamp_scale: (lo, hi) clamp of the scale (None: no clamp). The shift of a clamped
|
| 84 |
+
least-squares fit stays the shift of the unclamped scale, so a clamped image
|
| 85 |
+
is not the best fit for its clamped scale (compute_scale_and_shift2 with
|
| 86 |
+
clamp_shift="refit" refits it).
|
| 87 |
nonpositive: "fallback" (median / MAD matching, default) or "drop": images whose
|
| 88 |
fit is degenerate or gives scale <= 0 get valid=False (scale / shift NaN).
|
| 89 |
("clamp" exists only in compute_scale_and_shift2.)
|
|
|
|
| 182 |
clamp_scale, nonpositive and return_unfit as in compute_scale_and_shift.
|
| 183 |
Degenerate: var(p) <= eps (sum over the valid pixels).
|
| 184 |
|
| 185 |
+
clamp_shift: "stale" (default): the shift of the *unclamped* scale,
|
| 186 |
so a clamped image is moved off its target by (s - s_clamped) * mean(p);
|
| 187 |
"refit": shift = mean(g) - s_clamped * mean(p), the least-squares shift for the
|
| 188 |
clamped scale (the residual keeps a zero mean; the loss is then the plain MSE
|
|
|
|
| 240 |
s = cov_pg / denom
|
| 241 |
t = mean_g - s * mean_p
|
| 242 |
|
| 243 |
+
# a depth-like quantity needs a positive scale: s <= 0 counts as unsolvable
|
| 244 |
solvable = (var_p > eps) & (s > 0)
|
| 245 |
vidx = torch.where(valid)[0]
|
| 246 |
unfit = torch.zeros_like(valid)
|
|
|
|
| 322 |
return scale, shift, valid, rejected
|
| 323 |
|
| 324 |
|
| 325 |
+
@torch.no_grad()
|
| 326 |
+
def free_lsq_scale_and_shift(pred, target, mask, min_valid: int = 10):
|
| 327 |
+
"""Exact least squares with no constraint on the scale, Marigold's evaluation
|
| 328 |
+
fit (src/util/alignment.py align_depth_least_square: np.linalg.lstsq of the
|
| 329 |
+
target on [pred, 1] over the valid pixels). (scale, shift, valid, signed) [B]:
|
| 330 |
+
nonneg_lsq_scale_and_shift where it fits (bit for bit), and where it rejects the
|
| 331 |
+
fit the unconstrained optimum in fp64 (centered moments): a scale <= 0 is kept,
|
| 332 |
+
and a flat prediction (var(p) <= 1e-6) gets s = 0, t = mean GT, the aligned
|
| 333 |
+
prediction of lstsq's minimum-norm solution for a constant prediction. valid is
|
| 334 |
+
False only for < min_valid pixels; signed marks the images where this differs
|
| 335 |
+
from the non-negative fit. The evaluator's align_solver="lsq_free"."""
|
| 336 |
+
scale, shift, valid, signed = nonneg_lsq_scale_and_shift(
|
| 337 |
+
pred, target, mask, min_valid
|
| 338 |
+
)
|
| 339 |
+
if signed.any():
|
| 340 |
+
idx = torch.where(signed)[0]
|
| 341 |
+
m = mask[idx].flatten(1)
|
| 342 |
+
w = m.double()
|
| 343 |
+
p = pred[idx].flatten(1).double()
|
| 344 |
+
g = torch.where(m, target[idx].flatten(1).double(), 0.0)
|
| 345 |
+
n = w.sum(dim=1)
|
| 346 |
+
mean_p = (p * w).sum(dim=1) / n
|
| 347 |
+
mean_g = (g * w).sum(dim=1) / n
|
| 348 |
+
dp = p - mean_p.unsqueeze(1)
|
| 349 |
+
dg = g - mean_g.unsqueeze(1)
|
| 350 |
+
var_p = (dp * dp * w).sum(dim=1)
|
| 351 |
+
cov = (dp * dg * w).sum(dim=1)
|
| 352 |
+
s = torch.where(var_p > 1e-6, cov / var_p, torch.zeros_like(cov))
|
| 353 |
+
t = mean_g - s * mean_p
|
| 354 |
+
scale = scale.clone()
|
| 355 |
+
shift = shift.clone()
|
| 356 |
+
scale[idx] = s.to(scale.dtype)
|
| 357 |
+
shift[idx] = t.to(shift.dtype)
|
| 358 |
+
return scale, shift, valid, signed
|
| 359 |
+
|
| 360 |
+
|
| 361 |
def _median(x: Tensor) -> Tensor:
|
| 362 |
"""np.median of a 1-D tensor: the mean of the two middle values for an even count
|
| 363 |
(torch.median takes the lower one)."""
|
|
|
|
| 674 |
) -> Tuple[Tensor, Tensor, bool]:
|
| 675 |
"""ROE fit of one image's sampled pixels (prediction x, target y, weights w,
|
| 676 |
1-D) on conditioned inputs (docs/depth_loss.md section 4.1): in fp64,
|
| 677 |
+
x' = (x - median x) / spread, spread = median |x - median x| (the mean where the
|
| 678 |
+
median is 0), y' = y / h, w' = w h (h: the image's depth unit, the harmonic-mean
|
| 679 |
+
depth), the search in `search_dtype`, then
|
| 680 |
s = s' h / spread, t = h t' - s median. Equal in exact arithmetic (the objective is
|
| 681 |
equivariant), and the 1e-7 guards of the search stay meaningful for any offset of
|
| 682 |
x.
|
| 683 |
+
Returns (s, t, ok): fp64 0-d tensors, ok False for a constant x (spread <=
|
| 684 |
+
1e-12 max(|median|, 1e-30); s, t NaN), a constant sampled y (s =
|
| 685 |
0, t = y: the horizontal optimum, found without the search), a support pair
|
| 686 |
closer than 1e-6 in conditioned x (s = 0), a non-finite result or s <= 0."""
|
| 687 |
x, y, w = x.double(), y.double(), w.double()
|
| 688 |
h = torch.as_tensor(h, dtype=torch.float64, device=x.device)
|
| 689 |
med = x.median()
|
| 690 |
+
# robust spread: the median absolute deviation, so one extreme sampled d cannot
|
| 691 |
+
# push every other point under the search's 1e-7 guards; the mean absolute
|
| 692 |
+
# deviation where more than half of x equals the median
|
| 693 |
dev = (x - med).abs()
|
| 694 |
spread = dev.median()
|
| 695 |
if not bool(spread > 0):
|
|
|
|
| 704 |
return torch.zeros_like(nan), h * ys[0], False
|
| 705 |
# A sample whose conditioned x spans more than 1e4 (one extreme logit, say)
|
| 706 |
# would swamp the search's cumulative sums in fp32; such rare samples are
|
| 707 |
+
# searched in fp64.
|
| 708 |
dt = search_dtype if bool(xs.abs().max() <= 1e4) else torch.float64
|
| 709 |
i1, i2 = _roe_support(xs.to(dt), ys.to(dt), ws.to(dt), trunc)
|
| 710 |
# (s', t') from the two support points, in fp64 on the conditioned values. A
|
| 711 |
+
# pair closer than 1e-6 in x (units of the spread, so far below
|
| 712 |
# any real slope's support; an exact tie in the search dtype is returned as
|
| 713 |
# i2 = i1 by _roe_support) is a horizontal line: s' = 0, the image is dropped.
|
| 714 |
x1, x2, y1, y2 = xs[i1], xs[i2], ys[i1], ys[i2]
|
ldpt/utils/sdpa.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
The order in which PyTorch tries its scaled-dot-product attention backends: the context
|
| 3 |
+
the trainer runs each step in (``cfg.sdpa_backends``, unset: PyTorch's order) and
|
| 4 |
+
``api.predict`` runs the model in (``sdpa_backends=``, default SDPA_ORDER).
|
| 5 |
+
|
| 6 |
+
from ldpt.utils.sdpa import SDPA_ORDER, sdpa_context
|
| 7 |
+
|
| 8 |
+
with sdpa_context(SDPA_ORDER): # cuDNN attention first
|
| 9 |
+
y = model(x)
|
| 10 |
+
|
| 11 |
+
SDPA_ORDER puts cuDNN attention first: on an NVIDIA GB200 it is the fastest kernel for
|
| 12 |
+
the bf16 attention of L-DPT. PyTorch's own order (torch 2.8: FlashAttention,
|
| 13 |
+
memory-efficient, math, cuDNN) is what evaluation runs (scripts/evaluate.py, the
|
| 14 |
+
evaluator hooks). The kernels compute the same attention, so the order changes the
|
| 15 |
+
output only at the rounding level. A backend the device, the dtype or the shapes cannot
|
| 16 |
+
use is skipped (fp32 attention has neither a cuDNN nor a FlashAttention kernel; on the
|
| 17 |
+
CPU and Apple MPS the order changes nothing). Needs torch only.
|
| 18 |
+
|
| 19 |
+
Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
|
| 20 |
+
Please cite our work if the code is helpful to you.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
import contextlib
|
| 24 |
+
from typing import ContextManager, Sequence, Union
|
| 25 |
+
|
| 26 |
+
__all__ = ["SDPA_BACKENDS", "SDPA_ORDER", "sdpa_context"]
|
| 27 |
+
|
| 28 |
+
# name -> torch.nn.attention.SDPBackend member
|
| 29 |
+
SDPA_BACKENDS = dict(
|
| 30 |
+
cudnn="CUDNN_ATTENTION",
|
| 31 |
+
flash="FLASH_ATTENTION",
|
| 32 |
+
efficient="EFFICIENT_ATTENTION",
|
| 33 |
+
math="MATH",
|
| 34 |
+
)
|
| 35 |
+
SDPA_ORDER = ("cudnn", "flash", "efficient", "math")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def sdpa_context(
|
| 39 |
+
backends: Union[Sequence[str], str, None] = None,
|
| 40 |
+
) -> ContextManager:
|
| 41 |
+
"""A context that tries the scaled-dot-product attention backends in the order of
|
| 42 |
+
``backends`` (names of SDPA_BACKENDS; one name or a list), the others disabled, and
|
| 43 |
+
restores the previous state on exit (torch's process-wide SDPA flags). None or an
|
| 44 |
+
empty list keeps PyTorch's choice (flash, mem-efficient, math, cuDNN in torch
|
| 45 |
+
2.8). An unknown name raises ValueError here, before the context is entered."""
|
| 46 |
+
if isinstance(backends, str):
|
| 47 |
+
backends = [backends]
|
| 48 |
+
if not backends:
|
| 49 |
+
return contextlib.nullcontext()
|
| 50 |
+
unknown = [b for b in backends if b not in SDPA_BACKENDS]
|
| 51 |
+
if unknown:
|
| 52 |
+
raise ValueError(
|
| 53 |
+
f"sdpa_backends: unknown {unknown}, choose from {list(SDPA_BACKENDS)}"
|
| 54 |
+
)
|
| 55 |
+
from torch.nn.attention import SDPBackend, sdpa_kernel
|
| 56 |
+
|
| 57 |
+
order = [getattr(SDPBackend, SDPA_BACKENDS[b]) for b in backends]
|
| 58 |
+
return sdpa_kernel(order, set_priority=True)
|
space_utils.py
CHANGED
|
@@ -19,8 +19,9 @@ models.json:
|
|
| 19 |
A source whose repo, filename or revision contains "TODO" is not published yet.
|
| 20 |
$LDPT_CKPT_<NAME> names a local release file that replaces the source (not
|
| 21 |
hashed): NAME is the id without "l-dpt_", upper-cased, other characters -> "_",
|
| 22 |
-
the variable api.load reads for a preset (LDPT_CKPT_LARGE_DEPTH_ZEROSHOT);
|
| 23 |
-
|
|
|
|
| 24 |
|
| 25 |
Release files come from `python -m ldpt.models.l_dpt.convert SRC DST --preset
|
| 26 |
l-dpt_large_depth_zeroshot` (or `--config <the run's config.py>`); they carry the model
|
|
@@ -332,7 +333,7 @@ class ModelEntry:
|
|
| 332 |
|
| 333 |
@property
|
| 334 |
def legacy_env(self) -> str:
|
| 335 |
-
"""
|
| 336 |
return "LDPT_MODEL_" + re.sub(r"[^A-Z0-9]", "_", self.id.upper())
|
| 337 |
|
| 338 |
@property
|
|
|
|
| 19 |
A source whose repo, filename or revision contains "TODO" is not published yet.
|
| 20 |
$LDPT_CKPT_<NAME> names a local release file that replaces the source (not
|
| 21 |
hashed): NAME is the id without "l-dpt_", upper-cased, other characters -> "_",
|
| 22 |
+
the variable api.load reads for a preset (LDPT_CKPT_LARGE_DEPTH_ZEROSHOT);
|
| 23 |
+
$LDPT_MODEL_<ID> (LDPT_MODEL_L_DPT_LARGE_DEPTH_ZEROSHOT) is a second name, read
|
| 24 |
+
after it.
|
| 25 |
|
| 26 |
Release files come from `python -m ldpt.models.l_dpt.convert SRC DST --preset
|
| 27 |
l-dpt_large_depth_zeroshot` (or `--config <the run's config.py>`); they carry the model
|
|
|
|
| 333 |
|
| 334 |
@property
|
| 335 |
def legacy_env(self) -> str:
|
| 336 |
+
"""A second variable for the same file (LDPT_MODEL_<ID>), read after ``env``."""
|
| 337 |
return "LDPT_MODEL_" + re.sub(r"[^A-Z0-9]", "_", self.id.upper())
|
| 338 |
|
| 339 |
@property
|