pointcept-bot commited on
Commit
6fa100b
·
verified ·
1 Parent(s): ff4399e

Release code: expandable segments, segmentation API, timing notes

Browse files
README.md CHANGED
@@ -26,12 +26,16 @@ high-resolution training data. The model
26
  trained on synthetic and multi-view data only.
27
 
28
  **GPU time** on this Space, at native resolution: 1.5 s at 2 MP, 8.0 s at 8 MP, 79 s at
29
- 32 MP, 267 s at 60 MP and 380 s at 100 MP (photos above 91 MP run on the full GPU,
30
- which counts twice). A request reserves its expected time plus a margin from your daily
31
- ZeroGPU quota before it starts (188 s for a 32 MP photo, 520 s for a 60 MP photo and
32
- 1048 s for a 100 MP photo; a free account has 300 s), so large photos need a Hugging
33
- Face PRO account here; the app on your own GPU (below) has no such limit. Each example
34
- shows a precomputed result at once.
 
 
 
 
35
 
36
  **Output.** Relative depth: larger = farther, defined up to a scale and a shift. It is
37
  shown as in all L-DPT figures and scripts: log depth, near is warm, far is cool,
@@ -41,8 +45,9 @@ text chunk and in the sidecar JSON) and as a colour JPEG.
41
 
42
  ## Run it on your own GPU
43
 
44
- The same app runs from the L-DPT code on an NVIDIA GPU with 15 GiB of free memory
45
- at 2 MP and 41 GiB at 100 MP. It needs Meta's DINOv3 ViT-7B/16 weights, which we cannot
 
46
  redistribute: request access on the
47
  [release page](https://github.com/facebookresearch/dinov3) or the gated
48
  [Hugging Face repo](https://huggingface.co/facebook/dinov3-vit7b16-pretrain-lvd1689m)
 
26
  trained on synthetic and multi-view data only.
27
 
28
  **GPU time** on this Space, at native resolution: 1.5 s at 2 MP, 8.0 s at 8 MP, 79 s at
29
+ 32 MP, 267 s at 60 MP and 380 s at 100 MP (measured with cuDNN attention first; the
30
+ Space now runs PyTorch's order). Photos above 91 MP run on the full GPU, smaller ones on
31
+ half of it.
32
+
33
+ **Quota.** Before it starts, a request reserves GPU time from your daily ZeroGPU quota:
34
+ its estimated time with a margin, counted 1.5 times on half of the GPU and twice on the
35
+ full GPU. That is 188 s for a 32 MP photo, 520 s for a 60 MP photo and 1048 s for a
36
+ 100 MP photo; a free account has 300 s, enough for photos up to 43 MP, so larger photos
37
+ need a Hugging Face PRO account here. The app on your own GPU (below) has no such limit.
38
+ Each example shows a precomputed result at once.
39
 
40
  **Output.** Relative depth: larger = farther, defined up to a scale and a shift. It is
41
  shown as in all L-DPT figures and scripts: log depth, near is warm, far is cool,
 
45
 
46
  ## Run it on your own GPU
47
 
48
+ The same app runs from the L-DPT code on an NVIDIA GPU: its peak allocation is 15 GiB at
49
+ 2 MP and 41 GiB at 100 MP, where PyTorch reserves 46 GiB on a GB200. It needs
50
+ Meta's DINOv3 ViT-7B/16 weights, which we cannot
51
  redistribute: request access on the
52
  [release page](https://github.com/facebookresearch/dinov3) or the gated
53
  [Hugging Face repo](https://huggingface.co/facebook/dinov3-vit7b16-pretrain-lvd1689m)
app.py CHANGED
@@ -31,6 +31,11 @@ import time
31
  from pathlib import Path
32
  from typing import Any, Dict, Optional, Sequence
33
 
 
 
 
 
 
34
  HERE = Path(__file__).resolve().parent
35
  sys.path.insert(0, str(HERE))
36
  if not (HERE / "ldpt").is_dir() and (HERE.parent.parent / "ldpt").is_dir():
@@ -168,7 +173,7 @@ def timing_html(space: bool, precomputed: bool = False) -> str:
168
  )
169
  text = (
170
  f"<b>GPU time</b> (native resolution, no resizing) on one {gpu.name}: "
171
- f"{times}. Peak GPU memory: {peaks}."
172
  )
173
  return f'<div class="timing">{text}</div>'
174
 
@@ -340,7 +345,7 @@ def build_demo(service: Optional[su.DepthService] = None) -> gr.Blocks:
340
  label = registry.get(model_id).label
341
  mp = f"{ex.megapixels:g} MP · " if ex.megapixels else ""
342
  text = (
343
- f"Precomputed: {ex.title} · {mp}{label} · {r['seconds']:.0f} s on "
344
  f"{r.get('device', 'a GPU')} (native resolution){credit(ex)}. Press "
345
  f"**Estimate depth** to run it here."
346
  )
 
31
  from pathlib import Path
32
  from typing import Any, Dict, Optional, Sequence
33
 
34
+ # PyTorch's allocator with expandable segments reserves less GPU memory beyond the peak it
35
+ # allocates at native resolution (set before torch initialises CUDA; a value already in
36
+ # the environment wins)
37
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
38
+
39
  HERE = Path(__file__).resolve().parent
40
  sys.path.insert(0, str(HERE))
41
  if not (HERE / "ldpt").is_dir() and (HERE.parent.parent / "ldpt").is_dir():
 
173
  )
174
  text = (
175
  f"<b>GPU time</b> (native resolution, no resizing) on one {gpu.name}: "
176
+ f"{times}. Peak GPU memory allocated: {peaks}."
177
  )
178
  return f'<div class="timing">{text}</div>'
179
 
 
345
  label = registry.get(model_id).label
346
  mp = f"{ex.megapixels:g} MP · " if ex.megapixels else ""
347
  text = (
348
+ f"Precomputed: {ex.title} · {mp}{label} · computed on "
349
  f"{r.get('device', 'a GPU')} (native resolution){credit(ex)}. Press "
350
  f"**Estimate depth** to run it here."
351
  )
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: 07dee4a
3
  ldpt/models/__init__.py
4
  ldpt/models/builder.py
5
  ldpt/models/dinov3/__init__.py
@@ -31,3 +31,4 @@ ldpt/utils/depth_image.py
31
  ldpt/utils/misc.py
32
  ldpt/utils/registry.py
33
  ldpt/utils/sdpa.py
 
 
1
  # ldpt inference subset for the Space: written by demo/hf_space/sync_ldpt.sh
2
+ # source: the L-DPT release (Pointcept/L-DPT)
3
  ldpt/models/__init__.py
4
  ldpt/models/builder.py
5
  ldpt/models/dinov3/__init__.py
 
31
  ldpt/utils/misc.py
32
  ldpt/utils/registry.py
33
  ldpt/utils/sdpa.py
34
+ ldpt/utils/seg_image.py
ldpt/models/l_dpt/api.py CHANGED
@@ -1,5 +1,6 @@
1
  """
2
- Inference API: ``load`` a ready-to-run L-DPT, ``predict`` relative depth of an image.
 
3
 
4
  from ldpt.models.l_dpt import api
5
 
@@ -10,10 +11,15 @@ Inference API: ``load`` a ready-to-run L-DPT, ``predict`` relative depth of an i
10
  depth = api.predict(model, image) # HxWx3 uint8 (or float in [0, 1]) -> HxW float32
11
  depth = api.predict(model, image, size=None) # at the image's native resolution
12
 
13
- ``depth`` is positive relative depth: larger = farther, affine-invariant (the metric
14
- depth is about s * depth + t with s > 0 per image). The released models
 
 
 
15
  ("l-dpt_large_depth_zeroshot", "l-dpt_large_depth_mixed") have an exponential head:
16
- values in [exp(-30), exp(30)]; a sigmoid-head model gives (0, 1).
 
 
17
  ``api.load("l-dpt_large_depth_zeroshot", ...)`` downloads the pinned weights file from
18
  Hugging Face on first use; a local copy loads by path
19
  (``api.load("l-dpt_large_depth_zeroshot.pth", ...)``), with ``weights=`` or with
@@ -24,11 +30,12 @@ tensors on the target device (the 7B encoder stored in bf16 by default), so no f
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;
@@ -48,7 +55,7 @@ import logging
48
  import os
49
  import time
50
  from pathlib import Path
51
- from typing import Any, Dict, Iterable, Mapping, Optional, Sequence, Union
52
 
53
  import numpy as np
54
  import torch
@@ -62,6 +69,7 @@ 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
64
  from .presets import (
 
65
  IMAGE_MEAN,
66
  IMAGE_STD,
67
  INPUT_SIZE,
@@ -78,7 +86,15 @@ from .weights import (
78
  read_checkpoint,
79
  )
80
 
81
- __all__ = ["NATIVE_MEMORY", "SDPA_ORDER", "auto_order", "load", "predict"]
 
 
 
 
 
 
 
 
82
 
83
  log = logging.getLogger(__name__)
84
 
@@ -105,11 +121,13 @@ def load(
105
 
106
  Args:
107
  name_or_path: a preset with released weights
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; a short
112
- preset name of LEGACY_PRESETS stored in it is read as the current name).
 
 
113
  encoder_weights: the official DINOv3 file (default ``$LDPT_DINOV3``); its sha256
114
  prefix is checked once (``verify``). Or a folder in the transformers format
115
  (a download of Meta's gated Hugging Face repo, e.g.
@@ -146,17 +164,19 @@ def load(
146
  weights it holds is not checked.
147
  overrides: model kwargs replacing the preset's / file's; by default a frozen
148
  encoder is stored in bf16 (``encoder_weight_dtype="bf16"``, bit-identical
149
- outputs) and ``dec_pos_embed_rope_normalize_coords="min"`` (see the module
150
- docstring; ``"separate"`` normalises each axis to [-1, 1]). The
 
151
  model is built inference-only (``criterion=False``: no training loss, so
152
  no loss code runs; a training forward raises) unless ``criterion`` is
153
  passed. ``selection_impl`` / ``chunk_tokens`` here also set what
154
  ``predict(size=None)`` runs with (see ``.native_memory``).
155
 
156
  Returns:
157
- LatentDPT in eval mode, with ``.preset`` (name or None), ``.weights_info`` and
158
- ``.native_memory`` (the NATIVE_MEMORY options not in ``overrides``: what
159
- ``predict(size=None)`` sets for the call).
 
160
  """
161
  t0 = time.perf_counter()
162
  name = os.fspath(name_or_path)
@@ -235,7 +255,10 @@ def load(
235
  config["precision"] = precision
236
  if config.get("freeze_encoder", True) and "encoder_weight_dtype" not in overrides:
237
  config["encoder_weight_dtype"] = "bf16"
238
- if "dec_pos_embed_rope_normalize_coords" not in overrides:
 
 
 
239
  config["dec_pos_embed_rope_normalize_coords"] = "min"
240
  if "criterion" not in overrides: # inference only: no training loss
241
  config["criterion"] = False
@@ -289,6 +312,8 @@ def load(
289
  )
290
  model.eval()
291
  model.preset = preset
 
 
292
  model.weights_info = info
293
  model.native_memory = {k: v for k, v in NATIVE_MEMORY.items() if k not in overrides}
294
  log.info("load(%s): %.1f s on %s", name, time.perf_counter() - t0, dev)
@@ -304,9 +329,20 @@ def predict(
304
  flip: bool = False,
305
  sdpa_backends: Union[Sequence[str], str, None] = "auto",
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
309
- the exp head (the release models), in (0, 1) with a sigmoid head.
 
 
 
 
 
 
 
 
 
 
 
310
 
311
  Args:
312
  image: HxWx3 RGB, uint8 in [0, 255] or float in [0, 1] (numpy or torch).
@@ -316,7 +352,8 @@ def predict(
316
  ``model.native_memory`` options (from ``load``: NATIVE_MEMORY unless the
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
  sdpa_backends: the scaled-dot-product attention backends tried, in this order,
321
  while the model runs (names of ldpt.utils.sdpa.SDPA_BACKENDS: "cudnn",
322
  "flash", "efficient", "math"; the others are disabled for the call).
@@ -333,14 +370,10 @@ def predict(
333
  restored after it.
334
 
335
  Shapes:
336
- image: [H, W, 3] -> [H, W] float32 (numpy for numpy input, else a tensor on
337
- the model's device)
338
  """
339
- if model.task != "relative_depth":
340
- raise ValueError(
341
- f"predict returns relative depth; this model's task is {model.task!r}: "
342
- f"use model.infer(normalised [B, 3, H, W] image)"
343
- )
344
  device = _model_device(model)
345
  attention = sdpa_context(sdpa_backends, device) # an unknown name raises here
346
  x = _to_image(image, device) # [1, 3, H, W] in [0, 1]
@@ -363,15 +396,61 @@ def predict(
363
  pred = model.infer(x)
364
  if flip:
365
  flipped = torch.flip(model.infer(torch.flip(x, dims=[-1])), dims=[-1])
 
 
366
  pred = torch.stack([pred, flipped], dim=1).mean(dim=1)
367
  finally:
368
  for k, v in saved.items():
369
  setattr(model, k, v)
370
  model.train(was_training)
371
- if pred.shape[-2:] != (H, W):
372
- pred = F.interpolate(pred, size=(H, W), mode="bilinear", align_corners=False)
373
- depth = pred[0, 0].float()
374
- return depth.cpu().numpy() if isinstance(image, np.ndarray) else depth
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
 
376
 
377
  def resize_short_side(image: Tensor, size: int) -> Tensor:
 
1
  """
2
+ Inference API: ``load`` a ready-to-run L-DPT, ``predict`` relative depth or semantic
3
+ segmentation of an image.
4
 
5
  from ldpt.models.l_dpt import api
6
 
 
11
  depth = api.predict(model, image) # HxWx3 uint8 (or float in [0, 1]) -> HxW float32
12
  depth = api.predict(model, image, size=None) # at the image's native resolution
13
 
14
+ seg = api.load("l-dpt_large_semseg_cocostuff.pth") # a segmentation release file
15
+ classes = api.predict(seg, image) # HxW int64 class ids (seg.class_names)
16
+
17
+ ``depth`` is positive relative depth: larger = farther, affine-invariant (compare it
18
+ with metric depth through a fit s * depth + t with s > 0 per image). The released depth models
19
  ("l-dpt_large_depth_zeroshot", "l-dpt_large_depth_mixed") have an exponential head:
20
+ values in [exp(-30), exp(30)]; a sigmoid-head model gives (0, 1). A segmentation model
21
+ ("l-dpt_large_semseg_cocostuff": COCO-Stuff, 171 classes) gives one class id per pixel,
22
+ the argmax of its logits resized to the image, as its evaluation predicts.
23
  ``api.load("l-dpt_large_depth_zeroshot", ...)`` downloads the pinned weights file from
24
  Hugging Face on first use; a local copy loads by path
25
  (``api.load("l-dpt_large_depth_zeroshot.pth", ...)``), with ``weights=`` or with
 
30
  copy of the encoder is made. It builds the model as its release file or preset states
31
  it (decoder precision too, unless ``precision`` is passed) and refuses weights of
32
  another architecture (_ARCH_KEYS: the options that change the output). The decoder RoPE
33
+ of a depth model normalises token coordinates by the short side
34
  (``dec_pos_embed_rope_normalize_coords="min"``), which keeps the token spacing of the
35
  square training crops on any aspect ratio (``"separate"`` scales each axis to [-1, 1]
36
+ and squeezes the long side); a segmentation model keeps the value of its file or
37
+ preset (``"separate"``, as evaluated). Needs torch and numpy only (huggingface_hub to
38
+ download weights).
39
 
40
  ``predict`` uses the validation preprocessing (short side to the preset's INPUT_SIZE,
41
  bicubic, ImageNet normalisation) and resizes the output back to the input size;
 
55
  import os
56
  import time
57
  from pathlib import Path
58
+ from typing import Any, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Union
59
 
60
  import numpy as np
61
  import torch
 
69
  from .l_dpt_v1m1_base import PRECISIONS, LatentDPT, _resolve_attn_dtype
70
  from .modules import check_choice
71
  from .presets import (
72
+ CLASS_NAMES,
73
  IMAGE_MEAN,
74
  IMAGE_STD,
75
  INPUT_SIZE,
 
86
  read_checkpoint,
87
  )
88
 
89
+ __all__ = [
90
+ "CLASS_MAP_ELEMENTS",
91
+ "NATIVE_MEMORY",
92
+ "SDPA_ORDER",
93
+ "auto_order",
94
+ "class_map",
95
+ "load",
96
+ "predict",
97
+ ]
98
 
99
  log = logging.getLogger(__name__)
100
 
 
121
 
122
  Args:
123
  name_or_path: a preset with released weights
124
+ (``"l-dpt_large_depth_zeroshot"``, ``"l-dpt_large_depth_mixed"``,
125
+ ``"l-dpt_large_semseg_cocostuff"``; their files are downloaded from
126
+ Hugging Face on first use, or read from ``$LDPT_CKPT_LARGE_DEPTH_ZEROSHOT``
127
+ / ``$LDPT_CKPT_LARGE_DEPTH_MIXED`` / ``$LDPT_CKPT_LARGE_SEMSEG_COCOSTUFF``;
128
+ a preset whose slot is not published yet needs ``weights=``), or a
129
+ release file written by convert.py (it carries its config; a short preset
130
+ name of LEGACY_PRESETS stored in it is read as the current name).
131
  encoder_weights: the official DINOv3 file (default ``$LDPT_DINOV3``); its sha256
132
  prefix is checked once (``verify``). Or a folder in the transformers format
133
  (a download of Meta's gated Hugging Face repo, e.g.
 
164
  weights it holds is not checked.
165
  overrides: model kwargs replacing the preset's / file's; by default a frozen
166
  encoder is stored in bf16 (``encoder_weight_dtype="bf16"``, bit-identical
167
+ outputs) and a depth model runs ``dec_pos_embed_rope_normalize_coords=
168
+ "min"`` (see the module docstring; ``"separate"`` normalises each axis to
169
+ [-1, 1]; a segmentation model keeps its file's / preset's value). The
170
  model is built inference-only (``criterion=False``: no training loss, so
171
  no loss code runs; a training forward raises) unless ``criterion`` is
172
  passed. ``selection_impl`` / ``chunk_tokens`` here also set what
173
  ``predict(size=None)`` runs with (see ``.native_memory``).
174
 
175
  Returns:
176
+ LatentDPT in eval mode, with ``.preset`` (name or None), ``.class_names`` (a
177
+ segmentation preset's classes, presets.CLASS_NAMES, in output-channel order;
178
+ else None), ``.weights_info`` and ``.native_memory`` (the NATIVE_MEMORY options
179
+ not in ``overrides``: what ``predict(size=None)`` sets for the call).
180
  """
181
  t0 = time.perf_counter()
182
  name = os.fspath(name_or_path)
 
255
  config["precision"] = precision
256
  if config.get("freeze_encoder", True) and "encoder_weight_dtype" not in overrides:
257
  config["encoder_weight_dtype"] = "bf16"
258
+ if (
259
+ "dec_pos_embed_rope_normalize_coords" not in overrides
260
+ and config.get("task", "relative_depth") == "relative_depth"
261
+ ):
262
  config["dec_pos_embed_rope_normalize_coords"] = "min"
263
  if "criterion" not in overrides: # inference only: no training loss
264
  config["criterion"] = False
 
312
  )
313
  model.eval()
314
  model.preset = preset
315
+ names = CLASS_NAMES.get(preset or "")
316
+ model.class_names = list(names) if names is not None else None
317
  model.weights_info = info
318
  model.native_memory = {k: v for k, v in NATIVE_MEMORY.items() if k not in overrides}
319
  log.info("load(%s): %.1f s on %s", name, time.perf_counter() - t0, dev)
 
329
  flip: bool = False,
330
  sdpa_backends: Union[Sequence[str], str, None] = "auto",
331
  ) -> Union[np.ndarray, Tensor]:
332
+ """Relative depth or the class map of one image, at the image's resolution.
333
+
334
+ Relative depth (``model.task == "relative_depth"``): positive, larger = farther,
335
+ affine-invariant (compared with metric depth through a fit s * depth + t, s > 0, per
336
+ image); in [exp(-30), exp(30)] with the exp head (the released depth models), in
337
+ (0, 1) with a sigmoid head.
338
+
339
+ Semantic segmentation (``"semseg"``): the class id of every pixel (0 ..
340
+ num_classes - 1, names in ``model.class_names``), as SemSegEvaluator predicts it:
341
+ the logits (with ``flip``: the mean of the two softmaxes) resized bilinearly to the
342
+ image, then the argmax (the lowest id on a tie). The resize runs over a few classes
343
+ at a time when the image is large (CLASS_MAP_ELEMENTS values at most), with the
344
+ same result. At ``size=None`` the logits are computed at the native resolution:
345
+ num_classes x H x W x 4 bytes.
346
 
347
  Args:
348
  image: HxWx3 RGB, uint8 in [0, 255] or float in [0, 1] (numpy or torch).
 
352
  ``model.native_memory`` options (from ``load``: NATIVE_MEMORY unless the
353
  caller passed them) that are still at their LatentDPT default, and restores
354
  them after the call; a model built otherwise runs as it is.
355
+ flip: also run the horizontally flipped image and average (the eval TTA):
356
+ the depths, or the softmaxes of a segmentation model.
357
  sdpa_backends: the scaled-dot-product attention backends tried, in this order,
358
  while the model runs (names of ldpt.utils.sdpa.SDPA_BACKENDS: "cudnn",
359
  "flash", "efficient", "math"; the others are disabled for the call).
 
370
  restored after it.
371
 
372
  Shapes:
373
+ image: [H, W, 3] -> depth [H, W] float32, or class ids [H, W] int64 (numpy
374
+ for numpy input, else a tensor on the model's device)
375
  """
376
+ segment = model.task == "semseg"
 
 
 
 
377
  device = _model_device(model)
378
  attention = sdpa_context(sdpa_backends, device) # an unknown name raises here
379
  x = _to_image(image, device) # [1, 3, H, W] in [0, 1]
 
396
  pred = model.infer(x)
397
  if flip:
398
  flipped = torch.flip(model.infer(torch.flip(x, dims=[-1])), dims=[-1])
399
+ if segment: # SemSegEvaluator's TTA: the mean of the softmaxes
400
+ pred, flipped = pred.softmax(dim=1), flipped.softmax(dim=1)
401
  pred = torch.stack([pred, flipped], dim=1).mean(dim=1)
402
  finally:
403
  for k, v in saved.items():
404
  setattr(model, k, v)
405
  model.train(was_training)
406
+ if segment:
407
+ out = class_map(pred, (H, W))[0]
408
+ else:
409
+ if pred.shape[-2:] != (H, W):
410
+ pred = F.interpolate(
411
+ pred, size=(H, W), mode="bilinear", align_corners=False
412
+ )
413
+ out = pred[0, 0].float()
414
+ return out.cpu().numpy() if isinstance(image, np.ndarray) else out
415
+
416
+
417
+ # the most resized class scores class_map holds at once (1 GiB in fp32)
418
+ CLASS_MAP_ELEMENTS = 1 << 28
419
+
420
+
421
+ def class_map(
422
+ scores: Tensor, size: Tuple[int, int], max_elements: int = CLASS_MAP_ELEMENTS
423
+ ) -> Tensor:
424
+ """The argmax over classes of ``scores`` resized bilinearly to ``size``:
425
+ SemSegEvaluator's ``F.interpolate(..., mode="bilinear", align_corners=False)`` and
426
+ ``argmax(dim=1)`` (no resize at that size already), run on as many classes at a
427
+ time as keep the resized block within ``max_elements`` values, with the same result
428
+ (each class resizes on its own; on a tie the lowest class id, as argmax).
429
+
430
+ Shapes:
431
+ scores: [B, C, h, w] (logits or probabilities) -> [B, H, W] int64
432
+ """
433
+ if tuple(scores.shape[-2:]) == tuple(size):
434
+ return scores.argmax(dim=1)
435
+ B, C = scores.shape[:2]
436
+ step = max(1, max_elements // max(1, B * size[0] * size[1]))
437
+ if step >= C:
438
+ resized = F.interpolate(scores, size=size, mode="bilinear", align_corners=False)
439
+ return resized.argmax(dim=1)
440
+ best = best_id = None
441
+ for c0 in range(0, C, step):
442
+ resized = F.interpolate(
443
+ scores[:, c0 : c0 + step], size=size, mode="bilinear", align_corners=False
444
+ )
445
+ value, idx = resized.max(dim=1)
446
+ idx += c0
447
+ if best is None:
448
+ best, best_id = value, idx
449
+ else: # strictly greater: a tie keeps the lower id
450
+ better = value > best
451
+ best = torch.where(better, value, best)
452
+ best_id = torch.where(better, idx, best_id)
453
+ return best_id
454
 
455
 
456
  def resize_short_side(image: Tensor, size: int) -> Tensor:
ldpt/models/l_dpt/convert.py CHANGED
@@ -4,13 +4,16 @@ 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 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
12
  module), fp32
13
- provenance source file name and sha256, epoch, best metric, conversion time
 
 
 
14
  Optimizer, scheduler and scaler state are dropped. A release file builds its model
15
  inference-only (``criterion=False``), so loading it never builds the training loss
16
  (the loss code is not needed). "l-dpt-release/1" files (also storing the
@@ -19,6 +22,7 @@ strictly: every key of the model built from ``config`` filled once, with its sha
19
 
20
  CLI:
21
  python -m ldpt.models.l_dpt.convert SRC DST --preset l-dpt_large_depth_zeroshot
 
22
  python -m ldpt.models.l_dpt.convert SRC DST --config exp/hybrid/<run>/config.py
23
 
24
  Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
@@ -27,6 +31,7 @@ Please cite our work if the code is helpful to you.
27
 
28
  import argparse
29
  import datetime
 
30
  import os
31
  from pathlib import Path
32
  from typing import Any, Dict, Mapping, Optional, Tuple
@@ -168,6 +173,9 @@ def convert(
168
  timespec="seconds"
169
  ),
170
  )
 
 
 
171
  release = dict(
172
  format=FORMAT,
173
  model=MODEL,
@@ -263,6 +271,26 @@ def load_release(
263
  return config, state, info
264
 
265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  def _scalar(value: Any) -> Any:
267
  if isinstance(value, Tensor):
268
  return value.item()
 
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 (--preset), or None (--config); the short names of
8
+ LEGACY_PRESETS 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
12
  module), fp32
13
+ provenance source file name and sha256, epoch, best metric, conversion time;
14
+ for an average written by scripts/average_weights.py (its
15
+ SRC.avg.json beside SRC) also "averaged": the names and sha256 of
16
+ its inputs and their weights
17
  Optimizer, scheduler and scaler state are dropped. A release file builds its model
18
  inference-only (``criterion=False``), so loading it never builds the training loss
19
  (the loss code is not needed). "l-dpt-release/1" files (also storing the
 
22
 
23
  CLI:
24
  python -m ldpt.models.l_dpt.convert SRC DST --preset l-dpt_large_depth_zeroshot
25
+ python -m ldpt.models.l_dpt.convert SRC DST --preset l-dpt_large_semseg_cocostuff
26
  python -m ldpt.models.l_dpt.convert SRC DST --config exp/hybrid/<run>/config.py
27
 
28
  Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
 
31
 
32
  import argparse
33
  import datetime
34
+ import json
35
  import os
36
  from pathlib import Path
37
  from typing import Any, Dict, Mapping, Optional, Tuple
 
173
  timespec="seconds"
174
  ),
175
  )
176
+ averaged = _averaged(src)
177
+ if averaged is not None:
178
+ provenance["averaged"] = averaged
179
  release = dict(
180
  format=FORMAT,
181
  model=MODEL,
 
271
  return config, state, info
272
 
273
 
274
+ # the record scripts/average_weights.py writes beside its output
275
+ AVERAGE_SIDECAR = ".avg.json"
276
+
277
+
278
+ def _averaged(src: PathLike) -> Optional[Dict[str, Any]]:
279
+ """The inputs of an averaged checkpoint (file names, sha256, weights) from its
280
+ scripts/average_weights.py record (``<src>.avg.json``), None without one."""
281
+ record = Path(os.fspath(src) + AVERAGE_SIDECAR)
282
+ if not record.is_file():
283
+ return None
284
+ data = json.loads(record.read_text())
285
+ return dict(
286
+ sources=[
287
+ dict(source=os.path.basename(s["path"]), sha256=s["sha256"])
288
+ for s in data["sources"]
289
+ ],
290
+ weights=list(data["weights"]),
291
+ )
292
+
293
+
294
  def _scalar(value: Any) -> Any:
295
  if isinstance(value, Tensor):
296
  return value.item()
ldpt/models/l_dpt/l_dpt_v1m1_base.py CHANGED
@@ -129,11 +129,11 @@ class LatentDPT(nn.Module):
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
@@ -142,34 +142,36 @@ class LatentDPT(nn.Module):
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.
 
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
+ depth models). No parameters. A criterion with a head attribute must
133
+ name the same head.
134
+ readout_fp32: False (default) or True (the released depth models): the
135
+ readout (conv + pixel shuffle) runs outside the autocast on the fp32
136
+ decoder 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
 
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; the segmentation preset) or "bf16" (the
146
+ released depth models: q / k / v cast to bf16 for SDPA). attn_impl
147
+ ("auto" / "flash") is the legacy name of the same choice.
148
  attn_fp32: None (default), "last" (the last decoder block), "last_stage" (the
149
+ released depth 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 depth
155
+ models: 1000): in every decoder attention q and k are clipped per head
156
+ and token to an L2 norm of at most sqrt(B sqrt(head_dim)) before RoPE, so
157
+ |q.k| / sqrt(head_dim) <= B. No parameters. Active in training and eval:
158
+ a model trained with it needs it at inference. The strings "None" /
159
+ "null" / "" (from --options) turn it off.
160
+ Used by the COCO-Stuff segmentation recipe 1 (semseg-l-dpt-v1m1-1-large) and the
161
+ segmentation preset:
162
  dec_qk_norm (+ dec_qk_tau_max, default 200.0): cosine attention with a
163
  learned temperature per head, capped at dec_qk_tau_max (Attention
164
  qk_norm); one key dec_blocks.{s}.{i}.attn.logit_scale per block; raises
165
  with dec_qk_bound.
166
+ tap_bn: False (default) or True: a BatchNorm on each tapped encoder layer
167
+ before the selection, in fp32 (keys tap_bn.{i}.*; the trainer's sync_bn
168
+ converts them to SyncBatchNorm).
169
+ Experimental, used by no recipe (details: modules.py and the tests):
170
  dec_conv_mixer: None (default), "last" or "last_stage": those blocks mix
171
  tokens with LocalMix (3x3 depthwise conv on the token grid) instead of
172
  self-attention; keys local.* replace attn.*, every other parameter and the
173
  RNG stream stay as without it. attn_fp32 does not apply to them,
174
  block_fp32 does; compile_blocks leaves them eager.
 
 
 
175
  dec_pos_embed_rope_eval_scale: None (default) or r > 0: in eval mode the
176
  decoder RoPE coordinates are multiplied by r (training unchanged); r > 1
177
  spreads the tokens of a large input toward the trained token spacing.
ldpt/models/l_dpt/presets.py CHANGED
@@ -10,21 +10,29 @@ files, <name>.pth) read l-dpt_<decoder size>_<task>_<training data>:
10
  "l-dpt_large_depth_mixed" L-DPT Large (mixed): + the NYUv2 / KITTI / DIODE
11
  training splits (configs/hybrid/depth-l-dpt-v1m1-1-large-mixed.py,
12
  depth-l-dpt-v1m1-1a-large-mixed-anneal.py)
13
-
14
- Both share one architecture (RELEASE_L) and differ only in their weights: frozen DINOv3
15
- ViT-7B/16 tapped at blocks [9, 19, 29, 39], latent decoder 1024 / 16 heads / (4, 4, 4,
16
- 4) blocks in bf16, exponential depth head with an fp32 readout, fp32 attention in the
17
- last decoder stage, an attention-logit bound of 1000, trained at short side 768 with
18
- the L-DPT depth loss (docs/depth_loss.md). Inference only (criterion=False): the
19
- training losses live in the configs. In a config:
 
 
 
 
 
 
 
20
  model = dict(type="L-DPT-v1m1", **get_preset("l-dpt_large_depth_zeroshot"))
21
 
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.
@@ -33,9 +41,12 @@ Please cite our work if the code is helpful to you.
33
  import copy
34
  import difflib
35
  from dataclasses import dataclass
36
- from typing import Any, Dict, Optional
 
 
37
 
38
  __all__ = [
 
39
  "DINOV3_SHA256_PREFIX",
40
  "IMAGE_MEAN",
41
  "IMAGE_STD",
@@ -43,6 +54,7 @@ __all__ = [
43
  "LEGACY_PRESETS",
44
  "PRESETS",
45
  "RELEASE_L",
 
46
  "WEIGHTS",
47
  "WeightSource",
48
  "canonical_preset",
@@ -51,7 +63,7 @@ __all__ = [
51
 
52
  TAPS_7B = [9, 19, 29, 39]
53
 
54
- # the release architecture, shared by both release models (they differ only in their
55
  # weights): the model of configs/hybrid/*.py (tests/test_configs.py checks it)
56
  RELEASE_L: Dict[str, Any] = dict(
57
  encoder=dict(type="dinov3_vit7b"),
@@ -89,13 +101,53 @@ RELEASE_L: Dict[str, Any] = dict(
89
  criterion=False, # inference only: the training loss is in the configs
90
  )
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  PRESETS: Dict[str, Dict[str, Any]] = {
93
  "l-dpt_large_depth_zeroshot": RELEASE_L,
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",
@@ -105,6 +157,11 @@ LEGACY_PRESETS: Dict[str, str] = {
105
  INPUT_SIZE: Dict[str, int] = {
106
  "l-dpt_large_depth_zeroshot": 768,
107
  "l-dpt_large_depth_mixed": 768,
 
 
 
 
 
108
  }
109
  IMAGE_MEAN = (0.485, 0.456, 0.406)
110
  IMAGE_STD = (0.229, 0.224, 0.225)
@@ -165,6 +222,15 @@ WEIGHTS: Dict[str, WeightSource] = {
165
  env="LDPT_CKPT_LARGE_DEPTH_MIXED",
166
  format="release",
167
  ),
 
 
 
 
 
 
 
 
 
168
  }
169
 
170
 
 
10
  "l-dpt_large_depth_mixed" L-DPT Large (mixed): + the NYUv2 / KITTI / DIODE
11
  training splits (configs/hybrid/depth-l-dpt-v1m1-1-large-mixed.py,
12
  depth-l-dpt-v1m1-1a-large-mixed-anneal.py)
13
+ "l-dpt_large_semseg_cocostuff" L-DPT Large, COCO-Stuff semantic segmentation
14
+ (171 classes, CLASS_NAMES)
15
+
16
+ Both depth models share one architecture (RELEASE_L) and differ only in their weights:
17
+ frozen DINOv3 ViT-7B/16 tapped at blocks [9, 19, 29, 39], latent decoder 1024 / 16
18
+ heads / (4, 4, 4, 4) blocks in bf16, exponential depth head with an fp32 readout, fp32
19
+ attention in the last decoder stage, an attention-logit bound of 1000, trained at short
20
+ side 768 with the L-DPT depth loss (docs/depth_loss.md). The segmentation model
21
+ (SEMSEG_L) taps the same encoder: latent decoder 2048 / 16 heads / (2, 2, 2, 2) blocks
22
+ with attention at width 1024, cosine attention with a learned temperature per head, a
23
+ BatchNorm on each tapped layer, 64 pixel features and a 1x1 classifier, decoder RoPE
24
+ coordinates normalised per axis, trained on 768 x 768 crops and evaluated on the whole
25
+ image at short side 768. Inference only (criterion=False): the training losses live in
26
+ the configs. In a config:
27
  model = dict(type="L-DPT-v1m1", **get_preset("l-dpt_large_depth_zeroshot"))
28
 
29
  WEIGHTS pins the released decoder checkpoints (Hugging Face repo, revision, file,
30
+ sha256, and the variable naming a local copy; a slot of TBD values is not published
31
+ yet: the segmentation slot until its file is uploaded and pinned); DINOv3 weights are
32
+ not redistributed: weights.encoder_weights() takes a local file and checks the sha256
33
+ prefix in its official name. LEGACY_PRESETS maps the short
34
+ preset names of earlier release files ("l-zs", "l-mix") to the current names. This
35
+ module imports no torch.
36
 
37
  Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com)
38
  Please cite our work if the code is helpful to you.
 
41
  import copy
42
  import difflib
43
  from dataclasses import dataclass
44
+ from typing import Any, Dict, Optional, Tuple
45
+
46
+ from ldpt.utils.seg_image import COCOSTUFF_CLASS_NAMES
47
 
48
  __all__ = [
49
+ "CLASS_NAMES",
50
  "DINOV3_SHA256_PREFIX",
51
  "IMAGE_MEAN",
52
  "IMAGE_STD",
 
54
  "LEGACY_PRESETS",
55
  "PRESETS",
56
  "RELEASE_L",
57
+ "SEMSEG_L",
58
  "WEIGHTS",
59
  "WeightSource",
60
  "canonical_preset",
 
63
 
64
  TAPS_7B = [9, 19, 29, 39]
65
 
66
+ # the depth architecture, shared by both depth models (they differ only in their
67
  # weights): the model of configs/hybrid/*.py (tests/test_configs.py checks it)
68
  RELEASE_L: Dict[str, Any] = dict(
69
  encoder=dict(type="dinov3_vit7b"),
 
101
  criterion=False, # inference only: the training loss is in the configs
102
  )
103
 
104
+ # the segmentation architecture: the COCO-Stuff model without its training loss
105
+ SEMSEG_L: Dict[str, Any] = dict(
106
+ encoder=dict(type="dinov3_vit7b"),
107
+ encoder_inter_layers=TAPS_7B,
108
+ freeze_encoder=True,
109
+ encoder_train_mode=True,
110
+ encoder_weight_dtype="bf16", # frozen encoder stored in bf16 (bit-identical)
111
+ task="semseg",
112
+ out_dim=64, # pixel features before the 1x1 classifier (seg_head)
113
+ num_classes=171,
114
+ dec_dim=2048,
115
+ dec_num_heads=16,
116
+ dec_num_layers=(2, 2, 2, 2),
117
+ dec_attn_downscale=2, # attention at width 1024
118
+ dec_ffn_ratio=4.0,
119
+ dec_pos_embed_rope_base=100,
120
+ dec_pos_embed_rope_normalize_coords="separate", # per axis, as evaluated
121
+ dec_pos_embed_rope_shift_coords=None,
122
+ dec_pos_embed_rope_jitter_coords=None,
123
+ dec_pos_embed_rope_rescale_coords=2, # training only
124
+ dec_layer_scale_init=1.0e-05,
125
+ dec_qkv_bias=False,
126
+ dec_proj_bias=True,
127
+ dec_ffn_bias=True,
128
+ selection="stage",
129
+ readout_kernel_size=3,
130
+ precision="bf16", # decoder under bf16 autocast; classifier in fp32
131
+ attn_dtype="fp32",
132
+ readout_fp32=False,
133
+ attn_fp32=None,
134
+ block_fp32=None,
135
+ dec_qk_bound=None,
136
+ dec_qk_norm=True, # cosine attention, learned temperature per head
137
+ dec_qk_tau_max=200.0,
138
+ dec_conv_mixer=None,
139
+ tap_bn=True, # a BatchNorm on each tapped encoder layer
140
+ criterion=False, # inference only: the training loss is in the configs
141
+ )
142
+
143
  PRESETS: Dict[str, Dict[str, Any]] = {
144
  "l-dpt_large_depth_zeroshot": RELEASE_L,
145
  "l-dpt_large_depth_mixed": RELEASE_L,
146
+ "l-dpt_large_semseg_cocostuff": SEMSEG_L,
147
  }
148
 
149
+ # the short preset names of earlier release files (their "preset" field): read as
150
+ # the current names, never accepted as a preset
151
  LEGACY_PRESETS: Dict[str, str] = {
152
  "l-zs": "l-dpt_large_depth_zeroshot",
153
  "l-mix": "l-dpt_large_depth_mixed",
 
157
  INPUT_SIZE: Dict[str, int] = {
158
  "l-dpt_large_depth_zeroshot": 768,
159
  "l-dpt_large_depth_mixed": 768,
160
+ "l-dpt_large_semseg_cocostuff": 768,
161
+ }
162
+ # the class of each output channel, per segmentation preset (dataset train-id order)
163
+ CLASS_NAMES: Dict[str, Tuple[str, ...]] = {
164
+ "l-dpt_large_semseg_cocostuff": tuple(COCOSTUFF_CLASS_NAMES),
165
  }
166
  IMAGE_MEAN = (0.485, 0.456, 0.406)
167
  IMAGE_STD = (0.229, 0.224, 0.225)
 
222
  env="LDPT_CKPT_LARGE_DEPTH_MIXED",
223
  format="release",
224
  ),
225
+ "l-dpt_large_semseg_cocostuff": WeightSource(
226
+ repo=RELEASE_REPO,
227
+ file="l-dpt_large_semseg_cocostuff.pth",
228
+ revision="ef037204d77970fb4dbf65ee1f2a5a36b509143f",
229
+ sha256="034397a1ef38e0aa190ebea1ff1c133d4f7bb7250d781d9019a240a65f2b1bb7",
230
+ size=3_088_255_244,
231
+ env="LDPT_CKPT_LARGE_SEMSEG_COCOSTUFF",
232
+ format="release",
233
+ ),
234
  }
235
 
236
 
ldpt/models/utils/depth.py CHANGED
@@ -401,7 +401,8 @@ def ransac_scale_and_shift(
401
  return_rejected: bool = False,
402
  ):
403
  """Seeded RANSAC line fit target ~ s * pred + t per image (the evaluator's
404
- "ransac"; InfiniDepth's sklearn RANSACRegressor protocol, reproducible).
 
405
 
406
  Per image, on its valid pixels (fp32, on the input's device): a generator seeded
407
  with `seed` (per image: independent of the batch and the rank) draws `trials`
 
401
  return_rejected: bool = False,
402
  ):
403
  """Seeded RANSAC line fit target ~ s * pred + t per image (the evaluator's
404
+ align_solver="ransac" and "ransac" protocol; InfiniDepth's sklearn
405
+ RANSACRegressor protocol, reproducible).
406
 
407
  Per image, on its valid pixels (fp32, on the input's device): a generator seeded
408
  with `seed` (per image: independent of the batch and the rank) draws `trials`
ldpt/utils/seg_image.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Segmentation maps as images, one convention for scripts/demo_segment.py and the API:
3
+
4
+ - class names: COCOSTUFF_CLASS_NAMES, the 171 COCO-Stuff classes in the train-id order
5
+ of COCOStuffDataset (label_mapping="official": the 80 things, then the 91 stuff
6
+ classes, each in the order of the official labels.txt), which is the order of the
7
+ segmentation model's output channels;
8
+ - colour: class c is entry c + 1 of the PASCAL VOC colour map (bit-interleaved RGB;
9
+ entry 0, black, is left for ignored pixels, id -1), the same colour in every image.
10
+
11
+ from ldpt.utils.seg_image import COCOSTUFF_CLASS_NAMES, colorize, top_classes
12
+
13
+ rgb = colorize(classes) # HxW class ids -> HxWx3 uint8 RGB
14
+ for c, name, share in top_classes(classes, COCOSTUFF_CLASS_NAMES):
15
+ print(f"{100 * share:5.1f} % {name}")
16
+
17
+ Only numpy is imported here.
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
+ from typing import List, Optional, Sequence, Tuple, Union
24
+
25
+ import numpy as np
26
+
27
+ __all__ = [
28
+ "COCOSTUFF_CLASS_NAMES",
29
+ "IGNORE_INDEX",
30
+ "colorize",
31
+ "palette",
32
+ "top_classes",
33
+ ]
34
+
35
+ IGNORE_INDEX = -1 # the label of unlabelled pixels in the datasets (drawn black)
36
+
37
+ COCOSTUFF_CLASS_NAMES = [
38
+ "person",
39
+ "bicycle",
40
+ "car",
41
+ "motorcycle",
42
+ "airplane",
43
+ "bus",
44
+ "train",
45
+ "truck",
46
+ "boat",
47
+ "traffic light",
48
+ "fire hydrant",
49
+ "stop sign",
50
+ "parking meter",
51
+ "bench",
52
+ "bird",
53
+ "cat",
54
+ "dog",
55
+ "horse",
56
+ "sheep",
57
+ "cow",
58
+ "elephant",
59
+ "bear",
60
+ "zebra",
61
+ "giraffe",
62
+ "backpack",
63
+ "umbrella",
64
+ "handbag",
65
+ "tie",
66
+ "suitcase",
67
+ "frisbee",
68
+ "skis",
69
+ "snowboard",
70
+ "sports ball",
71
+ "kite",
72
+ "baseball bat",
73
+ "baseball glove",
74
+ "skateboard",
75
+ "surfboard",
76
+ "tennis racket",
77
+ "bottle",
78
+ "wine glass",
79
+ "cup",
80
+ "fork",
81
+ "knife",
82
+ "spoon",
83
+ "bowl",
84
+ "banana",
85
+ "apple",
86
+ "sandwich",
87
+ "orange",
88
+ "broccoli",
89
+ "carrot",
90
+ "hot dog",
91
+ "pizza",
92
+ "donut",
93
+ "cake",
94
+ "chair",
95
+ "couch",
96
+ "potted plant",
97
+ "bed",
98
+ "dining table",
99
+ "toilet",
100
+ "tv",
101
+ "laptop",
102
+ "mouse",
103
+ "remote",
104
+ "keyboard",
105
+ "cell phone",
106
+ "microwave",
107
+ "oven",
108
+ "toaster",
109
+ "sink",
110
+ "refrigerator",
111
+ "book",
112
+ "clock",
113
+ "vase",
114
+ "scissors",
115
+ "teddy bear",
116
+ "hair drier",
117
+ "toothbrush",
118
+ "banner",
119
+ "blanket",
120
+ "branch",
121
+ "bridge",
122
+ "building other",
123
+ "bush",
124
+ "cabinet",
125
+ "cage",
126
+ "cardboard",
127
+ "carpet",
128
+ "ceiling other",
129
+ "ceiling tile",
130
+ "cloth",
131
+ "clothes",
132
+ "clouds",
133
+ "counter",
134
+ "cupboard",
135
+ "curtain",
136
+ "desk stuff",
137
+ "dirt",
138
+ "door stuff",
139
+ "fence",
140
+ "floor marble",
141
+ "floor other",
142
+ "floor stone",
143
+ "floor tile",
144
+ "floor wood",
145
+ "flower",
146
+ "fog",
147
+ "food other",
148
+ "fruit",
149
+ "furniture other",
150
+ "grass",
151
+ "gravel",
152
+ "ground other",
153
+ "hill",
154
+ "house",
155
+ "leaves",
156
+ "light",
157
+ "mat",
158
+ "metal",
159
+ "mirror stuff",
160
+ "moss",
161
+ "mountain",
162
+ "mud",
163
+ "napkin",
164
+ "net",
165
+ "paper",
166
+ "pavement",
167
+ "pillow",
168
+ "plant other",
169
+ "plastic",
170
+ "platform",
171
+ "playingfield",
172
+ "railing",
173
+ "railroad",
174
+ "river",
175
+ "road",
176
+ "rock",
177
+ "roof",
178
+ "rug",
179
+ "salad",
180
+ "sand",
181
+ "sea",
182
+ "shelf",
183
+ "sky other",
184
+ "skyscraper",
185
+ "snow",
186
+ "solid other",
187
+ "stairs",
188
+ "stone",
189
+ "straw",
190
+ "structural other",
191
+ "table",
192
+ "tent",
193
+ "textile other",
194
+ "towel",
195
+ "tree",
196
+ "vegetable",
197
+ "wall brick",
198
+ "wall concrete",
199
+ "wall other",
200
+ "wall panel",
201
+ "wall stone",
202
+ "wall tile",
203
+ "wall wood",
204
+ "water other",
205
+ "waterdrops",
206
+ "window blind",
207
+ "window other",
208
+ "wood",
209
+ ]
210
+
211
+
212
+ def palette(num_classes: int) -> np.ndarray:
213
+ """The colour of each class: [num_classes, 3] uint8 RGB, class c = entry c + 1 of
214
+ the PASCAL VOC colour map (the bits of c + 1 spread over the high bits of R, G, B),
215
+ distinct for every class."""
216
+ if num_classes < 1:
217
+ raise ValueError(f"num_classes must be >= 1, got {num_classes}")
218
+ ids = np.arange(1, num_classes + 1, dtype=np.int64)
219
+ rgb = np.zeros((num_classes, 3), np.int64)
220
+ for bit in range(8):
221
+ for channel in range(3):
222
+ rgb[:, channel] |= ((ids >> (3 * bit + channel)) & 1) << (7 - bit)
223
+ return rgb.astype(np.uint8)
224
+
225
+
226
+ def colorize(
227
+ classes: np.ndarray,
228
+ num_classes: Optional[int] = None,
229
+ *,
230
+ colors: Optional[np.ndarray] = None,
231
+ bgr: bool = False,
232
+ ) -> np.ndarray:
233
+ """A class map in colour: [H, W] integer ids -> [H, W, 3] uint8 (RGB, BGR for
234
+ OpenCV with ``bgr``). ``colors`` ([N, 3] uint8) defaults to ``palette(num_classes)``
235
+ (num_classes default: the largest id + 1); ids below 0 (IGNORE_INDEX) are black, an
236
+ id >= N raises."""
237
+ classes = np.asarray(classes)
238
+ if classes.ndim != 2 or not np.issubdtype(classes.dtype, np.integer):
239
+ raise ValueError(
240
+ f"classes must be an HxW integer map, got {classes.dtype} {classes.shape}"
241
+ )
242
+ top = int(classes.max()) if classes.size else -1
243
+ if colors is None:
244
+ colors = palette(max(num_classes or 0, top + 1, 1))
245
+ colors = np.asarray(colors, np.uint8)
246
+ if top >= len(colors):
247
+ raise ValueError(f"class id {top} has no colour ({len(colors)} colours)")
248
+ table = np.concatenate([np.zeros((1, 3), np.uint8), colors]) # 0: ignored
249
+ rgb = table[np.where(classes < 0, 0, classes.astype(np.int64) + 1)]
250
+ return np.ascontiguousarray(rgb[..., ::-1]) if bgr else rgb
251
+
252
+
253
+ def top_classes(
254
+ classes: np.ndarray,
255
+ names: Optional[Sequence[str]] = None,
256
+ k: Optional[int] = 5,
257
+ ) -> List[Tuple[int, Union[str, None], float]]:
258
+ """The ``k`` largest classes of a class map (None: all present), largest first:
259
+ (class id, name or None, share of the labelled pixels); ties by class id, ignored
260
+ pixels (< 0) not counted."""
261
+ flat = np.asarray(classes).ravel()
262
+ flat = flat[flat >= 0]
263
+ if flat.size == 0:
264
+ return []
265
+ counts = np.bincount(flat.astype(np.int64))
266
+ present = np.flatnonzero(counts)
267
+ order = present[np.argsort(-counts[present], kind="stable")][:k]
268
+ return [
269
+ (
270
+ int(c),
271
+ names[c] if names is not None and c < len(names) else None,
272
+ counts[c] / flat.size,
273
+ )
274
+ for c in order
275
+ ]
models.json CHANGED
@@ -1,10 +1,10 @@
1
  {
2
- "_note": "Release files written by `python -m ldpt.models.l_dpt.convert SRC DST --preset l-dpt_large_depth_zeroshot` (or `--preset l-dpt_large_depth_mixed`) from the training checkpoints of configs/hybrid/ (docs/training.md), pinned to a commit of the model repo. The default is the first recommended entry; with one entry the UI shows no model choice. LDPT_CKPT_<NAME> (the id without 'l-dpt_', upper-cased, '-' -> '_': LDPT_CKPT_LARGE_DEPTH_ZEROSHOT, the variable of the API) replaces a source by a local release file. 'expect' pins release-config values checked before loading; 'sha256' is checked after a download.",
3
  "models": [
4
  {
5
  "id": "l-dpt_large_depth_zeroshot",
6
  "label": "L-DPT Large (zero-shot)",
7
- "description": "L-DPT Large (zero-shot): trained on 8 synthetic and multi-view sets only, with no image of the NYUv2, KITTI, DIODE or ETH3D benchmarks. The model for photos, and the model of every figure on the project page.",
8
  "recommended": true,
9
  "source": {
10
  "repo": "pointcept-bot/L-DPT",
 
1
  {
2
+ "_note": "Release files written by `python -m ldpt.models.l_dpt.convert` from the training checkpoints of configs/hybrid/ (docs/training.md), pinned to a commit of the model repo. The default is the first recommended entry; with one entry the UI shows no model choice. LDPT_CKPT_<NAME> (the id without 'l-dpt_', upper-cased, '-' -> '_': LDPT_CKPT_LARGE_DEPTH_ZEROSHOT, the variable of the API) replaces a source by a local release file. 'expect' pins release-config values checked before loading; 'sha256' is checked after a download.",
3
  "models": [
4
  {
5
  "id": "l-dpt_large_depth_zeroshot",
6
  "label": "L-DPT Large (zero-shot)",
7
+ "description": "L-DPT Large (zero-shot): trained on 8 synthetic and multi-view sets only, with no image of the NYUv2, KITTI, DIODE or ETH3D benchmarks. The model for photos, and the model of the demo examples and of the README figures.",
8
  "recommended": true,
9
  "source": {
10
  "repo": "pointcept-bot/L-DPT",
space_utils.py CHANGED
@@ -159,7 +159,7 @@ def check_inference(
159
  # that each fit still matches its measurements, so a new profiling run is entered here
160
  # first. Each GPU runs api.predict's attention order for it, except ZeroGPU (measured
161
  # with cuDNN attention first). The NVIDIA GB200 times are in docs/inference.md (the app
162
- # shows them only through the precomputed examples, examples.json "seconds").
163
 
164
 
165
  @dataclasses.dataclass(frozen=True)
 
159
  # that each fit still matches its measurements, so a new profiling run is entered here
160
  # first. Each GPU runs api.predict's attention order for it, except ZeroGPU (measured
161
  # with cuDNN attention first). The NVIDIA GB200 times are in docs/inference.md (the app
162
+ # shows none: a precomputed example names its GPU, not the seconds of its run).
163
 
164
 
165
  @dataclasses.dataclass(frozen=True)