singam96/ShadeNet-6-L-98M: upload L
Browse files- .gitattributes +10 -0
- README.md +191 -0
- assets/grid_100m.png +3 -0
- assets/hero.png +3 -0
- assets/panel_00.png +3 -0
- assets/panel_01.png +3 -0
- assets/panel_02.png +3 -0
- assets/panel_03.png +3 -0
- assets/panel_04.png +3 -0
- assets/panel_05.png +3 -0
- assets/panel_06.png +3 -0
- assets/panel_07.png +3 -0
- checkpoints/shadenet6-l.ckpt +3 -0
- config.json +42 -0
- inference/framing.py +48 -0
- inference/run.py +103 -0
- inference/shadenet6.py +813 -0
- requirements.txt +4 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,13 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
assets/grid_100m.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
assets/hero.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
assets/panel_00.png filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
assets/panel_01.png filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
assets/panel_02.png filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
assets/panel_03.png filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
assets/panel_04.png filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
assets/panel_05.png filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
assets/panel_06.png filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
assets/panel_07.png filter=lfs diff=lfs merge=lfs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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
base_model: facebook/dinov2-base
|
| 4 |
+
pipeline_tag: image-to-image
|
| 5 |
+
library_name: pytorch
|
| 6 |
+
tags:
|
| 7 |
+
- inverse-rendering
|
| 8 |
+
- intrinsic-decomposition
|
| 9 |
+
- albedo
|
| 10 |
+
- normal-map
|
| 11 |
+
- depth-estimation
|
| 12 |
+
- dinov2
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# ShadeNet-6 L
|
| 16 |
+
|
| 17 |
+
**Single-image inverse rendering** — one RGB photo in, albedo + relative depth + surface normal out.
|
| 18 |
+
|
| 19 |
+

|
| 20 |
+
|
| 21 |
+
A feed-forward network on a frozen **DINOv2 ViT-B/14** backbone (86.6M parameters) plus a 11.8M-parameter trainable head:
|
| 22 |
+
a projector, a convolutional **detail encoder** that sees the photo at full resolution (DINOv2's maps are smooth, it reads
|
| 23 |
+
14-pixel patches), a wide decoder, a small dense patch network that gives a coarse first guess, an input patch dictionary and a
|
| 24 |
+
tiny refiner. One forward pass, no iteration. On the 23-image held-out set its single pass has a **26% lower mean error than
|
| 25 |
+
ShadeNet-5's single pass** and is better on every one of the 23 images (see Results for the caveats).
|
| 26 |
+
|
| 27 |
+
*Hero: the first six validation images, in dataset order, not picked. Each panel: input | albedo / depth | normal.*
|
| 28 |
+
|
| 29 |
+
## TL;DR
|
| 30 |
+
|
| 31 |
+
| | |
|
| 32 |
+
|---|---|
|
| 33 |
+
| Task | Single-image inverse rendering (intrinsic decomposition) |
|
| 34 |
+
| Output | 7ch — albedo (3) + relative depth (1) + normal (3) |
|
| 35 |
+
| Params | 98.35M total (11.77M trainable; 86.58M is the frozen DINOv2 ViT-B/14) |
|
| 36 |
+
| Backbone | DINOv2 ViT-B/14, frozen (Meta AI) |
|
| 37 |
+
| Inference | one forward pass (about 39 ms per 448x448 image on an RTX 5060 Ti, bf16); a mirror average (2 passes) is optional |
|
| 38 |
+
| Input size | 448x448 (multiples of 14 and 32: 448, 896); `inference/run.py` keeps the whole photo |
|
| 39 |
+
| Framework | PyTorch (+ `transformers`); standalone inference code in `inference/`, no training code needed |
|
| 40 |
+
| License | Apache-2.0 |
|
| 41 |
+
|
| 42 |
+
## What it does
|
| 43 |
+
|
| 44 |
+
Given a single RGB image it predicts three intrinsic maps: **albedo** (base colour), **relative depth** (grayscale, per-image) and a **surface normal** map. Output channels are `[0:3]=albedo`, `[3:4]=depth`, `[4:7]=normal`, all in [-1, 1]; depth is relative (larger = farther), normals are x right, y up, z toward the viewer.
|
| 45 |
+
|
| 46 |
+
> Same output convention as ShadeNet-5: 7 channels, no shading channel. It is a new architecture trained from scratch, not a continuation of ShadeNet-5's weights.
|
| 47 |
+
|
| 48 |
+
## Results
|
| 49 |
+
|
| 50 |
+
Mean per-map L1 against the labels on the **same 23 held-out images**, run through both models in one script (lower is better; albedo and normal are scored on labelled pixels only, depth on all pixels; unit-length normals in the "+unit" rows). ShadeNet-5 numbers are measured here on the same images, not copied from its card (the ShadeNet-5 card's 0.1757 is on a different set of 23 images).
|
| 51 |
+
|
| 52 |
+
| Model and recipe | Parameters | Albedo | Depth | Normal | **Mean** |
|
| 53 |
+
|---|---|---|---|---|---|
|
| 54 |
+
| ShadeNet-5, single pass + unit normals | 34.65M | 0.166 | 0.169 | 0.163 | **0.1659** |
|
| 55 |
+
| ShadeNet-5 + its refiner | 34.65M + 0.91M | 0.160 | 0.168 | 0.151 | 0.1597 |
|
| 56 |
+
| ShadeNet-5, six passes (mirror + rotations ±4°) | 34.65M | 0.158 | 0.162 | 0.150 | 0.1562 |
|
| 57 |
+
| **ShadeNet-6 L**, single pass + unit normals | **98.35M** | 0.123 | 0.124 | 0.122 | **0.1232** |
|
| 58 |
+
| ShadeNet-6 L, single pass (raw normals) | 98.35M | 0.123 | 0.124 | 0.126 | 0.1244 |
|
| 59 |
+
| ShadeNet-6 L, mirror average | 98.35M | 0.122 | 0.122 | 0.119 | 0.1213 |
|
| 60 |
+
| ShadeNet-6 L, six passes (mirror + rotations ±4°) | 98.35M | 0.120 | 0.129 | 0.118 | 0.1223 |
|
| 61 |
+
| ShadeNet-6 XS, single pass + unit normals | 1.99M | 0.176 | 0.186 | 0.166 | 0.1759 |
|
| 62 |
+
|
| 63 |
+
Paired per-image difference in mean L1 (ShadeNet-6 L minus ShadeNet-5; negative = ShadeNet-6 L is better):
|
| 64 |
+
|
| 65 |
+
| Comparison | Difference | ShadeNet-6 L better on |
|
| 66 |
+
|---|---|---|
|
| 67 |
+
| single pass vs single pass | -0.0427 ± 0.0055 | 23 of 23 images |
|
| 68 |
+
| single pass vs ShadeNet-5 + refiner | -0.0364 ± 0.0055 | 23 of 23 |
|
| 69 |
+
| mirror average vs ShadeNet-5 + refiner | -0.0384 ± 0.0056 | 23 of 23 |
|
| 70 |
+
| six passes vs ShadeNet-5 six passes | -0.0340 ± 0.0053 | 22 of 23 |
|
| 71 |
+
|
| 72 |
+
- The gain is on **all three maps**: albedo 0.166 to 0.123, depth 0.169 to 0.124, normals 0.163 to 0.122.
|
| 73 |
+
- Test-time averaging barely helps this model: a mirror average gains 0.002 and six passes make depth worse (0.124 to 0.129), where ShadeNet-5 gains 0.010 from its six passes. Use a single pass or the mirror average.
|
| 74 |
+
- The model's own tiny refiner (0.51M) adds 0.0001 to 0.0017 on top of the main network's maps.
|
| 75 |
+
- **Speed:** one pass takes about 39 ms per image on an RTX 5060 Ti (bf16). ShadeNet-5's six-pass recipe took about 283 ms per image in the same run.
|
| 76 |
+
|
| 77 |
+

|
| 78 |
+
|
| 79 |
+
*Six of the 23 validation photos, chosen by the size of the difference, so the figure is not cherry-picked: the two where ShadeNet-6 L gains most, two typical ones, and the two where it gains least. Columns: photo, then albedo, depth and normal as label | ShadeNet-5 | ShadeNet-6 L (the column headers say "ShadeNet-6"). Both models: one pass, unit-length normals. The number on each photo is its mean L1 for each model.*
|
| 80 |
+
|
| 81 |
+
**Read these numbers with care.** The validation set is 23 images, every label is a Marigold-V2 pseudo-label (not a measurement), and the checkpoint was **chosen on these same 23 images**, which makes the score optimistic by roughly 0.001 to 0.003. The gap to ShadeNet-5 (0.04) is more than ten times that, but it is one run on a small set. See Limitations.
|
| 82 |
+
|
| 83 |
+
## Gallery
|
| 84 |
+
|
| 85 |
+
Held-out images (none was used for training), single forward pass, unit-length normals. These are the **first eight of the 23 validation images in dataset order**, not selected for how they look. Each panel: input | albedo / depth | normal.
|
| 86 |
+
|
| 87 |
+
### ski jump in a snow park
|
| 88 |
+
|
| 89 |
+

|
| 90 |
+
|
| 91 |
+
### man on a bench behind a bicycle
|
| 92 |
+
|
| 93 |
+

|
| 94 |
+
|
| 95 |
+
### fairground wheel with spectators
|
| 96 |
+
|
| 97 |
+

|
| 98 |
+
|
| 99 |
+
### climber leaping from a boulder
|
| 100 |
+
|
| 101 |
+

|
| 102 |
+
|
| 103 |
+
### child in an orange tube slide
|
| 104 |
+
|
| 105 |
+

|
| 106 |
+
|
| 107 |
+
### child hanging upside down from bars
|
| 108 |
+
|
| 109 |
+

|
| 110 |
+
|
| 111 |
+
### boy swinging on a pole
|
| 112 |
+
|
| 113 |
+

|
| 114 |
+
|
| 115 |
+
### portable toilets and city towers
|
| 116 |
+
|
| 117 |
+

|
| 118 |
+
|
| 119 |
+
## Architecture
|
| 120 |
+
|
| 121 |
+
Three networks in a row; a stop-gradient sits between each pair, so every part is trained on its own loss.
|
| 122 |
+
|
| 123 |
+
| # | Part | Parameters | What it does |
|
| 124 |
+
|---|---|---|---|
|
| 125 |
+
| 1 | **Pre-refiner** | 362,624 | A dense (fully connected) network applied to every 16x16 patch of the photo with shared weights: 768 numbers in, 1,792 out (a 16x16x7 patch of maps). Gives a coarse first guess. |
|
| 126 |
+
| 2 | **Main model** | 97,476,825 | A **frozen DINOv2 ViT-B/14** (86,580,480; `facebook/dinov2-base`; the outputs of four blocks, 3/6/9/12, are tapped and concatenated) with a 1x1 projector per pyramid level (2,753,408, trainable); a **convolutional detail encoder** at full resolution (strides 2 to 16, widths 48/96/192/320); a depthwise-separable decoder (widths 1024/512/320/160/96, two blocks per level) with a global-context block; and one soft patch dictionary (33,138 parameters) at its input. Decoder, encoder and dictionary together: about 8.14M. Takes the photo plus the pre-refiner's maps and outputs those maps plus a learned residual. |
|
| 127 |
+
| 3 | **Refiner** | 511,903 | A small 4-level convolutional UNet on the main model's clamped maps. The final output. |
|
| 128 |
+
|
| 129 |
+
There is no post-refiner in this model. A small PatchGAN discriminator (73,697 parameters, GroupNorm) is used in training only and is not in the released checkpoint.
|
| 130 |
+
|
| 131 |
+
The ViT never resizes its input, so height and width must be multiples of 14 and 32: 448 is what it was trained at (a 32x32 token grid). DINOv2's patch tokens are smooth at 14 pixels; the detail encoder is what supplies the high-resolution structure, as ShadeNet-5's UNet encoder did.
|
| 132 |
+
|
| 133 |
+
## Training
|
| 134 |
+
|
| 135 |
+
- **Data:** Flickr8k photos with Marigold-V2 pseudo-labels (albedo, normals, depth), 8,013 training and 23 validation scenes after a quality gate on the normal labels (41 scenes dropped). 448 px, with zoom, small rotation, warp and mirror augmentation (normals are reoriented with the geometry), plus photometric jitter on the photo only.
|
| 136 |
+
- **Loss:** per-map task losses on each part's own output — albedo: masked L1 + multiscale gradient matching; depth: scale-and-shift-invariant L1 + gradient matching + a raw-L1 anchor; normal: mean angle + a unit-length penalty — plus a **depth-orientation term**: the scale-and-shift losses cannot tell a depth map from its inverse, and from scratch the model settled into inverted depth until `relu(-scale)` was added. In phase 2 a **PatchGAN** term (weight 0.02, discriminator lr 2e-5, ramped in over 1,000 steps) judges the main model's albedo and normal maps; depth stays on L1.
|
| 137 |
+
- **Optimiser:** AdamW with warm-up and cosine decay, per-part gradient clipping, bf16, batch 8. About 10 minutes per epoch on one RTX 5060 Ti.
|
| 138 |
+
- **Phase 1 (L1 only):** peak learning rate 3e-4 on a 40-epoch cosine. Mean L1 on the training-time validation: epoch 0 0.1647, epoch 3 0.1428, best **epoch 6 0.1364**. Stopped by hand after epoch 7.
|
| 139 |
+
- **Phase 2 (+ PatchGAN):** restarted from the phase-1 best with a fresh optimiser, peak learning rate 1e-4 on a 25-epoch cosine. Epoch 0 0.1314, **best epoch 9 0.1243**, epochs 9 to 14 between 0.1243 and 0.1275 (a plateau at about 0.125). Stopped by hand after epoch 14. **The released checkpoint is epoch 9.**
|
| 140 |
+
- The frozen ViT is held in eval mode inside the forward pass (Lightning restores each module's saved mode after its sanity check, which would otherwise switch it back). The pre-refiner, main model and refiner share one optimiser but no loss.
|
| 141 |
+
|
| 142 |
+
## What we learned
|
| 143 |
+
|
| 144 |
+
- **The larger frozen backbone, the detail encoder and the wider decoder together were the big step** (0.176 for the 1.99M ShadeNet-6 XS to 0.136 after seven epochs). We did not ablate them one by one, so we cannot say how much each contributes.
|
| 145 |
+
- **Most of the gain came in the first epochs**: phase 1 fell from 0.165 to 0.143 in three epochs, then moved by less than the validation noise (about ±0.004) between epochs 4 and 7.
|
| 146 |
+
- **The refiner is nearly redundant** here (gain 0.0001 to 0.0017); the main model's output is already smooth.
|
| 147 |
+
- **Test-time averaging is not worth it** (see Results).
|
| 148 |
+
- **The PatchGAN's effect is not isolated.** Phase 2 also lowered the learning rate and restarted the optimiser, so the drop from 0.1364 to 0.1243 cannot be credited to the GAN alone, and L1 does not reward sharper detail.
|
| 149 |
+
|
| 150 |
+
## Usage
|
| 151 |
+
|
| 152 |
+
The inference code is in the `inference/` folder of this repository and needs no training code: a single file that rebuilds the network from the checkpoint (verified to give bit-identical outputs to the training code).
|
| 153 |
+
|
| 154 |
+
```bash
|
| 155 |
+
pip install torch transformers pillow numpy
|
| 156 |
+
python inference/run.py photos/ --checkpoint checkpoints/shadenet6-l.ckpt --out out/
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
Each photo becomes a panel image: input, albedo, depth, normal, at the photo's own shape (the long side is scaled to 448, the rest of the square is filled by mirroring the photo's edge, and the padding is cut off the maps; `--framing crop` takes the centre square, which is what the model was trained on, and `--mirror` averages the prediction with the mirrored-photo prediction). The whole-photo framing was not evaluated for this model: the numbers above use square crops.
|
| 160 |
+
|
| 161 |
+
From Python:
|
| 162 |
+
|
| 163 |
+
```python
|
| 164 |
+
import torch
|
| 165 |
+
from inference.shadenet6 import ShadeNet6
|
| 166 |
+
|
| 167 |
+
model = ShadeNet6.from_checkpoint("checkpoints/shadenet6-l.ckpt", device="cuda")
|
| 168 |
+
photo = ... # float32 [1, 3, 448, 448] in [-1, 1]
|
| 169 |
+
maps = model.predict(photo) # [1, 7, 448, 448] in [-1, 1]
|
| 170 |
+
albedo, depth, normal = maps[:, 0:3], maps[:, 3:4], maps[:, 4:7]
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
The backbone loads its configuration from `facebook/dinov2-base` on the Hub (a few kB; the weights come from the checkpoint). The checkpoint is 394 MB (fp32, inference only). `config.json` lists the architecture, the input and output convention and the validation numbers. There is no ONNX export yet.
|
| 174 |
+
|
| 175 |
+
## Limitations
|
| 176 |
+
|
| 177 |
+
- **Tiny validation set (23 images):** the score moves by 0.003 or more between epochs, one run is not a distribution, and the **checkpoint was chosen on the same 23 images**, so the reported number is optimistic by roughly 0.001 to 0.003.
|
| 178 |
+
- **Pseudo-labels:** the labels are model predictions (Marigold-V2), not measurements, so the model inherits their errors, and a model scored against them cannot be shown to be better than the labelling model.
|
| 179 |
+
- **Size:** 98.4M parameters (86.6M of them a frozen backbone) against ShadeNet-5's 34.65M, so this is a comparison of quality at a larger size, not at equal size.
|
| 180 |
+
- **Relative depth only:** no metric scale.
|
| 181 |
+
- **Fixed input sizes:** height and width must be multiples of 14 and 32 (448, 896, ...).
|
| 182 |
+
- **Whole-photo framing and test-time averaging beyond the mirror** were not evaluated for this model.
|
| 183 |
+
- **Not exported:** no ONNX, no quantisation; speed was measured on one GPU only.
|
| 184 |
+
|
| 185 |
+
## License & attribution
|
| 186 |
+
|
| 187 |
+
Code and weights: Apache-2.0.
|
| 188 |
+
|
| 189 |
+
- **Backbone:** DINOv2 ViT-B/14 ([facebook/dinov2-base](https://huggingface.co/facebook/dinov2-base), Meta AI, Apache-2.0), kept frozen; its weights are part of the checkpoint.
|
| 190 |
+
- **Labels:** the albedo, normal and depth training labels are pseudo-labels generated with Marigold V2 ([huawei-bayerlab/marigold-v2-0](https://huggingface.co/huawei-bayerlab/marigold-v2-0), Apache-2.0; its base model Qwen-Image-Edit-2509 is Apache-2.0 too). They are model outputs, not ground truth.
|
| 191 |
+
- **Images:** the photographs come from the Flickr8k corpus (Hodosh, Young and Hockenmaier, 2013; Rashtchian et al., 2010). The corpus authors release the *captions* under CC BY-SA, but the photographs are individual Flickr images owned by their photographers and have no blanket licence. The example images on this card are shown for illustration.
|
assets/grid_100m.png
ADDED
|
Git LFS Details
|
assets/hero.png
ADDED
|
Git LFS Details
|
assets/panel_00.png
ADDED
|
Git LFS Details
|
assets/panel_01.png
ADDED
|
Git LFS Details
|
assets/panel_02.png
ADDED
|
Git LFS Details
|
assets/panel_03.png
ADDED
|
Git LFS Details
|
assets/panel_04.png
ADDED
|
Git LFS Details
|
assets/panel_05.png
ADDED
|
Git LFS Details
|
assets/panel_06.png
ADDED
|
Git LFS Details
|
assets/panel_07.png
ADDED
|
Git LFS Details
|
checkpoints/shadenet6-l.ckpt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f1ffa00e1c126a798822239fa5f2a38d1b3c8366bdd8a664d998fe819515be12
|
| 3 |
+
size 393544423
|
config.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_name": "ShadeNet-6-L",
|
| 3 |
+
"task": "intrinsic-decomposition",
|
| 4 |
+
"architecture": "pre-refiner (dense 16x16 patch net) + main model (frozen DINOv2 ViT-B/14, conv detail encoder, wide decoder, input patch dictionary) + map refiner, stop-gradients between parts",
|
| 5 |
+
"backbone": "facebook/dinov2-base",
|
| 6 |
+
"parameters": 98351352,
|
| 7 |
+
"trainable_parameters": 11770872,
|
| 8 |
+
"image_size": 448,
|
| 9 |
+
"supported_image_sizes": [448, 896],
|
| 10 |
+
"input": {
|
| 11 |
+
"name": "photo",
|
| 12 |
+
"channels": 3,
|
| 13 |
+
"range": [-1.0, 1.0],
|
| 14 |
+
"note": "RGB photo; height and width multiples of 14 and 32"
|
| 15 |
+
},
|
| 16 |
+
"output": {
|
| 17 |
+
"name": "maps",
|
| 18 |
+
"channels": 7,
|
| 19 |
+
"range": [-1.0, 1.0],
|
| 20 |
+
"layout": {"albedo": [0, 3], "depth": [3, 4], "normal": [4, 7]},
|
| 21 |
+
"note": "depth is relative (larger = farther); normals are x right, y up, z toward the viewer"
|
| 22 |
+
},
|
| 23 |
+
"checkpoint": "checkpoints/shadenet6-l.ckpt",
|
| 24 |
+
"checkpoint_note": "fp32, inference only (no optimiser, no training discriminator); epoch 9 of the PatchGAN phase",
|
| 25 |
+
"inference_script": "inference/run.py",
|
| 26 |
+
"recommended_inference": {
|
| 27 |
+
"mode": "single pass",
|
| 28 |
+
"command": "python inference/run.py <photos> --checkpoint checkpoints/shadenet6-l.ckpt --out out/",
|
| 29 |
+
"mirror_average": "add --mirror (2 passes, mean L1 0.1213 vs 0.1232)"
|
| 30 |
+
},
|
| 31 |
+
"validation_mean_l1": {
|
| 32 |
+
"note": "23 held-out images, same images and masking as ShadeNet-5's numbers below; checkpoint chosen on these images",
|
| 33 |
+
"shadenet6_l_single_pass_unit_normals": 0.1232,
|
| 34 |
+
"shadenet6_l_single_pass_raw_normals": 0.1244,
|
| 35 |
+
"shadenet6_l_mirror_average": 0.1213,
|
| 36 |
+
"shadenet6_l_six_passes": 0.1223,
|
| 37 |
+
"shadenet5_single_pass_unit_normals": 0.1659,
|
| 38 |
+
"shadenet5_plus_refiner": 0.1597,
|
| 39 |
+
"shadenet5_six_passes": 0.1562
|
| 40 |
+
},
|
| 41 |
+
"forward_time_ms_rtx5060ti_bf16": 39.4
|
| 42 |
+
}
|
inference/framing.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fit a whole photo into the model's square input instead of cropping it.
|
| 2 |
+
|
| 3 |
+
The model takes 448x448. `letterbox` scales the photo so its LONG side is 448
|
| 4 |
+
and fills the rest of the square by mirroring the photo's own edge (the model
|
| 5 |
+
never saw flat-coloured bars, and the test-time rotation already feeds it
|
| 6 |
+
reflected borders). After the model runs, `crop_to_box` cuts the padding off
|
| 7 |
+
the maps again, so nothing of the photo is lost and nothing invented is shown.
|
| 8 |
+
"""
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from PIL import Image
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def letterbox(img: Image.Image, size: int):
|
| 16 |
+
"""Return (square PIL image, (left, top, w, h) of the real photo in it)."""
|
| 17 |
+
img = img.convert("RGB")
|
| 18 |
+
w, h = img.size
|
| 19 |
+
scale = size / float(max(w, h))
|
| 20 |
+
nw, nh = max(1, int(round(w * scale))), max(1, int(round(h * scale)))
|
| 21 |
+
arr = np.asarray(img.resize((nw, nh), Image.BICUBIC))
|
| 22 |
+
left, top = (size - nw) // 2, (size - nh) // 2
|
| 23 |
+
pad = ((top, size - nh - top), (left, size - nw - left), (0, 0))
|
| 24 |
+
# 'symmetric' (edge pixel included) is safe for any pad width, even when
|
| 25 |
+
# the padding is longer than the photo itself (a very elongated panorama).
|
| 26 |
+
out = np.pad(arr, pad, mode="symmetric")
|
| 27 |
+
return Image.fromarray(out), (left, top, nw, nh)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def crop_to_box(maps: torch.Tensor, box) -> torch.Tensor:
|
| 31 |
+
"""Cut [B, C, S, S] maps down to the photo's own pixels."""
|
| 32 |
+
left, top, w, h = box
|
| 33 |
+
return maps[:, :, top:top + h, left:left + w]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def resize_maps(maps: torch.Tensor, width: int, height: int) -> torch.Tensor:
|
| 37 |
+
"""Resize 7-channel maps for display and keep the normals unit length."""
|
| 38 |
+
out = F.interpolate(maps.float(), size=(height, width), mode="bicubic",
|
| 39 |
+
align_corners=False).clamp(-1.0, 1.0)
|
| 40 |
+
n = out[:, 4:7]
|
| 41 |
+
out[:, 4:7] = n / n.norm(dim=1, keepdim=True).clamp_min(1e-6)
|
| 42 |
+
return out
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def display_size(w: int, h: int, longest: int = 1024):
|
| 46 |
+
"""Output size: the photo's own shape, long side at most `longest`."""
|
| 47 |
+
s = min(1.0, longest / float(max(w, h)))
|
| 48 |
+
return max(1, int(round(w * s))), max(1, int(round(h * s)))
|
inference/run.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run ShadeNet-6 (L or XS) on photos. No training code needed.
|
| 2 |
+
|
| 3 |
+
pip install torch transformers pillow numpy # ShadeNet-6 XS needs torchvision instead of transformers
|
| 4 |
+
python inference/run.py photos/ --checkpoint checkpoints/shadenet6-l.ckpt --out out/
|
| 5 |
+
|
| 6 |
+
Each photo becomes a panel image: input | albedo | depth | normal, at the photo's own shape. The whole photo is
|
| 7 |
+
kept: its long side is scaled to 448 and the rest of the square is filled by mirroring its edge, then the padding is
|
| 8 |
+
cut off the maps (`--framing crop` takes the centre square instead, which is what the models were trained on).
|
| 9 |
+
`--mirror` averages the prediction with the prediction on the mirrored photo (two passes, normals renormalised).
|
| 10 |
+
Maps are written next to the panel with `--save-maps` (a .npz with `albedo`, `depth`, `normal`, all in [-1, 1]).
|
| 11 |
+
"""
|
| 12 |
+
import argparse
|
| 13 |
+
import os
|
| 14 |
+
import sys
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
from PIL import Image, ImageOps
|
| 19 |
+
|
| 20 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 21 |
+
from framing import crop_to_box, display_size, letterbox, resize_maps # noqa: E402
|
| 22 |
+
from shadenet6 import ShadeNet6 # noqa: E402
|
| 23 |
+
|
| 24 |
+
SIZE = 448 # both models were trained at 448 (a multiple of 14 and 32)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def to_tensor(img: Image.Image) -> torch.Tensor:
|
| 28 |
+
arr = np.asarray(img, dtype=np.float32) / 255.0
|
| 29 |
+
return torch.from_numpy(arr.transpose(2, 0, 1)[None] * 2.0 - 1.0)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def to_img(x: torch.Tensor) -> Image.Image:
|
| 33 |
+
"""[1, C, H, W] in [-1, 1] -> RGB image (one channel is shown as grey)."""
|
| 34 |
+
x = ((x + 1.0) / 2.0).clamp(0, 1)
|
| 35 |
+
if x.shape[1] == 1:
|
| 36 |
+
x = x.expand(-1, 3, -1, -1)
|
| 37 |
+
return Image.fromarray((x[0].permute(1, 2, 0).numpy() * 255).round().astype("uint8"))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def unit_normals(m: torch.Tensor) -> torch.Tensor:
|
| 41 |
+
out = m.clone()
|
| 42 |
+
n = out[:, 4:7]
|
| 43 |
+
out[:, 4:7] = n / n.norm(dim=1, keepdim=True).clamp_min(1e-6)
|
| 44 |
+
return out
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@torch.no_grad()
|
| 48 |
+
def predict(model: ShadeNet6, x: torch.Tensor, mirror: bool = False) -> torch.Tensor:
|
| 49 |
+
m = model.predict(x)
|
| 50 |
+
if mirror:
|
| 51 |
+
b = model.predict(x.flip(-1)).flip(-1).clone()
|
| 52 |
+
b[:, 4] = -b[:, 4] # the mirrored scene's normal x has the opposite sign
|
| 53 |
+
m = 0.5 * (m + b)
|
| 54 |
+
return unit_normals(m)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def panel(photo: Image.Image, maps: torch.Tensor) -> Image.Image:
|
| 58 |
+
w, h = photo.size
|
| 59 |
+
tiles = [photo, to_img(maps[:, 0:3]), to_img(maps[:, 3:4]), to_img(maps[:, 4:7])]
|
| 60 |
+
out = Image.new("RGB", (4 * w, h))
|
| 61 |
+
for i, t in enumerate(tiles):
|
| 62 |
+
out.paste(t.resize((w, h)), (i * w, 0))
|
| 63 |
+
return out
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def main():
|
| 67 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
| 68 |
+
ap.add_argument("photos", help="a photo or a folder of photos")
|
| 69 |
+
ap.add_argument("--checkpoint", required=True, help="shadenet6-l.ckpt or shadenet6-xs.ckpt")
|
| 70 |
+
ap.add_argument("--out", default="out")
|
| 71 |
+
ap.add_argument("--mirror", action="store_true", help="average with the mirrored-photo prediction (2 passes)")
|
| 72 |
+
ap.add_argument("--framing", choices=["letterbox", "crop"], default="letterbox")
|
| 73 |
+
ap.add_argument("--save-maps", action="store_true")
|
| 74 |
+
ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
|
| 75 |
+
args = ap.parse_args()
|
| 76 |
+
|
| 77 |
+
model = ShadeNet6.from_checkpoint(args.checkpoint, device=args.device)
|
| 78 |
+
print(f"{model.count_parameters() / 1e6:.2f}M parameters on {args.device}")
|
| 79 |
+
paths = ([os.path.join(args.photos, f) for f in sorted(os.listdir(args.photos))]
|
| 80 |
+
if os.path.isdir(args.photos) else [args.photos])
|
| 81 |
+
paths = [p for p in paths if p.lower().endswith((".jpg", ".jpeg", ".png", ".webp", ".bmp"))]
|
| 82 |
+
os.makedirs(args.out, exist_ok=True)
|
| 83 |
+
for p in paths:
|
| 84 |
+
img = ImageOps.exif_transpose(Image.open(p)).convert("RGB")
|
| 85 |
+
if args.framing == "letterbox":
|
| 86 |
+
sq, box = letterbox(img, SIZE)
|
| 87 |
+
else:
|
| 88 |
+
sq, box = ImageOps.fit(img, (SIZE, SIZE), Image.BICUBIC), (0, 0, SIZE, SIZE)
|
| 89 |
+
maps = predict(model, to_tensor(sq).to(args.device), args.mirror).float().cpu()
|
| 90 |
+
maps = crop_to_box(maps, box)
|
| 91 |
+
w, h = display_size(maps.shape[-1], maps.shape[-2])
|
| 92 |
+
maps = resize_maps(maps, w, h)
|
| 93 |
+
shown = (img if args.framing == "letterbox" else sq).resize((w, h), Image.BICUBIC)
|
| 94 |
+
stem = os.path.splitext(os.path.basename(p))[0]
|
| 95 |
+
panel(shown, maps).save(os.path.join(args.out, stem + "_result.png"))
|
| 96 |
+
if args.save_maps:
|
| 97 |
+
np.savez_compressed(os.path.join(args.out, stem + "_maps.npz"), albedo=maps[0, 0:3].numpy(),
|
| 98 |
+
depth=maps[0, 3].numpy(), normal=maps[0, 4:7].numpy())
|
| 99 |
+
print("wrote", stem + "_result.png")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__ == "__main__":
|
| 103 |
+
main()
|
inference/shadenet6.py
ADDED
|
@@ -0,0 +1,813 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ShadeNet-6 (L and XS): standalone inference code, generated by tools/build_s6_standalone.py.
|
| 2 |
+
|
| 3 |
+
No training code is needed: PyTorch + `transformers` (ShadeNet-6 L) or + `torchvision` (ShadeNet-6 XS).
|
| 4 |
+
Classes are copied from the training repository, so the state-dict keys match the released checkpoints.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import math
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# ---------------------------------------------------------------------------------------------- layers
|
| 16 |
+
|
| 17 |
+
class PatchDictionaryBias(nn.Module):
|
| 18 |
+
"""Soft patch-dictionary prior, added as a scaled residual.
|
| 19 |
+
|
| 20 |
+
Forward: unfold signal into p×p tiles -> per-tile addressing MLP ->
|
| 21 |
+
softmax over `n_atoms` -> weighted atom sum, added back onto the tile
|
| 22 |
+
with a learned per-channel scale (`tile + s * recon`, s init small).
|
| 23 |
+
The add forces the recon into the signal path: unlike the old
|
| 24 |
+
concat+1x1 mixer (which could zero its recon half and starve the atoms
|
| 25 |
+
of gradient forever), the atoms always affect the output and always
|
| 26 |
+
receive gradient. Addressing runs on a strided-downsampled tile
|
| 27 |
+
(cheap), never the raw tile (an MLP on p*p*C dims would dwarf the
|
| 28 |
+
model).
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self, channels=8, patch=16, n_atoms=1024, hidden=128,
|
| 32 |
+
deblock=True, blur_radius=2,
|
| 33 |
+
blend_scale_init=0.1,
|
| 34 |
+
init_std=0.0, init_seed=0,
|
| 35 |
+
addr_init_scale=1.0, gumbel=0.0, global_ctx=0):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.patch = int(patch)
|
| 38 |
+
self.n_atoms = int(n_atoms)
|
| 39 |
+
# Global-context branch for the selector: 0 = off; >0 = hidden width of
|
| 40 |
+
# a tiny MLP that maps the mean tile descriptor to a shared global code,
|
| 41 |
+
# concatenated onto every tile's own descriptor before `addr`.
|
| 42 |
+
self.global_ctx = int(global_ctx)
|
| 43 |
+
# Stochastic-addressing noise scale (training only; 0 = deterministic).
|
| 44 |
+
self.gumbel = float(gumbel)
|
| 45 |
+
self._last_usage = None # batch-mean address dist, set in forward
|
| 46 |
+
# Per-channel atoms: [A, C, p, p]. Zero-init is a clean passthrough
|
| 47 |
+
# start, but it makes every atom identical — and with identical atoms
|
| 48 |
+
# the addressing gradient dL/dw_a = atom_a . dL/drecon is the same for
|
| 49 |
+
# all a, so the softmax never learns to be selective and the atoms
|
| 50 |
+
# never differentiate (v4 symmetry lock-in). A small SEEDED Gaussian
|
| 51 |
+
# breaks it: a common gradient shifts all atoms equally and preserves
|
| 52 |
+
# their differences.
|
| 53 |
+
if init_std > 0:
|
| 54 |
+
g = torch.Generator().manual_seed(int(init_seed))
|
| 55 |
+
self.atoms = nn.Parameter(
|
| 56 |
+
torch.randn(n_atoms, channels, patch, patch, generator=g)
|
| 57 |
+
* float(init_std))
|
| 58 |
+
else:
|
| 59 |
+
self.atoms = nn.Parameter(
|
| 60 |
+
torch.zeros(n_atoms, channels, patch, patch))
|
| 61 |
+
# Tile descriptor: depthwise strided conv p -> ~p/4, then MLP.
|
| 62 |
+
# Kernel min(4, p) so small patches (p=2 at H/32) still collapse to 1x1.
|
| 63 |
+
k = min(4, self.patch)
|
| 64 |
+
out_sp = (self.patch - k) // k + 1
|
| 65 |
+
self.desc = nn.Conv2d(channels, channels, k, stride=k,
|
| 66 |
+
groups=channels, bias=False)
|
| 67 |
+
d = channels * out_sp * out_sp
|
| 68 |
+
if self.global_ctx > 0:
|
| 69 |
+
# Mean tile descriptor -> shared global code -> concat onto each
|
| 70 |
+
# tile. Cheap and resolution-independent (mean over tiles), so the
|
| 71 |
+
# selector sees scene-level context alongside its own tile.
|
| 72 |
+
self.gctx = nn.Sequential(
|
| 73 |
+
nn.Linear(d, self.global_ctx),
|
| 74 |
+
nn.ELU(inplace=True),
|
| 75 |
+
nn.Linear(self.global_ctx, d),
|
| 76 |
+
)
|
| 77 |
+
addr_in = 2 * d
|
| 78 |
+
else:
|
| 79 |
+
addr_in = d
|
| 80 |
+
self.addr = nn.Sequential(
|
| 81 |
+
nn.Linear(addr_in, hidden),
|
| 82 |
+
nn.ELU(inplace=True),
|
| 83 |
+
nn.Linear(hidden, n_atoms),
|
| 84 |
+
)
|
| 85 |
+
if addr_init_scale != 1.0:
|
| 86 |
+
# Sharpen the softmax at init: a near-uniform start gives every
|
| 87 |
+
# atom the same gradient, so the addressing never becomes
|
| 88 |
+
# selective (and the atoms collapse). Scaling the last layer's
|
| 89 |
+
# logits starts it peaked.
|
| 90 |
+
with torch.no_grad():
|
| 91 |
+
self.addr[-1].weight.mul_(float(addr_init_scale))
|
| 92 |
+
# Residual blend: tile + s*recon with a learned per-channel scale.
|
| 93 |
+
# Near-identity start (small s) so fresh atoms don't corrupt the
|
| 94 |
+
# signal, but s can never fully close the way a mixer half could —
|
| 95 |
+
# the atoms always receive gradient.
|
| 96 |
+
self.recon_scale = nn.Parameter(
|
| 97 |
+
torch.full((channels,), float(blend_scale_init)))
|
| 98 |
+
# Deblocking: reconcile tile seams by blurring recon near grid lines.
|
| 99 |
+
# Parameter-free; on by default (inference), baked into ONNX export.
|
| 100 |
+
# Kernel is a fixed buffer so it exports as an initializer.
|
| 101 |
+
self.blur_recon = bool(deblock)
|
| 102 |
+
self.blur_radius = int(blur_radius)
|
| 103 |
+
r = self.blur_radius
|
| 104 |
+
row = torch.tensor([math.comb(2 * r, i) for i in range(2 * r + 1)],
|
| 105 |
+
dtype=torch.float32)
|
| 106 |
+
row = row / row.sum()
|
| 107 |
+
k2 = (row[:, None] * row[None, :])[None, None].expand(
|
| 108 |
+
channels, 1, -1, -1).contiguous()
|
| 109 |
+
self.register_buffer("blur_k", k2)
|
| 110 |
+
|
| 111 |
+
def _gauss_blur(self, t: torch.Tensor) -> torch.Tensor:
|
| 112 |
+
r = self.blur_radius
|
| 113 |
+
t = F.pad(t, (r, r, r, r), mode="reflect")
|
| 114 |
+
return F.conv2d(t, self.blur_k, groups=t.shape[1])
|
| 115 |
+
|
| 116 |
+
def _deblock(self, recon, b, c, nh, nw, p):
|
| 117 |
+
"""Reconcile tile seams: blur recon in image space near grid lines."""
|
| 118 |
+
img = (recon.reshape(b, nh, nw, c, p, p)
|
| 119 |
+
.permute(0, 3, 1, 4, 2, 5)
|
| 120 |
+
.reshape(b, c, nh * p, nw * p))
|
| 121 |
+
r = self.blur_radius
|
| 122 |
+
blurred = self._gauss_blur(img)
|
| 123 |
+
H, W = img.shape[-2:]
|
| 124 |
+
ih = torch.arange(H, device=img.device)
|
| 125 |
+
iw = torch.arange(W, device=img.device)
|
| 126 |
+
mh = ((ih % p) < r) | ((ih % p) >= p - r)
|
| 127 |
+
mw = ((iw % p) < r) | ((iw % p) >= p - r)
|
| 128 |
+
mask = (mh[:, None] | mw[None, :]).to(img.dtype)[None, None]
|
| 129 |
+
img = img + mask * (blurred - img)
|
| 130 |
+
return (img.reshape(b, c, nh, p, nw, p)
|
| 131 |
+
.permute(0, 2, 4, 1, 3, 5)
|
| 132 |
+
.reshape(b * nh * nw, c, p, p))
|
| 133 |
+
|
| 134 |
+
def forward(self, x):
|
| 135 |
+
b, c, h, w = x.shape
|
| 136 |
+
p = self.patch
|
| 137 |
+
if h % p or w % p:
|
| 138 |
+
raise ValueError(
|
| 139 |
+
f"PatchDictionaryBias(patch={p}) needs H,W divisible by {p}, "
|
| 140 |
+
f"got {h}x{w}. Pick p that divides the stage resolution.")
|
| 141 |
+
nh, nw = h // p, w // p
|
| 142 |
+
# Non-overlapping tiles are a pure reshape (no col2im), so this
|
| 143 |
+
# exports to ONNX with dynamic H/W.
|
| 144 |
+
tiles = (x.reshape(b, c, nh, p, nw, p)
|
| 145 |
+
.permute(0, 2, 4, 1, 3, 5)
|
| 146 |
+
.reshape(b * nh * nw, c, p, p))
|
| 147 |
+
feat = self.desc(tiles).flatten(1) # [N, d], N = b*nh*nw
|
| 148 |
+
if self.global_ctx > 0:
|
| 149 |
+
d = feat.shape[1]
|
| 150 |
+
f = feat.reshape(b, nh * nw, d) # per-image tiles
|
| 151 |
+
g = self.gctx(f.mean(dim=1)).unsqueeze(1) # [b, 1, d] global code
|
| 152 |
+
feat = torch.cat([f, g.expand(-1, nh * nw, -1)], dim=2)
|
| 153 |
+
feat = feat.reshape(b * nh * nw, 2 * d)
|
| 154 |
+
logits = self.addr(feat)
|
| 155 |
+
if self.training and self.gumbel > 0:
|
| 156 |
+
# Stochastic addressing: scale-matched Gumbel noise keeps every
|
| 157 |
+
# atom samplable so a saturated (one-hot) softmax can recover —
|
| 158 |
+
# its addressing gradient is otherwise exactly zero, a dead state.
|
| 159 |
+
sd = logits.std(dim=1, keepdim=True).clamp_min(1e-6)
|
| 160 |
+
u = torch.rand_like(logits).clamp_min(1e-20)
|
| 161 |
+
logits = logits + (-torch.log(-torch.log(u))) * sd * self.gumbel
|
| 162 |
+
wts = torch.softmax(logits, dim=1) # [N, A]
|
| 163 |
+
self._last_wts = wts.detach() # for dict_health() monitoring
|
| 164 |
+
# Batch-mean address distribution (usage) with graph intact, for the
|
| 165 |
+
# usage-entropy bonus in training. Per-tile entropy would reward
|
| 166 |
+
# uniform mush on every tile; usage entropy rewards tiles for using
|
| 167 |
+
# *different* atoms — the actual u3/d2 failure (one atom, all tiles).
|
| 168 |
+
if self.training:
|
| 169 |
+
self._last_usage = wts.mean(dim=0)
|
| 170 |
+
else:
|
| 171 |
+
self._last_usage = None
|
| 172 |
+
recon = torch.einsum("na,achw->nchw", wts, self.atoms)
|
| 173 |
+
if self.blur_recon:
|
| 174 |
+
recon = self._deblock(recon, b, c, nh, nw, p)
|
| 175 |
+
out = (tiles + recon * self.recon_scale.view(1, -1, 1, 1)
|
| 176 |
+
).reshape(b, nh, nw, c, p, p)
|
| 177 |
+
return out.permute(0, 3, 1, 4, 2, 5).reshape(b, c, nh * p, nw * p)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# ---------------------------------------------------------------------------------------------- DINOv2 backbone
|
| 181 |
+
|
| 182 |
+
def _scale(width_mult):
|
| 183 |
+
"""Channel scaler: width_mult rounded to multiples of 8 (GroupNorm-safe)."""
|
| 184 |
+
w = float(width_mult)
|
| 185 |
+
|
| 186 |
+
def C(n):
|
| 187 |
+
return max(8, int(round(n * w / 8.0) * 8))
|
| 188 |
+
|
| 189 |
+
return C
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class DinoEncoder(nn.Module):
|
| 193 |
+
"""Frozen DINOv2 ViT-S/14 trunk with four intermediate block outputs tapped.
|
| 194 |
+
|
| 195 |
+
Replaces the MobileNetV2 trunk (2026-11-14). Converts the pipeline's
|
| 196 |
+
[-1, 1] input to ImageNet-normalised [0, 1] (the statistics DINOv2 was
|
| 197 |
+
trained with) and returns the patch tokens of four blocks as
|
| 198 |
+
[B, 384, H/14, W/14] maps. It never resizes: H and W must be multiples of
|
| 199 |
+
the 14px patch size (the pipeline runs at 448 = 14*32, a 32x32 grid, which
|
| 200 |
+
the UNet's /32 pyramid also divides; the position embedding is
|
| 201 |
+
interpolated by the model). Taps are the outputs of blocks 2/5/8/11 (the Depth Anything / DPT
|
| 202 |
+
choice for ViT-S), each passed through the final LayerNorm as DINOv2's own
|
| 203 |
+
`get_intermediate_layers(norm=True)` does. The class token is dropped.
|
| 204 |
+
Grouping/projection onto the UNet's pyramid is DinoProjector's job.
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
MODEL = "facebook/dinov2-small"
|
| 208 |
+
PATCH = 14
|
| 209 |
+
DIM = 384
|
| 210 |
+
TAPS = (3, 6, 9, 12) # hidden_states indices: [0] = embeddings
|
| 211 |
+
|
| 212 |
+
def __init__(self):
|
| 213 |
+
super().__init__()
|
| 214 |
+
from transformers import Dinov2Config, Dinov2Model
|
| 215 |
+
mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
|
| 216 |
+
std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
|
| 217 |
+
self.register_buffer("shift", 1.0 - 2.0 * mean) # (1 - 2*mean)
|
| 218 |
+
self.register_buffer("scale", 1.0 / (2.0 * std)) # 1/(2*std)
|
| 219 |
+
self.vit = Dinov2Model(Dinov2Config.from_pretrained(self.MODEL)) # config only: the checkpoint has the weights
|
| 220 |
+
for p in self.vit.parameters():
|
| 221 |
+
p.requires_grad = False
|
| 222 |
+
self.vit.eval()
|
| 223 |
+
|
| 224 |
+
def train(self, mode=True):
|
| 225 |
+
"""Keep the frozen trunk in eval (no dropout / drop-path) regardless
|
| 226 |
+
of the parent's mode."""
|
| 227 |
+
super().train(mode)
|
| 228 |
+
self.vit.eval()
|
| 229 |
+
return self
|
| 230 |
+
|
| 231 |
+
def reset_pretrained(self):
|
| 232 |
+
"""Restore the trunk to the pristine pretrained weights."""
|
| 233 |
+
from transformers import Dinov2Model
|
| 234 |
+
raise NotImplementedError('standalone build: weights come from the checkpoint')
|
| 235 |
+
|
| 236 |
+
def forward(self, x):
|
| 237 |
+
B, _, H, W = x.shape
|
| 238 |
+
p = self.PATCH
|
| 239 |
+
if H % p or W % p:
|
| 240 |
+
raise ValueError(
|
| 241 |
+
f"DINOv2 needs H and W divisible by {p} (the UNet needs 32, so "
|
| 242 |
+
f"multiples of 224: 224, 448, 672); got {H}x{W}. The trunk "
|
| 243 |
+
f"does not resize.")
|
| 244 |
+
with torch.no_grad(): # frozen trunk: no graph needed
|
| 245 |
+
z = (x + self.shift) * self.scale
|
| 246 |
+
hs = self.vit(pixel_values=z, output_hidden_states=True).hidden_states
|
| 247 |
+
feats = [self.vit.layernorm(hs[i])[:, 1:] for i in self.TAPS]
|
| 248 |
+
gh, gw = H // p, W // p
|
| 249 |
+
return [f.transpose(1, 2).reshape(B, self.DIM, gh, gw) for f in feats]
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class DinoProjector(nn.Module):
|
| 253 |
+
"""Project the DINOv2 token maps onto the UNet's five-level pyramid.
|
| 254 |
+
|
| 255 |
+
All four taps are concatenated at token resolution and 1x1-projected once
|
| 256 |
+
per level (cheap: the projection runs on the 28x28 grid), then bilinearly
|
| 257 |
+
resized to H/2, H/4, H/8, H/16, H/32. The output channel counts match what
|
| 258 |
+
the decoder skips expect (m0..m3 -> 32/24/32/96, m4 -> C(96)), so the
|
| 259 |
+
decoder is unchanged. The high-resolution levels are smooth by
|
| 260 |
+
construction (the ViT sees 14px patches); the vanilla UNet encoder
|
| 261 |
+
supplies the detail. Small init (output ~10% of input scale) so the trunk's
|
| 262 |
+
contribution starts quiet and grows, like the dict blend scale.
|
| 263 |
+
"""
|
| 264 |
+
|
| 265 |
+
LEVELS = ("m0", "m1", "m2", "m3", "m4") # strides 2, 4, 8, 16, 32
|
| 266 |
+
|
| 267 |
+
def __init__(self, width_mult=1.0, init_scale=0.1,
|
| 268 |
+
dim=DinoEncoder.DIM, n_taps=len(DinoEncoder.TAPS)):
|
| 269 |
+
super().__init__()
|
| 270 |
+
C = _scale(width_mult)
|
| 271 |
+
out_ch = {"m0": 32, "m1": 24, "m2": 32, "m3": 96, "m4": C(96)}
|
| 272 |
+
self.projs = nn.ModuleDict({
|
| 273 |
+
k: nn.Conv2d(dim * n_taps, out_ch[k], 1, bias=True)
|
| 274 |
+
for k in self.LEVELS})
|
| 275 |
+
for conv in self.projs.values():
|
| 276 |
+
nn.init.normal_(conv.weight,
|
| 277 |
+
std=float(init_scale) / math.sqrt(conv.in_channels))
|
| 278 |
+
nn.init.zeros_(conv.bias)
|
| 279 |
+
|
| 280 |
+
def forward(self, feats, size):
|
| 281 |
+
"""`feats` = DinoEncoder output, `size` = (H, W) of the model input."""
|
| 282 |
+
H, W = size
|
| 283 |
+
z = torch.cat(feats, dim=1)
|
| 284 |
+
out = []
|
| 285 |
+
for i, k in enumerate(self.LEVELS):
|
| 286 |
+
s = 2 ** (i + 1)
|
| 287 |
+
out.append(F.interpolate(self.projs[k](z),
|
| 288 |
+
size=(-(-H // s), -(-W // s)),
|
| 289 |
+
mode="bilinear", align_corners=False))
|
| 290 |
+
return out
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
# ---------------------------------------------------------------------------------------------- ShadeNet-6 parts
|
| 294 |
+
import math
|
| 295 |
+
|
| 296 |
+
import torch
|
| 297 |
+
import torch.nn as nn
|
| 298 |
+
import torch.nn.functional as F
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
PATCH = 16 # side of the pre-refiner's patches
|
| 302 |
+
MAP_CH = 7 # albedo 0:3 | depth 3:4 | normal 4:7
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def count_params(m: nn.Module, trainable_only: bool = False) -> int:
|
| 306 |
+
return sum(p.numel() for p in m.parameters() if p.requires_grad or not trainable_only)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
# --------------------------------------------------------------------------- helpers
|
| 310 |
+
|
| 311 |
+
def label_mask(y: torch.Tensor) -> torch.Tensor:
|
| 312 |
+
"""1 = labelled. Albedo and normal use the -1 sentinel for invalid pixels; depth is
|
| 313 |
+
exempt (its nearest ~2% is clipped to 0, which the threshold would drop)."""
|
| 314 |
+
m = (y > -0.99).float()
|
| 315 |
+
m[:, 3:4] = 1.0
|
| 316 |
+
return m
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
# --------------------------------------------------------------------------- pre-refiner
|
| 320 |
+
|
| 321 |
+
class PreRefiner(nn.Module):
|
| 322 |
+
"""Dense network on 16x16 patches. The photo [B, 3, H, W] is cut into non-overlapping
|
| 323 |
+
patch x patch tiles; each tile is flattened (3*16*16 = 768 numbers), passed through a few
|
| 324 |
+
fully connected layers (shared by every tile) and comes out as 7*16*16 = 1792 numbers,
|
| 325 |
+
reshaped to a 16x16x7 patch of maps; the patches are put back where they came from. Output
|
| 326 |
+
through tanh, so the maps stay in [-1, 1]. The last layer starts small, so an untrained
|
| 327 |
+
pre-refiner outputs about 0 everywhere. H and W must be multiples of the patch size."""
|
| 328 |
+
|
| 329 |
+
def __init__(self, patch: int = PATCH, in_ch: int = 3, out_ch: int = MAP_CH,
|
| 330 |
+
hidden=(128, 128, 128)):
|
| 331 |
+
super().__init__()
|
| 332 |
+
self.patch, self.in_ch, self.out_ch = int(patch), int(in_ch), int(out_ch)
|
| 333 |
+
dims = [self.in_ch * self.patch ** 2, *[int(h) for h in hidden],
|
| 334 |
+
self.out_ch * self.patch ** 2]
|
| 335 |
+
layers = []
|
| 336 |
+
for i in range(len(dims) - 1):
|
| 337 |
+
layers.append(nn.Linear(dims[i], dims[i + 1]))
|
| 338 |
+
if i < len(dims) - 2:
|
| 339 |
+
layers.append(nn.GELU())
|
| 340 |
+
self.net = nn.Sequential(*layers)
|
| 341 |
+
last = layers[-1]
|
| 342 |
+
nn.init.normal_(last.weight, std=0.01)
|
| 343 |
+
nn.init.zeros_(last.bias)
|
| 344 |
+
|
| 345 |
+
def forward(self, photo: torch.Tensor) -> torch.Tensor:
|
| 346 |
+
"""`photo` [B, 3, H, W] in [-1, 1] -> maps [B, 7, H, W]."""
|
| 347 |
+
b, c, h, w = photo.shape
|
| 348 |
+
p = self.patch
|
| 349 |
+
if h % p or w % p:
|
| 350 |
+
raise ValueError(f"PreRefiner needs H and W to be multiples of {p}, got {h}x{w}")
|
| 351 |
+
gh, gw = h // p, w // p
|
| 352 |
+
x = photo.reshape(b, c, gh, p, gw, p).permute(0, 2, 4, 1, 3, 5).reshape(b * gh * gw, c * p * p)
|
| 353 |
+
y = torch.tanh(self.net(x))
|
| 354 |
+
return (y.reshape(b, gh, gw, self.out_ch, p, p).permute(0, 3, 1, 4, 2, 5)
|
| 355 |
+
.reshape(b, self.out_ch, h, w))
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
# --------------------------------------------------------------------------- post-refiner
|
| 359 |
+
|
| 360 |
+
class PostRefiner(nn.Module):
|
| 361 |
+
"""Dense patch network after the main model, built like the pre-refiner: the image is cut
|
| 362 |
+
into non-overlapping 16x16 patches (one aligned grid), the same small fully connected
|
| 363 |
+
network runs on every patch (shared weights) and the patches are put back. Its input per
|
| 364 |
+
patch is the incoming maps (7 channels) plus the photo's luminance (1 channel); its output
|
| 365 |
+
is a residual added to the maps. The last layer starts at zero, so an untrained
|
| 366 |
+
post-refiner is the identity. H and W must be multiples of the patch size."""
|
| 367 |
+
|
| 368 |
+
def __init__(self, patch: int = PATCH, hidden=(48, 48), map_ch: int = MAP_CH):
|
| 369 |
+
super().__init__()
|
| 370 |
+
self.patch, self.map_ch = int(patch), int(map_ch)
|
| 371 |
+
dims = [(self.map_ch + 1) * self.patch ** 2, *[int(h) for h in hidden],
|
| 372 |
+
self.map_ch * self.patch ** 2]
|
| 373 |
+
layers = []
|
| 374 |
+
for i in range(len(dims) - 1):
|
| 375 |
+
layers.append(nn.Linear(dims[i], dims[i + 1]))
|
| 376 |
+
if i < len(dims) - 2:
|
| 377 |
+
layers.append(nn.GELU())
|
| 378 |
+
self.net = nn.Sequential(*layers)
|
| 379 |
+
nn.init.zeros_(layers[-1].weight)
|
| 380 |
+
nn.init.zeros_(layers[-1].bias)
|
| 381 |
+
|
| 382 |
+
def _patches(self, x: torch.Tensor) -> torch.Tensor:
|
| 383 |
+
b, c, h, w = x.shape
|
| 384 |
+
p = self.patch
|
| 385 |
+
if h % p or w % p:
|
| 386 |
+
raise ValueError(f"PostRefiner needs H and W to be multiples of {p}, got {h}x{w}")
|
| 387 |
+
gh, gw = h // p, w // p
|
| 388 |
+
t = x.reshape(b, c, gh, p, gw, p).permute(0, 2, 4, 1, 3, 5).reshape(b * gh * gw, c * p * p)
|
| 389 |
+
return (self.net(t).reshape(b, gh, gw, self.map_ch, p, p).permute(0, 3, 1, 4, 2, 5)
|
| 390 |
+
.reshape(b, self.map_ch, h, w))
|
| 391 |
+
|
| 392 |
+
def forward(self, photo: torch.Tensor, maps: torch.Tensor) -> torch.Tensor:
|
| 393 |
+
"""`photo` [B, 3, H, W] in [-1, 1], `maps` [B, 7, H, W] in [-1, 1] -> refined maps."""
|
| 394 |
+
luma = 0.299 * photo[:, 0:1] + 0.587 * photo[:, 1:2] + 0.114 * photo[:, 2:3]
|
| 395 |
+
x = torch.cat([maps, luma], 1)
|
| 396 |
+
return maps + self._patches(x)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
# --------------------------------------------------------------------------- trunk
|
| 400 |
+
|
| 401 |
+
class TinyTrunk(nn.Module):
|
| 402 |
+
"""MobileNetV3-small (ImageNet) feature extractor, classifier and the last 1x1 expansion
|
| 403 |
+
dropped. Returns five maps at strides 2, 4, 8, 16, 32 with 16, 16, 24, 48, 96 channels.
|
| 404 |
+
|
| 405 |
+
Input is the photo in [-1, 1]; ImageNet normalisation is applied inside. With
|
| 406 |
+
`bn_eval` the BatchNorm layers keep their pretrained statistics (small batches)."""
|
| 407 |
+
|
| 408 |
+
TAPS = (0, 1, 3, 8, 11) # indices into torchvision's `features`
|
| 409 |
+
CH = (16, 16, 24, 48, 96)
|
| 410 |
+
|
| 411 |
+
def __init__(self, pretrained: bool = True, bn_eval: bool = True):
|
| 412 |
+
super().__init__()
|
| 413 |
+
from torchvision.models import MobileNet_V3_Small_Weights, mobilenet_v3_small
|
| 414 |
+
weights = MobileNet_V3_Small_Weights.IMAGENET1K_V1 if pretrained else None
|
| 415 |
+
self.features = mobilenet_v3_small(weights=weights).features[:12]
|
| 416 |
+
self.bn_eval = bool(bn_eval)
|
| 417 |
+
self.frozen = False
|
| 418 |
+
self.register_buffer("mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
|
| 419 |
+
self.register_buffer("std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
|
| 420 |
+
|
| 421 |
+
def freeze(self):
|
| 422 |
+
"""No gradients, eval mode always (BatchNorm included), forward without autograd."""
|
| 423 |
+
self.frozen = True
|
| 424 |
+
for p in self.parameters():
|
| 425 |
+
p.requires_grad = False
|
| 426 |
+
self.eval()
|
| 427 |
+
return self
|
| 428 |
+
|
| 429 |
+
def train(self, mode: bool = True):
|
| 430 |
+
super().train(mode and not self.frozen)
|
| 431 |
+
if self.bn_eval:
|
| 432 |
+
for m in self.modules():
|
| 433 |
+
if isinstance(m, nn.BatchNorm2d):
|
| 434 |
+
m.eval()
|
| 435 |
+
return self
|
| 436 |
+
|
| 437 |
+
def reset_imagenet(self):
|
| 438 |
+
"""Put the factory (ImageNet) weights and BatchNorm statistics back."""
|
| 439 |
+
from torchvision.models import MobileNet_V3_Small_Weights, mobilenet_v3_small
|
| 440 |
+
ref = mobilenet_v3_small(weights=MobileNet_V3_Small_Weights.IMAGENET1K_V1).features[:12]
|
| 441 |
+
self.features.load_state_dict(ref.state_dict())
|
| 442 |
+
return self
|
| 443 |
+
|
| 444 |
+
def _force_eval(self):
|
| 445 |
+
"""Enforced inside forward: Lightning restores each module's saved train/eval flag after
|
| 446 |
+
its sanity check, which silently put the BatchNorm layers back into train mode (their
|
| 447 |
+
statistics then drifted every step, even when the weights were frozen)."""
|
| 448 |
+
if self.frozen:
|
| 449 |
+
for m in self.modules():
|
| 450 |
+
m.training = False
|
| 451 |
+
elif self.bn_eval:
|
| 452 |
+
for m in self.modules():
|
| 453 |
+
if isinstance(m, nn.BatchNorm2d):
|
| 454 |
+
m.training = False
|
| 455 |
+
|
| 456 |
+
def forward(self, photo: torch.Tensor):
|
| 457 |
+
self._force_eval()
|
| 458 |
+
x = ((photo * 0.5 + 0.5) - self.mean) / self.std
|
| 459 |
+
outs = []
|
| 460 |
+
with torch.set_grad_enabled(torch.is_grad_enabled() and not self.frozen):
|
| 461 |
+
for i, blk in enumerate(self.features):
|
| 462 |
+
x = blk(x)
|
| 463 |
+
if i in self.TAPS:
|
| 464 |
+
outs.append(x)
|
| 465 |
+
return outs
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
# --------------------------------------------------------------------------- decoder blocks
|
| 469 |
+
|
| 470 |
+
def _gn(c: int) -> nn.GroupNorm:
|
| 471 |
+
return nn.GroupNorm(8 if c % 8 == 0 else 1, c)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
class DSBlock(nn.Module):
|
| 475 |
+
"""Depthwise 3x3 -> pointwise 1x1 -> GroupNorm -> GELU, residual when widths match."""
|
| 476 |
+
|
| 477 |
+
def __init__(self, cin: int, cout: int | None = None, dilation: int = 1):
|
| 478 |
+
super().__init__()
|
| 479 |
+
cout = cout or cin
|
| 480 |
+
self.dw = nn.Conv2d(cin, cin, 3, padding=dilation, dilation=dilation,
|
| 481 |
+
groups=cin, bias=False)
|
| 482 |
+
self.pw = nn.Conv2d(cin, cout, 1, bias=False)
|
| 483 |
+
self.norm = _gn(cout)
|
| 484 |
+
self.act = nn.GELU()
|
| 485 |
+
self.skip = cin == cout
|
| 486 |
+
|
| 487 |
+
def forward(self, x):
|
| 488 |
+
y = self.act(self.norm(self.pw(self.dw(x))))
|
| 489 |
+
return x + y if self.skip else y
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
class Context(nn.Module):
|
| 493 |
+
"""Global context at the coarsest level (stands in for a ViT's global attention): a
|
| 494 |
+
pooled-vector term added everywhere, then dilated depthwise-separable blocks."""
|
| 495 |
+
|
| 496 |
+
def __init__(self, c: int, dilations=(1, 2, 4)):
|
| 497 |
+
super().__init__()
|
| 498 |
+
self.glob = nn.Sequential(nn.Linear(c, c), nn.GELU())
|
| 499 |
+
self.blocks = nn.ModuleList(DSBlock(c, c, d) for d in dilations)
|
| 500 |
+
|
| 501 |
+
def forward(self, x):
|
| 502 |
+
x = x + self.glob(x.mean(dim=(2, 3)))[:, :, None, None]
|
| 503 |
+
for blk in self.blocks:
|
| 504 |
+
x = blk(x)
|
| 505 |
+
return x
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
class UpStage(nn.Module):
|
| 509 |
+
"""Upsample the coarser features, fuse them with a trunk skip (plus the prior pooled to
|
| 510 |
+
this level), `blocks` depthwise-separable blocks."""
|
| 511 |
+
|
| 512 |
+
def __init__(self, c_prev: int, c_skip: int, c_out: int, prior_ch: int = MAP_CH, blocks: int = 1):
|
| 513 |
+
super().__init__()
|
| 514 |
+
self.skip = nn.Conv2d(c_skip + prior_ch, c_out, 1, bias=False)
|
| 515 |
+
self.fuse = nn.Conv2d(c_prev + c_out, c_out, 1, bias=False)
|
| 516 |
+
self.norm = _gn(c_out)
|
| 517 |
+
self.act = nn.GELU()
|
| 518 |
+
self.block = DSBlock(c_out) if blocks == 1 else nn.Sequential(*[DSBlock(c_out) for _ in range(blocks)])
|
| 519 |
+
|
| 520 |
+
def forward(self, u, skip, prior):
|
| 521 |
+
size = skip.shape[-2:]
|
| 522 |
+
u = F.interpolate(u, size=size, mode="bilinear", align_corners=False)
|
| 523 |
+
p = F.adaptive_avg_pool2d(prior, size)
|
| 524 |
+
s = self.skip(torch.cat([skip, p], 1))
|
| 525 |
+
return self.block(self.act(self.norm(self.fuse(torch.cat([u, s], 1)))))
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
class ScaledProjector(nn.Module):
|
| 529 |
+
"""DinoProjector with free output widths: the four concatenated ViT taps (4 x dim channels) are
|
| 530 |
+
1x1-projected once per pyramid level (strides 2, 4, 8, 16, 32) and bilinearly resized. Same key
|
| 531 |
+
layout as `DinoProjector` (`projs.m0` .. `projs.m4`) and the same small init."""
|
| 532 |
+
|
| 533 |
+
LEVELS = ("m0", "m1", "m2", "m3", "m4")
|
| 534 |
+
|
| 535 |
+
def __init__(self, dim: int, ch, n_taps: int = 4, init_scale: float = 0.1):
|
| 536 |
+
super().__init__()
|
| 537 |
+
self.projs = nn.ModuleDict({k: nn.Conv2d(dim * n_taps, int(c), 1, bias=True)
|
| 538 |
+
for k, c in zip(self.LEVELS, ch)})
|
| 539 |
+
for conv in self.projs.values():
|
| 540 |
+
nn.init.normal_(conv.weight, std=float(init_scale) / math.sqrt(conv.in_channels))
|
| 541 |
+
nn.init.zeros_(conv.bias)
|
| 542 |
+
|
| 543 |
+
def forward(self, feats, size):
|
| 544 |
+
H, W = size
|
| 545 |
+
z = torch.cat(feats, dim=1)
|
| 546 |
+
out = []
|
| 547 |
+
for i, k in enumerate(self.LEVELS):
|
| 548 |
+
s = 2 ** (i + 1)
|
| 549 |
+
out.append(F.interpolate(self.projs[k](z), size=(-(-H // s), -(-W // s)),
|
| 550 |
+
mode="bilinear", align_corners=False))
|
| 551 |
+
return out
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
class DinoTrunk(nn.Module):
|
| 555 |
+
"""The ShadeNet-5 backbone: a FROZEN DINOv2 ViT plus a 1x1 projector.
|
| 556 |
+
|
| 557 |
+
`size="small"` is the ViT-S/14 of ShadeNet-5 (22.1M parameters, 384 channels, `DinoProjector`, maps onto
|
| 558 |
+
32/24/32/96/96 channels). `size="base"` is the ViT-B/14 (`facebook/dinov2-base`, about 86.6M parameters,
|
| 559 |
+
768 channels) with a `ScaledProjector` whose widths are `ch`. Either way the ViT (always loaded pretrained)
|
| 560 |
+
reads the photo once, four of its blocks are tapped and concatenated, and only the projector trains. The
|
| 561 |
+
ViT never resizes, so H and W must be multiples of 14 (and of 32 for the decoder): 224, 448, ...
|
| 562 |
+
Needs `transformers`."""
|
| 563 |
+
|
| 564 |
+
CH = (32, 24, 32, 96, 96)
|
| 565 |
+
|
| 566 |
+
def __init__(self, pretrained: bool = True, bn_eval: bool = True, size: str = "small", ch=None):
|
| 567 |
+
super().__init__()
|
| 568 |
+
if size == "small":
|
| 569 |
+
self.encoder = DinoEncoder()
|
| 570 |
+
self.proj = DinoProjector(1.0)
|
| 571 |
+
self.CH = DinoTrunk.CH
|
| 572 |
+
elif size == "base":
|
| 573 |
+
class _DinoBase(DinoEncoder):
|
| 574 |
+
MODEL = "facebook/dinov2-base"
|
| 575 |
+
DIM = 768
|
| 576 |
+
ch = tuple(int(c) for c in (ch or (64, 96, 160, 256, 320)))
|
| 577 |
+
self.encoder = _DinoBase()
|
| 578 |
+
self.proj = ScaledProjector(768, ch)
|
| 579 |
+
self.CH = ch
|
| 580 |
+
else:
|
| 581 |
+
raise ValueError(f"size must be 'small' or 'base', got {size!r}")
|
| 582 |
+
self.freeze()
|
| 583 |
+
|
| 584 |
+
def freeze(self):
|
| 585 |
+
"""The ViT never trains and stays in eval mode; the projector keeps learning."""
|
| 586 |
+
for p in self.encoder.parameters():
|
| 587 |
+
p.requires_grad = False
|
| 588 |
+
self.encoder.eval()
|
| 589 |
+
return self
|
| 590 |
+
|
| 591 |
+
def forward(self, photo: torch.Tensor):
|
| 592 |
+
self.encoder.training = False # enforced here, as in TinyTrunk: Lightning's mode restore
|
| 593 |
+
self.encoder.vit.eval() # after its sanity check would otherwise flip it back
|
| 594 |
+
return self.proj(self.encoder(photo), photo.shape[-2:])
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
class DetailEncoder(nn.Module):
|
| 598 |
+
"""Convolutional high-resolution path. DINOv2 sees the photo in 14-pixel patches, so its maps are smooth;
|
| 599 |
+
this encoder reads [photo | prior] at full resolution and returns features at strides 2, 4, 8, 16
|
| 600 |
+
(widths `widths`), which the decoder concatenates with the backbone's maps at the same strides (the role of
|
| 601 |
+
ShadeNet-5's UNet encoder)."""
|
| 602 |
+
|
| 603 |
+
def __init__(self, in_ch: int, widths=(48, 96, 192, 320), blocks: int = 2):
|
| 604 |
+
super().__init__()
|
| 605 |
+
w = [int(c) for c in widths]
|
| 606 |
+
self.stem = nn.Sequential(nn.Conv2d(in_ch, w[0], 3, stride=2, padding=1, bias=False), _gn(w[0]), nn.GELU(),
|
| 607 |
+
*[DSBlock(w[0]) for _ in range(blocks)])
|
| 608 |
+
self.downs = nn.ModuleList(
|
| 609 |
+
nn.Sequential(nn.Conv2d(w[i - 1], w[i], 3, stride=2, padding=1, bias=False), _gn(w[i]), nn.GELU(),
|
| 610 |
+
*[DSBlock(w[i]) for _ in range(blocks)])
|
| 611 |
+
for i in range(1, len(w)))
|
| 612 |
+
|
| 613 |
+
def forward(self, x):
|
| 614 |
+
feats = [self.stem(x)]
|
| 615 |
+
for d in self.downs:
|
| 616 |
+
feats.append(d(feats[-1]))
|
| 617 |
+
return feats # strides 2, 4, 8, 16
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
class Shade2M(nn.Module):
|
| 621 |
+
"""Main model: (photo, prior maps) -> prior + residual.
|
| 622 |
+
|
| 623 |
+
The trunk sees only the photo: a frozen MobileNetV3-small (`trunk="mobilenet"`), the frozen DINOv2
|
| 624 |
+
ViT-S/14 of ShadeNet-5 (`trunk="dino"`) or a frozen DINOv2 ViT-B/14 (`trunk="dino-base"`, about 100M
|
| 625 |
+
parameters in total); the DINOv2 trunks need H and W to be multiples of 14 as well. `enc` adds a
|
| 626 |
+
convolutional detail encoder (widths at strides 2, 4, 8, 16) whose maps are concatenated with the trunk's;
|
| 627 |
+
`blocks` is the number of depthwise-separable blocks per decoder level. The prior enters the
|
| 628 |
+
full-resolution stem, every decoder level (pooled to that level) and the context block (pooled to
|
| 629 |
+
stride 32). H and W must be multiples of 32."""
|
| 630 |
+
|
| 631 |
+
def __init__(self, dec=(192, 128, 96, 64, 48), full: int = 32,
|
| 632 |
+
pretrained: bool = True, bn_eval: bool = True, trunk: str = "mobilenet",
|
| 633 |
+
proj_ch=None, enc=None, blocks: int = 1,
|
| 634 |
+
dict_sites=(), dict_patch: int = 8, dict_atoms: int = 32, dict_hidden: int = 64,
|
| 635 |
+
dict_repeat: int = 1, dict_global_ctx: int = 64, dict_init_std: float = 0.02,
|
| 636 |
+
dict_addr_init_scale: float = 16.0, dict_blend_scale_init: float = 1.0):
|
| 637 |
+
super().__init__()
|
| 638 |
+
c32, c16, c8, c4, c2 = (int(c) for c in dec)
|
| 639 |
+
full = int(full)
|
| 640 |
+
if trunk == "mobilenet":
|
| 641 |
+
self.trunk = TinyTrunk(pretrained=pretrained, bn_eval=bn_eval)
|
| 642 |
+
elif trunk == "dino":
|
| 643 |
+
self.trunk = DinoTrunk(pretrained=pretrained, bn_eval=bn_eval)
|
| 644 |
+
elif trunk == "dino-base":
|
| 645 |
+
self.trunk = DinoTrunk(pretrained=pretrained, bn_eval=bn_eval, size="base", ch=proj_ch)
|
| 646 |
+
else:
|
| 647 |
+
raise ValueError(f"trunk must be 'mobilenet', 'dino' or 'dino-base', got {trunk!r}")
|
| 648 |
+
self.detail = DetailEncoder(3 + MAP_CH, enc, blocks) if enc else None
|
| 649 |
+
e = tuple(int(c) for c in enc) if enc else (0, 0, 0, 0)
|
| 650 |
+
t = tuple(self.trunk.CH) # backbone channels at strides 2, 4, 8, 16, 32
|
| 651 |
+
self.ctx_in = nn.Sequential(nn.Conv2d(t[4] + MAP_CH, c32, 1, bias=False),
|
| 652 |
+
_gn(c32), nn.GELU())
|
| 653 |
+
self.context = Context(c32)
|
| 654 |
+
self.up16 = UpStage(c32, t[3] + e[3], c16, blocks=blocks)
|
| 655 |
+
self.up8 = UpStage(c16, t[2] + e[2], c8, blocks=blocks)
|
| 656 |
+
self.up4 = UpStage(c8, t[1] + e[1], c4, blocks=blocks)
|
| 657 |
+
self.up2 = UpStage(c4, t[0] + e[0], c2, blocks=blocks)
|
| 658 |
+
self.stem = nn.Sequential(nn.Conv2d(3 + MAP_CH, full, 3, padding=1, bias=False),
|
| 659 |
+
_gn(full), nn.GELU(), DSBlock(full))
|
| 660 |
+
self.fuse1 = nn.Sequential(nn.Conv2d(c2 + full, full, 1, bias=False),
|
| 661 |
+
_gn(full), nn.GELU())
|
| 662 |
+
self.block1 = DSBlock(full)
|
| 663 |
+
# Patch dictionaries (soft addressing over learned atoms, `tile + s * recon`) at the
|
| 664 |
+
# model's input ([photo | prior], 10 channels, ahead of the stem) and output (the final
|
| 665 |
+
# full-resolution features, ahead of the head). Each site is applied `dict_repeat` times.
|
| 666 |
+
chans = {"in": 3 + MAP_CH, "out": full}
|
| 667 |
+
bad = [s for s in dict_sites if s not in chans]
|
| 668 |
+
if bad:
|
| 669 |
+
raise ValueError(f"dict_sites must be in {sorted(chans)}, got {bad}")
|
| 670 |
+
self.dict_repeat = max(1, int(dict_repeat))
|
| 671 |
+
self.dicts = nn.ModuleDict({
|
| 672 |
+
s: PatchDictionaryBias(
|
| 673 |
+
channels=chans[s], patch=int(dict_patch), n_atoms=int(dict_atoms),
|
| 674 |
+
hidden=int(dict_hidden), deblock=False,
|
| 675 |
+
blend_scale_init=float(dict_blend_scale_init) / self.dict_repeat,
|
| 676 |
+
init_std=float(dict_init_std), init_seed=42 + 7 * i, gumbel=0.0,
|
| 677 |
+
addr_init_scale=float(dict_addr_init_scale), global_ctx=int(dict_global_ctx))
|
| 678 |
+
for i, s in enumerate(dict_sites)})
|
| 679 |
+
self.head = nn.Conv2d(full, MAP_CH, 1)
|
| 680 |
+
nn.init.zeros_(self.head.weight) # untrained = identity on the prior
|
| 681 |
+
nn.init.zeros_(self.head.bias)
|
| 682 |
+
|
| 683 |
+
def _sd(self, name: str, x: torch.Tensor) -> torch.Tensor:
|
| 684 |
+
mod = self.dicts[name] if name in self.dicts else None
|
| 685 |
+
if mod is None:
|
| 686 |
+
return x
|
| 687 |
+
for _ in range(self.dict_repeat):
|
| 688 |
+
x = mod(x)
|
| 689 |
+
return x
|
| 690 |
+
|
| 691 |
+
def forward(self, photo: torch.Tensor, prior: torch.Tensor) -> torch.Tensor:
|
| 692 |
+
h, w = photo.shape[-2:]
|
| 693 |
+
if h % 32 or w % 32:
|
| 694 |
+
raise ValueError(f"Shade2M needs H and W to be multiples of 32, got {h}x{w}")
|
| 695 |
+
x0 = self._sd("in", torch.cat([photo, prior], 1)) # [photo | prior] through the input dictionary
|
| 696 |
+
f2, f4, f8, f16, f32 = self.trunk(photo)
|
| 697 |
+
if self.detail is not None:
|
| 698 |
+
e2, e4, e8, e16 = self.detail(x0)
|
| 699 |
+
f2, f4, f8, f16 = (torch.cat([a, b], 1) for a, b in zip((f2, f4, f8, f16), (e2, e4, e8, e16)))
|
| 700 |
+
u = self.context(self.ctx_in(torch.cat([f32, F.adaptive_avg_pool2d(prior, f32.shape[-2:])], 1)))
|
| 701 |
+
u = self.up16(u, f16, prior)
|
| 702 |
+
u = self.up8(u, f8, prior)
|
| 703 |
+
u = self.up4(u, f4, prior)
|
| 704 |
+
u = self.up2(u, f2, prior)
|
| 705 |
+
u = F.interpolate(u, size=(h, w), mode="bilinear", align_corners=False)
|
| 706 |
+
s = self.stem(x0)
|
| 707 |
+
u = self.block1(self.fuse1(torch.cat([u, s], 1)))
|
| 708 |
+
return prior + self.head(self._sd("out", u))
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
# ---------------------------------------------------------------------------------------------- refiner
|
| 712 |
+
|
| 713 |
+
def _block(cin: int, cout: int) -> nn.Sequential:
|
| 714 |
+
g = 8 if cout % 8 == 0 else 1
|
| 715 |
+
return nn.Sequential(
|
| 716 |
+
nn.Conv2d(cin, cout, 3, padding=1, bias=False),
|
| 717 |
+
nn.GroupNorm(g, cout), nn.GELU(),
|
| 718 |
+
nn.Conv2d(cout, cout, 3, padding=1, bias=False),
|
| 719 |
+
nn.GroupNorm(g, cout), nn.GELU())
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
class MapRefiner(nn.Module):
|
| 723 |
+
def __init__(self, width: int = 32, levels: int = 4, photo_ch: int = 3):
|
| 724 |
+
super().__init__()
|
| 725 |
+
map_ch = 7
|
| 726 |
+
self.photo_ch, self.map_ch = photo_ch, map_ch
|
| 727 |
+
self.width, self.levels = int(width), int(levels)
|
| 728 |
+
ch = [self.width * m for m in (1, 2, 3, 4, 4, 4)[:self.levels]]
|
| 729 |
+
self.enc = nn.ModuleList()
|
| 730 |
+
cin = photo_ch + map_ch
|
| 731 |
+
for i, c in enumerate(ch):
|
| 732 |
+
self.enc.append(_block(cin, c))
|
| 733 |
+
cin = c
|
| 734 |
+
self.dec = nn.ModuleList(
|
| 735 |
+
_block(ch[i] + ch[i + 1], ch[i]) for i in range(self.levels - 1))
|
| 736 |
+
self.out = nn.Conv2d(ch[0], map_ch, 1)
|
| 737 |
+
nn.init.zeros_(self.out.weight)
|
| 738 |
+
nn.init.zeros_(self.out.bias)
|
| 739 |
+
|
| 740 |
+
def forward(self, photo: torch.Tensor, maps: torch.Tensor) -> torch.Tensor:
|
| 741 |
+
h, w = maps.shape[-2:]
|
| 742 |
+
d = 2 ** (self.levels - 1)
|
| 743 |
+
ph, pw = (-h) % d, (-w) % d # pad to a multiple of 2^(levels-1)
|
| 744 |
+
x = torch.cat([photo, maps], 1)
|
| 745 |
+
if ph or pw:
|
| 746 |
+
x = F.pad(x, (0, pw, 0, ph), mode="reflect")
|
| 747 |
+
skips = []
|
| 748 |
+
for i, blk in enumerate(self.enc):
|
| 749 |
+
x = blk(x if i == 0 else F.avg_pool2d(x, 2))
|
| 750 |
+
skips.append(x)
|
| 751 |
+
x = skips[-1]
|
| 752 |
+
for i in range(self.levels - 2, -1, -1):
|
| 753 |
+
x = F.interpolate(x, size=skips[i].shape[-2:], mode="bilinear",
|
| 754 |
+
align_corners=False)
|
| 755 |
+
x = self.dec[i](torch.cat([skips[i], x], 1))
|
| 756 |
+
res = self.out(x)[..., :h, :w]
|
| 757 |
+
return maps + res
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
# ---------------------------------------------------------------------------------------------- wrapper
|
| 761 |
+
|
| 762 |
+
class ShadeNet6(nn.Module):
|
| 763 |
+
"""ShadeNet-6 pre-refiner -> main model -> (post-refiner) -> refiner, loaded from a checkpoint.
|
| 764 |
+
|
| 765 |
+
model = ShadeNet6.from_checkpoint("shadenet6-l.ckpt", device="cuda")
|
| 766 |
+
maps = model.predict(photo) # photo [B, 3, H, W] in [-1, 1] -> maps [B, 7, H, W] in [-1, 1]
|
| 767 |
+
|
| 768 |
+
Maps: channels 0:3 albedo, 3 depth (relative, larger = farther), 4:7 normal (x right, y up, z toward the
|
| 769 |
+
viewer). H and W must be multiples of 32 (and of 14 for the DINOv2 models, so 448 for ShadeNet-6 L).
|
| 770 |
+
"""
|
| 771 |
+
|
| 772 |
+
def __init__(self, hp: dict):
|
| 773 |
+
super().__init__()
|
| 774 |
+
self.hp = hp
|
| 775 |
+
self.pre = PreRefiner(patch=PATCH, hidden=tuple(hp.get("pre_hidden", (128, 128, 128))))
|
| 776 |
+
self.main = Shade2M(
|
| 777 |
+
dec=tuple(hp.get("dec", (192, 128, 96, 64, 48))), full=hp.get("full", 32), pretrained=False,
|
| 778 |
+
trunk=hp.get("trunk", "mobilenet"), proj_ch=hp.get("proj_ch"), enc=hp.get("enc"),
|
| 779 |
+
blocks=hp.get("blocks", 1), dict_sites=tuple(hp.get("dict_sites", ())),
|
| 780 |
+
dict_patch=hp.get("dict_patch", 8), dict_atoms=hp.get("dict_atoms", 32),
|
| 781 |
+
dict_hidden=hp.get("dict_hidden", 64), dict_repeat=hp.get("dict_repeat", 1),
|
| 782 |
+
dict_global_ctx=hp.get("dict_global_ctx", 64))
|
| 783 |
+
self.refiner = MapRefiner(width=hp.get("refiner_width", 16), levels=hp.get("refiner_levels", 4))
|
| 784 |
+
post = tuple(hp.get("post_hidden", ()))
|
| 785 |
+
self.post = PostRefiner(patch=PATCH, hidden=post) if post else None
|
| 786 |
+
|
| 787 |
+
@classmethod
|
| 788 |
+
def from_checkpoint(cls, path, device="cpu"):
|
| 789 |
+
ck = torch.load(path, map_location="cpu", weights_only=False)
|
| 790 |
+
model = cls(dict(ck["hyper_parameters"]))
|
| 791 |
+
sd = {k: v for k, v in ck["state_dict"].items() if not k.startswith("disc.")}
|
| 792 |
+
if model.post is None:
|
| 793 |
+
sd = {k: v for k, v in sd.items() if not k.startswith("post.")}
|
| 794 |
+
res = model.load_state_dict(sd, strict=False)
|
| 795 |
+
# the only keys allowed to be absent are buffers recreated at construction
|
| 796 |
+
bad = [k for k in res.missing_keys if not k.endswith(("blur_k", "shift", "scale"))]
|
| 797 |
+
if bad or res.unexpected_keys:
|
| 798 |
+
raise RuntimeError(f"checkpoint does not match the model: missing {bad[:5]}, unexpected {res.unexpected_keys[:5]}")
|
| 799 |
+
return model.eval().to(device)
|
| 800 |
+
|
| 801 |
+
@torch.no_grad()
|
| 802 |
+
def predict(self, photo: torch.Tensor, upto: str = "refiner") -> torch.Tensor:
|
| 803 |
+
"""photo [B, 3, H, W] in [-1, 1] -> maps [B, 7, H, W] clamped to [-1, 1]. `upto`: pre | main | refiner."""
|
| 804 |
+
prior = self.pre(photo)
|
| 805 |
+
maps = self.main(photo, prior)
|
| 806 |
+
if upto != "main":
|
| 807 |
+
if self.post is not None:
|
| 808 |
+
maps = self.post(photo, maps.clamp(-1.0, 1.0))
|
| 809 |
+
maps = self.refiner(photo, maps.clamp(-1.0, 1.0))
|
| 810 |
+
return maps.clamp(-1.0, 1.0)
|
| 811 |
+
|
| 812 |
+
def count_parameters(self) -> int:
|
| 813 |
+
return sum(p.numel() for p in self.parameters())
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers
|
| 3 |
+
pillow
|
| 4 |
+
numpy
|