Commit ·
12510fb
0
Parent(s):
Initial
Browse files- .gitattributes +4 -0
- README.md +110 -0
- app.py +118 -0
- checkpoints/last.ckpt +3 -0
- config.py +13 -0
- inference.py +65 -0
- inference_utils.py +221 -0
- layers.py +19 -0
- model.py +266 -0
- onnx/model_mode0.onnx +3 -0
- onnx/model_mode0_quantized.onnx +3 -0
- onnx/model_mode1.onnx +3 -0
- onnx/model_mode1_quantized.onnx +3 -0
- requirements.txt +5 -0
.gitattributes
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-nc-4.0
|
| 3 |
+
library_name: pytorch
|
| 4 |
+
tags:
|
| 5 |
+
- inverse-rendering
|
| 6 |
+
- image-decomposition
|
| 7 |
+
- basecolor
|
| 8 |
+
- normal-map
|
| 9 |
+
- pbr
|
| 10 |
+
- material-estimation
|
| 11 |
+
- shadenet
|
| 12 |
+
pipeline_tag: image-to-image
|
| 13 |
+
datasets:
|
| 14 |
+
- flickr8k
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
# ShadeNet 28M
|
| 18 |
+
|
| 19 |
+
A lightweight inverse rendering model that decomposes RGB images into PBR material maps (basecolor, normal, roughness/metallic/depth) and reconstructs them back to RGB.
|
| 20 |
+
|
| 21 |
+
## Examples
|
| 22 |
+
|
| 23 |
+

|
| 24 |
+

|
| 25 |
+

|
| 26 |
+
|
| 27 |
+
*Each result shows: Input (blue) → Basecolor, Normal, Depth, Roughness, Metallic (green) → Recon RGB (orange)*
|
| 28 |
+
|
| 29 |
+
## Architecture
|
| 30 |
+
|
| 31 |
+
The model is a **MobileNetUNet (27.9M params)** with:
|
| 32 |
+
- **MobileNetV2 backbone** (frozen except last 8 layers) for feature extraction
|
| 33 |
+
- **Parallel Encoder** for additional learned features
|
| 34 |
+
- **UNet-style decoder** with skip connections, channel attention, and spatial attention
|
| 35 |
+
- **Dual mode** forward pass:
|
| 36 |
+
- **Mode 0**: RGB → Inverse Maps (basecolor, normal, roughness/metallic/depth)
|
| 37 |
+
- **Mode 1**: Inverse Maps → RGB reconstruction
|
| 38 |
+
|
| 39 |
+
## Output Maps
|
| 40 |
+
|
| 41 |
+
| Map | Channels | Description |
|
| 42 |
+
|-----|----------|-------------|
|
| 43 |
+
| **Basecolor** | 3 | Albedo / diffuse color |
|
| 44 |
+
| **Normal** | 3 | Surface normals (tangent space) |
|
| 45 |
+
| **Roughness** | 1 | R channel of RMD - surface roughness |
|
| 46 |
+
| **Metallic** | 1 | G channel of RMD - metalness |
|
| 47 |
+
| **Depth** | 1 | B channel of RMD - relative depth |
|
| 48 |
+
| **RGB** | 3 | Reconstructed RGB from inverse maps |
|
| 49 |
+
|
| 50 |
+
## Files
|
| 51 |
+
|
| 52 |
+
```
|
| 53 |
+
shadenet/
|
| 54 |
+
├── app.py # Gradio Space app
|
| 55 |
+
├── inference.py # Standalone inference script (CLI)
|
| 56 |
+
├── inference_utils.py # Inference utilities (tiling, compositing)
|
| 57 |
+
├── model.py # Model architecture
|
| 58 |
+
├── layers.py # Layer components
|
| 59 |
+
├── config.py # Configuration
|
| 60 |
+
├── requirements.txt # Python dependencies
|
| 61 |
+
├── README.md # This file
|
| 62 |
+
├── checkpoints/
|
| 63 |
+
│ └── last.ckpt # PyTorch Lightning checkpoint (model weights)
|
| 64 |
+
└── onnx/
|
| 65 |
+
├── model_mode0.onnx # Mode 0 ONNX (RGB → inverse maps)
|
| 66 |
+
├── model_mode0_quantized.onnx # Quantized mode 0
|
| 67 |
+
├── model_mode1.onnx # Mode 1 ONNX (inverse maps → RGB)
|
| 68 |
+
└── model_mode1_quantized.onnx # Quantized mode 1
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
## Usage
|
| 72 |
+
|
| 73 |
+
### Gradio Space
|
| 74 |
+
|
| 75 |
+
Upload an image and click "Decompose" to see all output maps side by side.
|
| 76 |
+
|
| 77 |
+
### CLI Inference
|
| 78 |
+
|
| 79 |
+
```bash
|
| 80 |
+
pip install -r requirements.txt
|
| 81 |
+
python inference.py input.jpg --output_dir ./output
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
### ONNX Inference
|
| 85 |
+
|
| 86 |
+
The `onnx/` folder contains exported ONNX models for deployment without PyTorch:
|
| 87 |
+
|
| 88 |
+
- `model_mode0.onnx` / `model_mode0_quantized.onnx`: RGB → basecolor, normal, RMD
|
| 89 |
+
- `model_mode1.onnx` / `model_mode1_quantized.onnx`: Inverse maps → RGB
|
| 90 |
+
|
| 91 |
+
Input shape: `[1, 3, 512, 512]`, values in `[-1, 1]`
|
| 92 |
+
|
| 93 |
+
## Training
|
| 94 |
+
|
| 95 |
+
Trained on Flickr8k with paired inverse-rendered data. The model learns both forward (RGB→inverse) and reverse (inverse→RGB) mappings simultaneously using a combined L1 + MSE loss per output map.
|
| 96 |
+
|
| 97 |
+
- Optimizer: AdamW / Prodigy
|
| 98 |
+
- Image size: 512×512
|
| 99 |
+
- Precision: 16-mixed
|
| 100 |
+
- Loss weights: basecolor=1.0, normal=1.5, RMD=1.0, RGB=1.0
|
| 101 |
+
|
| 102 |
+
## Citation
|
| 103 |
+
|
| 104 |
+
```
|
| 105 |
+
@software{shadenet,
|
| 106 |
+
author = {Sachin},
|
| 107 |
+
title = {ShadeNet},
|
| 108 |
+
year = {2026},
|
| 109 |
+
}
|
| 110 |
+
```
|
app.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import gradio as gr
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
from config import CONFIG
|
| 10 |
+
from model import load_from_checkpoint, MobileNetUNet
|
| 11 |
+
from inference_utils import full_inference, make_side_by_side, tiled_inference
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
MODEL = None
|
| 15 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def load_model():
|
| 19 |
+
global MODEL
|
| 20 |
+
ckpt_path = CONFIG["checkpoint_path"]
|
| 21 |
+
if os.path.exists(ckpt_path):
|
| 22 |
+
print(f"Loading checkpoint from {ckpt_path}...")
|
| 23 |
+
MODEL = load_from_checkpoint(ckpt_path, device=DEVICE, width_mult=CONFIG["width_mult"])
|
| 24 |
+
MODEL.to(DEVICE)
|
| 25 |
+
MODEL.eval()
|
| 26 |
+
print("Model loaded successfully.")
|
| 27 |
+
else:
|
| 28 |
+
print(f"Checkpoint not found at {ckpt_path}. Using ONNX is not yet supported in this app.")
|
| 29 |
+
MODEL = None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def process_image(input_img, use_tiled, tile_overlap):
|
| 33 |
+
if MODEL is None:
|
| 34 |
+
load_model()
|
| 35 |
+
if MODEL is None:
|
| 36 |
+
raise gr.Error("No model loaded. Please ensure checkpoints/last.ckpt exists.")
|
| 37 |
+
|
| 38 |
+
img = input_img.convert("RGB")
|
| 39 |
+
|
| 40 |
+
with torch.no_grad():
|
| 41 |
+
if use_tiled:
|
| 42 |
+
inp_img, outputs = tiled_inference(
|
| 43 |
+
MODEL, img, CONFIG["image_size"], DEVICE, overlap=tile_overlap,
|
| 44 |
+
)
|
| 45 |
+
else:
|
| 46 |
+
inp_img, outputs = full_inference(MODEL, img, CONFIG["image_size"], DEVICE)
|
| 47 |
+
|
| 48 |
+
result = make_side_by_side(inp_img, outputs)
|
| 49 |
+
return result, outputs
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def run_and_save(input_img, use_tiled, tile_overlap):
|
| 53 |
+
result, outputs = process_image(input_img, use_tiled, tile_overlap)
|
| 54 |
+
|
| 55 |
+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
|
| 56 |
+
result.save(tmp.name)
|
| 57 |
+
return tmp.name
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def run_and_return_maps(input_img, use_tiled, tile_overlap):
|
| 61 |
+
result, outputs = process_image(input_img, use_tiled, tile_overlap)
|
| 62 |
+
return result, outputs.get("basecolor"), outputs.get("normal"), outputs.get("rmd"), outputs.get("rgb")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
with gr.Blocks(title="ShadeNet", theme=gr.themes.Soft()) as demo:
|
| 66 |
+
gr.Markdown(
|
| 67 |
+
"""
|
| 68 |
+
# ShadeNet
|
| 69 |
+
Lightweight inverse rendering model that decomposes an RGB image into **basecolor**, **normal**, **roughness/metallic/depth** maps,
|
| 70 |
+
then recombines them into a reconstructed RGB.
|
| 71 |
+
"""
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
with gr.Row():
|
| 75 |
+
with gr.Column():
|
| 76 |
+
input_img = gr.Image(type="pil", label="Input Image")
|
| 77 |
+
with gr.Row():
|
| 78 |
+
use_tiled = gr.Checkbox(label="Tiled Inference", value=False)
|
| 79 |
+
tile_overlap = gr.Slider(minimum=0, maximum=128, value=16, step=1, label="Tile Overlap (px)")
|
| 80 |
+
run_btn = gr.Button("Decompose", variant="primary")
|
| 81 |
+
|
| 82 |
+
with gr.Column():
|
| 83 |
+
output_img = gr.Image(type="pil", label="Side-by-Side Result")
|
| 84 |
+
|
| 85 |
+
with gr.Row():
|
| 86 |
+
gr.Markdown("### Individual Output Maps")
|
| 87 |
+
with gr.Row():
|
| 88 |
+
basecolor_out = gr.Image(type="pil", label="Basecolor")
|
| 89 |
+
normal_out = gr.Image(type="pil", label="Normal")
|
| 90 |
+
rmd_out = gr.Image(type="pil", label="RMD (R=roughness, G=metallic, B=depth)")
|
| 91 |
+
rgb_out = gr.Image(type="pil", label="Reconstructed RGB")
|
| 92 |
+
|
| 93 |
+
run_btn.click(
|
| 94 |
+
fn=run_and_return_maps,
|
| 95 |
+
inputs=[input_img, use_tiled, tile_overlap],
|
| 96 |
+
outputs=[output_img, basecolor_out, normal_out, rmd_out, rgb_out],
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
gr.Examples(
|
| 100 |
+
examples=[],
|
| 101 |
+
inputs=[input_img],
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
gr.Markdown(
|
| 105 |
+
"""
|
| 106 |
+
---
|
| 107 |
+
### Model Details
|
| 108 |
+
- **Architecture**: ShadeNet 28M — MobileNetV2 backbone + Parallel Encoder + UNet decoder with attention
|
| 109 |
+
- **Input**: RGB image (resized to 512×512 center crop)
|
| 110 |
+
- **Outputs**: Basecolor (3ch), Normal (3ch), RMD (3ch = roughness, metallic, depth), Reconstructed RGB (3ch)
|
| 111 |
+
- **ONNX models**: Available in the `onnx/` folder for CPU/edge deployment
|
| 112 |
+
"""
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
if __name__ == "__main__":
|
| 117 |
+
load_model()
|
| 118 |
+
demo.launch(server_name="0.0.0.0")
|
checkpoints/last.ckpt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d1321a98dcfa6e14d2fb0d2cda6628f8c0b6fb763ab91f81fb6c9c9fbf2cf7cd
|
| 3 |
+
size 445582883
|
config.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
CONFIG = {
|
| 4 |
+
"image_size": 512,
|
| 5 |
+
"width_mult": 2.0,
|
| 6 |
+
"device": "cuda" if torch.cuda.is_available() else "cpu",
|
| 7 |
+
"checkpoint_path": "./checkpoints/last.ckpt",
|
| 8 |
+
"onnx_dir": "./onnx",
|
| 9 |
+
"onnx_mode0": "model_mode0.onnx",
|
| 10 |
+
"onnx_mode0_quantized": "model_mode0_quantized.onnx",
|
| 11 |
+
"onnx_mode1": "model_mode1.onnx",
|
| 12 |
+
"onnx_mode1_quantized": "model_mode1_quantized.onnx",
|
| 13 |
+
}
|
inference.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import argparse
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
from config import CONFIG
|
| 8 |
+
from model import load_from_checkpoint
|
| 9 |
+
from inference_utils import full_inference, make_side_by_side
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def run_inference(
|
| 13 |
+
input_image: str,
|
| 14 |
+
output_dir: str = "./output",
|
| 15 |
+
ckpt_path: str = None,
|
| 16 |
+
device: str = None,
|
| 17 |
+
image_size: int = None,
|
| 18 |
+
width_mult: float = None,
|
| 19 |
+
):
|
| 20 |
+
if device is None:
|
| 21 |
+
device = CONFIG["device"]
|
| 22 |
+
if image_size is None:
|
| 23 |
+
image_size = CONFIG["image_size"]
|
| 24 |
+
if width_mult is None:
|
| 25 |
+
width_mult = CONFIG["width_mult"]
|
| 26 |
+
if ckpt_path is None:
|
| 27 |
+
ckpt_path = CONFIG["checkpoint_path"]
|
| 28 |
+
|
| 29 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 30 |
+
|
| 31 |
+
print(f"Loading model from {ckpt_path}...")
|
| 32 |
+
model = load_from_checkpoint(ckpt_path, device=device, width_mult=width_mult)
|
| 33 |
+
model.to(device)
|
| 34 |
+
model.eval()
|
| 35 |
+
|
| 36 |
+
img = Image.open(input_image).convert("RGB")
|
| 37 |
+
base = os.path.splitext(os.path.basename(input_image))[0]
|
| 38 |
+
|
| 39 |
+
with torch.no_grad():
|
| 40 |
+
inp_img, outputs = full_inference(model, img, image_size, device)
|
| 41 |
+
|
| 42 |
+
side_by_side = make_side_by_side(inp_img, outputs)
|
| 43 |
+
out_path = os.path.join(output_dir, f"{base}_result.png")
|
| 44 |
+
side_by_side.save(out_path)
|
| 45 |
+
print(f"Saved result to {out_path}")
|
| 46 |
+
|
| 47 |
+
return outputs
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
parser = argparse.ArgumentParser(description="Diffusion Detailer Inference")
|
| 52 |
+
parser.add_argument("input", type=str, help="Path to input image")
|
| 53 |
+
parser.add_argument("--output_dir", type=str, default="./output", help="Output directory")
|
| 54 |
+
parser.add_argument("--ckpt_path", type=str, default=None, help="Path to checkpoint")
|
| 55 |
+
parser.add_argument("--device", type=str, default=None, help="Device (cuda/cpu)")
|
| 56 |
+
parser.add_argument("--image_size", type=int, default=None, help="Image size")
|
| 57 |
+
args = parser.parse_args()
|
| 58 |
+
|
| 59 |
+
run_inference(
|
| 60 |
+
input_image=args.input,
|
| 61 |
+
output_dir=args.output_dir,
|
| 62 |
+
ckpt_path=args.ckpt_path,
|
| 63 |
+
device=args.device,
|
| 64 |
+
image_size=args.image_size,
|
| 65 |
+
)
|
inference_utils.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 4 |
+
from torchvision import transforms
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def resize_pad(img_rgb: Image.Image, image_size: int) -> Image.Image:
|
| 8 |
+
img_rgb = img_rgb.convert("RGB")
|
| 9 |
+
w, h = img_rgb.size
|
| 10 |
+
size = int(image_size)
|
| 11 |
+
if w == 0 or h == 0:
|
| 12 |
+
return Image.new("RGB", (size, size), (0, 0, 0))
|
| 13 |
+
scale = max(size / float(w), size / float(h))
|
| 14 |
+
new_w = max(1, int(round(w * scale)))
|
| 15 |
+
new_h = max(1, int(round(h * scale)))
|
| 16 |
+
img_r = img_rgb.resize((new_w, new_h), resample=Image.BICUBIC)
|
| 17 |
+
left = (new_w - size) // 2
|
| 18 |
+
top = (new_h - size) // 2
|
| 19 |
+
return img_r.crop((left, top, left + size, top + size))
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def cond_tensor_from_pil(img_rgb: Image.Image, device: torch.device) -> torch.Tensor:
|
| 23 |
+
t = transforms.ToTensor()(img_rgb).unsqueeze(0).to(device)
|
| 24 |
+
t = t * 2.0 - 1.0
|
| 25 |
+
return t
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def full_inference(model, img_rgb: Image.Image, image_size: int, device: torch.device, num_passes: int = 5, noise_std: float = 0.01):
|
| 29 |
+
img_rgb = resize_pad(img_rgb, int(image_size))
|
| 30 |
+
x = cond_tensor_from_pil(img_rgb, device)
|
| 31 |
+
|
| 32 |
+
map_names = ['basecolor', 'normal', 'rmd']
|
| 33 |
+
stacks = {k: [] for k in map_names}
|
| 34 |
+
|
| 35 |
+
for p in range(num_passes):
|
| 36 |
+
noise = torch.randn_like(x) * noise_std if noise_std > 0 else 0
|
| 37 |
+
preds = model(x + noise)
|
| 38 |
+
|
| 39 |
+
for k in map_names:
|
| 40 |
+
stacks[k].append(preds[k])
|
| 41 |
+
|
| 42 |
+
merged = {}
|
| 43 |
+
for k in map_names:
|
| 44 |
+
merged[k] = torch.median(torch.stack(stacks[k]), dim=0).values
|
| 45 |
+
|
| 46 |
+
inv_input = torch.cat([merged['basecolor'], merged['normal'], merged['rmd']], dim=1)
|
| 47 |
+
with torch.no_grad():
|
| 48 |
+
merged['rgb'] = model(inv_input, mode=1)['rgb']
|
| 49 |
+
|
| 50 |
+
def to_pil(tensor):
|
| 51 |
+
out = (tensor + 1.0) / 2.0
|
| 52 |
+
out = out.clamp(0, 1)
|
| 53 |
+
out_np = out[0].detach().cpu().permute(1, 2, 0).numpy()
|
| 54 |
+
return Image.fromarray((out_np * 255.0 + 0.5).astype("uint8"))
|
| 55 |
+
|
| 56 |
+
outputs = {k: to_pil(v) for k, v in merged.items()}
|
| 57 |
+
return img_rgb, outputs
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def tiled_inference(model, img_rgb: Image.Image, tile: int, device: torch.device, overlap: int = 16):
|
| 61 |
+
img_rgb = img_rgb.convert("RGB")
|
| 62 |
+
|
| 63 |
+
overlap = int(overlap)
|
| 64 |
+
if overlap < 0:
|
| 65 |
+
overlap = 0
|
| 66 |
+
if overlap >= tile:
|
| 67 |
+
overlap = max(0, tile - 1)
|
| 68 |
+
stride = max(1, tile - overlap)
|
| 69 |
+
|
| 70 |
+
w, h = img_rgb.size
|
| 71 |
+
pad_w = (tile - (w % stride)) % stride
|
| 72 |
+
pad_h = (tile - (h % stride)) % stride
|
| 73 |
+
|
| 74 |
+
if pad_w or pad_h:
|
| 75 |
+
new_img = Image.new("RGB", (w + pad_w, h + pad_h), (0, 0, 0))
|
| 76 |
+
new_img.paste(img_rgb, (0, 0))
|
| 77 |
+
src_padded = new_img
|
| 78 |
+
else:
|
| 79 |
+
src_padded = img_rgb
|
| 80 |
+
|
| 81 |
+
pw, ph = src_padded.size
|
| 82 |
+
|
| 83 |
+
map_names = ['basecolor', 'normal', 'rmd']
|
| 84 |
+
acc = {k: np.zeros((ph, pw, 3), dtype=np.float32) for k in map_names}
|
| 85 |
+
wsum = np.zeros((ph, pw, 1), dtype=np.float32)
|
| 86 |
+
|
| 87 |
+
xs = list(range(0, max(1, pw - tile + 1), stride))
|
| 88 |
+
ys = list(range(0, max(1, ph - tile + 1), stride))
|
| 89 |
+
if xs[-1] != pw - tile:
|
| 90 |
+
xs.append(pw - tile)
|
| 91 |
+
if ys[-1] != ph - tile:
|
| 92 |
+
ys.append(ph - tile)
|
| 93 |
+
|
| 94 |
+
for top in ys:
|
| 95 |
+
for left in xs:
|
| 96 |
+
patch_img = src_padded.crop((left, top, left + tile, top + tile))
|
| 97 |
+
cond = cond_tensor_from_pil(patch_img, device)
|
| 98 |
+
|
| 99 |
+
with torch.no_grad():
|
| 100 |
+
preds = model(cond)
|
| 101 |
+
|
| 102 |
+
def tensor_to_np(t):
|
| 103 |
+
t = (t + 1.0) / 2.0
|
| 104 |
+
t = t.clamp(0, 1)
|
| 105 |
+
return t[0].detach().cpu().permute(1, 2, 0).numpy()
|
| 106 |
+
|
| 107 |
+
ramp_x = np.ones((tile,), dtype=np.float32)
|
| 108 |
+
ramp_y = np.ones((tile,), dtype=np.float32)
|
| 109 |
+
if overlap > 0:
|
| 110 |
+
if left > 0:
|
| 111 |
+
ramp_x[:overlap] = np.linspace(0.0, 1.0, overlap, endpoint=False, dtype=np.float32)
|
| 112 |
+
if left + tile < pw:
|
| 113 |
+
ramp_x[-overlap:] = np.linspace(1.0, 0.0, overlap, endpoint=False, dtype=np.float32)
|
| 114 |
+
if top > 0:
|
| 115 |
+
ramp_y[:overlap] = np.linspace(0.0, 1.0, overlap, endpoint=False, dtype=np.float32)
|
| 116 |
+
if top + tile < ph:
|
| 117 |
+
ramp_y[-overlap:] = np.linspace(1.0, 0.0, overlap, endpoint=False, dtype=np.float32)
|
| 118 |
+
|
| 119 |
+
weight = (ramp_y[:, None] * ramp_x[None, :])[:, :, None]
|
| 120 |
+
|
| 121 |
+
for k in map_names:
|
| 122 |
+
np_pred = tensor_to_np(preds[k])
|
| 123 |
+
acc[k][top : top + tile, left : left + tile, :] += np_pred * weight
|
| 124 |
+
wsum[top : top + tile, left : left + tile, :] += weight
|
| 125 |
+
|
| 126 |
+
def acc_to_pil(out_np):
|
| 127 |
+
out_np = out_np / np.maximum(wsum, 1e-8)
|
| 128 |
+
out_np = np.clip(out_np, 0.0, 1.0)
|
| 129 |
+
return Image.fromarray((out_np * 255.0 + 0.5).astype("uint8"))
|
| 130 |
+
|
| 131 |
+
outputs = {k: acc_to_pil(acc[k]) for k in map_names}
|
| 132 |
+
|
| 133 |
+
if pad_w or pad_h:
|
| 134 |
+
for k in map_names:
|
| 135 |
+
outputs[k] = outputs[k].crop((0, 0, w, h))
|
| 136 |
+
|
| 137 |
+
return img_rgb, outputs
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _draw_label(img: Image.Image, label: str, bar_color=(0, 0, 0)) -> Image.Image:
|
| 141 |
+
draw = ImageDraw.Draw(img)
|
| 142 |
+
try:
|
| 143 |
+
font = ImageFont.truetype("arial.ttf", 18)
|
| 144 |
+
except OSError:
|
| 145 |
+
font = ImageFont.load_default()
|
| 146 |
+
draw.rectangle((0, 0, img.width, 24), fill=bar_color)
|
| 147 |
+
draw.text((4, 2), label, fill=(255, 255, 255), font=font)
|
| 148 |
+
return img
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _draw_arrow(img: Image.Image, color=(180, 180, 180)) -> Image.Image:
|
| 152 |
+
draw = ImageDraw.Draw(img)
|
| 153 |
+
cx, cy = img.width // 2, img.height // 2
|
| 154 |
+
r = 8
|
| 155 |
+
draw.line((0, cy, img.width - r, cy), fill=color, width=3)
|
| 156 |
+
draw.polygon([(img.width - r, cy - r), (img.width - r, cy + r), (img.width, cy)], fill=color)
|
| 157 |
+
return img
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def make_side_by_side(inp_img: Image.Image, outputs: dict) -> Image.Image:
|
| 161 |
+
inp_img = inp_img.convert("RGB")
|
| 162 |
+
|
| 163 |
+
outputs = {k: v.convert("RGB") for k, v in outputs.items()}
|
| 164 |
+
|
| 165 |
+
r, g, b = outputs['rmd'].split()
|
| 166 |
+
|
| 167 |
+
cell_size = 200
|
| 168 |
+
arrow_w = 48
|
| 169 |
+
gap = 8
|
| 170 |
+
|
| 171 |
+
stage1_w = cell_size
|
| 172 |
+
stage2_w = cell_size * 3 + gap * 2
|
| 173 |
+
stage3_w = cell_size
|
| 174 |
+
|
| 175 |
+
total_w = stage1_w + arrow_w + stage2_w + arrow_w + stage3_w
|
| 176 |
+
total_h = cell_size * 2 + gap
|
| 177 |
+
|
| 178 |
+
canvas = Image.new("RGB", (total_w, total_h), (35, 35, 35))
|
| 179 |
+
|
| 180 |
+
def place(cvs, img, x, y, sz=cell_size):
|
| 181 |
+
img = img.resize((sz, sz), Image.BICUBIC)
|
| 182 |
+
cvs.paste(img, (x, y))
|
| 183 |
+
|
| 184 |
+
cx = 0
|
| 185 |
+
|
| 186 |
+
stage1 = _draw_label(inp_img.resize((cell_size, cell_size), Image.BICUBIC), "INPUT", (50, 100, 200))
|
| 187 |
+
place(canvas, stage1, cx, (total_h - cell_size) // 2)
|
| 188 |
+
cx += cell_size
|
| 189 |
+
|
| 190 |
+
arrow1 = Image.new("RGB", (arrow_w, total_h), (35, 35, 35))
|
| 191 |
+
arrow1 = _draw_arrow(arrow1)
|
| 192 |
+
canvas.paste(arrow1, (cx, 0))
|
| 193 |
+
cx += arrow_w
|
| 194 |
+
|
| 195 |
+
ordered = [
|
| 196 |
+
("BASECOLOR", outputs['basecolor'], (50, 160, 80)),
|
| 197 |
+
("NORMAL", outputs['normal'], (50, 160, 80)),
|
| 198 |
+
("DEPTH", b.convert("RGB"), (50, 160, 80)),
|
| 199 |
+
("ROUGHNESS", r.convert("RGB"), (50, 160, 80)),
|
| 200 |
+
("METALLIC", g.convert("RGB"), (50, 160, 80)),
|
| 201 |
+
]
|
| 202 |
+
|
| 203 |
+
for i, (label, img, color) in enumerate(ordered):
|
| 204 |
+
col = i % 3
|
| 205 |
+
row = i // 3
|
| 206 |
+
px = cx + col * (cell_size + gap)
|
| 207 |
+
py = row * (cell_size + gap)
|
| 208 |
+
panel = _draw_label(img.resize((cell_size, cell_size), Image.BICUBIC), label, color)
|
| 209 |
+
canvas.paste(panel, (px, py))
|
| 210 |
+
|
| 211 |
+
cx += cell_size * 3 + gap * 2
|
| 212 |
+
|
| 213 |
+
arrow2 = Image.new("RGB", (arrow_w, total_h), (35, 35, 35))
|
| 214 |
+
arrow2 = _draw_arrow(arrow2)
|
| 215 |
+
canvas.paste(arrow2, (cx, 0))
|
| 216 |
+
cx += arrow_w
|
| 217 |
+
|
| 218 |
+
stage3 = _draw_label(outputs['rgb'].resize((cell_size, cell_size), Image.BICUBIC), "RECON RGB", (200, 120, 50))
|
| 219 |
+
place(canvas, stage3, cx, (total_h - cell_size) // 2)
|
| 220 |
+
|
| 221 |
+
return canvas
|
layers.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class MultiScaleFusion(nn.Module):
|
| 7 |
+
def __init__(self, in_ch: int, out_ch: int):
|
| 8 |
+
super().__init__()
|
| 9 |
+
self.scale1 = nn.Conv2d(in_ch, in_ch, 3, padding="same")
|
| 10 |
+
self.scale2 = nn.Conv2d(in_ch, in_ch, 3, padding="same", dilation=2)
|
| 11 |
+
self.scale3 = nn.Conv2d(in_ch, in_ch, 3, padding="same", dilation=4)
|
| 12 |
+
self.proj = nn.Conv2d(in_ch * 3, out_ch, 1, bias=False) if in_ch * 3 != out_ch else nn.Identity()
|
| 13 |
+
|
| 14 |
+
def forward(self, x):
|
| 15 |
+
f1 = self.scale1(x)
|
| 16 |
+
f2 = self.scale2(x)
|
| 17 |
+
f3 = self.scale3(x)
|
| 18 |
+
fused = torch.cat([f1, f2, f3], dim=1)
|
| 19 |
+
return self.proj(fused)
|
model.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from torchvision import models
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class ConvMemoryLayer(nn.Module):
|
| 8 |
+
def __init__(self, channels: int):
|
| 9 |
+
super().__init__()
|
| 10 |
+
self.memory = nn.Parameter(torch.zeros(1, channels, 1, 1))
|
| 11 |
+
|
| 12 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 13 |
+
return x + self.memory
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ConvBlock(nn.Module):
|
| 17 |
+
def __init__(self, in_ch: int, out_ch: int):
|
| 18 |
+
super().__init__()
|
| 19 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 20 |
+
num_groups = min(32, out_ch)
|
| 21 |
+
while out_ch % num_groups != 0:
|
| 22 |
+
num_groups -= 1
|
| 23 |
+
self.bn1 = nn.GroupNorm(num_groups, out_ch)
|
| 24 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 25 |
+
self.bn2 = nn.GroupNorm(num_groups, out_ch)
|
| 26 |
+
|
| 27 |
+
self.memory = ConvMemoryLayer(out_ch)
|
| 28 |
+
|
| 29 |
+
mid = max(1, out_ch // 16)
|
| 30 |
+
self.channel_att = nn.Sequential(
|
| 31 |
+
nn.AdaptiveAvgPool2d(1),
|
| 32 |
+
nn.Flatten(),
|
| 33 |
+
nn.Linear(out_ch, mid),
|
| 34 |
+
nn.ReLU(),
|
| 35 |
+
nn.Linear(mid, out_ch),
|
| 36 |
+
nn.Sigmoid(),
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
self.spatial_att = nn.Sequential(
|
| 40 |
+
nn.Conv2d(out_ch, 1, kernel_size=3, padding="same"),
|
| 41 |
+
nn.Sigmoid()
|
| 42 |
+
)
|
| 43 |
+
nn.init.xavier_uniform_(self.spatial_att[0].weight, gain=0.01)
|
| 44 |
+
nn.init.constant_(self.spatial_att[0].bias, 0.0)
|
| 45 |
+
|
| 46 |
+
if in_ch != out_ch:
|
| 47 |
+
self.shortcut = nn.Conv2d(in_ch, out_ch, kernel_size=1, bias=False)
|
| 48 |
+
else:
|
| 49 |
+
self.shortcut = nn.Identity()
|
| 50 |
+
|
| 51 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 52 |
+
identity = self.shortcut(x)
|
| 53 |
+
|
| 54 |
+
x = F.elu(self.bn1(self.conv1(x)))
|
| 55 |
+
x = self.bn2(self.conv2(x))
|
| 56 |
+
|
| 57 |
+
b, c, _, _ = x.shape
|
| 58 |
+
ch_att = self.channel_att(x).view(b, c, 1, 1)
|
| 59 |
+
x = x * ch_att
|
| 60 |
+
|
| 61 |
+
sp_att = self.spatial_att(x)
|
| 62 |
+
x = x * sp_att
|
| 63 |
+
|
| 64 |
+
x = x + identity
|
| 65 |
+
x = F.elu(x)
|
| 66 |
+
x = self.memory(x)
|
| 67 |
+
return x
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class UpBlock(nn.Module):
|
| 71 |
+
def __init__(self, in_ch: int, skip_ch: int, out_ch: int):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.up = nn.ConvTranspose2d(in_ch, out_ch, kernel_size=2, stride=2)
|
| 74 |
+
self.block1 = ConvBlock(out_ch + skip_ch, out_ch)
|
| 75 |
+
self.block2 = ConvBlock(out_ch, out_ch)
|
| 76 |
+
|
| 77 |
+
def forward(self, x: torch.Tensor, skip: torch.Tensor) -> torch.Tensor:
|
| 78 |
+
x = self.up(x)
|
| 79 |
+
x = torch.cat([x, skip], dim=1)
|
| 80 |
+
x = self.block1(x)
|
| 81 |
+
x = self.block2(x)
|
| 82 |
+
return x
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class ParallelEncoder(nn.Module):
|
| 86 |
+
def __init__(self, in_ch: int = 3, width_mult: float = 1.0):
|
| 87 |
+
super().__init__()
|
| 88 |
+
c0 = max(8, int(16 * width_mult / 8) * 8)
|
| 89 |
+
c1 = max(8, int(32 * width_mult / 8) * 8)
|
| 90 |
+
c2 = max(8, int(64 * width_mult / 8) * 8)
|
| 91 |
+
c3 = max(8, int(128 * width_mult / 8) * 8)
|
| 92 |
+
c4 = max(8, int(256 * width_mult / 8) * 8)
|
| 93 |
+
self.s1 = nn.Sequential(
|
| 94 |
+
ConvBlock(in_ch, c0),
|
| 95 |
+
nn.Conv2d(c0, c0, kernel_size=3, stride=2, padding=1),
|
| 96 |
+
)
|
| 97 |
+
self.s2 = nn.Sequential(
|
| 98 |
+
ConvBlock(c0, c1),
|
| 99 |
+
nn.Conv2d(c1, c1, kernel_size=3, stride=2, padding=1),
|
| 100 |
+
)
|
| 101 |
+
self.s3 = nn.Sequential(
|
| 102 |
+
ConvBlock(c1, c2),
|
| 103 |
+
nn.Conv2d(c2, c2, kernel_size=3, stride=2, padding=1),
|
| 104 |
+
)
|
| 105 |
+
self.s4 = nn.Sequential(
|
| 106 |
+
ConvBlock(c2, c3),
|
| 107 |
+
nn.Conv2d(c3, c3, kernel_size=3, stride=2, padding=1),
|
| 108 |
+
)
|
| 109 |
+
self.s5 = nn.Sequential(
|
| 110 |
+
ConvBlock(c3, c4),
|
| 111 |
+
nn.Conv2d(c4, c4, kernel_size=3, stride=2, padding=1),
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
def forward(self, x):
|
| 115 |
+
c0 = self.s1(x)
|
| 116 |
+
c1 = self.s2(c0)
|
| 117 |
+
c2 = self.s3(c1)
|
| 118 |
+
c3 = self.s4(c2)
|
| 119 |
+
c4 = self.s5(c3)
|
| 120 |
+
return c0, c1, c2, c3, c4
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class MobileNetUNet(nn.Module):
|
| 124 |
+
def __init__(self, freeze_backbone: bool = True, width_mult: float = 1.0):
|
| 125 |
+
super().__init__()
|
| 126 |
+
backbone = models.mobilenet_v2(weights=models.MobileNet_V2_Weights.IMAGENET1K_V1)
|
| 127 |
+
self.features = backbone.features
|
| 128 |
+
if freeze_backbone:
|
| 129 |
+
for p in self.features.parameters():
|
| 130 |
+
p.requires_grad = False
|
| 131 |
+
for idx, layer in enumerate(self.features):
|
| 132 |
+
if idx >= 10:
|
| 133 |
+
for p in layer.parameters():
|
| 134 |
+
p.requires_grad = True
|
| 135 |
+
|
| 136 |
+
self.register_buffer('mean', torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
|
| 137 |
+
self.register_buffer('std', torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
|
| 138 |
+
|
| 139 |
+
def _ch(base: int) -> int:
|
| 140 |
+
return max(8, int(base * width_mult / 8) * 8)
|
| 141 |
+
|
| 142 |
+
self.custom_enc = ParallelEncoder(width_mult=width_mult)
|
| 143 |
+
|
| 144 |
+
enc_c = [_ch(16), _ch(32), _ch(64), _ch(128), _ch(256)]
|
| 145 |
+
mobile_c = [16, 24, 32, 96, 1280]
|
| 146 |
+
|
| 147 |
+
inv_target = list(enc_c)
|
| 148 |
+
|
| 149 |
+
self.inv_proj = nn.Sequential(
|
| 150 |
+
nn.Conv2d(9, 3, kernel_size=1),
|
| 151 |
+
nn.GroupNorm(3, 3),
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
def _proj_norm(in_ch, out_ch):
|
| 155 |
+
g = min(32, out_ch)
|
| 156 |
+
while out_ch % g != 0:
|
| 157 |
+
g -= 1
|
| 158 |
+
return nn.Sequential(
|
| 159 |
+
nn.Conv2d(in_ch, out_ch, kernel_size=1, bias=False),
|
| 160 |
+
nn.GroupNorm(g, out_ch),
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
self.compress0 = _proj_norm(mobile_c[0] + enc_c[0], inv_target[0])
|
| 164 |
+
self.compress1 = _proj_norm(mobile_c[1] + enc_c[1], inv_target[1])
|
| 165 |
+
self.compress2 = _proj_norm(mobile_c[2] + enc_c[2], inv_target[2])
|
| 166 |
+
self.compress3 = _proj_norm(mobile_c[3] + enc_c[3], inv_target[3])
|
| 167 |
+
self.compress4 = _proj_norm(mobile_c[4] + enc_c[4], inv_target[4])
|
| 168 |
+
|
| 169 |
+
self.up1 = UpBlock(in_ch=inv_target[4], skip_ch=inv_target[3], out_ch=enc_c[4])
|
| 170 |
+
self.up2 = UpBlock(in_ch=enc_c[4], skip_ch=inv_target[2], out_ch=enc_c[3])
|
| 171 |
+
self.up3 = UpBlock(in_ch=enc_c[3], skip_ch=inv_target[1], out_ch=enc_c[2])
|
| 172 |
+
self.up4 = UpBlock(in_ch=enc_c[2], skip_ch=inv_target[0], out_ch=enc_c[1])
|
| 173 |
+
self.up5 = nn.Sequential(
|
| 174 |
+
nn.ConvTranspose2d(enc_c[1], enc_c[0], kernel_size=2, stride=2),
|
| 175 |
+
ConvBlock(enc_c[0], enc_c[0]),
|
| 176 |
+
ConvBlock(enc_c[0], enc_c[0]),
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
self.shared_head = ConvBlock(enc_c[0] + 3, enc_c[1])
|
| 180 |
+
self.basecolor_proj = nn.Conv2d(enc_c[1], 3, kernel_size=1)
|
| 181 |
+
self.normal_proj = nn.Conv2d(enc_c[1], 3, kernel_size=1)
|
| 182 |
+
self.rmd_proj = nn.Conv2d(enc_c[1], 3, kernel_size=1)
|
| 183 |
+
self.rgb_proj = nn.Conv2d(enc_c[1], 3, kernel_size=1)
|
| 184 |
+
nn.init.zeros_(self.basecolor_proj.weight)
|
| 185 |
+
nn.init.zeros_(self.basecolor_proj.bias)
|
| 186 |
+
nn.init.zeros_(self.rgb_proj.weight)
|
| 187 |
+
nn.init.zeros_(self.rgb_proj.bias)
|
| 188 |
+
|
| 189 |
+
def train(self, mode: bool = True):
|
| 190 |
+
super().train(mode)
|
| 191 |
+
any_frozen = False
|
| 192 |
+
for p in self.features.parameters():
|
| 193 |
+
if not p.requires_grad:
|
| 194 |
+
any_frozen = True
|
| 195 |
+
break
|
| 196 |
+
if any_frozen:
|
| 197 |
+
self.features.eval()
|
| 198 |
+
return self
|
| 199 |
+
|
| 200 |
+
def forward(self, x: torch.Tensor, mode: int = 0) -> dict:
|
| 201 |
+
if mode == 0:
|
| 202 |
+
out = (x + 1.0) / 2.0
|
| 203 |
+
out = (out - self.mean) / self.std
|
| 204 |
+
|
| 205 |
+
mobile_out = out
|
| 206 |
+
mobile_feats = []
|
| 207 |
+
for idx, layer in enumerate(self.features):
|
| 208 |
+
mobile_out = layer(mobile_out)
|
| 209 |
+
if idx in (1, 3, 6, 13, 18):
|
| 210 |
+
mobile_feats.append(mobile_out)
|
| 211 |
+
|
| 212 |
+
custom_feats = self.custom_enc(out)
|
| 213 |
+
c0 = self.compress0(torch.cat([mobile_feats[0], custom_feats[0]], dim=1))
|
| 214 |
+
c1 = self.compress1(torch.cat([mobile_feats[1], custom_feats[1]], dim=1))
|
| 215 |
+
c2 = self.compress2(torch.cat([mobile_feats[2], custom_feats[2]], dim=1))
|
| 216 |
+
c3 = self.compress3(torch.cat([mobile_feats[3], custom_feats[3]], dim=1))
|
| 217 |
+
c4 = self.compress4(torch.cat([mobile_feats[4], custom_feats[4]], dim=1))
|
| 218 |
+
x_res = x
|
| 219 |
+
else:
|
| 220 |
+
x_proj = self.inv_proj(x)
|
| 221 |
+
c0, c1, c2, c3, c4 = self.custom_enc(x_proj)
|
| 222 |
+
x_res = x_proj
|
| 223 |
+
|
| 224 |
+
x = self.up1(c4, c3)
|
| 225 |
+
x = self.up2(x, c2)
|
| 226 |
+
x = self.up3(x, c1)
|
| 227 |
+
x = self.up4(x, c0)
|
| 228 |
+
x = self.up5(x)
|
| 229 |
+
|
| 230 |
+
x_cat = torch.cat([x, x_res], dim=1)
|
| 231 |
+
|
| 232 |
+
h = self.shared_head(x_cat)
|
| 233 |
+
basecolor = torch.clamp(self.basecolor_proj(h), -1, 1)
|
| 234 |
+
normal = torch.clamp(self.normal_proj(h), -1, 1)
|
| 235 |
+
rmd = torch.clamp(self.rmd_proj(h), -1, 1)
|
| 236 |
+
rgb = torch.clamp(self.rgb_proj(h), -1, 1)
|
| 237 |
+
|
| 238 |
+
return {'basecolor': basecolor, 'normal': normal, 'rmd': rmd, 'rgb': rgb}
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def create_model(image_size=128, width_mult=1.0):
|
| 242 |
+
return MobileNetUNet(freeze_backbone=True, width_mult=width_mult)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def load_from_checkpoint(ckpt_path, device="cpu", width_mult=2.0):
|
| 246 |
+
model = MobileNetUNet(freeze_backbone=True, width_mult=width_mult)
|
| 247 |
+
state = torch.load(ckpt_path, map_location=device, weights_only=True)
|
| 248 |
+
if "state_dict" in state:
|
| 249 |
+
sd = state["state_dict"]
|
| 250 |
+
else:
|
| 251 |
+
sd = state
|
| 252 |
+
|
| 253 |
+
renamed = {}
|
| 254 |
+
for k, v in sd.items():
|
| 255 |
+
if k.startswith("model."):
|
| 256 |
+
renamed[k[6:]] = v
|
| 257 |
+
else:
|
| 258 |
+
renamed[k] = v
|
| 259 |
+
|
| 260 |
+
missing, unexpected = model.load_state_dict(renamed, strict=False)
|
| 261 |
+
if missing:
|
| 262 |
+
print(f"Missing keys: {missing}")
|
| 263 |
+
if unexpected:
|
| 264 |
+
print(f"Unexpected keys: {unexpected}")
|
| 265 |
+
model.eval()
|
| 266 |
+
return model
|
onnx/model_mode0.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:22ed8d86539b89abaa332d493a6fb4b8f7b025bd34ba637061c82451d25ef6a9
|
| 3 |
+
size 111786946
|
onnx/model_mode0_quantized.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b84b62d3a0c677ab1f0f56032f9294a62c8e00c1b95a39ec0375e2b113cb1cc5
|
| 3 |
+
size 33539339
|
onnx/model_mode1.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:de793643a2a900075e21c4a19536458fefbd55c9a5e46c7cc356c37541ec0bfa
|
| 3 |
+
size 98778997
|
onnx/model_mode1_quantized.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8ad76ab59d37a23434e052bb2d03e1282d8704a86f891ca835028c73c8967794
|
| 3 |
+
size 30151266
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.0.0
|
| 2 |
+
torchvision>=0.15.0
|
| 3 |
+
Pillow>=10.0.0
|
| 4 |
+
numpy>=1.24.0
|
| 5 |
+
gradio>=4.0.0
|