pointcept-bot commited on
Commit
d8a5268
·
verified ·
1 Parent(s): c188325

cuDNN-first attention in api.predict; review fixes; unified evaluation code

Browse files
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](<GITHUB_URL>) ] [ [Weights](https://huggingface.co/pointcept-bot/L-DPT) ] [ [Training data](https://huggingface.co/datasets/pointcept-bot/DepthHybrid) ]
20
 
21
  Upload a photo and get its relative depth from L-DPT Large (zero-shot), computed on every
22
- pixel of the photo, up to 100 MP (uploads 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. Each request reserves some
30
- margin above that from your daily ZeroGPU quota (990 s for a 100 MP photo, more than a
31
- free account has), so large photos may need a Hugging Face PRO account here; the local
32
- app below has no such limit. The examples show a precomputed result at once.
 
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 <GITHUB_URL> l-dpt && cd l-dpt
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 of your photos (`docs/inference.md`
59
- of the code).
 
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 of this Space are in a
69
- private dataset, so a copy starts without a gallery unless it is given one
70
- (`LDPT_EXAMPLES_DIR` or `LDPT_EXAMPLES_REPO`).
 
71
 
72
  Optional variables:
73
 
@@ -87,9 +90,11 @@ Optional variables:
87
 
88
  ## License
89
 
90
- The L-DPT code and weights are released under
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
- # TODO(release): the code repository; the hero shows a Code link once this is a URL
82
- CODE_URL = "<GITHUB_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: f49c0ed
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, reads the checkpoints memory-mapped and
23
- assigns them tensor by tensor on the target device (the 7B encoder in bf16 storage by
24
- default), so no fp32 copy of the encoder is ever made. Only torch and numpy are needed
25
- (huggingface_hub when the decoder weights are downloaded). The decoder RoPE normalises
26
- token coordinates by the short side (``dec_pos_embed_rope_normalize_coords="min"``): the
27
- same as trained on the square training crops, and the trained token spacing on other
28
- aspect ratios, where ``"separate"`` (each axis to [-1, 1]) squeezes the long side.
29
-
30
- ``predict`` uses the preprocessing of the validation pipeline: [0, 1] RGB, short side
31
- resized to the preset's INPUT_SIZE (768 for the release models; bicubic, antialiased,
32
- as torchvision's Resize), ImageNet normalisation; the model pads to the patch grid and
33
- the output is resized bilinearly to the input size. ``size=None`` runs at the native
34
- resolution, with the inference memory options of LatentDPT that the demo and
35
- scripts/highres_infer.py use (NATIVE_MEMORY: selection_impl="stream",
36
- chunk_tokens=32768; same math, in bf16 equal up to rounding) for the call, unless the
37
- caller chose them: passed to ``load`` (e.g. ``selection_impl="concat"``), set on the
38
- model, or ``model.native_memory = {}``. The resized path runs the model as loaded.
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; the preset
112
- name stored in a file converted before the rename is read as the current
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
- pred = model.infer(x)
348
- if flip:
349
- flipped = model.infer(torch.flip(x, dims=[-1]))
350
- pred = torch.stack([pred, torch.flip(flipped, dims=[-1])], dim=1).mean(
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, whatever
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, stored by the
8
- first conversions, 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,7 +52,7 @@ __all__ = [
52
  ]
53
 
54
  FORMAT = "l-dpt-release/2" # written; config without the criterion
55
- # read: /1 (earlier files) also stored the training criterion in the config
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 stay as trained):
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: sigmoid relative depth (head="exp": exp of the clamped logit, the L-DPT
18
- depth loss), or 1x1 seg_head logits (infer); losses (forward).
 
19
 
20
- Kept on purpose, because every trained checkpoint depends on it:
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 ("stage": one Linear per
98
- stage, "shared": one Linear for all stages) and runs dec_num_layers[s] RoPE
99
- self-attention blocks. The readout is a conv + pixel shuffle.
 
 
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
- task: "relative_depth" (sigmoid depth, affine-invariant loss) or "semseg"
109
- (out_dim pixel features + 1x1 seg_head).
 
 
 
 
 
 
 
 
 
 
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, the head check below is skipped, a
114
- forward in eval returns the prediction without a loss even when the
115
- target is given, and a training forward raises. No loss has state-dict
116
- keys, so the model loads the same checkpoints either way.
117
- selection: "stage" (default) or "shared" (an ablation, key 'neck_block').
118
- readout_kernel_size: 3 for the released weights; 1 = a linear projection.
119
- precision: "fp32" (default, as trained) or "bf16": selection, decoder blocks and
120
- readout conv under bf16 autocast (norms / softmax as autocast does), readout
121
- output, heads and loss in fp32. "fp32" adds no autocast, so an autocast the
122
- caller entered (trainer enable_amp) still applies.
123
- attn_dtype: "fp32" (default) or "bf16" (q / k / v cast to bf16 for SDPA).
124
- attn_impl ("auto" / "flash") is the legacy name and maps to fp32 / bf16.
 
 
 
 
 
 
 
 
 
 
125
  attn_fp32: None (default), "last" (the last decoder block), "last_stage" (the
126
- blocks of the last stage) or "all": the attention of those blocks (q / k / v
127
- projections, RoPE, SDPA, out_proj) runs in fp32 with autocast off, the
128
- rest of the decoder as precision / attn_dtype say.
129
- block_fp32: None (default), "last" or "last_stage": those whole blocks run on
130
- the fp32 stream with autocast off, their attention as with attn_fp32 (SDPA
131
- in fp32 whatever attn_dtype). Without an autocast (precision "fp32",
132
- attn_dtype "fp32", no trainer amp) both are the same math as without them.
133
- dec_qk_bound: None (default) or a logit bound B > 0: in every decoder attention
134
- q and k are clipped per head and token to an L2 norm of at most
135
- sqrt(B sqrt(head_dim)) before RoPE, so |q.k| / sqrt(head_dim) <= B (40 and
136
- 200 at head_dim 64). No parameters, same state dict; in training and eval,
137
- so a model trained with it needs it at inference too. The strings "None" /
138
- "null" / "" (from --options) are off.
139
- dec_qk_norm: False (default) or True: cosine attention in every decoder
140
- attention (Attention qk_norm): q and k L2-normalised per head and token
141
- (fp32, before RoPE) and scaled so that the logit is tau_h cos(q, k), tau_h
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, replicate
153
- padding, fp32, + Linear) instead of self-attention (no RoPE, no softmax);
154
- norm1 / ls1 / norm2 / mlp / ls2 stay. Keys local.dw.* / local.out_proj.*
155
- replace attn.*; every other parameter keeps the initial value it has
156
- without the option, and the global RNG state after __init__ is the same.
157
- attn_fp32 does not apply to them (a scope of conv blocks only raises);
158
- block_fp32 does. Left out of
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 (in [-1, 1] after normalize_coords) are multiplied
173
- by r, the evaluation counterpart of the rescale augmentation (training
174
- draws log-uniform factors in [1 / rescale, rescale]); r > 1 spreads the
175
- tokens of a large input toward the trained token spacing (experimental).
176
- No parameters, same state dict; training unchanged; None is
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; no concatenation). Same math, other summation
196
- order.
197
- chunk_tokens: None (default) or a token count. In eval without autograd, the
198
- encoder blocks (DINOv3 forward_chunked) and the decoder FFN run on chunks of
199
- this many tokens: no full-size norm / RoPE / FFN intermediates; per-token
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] view (same strides as the old einops rearrange)
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 grad_exclude) gets the
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 its
 
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 (the old attn_impl="flash"); "fp32" runs SDPA in the input 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; typical 200.4-200.7).
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. As trained: the attention residual is added to the *normalised*
287
- tensor (x = norm1(x); x = x + attn(x)), not to the block input. chunk_tokens (no
288
- autograd only) runs the FFN on token chunks. attn_fp32: the attention is an fp32
289
- island (Attention force_fp32); qk_bound / qk_norm / qk_tau_max: Attention's.
290
- convert_mixer_ replaces the attention by LocalMix (mixer "conv", LatentDPT
291
- dec_conv_mixer): x = norm1(x); x = x + ls1(local(x, hw)); the FFN as before. Such a
292
- block needs the token grid hw and ignores rope.
 
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 (as trained), not on the block input
 
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 like the old einops path (the conv sees a channels-last view);
402
- # a no-op for one output channel, keeps the semseg 1x1 head bit-exact
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 stored in release files
26
- converted before the rename ("l-zs", "l-mix": the published files) to the current
27
- names. This module imports no torch.
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 of the first conversions, stored in the published release files
98
- # (their "preset" 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,7 +117,7 @@ DINOV3_SHA256_PREFIX: Dict[str, str] = {
117
  }
118
 
119
 
120
- TBD = "TBD" # a WeightSource field not pinned yet (before the upload)
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": the trained masks (centre pixel valid, _down2_mask between
139
- levels; 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,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, as trained) 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,174 +542,90 @@ def weighted_gradient_pyramid(
542
 
543
  @LOSSES.register_module("relative_depth_loss")
544
  class RelativeDepthLoss(nn.Module):
545
- """Affine-invariant least-squares depth loss (align="lsq", the default; l2 in depth
546
- space).
547
-
548
- The prediction is aligned to the GT per image with a closed-form least-squares
549
- scale and shift in *depth* space (no gradient through the fit, see
550
- ``compute_scale_and_shift``), then
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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* prediction.
554
- Images with fewer than ``min_valid`` valid pixels are skipped.
555
-
556
- Always computed in fp32 with autocast off, whatever the caller's precision (a bf16
557
- prediction under autocast used to fail in the scale / shift fit); fp32 inputs are
558
- used as they are, so the trained behaviour is bit-identical.
559
-
560
- Behaviours the trained checkpoints depend on (the defaults; keep them bit-identical,
561
- tests/test_depth_loss.py and tests/test_l_dpt_golden.py check it):
562
- - solver="sum": one-pass fp32 sums (``compute_scale_and_shift``);
563
- - clamp_scale=(1e-3, 1e3), keeping the shift of the *unclamped* least-squares
564
- scale: an image whose scale is clamped is moved far off its target (~1e4 m when
565
- the sigmoid spread is ~1e-2 on a 500 m depth range);
566
- - nonpositive="fallback": a degenerate fit or a scale <= 0 is replaced by median /
567
- MAD matching;
568
- - normalize=None, reduction="pixel": MSE in metres, mean over every valid pixel of
569
- the batch (far scenes dominate);
570
- - min_valid=10.
571
-
572
- Fit and reduction options (research, off by default; independent of each other):
573
- solver: "sum" (default) or "centered": exact least squares from centred fp64
574
- moments (``compute_scale_and_shift2`` with ridge=0, as the evaluator's
575
- "centered"); no one-pass cancellation for a near-constant prediction.
576
- clamp_scale: (lo, hi) (default (1e-3, 1e3)) or None (no clamp).
577
- nonpositive: "fallback" (default) or "drop": images whose fit is degenerate or
578
- gives a scale <= 0 add no loss.
579
- normalize: None (default) or "target_mad": residuals divided per image by
580
- ``target_mad`` = max(mean |g - median g|, 0.01 * median g), so the MSE does
581
- not grow with the scene's depth range. Target only: dividing by the
582
- prediction's spread or by the fitted scale rewards a collapsing
583
- prediction. Invariant to scaling the target (when the scale clamp does not
584
- bind, e.g. clamp_scale=None) and to shifting it while the 0.01 * median
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 that take
654
- part).
655
- grad_exclude: () (default) or sample-name prefixes (the dataset group of the
656
- evaluator, the part of the name before "/", e.g. ["kitti"]): images of
657
- these datasets take no part in the gradient-matching term (sparse GT).
658
- Needs the batch's names: the model passes data_dict["name"].
659
- MAGE is the mean over its levels of each level's mean |Scharr / 32 R|; MiDaS
660
- sums its K levels and its data term carries 1 / (2M), so MiDaS's alpha = 0.5
661
- is mage_weight = 0.5 * 4 * 2 = 4 here (Scharr / 32 is the one-pixel
662
- difference on a ramp and on a step edge, ~3x weaker on pixel noise).
663
- MiDaS-style preset: the normalised-fit preset above plus
664
- detach_fit=False, trim=0.1, residual="l1", mage_weight=4.0,
665
- mage_num_scales=4, male_weight=0.0, grad_mask="erode", grad_reduction="image"
666
- (MiDaS: median / MAD units, trimmed MAE, gradient matching with K = 4,
667
- alpha = 0.5, per-image weighting); the mixed-domain one adds
668
- grad_exclude=["kitti"].
669
-
670
- Logging:
671
- log_logit_stats: False (default) or True: also log detached statistics of the
672
- head's logit z = logit(p), p clamped to [1e-6, 1 - 1e-6] (|z| <= 13.8),
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 (pre-v5) options that are off their default."""
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]): # B <= 8: a short loop
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 trained loss, bit-identical; per-image values only for logging
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 trained path). Images with fewer than min_valid level-0 mask
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
- # as trained, bit-identical
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-squares scale and shift that align a relative depth prediction to
5
- the GT (used by the L-DPT loss, the depth evaluator and the visualizer).
 
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. This is the solver the L-DPT training loss was trained with.
 
 
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 (as trained), so a
82
- clamped image is not the best fit for its clamped scale.
 
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, as trained): the shift of the *unclamped* scale,
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
- # keep your "depth-like => positive scale" rule
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) / mean |x - median x|, y' = y / h, w' = w h (h: the image's
638
- depth unit, the harmonic-mean depth), the search in `search_dtype`, then
 
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 (mean |x -
643
- median| <= 1e-12 max(|median|, 1e-30); s, t NaN), a constant sampled y (s =
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 (spec review verify#1): the median absolute deviation, so one
650
- # extreme sampled d cannot push every other point under the search's 1e-7
651
- # guards; the mean absolute deviation where more than half of x equals the median
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 (spec review verify#1).
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 mean absolute deviation, so far below
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); the
23
- older $LDPT_MODEL_<ID> (LDPT_MODEL_L_DPT_LARGE_DEPTH_ZEROSHOT) is read after it.
 
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
- """The earlier name of ``env``, read after it."""
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