Update the inference and evaluation code
Browse files- code/NOTICE +2 -2
- code/README.md +11 -13
- code/THIRD_PARTY_NOTICES.md +0 -47
- code/agt/completion/flux_fill.py +7 -8
- code/agt/completion/reliability.py +0 -120
- code/agt/data/clips.py +11 -11
- code/agt/dataset/visibility.py +11 -13
- code/agt/eval/depth.py +10 -27
- code/agt/eval/hole.py +15 -131
- code/agt/eval/method_dir.py +0 -42
- code/agt/eval/regional.py +6 -26
- code/agt/eval/regions.py +5 -32
- code/agt/eval/rgb.py +2 -11
- code/agt/eval/scorer.py +34 -150
- code/agt/eval/summary.py +11 -101
- code/agt/masks/pipeline.py +8 -13
- code/agt/model/build.py +1 -0
- code/agt/model/runtime.py +17 -21
- code/agt/model/visibility.py +1 -1
- code/agt/recon/outputs.py +0 -21
- code/agt/recon/reconstruct.py +59 -118
- code/agt/refine/capture.py +10 -10
- code/agt/refine/refine.py +47 -62
- code/configs/completion.json +0 -1
- code/configs/eval/test_waymo.json +1 -3
- code/configs/eval/val_waymo.json +1 -3
- code/configs/masks/occluder_v1.yaml +0 -6
- code/configs/masks/verify_prompt.md +4 -6
- code/configs/masks/verify_schema.json +1 -1
- code/configs/model.json +1 -1
- code/configs/refinement.json +0 -6
- code/eval/score.py +4 -5
- code/inference.py +13 -16
- code/requirements.txt +0 -2
code/NOTICE
CHANGED
|
@@ -8,5 +8,5 @@ University (DGGT, https://xiaomi-research.github.io/dggt/), licensed under the
|
|
| 8 |
Apache License, Version 2.0. The used files are vendored, with a small patch, in
|
| 9 |
third_party/dggt/ together with their original LICENSE and NOTICE files.
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
|
|
|
| 8 |
Apache License, Version 2.0. The used files are vendored, with a small patch, in
|
| 9 |
third_party/dggt/ together with their original LICENSE and NOTICE files.
|
| 10 |
|
| 11 |
+
The other vendored components keep their own licence files in
|
| 12 |
+
third_party/dggt/third_party/.
|
code/README.md
CHANGED
|
@@ -29,7 +29,7 @@
|
|
| 29 |
AGT reconstructs a complete 4D Gaussian scene from a driving video whose every frame is partly hidden by the hood,
|
| 30 |
the dashboard, windshield reflections or watermarks.
|
| 31 |
|
| 32 |
-
- **Amodal geometry recovery.** The occluder mask masks the occluder tokens in the attention layers, so that the
|
| 33 |
feed-forward model recovers cameras, depth and motion from the obstructed frames in a single pass.
|
| 34 |
- **Observed appearance reconstruction.** The observability of every pixel is computed from this geometry, and
|
| 35 |
appearance is reconstructed only in the observed regions.
|
|
@@ -86,7 +86,7 @@ The AGT weights are hosted at [MRBSTUDIO/AGT](https://huggingface.co/MRBSTUDIO/A
|
|
| 86 |
```bash
|
| 87 |
hf download MRBSTUDIO/AGT agt_reconstruction.safetensors agt_completion_lora.safetensors --local-dir checkpoints/
|
| 88 |
hf download zbww/tapip3d tapip3d_final.pth --local-dir checkpoints/
|
| 89 |
-
mv checkpoints/tapip3d_final.pth checkpoints/
|
| 90 |
```
|
| 91 |
|
| 92 |
| File | Content | Size |
|
|
@@ -99,8 +99,7 @@ FLUX.1-Fill-dev and SegFormer are loaded from the Hugging Face Hub, or from loca
|
|
| 99 |
|
| 100 |
## Demo
|
| 101 |
|
| 102 |
-
The example clips of the project page are part of the dataset repository.
|
| 103 |
-
occluder mask and the clip metadata. Run the commands from the repository root.
|
| 104 |
|
| 105 |
```bash
|
| 106 |
hf download MRBSTUDIO/AmodalDrive --repo-type dataset --include "examples/*" --local-dir AmodalDrive
|
|
@@ -116,7 +115,7 @@ Outputs are rendered at 518x294.
|
|
| 116 |
|
| 117 |
## Inference on your own video
|
| 118 |
|
| 119 |
-
Cut a
|
| 120 |
|
| 121 |
```bash
|
| 122 |
python tools/prepare_clip.py --video drive.mp4 --start 12 --out work/export
|
|
@@ -138,13 +137,13 @@ python inference.py --export work/export --mask-dir work/masks --out outputs/my_
|
|
| 138 |
--completion-python "$(conda run -n agt-completion which python)"
|
| 139 |
```
|
| 140 |
|
| 141 |
-
The output directory holds the rendered frames
|
| 142 |
|
| 143 |
## Evaluation
|
| 144 |
|
| 145 |
Build the benchmark first, see [Dataset](#dataset). Both commands use the precomputed occluder masks of AmodalDrive.
|
| 146 |
|
| 147 |
-
**AGT without completion**
|
| 148 |
|
| 149 |
```bash
|
| 150 |
python -m agt.recon.reconstruct render --inputs AmodalDrive/exports/test --out outputs/test_feedforward \
|
|
@@ -159,11 +158,11 @@ python eval/score.py --config configs/eval/test_waymo.json --data-root AmodalDri
|
|
| 159 |
python inference.py --export AmodalDrive/exports/test --masks dataset --data-root AmodalDrive \
|
| 160 |
--out outputs/test_full --completion-python "$(conda run -n agt-completion which python)"
|
| 161 |
python eval/score.py --config configs/eval/test_waymo.json --data-root AmodalDrive \
|
| 162 |
-
--export AmodalDrive/exports/test --method outputs/test_full/final --out scores/test_full
|
| 163 |
```
|
| 164 |
|
| 165 |
-
`--clips ID ...` restricts `inference.py` to a subset of the export.
|
| 166 |
-
|
| 167 |
|
| 168 |
## Dataset
|
| 169 |
|
|
@@ -233,12 +232,11 @@ This code builds on the following projects. We thank their authors.
|
|
| 233 |
- [VGGT](https://github.com/facebookresearch/vggt): the geometry backbone of DGGT.
|
| 234 |
- [gsplat](https://github.com/nerfstudio-project/gsplat): Gaussian rasterization.
|
| 235 |
- [FLUX.1-Fill](https://huggingface.co/black-forest-labs/FLUX.1-Fill-dev): the image completion model.
|
| 236 |
-
- [TAPIP3D](https://github.com/zbw001/TAPIP3D) and [CoTracker](https://github.com/facebookresearch/co-tracker):
|
| 237 |
- [SAM 3](https://github.com/facebookresearch/sam3) and [Qwen3.5](https://huggingface.co/Qwen/Qwen3.5-35B-A3B): occluder mask generation.
|
| 238 |
- [Waymo Open Dataset](https://waymo.com/open/), [nuScenes](https://www.nuscenes.org/), [Argoverse 2](https://www.argoverse.org/av2.html), [BDD100K](https://www.vis.xyz/bdd100k/) and [MM-AU](https://github.com/jeffreychou777/LOTVS-MM-AU): data sources.
|
| 239 |
|
| 240 |
## License
|
| 241 |
|
| 242 |
-
- **Code**: Apache License 2.0, see `LICENSE`. Vendored third-party code keeps its own license, see `NOTICE`
|
| 243 |
-
`THIRD_PARTY_NOTICES.md`.
|
| 244 |
- **Weights and dataset**: CC BY-NC 4.0.
|
|
|
|
| 29 |
AGT reconstructs a complete 4D Gaussian scene from a driving video whose every frame is partly hidden by the hood,
|
| 30 |
the dashboard, windshield reflections or watermarks.
|
| 31 |
|
| 32 |
+
- **Amodal geometry recovery.** The occluder mask masks the occluder tokens in the global attention layers, so that the
|
| 33 |
feed-forward model recovers cameras, depth and motion from the obstructed frames in a single pass.
|
| 34 |
- **Observed appearance reconstruction.** The observability of every pixel is computed from this geometry, and
|
| 35 |
appearance is reconstructed only in the observed regions.
|
|
|
|
| 86 |
```bash
|
| 87 |
hf download MRBSTUDIO/AGT agt_reconstruction.safetensors agt_completion_lora.safetensors --local-dir checkpoints/
|
| 88 |
hf download zbww/tapip3d tapip3d_final.pth --local-dir checkpoints/
|
| 89 |
+
mv checkpoints/tapip3d_final.pth checkpoints/motion_head.pth
|
| 90 |
```
|
| 91 |
|
| 92 |
| File | Content | Size |
|
|
|
|
| 99 |
|
| 100 |
## Demo
|
| 101 |
|
| 102 |
+
The example clips of the project page are part of the dataset repository. Run the commands from the repository root.
|
|
|
|
| 103 |
|
| 104 |
```bash
|
| 105 |
hf download MRBSTUDIO/AmodalDrive --repo-type dataset --include "examples/*" --local-dir AmodalDrive
|
|
|
|
| 115 |
|
| 116 |
## Inference on your own video
|
| 117 |
|
| 118 |
+
Cut a clip from the video:
|
| 119 |
|
| 120 |
```bash
|
| 121 |
python tools/prepare_clip.py --video drive.mp4 --start 12 --out work/export
|
|
|
|
| 137 |
--completion-python "$(conda run -n agt-completion which python)"
|
| 138 |
```
|
| 139 |
|
| 140 |
+
The output directory holds the rendered frames and depth of every clip.
|
| 141 |
|
| 142 |
## Evaluation
|
| 143 |
|
| 144 |
Build the benchmark first, see [Dataset](#dataset). Both commands use the precomputed occluder masks of AmodalDrive.
|
| 145 |
|
| 146 |
+
**AGT without completion**:
|
| 147 |
|
| 148 |
```bash
|
| 149 |
python -m agt.recon.reconstruct render --inputs AmodalDrive/exports/test --out outputs/test_feedforward \
|
|
|
|
| 158 |
python inference.py --export AmodalDrive/exports/test --masks dataset --data-root AmodalDrive \
|
| 159 |
--out outputs/test_full --completion-python "$(conda run -n agt-completion which python)"
|
| 160 |
python eval/score.py --config configs/eval/test_waymo.json --data-root AmodalDrive \
|
| 161 |
+
--export AmodalDrive/exports/test --method outputs/test_full/final --out scores/test_full
|
| 162 |
```
|
| 163 |
|
| 164 |
+
`--clips ID ...` restricts `inference.py` to a subset of the export. `configs/eval/val_waymo.json` scores the
|
| 165 |
+
validation export.
|
| 166 |
|
| 167 |
## Dataset
|
| 168 |
|
|
|
|
| 232 |
- [VGGT](https://github.com/facebookresearch/vggt): the geometry backbone of DGGT.
|
| 233 |
- [gsplat](https://github.com/nerfstudio-project/gsplat): Gaussian rasterization.
|
| 234 |
- [FLUX.1-Fill](https://huggingface.co/black-forest-labs/FLUX.1-Fill-dev): the image completion model.
|
| 235 |
+
- [TAPIP3D](https://github.com/zbw001/TAPIP3D) and [CoTracker](https://github.com/facebookresearch/co-tracker): the motion head.
|
| 236 |
- [SAM 3](https://github.com/facebookresearch/sam3) and [Qwen3.5](https://huggingface.co/Qwen/Qwen3.5-35B-A3B): occluder mask generation.
|
| 237 |
- [Waymo Open Dataset](https://waymo.com/open/), [nuScenes](https://www.nuscenes.org/), [Argoverse 2](https://www.argoverse.org/av2.html), [BDD100K](https://www.vis.xyz/bdd100k/) and [MM-AU](https://github.com/jeffreychou777/LOTVS-MM-AU): data sources.
|
| 238 |
|
| 239 |
## License
|
| 240 |
|
| 241 |
+
- **Code**: Apache License 2.0, see `LICENSE`. Vendored third-party code keeps its own license, see `NOTICE`.
|
|
|
|
| 242 |
- **Weights and dataset**: CC BY-NC 4.0.
|
code/THIRD_PARTY_NOTICES.md
DELETED
|
@@ -1,47 +0,0 @@
|
|
| 1 |
-
# Third-party notices
|
| 2 |
-
|
| 3 |
-
The AGT code in this repository is licensed under the Apache License, Version 2.0 (see `LICENSE`).
|
| 4 |
-
The released AGT model weights (reconstruction checkpoint and completion LoRA) are distributed separately under
|
| 5 |
-
CC BY-NC 4.0; they are fine-tuned from the DGGT Waymo checkpoint, on data derived from the Waymo Open Dataset, and
|
| 6 |
-
the LoRA adapts FLUX.1-Fill-dev, so the terms of those sources also apply.
|
| 7 |
-
|
| 8 |
-
## Vendored code
|
| 9 |
-
|
| 10 |
-
| Component | Location | Upstream | Licence |
|
| 11 |
-
|---|---|---|---|
|
| 12 |
-
| DGGT (model, heads, layers, sky model, `utils/interplation.py`) | `third_party/dggt/` | https://xiaomi-research.github.io/dggt/ (commit a3276d2) | Apache-2.0, `third_party/dggt/LICENSE` and `NOTICE`; parts derived from VGGT (facebookresearch/vggt), see the DGGT `NOTICE` |
|
| 13 |
-
| TAPIP3D (as shipped inside DGGT) | `third_party/dggt/third_party/TAPIP3D/` | https://github.com/zbw001/TAPIP3D | Apache-2.0, `third_party/dggt/third_party/TAPIP3D/LICENSE` |
|
| 14 |
-
| CoTracker utilities (as shipped inside DGGT and TAPIP3D) | `third_party/dggt/third_party/cotracker/` | https://github.com/facebookresearch/co-tracker | CC BY-NC 4.0, `third_party/dggt/third_party/cotracker/LICENSE.md` |
|
| 15 |
-
| pointops2 (as shipped inside DGGT and TAPIP3D) | `third_party/dggt/third_party/pointops2/` | Stratified Transformer, https://github.com/dvlab-research/Stratified-Transformer (`lib/pointops2`) | MIT, `third_party/dggt/third_party/pointops2/LICENSE.md` |
|
| 16 |
-
|
| 17 |
-
The three licence files are copied from the upstream repositories (TAPIP3D at commit 4cb7e69, co-tracker at commit
|
| 18 |
-
82e02e8, Stratified-Transformer at commit 140783d). The vendored `cotracker/` and `pointops2/` files are identical to
|
| 19 |
-
the copies in TAPIP3D's `third_party/`; the pointops2 functions are identical to Stratified Transformer's
|
| 20 |
-
`lib/pointops2`. The DGGT repository does not ship licence files for these three directories, so the exact upstream
|
| 21 |
-
commit they were taken from is not recorded.
|
| 22 |
-
|
| 23 |
-
Changes to vendored files: only `third_party/dggt/third_party/TAPIP3D/models/encoders/cotracker_cnn.py`, see
|
| 24 |
-
`third_party/dggt/CHANGES.patch`. Files of the DGGT repository that this code does not use are not included.
|
| 25 |
-
|
| 26 |
-
Code ported from DGGT into the `agt` package (Apache-2.0): the render of DGGT `train.py` used at the
|
| 27 |
-
target cameras (`agt/recon/reconstruct.py`), the attention forward of `dggt/layers/attention.py` and the global
|
| 28 |
-
attention loop of `dggt/models/aggregator.py` (`agt/model/mask_attention.py`), a vectorized copy of `interp_all`
|
| 29 |
-
(`agt/recon/interp.py`), the image preprocessing of `datasets/dataset.py` (`agt/recon/preprocess.py`) and the
|
| 30 |
-
SegFormer sky masks of `datasets/tools/extract_masks.py` (`agt/recon/sky.py`).
|
| 31 |
-
|
| 32 |
-
## Models and weights loaded at run time (not included; obtain them under their own terms)
|
| 33 |
-
|
| 34 |
-
| Model | Used for | Source |
|
| 35 |
-
|---|---|---|
|
| 36 |
-
| FLUX.1-Fill-dev | generative completion | https://huggingface.co/black-forest-labs/FLUX.1-Fill-dev (FLUX.1 [dev] Non-Commercial License) |
|
| 37 |
-
| SegFormer-B5 Cityscapes | sky masks | https://huggingface.co/nvidia/segformer-b5-finetuned-cityscapes-1024-1024 (NVIDIA licence) |
|
| 38 |
-
| TAPIP3D checkpoint | dynamic-object tracking between input frames | https://huggingface.co/zbww/tapip3d (`tapip3d_final.pth`) |
|
| 39 |
-
| CoTracker3 (torch.hub) | feature encoder initialisation inside TAPIP3D | https://github.com/facebookresearch/co-tracker |
|
| 40 |
-
| SAM 3 | occluder proposals for new clips | https://github.com/facebookresearch/sam3 (SAM License) |
|
| 41 |
-
| Qwen3.5 | occluder verification for new clips | https://huggingface.co/Qwen/Qwen3.5-35B-A3B (Apache-2.0) |
|
| 42 |
-
| LPIPS (AlexNet), DISTS, Inception (FID/KID) | evaluation metrics | `lpips`, `DISTS_pytorch`, `torchmetrics` / `torch-fidelity` packages |
|
| 43 |
-
|
| 44 |
-
## Data
|
| 45 |
-
|
| 46 |
-
The evaluation reads the Waymo Open Dataset (not redistributed; users download it under the Waymo licence) and
|
| 47 |
-
the AmodalDrive files (https://huggingface.co/datasets/MRBSTUDIO/AmodalDrive, CC BY-NC 4.0).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
code/agt/completion/flux_fill.py
CHANGED
|
@@ -8,7 +8,6 @@ from pathlib import Path
|
|
| 8 |
import numpy as np
|
| 9 |
|
| 10 |
from .handoff import write_handoff
|
| 11 |
-
from .reliability import load_repair_mask
|
| 12 |
|
| 13 |
CONFIG = Path(__file__).resolve().parents[2] / 'configs' / 'completion.json'
|
| 14 |
GRID_HW = (294, 518)
|
|
@@ -131,17 +130,16 @@ def fix_frame(pipe, frame_u8, mask, prompt_embeds, pooled_prompt_embeds, samplin
|
|
| 131 |
def main(argv=None):
|
| 132 |
import torch
|
| 133 |
p = argparse.ArgumentParser(prog='agt.completion.flux_fill')
|
| 134 |
-
p.add_argument('--pass1', required=True, help='
|
| 135 |
-
p.add_argument('--rel', required=True, help='reliability maps (agt.completion.reliability)')
|
| 136 |
p.add_argument('--out', required=True)
|
| 137 |
p.add_argument('--config', default=str(CONFIG))
|
| 138 |
p.add_argument('--base', default=None, help='FLUX.1-Fill-dev: local diffusers directory or hub id (default: config)')
|
| 139 |
p.add_argument('--lora', default='checkpoints/agt_completion_lora.safetensors')
|
| 140 |
-
p.add_argument('--clips', nargs='+', help='clip ids (default: every clip of --
|
| 141 |
a = p.parse_args(argv)
|
| 142 |
cfg = json.loads(Path(a.config).read_text())
|
| 143 |
sampling, position = cfg['sampling'], cfg['position']
|
| 144 |
-
clips = a.clips or sorted(d.name for d in Path(a.
|
| 145 |
out = Path(a.out)
|
| 146 |
dev = torch.device('cuda:0')
|
| 147 |
t0 = time.time()
|
|
@@ -151,14 +149,15 @@ def main(argv=None):
|
|
| 151 |
for cid in clips:
|
| 152 |
with np.load(Path(a.pass1) / cid / 'frames.npz', allow_pickle=False) as h:
|
| 153 |
frame = h['rgb'][position].astype(np.float32)
|
| 154 |
-
|
|
|
|
| 155 |
ti = time.time()
|
| 156 |
fixed = fix_frame(pipe, to_u8(frame), mask, pe, ppe, sampling)
|
| 157 |
fixed01 = fixed.astype(np.float32) / np.float32(255)
|
| 158 |
meta = dict(clip_id=cid, generator='FLUX.1-Fill-dev' + (' + LoRA' if a.lora else ''), prompt=cfg['prompt'],
|
| 159 |
-
sampling=sampling, dtype=cfg['dtype'], position=position
|
| 160 |
write_handoff(out / f'{cid}.npz', fixed01[None], mask[None], [position], meta)
|
| 161 |
-
print(json.dumps(dict(clip=cid, seconds=round(time.time() - ti, 1),
|
| 162 |
|
| 163 |
|
| 164 |
if __name__ == '__main__':
|
|
|
|
| 8 |
import numpy as np
|
| 9 |
|
| 10 |
from .handoff import write_handoff
|
|
|
|
| 11 |
|
| 12 |
CONFIG = Path(__file__).resolve().parents[2] / 'configs' / 'completion.json'
|
| 13 |
GRID_HW = (294, 518)
|
|
|
|
| 130 |
def main(argv=None):
|
| 131 |
import torch
|
| 132 |
p = argparse.ArgumentParser(prog='agt.completion.flux_fill')
|
| 133 |
+
p.add_argument('--pass1', required=True, help='reconstruction output directory (frames.npz, observability.npz)')
|
|
|
|
| 134 |
p.add_argument('--out', required=True)
|
| 135 |
p.add_argument('--config', default=str(CONFIG))
|
| 136 |
p.add_argument('--base', default=None, help='FLUX.1-Fill-dev: local diffusers directory or hub id (default: config)')
|
| 137 |
p.add_argument('--lora', default='checkpoints/agt_completion_lora.safetensors')
|
| 138 |
+
p.add_argument('--clips', nargs='+', help='clip ids (default: every clip of --pass1)')
|
| 139 |
a = p.parse_args(argv)
|
| 140 |
cfg = json.loads(Path(a.config).read_text())
|
| 141 |
sampling, position = cfg['sampling'], cfg['position']
|
| 142 |
+
clips = a.clips or sorted(d.name for d in Path(a.pass1).iterdir() if (d / 'observability.npz').is_file())
|
| 143 |
out = Path(a.out)
|
| 144 |
dev = torch.device('cuda:0')
|
| 145 |
t0 = time.time()
|
|
|
|
| 149 |
for cid in clips:
|
| 150 |
with np.load(Path(a.pass1) / cid / 'frames.npz', allow_pickle=False) as h:
|
| 151 |
frame = h['rgb'][position].astype(np.float32)
|
| 152 |
+
with np.load(Path(a.pass1) / cid / 'observability.npz', allow_pickle=False) as h:
|
| 153 |
+
mask = h['unobserved'][position].astype(bool)
|
| 154 |
ti = time.time()
|
| 155 |
fixed = fix_frame(pipe, to_u8(frame), mask, pe, ppe, sampling)
|
| 156 |
fixed01 = fixed.astype(np.float32) / np.float32(255)
|
| 157 |
meta = dict(clip_id=cid, generator='FLUX.1-Fill-dev' + (' + LoRA' if a.lora else ''), prompt=cfg['prompt'],
|
| 158 |
+
sampling=sampling, dtype=cfg['dtype'], position=position)
|
| 159 |
write_handoff(out / f'{cid}.npz', fixed01[None], mask[None], [position], meta)
|
| 160 |
+
print(json.dumps(dict(clip=cid, seconds=round(time.time() - ti, 1), unobserved_fraction=float(mask.mean()))), flush=True)
|
| 161 |
|
| 162 |
|
| 163 |
if __name__ == '__main__':
|
code/agt/completion/reliability.py
DELETED
|
@@ -1,120 +0,0 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import argparse
|
| 4 |
-
import json
|
| 5 |
-
from pathlib import Path
|
| 6 |
-
|
| 7 |
-
import numpy as np
|
| 8 |
-
|
| 9 |
-
EXPORT_CONTEXT = [0, 5, 10, 15]
|
| 10 |
-
MAX_SOURCES = 8
|
| 11 |
-
LEDGER = {'S': 0, 'G': 1, 'R': 2}
|
| 12 |
-
CONFIG = Path(__file__).resolve().parents[2] / 'configs' / 'completion.json'
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def source_chunks(sources):
|
| 16 |
-
sources = list(sources)
|
| 17 |
-
return [sources[i:i + MAX_SOURCES] for i in range(0, len(sources), MAX_SOURCES)]
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def observation_count(depth, K, c2w, mask, context_positions, *, device='cpu'):
|
| 21 |
-
import torch
|
| 22 |
-
from ..model.visibility import visibility_camera
|
| 23 |
-
depth = torch.as_tensor(np.asarray(depth), dtype=torch.float64, device=device)
|
| 24 |
-
t, h, w = depth.shape
|
| 25 |
-
mask_np = np.asarray(mask, bool)
|
| 26 |
-
n = None
|
| 27 |
-
for chunk in source_chunks(context_positions):
|
| 28 |
-
res = visibility_camera(depth[None], torch.as_tensor(np.asarray(K), dtype=torch.float64, device=device)[None],
|
| 29 |
-
torch.as_tensor(np.asarray(c2w), dtype=torch.float64, device=device)[None],
|
| 30 |
-
torch.ones((1, t, h, w), dtype=torch.bool, device=device), list(chunk),
|
| 31 |
-
alpha=torch.as_tensor(mask_np, dtype=torch.float64, device=device)[None])
|
| 32 |
-
b = res['bits'][0].cpu().numpy()
|
| 33 |
-
c = np.unpackbits(b[..., None], axis=-1).sum(-1).astype(np.uint8)
|
| 34 |
-
n = c if n is None else n + c
|
| 35 |
-
for p in context_positions:
|
| 36 |
-
n[p] += (~mask_np[p]).astype(np.uint8)
|
| 37 |
-
valid = (torch.isfinite(depth) & (depth > 0)).cpu().numpy()
|
| 38 |
-
return {'n': n, 'valid': valid}
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
def compose(n, alpha, sky, taus, mask):
|
| 42 |
-
n, alpha, sky = np.asarray(n), np.asarray(alpha, np.float32), np.asarray(sky, bool)
|
| 43 |
-
U = (n == 0) & ~(sky & ~np.broadcast_to(np.asarray(mask, bool), sky.shape))
|
| 44 |
-
holes = np.stack([(alpha < tau) & ~sky for tau in taus])
|
| 45 |
-
repair = U[None] | holes
|
| 46 |
-
ledger = np.zeros(holes.shape, np.uint8)
|
| 47 |
-
ledger[holes & ~U[None]] = LEDGER['R']
|
| 48 |
-
ledger[np.broadcast_to(U, holes.shape)] = LEDGER['G']
|
| 49 |
-
return {'U': U, 'holes': holes, 'repair_mask': repair, 'ledger': ledger}
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
def load_pass1(pass1, cid):
|
| 53 |
-
d = Path(pass1) / cid
|
| 54 |
-
with np.load(d / 'depth.npz') as f:
|
| 55 |
-
depth, alpha = f['depth'].astype(np.float32), f['alpha'].astype(np.float32)
|
| 56 |
-
with np.load(d / 'render_cameras.npz') as f:
|
| 57 |
-
cams = {k: f[k] for k in f.files}
|
| 58 |
-
with np.load(d / 'render_sky.npz') as f:
|
| 59 |
-
sky = f['sky'].astype(bool)
|
| 60 |
-
return dict(depth=depth, alpha=alpha, K=cams['K'], c2w=cams['c2w'], w2c=cams['w2c'], sky=sky,
|
| 61 |
-
positions=cams['positions'].tolist(), context_positions=cams['context_positions'].tolist())
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
def build_clip(pass1, inputs, masks, cid, *, taus, device='cpu'):
|
| 65 |
-
clip = json.loads((Path(inputs) / cid / 'clip.json').read_text())
|
| 66 |
-
if clip['context_positions'] != EXPORT_CONTEXT:
|
| 67 |
-
raise ValueError(f'{cid}: input frames {clip["context_positions"]} of the export')
|
| 68 |
-
p1 = load_pass1(pass1, cid)
|
| 69 |
-
occluder_mask = masks.load(clip)[0]
|
| 70 |
-
mask = np.broadcast_to(np.asarray(occluder_mask, bool), p1['depth'].shape)
|
| 71 |
-
context = p1['context_positions']
|
| 72 |
-
obs = observation_count(p1['depth'], p1['K'], p1['c2w'], mask, context, device=device)
|
| 73 |
-
maps = compose(obs['n'], p1['alpha'], p1['sky'], taus, occluder_mask)
|
| 74 |
-
return dict(n=obs['n'], alpha=p1['alpha'], sky=p1['sky'], depth_valid=obs['valid'], U=maps['U'],
|
| 75 |
-
holes=maps['holes'], repair_mask=maps['repair_mask'], ledger=maps['ledger'],
|
| 76 |
-
taus=np.asarray(taus, np.float32), positions=np.asarray(p1['positions']),
|
| 77 |
-
context_positions=np.asarray(context))
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
def write_clip(out, cid, arrays):
|
| 81 |
-
d = Path(out) / cid
|
| 82 |
-
d.mkdir(parents=True, exist_ok=True)
|
| 83 |
-
temp = d / '.reliability.npz'
|
| 84 |
-
np.savez_compressed(temp, **arrays)
|
| 85 |
-
temp.replace(d / 'reliability.npz')
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
def load_repair_mask(rel, cid, tau):
|
| 89 |
-
with np.load(Path(rel) / cid / 'reliability.npz', allow_pickle=False) as h:
|
| 90 |
-
taus = [round(float(x), 6) for x in h['taus']]
|
| 91 |
-
return h['repair_mask'][taus.index(round(float(tau), 6))].astype(bool)
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
def main(argv=None):
|
| 95 |
-
from ..recon.reconstruct import open_masks
|
| 96 |
-
p = argparse.ArgumentParser(prog='agt.completion.reliability')
|
| 97 |
-
p.add_argument('--pass1', required=True, help='first-pass output directory (reconstruct with '
|
| 98 |
-
'--export-render-cameras --export-render-sky)')
|
| 99 |
-
p.add_argument('--inputs', required=True, help='clip export of the first pass')
|
| 100 |
-
p.add_argument('--out', required=True)
|
| 101 |
-
p.add_argument('--config', default=str(CONFIG), help='completion config (tau)')
|
| 102 |
-
p.add_argument('--masks', choices=('dataset', 'dir', 'images'), default='dataset', help='as in the first pass')
|
| 103 |
-
p.add_argument('--data-root')
|
| 104 |
-
p.add_argument('--mask-dir')
|
| 105 |
-
p.add_argument('--mask-dilate', type=int, default=0)
|
| 106 |
-
p.add_argument('--clips', nargs='+', help='clip ids (default: every clip of the export)')
|
| 107 |
-
p.add_argument('--device', default='cuda')
|
| 108 |
-
a = p.parse_args(argv)
|
| 109 |
-
taus = (json.loads(Path(a.config).read_text())['tau'],)
|
| 110 |
-
masks = open_masks(a)
|
| 111 |
-
cids = a.clips or json.loads((Path(a.inputs) / 'manifest.json').read_text())['clips']
|
| 112 |
-
for cid in cids:
|
| 113 |
-
arrays = build_clip(a.pass1, a.inputs, masks, cid, taus=taus, device=a.device)
|
| 114 |
-
write_clip(a.out, cid, arrays)
|
| 115 |
-
print(json.dumps(dict(clip=cid, U=float(arrays['U'].mean()),
|
| 116 |
-
repair=[float(r.mean()) for r in arrays['repair_mask']])), flush=True)
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
if __name__ == '__main__':
|
| 120 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
code/agt/data/clips.py
CHANGED
|
@@ -20,28 +20,28 @@ def frame_times(frames_meta) -> dict:
|
|
| 20 |
if len(start) < 2 or not np.all(np.diff(start) > 0) or np.any(end < start):
|
| 21 |
raise ValueError('Frame timestamps must be strictly increasing with end >= start')
|
| 22 |
mid = (start.astype(np.float64) + end) / 2
|
| 23 |
-
|
| 24 |
-
period = float(
|
| 25 |
-
return {'start_us': start, 'end_us': end, 'mid_us': mid, '
|
| 26 |
-
'duration_us': period * len(
|
| 27 |
|
| 28 |
|
| 29 |
-
def nearest_frames(
|
| 30 |
targets = np.asarray(targets_us, dtype=np.float64)
|
| 31 |
-
right = np.clip(np.searchsorted(
|
| 32 |
left = right - 1
|
| 33 |
-
pick = np.where(np.abs(
|
| 34 |
-
return pick.astype(np.int64), np.abs(
|
| 35 |
|
| 36 |
|
| 37 |
def selection_tolerance_us(period_us: float, tolerance_us: float | None = None) -> float:
|
| 38 |
return float(period_us) / 2 if tolerance_us is None else float(tolerance_us)
|
| 39 |
|
| 40 |
|
| 41 |
-
def select_frames(
|
| 42 |
tol = selection_tolerance_us(period_us, tolerance_us)
|
| 43 |
targets = np.asarray(targets_us, dtype=np.float64)
|
| 44 |
-
pick, error = nearest_frames(
|
| 45 |
far = error > tol
|
| 46 |
rules = ([RULE_NO_FRAME] if np.any(far) else []) + ([RULE_SAME_FRAME] if np.any(np.diff(pick) <= 0) else [])
|
| 47 |
if rules:
|
|
@@ -68,7 +68,7 @@ def build_clips(protocol: ClipProtocol, record, frames_meta, *, sample_id: str |
|
|
| 68 |
clips = []
|
| 69 |
for start_us in protocol.window_starts_us(times['duration_us'], times['period_us']):
|
| 70 |
try:
|
| 71 |
-
idx, error = select_frames(times['
|
| 72 |
except FrameSelectionError as exc:
|
| 73 |
if skipped is None:
|
| 74 |
raise
|
|
|
|
| 20 |
if len(start) < 2 or not np.all(np.diff(start) > 0) or np.any(end < start):
|
| 21 |
raise ValueError('Frame timestamps must be strictly increasing with end >= start')
|
| 22 |
mid = (start.astype(np.float64) + end) / 2
|
| 23 |
+
elapsed = mid - mid[0]
|
| 24 |
+
period = float(elapsed[-1] / (len(elapsed) - 1))
|
| 25 |
+
return {'start_us': start, 'end_us': end, 'mid_us': mid, 'elapsed_us': elapsed, 'period_us': period,
|
| 26 |
+
'duration_us': period * len(elapsed)}
|
| 27 |
|
| 28 |
|
| 29 |
+
def nearest_frames(elapsed_us: np.ndarray, targets_us) -> tuple:
|
| 30 |
targets = np.asarray(targets_us, dtype=np.float64)
|
| 31 |
+
right = np.clip(np.searchsorted(elapsed_us, targets), 1, len(elapsed_us) - 1)
|
| 32 |
left = right - 1
|
| 33 |
+
pick = np.where(np.abs(elapsed_us[left] - targets) <= np.abs(elapsed_us[right] - targets), left, right)
|
| 34 |
+
return pick.astype(np.int64), np.abs(elapsed_us[pick] - targets)
|
| 35 |
|
| 36 |
|
| 37 |
def selection_tolerance_us(period_us: float, tolerance_us: float | None = None) -> float:
|
| 38 |
return float(period_us) / 2 if tolerance_us is None else float(tolerance_us)
|
| 39 |
|
| 40 |
|
| 41 |
+
def select_frames(elapsed_us: np.ndarray, targets_us, period_us: float, tolerance_us: float | None = None) -> tuple:
|
| 42 |
tol = selection_tolerance_us(period_us, tolerance_us)
|
| 43 |
targets = np.asarray(targets_us, dtype=np.float64)
|
| 44 |
+
pick, error = nearest_frames(elapsed_us, targets)
|
| 45 |
far = error > tol
|
| 46 |
rules = ([RULE_NO_FRAME] if np.any(far) else []) + ([RULE_SAME_FRAME] if np.any(np.diff(pick) <= 0) else [])
|
| 47 |
if rules:
|
|
|
|
| 68 |
clips = []
|
| 69 |
for start_us in protocol.window_starts_us(times['duration_us'], times['period_us']):
|
| 70 |
try:
|
| 71 |
+
idx, error = select_frames(times['elapsed_us'], start_us + offsets, times['period_us'], tolerance_us)
|
| 72 |
except FrameSelectionError as exc:
|
| 73 |
if skipped is None:
|
| 74 |
raise
|
code/agt/dataset/visibility.py
CHANGED
|
@@ -17,7 +17,6 @@ SEMANTICS = 'camera-occluder only; scene self-occlusion not modelled'
|
|
| 17 |
RECIPE = 'camera_only_v2'
|
| 18 |
SOURCE_POLICY = 'occluder_policy_hard_v1'
|
| 19 |
OFFSET_RADIUS = 20
|
| 20 |
-
TOLERANCES = {.05: 'strict'}
|
| 21 |
SOURCE = 'waymo'
|
| 22 |
DGGT_CHECKPOINT = 'https://huggingface.co/xiaomi-research/dggt/resolve/main/model_latest_waymo.pt'
|
| 23 |
DGGT_UNUSED_HEADS = ('point_head', 'semantic_head')
|
|
@@ -180,19 +179,18 @@ def pair_bits(depth, K, c2w, occluder, *, offsets, device='cuda'):
|
|
| 180 |
count, h, w = depth.shape
|
| 181 |
source_occluder = torch.as_tensor(np.broadcast_to(occluder, (count, h, w)).copy(), dtype=torch.float64, device=device)
|
| 182 |
pixels = np.arange(h*w, dtype=np.int32)
|
| 183 |
-
packed =
|
| 184 |
for j in range(count):
|
| 185 |
lo, hi = max(0, j-radius), min(count, j+radius+1)
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
return packed
|
| 196 |
|
| 197 |
|
| 198 |
def write_cache(path, identity, packed, scales, K, c2w, owners, *, timings=None):
|
|
@@ -220,7 +218,7 @@ def write_cache(path, identity, packed, scales, K, c2w, owners, *, timings=None)
|
|
| 220 |
|
| 221 |
def manifest(offsets) -> dict:
|
| 222 |
return {'schema': SCHEMA, 'label_id': LABEL_ID, 'implementation_version': LABEL_ID, 'recipe': RECIPE,
|
| 223 |
-
'visibility_semantics': SEMANTICS, 'depth_consistency': False,
|
| 224 |
'source_alpha_tolerance': .1, 'source_filter_label': SOURCE_POLICY,
|
| 225 |
'offsets_by_source': {SOURCE: list(offsets)},
|
| 226 |
'storage': 'strict[frame, offset, ceil(H*W/8)] little bit order; all target pixels',
|
|
|
|
| 17 |
RECIPE = 'camera_only_v2'
|
| 18 |
SOURCE_POLICY = 'occluder_policy_hard_v1'
|
| 19 |
OFFSET_RADIUS = 20
|
|
|
|
| 20 |
SOURCE = 'waymo'
|
| 21 |
DGGT_CHECKPOINT = 'https://huggingface.co/xiaomi-research/dggt/resolve/main/model_latest_waymo.pt'
|
| 22 |
DGGT_UNUSED_HEADS = ('point_head', 'semantic_head')
|
|
|
|
| 179 |
count, h, w = depth.shape
|
| 180 |
source_occluder = torch.as_tensor(np.broadcast_to(occluder, (count, h, w)).copy(), dtype=torch.float64, device=device)
|
| 181 |
pixels = np.arange(h*w, dtype=np.int32)
|
| 182 |
+
packed = np.zeros((count, len(offsets), (len(pixels)+7)//8), np.uint8)
|
| 183 |
for j in range(count):
|
| 184 |
lo, hi = max(0, j-radius), min(count, j+radius+1)
|
| 185 |
+
result = visibility_camera(depth[None, lo:hi], K[None, lo:hi], c2w[None, lo:hi],
|
| 186 |
+
torch.ones((1, hi-lo, h, w), dtype=torch.bool, device=device), [j-lo],
|
| 187 |
+
alpha=source_occluder[None, lo:hi])
|
| 188 |
+
selected = result['bits'][0].reshape(hi-lo, h*w).cpu().numpy()
|
| 189 |
+
bits = np.packbits(selected, axis=-1, bitorder='little')
|
| 190 |
+
for t in range(lo, hi):
|
| 191 |
+
if t != j:
|
| 192 |
+
packed[t, offsets.index(j-t)] = bits[t-lo]
|
| 193 |
+
return {'strict': packed}
|
|
|
|
| 194 |
|
| 195 |
|
| 196 |
def write_cache(path, identity, packed, scales, K, c2w, owners, *, timings=None):
|
|
|
|
| 218 |
|
| 219 |
def manifest(offsets) -> dict:
|
| 220 |
return {'schema': SCHEMA, 'label_id': LABEL_ID, 'implementation_version': LABEL_ID, 'recipe': RECIPE,
|
| 221 |
+
'visibility_semantics': SEMANTICS, 'depth_consistency': False,
|
| 222 |
'source_alpha_tolerance': .1, 'source_filter_label': SOURCE_POLICY,
|
| 223 |
'offsets_by_source': {SOURCE: list(offsets)},
|
| 224 |
'storage': 'strict[frame, offset, ceil(H*W/8)] little bit order; all target pixels',
|
code/agt/eval/depth.py
CHANGED
|
@@ -72,41 +72,24 @@ def frame_drmse(pred, gt, mask, *, alpha=None, eps):
|
|
| 72 |
'a_nonpositive': bool(status == 'fit' and a <= 0)}
|
| 73 |
|
| 74 |
|
| 75 |
-
def frame_metrics(pred, gt, mask, *, alpha=None, eps
|
| 76 |
mask = np.asarray(mask, bool)
|
| 77 |
fit = frame_drmse(pred, gt, mask, alpha=alpha, eps=eps)
|
| 78 |
gt = np.asarray(gt, np.float64)
|
| 79 |
missing = np.ones(mask.shape, bool) if pred is None else missing_mask(np.asarray(pred), alpha, eps)
|
| 80 |
prediction = np.zeros_like(gt) if pred is None else np.asarray(pred, np.float64)
|
| 81 |
aligned = fit['a'] * np.where(missing, 0., prediction) + fit['b']
|
| 82 |
-
global_mean = float(gt[mask].mean())
|
| 83 |
-
squared = np.where(missing, (gt-global_mean)**2, (aligned-gt)**2)
|
| 84 |
relative = np.abs(aligned-gt) / np.where(mask, gt, 1.)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
out = {}
|
| 86 |
-
for
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
n, n_pred = int(valid.sum()), int(present.sum())
|
| 90 |
-
value = float(np.sqrt(squared[valid].mean())) if n else None
|
| 91 |
-
if name == 'full':
|
| 92 |
-
value = fit['value']
|
| 93 |
-
out[name] = dict(drmse=value, absrel=float(relative[present].mean()) if n_pred else None,
|
| 94 |
-
n_valid=n, n_pred=n_pred, n_missing=int((valid & missing).sum()))
|
| 95 |
-
return dict(fit=fit, regions=out)
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
def aggregate(frames, positions):
|
| 99 |
-
selected = [frames[i] for i in positions if frames[i] is not None]
|
| 100 |
-
keys = sorted({key for frame in selected for key in frame['regions']})
|
| 101 |
-
out = {}
|
| 102 |
-
for key in keys:
|
| 103 |
-
items = [frame['regions'][key] for frame in selected]
|
| 104 |
-
entry = {field: sum(item[field] for item in items) for field in ('n_valid', 'n_pred', 'n_missing')}
|
| 105 |
-
for metric in ('drmse', 'absrel'):
|
| 106 |
-
values = [item[metric] for item in items if item[metric] is not None]
|
| 107 |
-
entry[metric] = sum(values)/len(values) if values else None
|
| 108 |
-
entry['n_frames_'+metric] = len(values)
|
| 109 |
-
out[key] = entry
|
| 110 |
return out
|
| 111 |
|
| 112 |
|
|
|
|
| 72 |
'a_nonpositive': bool(status == 'fit' and a <= 0)}
|
| 73 |
|
| 74 |
|
| 75 |
+
def frame_metrics(pred, gt, mask, *, alpha=None, eps):
|
| 76 |
mask = np.asarray(mask, bool)
|
| 77 |
fit = frame_drmse(pred, gt, mask, alpha=alpha, eps=eps)
|
| 78 |
gt = np.asarray(gt, np.float64)
|
| 79 |
missing = np.ones(mask.shape, bool) if pred is None else missing_mask(np.asarray(pred), alpha, eps)
|
| 80 |
prediction = np.zeros_like(gt) if pred is None else np.asarray(pred, np.float64)
|
| 81 |
aligned = fit['a'] * np.where(missing, 0., prediction) + fit['b']
|
|
|
|
|
|
|
| 82 |
relative = np.abs(aligned-gt) / np.where(mask, gt, 1.)
|
| 83 |
+
present = mask & ~missing
|
| 84 |
+
return dict(fit=fit, rmse=fit['value'], absrel=float(relative[present].mean()) if present.any() else None)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def aggregate(frames):
|
| 88 |
+
selected = [frame for frame in frames if frame is not None]
|
| 89 |
out = {}
|
| 90 |
+
for metric in ('rmse', 'absrel'):
|
| 91 |
+
values = [frame[metric] for frame in selected if frame[metric] is not None]
|
| 92 |
+
out[metric] = sum(values)/len(values) if values else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
return out
|
| 94 |
|
| 95 |
|
code/agt/eval/hole.py
CHANGED
|
@@ -6,14 +6,11 @@ from scipy.ndimage import find_objects, label
|
|
| 6 |
|
| 7 |
from .rgb import gt_float
|
| 8 |
|
| 9 |
-
MIN_COLLECTION_BOXES = 1000
|
| 10 |
-
KID_SEED = 20261029
|
| 11 |
-
|
| 12 |
|
| 13 |
def component_boxes(mask, expansion=.1):
|
| 14 |
mask = np.asarray(mask, bool)
|
| 15 |
if mask.ndim != 2:
|
| 16 |
-
raise ValueError('component boxes require a single HW
|
| 17 |
components, _ = label(mask, structure=np.ones((3, 3), bool))
|
| 18 |
boxes = []
|
| 19 |
for region in find_objects(components):
|
|
@@ -24,48 +21,11 @@ def component_boxes(mask, expansion=.1):
|
|
| 24 |
return boxes
|
| 25 |
|
| 26 |
|
| 27 |
-
def seam_residual(pred, gt, U):
|
| 28 |
-
total, count = 0., 0
|
| 29 |
-
for axis in (0, 1):
|
| 30 |
-
a = [slice(None)] * 2
|
| 31 |
-
b = a.copy()
|
| 32 |
-
a[axis], b[axis] = slice(None, -1), slice(1, None)
|
| 33 |
-
a, b = tuple(a), tuple(b)
|
| 34 |
-
crossing = U[a] ^ U[b]
|
| 35 |
-
error = np.abs((pred[b] - pred[a]) - (gt[b] - gt[a])).mean(axis=-1)
|
| 36 |
-
total += float(error[crossing].sum(dtype=np.float64))
|
| 37 |
-
count += int(crossing.sum())
|
| 38 |
-
return dict(value=total/count if count else None, edges=count, sum=total)
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
def coverage(pred, truth, domain):
|
| 42 |
-
pred, truth, domain = np.asarray(pred, bool), np.asarray(truth, bool), np.asarray(domain, bool)
|
| 43 |
-
tp = int((pred & truth & domain).sum())
|
| 44 |
-
positives, actual = int((pred & domain).sum()), int((truth & domain).sum())
|
| 45 |
-
return dict(precision=tp/positives if positives else None, recall=tp/actual if actual else None,
|
| 46 |
-
true_positive=tp, predicted_positive=positives, actual_positive=actual)
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
def frechet_distance(fake, real):
|
| 50 |
-
import torch
|
| 51 |
-
from torchmetrics.image.fid import _compute_fid
|
| 52 |
-
stats = []
|
| 53 |
-
for features in (real, fake):
|
| 54 |
-
x = torch.as_tensor(features).detach().to('cpu', torch.float64)
|
| 55 |
-
n = x.shape[0]
|
| 56 |
-
mean = (x.sum(dim=0) / n).unsqueeze(0)
|
| 57 |
-
cov = (x.t().mm(x) - n * mean.t().mm(mean)) / (n - 1)
|
| 58 |
-
stats += [mean.squeeze(0), cov]
|
| 59 |
-
return float(_compute_fid(*stats))
|
| 60 |
-
|
| 61 |
-
|
| 62 |
class HoleScorer:
|
| 63 |
-
def __init__(self, region_scorer
|
| 64 |
self.region = region_scorer
|
| 65 |
self.device = region_scorer.device
|
| 66 |
-
self.
|
| 67 |
-
self._dists, self._kid = None, None
|
| 68 |
-
self.features = {}
|
| 69 |
|
| 70 |
def dists(self, pred, gt):
|
| 71 |
import torch
|
|
@@ -84,92 +44,16 @@ class HoleScorer:
|
|
| 84 |
with torch.inference_mode():
|
| 85 |
return float(self._dists(*inputs).item())
|
| 86 |
|
| 87 |
-
def
|
| 88 |
-
if self._kid is None:
|
| 89 |
-
from torchmetrics.image.kid import KernelInceptionDistance
|
| 90 |
-
self._kid = KernelInceptionDistance().to(self.device)
|
| 91 |
-
return self._kid
|
| 92 |
-
|
| 93 |
-
def extract_features(self, pred, gt):
|
| 94 |
-
import torch
|
| 95 |
-
metric = self.kid()
|
| 96 |
-
metric.reset()
|
| 97 |
-
for array, real in ((pred, False), (gt, True)):
|
| 98 |
-
image = np.rint(np.clip(array, 0, 1) * 255).astype(np.uint8)
|
| 99 |
-
image = torch.from_numpy(np.ascontiguousarray(image.transpose(2, 0, 1)))[None].to(self.device)
|
| 100 |
-
with torch.inference_mode():
|
| 101 |
-
metric.update(image, real=real)
|
| 102 |
-
return metric.fake_features[-1].cpu(), metric.real_features[-1].cpu()
|
| 103 |
-
|
| 104 |
-
def collection_kid(self, keys):
|
| 105 |
-
import torch
|
| 106 |
-
pairs = [pair for key in keys for pair in self.features.get(key, [])]
|
| 107 |
-
if len(pairs) < MIN_COLLECTION_BOXES:
|
| 108 |
-
return dict(value=None, std=None, n_boxes=len(pairs), status='insufficient_samples',
|
| 109 |
-
required=MIN_COLLECTION_BOXES)
|
| 110 |
-
metric = self.kid()
|
| 111 |
-
metric.reset()
|
| 112 |
-
metric.fake_features = [p.to(self.device) for p, _ in pairs]
|
| 113 |
-
metric.real_features = [g.to(self.device) for _, g in pairs]
|
| 114 |
-
with torch.random.fork_rng(devices=[]):
|
| 115 |
-
torch.manual_seed(KID_SEED)
|
| 116 |
-
value, std = metric.compute()
|
| 117 |
-
return dict(value=float(value), std=float(std), n_boxes=len(pairs), status='ok')
|
| 118 |
-
|
| 119 |
-
def collection_fid(self, keys):
|
| 120 |
-
import torch
|
| 121 |
-
pairs = [pair for key in keys for pair in self.features.get(key, [])]
|
| 122 |
-
if len(pairs) < MIN_COLLECTION_BOXES:
|
| 123 |
-
return dict(value=None, n_boxes=len(pairs), status='insufficient_samples', required=MIN_COLLECTION_BOXES)
|
| 124 |
-
value = frechet_distance(torch.cat([p for p, _ in pairs]), torch.cat([g for _, g in pairs]))
|
| 125 |
-
return dict(value=value, n_boxes=len(pairs), status='ok')
|
| 126 |
-
|
| 127 |
-
def score(self, pred, gt_u8, regions, frame_sets, *, key, score_mask, visible, aux=None):
|
| 128 |
pred, gt = np.clip(np.asarray(pred, np.float32), 0, 1), gt_float(gt_u8)
|
| 129 |
-
|
| 130 |
-
for
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
for y0, y1, x0, x1 in boxes:
|
| 141 |
-
p, g = pred[i, y0:y1, x0:x1], gt[i, y0:y1, x0:x1]
|
| 142 |
-
if self.enable_dists:
|
| 143 |
-
values.append(self.dists(p, g))
|
| 144 |
-
if self.enable_kid or self.enable_fid:
|
| 145 |
-
features.append(self.extract_features(p, g))
|
| 146 |
-
record['dists'] = sum(values)/len(values) if values else None
|
| 147 |
-
record['dists_sum'], record['n_dists'] = sum(values), len(values)
|
| 148 |
-
records.append(record)
|
| 149 |
-
pixels = sum(r['pixels'] for r in records)
|
| 150 |
-
n_dists = sum(r['n_dists'] for r in records)
|
| 151 |
-
seam_count = sum(r['seam']['edges'] for r in records)
|
| 152 |
-
out = dict(status='ok' if pixels else 'empty_U', n_pixels=pixels,
|
| 153 |
-
lpips=sum(r['lpips']*r['pixels'] for r in records if r['pixels'])/pixels if pixels else None,
|
| 154 |
-
dists=sum(r['dists_sum'] for r in records)/n_dists if n_dists else None,
|
| 155 |
-
seam_gradient=sum(r['seam']['sum'] for r in records)/seam_count if seam_count else None,
|
| 156 |
-
frames=records, opacity={}, coverage={})
|
| 157 |
-
for attachment in aux or []:
|
| 158 |
-
selected = [p for p in positions if p in attachment['positions']]
|
| 159 |
-
if not selected:
|
| 160 |
-
continue
|
| 161 |
-
indices = [attachment['positions'].index(p) for p in selected]
|
| 162 |
-
arrays = attachment['array'][indices]
|
| 163 |
-
domain, truth = score_mask[selected], score_mask[selected] & visible[selected]
|
| 164 |
-
name = 'pass' + str(attachment['pass']) + '_' + attachment['kind']
|
| 165 |
-
if attachment['kind'] == 'opacity':
|
| 166 |
-
values = arrays[regions.masks['U'][selected]]
|
| 167 |
-
out['opacity'][name] = dict(mean=float(values.mean()), median=float(np.median(values)),
|
| 168 |
-
p10=float(np.quantile(values, .1)), p90=float(np.quantile(values, .9))) if values.size else None
|
| 169 |
-
out['coverage'][name] = coverage(arrays >= .5, truth, domain)
|
| 170 |
-
elif attachment['kind'] == 'online_v':
|
| 171 |
-
out['coverage'][name] = coverage(arrays, truth, domain)
|
| 172 |
-
output[fs] = out
|
| 173 |
-
self.features[(key, fs)] = features
|
| 174 |
-
features = []
|
| 175 |
-
return output
|
|
|
|
| 6 |
|
| 7 |
from .rgb import gt_float
|
| 8 |
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
def component_boxes(mask, expansion=.1):
|
| 11 |
mask = np.asarray(mask, bool)
|
| 12 |
if mask.ndim != 2:
|
| 13 |
+
raise ValueError('component boxes require a single HW mask')
|
| 14 |
components, _ = label(mask, structure=np.ones((3, 3), bool))
|
| 15 |
boxes = []
|
| 16 |
for region in find_objects(components):
|
|
|
|
| 21 |
return boxes
|
| 22 |
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
class HoleScorer:
|
| 25 |
+
def __init__(self, region_scorer):
|
| 26 |
self.region = region_scorer
|
| 27 |
self.device = region_scorer.device
|
| 28 |
+
self._dists = None
|
|
|
|
|
|
|
| 29 |
|
| 30 |
def dists(self, pred, gt):
|
| 31 |
import torch
|
|
|
|
| 44 |
with torch.inference_mode():
|
| 45 |
return float(self._dists(*inputs).item())
|
| 46 |
|
| 47 |
+
def score(self, pred, gt_u8, unobserved):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
pred, gt = np.clip(np.asarray(pred, np.float32), 0, 1), gt_float(gt_u8)
|
| 49 |
+
pixels, lpips_sum, dists_sum, n_dists = 0, 0., 0., 0
|
| 50 |
+
for i, U in enumerate(unobserved):
|
| 51 |
+
n = int(U.sum())
|
| 52 |
+
if not n:
|
| 53 |
+
continue
|
| 54 |
+
pixels += n
|
| 55 |
+
lpips_sum += self.region.lpips_map(pred[i], gt[i], U, blackout=False) * n
|
| 56 |
+
values = [self.dists(pred[i, y0:y1, x0:x1], gt[i, y0:y1, x0:x1]) for y0, y1, x0, x1 in component_boxes(U)]
|
| 57 |
+
dists_sum += sum(values)
|
| 58 |
+
n_dists += len(values)
|
| 59 |
+
return dict(lpips=lpips_sum / pixels if pixels else None, dists=dists_sum / n_dists if n_dists else None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
code/agt/eval/method_dir.py
CHANGED
|
@@ -6,8 +6,6 @@ from pathlib import Path
|
|
| 6 |
import numpy as np
|
| 7 |
|
| 8 |
FRAMES = 20
|
| 9 |
-
CONTEXT = [0, 5, 10, 15]
|
| 10 |
-
GRID_HW = (294, 518)
|
| 11 |
DEPTH_SEMANTICS = 'normalized_expected_camera_z'
|
| 12 |
|
| 13 |
|
|
@@ -33,21 +31,6 @@ def select_scored(output, n_samples, scored_positions):
|
|
| 33 |
return rgb[[positions.index(p) for p in scored_positions]]
|
| 34 |
|
| 35 |
|
| 36 |
-
def checked_map(kind, array, positions):
|
| 37 |
-
if array.shape != (len(positions), *GRID_HW):
|
| 38 |
-
raise ValueError('auxiliary map grid mismatch')
|
| 39 |
-
if kind == 'online_v':
|
| 40 |
-
if not np.isin(array, (0, 1)).all():
|
| 41 |
-
raise ValueError('online_v must be binary')
|
| 42 |
-
return array.astype(bool)
|
| 43 |
-
if kind == 'opacity':
|
| 44 |
-
if array.dtype == np.uint8:
|
| 45 |
-
return array.astype(np.float32)/255
|
| 46 |
-
if array.dtype.kind != 'f' or not np.isfinite(array).all() or np.any((array < 0) | (array > 1)):
|
| 47 |
-
raise ValueError('opacity must be finite [0,1] or uint8')
|
| 48 |
-
return array
|
| 49 |
-
|
| 50 |
-
|
| 51 |
class MethodDirectory:
|
| 52 |
def __init__(self, root):
|
| 53 |
self.root = Path(root)
|
|
@@ -57,7 +40,6 @@ class MethodDirectory:
|
|
| 57 |
self.depth = json.loads(path.read_text()) if path.is_file() else None
|
| 58 |
if self.depth is not None and self.depth.get('semantics') != DEPTH_SEMANTICS:
|
| 59 |
raise ValueError(f'{path}: depth semantics must be {DEPTH_SEMANTICS!r}')
|
| 60 |
-
self.has_input_depth = any(self.root.glob('*/input_depth.json'))
|
| 61 |
|
| 62 |
def predict(self, clip: dict) -> dict:
|
| 63 |
entry = self.meta['files'].get(clip['clip_id'])
|
|
@@ -86,27 +68,3 @@ class MethodDirectory:
|
|
| 86 |
if depth.shape[0] != len(positions) or tuple(depth.shape[2:0:-1]) != tuple(self.depth['native_resolution']):
|
| 87 |
raise ValueError(f'{path}: depth {depth.shape} != {len(positions)} x {self.depth["native_resolution"]}')
|
| 88 |
return {'depth': depth, 'alpha': alpha, 'positions': positions}
|
| 89 |
-
|
| 90 |
-
def input_depth(self, clip_id: str):
|
| 91 |
-
root = self.root / clip_id
|
| 92 |
-
if not (root / 'input_depth.json').is_file():
|
| 93 |
-
return None
|
| 94 |
-
with np.load(root / 'input_depth.npz', allow_pickle=False) as z:
|
| 95 |
-
depth = z['depth']
|
| 96 |
-
if depth.dtype != np.float16 or depth.ndim != 3 or depth.shape[0] != 4:
|
| 97 |
-
raise ValueError(f'{root}: input depth must be float16 [4,H,W]')
|
| 98 |
-
if not np.isfinite(depth).all() or np.any(depth <= 0):
|
| 99 |
-
raise ValueError(f'{root}: input depth must be finite and positive')
|
| 100 |
-
return depth
|
| 101 |
-
|
| 102 |
-
def aux(self, clip, *, pass_number=1):
|
| 103 |
-
path = self.root / clip['clip_id'] / 'ab_maps.npz'
|
| 104 |
-
if not path.is_file():
|
| 105 |
-
return [], dict(status='N/A', reason='method supplied no auxiliary maps')
|
| 106 |
-
with np.load(path, allow_pickle=False) as handle:
|
| 107 |
-
positions = handle['positions'].tolist(); contexts = handle['context_positions'].tolist()
|
| 108 |
-
if positions != list(range(16)) or contexts != CONTEXT:
|
| 109 |
-
raise ValueError('auxiliary maps protocol positions mismatch')
|
| 110 |
-
maps = [dict(kind=kind, **{'pass': pass_number}, positions=ps, array=checked_map(kind, handle[kind], ps))
|
| 111 |
-
for kind, ps in [('opacity', positions), ('online_v', contexts)]]
|
| 112 |
-
return maps, dict(status='ok', positions=positions, context_positions=contexts)
|
|
|
|
| 6 |
import numpy as np
|
| 7 |
|
| 8 |
FRAMES = 20
|
|
|
|
|
|
|
| 9 |
DEPTH_SEMANTICS = 'normalized_expected_camera_z'
|
| 10 |
|
| 11 |
|
|
|
|
| 31 |
return rgb[[positions.index(p) for p in scored_positions]]
|
| 32 |
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
class MethodDirectory:
|
| 35 |
def __init__(self, root):
|
| 36 |
self.root = Path(root)
|
|
|
|
| 40 |
self.depth = json.loads(path.read_text()) if path.is_file() else None
|
| 41 |
if self.depth is not None and self.depth.get('semantics') != DEPTH_SEMANTICS:
|
| 42 |
raise ValueError(f'{path}: depth semantics must be {DEPTH_SEMANTICS!r}')
|
|
|
|
| 43 |
|
| 44 |
def predict(self, clip: dict) -> dict:
|
| 45 |
entry = self.meta['files'].get(clip['clip_id'])
|
|
|
|
| 68 |
if depth.shape[0] != len(positions) or tuple(depth.shape[2:0:-1]) != tuple(self.depth['native_resolution']):
|
| 69 |
raise ValueError(f'{path}: depth {depth.shape} != {len(positions)} x {self.depth["native_resolution"]}')
|
| 70 |
return {'depth': depth, 'alpha': alpha, 'positions': positions}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
code/agt/eval/regional.py
CHANGED
|
@@ -53,20 +53,6 @@ def aggregate_region(frames, positions, *, min_pixels=MIN_PIXELS):
|
|
| 53 |
return out
|
| 54 |
|
| 55 |
|
| 56 |
-
def decomposition(errors, masks, positions):
|
| 57 |
-
parts = {}
|
| 58 |
-
E = masks['E'][positions]
|
| 59 |
-
total_pixels, total_sse = int(E.sum()), float(errors[positions][E].sum(dtype=np.float64))
|
| 60 |
-
for name in ('scene', 'observed', 'U'):
|
| 61 |
-
chosen = masks[name][positions]
|
| 62 |
-
pixels, sse = int(chosen.sum()), float(errors[positions][chosen].sum(dtype=np.float64))
|
| 63 |
-
parts[name] = dict(pixels=pixels, sse=sse, area_fraction=pixels / total_pixels if total_pixels else None,
|
| 64 |
-
error_fraction=sse / total_sse if total_sse else None,
|
| 65 |
-
mse=sse / pixels if pixels else None)
|
| 66 |
-
return dict(E_pixels=total_pixels, E_sse=total_sse,
|
| 67 |
-
E_mse=total_sse / total_pixels if total_pixels else None, regions=parts)
|
| 68 |
-
|
| 69 |
-
|
| 70 |
class RegionScorer:
|
| 71 |
def __init__(self, device='cpu', *, min_pixels=MIN_PIXELS):
|
| 72 |
self.device, self.min_pixels = device, min_pixels
|
|
@@ -92,7 +78,7 @@ class RegionScorer:
|
|
| 92 |
distance = self.lpips(net)(p * 2 - 1, g * 2 - 1)
|
| 93 |
return float(weighted_mean(distance, w).item())
|
| 94 |
|
| 95 |
-
def score_region(self, pred, gt, mask, *, perceptual=True):
|
| 96 |
pred, gt, mask = np.clip(np.asarray(pred, np.float32), 0, 1), np.asarray(gt, np.float32), np.asarray(mask, bool)
|
| 97 |
if pred.shape != gt.shape or mask.shape != pred.shape[:-1]:
|
| 98 |
raise ValueError('mask shape must match every target frame, without channel axis')
|
|
@@ -103,19 +89,13 @@ class RegionScorer:
|
|
| 103 |
f = dict(pixels=pixels, sse=float(err[m].sum(dtype=np.float64)), ssim=None, lpips=None)
|
| 104 |
if pixels:
|
| 105 |
pm, gm = p * m[..., None], g * m[..., None]
|
| 106 |
-
|
|
|
|
| 107 |
if perceptual:
|
| 108 |
f['lpips'] = self.lpips_map(p, g, m)
|
| 109 |
frames.append(f)
|
| 110 |
return frames
|
| 111 |
|
| 112 |
-
def
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
for name, mask in regions.masks.items():
|
| 116 |
-
frames = self.score_region(pred, gt, mask, perceptual=perceptual)
|
| 117 |
-
result[name] = dict(frames=frames, sets={fs: aggregate_region(frames, ps, min_pixels=self.min_pixels)
|
| 118 |
-
for fs, ps in frame_sets.items()})
|
| 119 |
-
result['decomposition'] = {fs: decomposition(pixel_errors(pred, gt), regions.masks, ps)
|
| 120 |
-
for fs, ps in frame_sets.items()}
|
| 121 |
-
return result
|
|
|
|
| 53 |
return out
|
| 54 |
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
class RegionScorer:
|
| 57 |
def __init__(self, device='cpu', *, min_pixels=MIN_PIXELS):
|
| 58 |
self.device, self.min_pixels = device, min_pixels
|
|
|
|
| 78 |
distance = self.lpips(net)(p * 2 - 1, g * 2 - 1)
|
| 79 |
return float(weighted_mean(distance, w).item())
|
| 80 |
|
| 81 |
+
def score_region(self, pred, gt, mask, *, structural=True, perceptual=True):
|
| 82 |
pred, gt, mask = np.clip(np.asarray(pred, np.float32), 0, 1), np.asarray(gt, np.float32), np.asarray(mask, bool)
|
| 83 |
if pred.shape != gt.shape or mask.shape != pred.shape[:-1]:
|
| 84 |
raise ValueError('mask shape must match every target frame, without channel axis')
|
|
|
|
| 89 |
f = dict(pixels=pixels, sse=float(err[m].sum(dtype=np.float64)), ssim=None, lpips=None)
|
| 90 |
if pixels:
|
| 91 |
pm, gm = p * m[..., None], g * m[..., None]
|
| 92 |
+
if structural:
|
| 93 |
+
f['ssim'] = float(ssim_map(pm, gm)[m].mean(dtype=np.float64))
|
| 94 |
if perceptual:
|
| 95 |
f['lpips'] = self.lpips_map(p, g, m)
|
| 96 |
frames.append(f)
|
| 97 |
return frames
|
| 98 |
|
| 99 |
+
def region(self, pred, gt_u8, mask, *, structural=True, perceptual=True):
|
| 100 |
+
frames = self.score_region(pred, gt_float(gt_u8), mask, structural=structural, perceptual=perceptual)
|
| 101 |
+
return aggregate_region(frames, range(len(frames)), min_pixels=self.min_pixels)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
code/agt/eval/regions.py
CHANGED
|
@@ -1,41 +1,14 @@
|
|
| 1 |
-
from dataclasses import dataclass
|
| 2 |
-
|
| 3 |
import numpy as np
|
| 4 |
from scipy.ndimage import maximum_filter, minimum_filter
|
| 5 |
|
| 6 |
-
PRIMARY = ('scene', 'observed', 'U')
|
| 7 |
-
CROSS_BITS = {'sky': 1, 'motion': 2, 'semi': 4, 'band': 8, 'depth_invalid': 16}
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
@dataclass
|
| 11 |
-
class Regions:
|
| 12 |
-
labels: np.ndarray
|
| 13 |
-
cross: np.ndarray
|
| 14 |
-
masks: dict
|
| 15 |
-
areas: dict
|
| 16 |
-
|
| 17 |
|
| 18 |
-
def partition(mask, visible, *, width=3
|
| 19 |
mask, visible = np.asarray(mask, bool), np.asarray(visible, bool)
|
| 20 |
if mask.shape != visible.shape or mask.ndim not in (2, 3):
|
| 21 |
raise ValueError('mask and V must be matching HW or NHW arrays')
|
| 22 |
if type(width) is not int or width < 0:
|
| 23 |
-
raise ValueError('
|
| 24 |
size = (1,) * (mask.ndim - 2) + (2 * width + 1, 2 * width + 1)
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
E=E, S=E & (~mask | visible), void=void)
|
| 29 |
-
labels = np.zeros(mask.shape, np.uint8)
|
| 30 |
-
for value, key in enumerate(PRIMARY, 1):
|
| 31 |
-
labels[masks[key]] = value
|
| 32 |
-
cross = void.astype(np.uint8) * CROSS_BITS['band']
|
| 33 |
-
diagnostics = dict(sky=sky, motion=motion, semi=None if alpha is None else (~mask & (np.asarray(alpha) >= .05)),
|
| 34 |
-
depth_invalid=None if depth_valid is None else ~np.asarray(depth_valid, bool))
|
| 35 |
-
for name, diagnostic in diagnostics.items():
|
| 36 |
-
if diagnostic is None:
|
| 37 |
-
continue
|
| 38 |
-
diagnostic = np.broadcast_to(np.asarray(diagnostic, bool), mask.shape)
|
| 39 |
-
cross |= diagnostic.astype(np.uint8) * CROSS_BITS[name]
|
| 40 |
-
masks['diagnostic_' + name] = diagnostic
|
| 41 |
-
return Regions(labels, cross, masks, {key: int(value.sum()) for key, value in masks.items()})
|
|
|
|
|
|
|
|
|
|
| 1 |
import numpy as np
|
| 2 |
from scipy.ndimage import maximum_filter, minimum_filter
|
| 3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
def partition(mask, visible, *, width=3):
|
| 6 |
mask, visible = np.asarray(mask, bool), np.asarray(visible, bool)
|
| 7 |
if mask.shape != visible.shape or mask.ndim not in (2, 3):
|
| 8 |
raise ValueError('mask and V must be matching HW or NHW arrays')
|
| 9 |
if type(width) is not int or width < 0:
|
| 10 |
+
raise ValueError('boundary width must be a nonnegative integer radius')
|
| 11 |
size = (1,) * (mask.ndim - 2) + (2 * width + 1, 2 * width + 1)
|
| 12 |
+
boundary = maximum_filter(mask, size=size, mode='nearest') ^ minimum_filter(mask, size=size, mode='nearest')
|
| 13 |
+
scored = ~boundary
|
| 14 |
+
return dict(observed=scored & (~mask | visible), unobserved=scored & mask & ~visible)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
code/agt/eval/rgb.py
CHANGED
|
@@ -3,7 +3,6 @@ import math
|
|
| 3 |
import numpy as np
|
| 4 |
|
| 5 |
METRICS = ('rgb_psnr', 'rgb_ssim', 'rgb_lpips')
|
| 6 |
-
SCORED_FRAME_SETS = ('interp', 'recon')
|
| 7 |
|
| 8 |
|
| 9 |
def scalar(value):
|
|
@@ -19,10 +18,6 @@ def mean(values):
|
|
| 19 |
return sum(values) / len(values)
|
| 20 |
|
| 21 |
|
| 22 |
-
def aggregate_frames(values):
|
| 23 |
-
return {'value': scalar(mean(values)), 'n_frames': len(values)}
|
| 24 |
-
|
| 25 |
-
|
| 26 |
def frame_metrics(img1, img2, loss_fn=None, metrics=METRICS):
|
| 27 |
from skimage.metrics import peak_signal_noise_ratio, structural_similarity
|
| 28 |
img1 = img1.clamp(0, 1)
|
|
@@ -77,10 +72,6 @@ class RGBScorer:
|
|
| 77 |
with torch.inference_mode():
|
| 78 |
return frame_metrics(img1, img2, self.lpips() if 'rgb_lpips' in metrics else None, metrics)
|
| 79 |
|
| 80 |
-
def score(self, pred, gt_u8,
|
| 81 |
per_frame = self.frames(pred, gt_u8, metrics)
|
| 82 |
-
|
| 83 |
-
for m in metrics:
|
| 84 |
-
result[m] = {fs: aggregate_frames([per_frame[m][i] for i in positions])
|
| 85 |
-
for fs, positions in frame_sets.items()}
|
| 86 |
-
return result
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
|
| 5 |
METRICS = ('rgb_psnr', 'rgb_ssim', 'rgb_lpips')
|
|
|
|
| 6 |
|
| 7 |
|
| 8 |
def scalar(value):
|
|
|
|
| 18 |
return sum(values) / len(values)
|
| 19 |
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
def frame_metrics(img1, img2, loss_fn=None, metrics=METRICS):
|
| 22 |
from skimage.metrics import peak_signal_noise_ratio, structural_similarity
|
| 23 |
img1 = img1.clamp(0, 1)
|
|
|
|
| 72 |
with torch.inference_mode():
|
| 73 |
return frame_metrics(img1, img2, self.lpips() if 'rgb_lpips' in metrics else None, metrics)
|
| 74 |
|
| 75 |
+
def score(self, pred, gt_u8, metrics=METRICS):
|
| 76 |
per_frame = self.frames(pred, gt_u8, metrics)
|
| 77 |
+
return {m: scalar(mean(values)) for m, values in per_frame.items()}
|
|
|
|
|
|
|
|
|
|
|
|
code/agt/eval/scorer.py
CHANGED
|
@@ -3,35 +3,27 @@ from __future__ import annotations
|
|
| 3 |
import json
|
| 4 |
from pathlib import Path
|
| 5 |
|
| 6 |
-
import numpy as np
|
| 7 |
-
|
| 8 |
from agt.data.protocol import ClipProtocol
|
| 9 |
from agt.data.reader import open_reader
|
| 10 |
from agt.data.store import LabelsUnavailable
|
| 11 |
from .depth import DepthLabels, aggregate, frame_metrics, frame_reasons, native_cells_in_v
|
| 12 |
from .hole import HoleScorer
|
| 13 |
-
from .labels import
|
| 14 |
from .method_dir import MethodDirectory, select_scored
|
| 15 |
from .output_grid import depth_to_scoring_grid, to_scoring_grid
|
| 16 |
from .regional import RegionScorer
|
| 17 |
from .regions import partition
|
| 18 |
from .rgb import RGBScorer
|
| 19 |
-
from .summary import export, write_json
|
| 20 |
|
| 21 |
-
ALL_TABLES = ('A1', 'A2', 'B', 'depth_render', 'depth_input')
|
| 22 |
DEFAULTS = dict(protocol='partial', map_version='v2', source='waymo', scoring_mask='ground_truth',
|
| 23 |
-
visibility='gt_visibility_v2',
|
| 24 |
-
|
| 25 |
|
| 26 |
|
| 27 |
-
def score_depth(labels, clip, output,
|
| 28 |
-
positions = list(range(16)) if positions is None else list(positions)
|
| 29 |
-
depth_keys = ('full',)+tuple(name for name in regions.masks if name in ('scene', 'observed', 'U', 'void') or name.startswith('diagnostic_'))
|
| 30 |
-
empty = {name: {metric: None for metric in ('drmse', 'absrel')} for name in depth_keys}
|
| 31 |
if labels is None or not labels.has_scene(clip['scene_id']):
|
| 32 |
-
return dict(status='no_gt_labels',
|
| 33 |
-
if output is None and not declared:
|
| 34 |
-
return dict(status='no_depth_product', sets={fs: empty for fs in frame_sets}, frames=[])
|
| 35 |
data = labels.read(clip['scene_id'], [clip['frame_indices'][p] for p in positions])
|
| 36 |
native_shape = data['native'].shape[1:]
|
| 37 |
if output is None:
|
|
@@ -48,72 +40,19 @@ def score_depth(labels, clip, output, regions, frame_sets, *, eps, positions=Non
|
|
| 48 |
frames.append(None)
|
| 49 |
continue
|
| 50 |
j = output_positions.index(p) if p in output_positions else None
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
frame['position'] = p
|
| 55 |
-
frames.append(frame)
|
| 56 |
-
return dict(status='ok', frames=frames,
|
| 57 |
-
sets={fs: aggregate(frames, [positions.index(p) for p in ps if p in positions])
|
| 58 |
-
for fs, ps in frame_sets.items()})
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def flatten_depth(result, fs):
|
| 62 |
-
return {region+'_'+metric: values.get(metric)
|
| 63 |
-
for region, values in result['sets'].get(fs, {}).items() for metric in ('drmse', 'absrel')}
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
def unavailable_rows(meta, frame_sets, *, tables):
|
| 67 |
-
depth = {region+'_'+metric: None for region in ('full', 'scene', 'observed', 'U', 'void')
|
| 68 |
-
for metric in ('drmse', 'absrel')}
|
| 69 |
-
for fs in frame_sets:
|
| 70 |
-
for table, values in [('A2', {r+'_'+m: None for r in ('scene', 'observed', 'S', 'E', 'void')
|
| 71 |
-
for m in ('psnr', 'ssim', 'lpips')}),
|
| 72 |
-
('B', {m: None for m in ('psnr', 'ssim', 'lpips', 'dists', 'seam_gradient')}),
|
| 73 |
-
('depth_render', depth)]:
|
| 74 |
-
if table in tables:
|
| 75 |
-
yield {**meta, 'table': table, 'frame_set': fs, 'values': values, 'status': 'visibility_unavailable'}
|
| 76 |
-
if fs == 'recon' and 'depth_input' in tables:
|
| 77 |
-
yield {**meta, 'table': 'depth_input', 'frame_set': fs,
|
| 78 |
-
'values': {'pass1_'+k: None for k in depth}, 'status': 'visibility_unavailable'}
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def load_diagnostics(data_root, reader, clip):
|
| 82 |
-
from agt.data.labels import CleanSkyStore, MotionStore
|
| 83 |
-
src = reader.source(clip['sample_id'])
|
| 84 |
-
frames = clip['frame_indices']; source = source_of(clip)
|
| 85 |
-
alpha = src.template().layers['effective_alpha']
|
| 86 |
-
arrays = {'alpha': np.broadcast_to(alpha, (len(frames), *alpha.shape))}
|
| 87 |
-
for kind, version, store_class, field in [('sky', 'sky_v1', CleanSkyStore, 'sky'),
|
| 88 |
-
('motion', 'motion_v2', MotionStore, 'motion_mask')]:
|
| 89 |
-
root = Path(data_root)/'labels'/version/source
|
| 90 |
-
if not (root/'label_manifest.json').is_file():
|
| 91 |
-
continue
|
| 92 |
-
store = store_class(root)
|
| 93 |
-
try:
|
| 94 |
-
values = store.read(clip['scene_id'], frames, src.record.frame_count, src.timestamps_start_us[frames])[field]
|
| 95 |
-
except LabelsUnavailable:
|
| 96 |
-
continue
|
| 97 |
-
arrays[kind] = values >= 128 if kind == 'sky' else values.astype(bool)
|
| 98 |
-
return arrays
|
| 99 |
|
| 100 |
|
| 101 |
def score(config: dict) -> dict:
|
| 102 |
cfg = {**DEFAULTS, **config}
|
| 103 |
-
tables = frozenset(cfg['tables'])
|
| 104 |
-
if not tables or not tables <= set(ALL_TABLES):
|
| 105 |
-
raise ValueError('tables must be a nonempty subset of ' + ', '.join(ALL_TABLES))
|
| 106 |
data_root, source, device = Path(cfg['data_root']), cfg['source'], cfg['device']
|
| 107 |
protocol = ClipProtocol.load(cfg['protocol'])
|
| 108 |
-
positions =
|
| 109 |
-
|
| 110 |
-
local_sets = {fs: [positions.index(p) for p in ps] for fs, ps in frame_sets.items()}
|
| 111 |
-
scorer = RegionScorer(device, min_pixels=cfg['min_pixels'])
|
| 112 |
rgb = RGBScorer(device)
|
| 113 |
-
|
| 114 |
-
hole = HoleScorer(scorer, dists='dists' in hole_metrics, kid='kid' in hole_metrics,
|
| 115 |
-
fid='fid' in hole_metrics) if 'B' in tables else None
|
| 116 |
-
eps = cfg['depth_alpha_eps']
|
| 117 |
|
| 118 |
inputs = Path(cfg['export'])
|
| 119 |
manifest = json.loads((inputs/'manifest.json').read_text())
|
|
@@ -127,7 +66,7 @@ def score(config: dict) -> dict:
|
|
| 127 |
labels = DepthLabels(data_root/'labels/lidar_dggt_single_v2', data_root/'labels/sky_v1', [source])
|
| 128 |
method = MethodDirectory(cfg['method'])
|
| 129 |
|
| 130 |
-
per_clip
|
| 131 |
for cid in cfg['clips'] or manifest['clips']:
|
| 132 |
if cid not in manifest['clips'] or cid not in canonical:
|
| 133 |
raise ValueError(f'clip {cid} is outside the export / the protocol clips of the data root')
|
|
@@ -138,88 +77,33 @@ def score(config: dict) -> dict:
|
|
| 138 |
if source_of(clip) != source:
|
| 139 |
raise ValueError('clip/export source mismatch')
|
| 140 |
data = reader.load(selected, rgb=('clean',))
|
| 141 |
-
masks,
|
| 142 |
try:
|
| 143 |
-
visible,
|
| 144 |
except LabelsUnavailable:
|
| 145 |
-
visible
|
| 146 |
-
diagnostics = load_diagnostics(data_root, reader, clip) if visible is not None else {}
|
| 147 |
-
if visible is not None and labels and labels.has_scene(clip['scene_id']):
|
| 148 |
-
label_data = labels.read(clip['scene_id'], clip['frame_indices'])
|
| 149 |
-
diagnostics.update(sky=label_data['sky'], depth_valid=label_data['eval_valid'])
|
| 150 |
-
regions = None if visible is None else partition(masks[:16], visible[:16], width=cfg['void_width'],
|
| 151 |
-
**{k: np.broadcast_to(v, masks.shape)[:16] for k, v in diagnostics.items()})
|
| 152 |
output = method.predict(selected)
|
| 153 |
prediction = to_scoring_grid(select_scored(output, len(clip['frame_indices']), positions), reader.grid)
|
| 154 |
gt = data['rgb_clean'][positions]
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
depth_declared = 'depth_render' in tables and method.depth is not None
|
| 173 |
-
depth_output = method.predict_depth(clip) if depth_declared else None
|
| 174 |
-
depth = score_depth(labels, clip, depth_output, regions, local_sets, eps=eps,
|
| 175 |
-
declared=depth_declared) if 'depth_render' in tables else None
|
| 176 |
-
input_depth = None
|
| 177 |
-
if 'depth_input' in tables:
|
| 178 |
-
arrays = method.input_depth(cid)
|
| 179 |
-
input_output = None if arrays is None else dict(depth=arrays, positions=list(CONTEXT))
|
| 180 |
-
input_depth = score_depth(labels, clip, input_output, regions, {'recon': list(CONTEXT)}, eps=eps,
|
| 181 |
-
positions=CONTEXT, declared=method.has_input_depth)
|
| 182 |
-
for fs in frame_sets:
|
| 183 |
-
if 'A1' in tables:
|
| 184 |
-
full = {metric.replace('rgb_', ''): a1[metric][fs]['value'] for metric in ('rgb_psnr', 'rgb_ssim', 'rgb_lpips')}
|
| 185 |
-
per_clip.append({**meta, 'table': 'A1', 'frame_set': fs, 'values': full})
|
| 186 |
-
if 'A2' in tables:
|
| 187 |
-
values = {region+'_'+metric: entry['sets'][fs].get(metric)
|
| 188 |
-
for region, entry in a2.items() if region != 'decomposition' and region != 'U'
|
| 189 |
-
for metric in ('psnr', 'ssim', 'lpips')}
|
| 190 |
-
per_clip.append({**meta, 'table': 'A2', 'frame_set': fs, 'values': values,
|
| 191 |
-
'decomposition': a2['decomposition'][fs]})
|
| 192 |
-
if 'B' in tables:
|
| 193 |
-
holes = {k: b[fs].get(k) for k in ('lpips', 'dists', 'seam_gradient')}
|
| 194 |
-
holes.update({metric: a2['U']['sets'][fs].get(metric) for metric in ('psnr', 'ssim')})
|
| 195 |
-
for pass_number in (1, 2):
|
| 196 |
-
for statistic in ('mean', 'median', 'p10', 'p90'):
|
| 197 |
-
holes[f'pass{pass_number}_opacity_{statistic}'] = b[fs]['opacity'].get(f'pass{pass_number}_opacity', {}).get(statistic) if b[fs]['opacity'].get(f'pass{pass_number}_opacity') else None
|
| 198 |
-
for kind in ('opacity', 'online_v'):
|
| 199 |
-
for stat in ('precision', 'recall'):
|
| 200 |
-
holes[f'pass{pass_number}_{kind}_{stat}'] = b[fs]['coverage'].get(f'pass{pass_number}_{kind}', {}).get(stat)
|
| 201 |
-
per_clip.append({**meta, 'table': 'B', 'frame_set': fs, 'values': holes, 'status': b[fs]['status'],
|
| 202 |
-
'auxiliary': aux_status})
|
| 203 |
-
for group in ('all', clip['group']):
|
| 204 |
-
collection_members.setdefault(('B', fs, group), []).append((cid, fs))
|
| 205 |
-
if 'depth_render' in tables:
|
| 206 |
-
per_clip.append({**meta, 'table': 'depth_render', 'frame_set': fs,
|
| 207 |
-
'values': flatten_depth(depth, fs), 'status': depth['status']})
|
| 208 |
-
if fs == 'recon' and 'depth_input' in tables:
|
| 209 |
-
per_clip.append({**meta, 'table': 'depth_input', 'frame_set': fs,
|
| 210 |
-
'values': {'pass1_'+k: v for k, v in flatten_depth(input_depth, fs).items()},
|
| 211 |
-
'status': input_depth['status']})
|
| 212 |
-
evidence.append({**meta, 'A1': a1, 'regions': a2, 'B': b, 'depth_render': depth, 'depth_input': input_depth,
|
| 213 |
-
'mask': mask_id, 'visibility': v_id})
|
| 214 |
print(json.dumps(dict(scored_clip=cid)), flush=True)
|
| 215 |
reader.close()
|
| 216 |
-
collections = {}
|
| 217 |
-
if hole is not None:
|
| 218 |
-
collections = {key: {'kid': hole.collection_kid(members)} for key, members in collection_members.items()}
|
| 219 |
-
if 'fid' in hole_metrics:
|
| 220 |
-
for key, members in collection_members.items():
|
| 221 |
-
collections[key]['fid'] = hole.collection_fid(members)
|
| 222 |
out = Path(cfg['out'])
|
| 223 |
-
write_json(out/'evidence.json', evidence)
|
| 224 |
write_json(out/'config.json', {k: str(v) if isinstance(v, Path) else v for k, v in cfg.items()})
|
| 225 |
-
return export(per_clip,
|
|
|
|
| 3 |
import json
|
| 4 |
from pathlib import Path
|
| 5 |
|
|
|
|
|
|
|
| 6 |
from agt.data.protocol import ClipProtocol
|
| 7 |
from agt.data.reader import open_reader
|
| 8 |
from agt.data.store import LabelsUnavailable
|
| 9 |
from .depth import DepthLabels, aggregate, frame_metrics, frame_reasons, native_cells_in_v
|
| 10 |
from .hole import HoleScorer
|
| 11 |
+
from .labels import MaskProvider, VisibilityProvider, source_of
|
| 12 |
from .method_dir import MethodDirectory, select_scored
|
| 13 |
from .output_grid import depth_to_scoring_grid, to_scoring_grid
|
| 14 |
from .regional import RegionScorer
|
| 15 |
from .regions import partition
|
| 16 |
from .rgb import RGBScorer
|
| 17 |
+
from .summary import METRICS, export, write_json
|
| 18 |
|
|
|
|
| 19 |
DEFAULTS = dict(protocol='partial', map_version='v2', source='waymo', scoring_mask='ground_truth',
|
| 20 |
+
visibility='gt_visibility_v2', boundary_width=3, min_pixels=49, depth_alpha_eps=1e-3, device='cuda',
|
| 21 |
+
clips=None)
|
| 22 |
|
| 23 |
|
| 24 |
+
def score_depth(labels, clip, output, positions, *, eps):
|
|
|
|
|
|
|
|
|
|
| 25 |
if labels is None or not labels.has_scene(clip['scene_id']):
|
| 26 |
+
return dict(status='no_gt_labels', rmse=None, absrel=None)
|
|
|
|
|
|
|
| 27 |
data = labels.read(clip['scene_id'], [clip['frame_indices'][p] for p in positions])
|
| 28 |
native_shape = data['native'].shape[1:]
|
| 29 |
if output is None:
|
|
|
|
| 40 |
frames.append(None)
|
| 41 |
continue
|
| 42 |
j = output_positions.index(p) if p in output_positions else None
|
| 43 |
+
frames.append(frame_metrics(None if j is None else pred[j], data['depth_z_m'][i], mask,
|
| 44 |
+
alpha=None if j is None or alpha is None else alpha[j], eps=eps))
|
| 45 |
+
return dict(status='ok', **aggregate(frames))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
|
| 48 |
def score(config: dict) -> dict:
|
| 49 |
cfg = {**DEFAULTS, **config}
|
|
|
|
|
|
|
|
|
|
| 50 |
data_root, source, device = Path(cfg['data_root']), cfg['source'], cfg['device']
|
| 51 |
protocol = ClipProtocol.load(cfg['protocol'])
|
| 52 |
+
positions = protocol.frame_set_positions('interp')
|
| 53 |
+
regions_scorer = RegionScorer(device, min_pixels=cfg['min_pixels'])
|
|
|
|
|
|
|
| 54 |
rgb = RGBScorer(device)
|
| 55 |
+
hole = HoleScorer(regions_scorer)
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
inputs = Path(cfg['export'])
|
| 58 |
manifest = json.loads((inputs/'manifest.json').read_text())
|
|
|
|
| 66 |
labels = DepthLabels(data_root/'labels/lidar_dggt_single_v2', data_root/'labels/sky_v1', [source])
|
| 67 |
method = MethodDirectory(cfg['method'])
|
| 68 |
|
| 69 |
+
per_clip = []
|
| 70 |
for cid in cfg['clips'] or manifest['clips']:
|
| 71 |
if cid not in manifest['clips'] or cid not in canonical:
|
| 72 |
raise ValueError(f'clip {cid} is outside the export / the protocol clips of the data root')
|
|
|
|
| 77 |
if source_of(clip) != source:
|
| 78 |
raise ValueError('clip/export source mismatch')
|
| 79 |
data = reader.load(selected, rgb=('clean',))
|
| 80 |
+
masks, _ = mask_provider.load(clip)
|
| 81 |
try:
|
| 82 |
+
visible, _ = visibility.load(clip)
|
| 83 |
except LabelsUnavailable:
|
| 84 |
+
visible = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
output = method.predict(selected)
|
| 86 |
prediction = to_scoring_grid(select_scored(output, len(clip['frame_indices']), positions), reader.grid)
|
| 87 |
gt = data['rgb_clean'][positions]
|
| 88 |
+
full = rgb.score(prediction, gt)
|
| 89 |
+
values = dict.fromkeys(METRICS)
|
| 90 |
+
values.update(full_psnr=full['rgb_psnr'], full_ssim=full['rgb_ssim'], full_lpips=full['rgb_lpips'])
|
| 91 |
+
status = 'visibility_unavailable'
|
| 92 |
+
if visible is not None:
|
| 93 |
+
status = 'ok'
|
| 94 |
+
regions = partition(masks[positions], visible[positions], width=cfg['boundary_width'])
|
| 95 |
+
observed = regions_scorer.region(prediction, gt, regions['observed'])
|
| 96 |
+
unobserved = regions_scorer.region(prediction, gt, regions['unobserved'], structural=False, perceptual=False)
|
| 97 |
+
holes = hole.score(prediction, gt, regions['unobserved'])
|
| 98 |
+
values.update(observed_psnr=observed['psnr'], observed_ssim=observed['ssim'], observed_lpips=observed['lpips'],
|
| 99 |
+
unobserved_psnr=unobserved['psnr'], unobserved_lpips=holes['lpips'],
|
| 100 |
+
unobserved_dists=holes['dists'])
|
| 101 |
+
if method.depth is not None:
|
| 102 |
+
depth = score_depth(labels, clip, method.predict_depth(clip), positions, eps=cfg['depth_alpha_eps'])
|
| 103 |
+
values.update(depth_absrel=depth['absrel'], depth_rmse=depth['rmse'])
|
| 104 |
+
per_clip.append(dict(source_id=source, scene_id=clip['scene_id'], clip_id=cid, status=status, values=values))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
print(json.dumps(dict(scored_clip=cid)), flush=True)
|
| 106 |
reader.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
out = Path(cfg['out'])
|
|
|
|
| 108 |
write_json(out/'config.json', {k: str(v) if isinstance(v, Path) else v for k, v in cfg.items()})
|
| 109 |
+
return export(per_clip, out)
|
code/agt/eval/summary.py
CHANGED
|
@@ -9,9 +9,8 @@ import numpy as np
|
|
| 9 |
|
| 10 |
from .rgb import mean, number, scalar
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
COLLECTION_METRICS = ('kid', 'fid')
|
| 15 |
|
| 16 |
|
| 17 |
def write_json(path, value):
|
|
@@ -29,107 +28,18 @@ def valid_value(value):
|
|
| 29 |
return isinstance(value, (int, float, np.floating)) and not math.isnan(value) and value != -float('inf')
|
| 30 |
|
| 31 |
|
| 32 |
-
def
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
-
def
|
| 38 |
-
cols = []
|
| 39 |
-
|
| 40 |
-
def add(new, tab, fs, old):
|
| 41 |
-
cols.append((new, tab, fs, old))
|
| 42 |
-
for fs in ('interp', 'recon'):
|
| 43 |
-
pre = 'interp_' if fs == 'interp' else 'recon_'
|
| 44 |
-
for m in ('psnr', 'ssim', 'lpips'):
|
| 45 |
-
add(pre + m, 'A1', fs, m)
|
| 46 |
-
for fs in ('interp', 'recon'):
|
| 47 |
-
pre = 's_' if fs == 'interp' else 's_recon_'
|
| 48 |
-
for m in ('psnr', 'ssim', 'lpips'):
|
| 49 |
-
add(pre + m, 'A2', fs, 'S_' + m)
|
| 50 |
-
for fs in ('interp', 'recon'):
|
| 51 |
-
pre = 'u_' if fs == 'interp' else 'u_recon_'
|
| 52 |
-
for m in ('psnr', 'ssim', 'lpips'):
|
| 53 |
-
add(pre + m, 'B', fs, m)
|
| 54 |
-
for fs in ('interp', 'recon'):
|
| 55 |
-
pre = 'depth_render_' if fs == 'interp' else 'depth_render_recon_'
|
| 56 |
-
add(pre + 'drmse', 'depth_render', fs, 'full_drmse')
|
| 57 |
-
add(pre + 'absrel', 'depth_render', fs, 'full_absrel')
|
| 58 |
-
add('depth_input_drmse', 'depth_input', 'recon', 'pass1_full_drmse')
|
| 59 |
-
add('depth_input_absrel', 'depth_input', 'recon', 'pass1_full_absrel')
|
| 60 |
-
for fs in ('interp', 'recon'):
|
| 61 |
-
f = FRAME_SET_NAMES[fs]
|
| 62 |
-
for m in ('psnr', 'ssim', 'lpips'):
|
| 63 |
-
add(f'e_{f}_{m}', 'A2', fs, 'E_' + m)
|
| 64 |
-
for reg in ('semi', 'sky', 'depth_invalid', 'observed', 'scene', 'void'):
|
| 65 |
-
old = 'diagnostic_' + reg if reg in ('semi', 'sky', 'depth_invalid') else reg
|
| 66 |
-
for m in ('psnr', 'ssim', 'lpips'):
|
| 67 |
-
add(f'a2_{f}_{reg}_{m}', 'A2', fs, f'{old}_{m}')
|
| 68 |
-
for m in ('dists', 'kid', 'seam_gradient'):
|
| 69 |
-
add(f'u_{f}_{m}' if m != 'seam_gradient' else f'u_{f}_seam', 'B', fs, m)
|
| 70 |
-
add(f'u_{f}_fid', 'B', fs, 'fid')
|
| 71 |
-
for p in ('pass1', 'pass2'):
|
| 72 |
-
for s in ('mean', 'median', 'p10', 'p90', 'precision', 'recall'):
|
| 73 |
-
add(f'b_{f}_{p}_opacity_{s}', 'B', fs, f'{p}_opacity_{s}')
|
| 74 |
-
for s in ('precision', 'recall'):
|
| 75 |
-
add(f'b_{f}_{p}_onlinev_{s}', 'B', fs, f'{p}_online_v_{s}')
|
| 76 |
-
for reg in ('U', 'semi', 'sky', 'depth_invalid', 'observed', 'scene', 'void'):
|
| 77 |
-
old = 'diagnostic_' + reg if reg in ('semi', 'sky', 'depth_invalid') else reg
|
| 78 |
-
for m in ('drmse', 'absrel'):
|
| 79 |
-
add(f'depth_render_{f}_{reg}_{m}', 'depth_render', fs, f'{old}_{m}')
|
| 80 |
-
for reg in ('U', 'semi', 'sky', 'depth_invalid', 'observed', 'scene', 'void'):
|
| 81 |
-
old = 'diagnostic_' + reg if reg in ('semi', 'sky', 'depth_invalid') else reg
|
| 82 |
-
for m in ('drmse', 'absrel'):
|
| 83 |
-
add(f'depth_input_{reg}_{m}', 'depth_input', 'recon', f'pass1_{old}_{m}')
|
| 84 |
-
return cols
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
COLUMNS = build_columns()
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def table_statistics(per_clip, collections):
|
| 91 |
-
tables = {}
|
| 92 |
-
for key in sorted({(r['table'], r['frame_set']) for r in per_clip}):
|
| 93 |
-
rows = [r for r in per_clip if (r['table'], r['frame_set']) == key]
|
| 94 |
-
keys = sorted({k for r in rows for k in r['values']} | {k for (t, f, _), v in collections.items()
|
| 95 |
-
if (t, f) == key for k in v})
|
| 96 |
-
split, counts, coll = {}, {}, {}
|
| 97 |
-
for group in SPLITS:
|
| 98 |
-
group_rows = [r for r in rows if group == 'all' or r['group'] == group]
|
| 99 |
-
split[group], counts[group] = {}, {}
|
| 100 |
-
for k in keys:
|
| 101 |
-
stat = aggregate_rows(group_rows, k)
|
| 102 |
-
split[group][k], counts[group][k] = stat['value'], stat['n_valid']
|
| 103 |
-
split[group]['n'] = len(group_rows)
|
| 104 |
-
coll[group] = collections.get((*key, group), {})
|
| 105 |
-
for k, value in coll[group].items():
|
| 106 |
-
split[group][k] = value['value']
|
| 107 |
-
counts[group][k] = None
|
| 108 |
-
tables[key] = dict(split=split, valid_clip_counts=counts, collection_statistics=coll)
|
| 109 |
-
return tables
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
def summary(tables):
|
| 113 |
-
out = {s: {} for s in SPLITS}
|
| 114 |
-
counts = {s: {} for s in SPLITS}
|
| 115 |
-
for new, tab, fs, old in COLUMNS:
|
| 116 |
-
src = tables.get((tab, fs))
|
| 117 |
-
if src is None:
|
| 118 |
-
continue
|
| 119 |
-
for s in SPLITS:
|
| 120 |
-
out[s][new] = src['split'][s].get(old)
|
| 121 |
-
counts[s][new] = src['valid_clip_counts'][s].get(old)
|
| 122 |
-
first = tables.get(('A1', 'interp')) or next(iter(tables.values()))
|
| 123 |
-
for s in SPLITS:
|
| 124 |
-
out[s]['n'] = first['split'][s]['n']
|
| 125 |
-
return dict(split=out, valid_clip_counts=counts)
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
def export(per_clip, collections, destination):
|
| 129 |
destination = Path(destination)
|
| 130 |
-
tables = table_statistics(per_clip, collections)
|
| 131 |
write_json(destination / 'per_clip.json', per_clip)
|
| 132 |
-
|
| 133 |
-
result = summary(tables)
|
| 134 |
write_json(destination / 'summary.json', result)
|
| 135 |
return result
|
|
|
|
| 9 |
|
| 10 |
from .rgb import mean, number, scalar
|
| 11 |
|
| 12 |
+
METRICS = ('full_psnr', 'full_ssim', 'full_lpips', 'observed_psnr', 'observed_ssim', 'observed_lpips',
|
| 13 |
+
'unobserved_psnr', 'unobserved_lpips', 'unobserved_dists', 'depth_absrel', 'depth_rmse')
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
def write_json(path, value):
|
|
|
|
| 28 |
return isinstance(value, (int, float, np.floating)) and not math.isnan(value) and value != -float('inf')
|
| 29 |
|
| 30 |
|
| 31 |
+
def summary(per_clip):
|
| 32 |
+
out, counts = {}, {}
|
| 33 |
+
for key in METRICS:
|
| 34 |
+
values = [row['values'][key] for row in per_clip if valid_value(row['values'][key])]
|
| 35 |
+
out[key], counts[key] = (scalar(mean(values)) if values else None), len(values)
|
| 36 |
+
out['n'] = len(per_clip)
|
| 37 |
+
return dict(metrics=out, valid_clip_counts=counts)
|
| 38 |
|
| 39 |
|
| 40 |
+
def export(per_clip, destination):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
destination = Path(destination)
|
|
|
|
| 42 |
write_json(destination / 'per_clip.json', per_clip)
|
| 43 |
+
result = summary(per_clip)
|
|
|
|
| 44 |
write_json(destination / 'summary.json', result)
|
| 45 |
return result
|
code/agt/masks/pipeline.py
CHANGED
|
@@ -15,7 +15,6 @@ from .verify import build_pages, read_proposals, read_verdicts, send_page, write
|
|
| 15 |
SCHEMA = "clip_masks_v1"
|
| 16 |
CONTEXT_POSITIONS = [0, 5, 10, 15]
|
| 17 |
GRID = (518, 294)
|
| 18 |
-
OVERLAY_COLOUR = (255, 0, 255)
|
| 19 |
|
| 20 |
|
| 21 |
def load_config(path) -> dict:
|
|
@@ -112,11 +111,9 @@ def frame_mask(directory: Path, config: dict) -> dict:
|
|
| 112 |
verdict_of = read_verdicts(directory, p["kept"])
|
| 113 |
a = assemble_entities(p["raw"], p["kept"], verdict_of, post)
|
| 114 |
target = grid_masks(a["repaired"], a["roles"], GRID, bottom_ratio=post["bottom_opaque_ratio"], edge_settings=post["panel_edge"])
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
return {"mask": target["mask"], "overlay": overlay,
|
| 119 |
-
"stats": {"raw_candidates": len(p["raw"]), "candidates": len(p["kept"]), "overlay_yes": len(overlay_indices),
|
| 120 |
"no_candidates": not p["kept"], **a["summary"]}}
|
| 121 |
|
| 122 |
|
|
@@ -145,9 +142,8 @@ def finish(export, out, config: dict, clips=None) -> dict:
|
|
| 145 |
"frame_vote_iou": [iou(m, occluder) for m in per_frame],
|
| 146 |
"no_candidate_positions": [f["position"] for f, s in zip(clip_frames, frame_stats) if s["no_candidates"]],
|
| 147 |
"no_accepted_positions": [f["position"] for f, s in zip(clip_frames, frame_stats) if s["yes"] == 0],
|
| 148 |
-
"verified_yes": sum(s["yes"] for s in frame_stats),
|
| 149 |
-
|
| 150 |
-
qc_image(out / "qc" / f"{cid}.png", cid, clip_frames, occluder, per_frame, [r["overlay"] for r in results], frame_stats)
|
| 151 |
done.append(cid)
|
| 152 |
write_json(out / "stats.json", stats)
|
| 153 |
write_json(out / "manifest.json", {"schema": SCHEMA, "grid_hw": [GRID[1], GRID[0]], "context_positions": CONTEXT_POSITIONS,
|
|
@@ -155,21 +151,20 @@ def finish(export, out, config: dict, clips=None) -> dict:
|
|
| 155 |
return {"stage": "finish", "clips": len(done), "out": str(out)}
|
| 156 |
|
| 157 |
|
| 158 |
-
def qc_image(path: Path, cid: str, frames: list[dict], occluder, per_frame,
|
| 159 |
edge = outline(occluder.astype(bool))
|
| 160 |
canvas = Image.new("RGB", (2 * GRID[0], 2 * (GRID[1] + 26) + 26), "#101820")
|
| 161 |
draw = ImageDraw.Draw(canvas)
|
| 162 |
-
draw.text((6, 6), f"{cid} | RED: per-frame; GREEN: vote
|
| 163 |
for i, frame in enumerate(frames):
|
| 164 |
with Image.open(frame["path"]) as im:
|
| 165 |
rgb = np.asarray(im.convert("RGB").resize(GRID, Image.Resampling.BICUBIC)).copy()
|
| 166 |
mask = per_frame[i].astype(bool)
|
| 167 |
rgb[mask] = (rgb[mask] * .55 + np.array([255, 0, 0]) * .45).astype(np.uint8)
|
| 168 |
rgb[edge] = [0, 255, 0]
|
| 169 |
-
rgb[outline(overlays[i].astype(bool))] = OVERLAY_COLOUR
|
| 170 |
x, y = (i % 2) * GRID[0], 26 + (i // 2) * (GRID[1] + 26)
|
| 171 |
s = frame_stats[i]
|
| 172 |
-
draw.text((x + 6, y + 6), f"pos {frame['position']:02d} | candidates {s['candidates']} | yes {s['yes']}
|
| 173 |
+ (" | NO CANDIDATES" if s["no_candidates"] else ""), fill="white")
|
| 174 |
canvas.paste(Image.fromarray(rgb), (x, y + 26))
|
| 175 |
canvas.save(path)
|
|
|
|
| 15 |
SCHEMA = "clip_masks_v1"
|
| 16 |
CONTEXT_POSITIONS = [0, 5, 10, 15]
|
| 17 |
GRID = (518, 294)
|
|
|
|
| 18 |
|
| 19 |
|
| 20 |
def load_config(path) -> dict:
|
|
|
|
| 111 |
verdict_of = read_verdicts(directory, p["kept"])
|
| 112 |
a = assemble_entities(p["raw"], p["kept"], verdict_of, post)
|
| 113 |
target = grid_masks(a["repaired"], a["roles"], GRID, bottom_ratio=post["bottom_opaque_ratio"], edge_settings=post["panel_edge"])
|
| 114 |
+
np.savez_compressed(directory / "frame_mask.npz", solid_mask_hard=target["mask"])
|
| 115 |
+
return {"mask": target["mask"],
|
| 116 |
+
"stats": {"raw_candidates": len(p["raw"]), "candidates": len(p["kept"]),
|
|
|
|
|
|
|
| 117 |
"no_candidates": not p["kept"], **a["summary"]}}
|
| 118 |
|
| 119 |
|
|
|
|
| 142 |
"frame_vote_iou": [iou(m, occluder) for m in per_frame],
|
| 143 |
"no_candidate_positions": [f["position"] for f, s in zip(clip_frames, frame_stats) if s["no_candidates"]],
|
| 144 |
"no_accepted_positions": [f["position"] for f, s in zip(clip_frames, frame_stats) if s["yes"] == 0],
|
| 145 |
+
"verified_yes": sum(s["yes"] for s in frame_stats), "per_frame": frame_stats}
|
| 146 |
+
qc_image(out / "qc" / f"{cid}.png", cid, clip_frames, occluder, per_frame, frame_stats)
|
|
|
|
| 147 |
done.append(cid)
|
| 148 |
write_json(out / "stats.json", stats)
|
| 149 |
write_json(out / "manifest.json", {"schema": SCHEMA, "grid_hw": [GRID[1], GRID[0]], "context_positions": CONTEXT_POSITIONS,
|
|
|
|
| 151 |
return {"stage": "finish", "clips": len(done), "out": str(out)}
|
| 152 |
|
| 153 |
|
| 154 |
+
def qc_image(path: Path, cid: str, frames: list[dict], occluder, per_frame, frame_stats) -> None:
|
| 155 |
edge = outline(occluder.astype(bool))
|
| 156 |
canvas = Image.new("RGB", (2 * GRID[0], 2 * (GRID[1] + 26) + 26), "#101820")
|
| 157 |
draw = ImageDraw.Draw(canvas)
|
| 158 |
+
draw.text((6, 6), f"{cid} | RED: per-frame; GREEN: vote", fill="white")
|
| 159 |
for i, frame in enumerate(frames):
|
| 160 |
with Image.open(frame["path"]) as im:
|
| 161 |
rgb = np.asarray(im.convert("RGB").resize(GRID, Image.Resampling.BICUBIC)).copy()
|
| 162 |
mask = per_frame[i].astype(bool)
|
| 163 |
rgb[mask] = (rgb[mask] * .55 + np.array([255, 0, 0]) * .45).astype(np.uint8)
|
| 164 |
rgb[edge] = [0, 255, 0]
|
|
|
|
| 165 |
x, y = (i % 2) * GRID[0], 26 + (i // 2) * (GRID[1] + 26)
|
| 166 |
s = frame_stats[i]
|
| 167 |
+
draw.text((x + 6, y + 6), f"pos {frame['position']:02d} | candidates {s['candidates']} | yes {s['yes']}"
|
| 168 |
+ (" | NO CANDIDATES" if s["no_candidates"] else ""), fill="white")
|
| 169 |
canvas.paste(Image.fromarray(rgb), (x, y + 26))
|
| 170 |
canvas.save(path)
|
code/agt/model/build.py
CHANGED
|
@@ -33,6 +33,7 @@ def build_model(config=None, checkpoint=None, checkpoint_dir=None):
|
|
| 33 |
add_dggt_to_path()
|
| 34 |
from dggt.models.vggt import VGGT
|
| 35 |
model = VGGT(img_size=config['img_size'], patch_size=config['patch_size'], embed_dim=config['embed_dim'])
|
|
|
|
| 36 |
for name in config['removed_heads']:
|
| 37 |
setattr(model, name, None)
|
| 38 |
state = load_file(str(resolve_checkpoint(config, checkpoint, checkpoint_dir)))
|
|
|
|
| 33 |
add_dggt_to_path()
|
| 34 |
from dggt.models.vggt import VGGT
|
| 35 |
model = VGGT(img_size=config['img_size'], patch_size=config['patch_size'], embed_dim=config['embed_dim'])
|
| 36 |
+
model.track_head = None
|
| 37 |
for name in config['removed_heads']:
|
| 38 |
setattr(model, name, None)
|
| 39 |
state = load_file(str(resolve_checkpoint(config, checkpoint, checkpoint_dir)))
|
code/agt/model/runtime.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
from .gating import cap_scales, gate_predictions, mask_for_images
|
| 2 |
from .mask_attention import mask_context
|
| 3 |
-
from .visibility import ext_to_c2w, visibility
|
| 4 |
|
| 5 |
|
| 6 |
def cameras(predictions, images):
|
|
@@ -9,32 +9,28 @@ def cameras(predictions, images):
|
|
| 9 |
return ext, K
|
| 10 |
|
| 11 |
|
| 12 |
-
def
|
| 13 |
-
mask = mask_for_images(mask, images)
|
| 14 |
-
ext, K = cameras(predictions, images)
|
| 15 |
-
t = mask.shape[1]
|
| 16 |
-
if t <= 8:
|
| 17 |
-
return visibility(predictions['depth'][..., 0], K, ext_to_c2w(ext), mask, z_tol=z_tol)
|
| 18 |
-
c2w = ext_to_c2w(ext)
|
| 19 |
V = None
|
| 20 |
-
for i in range(0,
|
| 21 |
-
v = visibility(
|
| 22 |
V = v if V is None else V | v
|
| 23 |
-
return
|
| 24 |
|
| 25 |
|
| 26 |
-
def
|
| 27 |
mask = mask_for_images(mask, images)
|
| 28 |
ext, K = cameras(predictions, images)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
| 38 |
|
| 39 |
|
| 40 |
def predict(model, images, occluder_mask, *, z_tol=None, attention_mask=None):
|
|
|
|
| 1 |
from .gating import cap_scales, gate_predictions, mask_for_images
|
| 2 |
from .mask_attention import mask_context
|
| 3 |
+
from .visibility import ext_to_c2w, visibility
|
| 4 |
|
| 5 |
|
| 6 |
def cameras(predictions, images):
|
|
|
|
| 9 |
return ext, K
|
| 10 |
|
| 11 |
|
| 12 |
+
def observed_by_inputs(depth, K, c2w, mask, inputs, *, z_tol):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
V = None
|
| 14 |
+
for i in range(0, inputs, 8):
|
| 15 |
+
v = visibility(depth, K, c2w, mask, list(range(i, min(i + 8, inputs))), z_tol=z_tol)['V']
|
| 16 |
V = v if V is None else V | v
|
| 17 |
+
return V
|
| 18 |
|
| 19 |
|
| 20 |
+
def online_visibility(predictions, images, mask, *, z_tol=.05):
|
| 21 |
mask = mask_for_images(mask, images)
|
| 22 |
ext, K = cameras(predictions, images)
|
| 23 |
+
return {'V': observed_by_inputs(predictions['depth'][..., 0], K, ext_to_c2w(ext), mask, mask.shape[1], z_tol=z_tol)}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def render_visibility(input_depth, input_K, input_w2c, render_depth, render_K, render_w2c, mask, *, z_tol):
|
| 27 |
+
import torch
|
| 28 |
+
n = input_depth.shape[1]
|
| 29 |
+
depth = torch.cat([input_depth, render_depth], 1)
|
| 30 |
+
K = torch.cat([input_K, render_K], 1)
|
| 31 |
+
c2w = ext_to_c2w(torch.cat([input_w2c, render_w2c], 1))
|
| 32 |
+
mask = mask[:, :1].expand(depth.shape).contiguous()
|
| 33 |
+
return observed_by_inputs(depth, K, c2w, mask, n, z_tol=z_tol)[:, n:]
|
| 34 |
|
| 35 |
|
| 36 |
def predict(model, images, occluder_mask, *, z_tol=None, attention_mask=None):
|
code/agt/model/visibility.py
CHANGED
|
@@ -95,7 +95,7 @@ def visibility(depth, K, c2w, mask, source_indices=None, *, alpha=None, z_tol=Z_
|
|
| 95 |
|
| 96 |
|
| 97 |
@torch.no_grad()
|
| 98 |
-
def visibility_camera(depth, K, c2w, mask, source_indices=None, *, alpha=None, a_tol=A_TOL
|
| 99 |
b, t, h, w = depth.shape
|
| 100 |
if mask.shape != depth.shape or K.shape != (b, t, 3, 3) or c2w.shape != (b, t, 4, 4):
|
| 101 |
raise ValueError('visibility: depth/mask/camera shape mismatch')
|
|
|
|
| 95 |
|
| 96 |
|
| 97 |
@torch.no_grad()
|
| 98 |
+
def visibility_camera(depth, K, c2w, mask, source_indices=None, *, alpha=None, a_tol=A_TOL):
|
| 99 |
b, t, h, w = depth.shape
|
| 100 |
if mask.shape != depth.shape or K.shape != (b, t, 3, 3) or c2w.shape != (b, t, 4, 4):
|
| 101 |
raise ValueError('visibility: depth/mask/camera shape mismatch')
|
code/agt/recon/outputs.py
CHANGED
|
@@ -9,7 +9,6 @@ import numpy as np
|
|
| 9 |
FRAMES = 20
|
| 10 |
GRID = (518, 294)
|
| 11 |
DEPTH_SEMANTICS = 'normalized_expected_camera_z'
|
| 12 |
-
CONTEXT = [0, 5, 10, 15]
|
| 13 |
|
| 14 |
|
| 15 |
def check_positions(positions) -> list:
|
|
@@ -45,26 +44,6 @@ def write_depth_clip(root, clip_id: str, depth, alpha, positions=None) -> None:
|
|
| 45 |
temp.replace(directory / 'depth.npz')
|
| 46 |
|
| 47 |
|
| 48 |
-
def write_input_depth(root, clip, depth, pose_enc, ext, K) -> dict:
|
| 49 |
-
root = Path(root) / clip['clip_id']
|
| 50 |
-
root.mkdir(parents=True, exist_ok=True)
|
| 51 |
-
arrays = {'depth': np.asarray(depth).astype('float16'), 'pose_enc': np.asarray(pose_enc, np.float32),
|
| 52 |
-
'ext': np.asarray(ext, np.float32), 'K': np.asarray(K, np.float32),
|
| 53 |
-
'context_positions': np.asarray(CONTEXT)}
|
| 54 |
-
if arrays['depth'].shape[0] != 4 or not np.isfinite(arrays['depth']).all() or np.any(arrays['depth'] <= 0):
|
| 55 |
-
raise ValueError('input depth must be finite positive float16 [4,H,W]')
|
| 56 |
-
temp = root / '.input_depth.npz'
|
| 57 |
-
np.savez_compressed(temp, **arrays)
|
| 58 |
-
temp.replace(root / 'input_depth.npz')
|
| 59 |
-
record = {'file': 'input_depth.npz', 'clip_id': clip['clip_id'], 'context_positions': CONTEXT, 'dtype': 'float16',
|
| 60 |
-
'shape': list(arrays['depth'].shape),
|
| 61 |
-
'semantics': 'depth head camera z, unaligned; ext world-to-camera; not Gaussian expected depth'}
|
| 62 |
-
temp = root / '.input_depth.json'
|
| 63 |
-
temp.write_text(json.dumps(record, indent=1) + '\n')
|
| 64 |
-
temp.replace(root / 'input_depth.json')
|
| 65 |
-
return record
|
| 66 |
-
|
| 67 |
-
|
| 68 |
def write_meta(root, clips, positions, extra=None) -> dict:
|
| 69 |
root = Path(root)
|
| 70 |
meta = {**(extra or {}), 'native_resolution': list(GRID), 'dtype': 'float32',
|
|
|
|
| 9 |
FRAMES = 20
|
| 10 |
GRID = (518, 294)
|
| 11 |
DEPTH_SEMANTICS = 'normalized_expected_camera_z'
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
def check_positions(positions) -> list:
|
|
|
|
| 44 |
temp.replace(directory / 'depth.npz')
|
| 45 |
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
def write_meta(root, clips, positions, extra=None) -> dict:
|
| 48 |
root = Path(root)
|
| 49 |
meta = {**(extra or {}), 'native_resolution': list(GRID), 'dtype': 'float32',
|
code/agt/recon/reconstruct.py
CHANGED
|
@@ -12,59 +12,23 @@ import time
|
|
| 12 |
import numpy as np
|
| 13 |
|
| 14 |
from . import interp as interp_vectorized
|
| 15 |
-
from .outputs import write_clip, write_depth_clip,
|
| 16 |
from .pose_rule import interpolate_poses
|
| 17 |
|
| 18 |
-
CONTEXT_POSITIONS = [0, 5, 10, 15]
|
| 19 |
-
POSITIONS = list(range(16))
|
| 20 |
TARGET_SIZE = 518
|
| 21 |
GRID = (518, 294)
|
| 22 |
SKY_LABEL = 10
|
| 23 |
PRECISION = {'matmul': False, 'cudnn': True}
|
| 24 |
SKY_PRECISION = {'matmul': False, 'cudnn': False}
|
| 25 |
-
|
| 26 |
-
|
| 27 |
INTERVAL, VIEWS = 5, 1
|
| 28 |
DY_THRESHOLD, DY_MIN_PIXELS = 0.95, 500
|
| 29 |
-
|
| 30 |
-
RENDER_SKY_FILE = 'render_sky.npz'
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def write_render_cameras(clip_dir, w2c, K, t_norm, positions, context_positions) -> dict:
|
| 34 |
-
w2c = np.asarray(w2c, np.float32); K = np.asarray(K, np.float32)
|
| 35 |
-
n = len(positions)
|
| 36 |
-
if w2c.shape != (n, 4, 4) or K.shape != (n, 3, 3) or len(t_norm) != n:
|
| 37 |
-
raise ValueError(f'render cameras {w2c.shape} / {K.shape} / {len(t_norm)} for {n} targets')
|
| 38 |
-
arrays = {'w2c': w2c, 'c2w': np.linalg.inv(w2c.astype(np.float64)), 'K': K,
|
| 39 |
-
't_norm': np.asarray(t_norm, np.float64), 'positions': np.asarray(positions, np.int64),
|
| 40 |
-
'context_positions': np.asarray(context_positions, np.int64)}
|
| 41 |
-
clip_dir = Path(clip_dir); clip_dir.mkdir(parents=True, exist_ok=True)
|
| 42 |
-
temp = clip_dir / ('.' + RENDER_CAMERAS_FILE)
|
| 43 |
-
np.savez_compressed(temp, **arrays)
|
| 44 |
-
temp.replace(clip_dir / RENDER_CAMERAS_FILE)
|
| 45 |
-
return arrays
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
def render_sky(seg, rgb) -> np.ndarray:
|
| 49 |
-
import torch
|
| 50 |
-
from .sky import slide_inference
|
| 51 |
-
out = []
|
| 52 |
-
for frame in np.asarray(rgb):
|
| 53 |
-
image = (np.clip(frame, 0, 1) * 255).round().astype(np.uint8)
|
| 54 |
-
with precision(**SKY_PRECISION), torch.inference_mode():
|
| 55 |
-
labels = slide_inference(seg, image[..., ::-1].copy(), 'cuda', torch.float32)
|
| 56 |
-
out.append(np.asarray(labels) == SKY_LABEL)
|
| 57 |
-
return np.stack(out)
|
| 58 |
|
| 59 |
|
| 60 |
-
def
|
| 61 |
-
|
| 62 |
-
if sky.shape != (len(positions), GRID[1], GRID[0]) or sky.dtype != bool:
|
| 63 |
-
raise ValueError(f'render sky {sky.shape} {sky.dtype}')
|
| 64 |
-
clip_dir = Path(clip_dir); clip_dir.mkdir(parents=True, exist_ok=True)
|
| 65 |
-
temp = clip_dir / ('.' + RENDER_SKY_FILE)
|
| 66 |
-
np.savez_compressed(temp, sky=sky.astype(np.uint8), positions=np.asarray(positions, np.int64))
|
| 67 |
-
temp.replace(clip_dir / RENDER_SKY_FILE)
|
| 68 |
|
| 69 |
|
| 70 |
def plain_gate(t, t0, alpha, gamma0=1, gamma1=0.1):
|
|
@@ -123,10 +87,10 @@ def interp_frame_index(context_positions, positions) -> list:
|
|
| 123 |
return list(positions)
|
| 124 |
|
| 125 |
|
| 126 |
-
def
|
| 127 |
np.random.seed(seed)
|
| 128 |
(ext_i, k_i, point_map, gs_map, dy_map, gs_conf, bg_mask, _, _, _, _) = interp_all(
|
| 129 |
-
ext, k, xyz, gs, dy, conf, mask, images, None, depth[0].unsqueeze(0),
|
| 130 |
return {'extrinsics': ext_i, 'intrinsics': k_i, 'point_map': point_map, 'gs_map': gs_map, 'dy_map': dy_map,
|
| 131 |
'gs_conf': gs_conf, 'bg_mask': bg_mask}
|
| 132 |
|
|
@@ -194,7 +158,7 @@ def counting_filter_dense_points(points, radius=0.2, min_neighbors=10, min_total
|
|
| 194 |
return filtered
|
| 195 |
|
| 196 |
|
| 197 |
-
def
|
| 198 |
import importlib
|
| 199 |
import importlib.util
|
| 200 |
copy, ckpt = Path(dggt_root).resolve(), Path(ckpt)
|
|
@@ -207,46 +171,42 @@ def load_tracker(dggt_root, ckpt) -> dict:
|
|
| 207 |
spec.loader.exec_module(module)
|
| 208 |
model = inference_utils.load_model(str(ckpt))
|
| 209 |
model.to('cuda')
|
| 210 |
-
model.seq_len =
|
| 211 |
module.filter_dense_points = counting_filter_dense_points
|
| 212 |
return {'interp_all': interp_vectorized.bind(module), 'model': model, 'probe': _Probe(module)}
|
| 213 |
|
| 214 |
|
| 215 |
-
def
|
| 216 |
import torch
|
| 217 |
-
probe =
|
| 218 |
probe.reset()
|
| 219 |
dy_pixels = int((dy.sigmoid() > DY_THRESHOLD)[0, 0].count_nonzero())
|
| 220 |
-
diag = {'seed': seed, '
|
| 221 |
start = time.perf_counter()
|
| 222 |
try:
|
| 223 |
-
src =
|
|
|
|
| 224 |
except UnboundLocalError as error:
|
| 225 |
-
if not (diag['
|
| 226 |
raise
|
| 227 |
src, diag['fallback'] = None, f'repeat: interp_all {type(error).__name__} ({error}) with no cluster on input 0'
|
| 228 |
if torch.cuda.is_available():
|
| 229 |
torch.cuda.synchronize()
|
| 230 |
diag.update({'interp_all_seconds': time.perf_counter() - start, 'dbscan_clusters': [f['clusters'] for f in probe.fits],
|
| 231 |
-
'objects': probe.fits[0]['clusters'] if probe.fits else 0, '
|
| 232 |
return src, diag
|
| 233 |
|
| 234 |
|
| 235 |
def render(model, images, sky, times, validity, target_times, target_positions, context_positions,
|
| 236 |
-
|
| 237 |
import torch
|
| 238 |
from gsplat.rendering import rasterization
|
| 239 |
from dggt.utils.geometry import unproject_depth_map_to_point_map
|
| 240 |
from dggt.utils.gs import concat_list, get_split_gs
|
| 241 |
from dggt.utils.pose_enc import pose_encoding_to_extri_intri
|
| 242 |
-
from ..model.runtime import
|
| 243 |
pred, online_v = predict(model, images, ~validity, **({'attention_mask': attention_mask} if attention_mask is not None else {}),
|
| 244 |
**({'z_tol': v_z_tol} if v_z_tol is not None else {}))
|
| 245 |
-
exported_v = online_v
|
| 246 |
-
if online_v_semantics == 'camera_only':
|
| 247 |
-
exported_v = online_visibility_camera(pred, images, ~validity)['V']
|
| 248 |
-
elif online_v_semantics != 'depth_consistency':
|
| 249 |
-
raise ValueError('online_v_semantics must be depth_consistency or camera_only')
|
| 250 |
h, w = images.shape[-2:]
|
| 251 |
ext, k = pose_encoding_to_extri_intri(pred['pose_enc'], (h, w)); ext = ext[0]; k = k[0]
|
| 252 |
xyz = torch.from_numpy(unproject_depth_map_to_point_map(pred['depth'][0], ext, k)[None]).to(images.device).float()
|
|
@@ -262,10 +222,10 @@ def render(model, images, sky, times, validity, target_times, target_positions,
|
|
| 262 |
ext_t = torch.as_tensor(ext_np, dtype=ext.dtype, device=ext.device)
|
| 263 |
k_t = torch.as_tensor(k_np, dtype=k.dtype, device=k.device)
|
| 264 |
dynamic_from = previous_context(context_positions, target_positions)
|
| 265 |
-
src,
|
| 266 |
-
if
|
| 267 |
frame_of = interp_frame_index(context_positions, target_positions)
|
| 268 |
-
src,
|
| 269 |
context_positions)
|
| 270 |
renders, alphas, depths = [], [], []
|
| 271 |
for j in range(len(target_positions)):
|
|
@@ -290,14 +250,22 @@ def render(model, images, sky, times, validity, target_times, target_positions,
|
|
| 290 |
alpha = torch.cat(alphas); foreground = torch.cat(renders)
|
| 291 |
background = model.sky_model.forward_with_new_pose(images, ext, k, ext_t, k_t)
|
| 292 |
out = alpha * foreground + (1 - alpha) * background
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
diag = {'sources': int(mask.sum()), 'alpha_mean': float(alpha.mean())}
|
| 294 |
-
if
|
| 295 |
-
diag['
|
| 296 |
-
auxiliary = {'depth':
|
| 297 |
-
'online_v': exported_v[0].to(torch.uint8), 'gate_v': online_v[0].to(torch.uint8),
|
| 298 |
-
'opacity_u8': (alpha[..., 0].clamp(0, 1) * 255).round().to(torch.uint8),
|
| 299 |
-
'input_depth': pred['depth'][0, ..., 0], 'input_pose_enc': pred['pose_enc'][0],
|
| 300 |
-
'input_ext': ext[:, :3, :], 'input_K': k, 'render_w2c': ext_t, 'render_K': k_t}
|
| 301 |
return out, diag, auxiliary
|
| 302 |
|
| 303 |
|
|
@@ -339,10 +307,10 @@ def run_render(args) -> None:
|
|
| 339 |
masks = open_masks(args)
|
| 340 |
seg = load_segformer(args.segformer)
|
| 341 |
model = build_model(config, args.checkpoint, args.checkpoint_dir)
|
| 342 |
-
|
| 343 |
-
if
|
| 344 |
-
ckpt = args.
|
| 345 |
-
|
| 346 |
versions = {}
|
| 347 |
for name in ('torch', 'torchvision', 'gsplat', 'numpy', 'scipy', 'pillow', 'transformers'):
|
| 348 |
try:
|
|
@@ -353,30 +321,20 @@ def run_render(args) -> None:
|
|
| 353 |
record = {'command': ' '.join(sys.argv), 'started_utc': datetime.now(timezone.utc).isoformat(),
|
| 354 |
'python': sys.version.split()[0], 'packages': versions, 'gpu': torch.cuda.get_device_name(0),
|
| 355 |
'config': config, 'masks': args.masks, 'mask_dilate': args.mask_dilate,
|
| 356 |
-
'
|
| 357 |
-
'online_v_semantics': args.online_v_semantics, 'v_z_tol': v_z_tol,
|
| 358 |
-
'export_render_cameras': args.export_render_cameras, 'export_render_sky': args.export_render_sky}
|
| 359 |
(out / f'render.{tag}.json').write_text(json.dumps(record, indent=1) + '\n')
|
| 360 |
log = (out / f'runtime.{tag}.jsonl').open('a')
|
| 361 |
writer = ThreadPoolExecutor(max_workers=2)
|
| 362 |
pending = []
|
| 363 |
-
dense = args.input_frames == 'all'
|
| 364 |
for clip_id in _clips(inputs, args.shard, args.limit):
|
| 365 |
-
done = [out / clip_id / n for n in ('frames.npz', 'depth.npz',
|
| 366 |
-
done += [] if dense else [out / clip_id / 'input_depth.json']
|
| 367 |
-
done += [out / clip_id / RENDER_CAMERAS_FILE] if args.export_render_cameras else []
|
| 368 |
-
done += [out / clip_id / RENDER_SKY_FILE] if args.export_render_sky else []
|
| 369 |
if all(p.is_file() for p in done):
|
| 370 |
continue
|
| 371 |
try:
|
| 372 |
clip = json.loads((inputs / clip_id / 'clip.json').read_text())
|
| 373 |
-
ctx = clip['context_positions']
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
raise ValueError(f'input frames {ctx} / roles do not match the 4 + 12 layout')
|
| 377 |
-
targets = POSITIONS
|
| 378 |
-
if dense:
|
| 379 |
-
ctx = targets = list(range(len(clip['frame_files'])))
|
| 380 |
occluder_mask, attention_np = masks.load(clip)
|
| 381 |
validity_np = ~occluder_mask
|
| 382 |
torch.cuda.synchronize(); start = time.perf_counter()
|
|
@@ -398,14 +356,13 @@ def run_render(args) -> None:
|
|
| 398 |
sky = torch.from_numpy(np.stack(skies)).cuda()
|
| 399 |
validity = torch.from_numpy(validity_np)[None, None].expand(1, len(ctx), -1, -1).contiguous().cuda()
|
| 400 |
t_norm = torch.tensor(clip['t_norm'], dtype=torch.float64, device='cuda')
|
| 401 |
-
|
| 402 |
-
t_norm = (t_norm - t_norm[0]) / (t_norm[-1] - t_norm[0])
|
| 403 |
attention_mask = torch.from_numpy(attention_np)[None, None].expand(1, len(ctx), -1, -1).to(images.device)
|
| 404 |
with precision(**PRECISION), torch.no_grad():
|
| 405 |
rgb, diag, aux = render(model, images, sky, t_norm[ctx], validity, t_norm[targets], targets, ctx,
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
rgb = rgb.clamp(0, 1).float()
|
| 410 |
torch.cuda.synchronize(); seconds = time.perf_counter() - start
|
| 411 |
rgb = rgb.cpu().numpy().astype(np.float32)
|
|
@@ -413,20 +370,10 @@ def run_render(args) -> None:
|
|
| 413 |
raise ValueError(f'render {rgb.shape}, finite={np.isfinite(rgb).all()}')
|
| 414 |
depth_np = aux['depth'].float().cpu().numpy(); alpha_np = aux['alpha'].float().cpu().numpy()
|
| 415 |
write_depth_clip(out, clip_id, depth_np, alpha_np, targets)
|
| 416 |
-
if args.export_render_cameras:
|
| 417 |
-
write_render_cameras(out / clip_id, aux['render_w2c'].cpu().numpy(), aux['render_K'].cpu().numpy(),
|
| 418 |
-
t_norm[targets].double().cpu().numpy(), targets, ctx)
|
| 419 |
-
if args.export_render_sky:
|
| 420 |
-
write_render_sky(out / clip_id, render_sky(seg, rgb), targets)
|
| 421 |
clip_out = out / clip_id
|
| 422 |
clip_out.mkdir(parents=True, exist_ok=True)
|
| 423 |
-
np.savez_compressed(clip_out /
|
| 424 |
-
|
| 425 |
-
context_positions=np.asarray(ctx), positions=np.asarray(targets))
|
| 426 |
-
if not dense:
|
| 427 |
-
write_input_depth(out, clip, aux['input_depth'].float().cpu().numpy(),
|
| 428 |
-
aux['input_pose_enc'].float().cpu().numpy(), aux['input_ext'].float().cpu().numpy(),
|
| 429 |
-
aux['input_K'].float().cpu().numpy())
|
| 430 |
pending.append((clip_id, writer.submit(write_clip, out, clip_id, rgb, targets)))
|
| 431 |
log.write(json.dumps({'clip_id': clip_id, 'seconds': seconds,
|
| 432 |
'peak_vram_gb': torch.cuda.max_memory_allocated() / 1e9,
|
|
@@ -458,8 +405,8 @@ def run_finalize(args) -> None:
|
|
| 458 |
if missing:
|
| 459 |
raise SystemExit(f'{len(missing)} clips without renders, e.g. {missing[:3]}; see runtime.*.jsonl')
|
| 460 |
first = json.loads(next(iter(sorted(out.glob('render.*.json')))).read_text())
|
| 461 |
-
|
| 462 |
-
|
| 463 |
write_meta(out, manifest['clips'], positions, {'method': 'agt', 'config': first['config']})
|
| 464 |
write_depth_meta(out, manifest['clips'], positions, {'method': 'agt'})
|
| 465 |
print(json.dumps({'out': str(out), 'clips': len(manifest['clips'])}))
|
|
@@ -475,29 +422,23 @@ def main(argv=None) -> None:
|
|
| 475 |
p.add_argument('--checkpoint-dir', default='checkpoints', help='directory with the released and third-party weights')
|
| 476 |
p.add_argument('--segformer', default='nvidia/segformer-b5-finetuned-cityscapes-1024-1024',
|
| 477 |
help='SegFormer-B5 Cityscapes: Hugging Face id or local directory')
|
| 478 |
-
p.add_argument('--
|
| 479 |
p.add_argument('--masks', choices=('dataset', 'dir', 'images'), default='dataset',
|
| 480 |
help='dataset: predicted masks of the AmodalDrive data root; dir: per-clip npz from tools/make_masks.py; '
|
| 481 |
'images: <mask-dir>/<clip_id>.png (255 = occluder)')
|
| 482 |
p.add_argument('--data-root', help='AmodalDrive data root (--masks dataset)')
|
| 483 |
p.add_argument('--mask-dir')
|
| 484 |
p.add_argument('--mask-dilate', type=int, default=0, help='mask dilation radius in pixels on the 294x518 grid')
|
| 485 |
-
p.add_argument('--
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
'
|
| 489 |
-
p.add_argument('--online-v-semantics', choices=('depth_consistency', 'camera_only'), default='depth_consistency',
|
| 490 |
-
help='semantics of the exported input-frame V in ab_maps.npz (the gate always uses depth consistency)')
|
| 491 |
-
p.add_argument('--export-render-cameras', action='store_true', help='write render_cameras.npz per clip')
|
| 492 |
-
p.add_argument('--export-render-sky', action='store_true', help='write render_sky.npz (SegFormer on the renders)')
|
| 493 |
p.add_argument('--shard', help='i/n: every n-th clip from i (run finalize after all shards)')
|
| 494 |
p.add_argument('--limit', type=int, help='render only the first n clips')
|
| 495 |
args = p.parse_args(argv)
|
| 496 |
if args.config is None:
|
| 497 |
from ..model.build import DEFAULT_CONFIG
|
| 498 |
args.config = DEFAULT_CONFIG
|
| 499 |
-
if args.input_frames == 'all' and not args.no_tracking:
|
| 500 |
-
p.error('--input-frames all needs --no-tracking')
|
| 501 |
if args.step == 'render':
|
| 502 |
run_render(args)
|
| 503 |
else:
|
|
|
|
| 12 |
import numpy as np
|
| 13 |
|
| 14 |
from . import interp as interp_vectorized
|
| 15 |
+
from .outputs import write_clip, write_depth_clip, write_meta, write_depth_meta
|
| 16 |
from .pose_rule import interpolate_poses
|
| 17 |
|
|
|
|
|
|
|
| 18 |
TARGET_SIZE = 518
|
| 19 |
GRID = (518, 294)
|
| 20 |
SKY_LABEL = 10
|
| 21 |
PRECISION = {'matmul': False, 'cudnn': True}
|
| 22 |
SKY_PRECISION = {'matmul': False, 'cudnn': False}
|
| 23 |
+
MOTION_HEAD = 'motion_head.pth'
|
| 24 |
+
MOTION_SEQ_LEN = 2
|
| 25 |
INTERVAL, VIEWS = 5, 1
|
| 26 |
DY_THRESHOLD, DY_MIN_PIXELS = 0.95, 500
|
| 27 |
+
OBSERVABILITY_FILE = 'observability.npz'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
|
| 30 |
+
def rendered_positions(input_positions) -> list:
|
| 31 |
+
return list(range(input_positions[0], input_positions[-1] + 1))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
|
| 34 |
def plain_gate(t, t0, alpha, gamma0=1, gamma1=0.1):
|
|
|
|
| 87 |
return list(positions)
|
| 88 |
|
| 89 |
|
| 90 |
+
def move_dynamic(interp_all, motion_model, ext, k, xyz, gs, dy, conf, mask, images, depth, seed: int) -> dict:
|
| 91 |
np.random.seed(seed)
|
| 92 |
(ext_i, k_i, point_map, gs_map, dy_map, gs_conf, bg_mask, _, _, _, _) = interp_all(
|
| 93 |
+
ext, k, xyz, gs, dy, conf, mask, images, None, depth[0].unsqueeze(0), motion_model, INTERVAL, VIEWS)
|
| 94 |
return {'extrinsics': ext_i, 'intrinsics': k_i, 'point_map': point_map, 'gs_map': gs_map, 'dy_map': dy_map,
|
| 95 |
'gs_conf': gs_conf, 'bg_mask': bg_mask}
|
| 96 |
|
|
|
|
| 158 |
return filtered
|
| 159 |
|
| 160 |
|
| 161 |
+
def load_motion_head(dggt_root, ckpt) -> dict:
|
| 162 |
import importlib
|
| 163 |
import importlib.util
|
| 164 |
copy, ckpt = Path(dggt_root).resolve(), Path(ckpt)
|
|
|
|
| 171 |
spec.loader.exec_module(module)
|
| 172 |
model = inference_utils.load_model(str(ckpt))
|
| 173 |
model.to('cuda')
|
| 174 |
+
model.seq_len = MOTION_SEQ_LEN
|
| 175 |
module.filter_dense_points = counting_filter_dense_points
|
| 176 |
return {'interp_all': interp_vectorized.bind(module), 'model': model, 'probe': _Probe(module)}
|
| 177 |
|
| 178 |
|
| 179 |
+
def motion_sources(motion_head, ext, k, xyz, gs, dy, conf, mask, images, depth, seed, context_positions):
|
| 180 |
import torch
|
| 181 |
+
probe = motion_head['probe']
|
| 182 |
probe.reset()
|
| 183 |
dy_pixels = int((dy.sigmoid() > DY_THRESHOLD)[0, 0].count_nonzero())
|
| 184 |
+
diag = {'seed': seed, 'dynamic_pixels_input0': dy_pixels, 'moves_objects': dy_pixels > DY_MIN_PIXELS}
|
| 185 |
start = time.perf_counter()
|
| 186 |
try:
|
| 187 |
+
src = move_dynamic(motion_head['interp_all'], motion_head['model'], ext, k, xyz, gs, dy, conf, mask, images,
|
| 188 |
+
depth, seed)
|
| 189 |
except UnboundLocalError as error:
|
| 190 |
+
if not (diag['moves_objects'] and probe.fits and probe.fits[0]['clusters'] == 0 and not probe.calls):
|
| 191 |
raise
|
| 192 |
src, diag['fallback'] = None, f'repeat: interp_all {type(error).__name__} ({error}) with no cluster on input 0'
|
| 193 |
if torch.cuda.is_available():
|
| 194 |
torch.cuda.synchronize()
|
| 195 |
diag.update({'interp_all_seconds': time.perf_counter() - start, 'dbscan_clusters': [f['clusters'] for f in probe.fits],
|
| 196 |
+
'objects': probe.fits[0]['clusters'] if probe.fits else 0, 'motion_head_calls': probe.calls})
|
| 197 |
return src, diag
|
| 198 |
|
| 199 |
|
| 200 |
def render(model, images, sky, times, validity, target_times, target_positions, context_positions,
|
| 201 |
+
motion_head=None, seed=None, v_z_tol=None, attention_mask=None):
|
| 202 |
import torch
|
| 203 |
from gsplat.rendering import rasterization
|
| 204 |
from dggt.utils.geometry import unproject_depth_map_to_point_map
|
| 205 |
from dggt.utils.gs import concat_list, get_split_gs
|
| 206 |
from dggt.utils.pose_enc import pose_encoding_to_extri_intri
|
| 207 |
+
from ..model.runtime import predict, render_visibility
|
| 208 |
pred, online_v = predict(model, images, ~validity, **({'attention_mask': attention_mask} if attention_mask is not None else {}),
|
| 209 |
**({'z_tol': v_z_tol} if v_z_tol is not None else {}))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
h, w = images.shape[-2:]
|
| 211 |
ext, k = pose_encoding_to_extri_intri(pred['pose_enc'], (h, w)); ext = ext[0]; k = k[0]
|
| 212 |
xyz = torch.from_numpy(unproject_depth_map_to_point_map(pred['depth'][0], ext, k)[None]).to(images.device).float()
|
|
|
|
| 222 |
ext_t = torch.as_tensor(ext_np, dtype=ext.dtype, device=ext.device)
|
| 223 |
k_t = torch.as_tensor(k_np, dtype=k.dtype, device=k.device)
|
| 224 |
dynamic_from = previous_context(context_positions, target_positions)
|
| 225 |
+
src, motion_diag = None, None
|
| 226 |
+
if motion_head is not None:
|
| 227 |
frame_of = interp_frame_index(context_positions, target_positions)
|
| 228 |
+
src, motion_diag = motion_sources(motion_head, ext, k, xyz, gs, dy, conf, mask, images, pred['depth'], seed,
|
| 229 |
context_positions)
|
| 230 |
renders, alphas, depths = [], [], []
|
| 231 |
for j in range(len(target_positions)):
|
|
|
|
| 250 |
alpha = torch.cat(alphas); foreground = torch.cat(renders)
|
| 251 |
background = model.sky_model.forward_with_new_pose(images, ext, k, ext_t, k_t)
|
| 252 |
out = alpha * foreground + (1 - alpha) * background
|
| 253 |
+
depth = torch.cat(depths)
|
| 254 |
+
ctx = list(context_positions)
|
| 255 |
+
unobserved = torch.zeros(depth.shape, dtype=torch.bool, device=depth.device)
|
| 256 |
+
held_out = [j for j, p in enumerate(target_positions) if p not in ctx]
|
| 257 |
+
for j, p in enumerate(target_positions):
|
| 258 |
+
if p in ctx:
|
| 259 |
+
unobserved[j] = ~online_v[0, ctx.index(p)]
|
| 260 |
+
if held_out:
|
| 261 |
+
observed = render_visibility(pred['depth'][..., 0], k[None], ext[None], depth[held_out][None], k_t[held_out][None],
|
| 262 |
+
ext_t[held_out][None], ~validity,
|
| 263 |
+
z_tol=model._options['v_z_tol'] if v_z_tol is None else v_z_tol)
|
| 264 |
+
unobserved[held_out] = ~observed[0]
|
| 265 |
diag = {'sources': int(mask.sum()), 'alpha_mean': float(alpha.mean())}
|
| 266 |
+
if motion_diag is not None:
|
| 267 |
+
diag['motion_head'] = motion_diag
|
| 268 |
+
auxiliary = {'depth': depth, 'alpha': alpha[..., 0], 'gate_v': online_v[0].to(torch.uint8), 'unobserved': unobserved}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
return out, diag, auxiliary
|
| 270 |
|
| 271 |
|
|
|
|
| 307 |
masks = open_masks(args)
|
| 308 |
seg = load_segformer(args.segformer)
|
| 309 |
model = build_model(config, args.checkpoint, args.checkpoint_dir)
|
| 310 |
+
motion_head = None
|
| 311 |
+
if args.input_frames is None or rendered_positions(args.input_frames) != args.input_frames:
|
| 312 |
+
ckpt = args.motion_head or Path(args.checkpoint_dir or 'checkpoints') / MOTION_HEAD
|
| 313 |
+
motion_head = load_motion_head(DGGT_ROOT, ckpt)
|
| 314 |
versions = {}
|
| 315 |
for name in ('torch', 'torchvision', 'gsplat', 'numpy', 'scipy', 'pillow', 'transformers'):
|
| 316 |
try:
|
|
|
|
| 321 |
record = {'command': ' '.join(sys.argv), 'started_utc': datetime.now(timezone.utc).isoformat(),
|
| 322 |
'python': sys.version.split()[0], 'packages': versions, 'gpu': torch.cuda.get_device_name(0),
|
| 323 |
'config': config, 'masks': args.masks, 'mask_dilate': args.mask_dilate,
|
| 324 |
+
'input_frames': args.input_frames, 'v_z_tol': v_z_tol}
|
|
|
|
|
|
|
| 325 |
(out / f'render.{tag}.json').write_text(json.dumps(record, indent=1) + '\n')
|
| 326 |
log = (out / f'runtime.{tag}.jsonl').open('a')
|
| 327 |
writer = ThreadPoolExecutor(max_workers=2)
|
| 328 |
pending = []
|
|
|
|
| 329 |
for clip_id in _clips(inputs, args.shard, args.limit):
|
| 330 |
+
done = [out / clip_id / n for n in ('frames.npz', 'depth.npz', OBSERVABILITY_FILE)]
|
|
|
|
|
|
|
|
|
|
| 331 |
if all(p.is_file() for p in done):
|
| 332 |
continue
|
| 333 |
try:
|
| 334 |
clip = json.loads((inputs / clip_id / 'clip.json').read_text())
|
| 335 |
+
ctx = list(args.input_frames or clip['context_positions'])
|
| 336 |
+
targets = rendered_positions(ctx)
|
| 337 |
+
held_out = targets != ctx
|
|
|
|
|
|
|
|
|
|
|
|
|
| 338 |
occluder_mask, attention_np = masks.load(clip)
|
| 339 |
validity_np = ~occluder_mask
|
| 340 |
torch.cuda.synchronize(); start = time.perf_counter()
|
|
|
|
| 356 |
sky = torch.from_numpy(np.stack(skies)).cuda()
|
| 357 |
validity = torch.from_numpy(validity_np)[None, None].expand(1, len(ctx), -1, -1).contiguous().cuda()
|
| 358 |
t_norm = torch.tensor(clip['t_norm'], dtype=torch.float64, device='cuda')
|
| 359 |
+
t_norm = (t_norm - t_norm[ctx[0]]) / (t_norm[ctx[-1]] - t_norm[ctx[0]])
|
|
|
|
| 360 |
attention_mask = torch.from_numpy(attention_np)[None, None].expand(1, len(ctx), -1, -1).to(images.device)
|
| 361 |
with precision(**PRECISION), torch.no_grad():
|
| 362 |
rgb, diag, aux = render(model, images, sky, t_norm[ctx], validity, t_norm[targets], targets, ctx,
|
| 363 |
+
motion_head=motion_head if held_out else None,
|
| 364 |
+
seed=clip_seed(clip_id) if held_out else None,
|
| 365 |
+
v_z_tol=v_z_tol, attention_mask=attention_mask)
|
| 366 |
rgb = rgb.clamp(0, 1).float()
|
| 367 |
torch.cuda.synchronize(); seconds = time.perf_counter() - start
|
| 368 |
rgb = rgb.cpu().numpy().astype(np.float32)
|
|
|
|
| 370 |
raise ValueError(f'render {rgb.shape}, finite={np.isfinite(rgb).all()}')
|
| 371 |
depth_np = aux['depth'].float().cpu().numpy(); alpha_np = aux['alpha'].float().cpu().numpy()
|
| 372 |
write_depth_clip(out, clip_id, depth_np, alpha_np, targets)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
clip_out = out / clip_id
|
| 374 |
clip_out.mkdir(parents=True, exist_ok=True)
|
| 375 |
+
np.savez_compressed(clip_out / OBSERVABILITY_FILE, unobserved=aux['unobserved'].cpu().numpy().astype(np.uint8),
|
| 376 |
+
positions=np.asarray(targets), input_positions=np.asarray(ctx))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 377 |
pending.append((clip_id, writer.submit(write_clip, out, clip_id, rgb, targets)))
|
| 378 |
log.write(json.dumps({'clip_id': clip_id, 'seconds': seconds,
|
| 379 |
'peak_vram_gb': torch.cuda.max_memory_allocated() / 1e9,
|
|
|
|
| 405 |
if missing:
|
| 406 |
raise SystemExit(f'{len(missing)} clips without renders, e.g. {missing[:3]}; see runtime.*.jsonl')
|
| 407 |
first = json.loads(next(iter(sorted(out.glob('render.*.json')))).read_text())
|
| 408 |
+
clip = json.loads((inputs / manifest['clips'][0] / 'clip.json').read_text())
|
| 409 |
+
positions = rendered_positions(first['input_frames'] or clip['context_positions'])
|
| 410 |
write_meta(out, manifest['clips'], positions, {'method': 'agt', 'config': first['config']})
|
| 411 |
write_depth_meta(out, manifest['clips'], positions, {'method': 'agt'})
|
| 412 |
print(json.dumps({'out': str(out), 'clips': len(manifest['clips'])}))
|
|
|
|
| 422 |
p.add_argument('--checkpoint-dir', default='checkpoints', help='directory with the released and third-party weights')
|
| 423 |
p.add_argument('--segformer', default='nvidia/segformer-b5-finetuned-cityscapes-1024-1024',
|
| 424 |
help='SegFormer-B5 Cityscapes: Hugging Face id or local directory')
|
| 425 |
+
p.add_argument('--motion-head', help=f'motion head checkpoint (default <checkpoint-dir>/{MOTION_HEAD})')
|
| 426 |
p.add_argument('--masks', choices=('dataset', 'dir', 'images'), default='dataset',
|
| 427 |
help='dataset: predicted masks of the AmodalDrive data root; dir: per-clip npz from tools/make_masks.py; '
|
| 428 |
'images: <mask-dir>/<clip_id>.png (255 = occluder)')
|
| 429 |
p.add_argument('--data-root', help='AmodalDrive data root (--masks dataset)')
|
| 430 |
p.add_argument('--mask-dir')
|
| 431 |
p.add_argument('--mask-dilate', type=int, default=0, help='mask dilation radius in pixels on the 294x518 grid')
|
| 432 |
+
p.add_argument('--input-frames', type=int, nargs='+',
|
| 433 |
+
help='positions of the input frames in the clip (default: context_positions of clip.json); the frames '
|
| 434 |
+
'from the first to the last input are rendered, and the motion head moves the dynamic Gaussians '
|
| 435 |
+
'to the frames between the inputs')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
p.add_argument('--shard', help='i/n: every n-th clip from i (run finalize after all shards)')
|
| 437 |
p.add_argument('--limit', type=int, help='render only the first n clips')
|
| 438 |
args = p.parse_args(argv)
|
| 439 |
if args.config is None:
|
| 440 |
from ..model.build import DEFAULT_CONFIG
|
| 441 |
args.config = DEFAULT_CONFIG
|
|
|
|
|
|
|
| 442 |
if args.step == 'render':
|
| 443 |
run_render(args)
|
| 444 |
else:
|
code/agt/refine/capture.py
CHANGED
|
@@ -39,17 +39,17 @@ def capture(a):
|
|
| 39 |
current['cid'] = c
|
| 40 |
yield c
|
| 41 |
state = {}
|
| 42 |
-
|
| 43 |
|
| 44 |
-
def
|
| 45 |
rep = state.get('rep_images')
|
| 46 |
-
src, diag =
|
| 47 |
if src is None:
|
| 48 |
prev = R.previous_context(ctx, state['positions'])
|
| 49 |
state['dy16'], state['bg16'] = dy[0, prev].float().cpu(), mask[0, prev].cpu()
|
| 50 |
else:
|
| 51 |
state['dy16'], state['bg16'] = src['dy_map'][0].float().cpu(), src['bg_mask'][0].cpu()
|
| 52 |
-
state['
|
| 53 |
return src, diag
|
| 54 |
|
| 55 |
def wrapped(model, images, sky, times, validity, target_times, target_positions, context_positions, **kw):
|
|
@@ -99,19 +99,19 @@ def capture(a):
|
|
| 99 |
finally:
|
| 100 |
runtime.predict, GR.rasterization = orig_pred, orig_ras
|
| 101 |
model.sky_model.forward_with_new_pose = orig_sky
|
| 102 |
-
if kw.get('
|
| 103 |
mask = (sky == 0)[None]
|
| 104 |
prev = R.previous_context(context_positions, target_positions)
|
| 105 |
state['dy16'], state['bg16'] = cap['dy4_used'][prev].float(), mask[0, prev].cpu()
|
| 106 |
-
state['
|
| 107 |
n_static = len(context_positions) * images.shape[-2] * images.shape[-1]
|
| 108 |
for j in range(len(target_positions)):
|
| 109 |
n_dyn = cap['rgb_calls'][j]['opacities'].shape[0] - n_static
|
| 110 |
if n_dyn != int(state['bg16'][j].sum()):
|
| 111 |
raise ValueError(f'{cid} p{j}: dynamic layer size {n_dyn} != source mask {int(state["bg16"][j].sum())}')
|
| 112 |
-
cap.update(gate_v=r[2]['gate_v'].cpu(), rgb_final=r[0].clamp(0, 1).float().cpu(),
|
| 113 |
-
bg16=state['bg16'],
|
| 114 |
-
line = dict(captured=cid, calls=len(cap['rgb_calls']),
|
| 115 |
if a.pass1:
|
| 116 |
with np.load(Path(a.pass1) / cid / 'frames.npz', allow_pickle=False) as h:
|
| 117 |
saved = h['rgb'].astype(np.float32)
|
|
@@ -124,7 +124,7 @@ def capture(a):
|
|
| 124 |
return r
|
| 125 |
if not clips:
|
| 126 |
return
|
| 127 |
-
R._clips, R.render, R.
|
| 128 |
R.run_finalize = lambda args: None
|
| 129 |
shutil.rmtree(rerender, ignore_errors=True)
|
| 130 |
R.main(argv)
|
|
|
|
| 39 |
current['cid'] = c
|
| 40 |
yield c
|
| 41 |
state = {}
|
| 42 |
+
orig_motion, orig_render = R.motion_sources, R.render
|
| 43 |
|
| 44 |
+
def moved(motion_head, ext, k, xyz, gs, dy, conf, mask, images, depth, seed, ctx):
|
| 45 |
rep = state.get('rep_images')
|
| 46 |
+
src, diag = orig_motion(motion_head, ext, k, xyz, gs, dy, conf, mask, images if rep is None else rep, depth, seed, ctx)
|
| 47 |
if src is None:
|
| 48 |
prev = R.previous_context(ctx, state['positions'])
|
| 49 |
state['dy16'], state['bg16'] = dy[0, prev].float().cpu(), mask[0, prev].cpu()
|
| 50 |
else:
|
| 51 |
state['dy16'], state['bg16'] = src['dy_map'][0].float().cpu(), src['bg_mask'][0].cpu()
|
| 52 |
+
state['motion_fallback'] = src is None
|
| 53 |
return src, diag
|
| 54 |
|
| 55 |
def wrapped(model, images, sky, times, validity, target_times, target_positions, context_positions, **kw):
|
|
|
|
| 99 |
finally:
|
| 100 |
runtime.predict, GR.rasterization = orig_pred, orig_ras
|
| 101 |
model.sky_model.forward_with_new_pose = orig_sky
|
| 102 |
+
if kw.get('motion_head') is None:
|
| 103 |
mask = (sky == 0)[None]
|
| 104 |
prev = R.previous_context(context_positions, target_positions)
|
| 105 |
state['dy16'], state['bg16'] = cap['dy4_used'][prev].float(), mask[0, prev].cpu()
|
| 106 |
+
state['motion_fallback'] = True
|
| 107 |
n_static = len(context_positions) * images.shape[-2] * images.shape[-1]
|
| 108 |
for j in range(len(target_positions)):
|
| 109 |
n_dyn = cap['rgb_calls'][j]['opacities'].shape[0] - n_static
|
| 110 |
if n_dyn != int(state['bg16'][j].sum()):
|
| 111 |
raise ValueError(f'{cid} p{j}: dynamic layer size {n_dyn} != source mask {int(state["bg16"][j].sum())}')
|
| 112 |
+
cap.update(gate_v=r[2]['gate_v'].cpu(), unobserved=r[2]['unobserved'].cpu(), rgb_final=r[0].clamp(0, 1).float().cpu(),
|
| 113 |
+
dy16=state['dy16'], bg16=state['bg16'], motion_fallback=state['motion_fallback'])
|
| 114 |
+
line = dict(captured=cid, calls=len(cap['rgb_calls']), motion_fallback=state['motion_fallback'])
|
| 115 |
if a.pass1:
|
| 116 |
with np.load(Path(a.pass1) / cid / 'frames.npz', allow_pickle=False) as h:
|
| 117 |
saved = h['rgb'].astype(np.float32)
|
|
|
|
| 124 |
return r
|
| 125 |
if not clips:
|
| 126 |
return
|
| 127 |
+
R._clips, R.render, R.motion_sources = walk, wrapped, moved
|
| 128 |
R.run_finalize = lambda args: None
|
| 129 |
shutil.rmtree(rerender, ignore_errors=True)
|
| 130 |
R.main(argv)
|
code/agt/refine/refine.py
CHANGED
|
@@ -8,7 +8,6 @@ from pathlib import Path
|
|
| 8 |
import numpy as np
|
| 9 |
|
| 10 |
from ..completion.handoff import load_handoff, write_handoff
|
| 11 |
-
from ..completion.reliability import load_repair_mask
|
| 12 |
from .losses import frame_loss, make_lpips
|
| 13 |
from .scene import SOURCE, FrameScene, frozen_check, logit, zero_step
|
| 14 |
|
|
@@ -23,39 +22,12 @@ def write_json(path, value):
|
|
| 23 |
tmp.replace(path)
|
| 24 |
|
| 25 |
|
| 26 |
-
def
|
| 27 |
-
from scipy.ndimage import distance_transform_edt
|
| 28 |
-
mask = np.asarray(mask, bool)
|
| 29 |
-
d = distance_transform_edt(~mask) if mask.any() else np.full(mask.shape, np.inf)
|
| 30 |
-
w = np.where(mask, 1., np.where(d < band, 1 - (1 - w_min) * d / band, w_min))
|
| 31 |
-
return w, d
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def weight_groups(w, mask, d, band, w_min, n_groups):
|
| 35 |
-
mask = np.asarray(mask, bool)
|
| 36 |
-
k = 1 + np.floor((w - w_min) / (1 - w_min) * (n_groups - 2)).astype(np.int64)
|
| 37 |
-
g = np.clip(k, 1, n_groups - 2)
|
| 38 |
-
g = np.where(d >= band, 0, g)
|
| 39 |
-
return np.where(mask, n_groups - 1, g)
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
def group_lr(w, groups, n_groups):
|
| 43 |
-
w, groups = np.asarray(w).ravel(), np.asarray(groups).ravel()
|
| 44 |
-
return [float(w[groups == k].mean()) if (groups == k).any() else None for k in range(n_groups)]
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
def optimize(scene, targets, masks, supervised, cfg, lpips_fn, theta_init, color_init, groups, lr_mult):
|
| 48 |
import torch
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
cols = [color_init[s].clone().requires_grad_(True) for _, s in sels]
|
| 54 |
-
pg = []
|
| 55 |
-
for (k, _), th, co in zip(sels, thetas, cols):
|
| 56 |
-
pg += [dict(params=[th], lr=cfg['lr_opacity'] * lr_mult[k]), dict(params=[co], lr=cfg['lr_color'] * lr_mult[k])]
|
| 57 |
-
opt = torch.optim.Adam(pg, eps=cfg['eps'])
|
| 58 |
-
full = lambda xs: torch.cat(xs)[inv]
|
| 59 |
sup = set(supervised)
|
| 60 |
n = len(scene.calls)
|
| 61 |
losses = []
|
|
@@ -63,19 +35,17 @@ def optimize(scene, targets, masks, supervised, cfg, lpips_fn, theta_init, color
|
|
| 63 |
opt.zero_grad(set_to_none=True)
|
| 64 |
total = 0.
|
| 65 |
for j in range(n):
|
| 66 |
-
out, _, _ = scene.render(j,
|
| 67 |
loss, _ = frame_loss(out, targets[j], masks[j], j in sup, lpips_fn, cfg['w_lpips'])
|
| 68 |
(loss / n).backward()
|
| 69 |
total += float(loss.detach()) / n
|
| 70 |
opt.step()
|
| 71 |
losses.append(total)
|
| 72 |
-
|
| 73 |
-
return full(cols).detach(), full(thetas).detach(), losses
|
| 74 |
|
| 75 |
|
| 76 |
def load_cfg(path):
|
| 77 |
-
|
| 78 |
-
return dict(cfg['optimizer'], tau=cfg['tau'], **cfg['boundary_band'])
|
| 79 |
|
| 80 |
|
| 81 |
def run_clip(cid, a, cfg, lpips_fn, device):
|
|
@@ -84,40 +54,37 @@ def run_clip(cid, a, cfg, lpips_fn, device):
|
|
| 84 |
cap = torch.load(Path(a.capture) / f'{cid}.pt', map_location='cpu', weights_only=False)
|
| 85 |
target0, hmask, _ = load_handoff(Path(a.handoff) / f'{cid}.npz', [SOURCE])
|
| 86 |
target0, hmask = target0[0], hmask[0]
|
| 87 |
-
|
| 88 |
-
if not np.array_equal(
|
| 89 |
-
raise ValueError(f'{cid}: hand-off mask !=
|
| 90 |
scene = FrameScene(cap, device)
|
| 91 |
context = scene.context
|
| 92 |
-
w, d = band_weights(hmask, cfg['band_px'], cfg['w_min'])
|
| 93 |
-
groups = weight_groups(w, hmask, d, cfg['band_px'], cfg['w_min'], cfg['n_groups'])
|
| 94 |
-
lr_mult = group_lr(w, groups, cfg['n_groups'])
|
| 95 |
is_u = scene.is_u
|
| 96 |
captured_u = max(float(c['opacities'][scene.touched(j).cpu()][is_u[scene.param[j]].cpu()].max())
|
| 97 |
if is_u[scene.param[j]].any() else 0. for j, c in enumerate(cap['rgb_calls']))
|
| 98 |
z = zero_step(scene, cap)
|
| 99 |
-
diag = dict(clip_id=cid, n_open=scene.hw, n_U=int(is_u.sum()),
|
| 100 |
-
|
| 101 |
-
captured_U_opacity_max=captured_u, zero_step=z)
|
| 102 |
if z['rgb_max_abs'] != 0 or z['merged_colors_max_abs'] != 0 or z['merged_opacities_max_abs'] != 0 or captured_u != 0:
|
| 103 |
write_json(work / 'diag' / f'{cid}.json', diag)
|
| 104 |
raise RuntimeError(f'{cid}: zero-step check failed {z}, captured U opacity {captured_u}')
|
| 105 |
targets = cap['rgb_final'].numpy().copy(); targets[SOURCE] = target0
|
| 106 |
targets = torch.from_numpy(targets).to(device)
|
| 107 |
-
masks = torch.from_numpy(
|
| 108 |
tgt = torch.from_numpy(target0).to(device).reshape(-1, 3)
|
| 109 |
color_init = torch.where(is_u[:, None], tgt, scene.head_colors())
|
| 110 |
theta_init = torch.where(is_u, torch.full_like(scene.theta0, logit(cfg['opacity_init'])), scene.theta0)
|
| 111 |
start = time.perf_counter()
|
| 112 |
-
colors, theta, losses = optimize(scene, targets, masks, [SOURCE], cfg, lpips_fn, theta_init, color_init
|
| 113 |
seconds = time.perf_counter() - start
|
| 114 |
fz = frozen_check(scene, cap['rgb_calls'], colors, theta)
|
| 115 |
if not fz['ok']:
|
| 116 |
raise RuntimeError(f'{cid}: frozen check failed {fz}')
|
|
|
|
| 117 |
with torch.no_grad():
|
| 118 |
-
views = [scene.render(j, colors, theta)[0].clamp(0, 1).float().cpu().numpy() for j in
|
| 119 |
-
write_handoff(work / 'views' / f'{cid}.npz', np.stack(views),
|
| 120 |
-
dict(clip_id=cid, content='renders of the input frames after scene optimization'
|
| 121 |
(work / 'params').mkdir(parents=True, exist_ok=True)
|
| 122 |
torch.save(dict(colors=colors.cpu(), theta=theta.cpu(), den=scene.den.cpu(), is_u=is_u.cpu()), work / 'params' / f'{cid}.pt')
|
| 123 |
diag.update(seconds=seconds, frozen=fz, loss_first=losses[0], loss_last=losses[-1])
|
|
@@ -125,37 +92,55 @@ def run_clip(cid, a, cfg, lpips_fn, device):
|
|
| 125 |
print(json.dumps(dict(clip=cid, seconds=round(seconds, 1), loss_first=losses[0], loss_last=losses[-1], n_U=diag['n_U'])), flush=True)
|
| 126 |
|
| 127 |
|
| 128 |
-
def transplant_render(cap, pr, device,
|
| 129 |
import torch
|
| 130 |
scene = FrameScene(cap, device, den=pr['den'])
|
| 131 |
if not torch.equal(scene.is_u.cpu(), pr['is_u']):
|
| 132 |
-
raise ValueError('
|
| 133 |
colors, theta = pr['colors'].to(device), pr['theta'].to(device)
|
| 134 |
with torch.no_grad():
|
| 135 |
-
frames = [scene.render(j, colors, theta)[0].clamp(0, 1).float().cpu().numpy() for j in
|
| 136 |
return np.stack(frames), scene, colors, theta
|
| 137 |
|
| 138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
def final_clip(cid, a, device):
|
| 140 |
import torch
|
| 141 |
-
from ..recon.outputs import write_clip
|
| 142 |
work = Path(a.work)
|
| 143 |
pr = torch.load(work / 'params' / f'{cid}.pt', map_location='cpu', weights_only=False)
|
| 144 |
cap = torch.load(Path(a.capture) / f'{cid}.pt', map_location='cpu', weights_only=False)
|
| 145 |
positions = list(cap['positions'])
|
| 146 |
-
frames, scene, colors, theta = transplant_render(cap, pr, device, positions)
|
|
|
|
| 147 |
fz = frozen_check(scene, cap['rgb_calls'], colors, theta)
|
| 148 |
if not fz['ok']:
|
| 149 |
raise RuntimeError(f'{cid}: frozen check (final) failed {fz}')
|
| 150 |
-
line = dict(final=cid,
|
| 151 |
if a.check_capture:
|
| 152 |
cap0 = torch.load(Path(a.check_capture) / f'{cid}.pt', map_location='cpu', weights_only=False)
|
| 153 |
-
views, _, _, _ = transplant_render(cap0, pr, device, cap0['context_positions'])
|
| 154 |
with np.load(work / 'views' / f'{cid}.npz', allow_pickle=False) as h:
|
| 155 |
ref = h['rgb']
|
| 156 |
line['transplant_bitwise'] = bool(views.tobytes() == ref.astype(np.float32).tobytes())
|
| 157 |
if not line['transplant_bitwise']:
|
| 158 |
raise RuntimeError(f'{cid}: transplant check failed, max abs {float(np.abs(views - ref).max())}')
|
|
|
|
| 159 |
write_clip(a.out, cid, frames, positions=positions)
|
| 160 |
print(json.dumps(line), flush=True)
|
| 161 |
return positions
|
|
@@ -171,11 +156,10 @@ def main(argv=None):
|
|
| 171 |
s = sub.add_parser('run', help='scene optimization on the first capture; writes the input-frame renders')
|
| 172 |
s.add_argument('--capture', required=True, help='capture of the first pass')
|
| 173 |
s.add_argument('--handoff', required=True, help='output of the generative completion (agt.completion.flux_fill)')
|
| 174 |
-
s.add_argument('--rel', required=True, help='reliability maps')
|
| 175 |
s.add_argument('--work', required=True, help='refinement directory (views/, params/, diag/)')
|
| 176 |
s.add_argument('--config', default=str(CONFIG))
|
| 177 |
s.add_argument('--clips', nargs='+')
|
| 178 |
-
s = sub.add_parser('final', help='apply the optimized Gaussians to the second capture and render')
|
| 179 |
s.add_argument('--capture', required=True, help='capture with --repaired <work>/views')
|
| 180 |
s.add_argument('--work', required=True)
|
| 181 |
s.add_argument('--out', required=True, help='final render directory')
|
|
@@ -189,12 +173,13 @@ def main(argv=None):
|
|
| 189 |
for cid in _clips(a):
|
| 190 |
run_clip(cid, a, cfg, lpips_fn, device)
|
| 191 |
else:
|
| 192 |
-
from ..recon.outputs import write_meta
|
| 193 |
positions = None
|
| 194 |
for cid in _clips(a):
|
| 195 |
positions = final_clip(cid, a, 'cuda')
|
| 196 |
done = sorted(d.name for d in Path(a.out).iterdir() if (d / 'frames.npz').is_file())
|
| 197 |
write_meta(a.out, done, positions, {'method': 'agt'})
|
|
|
|
| 198 |
|
| 199 |
|
| 200 |
if __name__ == '__main__':
|
|
|
|
| 8 |
import numpy as np
|
| 9 |
|
| 10 |
from ..completion.handoff import load_handoff, write_handoff
|
|
|
|
| 11 |
from .losses import frame_loss, make_lpips
|
| 12 |
from .scene import SOURCE, FrameScene, frozen_check, logit, zero_step
|
| 13 |
|
|
|
|
| 22 |
tmp.replace(path)
|
| 23 |
|
| 24 |
|
| 25 |
+
def optimize(scene, targets, masks, supervised, cfg, lpips_fn, theta_init, color_init):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
import torch
|
| 27 |
+
theta = theta_init.clone().requires_grad_(True)
|
| 28 |
+
colors = color_init.clone().requires_grad_(True)
|
| 29 |
+
opt = torch.optim.Adam([dict(params=[theta], lr=cfg['lr_opacity']), dict(params=[colors], lr=cfg['lr_color'])],
|
| 30 |
+
eps=cfg['eps'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
sup = set(supervised)
|
| 32 |
n = len(scene.calls)
|
| 33 |
losses = []
|
|
|
|
| 35 |
opt.zero_grad(set_to_none=True)
|
| 36 |
total = 0.
|
| 37 |
for j in range(n):
|
| 38 |
+
out, _, _ = scene.render(j, colors, theta)
|
| 39 |
loss, _ = frame_loss(out, targets[j], masks[j], j in sup, lpips_fn, cfg['w_lpips'])
|
| 40 |
(loss / n).backward()
|
| 41 |
total += float(loss.detach()) / n
|
| 42 |
opt.step()
|
| 43 |
losses.append(total)
|
| 44 |
+
return colors.detach(), theta.detach(), losses
|
|
|
|
| 45 |
|
| 46 |
|
| 47 |
def load_cfg(path):
|
| 48 |
+
return json.loads(Path(path).read_text())['optimizer']
|
|
|
|
| 49 |
|
| 50 |
|
| 51 |
def run_clip(cid, a, cfg, lpips_fn, device):
|
|
|
|
| 54 |
cap = torch.load(Path(a.capture) / f'{cid}.pt', map_location='cpu', weights_only=False)
|
| 55 |
target0, hmask, _ = load_handoff(Path(a.handoff) / f'{cid}.npz', [SOURCE])
|
| 56 |
target0, hmask = target0[0], hmask[0]
|
| 57 |
+
unobserved = cap['unobserved'].numpy().astype(bool)
|
| 58 |
+
if not np.array_equal(unobserved[SOURCE], hmask):
|
| 59 |
+
raise ValueError(f'{cid}: hand-off mask != unobserved region of the first input frame')
|
| 60 |
scene = FrameScene(cap, device)
|
| 61 |
context = scene.context
|
|
|
|
|
|
|
|
|
|
| 62 |
is_u = scene.is_u
|
| 63 |
captured_u = max(float(c['opacities'][scene.touched(j).cpu()][is_u[scene.param[j]].cpu()].max())
|
| 64 |
if is_u[scene.param[j]].any() else 0. for j, c in enumerate(cap['rgb_calls']))
|
| 65 |
z = zero_step(scene, cap)
|
| 66 |
+
diag = dict(clip_id=cid, n_open=scene.hw, n_U=int(is_u.sum()), unobserved_pixels=[int(u.sum()) for u in unobserved],
|
| 67 |
+
motion_fallback=cap['motion_fallback'], captured_U_opacity_max=captured_u, zero_step=z)
|
|
|
|
| 68 |
if z['rgb_max_abs'] != 0 or z['merged_colors_max_abs'] != 0 or z['merged_opacities_max_abs'] != 0 or captured_u != 0:
|
| 69 |
write_json(work / 'diag' / f'{cid}.json', diag)
|
| 70 |
raise RuntimeError(f'{cid}: zero-step check failed {z}, captured U opacity {captured_u}')
|
| 71 |
targets = cap['rgb_final'].numpy().copy(); targets[SOURCE] = target0
|
| 72 |
targets = torch.from_numpy(targets).to(device)
|
| 73 |
+
masks = torch.from_numpy(unobserved).to(device)
|
| 74 |
tgt = torch.from_numpy(target0).to(device).reshape(-1, 3)
|
| 75 |
color_init = torch.where(is_u[:, None], tgt, scene.head_colors())
|
| 76 |
theta_init = torch.where(is_u, torch.full_like(scene.theta0, logit(cfg['opacity_init'])), scene.theta0)
|
| 77 |
start = time.perf_counter()
|
| 78 |
+
colors, theta, losses = optimize(scene, targets, masks, [SOURCE], cfg, lpips_fn, theta_init, color_init)
|
| 79 |
seconds = time.perf_counter() - start
|
| 80 |
fz = frozen_check(scene, cap['rgb_calls'], colors, theta)
|
| 81 |
if not fz['ok']:
|
| 82 |
raise RuntimeError(f'{cid}: frozen check failed {fz}')
|
| 83 |
+
inputs = [scene.positions.index(c) for c in context]
|
| 84 |
with torch.no_grad():
|
| 85 |
+
views = [scene.render(j, colors, theta)[0].clamp(0, 1).float().cpu().numpy() for j in inputs]
|
| 86 |
+
write_handoff(work / 'views' / f'{cid}.npz', np.stack(views), unobserved[inputs], context,
|
| 87 |
+
dict(clip_id=cid, content='renders of the input frames after scene optimization'))
|
| 88 |
(work / 'params').mkdir(parents=True, exist_ok=True)
|
| 89 |
torch.save(dict(colors=colors.cpu(), theta=theta.cpu(), den=scene.den.cpu(), is_u=is_u.cpu()), work / 'params' / f'{cid}.pt')
|
| 90 |
diag.update(seconds=seconds, frozen=fz, loss_first=losses[0], loss_last=losses[-1])
|
|
|
|
| 92 |
print(json.dumps(dict(clip=cid, seconds=round(seconds, 1), loss_first=losses[0], loss_last=losses[-1], n_U=diag['n_U'])), flush=True)
|
| 93 |
|
| 94 |
|
| 95 |
+
def transplant_render(cap, pr, device, indices):
|
| 96 |
import torch
|
| 97 |
scene = FrameScene(cap, device, den=pr['den'])
|
| 98 |
if not torch.equal(scene.is_u.cpu(), pr['is_u']):
|
| 99 |
+
raise ValueError('unobserved Gaussians of the first input frame differ between the refined capture and this capture')
|
| 100 |
colors, theta = pr['colors'].to(device), pr['theta'].to(device)
|
| 101 |
with torch.no_grad():
|
| 102 |
+
frames = [scene.render(j, colors, theta)[0].clamp(0, 1).float().cpu().numpy() for j in indices]
|
| 103 |
return np.stack(frames), scene, colors, theta
|
| 104 |
|
| 105 |
|
| 106 |
+
def transplant_depth(scene, colors, theta, indices):
|
| 107 |
+
import torch
|
| 108 |
+
from gsplat.rendering import rasterization
|
| 109 |
+
depths, alphas = [], []
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
for j in indices:
|
| 112 |
+
c, o = scene.merged(j, colors, theta)
|
| 113 |
+
call = scene.calls[j]
|
| 114 |
+
kw = dict(means=call['means'], quats=call['quats'], scales=call['scales'], opacities=o, colors=c,
|
| 115 |
+
viewmats=call['viewmats'], Ks=call['Ks'], width=scene.width, height=scene.height)
|
| 116 |
+
_, a, _ = rasterization(**kw)
|
| 117 |
+
ed, _, _ = rasterization(**kw, render_mode='ED')
|
| 118 |
+
depths.append(ed[0, ..., 0].float().cpu().numpy()); alphas.append(a[0, ..., 0].float().cpu().numpy())
|
| 119 |
+
return np.stack(depths), np.stack(alphas)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
def final_clip(cid, a, device):
|
| 123 |
import torch
|
| 124 |
+
from ..recon.outputs import write_clip, write_depth_clip
|
| 125 |
work = Path(a.work)
|
| 126 |
pr = torch.load(work / 'params' / f'{cid}.pt', map_location='cpu', weights_only=False)
|
| 127 |
cap = torch.load(Path(a.capture) / f'{cid}.pt', map_location='cpu', weights_only=False)
|
| 128 |
positions = list(cap['positions'])
|
| 129 |
+
frames, scene, colors, theta = transplant_render(cap, pr, device, range(len(positions)))
|
| 130 |
+
depth, alpha = transplant_depth(scene, colors, theta, range(len(positions)))
|
| 131 |
fz = frozen_check(scene, cap['rgb_calls'], colors, theta)
|
| 132 |
if not fz['ok']:
|
| 133 |
raise RuntimeError(f'{cid}: frozen check (final) failed {fz}')
|
| 134 |
+
line = dict(final=cid, motion_fallback=cap['motion_fallback'])
|
| 135 |
if a.check_capture:
|
| 136 |
cap0 = torch.load(Path(a.check_capture) / f'{cid}.pt', map_location='cpu', weights_only=False)
|
| 137 |
+
views, _, _, _ = transplant_render(cap0, pr, device, [cap0['positions'].index(c) for c in cap0['context_positions']])
|
| 138 |
with np.load(work / 'views' / f'{cid}.npz', allow_pickle=False) as h:
|
| 139 |
ref = h['rgb']
|
| 140 |
line['transplant_bitwise'] = bool(views.tobytes() == ref.astype(np.float32).tobytes())
|
| 141 |
if not line['transplant_bitwise']:
|
| 142 |
raise RuntimeError(f'{cid}: transplant check failed, max abs {float(np.abs(views - ref).max())}')
|
| 143 |
+
write_depth_clip(a.out, cid, depth, alpha, positions=positions)
|
| 144 |
write_clip(a.out, cid, frames, positions=positions)
|
| 145 |
print(json.dumps(line), flush=True)
|
| 146 |
return positions
|
|
|
|
| 156 |
s = sub.add_parser('run', help='scene optimization on the first capture; writes the input-frame renders')
|
| 157 |
s.add_argument('--capture', required=True, help='capture of the first pass')
|
| 158 |
s.add_argument('--handoff', required=True, help='output of the generative completion (agt.completion.flux_fill)')
|
|
|
|
| 159 |
s.add_argument('--work', required=True, help='refinement directory (views/, params/, diag/)')
|
| 160 |
s.add_argument('--config', default=str(CONFIG))
|
| 161 |
s.add_argument('--clips', nargs='+')
|
| 162 |
+
s = sub.add_parser('final', help='apply the optimized Gaussians to the second capture and render colour and depth')
|
| 163 |
s.add_argument('--capture', required=True, help='capture with --repaired <work>/views')
|
| 164 |
s.add_argument('--work', required=True)
|
| 165 |
s.add_argument('--out', required=True, help='final render directory')
|
|
|
|
| 173 |
for cid in _clips(a):
|
| 174 |
run_clip(cid, a, cfg, lpips_fn, device)
|
| 175 |
else:
|
| 176 |
+
from ..recon.outputs import write_depth_meta, write_meta
|
| 177 |
positions = None
|
| 178 |
for cid in _clips(a):
|
| 179 |
positions = final_clip(cid, a, 'cuda')
|
| 180 |
done = sorted(d.name for d in Path(a.out).iterdir() if (d / 'frames.npz').is_file())
|
| 181 |
write_meta(a.out, done, positions, {'method': 'agt'})
|
| 182 |
+
write_depth_meta(a.out, done, positions, {'method': 'agt'})
|
| 183 |
|
| 184 |
|
| 185 |
if __name__ == '__main__':
|
code/configs/completion.json
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
{
|
| 2 |
-
"tau": 0.1,
|
| 3 |
"position": 0,
|
| 4 |
"base_model": "black-forest-labs/FLUX.1-Fill-dev",
|
| 5 |
"base_revision": "358293da0354175698b67ec8299acf928313a78a",
|
|
|
|
| 1 |
{
|
|
|
|
| 2 |
"position": 0,
|
| 3 |
"base_model": "black-forest-labs/FLUX.1-Fill-dev",
|
| 4 |
"base_revision": "358293da0354175698b67ec8299acf928313a78a",
|
code/configs/eval/test_waymo.json
CHANGED
|
@@ -9,9 +9,7 @@
|
|
| 9 |
"map_version": "v2",
|
| 10 |
"scoring_mask": "ground_truth",
|
| 11 |
"visibility": "gt_visibility_v2",
|
| 12 |
-
"
|
| 13 |
-
"hole_metrics": ["lpips", "dists", "kid", "fid"],
|
| 14 |
-
"void_width": 3,
|
| 15 |
"min_pixels": 49,
|
| 16 |
"depth_alpha_eps": 0.001,
|
| 17 |
"device": "cuda"
|
|
|
|
| 9 |
"map_version": "v2",
|
| 10 |
"scoring_mask": "ground_truth",
|
| 11 |
"visibility": "gt_visibility_v2",
|
| 12 |
+
"boundary_width": 3,
|
|
|
|
|
|
|
| 13 |
"min_pixels": 49,
|
| 14 |
"depth_alpha_eps": 0.001,
|
| 15 |
"device": "cuda"
|
code/configs/eval/val_waymo.json
CHANGED
|
@@ -9,9 +9,7 @@
|
|
| 9 |
"map_version": "v2",
|
| 10 |
"scoring_mask": "ground_truth",
|
| 11 |
"visibility": "gt_visibility_v2",
|
| 12 |
-
"
|
| 13 |
-
"hole_metrics": ["lpips", "dists", "kid"],
|
| 14 |
-
"void_width": 3,
|
| 15 |
"min_pixels": 49,
|
| 16 |
"depth_alpha_eps": 0.001,
|
| 17 |
"device": "cuda"
|
|
|
|
| 9 |
"map_version": "v2",
|
| 10 |
"scoring_mask": "ground_truth",
|
| 11 |
"visibility": "gt_visibility_v2",
|
| 12 |
+
"boundary_width": 3,
|
|
|
|
|
|
|
| 13 |
"min_pixels": 49,
|
| 14 |
"depth_alpha_eps": 0.001,
|
| 15 |
"device": "cuda"
|
code/configs/masks/occluder_v1.yaml
CHANGED
|
@@ -34,12 +34,6 @@ sam3:
|
|
| 34 |
- {phrase: card on the dashboard, role: object}
|
| 35 |
- {phrase: sticker on the windshield, role: object}
|
| 36 |
- {phrase: cloth on the dashboard, role: object}
|
| 37 |
-
- {phrase: watermark, role: object}
|
| 38 |
-
- {phrase: logo in the corner of the video, role: object}
|
| 39 |
-
- {phrase: TV channel logo, role: object}
|
| 40 |
-
- {phrase: timestamp text overlay, role: object}
|
| 41 |
-
- {phrase: on-screen text, role: object}
|
| 42 |
-
- {phrase: subtitle banner, role: object}
|
| 43 |
|
| 44 |
verify:
|
| 45 |
verifier: qwen
|
|
|
|
| 34 |
- {phrase: card on the dashboard, role: object}
|
| 35 |
- {phrase: sticker on the windshield, role: object}
|
| 36 |
- {phrase: cloth on the dashboard, role: object}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
verify:
|
| 39 |
verifier: qwen
|
code/configs/masks/verify_prompt.md
CHANGED
|
@@ -1,11 +1,9 @@
|
|
| 1 |
-
You are the candidate-region verifier for
|
| 2 |
|
| 3 |
The first attachment is the original, unannotated RGB source frame; use it to understand the whole scene. The remaining attachments are candidate sheets with at most 6 cells each, one cell per candidate. A cell's header gives the candidate number (written like #0, #1, ...), the phrase that proposed it together with its segmentation score, the position of its centre within the frame, and whether it touches the bottom edge of the frame. The left part of the cell is a thumbnail of the whole frame in which only that candidate is tinted and boxed, so you can see where it sits. The right part is an enlarged view of the candidate's surroundings with the candidate outlined and lightly tinted. The phrase and the score are only bookkeeping from the proposal stage, not conclusions; judge independently.
|
| 4 |
|
| 5 |
-
Task: for every candidate number, decide whether it is a
|
| 6 |
|
| 7 |
-
|
| 8 |
|
| 9 |
-
For
|
| 10 |
-
|
| 11 |
-
For every candidate give: opaque_hard (yes / no / uncertain), category (one of dashboard, hood, pillar, mirror, ornament, device, wiper, paper, cloth, visor, overlay, other; for no or uncertain still give the closest category or other), and reason (one sentence naming the visual evidence). The candidate numbers must match the attachments exactly, each number exactly once, none added or dropped. Do not output points, boxes or any pixel coordinates.
|
|
|
|
| 1 |
+
You are the candidate-region verifier for dashcam templates. Look only at the attached images and return the requested JSON. Do not read other files, do not run segmentation, and never output coordinates.
|
| 2 |
|
| 3 |
The first attachment is the original, unannotated RGB source frame; use it to understand the whole scene. The remaining attachments are candidate sheets with at most 6 cells each, one cell per candidate. A cell's header gives the candidate number (written like #0, #1, ...), the phrase that proposed it together with its segmentation score, the position of its centre within the frame, and whether it touches the bottom edge of the frame. The left part of the cell is a thumbnail of the whole frame in which only that candidate is tinted and boxed, so you can see where it sits. The right part is an enlarged view of the candidate's surroundings with the candidate outlined and lightly tinted. The phrase and the score are only bookkeeping from the proposal stage, not conclusions; judge independently.
|
| 4 |
|
| 5 |
+
Task: for every candidate number, decide whether it is a physically opaque part of the ego car, or a physical object attached to the ego car, that is, something that fully hides the background in a real driving video and does not change with the scene outside. Examples that qualify: the dashboard, the visible hood of the ego car, A-pillars and the roof lining, the rearview mirror, ornaments fixed on the dashboard or the windshield, devices and mounts, tissue boxes, cards and tickets, cloth, a resting wiper arm, sun visors. Examples that do not qualify: the road, the sky, other vehicles, pedestrians, trees and buildings, reflections or glare on the windshield (for example the dashboard mirrored in the glass, or a translucent ghost image), the fine dotted sun-shade band at the top of the windshield, and any region that only covers the see-through part of the glass.
|
| 6 |
|
| 7 |
+
Judge from the image content itself: is the thing inside the car, does it have solid edges and thickness, is it occluded by anything outside the car (nothing outside the car can occlude an object inside it), does it look translucent and superimposed on the outside scene like a reflection. The ego hood and dashboard are cut off by the bottom edge of the frame and span most of the frame width; no wheels, lights or windows are visible on them. Other vehicles are surrounded by road, show wheels, lights, plates or windows, and sit higher and farther away in the frame; their hoods are not parts of the ego car, answer no. If a candidate outline covers both a real object and a large see-through or reflective area of the glass, answer no or uncertain and say in the reason what it mixes in. Do not call something an object merely because it looks stationary. Do not guess; when evidence is insufficient, answer uncertain.
|
| 8 |
|
| 9 |
+
For every candidate give: opaque_hard (yes / no / uncertain), category (one of dashboard, hood, pillar, mirror, ornament, device, wiper, paper, cloth, visor, other; for no or uncertain still give the closest category or other), and reason (one sentence naming the visual evidence). The candidate numbers must match the attachments exactly, each number exactly once, none added or dropped. Do not output points, boxes or any pixel coordinates.
|
|
|
|
|
|
code/configs/masks/verify_schema.json
CHANGED
|
@@ -15,7 +15,7 @@
|
|
| 15 |
"properties": {
|
| 16 |
"candidate_id": {"type": "integer", "minimum": 0},
|
| 17 |
"opaque_hard": {"type": "string", "enum": ["yes", "no", "uncertain"]},
|
| 18 |
-
"category": {"type": "string", "enum": ["dashboard", "hood", "pillar", "mirror", "ornament", "device", "wiper", "paper", "cloth", "visor", "
|
| 19 |
"reason": {"type": "string", "minLength": 1}
|
| 20 |
},
|
| 21 |
"required": ["candidate_id", "opaque_hard", "category", "reason"]
|
|
|
|
| 15 |
"properties": {
|
| 16 |
"candidate_id": {"type": "integer", "minimum": 0},
|
| 17 |
"opaque_hard": {"type": "string", "enum": ["yes", "no", "uncertain"]},
|
| 18 |
+
"category": {"type": "string", "enum": ["dashboard", "hood", "pillar", "mirror", "ornament", "device", "wiper", "paper", "cloth", "visor", "other"]},
|
| 19 |
"reason": {"type": "string", "minLength": 1}
|
| 20 |
},
|
| 21 |
"required": ["candidate_id", "opaque_hard", "category", "reason"]
|
code/configs/model.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
"img_size": 518,
|
| 3 |
"patch_size": 14,
|
| 4 |
"embed_dim": 1024,
|
| 5 |
-
"removed_heads": ["point_head", "semantic_head"
|
| 6 |
"visibility_gating": true,
|
| 7 |
"visibility_depth_tolerance": 0.05,
|
| 8 |
"scale_cap": 0.3,
|
|
|
|
| 2 |
"img_size": 518,
|
| 3 |
"patch_size": 14,
|
| 4 |
"embed_dim": 1024,
|
| 5 |
+
"removed_heads": ["point_head", "semantic_head"],
|
| 6 |
"visibility_gating": true,
|
| 7 |
"visibility_depth_tolerance": 0.05,
|
| 8 |
"scale_cap": 0.3,
|
code/configs/refinement.json
CHANGED
|
@@ -1,10 +1,4 @@
|
|
| 1 |
{
|
| 2 |
-
"tau": 0.1,
|
| 3 |
-
"boundary_band": {
|
| 4 |
-
"band_px": 20,
|
| 5 |
-
"w_min": 0.02,
|
| 6 |
-
"n_groups": 16
|
| 7 |
-
},
|
| 8 |
"optimizer": {
|
| 9 |
"name": "Adam",
|
| 10 |
"eps": 1e-15,
|
|
|
|
| 1 |
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
"optimizer": {
|
| 3 |
"name": "Adam",
|
| 4 |
"eps": 1e-15,
|
code/eval/score.py
CHANGED
|
@@ -6,7 +6,7 @@ import sys
|
|
| 6 |
REPO = Path(__file__).resolve().parents[1]
|
| 7 |
sys.path.insert(0, str(REPO))
|
| 8 |
|
| 9 |
-
from agt.eval.scorer import
|
| 10 |
|
| 11 |
PATH_KEYS = ('data_root', 'export', 'method', 'out')
|
| 12 |
|
|
@@ -16,9 +16,8 @@ def main(argv=None):
|
|
| 16 |
parser.add_argument('--config', type=Path, required=True)
|
| 17 |
parser.add_argument('--data-root', dest='data_root')
|
| 18 |
parser.add_argument('--export', help='exported clip set (manifest.json + <clip>/clip.json)')
|
| 19 |
-
parser.add_argument('--method', help='method directory (meta.json + <clip>/frames.npz, ..
|
| 20 |
parser.add_argument('--out')
|
| 21 |
-
parser.add_argument('--tables', nargs='+', choices=ALL_TABLES)
|
| 22 |
parser.add_argument('--device', choices=('cpu', 'cuda'))
|
| 23 |
parser.add_argument('--clips', nargs='+', help='score only these clip ids')
|
| 24 |
args = parser.parse_args(argv)
|
|
@@ -26,14 +25,14 @@ def main(argv=None):
|
|
| 26 |
for key in PATH_KEYS:
|
| 27 |
if config.get(key) is not None and not Path(config[key]).is_absolute():
|
| 28 |
config[key] = str(REPO / config[key])
|
| 29 |
-
for key in (*PATH_KEYS, '
|
| 30 |
if getattr(args, key) is not None:
|
| 31 |
config[key] = getattr(args, key)
|
| 32 |
missing = [k for k in PATH_KEYS if not config.get(k)]
|
| 33 |
if missing:
|
| 34 |
parser.error('missing ' + ', '.join(missing))
|
| 35 |
result = score(config)
|
| 36 |
-
print(json.dumps(result['
|
| 37 |
|
| 38 |
|
| 39 |
if __name__ == '__main__':
|
|
|
|
| 6 |
REPO = Path(__file__).resolve().parents[1]
|
| 7 |
sys.path.insert(0, str(REPO))
|
| 8 |
|
| 9 |
+
from agt.eval.scorer import score
|
| 10 |
|
| 11 |
PATH_KEYS = ('data_root', 'export', 'method', 'out')
|
| 12 |
|
|
|
|
| 16 |
parser.add_argument('--config', type=Path, required=True)
|
| 17 |
parser.add_argument('--data-root', dest='data_root')
|
| 18 |
parser.add_argument('--export', help='exported clip set (manifest.json + <clip>/clip.json)')
|
| 19 |
+
parser.add_argument('--method', help='method directory (meta.json + <clip>/frames.npz, optional depth_meta.json + <clip>/depth.npz)')
|
| 20 |
parser.add_argument('--out')
|
|
|
|
| 21 |
parser.add_argument('--device', choices=('cpu', 'cuda'))
|
| 22 |
parser.add_argument('--clips', nargs='+', help='score only these clip ids')
|
| 23 |
args = parser.parse_args(argv)
|
|
|
|
| 25 |
for key in PATH_KEYS:
|
| 26 |
if config.get(key) is not None and not Path(config[key]).is_absolute():
|
| 27 |
config[key] = str(REPO / config[key])
|
| 28 |
+
for key in (*PATH_KEYS, 'device', 'clips'):
|
| 29 |
if getattr(args, key) is not None:
|
| 30 |
config[key] = getattr(args, key)
|
| 31 |
missing = [k for k in PATH_KEYS if not config.get(k)]
|
| 32 |
if missing:
|
| 33 |
parser.error('missing ' + ', '.join(missing))
|
| 34 |
result = score(config)
|
| 35 |
+
print(json.dumps(result['metrics'], indent=1))
|
| 36 |
|
| 37 |
|
| 38 |
if __name__ == '__main__':
|
code/inference.py
CHANGED
|
@@ -33,8 +33,7 @@ def prepare_case(case: Path, out: Path):
|
|
| 33 |
index = case.parent / 'index.json'
|
| 34 |
if index.is_file():
|
| 35 |
info = next((c for c in json.loads(index.read_text())['cases'] if c['clip_id'] == clip_id), {})
|
| 36 |
-
|
| 37 |
-
return export, masks, info.get('mask', {}).get('dilate_px', 0), dense
|
| 38 |
|
| 39 |
|
| 40 |
def subset_export(export: Path, clips, out: Path) -> Path:
|
|
@@ -81,25 +80,25 @@ def main(argv=None):
|
|
| 81 |
p.add_argument('--clips', nargs='+', help='with --export: only these clip ids')
|
| 82 |
p.add_argument('--out', type=Path, required=True)
|
| 83 |
p.add_argument('--checkpoint-dir', type=Path, default=REPO / 'checkpoints',
|
| 84 |
-
help='agt_reconstruction.safetensors, agt_completion_lora.safetensors,
|
| 85 |
p.add_argument('--segformer', default=None, help='SegFormer-B5 Cityscapes: local directory or hub id')
|
| 86 |
p.add_argument('--flux', default=None, help='FLUX.1-Fill-dev: local diffusers directory or hub id')
|
| 87 |
p.add_argument('--completion-python', default=sys.executable, help='python of the completion environment')
|
| 88 |
p.add_argument('--mask-dilate', type=int, default=None,
|
| 89 |
help='mask dilation in pixels (default: the case setting; 4 for --masks dir; 0 for --masks dataset)')
|
| 90 |
-
p.add_argument('--input-frames',
|
| 91 |
-
help='
|
| 92 |
-
'
|
| 93 |
p.add_argument('--reconstruction-only', action='store_true')
|
| 94 |
-
p.add_argument('--keep-captures', action='store_true', help='keep the large capture files of
|
| 95 |
args = p.parse_args(argv)
|
| 96 |
out = args.out.resolve()
|
| 97 |
ckpt = args.checkpoint_dir.resolve()
|
| 98 |
if args.case:
|
| 99 |
-
export, masks, dilate,
|
| 100 |
mask_kind = 'images'
|
| 101 |
else:
|
| 102 |
-
export,
|
| 103 |
if args.clips:
|
| 104 |
export = subset_export(export, args.clips, out)
|
| 105 |
if args.masks == 'dataset':
|
|
@@ -113,25 +112,23 @@ def main(argv=None):
|
|
| 113 |
if args.case:
|
| 114 |
location = ['--mask-dir', masks]
|
| 115 |
dilate = dilate if args.mask_dilate is None else args.mask_dilate
|
| 116 |
-
|
| 117 |
mask = ['--masks', mask_kind, *location, '--mask-dilate', dilate]
|
| 118 |
py = sys.executable
|
| 119 |
|
| 120 |
-
pass1,
|
| 121 |
run(py, 'agt.recon.reconstruct', 'render', '--inputs', export, '--out', pass1, '--checkpoint-dir', ckpt, *mask,
|
| 122 |
*(['--segformer', args.segformer] if args.segformer else []),
|
| 123 |
-
*(['--input-frames',
|
| 124 |
-
'--online-v-semantics', 'camera_only', '--export-render-cameras', '--export-render-sky')
|
| 125 |
if args.reconstruction_only:
|
| 126 |
write_pngs(pass1, out / 'frames')
|
| 127 |
return
|
| 128 |
-
run(
|
| 129 |
-
run(args.completion_python, 'agt.completion.flux_fill', '--pass1', pass1, '--rel', rel, '--out', completion,
|
| 130 |
'--lora', ckpt / 'agt_completion_lora.safetensors', *(['--base', args.flux] if args.flux else []))
|
| 131 |
render_json = next(iter(sorted(pass1.glob('render.*.json'))))
|
| 132 |
cap0, cap1, work, final = out / 'capture0', out / 'capture1', out / 'refinement', out / 'final'
|
| 133 |
run(py, 'agt.refine.capture', '--render-json', render_json, '--out', cap0)
|
| 134 |
-
run(py, 'agt.refine.refine', 'run', '--capture', cap0, '--handoff', completion, '--
|
| 135 |
run(py, 'agt.refine.capture', '--render-json', render_json, '--out', cap1, '--repaired', work / 'views')
|
| 136 |
run(py, 'agt.refine.refine', 'final', '--capture', cap1, '--work', work, '--out', final, '--check-capture', cap0)
|
| 137 |
if not args.keep_captures:
|
|
|
|
| 33 |
index = case.parent / 'index.json'
|
| 34 |
if index.is_file():
|
| 35 |
info = next((c for c in json.loads(index.read_text())['cases'] if c['clip_id'] == clip_id), {})
|
| 36 |
+
return export, masks, info.get('mask', {}).get('dilate_px', 0), info.get('input_positions')
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def subset_export(export: Path, clips, out: Path) -> Path:
|
|
|
|
| 80 |
p.add_argument('--clips', nargs='+', help='with --export: only these clip ids')
|
| 81 |
p.add_argument('--out', type=Path, required=True)
|
| 82 |
p.add_argument('--checkpoint-dir', type=Path, default=REPO / 'checkpoints',
|
| 83 |
+
help='agt_reconstruction.safetensors, agt_completion_lora.safetensors, motion_head.pth')
|
| 84 |
p.add_argument('--segformer', default=None, help='SegFormer-B5 Cityscapes: local directory or hub id')
|
| 85 |
p.add_argument('--flux', default=None, help='FLUX.1-Fill-dev: local diffusers directory or hub id')
|
| 86 |
p.add_argument('--completion-python', default=sys.executable, help='python of the completion environment')
|
| 87 |
p.add_argument('--mask-dilate', type=int, default=None,
|
| 88 |
help='mask dilation in pixels (default: the case setting; 4 for --masks dir; 0 for --masks dataset)')
|
| 89 |
+
p.add_argument('--input-frames', type=int, nargs='+', default=None,
|
| 90 |
+
help='positions of the input frames; the frames from the first to the last input are rendered '
|
| 91 |
+
'(default: the case setting; the input frames of clip.json for --export)')
|
| 92 |
p.add_argument('--reconstruction-only', action='store_true')
|
| 93 |
+
p.add_argument('--keep-captures', action='store_true', help='keep the large capture files of the scene optimization')
|
| 94 |
args = p.parse_args(argv)
|
| 95 |
out = args.out.resolve()
|
| 96 |
ckpt = args.checkpoint_dir.resolve()
|
| 97 |
if args.case:
|
| 98 |
+
export, masks, dilate, inputs = prepare_case(args.case.resolve(), out)
|
| 99 |
mask_kind = 'images'
|
| 100 |
else:
|
| 101 |
+
export, inputs = args.export.resolve(), None
|
| 102 |
if args.clips:
|
| 103 |
export = subset_export(export, args.clips, out)
|
| 104 |
if args.masks == 'dataset':
|
|
|
|
| 112 |
if args.case:
|
| 113 |
location = ['--mask-dir', masks]
|
| 114 |
dilate = dilate if args.mask_dilate is None else args.mask_dilate
|
| 115 |
+
inputs = inputs if args.input_frames is None else args.input_frames
|
| 116 |
mask = ['--masks', mask_kind, *location, '--mask-dilate', dilate]
|
| 117 |
py = sys.executable
|
| 118 |
|
| 119 |
+
pass1, completion = out / 'reconstruction', out / 'completion'
|
| 120 |
run(py, 'agt.recon.reconstruct', 'render', '--inputs', export, '--out', pass1, '--checkpoint-dir', ckpt, *mask,
|
| 121 |
*(['--segformer', args.segformer] if args.segformer else []),
|
| 122 |
+
*(['--input-frames', *inputs] if inputs else []))
|
|
|
|
| 123 |
if args.reconstruction_only:
|
| 124 |
write_pngs(pass1, out / 'frames')
|
| 125 |
return
|
| 126 |
+
run(args.completion_python, 'agt.completion.flux_fill', '--pass1', pass1, '--out', completion,
|
|
|
|
| 127 |
'--lora', ckpt / 'agt_completion_lora.safetensors', *(['--base', args.flux] if args.flux else []))
|
| 128 |
render_json = next(iter(sorted(pass1.glob('render.*.json'))))
|
| 129 |
cap0, cap1, work, final = out / 'capture0', out / 'capture1', out / 'refinement', out / 'final'
|
| 130 |
run(py, 'agt.refine.capture', '--render-json', render_json, '--out', cap0)
|
| 131 |
+
run(py, 'agt.refine.refine', 'run', '--capture', cap0, '--handoff', completion, '--work', work)
|
| 132 |
run(py, 'agt.refine.capture', '--render-json', render_json, '--out', cap1, '--repaired', work / 'views')
|
| 133 |
run(py, 'agt.refine.refine', 'final', '--capture', cap1, '--work', work, '--out', final, '--check-capture', cap0)
|
| 134 |
if not args.keep_captures:
|
code/requirements.txt
CHANGED
|
@@ -29,6 +29,4 @@ sentencepiece
|
|
| 29 |
protobuf
|
| 30 |
lpips==0.1.4
|
| 31 |
DISTS_pytorch==0.1
|
| 32 |
-
torchmetrics==1.9.0
|
| 33 |
-
torch-fidelity==0.3.0
|
| 34 |
python-box==7.4.1
|
|
|
|
| 29 |
protobuf
|
| 30 |
lpips==0.1.4
|
| 31 |
DISTS_pytorch==0.1
|
|
|
|
|
|
|
| 32 |
python-box==7.4.1
|