Run this model with HF Jobs
Run phi-lab-rice/GRADE on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/phi-lab-rice/GRADE. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/phi-lab-rice/GRADE on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use phi-lab-rice/GRADE with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use phi-lab-rice/GRADE with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("phi-lab-rice/GRADE", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
Release GRADE full model and checkpoints
Browse filesFiles changed (20)
- .gitignoreAdded+4
- README.mdAdded+111
- SHA256SUMSAdded+4
- checkpoints/grade/control.safetensorsAdded+3
- checkpoints/grade/diffusion.safetensorsAdded+3
- checkpoints/grade/radar.safetensorsAdded+3
- checkpoints/misc/marigold_unet/config.jsonAdded+72
- checkpoints/misc/taesd/config.jsonAdded+39
- checkpoints/misc/taesd/diffusion_pytorch_model.safetensorsAdded+3
- config.yamlAdded+14
- requirements.txtAdded+9
- src/GRADE/stage1_radar_depth_module/__init__.pyAdded+5
- src/GRADE/stage1_radar_depth_module/radar_depth.pyAdded+406
- src/GRADE/stage2_diffusion_refinement/collate_fn_helpers.pyAdded+287
- src/GRADE/stage2_diffusion_refinement/inference.pyAdded+829
- src/GRADE/stage2_diffusion_refinement/inference_full.pyAdded+15
- src/GRADE/stage2_diffusion_refinement/models/radar_depth.pyAdded+22
- src/GRADE/stage2_diffusion_refinement/models/unet.pyAdded+55
- src/GRADE/stage2_diffusion_refinement/models/vae.pyAdded+66
- src/GRADE/stage2_diffusion_refinement/rice_dataset.pyAdded+183
1234inputs/outputs/__pycache__/*.pyc123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111---license: cc-by-nc-4.0library_name: pytorchdatasets:- phi-lab-rice/GRADE_Datasettags:- radar- rgb- depth-estimation- multimodal- safetensorsarxiv: 2609.10756---
# GRADE full model
This repository contains the **full GRADE model** from [GRADE: Single-Frame Generative Radar Depth Estimation Under Visual Degradation](https://arxiv.org/abs/2609.10756) (ACM MobiCom 2026). It estimates one depth map per synchronized radar and DJI RGB frame. The three GRADE checkpoints are `radar.safetensors` (radar depth), `diffusion.safetensors` (diffusion UNet), and `control.safetensors` (RGB ControlNet). The small TAESD checkpoint and the Marigold UNet architecture configuration are also included because inference requires them. This repository does not contain the paper's baselines or ablations.
The code uses the paper's eight-step DDIM inference with seed 42, an output resolution of 288 × 512, and a depth range of 0–11.2 m. It requires an NVIDIA GPU with a working CUDA installation. We verified one-frame inference on an RTX 4080 SUPER with Python 3.12.14, PyTorch 2.11.0+cu128, and the package versions in `requirements.txt`. On one processed evaluation frame, the release produced exactly the same output array as the original artifact inference.
## Download and install
```bashhf download phi-lab-rice/GRADE --local-dir grade-modelcd grade-modelpython3.12 -m venv .venvsource .venv/bin/activatepython -m pip install --upgrade pippython -m pip install torch==2.11.0 torchvision==0.26.0 \ --index-url https://download.pytorch.org/whl/cu128python -m pip install -r requirements.txt```
Install the [Hugging Face CLI](https://huggingface.co/docs/huggingface_hub/guides/cli) first if `hf` is unavailable. For a different CUDA runtime, install a matching PyTorch wheel and then install `requirements.txt`. The checkpoint files can be checked with `sha256sum -c SHA256SUMS` from the repository root.
## Input data
Place each processed sequence in a directory under `inputs/`:
```textinputs/ my_sequence/ radar.npy # complex64, (N, 64, 2, 8, 256) dji_rgb.npy # uint8 RGB, (N, 504, 896, 3)```
The two arrays must have the same frame count and synchronized order. `N` may be 1. The included loader applies the original radar scaling and DJI camera calibration; supply the processed arrays produced by the [GRADE dataset processor](https://huggingface.co/datasets/phi-lab-rice/GRADE_Dataset), without further normalization, channel swapping, or defishing. ZED depth is ground truth for evaluation and is **not** needed for inference.
The linked raw dataset currently contains non-video files only. Its processor needs DJI and ZED videos, so the public dataset download alone cannot yet produce the RGB input for this model. Users with their own synchronized data or locally processed GRADE sequences can run inference now. The calibration in this release is for the GRADE sensor setup; a different camera setup needs corresponding calibration changes.
## Run the full model
From the repository root, after adding at least one input sequence:
```bashaccelerate launch --num_processes 1 --num_machines 1 \ --mixed_precision fp16 --dynamo_backend no \ src/GRADE/stage2_diffusion_refinement/inference_full.py \ --config config.yaml```
The command reads all valid subdirectories of `inputs/` and writes `outputs/ours_full/<sequence>_pred.npy` (sequence names are lowercased in output filenames). Each output is `float32` with shape `(N, 1, 288, 512)` and values in `[0, 1]`. Multiply by `11.2` to obtain estimated meters:
```pythonimport numpy as npdepth_m = np.load("outputs/ours_full/my_sequence_pred.npy") * 11.2```
To use other input and output directories, edit `data.smoke_eval_root` and `inference.output_root` in `config.yaml`. Relative paths are resolved from the configuration file's directory. Existing output files with the same sequence name will be overwritten, so copy results you want to retain before rerunning.
For a code and checkpoint loading check without real sensor data, make one synthetic frame in a new `inputs/synthetic/` directory. Its prediction has no scientific meaning:
```bashpython - <<'PY'from pathlib import Pathimport numpy as npp = Path("inputs/synthetic")p.mkdir(parents=True, exist_ok=True)np.save(p / "radar.npy", np.zeros((1, 64, 2, 8, 256), np.complex64))np.save(p / "dji_rgb.npy", np.full((1, 504, 896, 3), 127, np.uint8))PY```
Then run the inference command above and check `outputs/ours_full/synthetic_pred.npy`.
## Checkpoints and code
```textcheckpoints/grade/ three GRADE full-model checkpointscheckpoints/misc/ TAESD VAE weights and architecture configssrc/GRADE/ radar encoder and full-model inference codeconfig.yaml inference paths and paper settingsrequirements.txt tested non-PyTorch Python dependenciesSHA256SUMS checksum manifest for checkpoint files```
The `.safetensors` files contain model tensors for inference, not optimizer or training state. The architecture configuration for the UNet is bundled locally. TAESD is an auxiliary VAE from the [TAESD project](https://huggingface.co/madebyollin/taesd). The GRADE code and model weights are released under CC BY-NC 4.0; the upstream TAESD model is MIT licensed.
## Citation
```bibtex@inproceedings{zhao2026grade, author = {Bin Zhao and Patrick Chiou and Nakul Garg}, title = {{GRADE}: Single-Frame Generative Radar Depth Estimation Under Visual Degradation}, booktitle = {Proceedings of the 32nd Annual International Conference on Mobile Computing and Networking}, series = {MobiCom '26}, year = {2026}, publisher = {ACM}, doi = {10.1145/3795866.3844478}}```1234c4125ae3670f646d1e60639f97b27d4e6b6c2f995cdb818e90c9d36198727d34 checkpoints/grade/radar.safetensors5c9ff00df7e9ce75217f0ca900503c3a6e631ad902966a7bb05bae0e4017c5c8 checkpoints/grade/diffusion.safetensors6bc3bf8e520a1ba5ac672cc587a17c50398cfa4a49c0b17b0b4fc634bab53e3e checkpoints/grade/control.safetensorsdb169d69145ec4ff064e49d99c95fa05d3eb04ee453de35824a6d0f325513549 checkpoints/misc/taesd/diffusion_pytorch_model.safetensors123version https://git-lfs.github.com/spec/v1oid sha256:6bc3bf8e520a1ba5ac672cc587a17c50398cfa4a49c0b17b0b4fc634bab53e3esize 1456999608123version https://git-lfs.github.com/spec/v1oid sha256:5c9ff00df7e9ce75217f0ca900503c3a6e631ad902966a7bb05bae0e4017c5c8size 3463772560123version https://git-lfs.github.com/spec/v1oid sha256:c4125ae3670f646d1e60639f97b27d4e6b6c2f995cdb818e90c9d36198727d34size 28153012123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172{ "_class_name": "UNet2DConditionModel", "_diffusers_version": "0.31.0", "act_fn": "silu", "addition_embed_type": null, "addition_embed_type_num_heads": 64, "addition_time_embed_dim": null, "attention_head_dim": [ 5, 10, 20, 20 ], "attention_type": "default", "block_out_channels": [ 320, 640, 1280, 1280 ], "center_input_sample": false, "class_embed_type": null, "class_embeddings_concat": false, "conv_in_kernel": 3, "conv_out_kernel": 3, "cross_attention_dim": 1024, "cross_attention_norm": null, "down_block_types": [ "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D" ], "downsample_padding": 1, "dropout": 0.0, "dual_cross_attention": false, "encoder_hid_dim": null, "encoder_hid_dim_type": null, "flip_sin_to_cos": true, "freq_shift": 0, "in_channels": 8, "layers_per_block": 2, "mid_block_only_cross_attention": null, "mid_block_scale_factor": 1, "mid_block_type": "UNetMidBlock2DCrossAttn", "norm_eps": 1e-05, "norm_num_groups": 32, "num_attention_heads": null, "num_class_embeds": null, "only_cross_attention": false, "out_channels": 4, "projection_class_embeddings_input_dim": null, "resnet_out_scale_factor": 1.0, "resnet_skip_time_act": false, "resnet_time_scale_shift": "default", "reverse_transformer_layers_per_block": null, "sample_size": 96, "time_cond_proj_dim": null, "time_embedding_act_fn": null, "time_embedding_dim": null, "time_embedding_type": "positional", "timestep_post_act": null, "transformer_layers_per_block": 1, "up_block_types": [ "UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D" ], "upcast_attention": false, "use_linear_projection": true}123456789101112131415161718192021222324252627282930313233343536373839{ "_class_name": "AutoencoderTiny", "_diffusers_version": "0.30.0", "act_fn": "relu", "decoder_block_out_channels": [ 64, 64, 64, 64 ], "encoder_block_out_channels": [ 64, 64, 64, 64 ], "force_upcast": false, "in_channels": 3, "latent_channels": 4, "latent_magnitude": 3, "latent_shift": 0.5, "num_decoder_blocks": [ 3, 3, 3, 1 ], "num_encoder_blocks": [ 1, 3, 3, 3 ], "out_channels": 3, "scaling_factor": 1.0, "shift_factor": 0.0, "upsample_fn": "nearest", "upsampling_scaling_factor": 2}123version https://git-lfs.github.com/spec/v1oid sha256:db169d69145ec4ff064e49d99c95fa05d3eb04ee453de35824a6d0f325513549size 97932921234567891011121314training: {batch_size: 1, mixed_precision: fp16, seed: 42}data: smoke_eval_root: inputs resolution: {height: 288, width: 512} scale_factor: 0.001 max_depth_m: 11.2 num_frames: 1 num_workers: 0pretrained: radar_model: checkpoints/grade/radar.safetensors unet: checkpoints/grade/diffusion.safetensors controlnet: checkpoints/grade/control.safetensorsdiffusion: {num_train_timesteps: 1000}inference: {frame_skip: 1, batch_size: 1, num_workers: 0, output_root: outputs}123456789# Install a CUDA-compatible torch and torchvision first; see README.md.accelerate==1.15.0diffusers==0.40.0transformers==5.17.0safetensors==0.8.0numpy==2.5.2opencv-python-headless==4.14.0.94PyYAML==6.0.3tqdm==4.70.112345"""Stage-1 radar-depth module used by GRADE and its ablations."""
from .radar_depth import RadarDepth
__all__ = ["RadarDepth"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406import torch
import torch.nn as nn
from typing import Tuple
class RadarPatchEmbed(nn.Module):
"""
Radar Spectrum Patch Embedding Layer.
Takes 5D radar spectrum data and converts it into patch embeddings:
1. Input: [B, 2, 256, 64, 8, 2] where channels are (magnitude, phase)
2. Patchifies along range and doppler dimensions
3. Outputs: [B, num_patches, embed_dim] where num_patches = 2048
Patch extraction:
- Range dimension (256): patch_size=4, stride=4 -> 64 patches
- Doppler dimension (64): patch_size=2, stride=2 -> 32 patches
- Total patches: 64 × 32 = 2048
- Each patch: [4 range × 2 doppler × 8 elevation × 2 azimuth] × 2 channels = 256 features
"""
def __init__(
self,
input_shape: Tuple[int, int, int, int] = (
256,
64,
8,
2,
), # (Range, Doppler, Elevation, Azimuth)
patch_size: Tuple[int, int, int, int] = (
4,
2,
8,
2,
), # (Range, Doppler, Elevation, Azimuth)
stride: Tuple[int, int] = (4, 2), # (Range, Doppler)
embed_dim: int = 256,
in_channels: int = 2, # magnitude + phase
):
super().__init__()
self.input_shape = input_shape
self.patch_size = patch_size
self.stride = stride
self.embed_dim = embed_dim
self.in_channels = in_channels
# Calculate number of patches
range_dim, doppler_dim, elev_dim, azim_dim = input_shape
patch_range, patch_doppler, patch_elev, patch_azim = patch_size
stride_range, stride_doppler = stride
self.num_patches_range = (range_dim - patch_range) // stride_range + 1 # 64
self.num_patches_doppler = (
doppler_dim - patch_doppler
) // stride_doppler + 1 # 32
self.num_patches = self.num_patches_range * self.num_patches_doppler # 2048
# Each patch has: patch_range × patch_doppler × patch_elev × patch_azim features per channel
patch_volume = (
patch_range * patch_doppler * patch_elev * patch_azim
) # 4×2×8×2 = 128
self.patch_features = patch_volume * in_channels # 128 × 2 = 256
# Linear projection from patch features to embedding dimension
self.proj = nn.Linear(self.patch_features, embed_dim)
print(f"Radar Patch Embedding Configuration:")
print(
f" Input shape: [B, {in_channels}, {range_dim}, {doppler_dim}, {elev_dim}, {azim_dim}]"
)
print(f" Patch size: {patch_size}")
print(f" Stride: {stride}")
print(
f" Number of patches (range × doppler): {self.num_patches_range} × {self.num_patches_doppler} = {self.num_patches}"
)
print(f" Patch features per channel: {patch_volume}")
print(f" Total patch features (mag+phase): {self.patch_features}")
print(f" Embedding dimension: {embed_dim}")
def extract_patches(self, x: torch.Tensor) -> torch.Tensor:
"""
Extract patches from radar spectrum data.
Args:
x: [B, 2, 256, 64, 8, 2] (magnitude + phase channels)
Returns:
patches: [B, num_patches, patch_features]
"""
batch_size = x.shape[0]
x_mag = x[:, 0] # [B, 256, 64, 8, 2]
x_phase = x[:, 1] # [B, 256, 64, 8, 2]
all_patches = []
# Extract patches with stride along range and doppler dimensions
for i in range(self.num_patches_range):
for j in range(self.num_patches_doppler):
start_range = i * self.stride[0]
end_range = start_range + self.patch_size[0]
start_doppler = j * self.stride[1]
end_doppler = start_doppler + self.patch_size[1]
# Extract patch from both channels
patch_mag = x_mag[
:, start_range:end_range, start_doppler:end_doppler, :, :
]
patch_phase = x_phase[
:, start_range:end_range, start_doppler:end_doppler, :, :
]
# Flatten patches
patch_mag_flat = patch_mag.flatten(1) # [B, 128]
patch_phase_flat = patch_phase.flatten(1) # [B, 128]
# Interleave magnitude and phase features
patch_interleaved = torch.stack(
[patch_mag_flat, patch_phase_flat], dim=-1
)
patch_interleaved = patch_interleaved.flatten(1, -1) # [B, 256]
all_patches.append(patch_interleaved)
# Stack all patches: [B, num_patches, patch_features]
all_patches = torch.stack(all_patches, dim=1)
return all_patches
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass.
Args:
x: [B, 2, 256, 64, 8, 2]
Returns:
embeddings: [B, num_patches, embed_dim]
"""
# Extract patches: [B, 2048, 256]
patches = self.extract_patches(x)
# Project to embedding dimension: [B, 2048, embed_dim]
embeddings = self.proj(patches)
return embeddings
class RadarEncoder(nn.Module):
"""
Radar Vision Transformer (ViT) Encoder.
"""
def __init__(
self,
input_shape: Tuple[int, int, int, int] = (256, 64, 8, 2),
patch_size: Tuple[int, int, int, int] = (4, 2, 8, 2),
stride: Tuple[int, int] = (4, 2),
embed_dim: int = 256,
num_heads: int = 8,
num_layers: int = 4,
mlp_ratio: float = 4.0,
dropout: float = 0.1,
):
super().__init__()
self.embed_dim = embed_dim
# Patch embedding layer
self.patch_embed = RadarPatchEmbed(
input_shape=input_shape,
patch_size=patch_size,
stride=stride,
embed_dim=embed_dim,
in_channels=2,
)
self.num_patches = self.patch_embed.num_patches
# Learnable positional embeddings
self.pos_embed = nn.Parameter(torch.zeros(1, self.num_patches, embed_dim))
# Transformer encoder
encoder_layer = nn.TransformerEncoderLayer(
d_model=embed_dim,
nhead=num_heads,
dim_feedforward=int(embed_dim * mlp_ratio),
dropout=dropout,
activation="gelu",
batch_first=True,
norm_first=True,
)
self.transformer = nn.TransformerEncoder(
encoder_layer=encoder_layer,
num_layers=num_layers,
norm=nn.LayerNorm(embed_dim),
)
self._init_weights()
def _init_weights(self):
"""Initialize weights."""
# Initialize positional embeddings
nn.init.trunc_normal_(self.pos_embed, std=0.02)
# Initialize patch embedding projection
if hasattr(self.patch_embed.proj, "weight"):
nn.init.xavier_uniform_(self.patch_embed.proj.weight)
if self.patch_embed.proj.bias is not None:
nn.init.zeros_(self.patch_embed.proj.bias)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.patch_embed(x)
x = x + self.pos_embed
x = self.transformer(x)
return x
class TransformerDecoderBlock(nn.Module):
"""Transformer decoder block with self-attention and feedforward"""
def __init__(self, embed_dim=384, num_heads=6, mlp_ratio=4.0, dropout=0.0):
super().__init__()
self.norm1 = nn.LayerNorm(embed_dim)
self.attn = nn.MultiheadAttention(
embed_dim, num_heads, dropout=dropout, batch_first=True
)
self.norm2 = nn.LayerNorm(embed_dim)
self.mlp = nn.Sequential(
nn.Linear(embed_dim, int(embed_dim * mlp_ratio)),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(int(embed_dim * mlp_ratio), embed_dim),
nn.Dropout(dropout),
)
def forward(self, x):
# Self-attention with residual
x = x + self.attn(self.norm1(x), self.norm1(x), self.norm1(x))[0]
# MLP with residual
x = x + self.mlp(self.norm2(x))
return x
class DepthDecoder(nn.Module):
"""
Hybrid Transformer+CNN decoder for depth image generation.
Input: [batch_size, num_patches=2048, embed_dim=512]
Output: [batch_size, 1, height=128, width=256]
Architecture:
1. Transformer decoder blocks (4 layers)
2. Reshape to 2D feature map (64x32)
3. CNN upsampling stages (64x32 -> 128x256)
"""
def __init__(
self,
embed_dim=256,
num_patches=2048,
patch_grid_size=(64, 32), # Spatial structure from radar encoder
num_decoder_blocks=4,
num_heads=8,
mlp_ratio=4.0,
dropout=0.0,
output_height=128,
output_width=256,
output_channels=1,
):
super().__init__()
self.embed_dim = embed_dim
self.num_patches = num_patches
self.patch_grid_size = patch_grid_size # (64, 32) spatial grid
self.output_height = output_height
self.output_width = output_width
self.output_channels = output_channels
# Transformer decoder blocks
self.decoder_blocks = nn.ModuleList(
[
TransformerDecoderBlock(embed_dim, num_heads, mlp_ratio, dropout)
for _ in range(num_decoder_blocks)
]
)
self.norm = nn.LayerNorm(embed_dim)
# Projection to intermediate feature map
# From 64x32x256 to 64x32x128 (reduce dimension for upsampling)
self.feature_proj = nn.Conv2d(embed_dim, 128, kernel_size=1)
# Upsampling network: 64x32 -> 128x256
# Start from 64x32 (range x doppler), upsample to 128x256
self.upsample = nn.Sequential(
# Upsample doppler dimension: 64x32 -> 64x64
nn.Upsample(scale_factor=(1, 2), mode="bilinear", align_corners=False),
nn.Conv2d(128, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
# Upsample both dimensions: 64x64 -> 128x128
nn.Upsample(scale_factor=(2, 2), mode="bilinear", align_corners=False),
nn.Conv2d(64, 32, kernel_size=3, padding=1),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True),
# Upsample width dimension: 128x128 -> 128x256
nn.Upsample(scale_factor=(1, 2), mode="bilinear", align_corners=False),
nn.Conv2d(32, output_channels, kernel_size=3, padding=1),
nn.Sigmoid(), # Output in [0, 1] range
)
def forward(self, x):
"""
Args:
x: [batch_size, num_patches, embed_dim]
Returns:
depth: [batch_size, output_channels, output_height, output_width]
"""
batch_size = x.shape[0]
# Apply transformer decoder blocks
for block in self.decoder_blocks:
x = block(x)
x = self.norm(x)
# Reshape to spatial dimensions: [B, 2048, 512] -> [B, 64, 32, 512]
x = x.reshape(
batch_size,
self.patch_grid_size[0], # 64 (range)
self.patch_grid_size[1], # 32 (doppler)
self.embed_dim,
)
# Permute to channel-first: [B, H, W, C] -> [B, C, H, W]
x = x.permute(0, 3, 1, 2)
# Shape: [batch, 512, 64, 32]
# Project features
x = self.feature_proj(x)
# Shape: [batch, 128, 64, 32]
# Upsample to target resolution
depth = self.upsample(x)
# Shape: [batch, 1, 128, 256]
return depth
class RadarDepth(nn.Module):
"""
End-to-end Radar to Depth model (Doppler-as-Channels).
"""
def __init__(
self,
# Encoder args
input_shape: Tuple[int, int, int, int] = (256, 64, 8, 2),
patch_size: Tuple[int, int, int, int] = (4, 2, 8, 2),
stride: Tuple[int, int] = (4, 2),
embed_dim: int = 256,
encoder_num_heads: int = 8,
encoder_num_layers: int = 4,
encoder_mlp_ratio: float = 4.0,
encoder_dropout: float = 0.1,
# Decoder args
decoder_num_blocks: int = 4,
decoder_num_heads: int = 8,
output_height: int = 128,
output_width: int = 256,
):
super().__init__()
self.encoder = RadarEncoder(
input_shape=input_shape,
patch_size=patch_size,
stride=stride,
embed_dim=embed_dim,
num_heads=encoder_num_heads,
num_layers=encoder_num_layers,
mlp_ratio=encoder_mlp_ratio,
dropout=encoder_dropout,
)
# Get patch info from encoder
num_patches = self.encoder.num_patches # 64
self.decoder = DepthDecoder(
embed_dim=embed_dim,
num_patches=num_patches,
num_decoder_blocks=decoder_num_blocks,
num_heads=decoder_num_heads,
output_height=output_height,
output_width=output_width,
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.encoder(x)
x = self.decoder(x)
return x
def create_radar_encoder(*args, **kwargs):
return RadarEncoder(*args, **kwargs)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287import torchimport numpy as npimport cv2from typing import Optional, Tuple, Unionfrom torchvision import transforms as T
## General Purpose Helper Functions ##def to_zero_one(tensor: torch.Tensor) -> torch.Tensor: """Convert tensor from [-1, 1] to [0, 1].""" return torch.clamp((tensor + 1.0) / 2.0, min=0, max=1)
def to_neg_pos(tensor: torch.Tensor) -> torch.Tensor: """Convert tensor from [0, 1] to [-1, 1].""" return torch.clamp(tensor * 2.0 - 1.0, min=-1, max=1)
def to_3ch(depth_map: torch.Tensor) -> torch.Tensor: """Repeat depth map to 3 channels.""" return depth_map.repeat(1, 3, 1, 1) if depth_map.shape[1] == 1 else depth_map
## Radar Handler Functions ##def radar_collator( radar_amplitude: torch.Tensor, radar_phase: Optional[torch.Tensor] = None, scale_factor: float = 0.001,) -> torch.Tensor: """Convert radar amplitude/phase to normalized spectrum.""" if radar_phase is not None: radar_data = torch.stack([radar_amplitude, radar_phase], dim=1) radar_data = radar_data.permute(0, 1, 5, 2, 4, 3) else: radar_data = radar_amplitude
radar_mag = radar_data[:, 0:1, :, :, :, :] radar_phase_ch = radar_data[:, 1:2, :, :, :, :]
radar_mag_processed = torch.sqrt(radar_mag + 1e-8) * scale_factor radar_phase_processed = to_zero_one(radar_phase_ch)
return torch.cat([radar_mag_processed, radar_phase_processed], dim=1)
## Depth Handler Functions ##def depth_collator( depth: Union[torch.Tensor, np.ndarray], max_depth_m: float = 11.2, target_size: Tuple[int, int] = (128, 256),) -> Union[torch.Tensor, np.ndarray]: """Clamp, normalize to [0, 1], and resize depth.""" is_numpy = isinstance(depth, np.ndarray) if is_numpy: depth = torch.from_numpy(depth)
depth = depth.float() original_shape = depth.shape
if depth.dim() == 2: depth = depth.unsqueeze(0) elif depth.dim() == 3: depth = depth.unsqueeze(1)
invalid_mask = ~(torch.isfinite(depth) & (depth >= 0)) depth[invalid_mask] = 0.0
depth = torch.clamp(depth, min=0.0, max=max_depth_m) depth = depth / max_depth_m
invalid_mask = ~torch.isfinite(depth) depth[invalid_mask] = 0.0
resized = T.Resize( target_size, interpolation=T.InterpolationMode.BILINEAR, antialias=True )(depth)
if len(original_shape) == 2: resized = resized.squeeze(0)
return resized.numpy() if is_numpy else resized
## DJI RGB Handler Functions ##def dji_rgb_collator( image: torch.Tensor, target_size: Tuple[int, int] = (128, 256),) -> torch.Tensor: """Defish, calibrate, and resize a batch of DJI RGB images.
Args: image: Batch of DJI RGB images as torch tensor (B, C, H, W) in CHW format. target_size: Target resolution as (height, width).
Returns: Batch of processed and resized torch tensors in CHW format (B, C, H, W), normalised to [0, 1]. """ if not isinstance(image, torch.Tensor): raise ValueError(f"Expected torch.Tensor, got {type(image)}")
if image.dim() != 4: raise ValueError( f"Expected 4D tensor (B, C, H, W), got {image.dim()}D tensor with shape {image.shape}" )
target_h, target_w = target_size
# Calibration parameters (hardcoded) CALIB_K_DJI = np.array( [ [718.48555551, 0.0, 963.36465011], [0.0, 720.25844189, 537.87569913], [0.0, 0.0, 1.0], ], dtype=np.float64, ) CALIB_D_DJI = np.array( [0.19022699, 0.03466753, 0.05858962, -0.07070669], dtype=np.float64 ) CALIB_DEFISH_SHAPE = (1920, 1080) CALIB_DEFISH_BALANCE = 0.2 CALIB_H_FULL = np.array( [ [0.8274446551892256, -0.0742944198979625, 80.23797348979947], [-0.014725864916652691, 0.8471179917075127, 28.27366063997317], [-5.083573451500717e-05, -6.846079418201229e-05, 1.0], ], dtype=np.float64, ) CALIB_OUT_SIZE = (1918, 1105) CALIB_CROP = (115, 255, 1400, 760) # top, left, right, bottom
# Precompute defish maps R_DEFISH = np.eye(3) K_NEW_DEFISH = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify( CALIB_K_DJI, CALIB_D_DJI, CALIB_DEFISH_SHAPE, R_DEFISH, balance=CALIB_DEFISH_BALANCE, fov_scale=1.0, ) MAP1_DEFISH, MAP2_DEFISH = cv2.fisheye.initUndistortRectifyMap( CALIB_K_DJI, CALIB_D_DJI, R_DEFISH, K_NEW_DEFISH, CALIB_DEFISH_SHAPE, cv2.CV_16SC2, )
batch_size = image.shape[0]
# Handle normalized tensors [0, 1] or unnormalized if image.max() <= 1.0: img_batch = (image.permute(0, 2, 3, 1).numpy() * 255).astype( np.uint8 ) # (B, H, W, C) else: img_batch = image.permute(0, 2, 3, 1).numpy().astype(np.uint8) # (B, H, W, C)
# Process each image in the batch calibrated_images = []
for i in range(batch_size): img = img_batch[i]
# Resize to original DJI resolution (1920x1080) before calibration if img.shape[1] != 1920 or img.shape[0] != 1080: img = cv2.resize(img, (1920, 1080), interpolation=cv2.INTER_LINEAR)
# Defish img = cv2.remap(img, MAP1_DEFISH, MAP2_DEFISH, interpolation=cv2.INTER_LINEAR)
# Project img = cv2.warpPerspective( img, CALIB_H_FULL, CALIB_OUT_SIZE, flags=cv2.INTER_LINEAR )
# Crop top, left, right, bottom = CALIB_CROP img = img[top:bottom, left:right]
# Resize to target resolution img = cv2.resize(img, (target_w, target_h), interpolation=cv2.INTER_LINEAR)
calibrated_images.append(img)
# Stack and convert to torch tensor in CHW format img_batch = np.stack(calibrated_images, axis=0) # (B, H, W, C) img_tensor = ( torch.from_numpy(img_batch).permute(0, 3, 1, 2).float() / 255.0 ) # (B, C, H, W)
return img_tensor
## Fisheye RGB Handler Functions ##def fisheye_rgb_collator( image: torch.Tensor, target_size: Tuple[int, int] = (128, 256),) -> torch.Tensor: """Calibrate and resize Fisheye RGB image batch.
Args: image: Batch of Fisheye RGB images as torch tensor (B, C, H, W) in CHW format target_size: Target resolution as (width, height)
Returns: Batch of calibrated and resized torch tensors in CHW format (B, C, H, W) """ # Hardcoded parameters for Black Magic Micro Studio Camera 4K G2 # with Olympus 9mm f/8 Fisheye lens IMAGE_WIDTH = 1920 IMAGE_HEIGHT = 1080 FOCAL_LENGTH_X = 0.613260 FOCAL_LENGTH_Y = 0.613260 CENTER_X = 0.5 CENTER_Y = 0.5 K1 = -0.120000 K2 = -0.015000
# Precompute undistortion maps w, h = IMAGE_WIDTH, IMAGE_HEIGHT x_out, y_out = np.meshgrid(np.arange(w), np.arange(h)) x_norm = (x_out - w * CENTER_X) / (w * FOCAL_LENGTH_X) y_norm = (y_out - h * CENTER_Y) / (h * FOCAL_LENGTH_Y) r = np.sqrt(x_norm**2 + y_norm**2) r_distorted = r + K1 * r**2 + K2 * r**3 r_safe = np.where(r > 0, r, 1.0) scale = np.where(r > 0, r_distorted / r_safe, 1.0) x_norm_distorted = x_norm * scale y_norm_distorted = y_norm * scale map_x = ( x_norm_distorted * (w * FOCAL_LENGTH_X) + w * CENTER_X ).astype(np.float32) map_y = ( y_norm_distorted * (h * FOCAL_LENGTH_Y) + h * CENTER_Y ).astype(np.float32)
# Expect batched torch tensor (B, C, H, W) if not isinstance(image, torch.Tensor): raise ValueError(f"Expected torch.Tensor, got {type(image)}") if image.dim() != 4: raise ValueError(f"Expected 4D tensor (B, C, H, W), got {image.dim()}D tensor with shape {image.shape}") batch_size = image.shape[0] # Handle normalized tensors [0, 1] or unnormalized if image.max() <= 1.0: img_batch = (image.permute(0, 2, 3, 1).numpy() * 255).astype(np.uint8) # (B, H, W, C) else: img_batch = image.permute(0, 2, 3, 1).numpy().astype(np.uint8) # (B, H, W, C)
# Process each image in the batch calibrated_images = [] target_h, target_w = target_size for i in range(batch_size): img = img_batch[i] # Resize to original resolution (1920x1080) if needed if img.shape[1] != IMAGE_WIDTH or img.shape[0] != IMAGE_HEIGHT: img = cv2.resize(img, (IMAGE_WIDTH, IMAGE_HEIGHT), interpolation=cv2.INTER_LINEAR)
# Undistort fisheye img = cv2.remap( img, map_x, map_y, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0), )
# Resize to target resolution img = cv2.resize(img, (target_w, target_h), interpolation=cv2.INTER_LINEAR) calibrated_images.append(img) # Stack and convert to torch tensor in CHW format img_batch = np.stack(calibrated_images, axis=0) # (B, H, W, C) img_tensor = torch.from_numpy(img_batch).permute(0, 3, 1, 2).float() / 255.0 # (B, C, H, W)
return img_tensor123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829#!/usr/bin/env python3"""Full GRADE inference from synchronized radar and DJI RGB arrays."""
import argparseimport osimport picklefrom pathlib import Pathfrom typing import Dict, List, Optional, Sequence, Tuple
import numpy as npimport torchimport torch.nn.functional as Fimport yamlfrom accelerate import Acceleratorfrom accelerate.utils import set_seedfrom diffusers import ControlNetModel, DDIMSchedulerfrom safetensors.torch import load_filefrom torch.utils.data import DataLoaderfrom tqdm import tqdm
from collate_fn_helpers import to_3ch, to_neg_posfrom models.radar_depth import RadarDepthfrom models.unet import SDUnetfrom models.vae import VAEfrom rice_dataset import RiceDataset
VARIANT_RADAR = "ours_radar"VARIANT_DIFFUSION = "ours_diffusion"VARIANT_FULL = "ours_full"VALIDATION_NOISE_SEED = 42VALIDATION_NUM_INFERENCE_STEPS = 8
def _resolve_path(config_path: str, value: str) -> str: if os.path.isabs(value): return value config_dir = os.path.dirname(os.path.abspath(config_path)) return os.path.normpath(os.path.join(config_dir, value))
def _safe_sequence_name(sequence: str) -> str: return sequence.replace("/", "_").replace("\\", "_").lower()
def _discover_sequences(smoke_eval_root: str) -> List[str]: root = Path(smoke_eval_root) if not root.is_dir(): raise FileNotFoundError(f"Smoke-Eval root not found: {smoke_eval_root}")
required_files = ("radar.npy", "dji_rgb.npy") sequences = sorted( item.name for item in root.iterdir() if item.is_dir() and not item.name.startswith(".") and all((item / name).is_file() for name in required_files) ) if not sequences: raise ValueError( f"No Smoke-Eval sequences with {required_files} found under {root}" ) for sequence in sequences: sequence_dir = root / sequence frame_counts = { name: int(np.load(sequence_dir / name, mmap_mode="r").shape[0]) for name in required_files } if len(set(frame_counts.values())) != 1: raise ValueError( f"{sequence}: radar/RGB frame counts must match so " f"diffusion and ControlNet consume the same seed-42 noise stream; " f"got {frame_counts}" ) return sequences
def _validate_prediction_array( predictions: np.ndarray, sequence: str, expected_count: int,) -> None: if predictions.shape[0] != expected_count: raise RuntimeError( f"{sequence}: expected {expected_count} predictions, " f"got {predictions.shape[0]}" ) if predictions.ndim != 4 or predictions.shape[1] != 1: raise RuntimeError( f"{sequence}: expected [N, 1, H, W], got {predictions.shape}" ) if predictions.dtype != np.float32: raise RuntimeError( f"{sequence}: expected float32 predictions, got {predictions.dtype}" ) if not np.isfinite(predictions).all(): raise RuntimeError(f"{sequence}: predictions contain NaN or Inf") if predictions.size and (predictions.min() < 0.0 or predictions.max() > 1.0): raise RuntimeError( f"{sequence}: normalized predictions are outside [0, 1]: " f"[{predictions.min()}, {predictions.max()}]" )
def _merge_rank_results( gather_dir: str, variant: str, sequence: str, num_processes: int,) -> Dict[int, np.ndarray]: safe_sequence = _safe_sequence_name(sequence) merged: Dict[int, np.ndarray] = {} for rank in range(num_processes): rank_path = os.path.join( gather_dir, f"{variant}_rank_{rank}_{safe_sequence}.pkl", ) with open(rank_path, "rb") as handle: rank_results = pickle.load(handle) for frame_idx, prediction in rank_results: merged.setdefault(int(frame_idx), prediction) os.remove(rank_path) return merged
def _gather_deduplicate_and_save( accelerator: Accelerator, local_results: List[Tuple[int, np.ndarray]], gather_dir: str, output_dir: str, variant: str, sequence: str, expected_frames: Sequence[int],) -> Optional[np.ndarray]: os.makedirs(gather_dir, exist_ok=True) safe_sequence = _safe_sequence_name(sequence) rank_path = os.path.join( gather_dir, f"{variant}_rank_{accelerator.process_index}_{safe_sequence}.pkl", ) with open(rank_path, "wb") as handle: pickle.dump(local_results, handle, protocol=pickle.HIGHEST_PROTOCOL)
accelerator.wait_for_everyone() saved_array = None if accelerator.is_main_process: predictions = _merge_rank_results( gather_dir, variant, sequence, accelerator.num_processes, ) expected_frames = [int(frame_idx) for frame_idx in expected_frames] expected_set = set(expected_frames) missing = [frame_idx for frame_idx in expected_frames if frame_idx not in predictions] unexpected = sorted(set(predictions) - expected_set) if missing or unexpected: raise RuntimeError( f"{sequence}: distributed inference coverage mismatch; " f"missing={missing[:5]} ({len(missing)} total), " f"unexpected={unexpected[:5]} ({len(unexpected)} total)" )
saved_array = np.stack( [predictions[frame_idx] for frame_idx in expected_frames], axis=0, ).astype(np.float32, copy=False) _validate_prediction_array(saved_array, sequence, len(expected_frames)) output_path = os.path.join(output_dir, f"{safe_sequence}_pred.npy") np.save(output_path, saved_array) print( f" Saved {saved_array.shape[0]} frames, " f"shape={saved_array.shape} -> {output_path}" )
accelerator.wait_for_everyone() return saved_array
def _make_sequence_dataset( data_root: str, sequence: str, frame_skip: int, num_frames: int, scale_factor: float, max_depth_m: float, target_height: int, target_width: int, use_rgb: bool,) -> RiceDataset: return RiceDataset( root_dir=data_root, sequences=[sequence], frame_skip=frame_skip, num_frames=num_frames, scale_factor=scale_factor, max_depth_m=max_depth_m, depth_resolution=(target_height, target_width), use_rgb=use_rgb, rgb_resolution=(target_height, target_width), )
def _make_loader( dataset: RiceDataset, batch_size: int, num_workers: int, accelerator: Accelerator,) -> DataLoader: loader = DataLoader( dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers, pin_memory=(accelerator.device.type == "cuda"), drop_last=False, ) return accelerator.prepare(loader)
def _load_state_dict( checkpoint_path: str, candidate_keys: Sequence[str], label: str,) -> Dict[str, torch.Tensor]: del candidate_keys, label return load_file(checkpoint_path, device="cpu")
@torch.no_grad()def _run_radar_stage( sequences: Sequence[str], data_root: str, output_dir: str, gather_dir: str, radar_model: torch.nn.Module, accelerator: Accelerator, frame_skip: int, num_frames: int, batch_size: int, num_workers: int, scale_factor: float, max_depth_m: float, target_height: int, target_width: int,) -> None: if accelerator.is_main_process: print(f"\nStage 1/3: {VARIANT_RADAR}")
radar_model.eval() for sequence_index, sequence in enumerate(sequences): dataset = _make_sequence_dataset( data_root, sequence, frame_skip, num_frames, scale_factor, max_depth_m, target_height, target_width, use_rgb=False, ) expected_frames = [int(frame_idx) for _, frame_idx in dataset.index_map] if not expected_frames: raise RuntimeError(f"{sequence}: no frames found") loader = _make_loader(dataset, batch_size, num_workers, accelerator)
local_results: List[Tuple[int, np.ndarray]] = [] progress = tqdm( loader, desc=f"[{sequence_index + 1}/{len(sequences)}] {sequence}", disable=not accelerator.is_local_main_process, dynamic_ncols=True, leave=False, ) for batch in progress: radar_spectrum = batch["radar"][:, 0] with accelerator.autocast(): # Preserve RadarDepth's native [B, 1, 128, 256] prediction grid. prediction = radar_model(radar_spectrum).clamp(0.0, 1.0) prediction_np = prediction.detach().float().cpu().numpy() frame_indices = batch["frame_idx"].detach().cpu().tolist() local_results.extend( (int(frame_idx), prediction_np[index]) for index, frame_idx in enumerate(frame_indices) )
_gather_deduplicate_and_save( accelerator, local_results, gather_dir, output_dir, VARIANT_RADAR, sequence, expected_frames, ) del loader, dataset, local_results
@torch.no_grad()def _prepare_refinement_inputs( batch: Dict[str, torch.Tensor], radar_model: torch.nn.Module, vae: VAE, accelerator: Accelerator, use_control: bool, target_height: int, target_width: int,) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: """Build model inputs without requiring ground-truth depth at inference.""" radar_spectrum = batch["radar"][:, 0]
with accelerator.autocast(): radar_depth = radar_model(radar_spectrum) radar_depth_resized = F.interpolate( radar_depth, size=(target_height, target_width), mode="bilinear", align_corners=False, )
radar_depth_norm = to_neg_pos(to_3ch(radar_depth_resized)) unet_conditions = vae.encode_latent(radar_depth_norm)
control_pixel = None if use_control: # Matches prepare_inputs(..., apply_weather=False): clean calibrated RGB. control_pixel = to_neg_pos(batch["rgb"][:, 0]) return unet_conditions, control_pixel
@torch.no_grad()def _run_refinement_stage( variant: str, sequences: Sequence[str], data_root: str, output_dir: str, gather_dir: str, radar_model: torch.nn.Module, unet: torch.nn.Module, controlnet: Optional[torch.nn.Module], vae: VAE, accelerator: Accelerator, frame_skip: int, num_frames: int, batch_size: int, num_workers: int, scale_factor: float, max_depth_m: float, target_height: int, target_width: int, num_train_timesteps: int,) -> None: use_control = controlnet is not None if accelerator.is_main_process: print(f"\nStage {'3' if use_control else '2'}/3: {variant}")
scheduler = DDIMScheduler( num_train_timesteps=num_train_timesteps, beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", prediction_type="epsilon", ) if accelerator.device.type == "cpu": noise_generator = torch.Generator() else: noise_generator = torch.Generator(device=accelerator.device) noise_generator.manual_seed(VALIDATION_NOISE_SEED)
radar_model.eval() unet.eval() if controlnet is not None: controlnet.eval()
for sequence_index, sequence in enumerate(sequences): dataset = _make_sequence_dataset( data_root, sequence, frame_skip, num_frames, scale_factor, max_depth_m, target_height, target_width, use_rgb=use_control, ) expected_frames = [int(frame_idx) for _, frame_idx in dataset.index_map] if not expected_frames: raise RuntimeError(f"{sequence}: no frames found") loader = _make_loader(dataset, batch_size, num_workers, accelerator)
local_results: List[Tuple[int, np.ndarray]] = [] progress = tqdm( loader, desc=f"[{sequence_index + 1}/{len(sequences)}] {sequence}", disable=not accelerator.is_local_main_process, dynamic_ncols=True, leave=False, ) for batch in progress: frame_indices = [ int(frame_idx) for frame_idx in batch["frame_idx"].detach().cpu().tolist() ] unet_conditions, control_pixel = ( _prepare_refinement_inputs( batch, radar_model, vae, accelerator, use_control, target_height, target_width, ) ) batch_size_actual = unet_conditions.shape[0] latents = torch.randn( unet_conditions.shape, generator=noise_generator, device=unet_conditions.device, dtype=unet_conditions.dtype, ) scheduler.set_timesteps( VALIDATION_NUM_INFERENCE_STEPS, device=accelerator.device, ) encoder_hidden_states = torch.zeros( batch_size_actual, 1, 1024, device=accelerator.device, dtype=latents.dtype, )
if controlnet is not None: # Matches validate() in train_control-defish.py. with accelerator.autocast(): for timestep in scheduler.timesteps: scaled_latents = scheduler.scale_model_input( latents, timestep ) unet_input = torch.cat( [scaled_latents, unet_conditions], dim=1, ) timesteps = torch.full( (batch_size_actual,), timestep, device=accelerator.device, dtype=torch.long, ) down_samples, mid_sample = controlnet( unet_input, timesteps, encoder_hidden_states=encoder_hidden_states, controlnet_cond=control_pixel, return_dict=False, ) noise_prediction = unet( unet_input, timesteps, encoder_hidden_states=encoder_hidden_states, down_block_additional_residuals=down_samples, mid_block_additional_residual=mid_sample, ).sample latents = scheduler.step( model_output=noise_prediction, timestep=timestep, sample=latents, ).prev_sample else: # Matches validate() in train_diffusion.py (no outer autocast). for timestep in scheduler.timesteps: scaled_latents = scheduler.scale_model_input(latents, timestep) unet_input = torch.cat( [scaled_latents, unet_conditions], dim=1, ) timesteps = torch.full( (batch_size_actual,), timestep, device=accelerator.device, dtype=torch.long, ) noise_prediction = unet( unet_input, timesteps, encoder_hidden_states=encoder_hidden_states, ).sample latents = scheduler.step( model_output=noise_prediction, timestep=timestep, sample=latents, ).prev_sample
prediction_3ch, _ = vae.decode_latent(latents) prediction = prediction_3ch.mean(dim=1, keepdim=True).clamp(0.0, 1.0)
prediction_np = prediction.detach().float().cpu().numpy() local_results.extend( (frame_idx, prediction_np[index]) for index, frame_idx in enumerate(frame_indices) )
_gather_deduplicate_and_save( accelerator, local_results, gather_dir, output_dir, variant, sequence, expected_frames, ) del loader, dataset, local_results
def parse_stage_args(description: str) -> argparse.Namespace: parser = argparse.ArgumentParser( description=description, ) parser.add_argument( "--config", default=str(Path(__file__).resolve().parents[3] / "config.yaml"), help="Path to the retrain ControlNet YAML config", ) return parser.parse_args()
def _load_runtime( config_path: str, required_checkpoints: Sequence[str],) -> Dict[str, object]: with open(config_path, "r") as handle: config = yaml.safe_load(handle) or {}
training = config.get("training", {}) data = config.get("data", {}) pretrained = config.get("pretrained", {}) diffusion = config.get("diffusion", {}) inference = config.get("inference", {})
smoke_eval_value = data.get("smoke_eval_root") radar_value = pretrained.get("radar_model") unet_value = pretrained.get("unet") or pretrained.get("diffusion_unet") controlnet_value = pretrained.get("controlnet") checkpoint_values = { "radar": ("pretrained.radar_model", radar_value), "unet": ("pretrained.unet", unet_value), "controlnet": ("pretrained.controlnet", controlnet_value), } missing_config = [] if not smoke_eval_value: missing_config.append("data.smoke_eval_root") for checkpoint_name in required_checkpoints: config_name, value = checkpoint_values[checkpoint_name] if not value: missing_config.append(config_name) if missing_config: raise ValueError(f"Missing required config values: {missing_config}")
smoke_eval_root = _resolve_path(config_path, str(smoke_eval_value)) resolved_checkpoints = {} checkpoint_labels = { "radar": "RadarDepth", "unet": "UNet", "controlnet": "ControlNet", } for checkpoint_name in required_checkpoints: _, value = checkpoint_values[checkpoint_name] checkpoint_path = _resolve_path(config_path, str(value)) if not os.path.isfile(checkpoint_path): raise FileNotFoundError( f"{checkpoint_labels[checkpoint_name]} checkpoint not found: " f"{checkpoint_path}" ) resolved_checkpoints[checkpoint_name] = checkpoint_path
target_height = int(data.get("resolution", {}).get("height", 288)) target_width = int(data.get("resolution", {}).get("width", 512)) frame_skip = int(inference.get("frame_skip", data.get("test_skip", 1))) if frame_skip != 1: raise ValueError( f"Final Smoke-Eval inference requires frame_skip=1, got {frame_skip}" ) num_frames = int(data.get("num_frames", 1)) scale_factor = float(data.get("scale_factor", 0.001)) max_depth_m = float(data.get("max_depth_m", 11.2)) batch_size = int(inference.get("batch_size", training.get("batch_size", 1))) num_workers = int(inference.get("num_workers", data.get("num_workers", 0))) mixed_precision = "fp16" num_train_timesteps = int(diffusion.get("num_train_timesteps", 1000))
# Keep newly generated predictions separate from the archived cluster # results. A caller may provide ``inference.output_root`` in the YAML, # which is particularly useful for a small reproducibility run. Preserve # the historical in-source default for legacy configs that do not provide # an override. output_root_value = inference.get("output_root") if output_root_value: output_root = _resolve_path(config_path, str(output_root_value)) else: output_root = os.path.join( os.path.dirname(os.path.abspath(__file__)), "inference_results", ) output_dirs = { variant: os.path.join(output_root, variant) for variant in (VARIANT_RADAR, VARIANT_DIFFUSION, VARIANT_FULL) } gather_dir = os.path.join(output_root, "_gather")
sequences = _discover_sequences(smoke_eval_root) return { "smoke_eval_root": smoke_eval_root, "checkpoints": resolved_checkpoints, "target_height": target_height, "target_width": target_width, "frame_skip": frame_skip, "num_frames": num_frames, "scale_factor": scale_factor, "max_depth_m": max_depth_m, "batch_size": batch_size, "num_workers": num_workers, "mixed_precision": mixed_precision, "num_train_timesteps": num_train_timesteps, "output_root": output_root, "output_dirs": output_dirs, "gather_dir": gather_dir, "sequences": sequences, }
def _make_accelerator(runtime: Dict[str, object], stage: str) -> Accelerator: accelerator = Accelerator(mixed_precision=str(runtime["mixed_precision"])) set_seed(VALIDATION_NOISE_SEED)
if accelerator.is_main_process: for output_dir in runtime["output_dirs"].values(): os.makedirs(str(output_dir), exist_ok=True) os.makedirs(str(runtime["gather_dir"]), exist_ok=True) print(f"Stage: {stage}") print(f"Smoke-Eval: {runtime['smoke_eval_root']}") print(f"Sequences: {len(runtime['sequences'])}") print(f"Output root: {runtime['output_root']}") print( f"Mixed precision: {runtime['mixed_precision']} | " f"processes: {accelerator.num_processes} | " f"batch size: {runtime['batch_size']}" ) print( f"Validation sampling: seed={VALIDATION_NOISE_SEED} | " f"DDIM steps={VALIDATION_NUM_INFERENCE_STEPS}" ) accelerator.wait_for_everyone() return accelerator
def _remove_empty_gather_dir( accelerator: Accelerator, gather_dir: str,) -> None: accelerator.wait_for_everyone() if accelerator.is_main_process: if os.path.isdir(gather_dir) and not os.listdir(gather_dir): os.rmdir(gather_dir)
def run_radar(config_path: str) -> None: runtime = _load_runtime(config_path, required_checkpoints=("radar",)) accelerator = _make_accelerator(runtime, VARIANT_RADAR)
radar_model = RadarDepth() radar_state = _load_state_dict( runtime["checkpoints"]["radar"], ("model_state_dict", "state_dict"), "RadarDepth", ) radar_model.load_state_dict(radar_state, strict=True) radar_model.eval() for parameter in radar_model.parameters(): parameter.requires_grad = False radar_model = accelerator.prepare(radar_model)
_run_radar_stage( runtime["sequences"], runtime["smoke_eval_root"], runtime["output_dirs"][VARIANT_RADAR], runtime["gather_dir"], radar_model, accelerator, runtime["frame_skip"], runtime["num_frames"], runtime["batch_size"], runtime["num_workers"], runtime["scale_factor"], runtime["max_depth_m"], runtime["target_height"], runtime["target_width"], ) _remove_empty_gather_dir(accelerator, str(runtime["gather_dir"])) if accelerator.is_main_process: print(f"\n{VARIANT_RADAR} inference complete.")
def _load_radar_model(runtime: Dict[str, object]) -> torch.nn.Module: radar_model = RadarDepth() radar_state = _load_state_dict( runtime["checkpoints"]["radar"], ("model_state_dict", "state_dict"), "RadarDepth", ) radar_model.load_state_dict(radar_state, strict=True) radar_model.eval() for parameter in radar_model.parameters(): parameter.requires_grad = False return radar_model
def _load_vae_and_unet( runtime: Dict[str, object], accelerator: Accelerator,) -> Tuple[VAE, torch.nn.Module]:
vae = VAE(device=accelerator.device, torch_dtype=torch.float32) vae.vae.eval() for parameter in vae.vae.parameters(): parameter.requires_grad = False
sd_unet = SDUnet( use_pretrained=False, device=accelerator.device, torch_dtype=torch.float32, ) unet = sd_unet.unet unet_state = _load_state_dict( runtime["checkpoints"]["unet"], ("unet_state_dict", "model_state_dict", "state_dict"), "UNet", ) unet.load_state_dict(unet_state, strict=True) unet.eval() for parameter in unet.parameters(): parameter.requires_grad = False return vae, unet
def run_diffusion(config_path: str) -> None: runtime = _load_runtime(config_path, required_checkpoints=("radar", "unet")) accelerator = _make_accelerator(runtime, VARIANT_DIFFUSION) radar_model = _load_radar_model(runtime) vae, unet = _load_vae_and_unet(runtime, accelerator) radar_model, unet = accelerator.prepare(radar_model, unet)
_run_refinement_stage( VARIANT_DIFFUSION, runtime["sequences"], runtime["smoke_eval_root"], runtime["output_dirs"][VARIANT_DIFFUSION], runtime["gather_dir"], radar_model, unet, None, vae, accelerator, runtime["frame_skip"], runtime["num_frames"], runtime["batch_size"], runtime["num_workers"], runtime["scale_factor"], runtime["max_depth_m"], runtime["target_height"], runtime["target_width"], runtime["num_train_timesteps"], ) _remove_empty_gather_dir(accelerator, str(runtime["gather_dir"])) if accelerator.is_main_process: print(f"\n{VARIANT_DIFFUSION} inference complete.")
def run_full(config_path: str) -> None: runtime = _load_runtime( config_path, required_checkpoints=("radar", "unet", "controlnet"), ) accelerator = _make_accelerator(runtime, VARIANT_FULL) radar_model = _load_radar_model(runtime) vae, unet = _load_vae_and_unet(runtime, accelerator)
controlnet = ControlNetModel.from_unet(unet) controlnet_state = _load_state_dict( runtime["checkpoints"]["controlnet"], ("controlnet_state_dict", "model_state_dict", "state_dict"), "ControlNet", ) controlnet.load_state_dict(controlnet_state, strict=True) controlnet.eval() for parameter in controlnet.parameters(): parameter.requires_grad = False
radar_model, unet, controlnet = accelerator.prepare( radar_model, unet, controlnet, ) _run_refinement_stage( VARIANT_FULL, runtime["sequences"], runtime["smoke_eval_root"], runtime["output_dirs"][VARIANT_FULL], runtime["gather_dir"], radar_model, unet, controlnet, vae, accelerator, runtime["frame_skip"], runtime["num_frames"], runtime["batch_size"], runtime["num_workers"], runtime["scale_factor"], runtime["max_depth_m"], runtime["target_height"], runtime["target_width"], runtime["num_train_timesteps"], ) _remove_empty_gather_dir(accelerator, str(runtime["gather_dir"])) if accelerator.is_main_process: print(f"\n{VARIANT_FULL} inference complete.")123456789101112131415#!/usr/bin/env python3"""Run full ControlNet inference with validation-matched RadarDepth conditioning."""
from inference import parse_stage_args, run_full
def main() -> None: args = parse_stage_args( "Run ours_full with the train_control-defish.validate() sampling setup." ) run_full(args.config)
if __name__ == "__main__": main()12345678910111213141516171819202122"""Compatibility export for the Stage-1 radar-depth model.
Stage-2 entry points historically imported ``models.radar_depth`` from theirown source folder. The canonical implementation now lives in the explicit``GRADE/stage1_radar_depth_module`` directory; re-exporting it here keeps thosereleased entry points and their safetensors state-dict keys unchanged."""
from __future__ import annotations
import sysfrom pathlib import Path
STAGE1_DIR = Path(__file__).resolve().parents[2] / "stage1_radar_depth_module"if str(STAGE1_DIR) not in sys.path: sys.path.insert(0, str(STAGE1_DIR))
from radar_depth import RadarDepth # noqa: E402
__all__ = ["RadarDepth"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455from pathlib import Path
import torchimport torch.nn as nn
from diffusers import UNet2DConditionModel
class SDUnet: MODEL_PATH = Path(__file__).resolve().parents[4] / "checkpoints" / "misc" / "marigold_unet" def __init__(
self,
use_pretrained=False,
device="cuda",
torch_dtype=torch.float16,
):
"""
Initialize SD UNet (Marigold).
Args:
use_pretrained: Whether to load pretrained weights
device: Device to load model on
torch_dtype: Data type for model weights
"""
self.device = device
self.torch_dtype = torch_dtype
self._init_unet(use_pretrained)
def _init_unet(self, use_pretrained):
# The released checkpoint supplies learned weights; this bundled file # provides only the corresponding architecture configuration. model_path = str(self.MODEL_PATH)
if use_pretrained:
# OPTIMIZATION 1: Pass torch_dtype inside from_pretrained.
# This loads the weights directly in the target precision (fp16/bf16),
# preventing the CPU RAM spike of loading the full fp32 model first.
self.unet = UNet2DConditionModel.from_pretrained(
model_path, torch_dtype=self.torch_dtype,
use_safetensors=True, local_files_only=True, ).to(self.device)
else:
# Initialize random weights from config (for training from scratch)
config = UNet2DConditionModel.load_config(
pretrained_model_name_or_path=model_path, local_files_only=True )
# from_config usually initializes in float32 on CPU, so we must cast after.
self.unet = UNet2DConditionModel.from_config(config).to(
self.device, dtype=self.torch_dtype
)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566from pathlib import Path
import torchfrom diffusers import AutoencoderTiny
class VAE: # Bundled with the artifact so inference does not depend on a user cache # or network access. MODEL_PATH = Path(__file__).resolve().parents[4] / "checkpoints" / "misc" / "taesd"
def __init__(self, device, torch_dtype):
self.device = device
self.torch_dtype = torch_dtype
self.scaling_factor = 0.18215
self._init_vae()
def _init_vae(self):
# When loading a model with known architecture mismatches,
# it's safer to disable low_cpu_mem_usage. This prevents
# the creation of "meta" tensors that cause errors on .to(device).
vae = AutoencoderTiny.from_pretrained(
str(self.MODEL_PATH), local_files_only=True, torch_dtype=self.torch_dtype,
).to(self.device, memory_format=torch.channels_last)
print("Loaded bundled TAESD.")
for param in vae.parameters():
param.requires_grad = False
# Compile the entire VAE module after it's on the correct device
self.vae = vae
def encode_latent(self, input_neg_one_to_one):
"""Encodes an input tensor from the range [-1, 1]."""
input_tensor = input_neg_one_to_one.to(
self.device, dtype=self.torch_dtype, memory_format=torch.channels_last
)
# with torch.no_grad():
# # Call the compiled VAE's encode method
latents = self.vae.encode(input_tensor).latents * self.scaling_factor
return latents
def decode_latent(self, latents):
"""
Decodes latents back into image space.
Note: VAE parameters are frozen (requires_grad=False), but gradients
can still flow through this operation for backpropagation to upstream models.
"""
latents = latents.to(
self.device, dtype=self.torch_dtype, memory_format=torch.channels_last
)
# Decode without blocking gradients (VAE is frozen via requires_grad=False)
decoded = self.vae.decode(latents / self.scaling_factor).sample
# Output in [0, 1] range
decoded_zero_one = (decoded * 0.5 + 0.5).clamp(0, 1)
# Output in [-1, 1] range
decoded_neg_pos = decoded.clamp(-1, 1)
return decoded_zero_one, decoded_neg_pos
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183import numpy as npimport torchfrom pathlib import Pathfrom typing import Dict, List, Optional, Tuplefrom collate_fn_helpers import dji_rgb_collator, radar_collator, depth_collatorfrom torch.utils.data import Dataset
class RiceDataset(Dataset): """Dataset for aligned radar and DJI RGB frames.
Supports causal sliding-window data loading. For target frame at index i, returns frames [i-(F-1), ..., i-1, i]. When i < F-1, the window is padded by repeating the first available frame of the sequence.
Each tensor always has a leading frame dimension (F, ...), even when F=1. """
RGB_FILENAME = "dji_rgb.npy"
def __init__( self, root_dir: str, sequences: Optional[List[str]] = None, frame_skip: int = 1, depth_in_meters: bool = True, rgb_normalize: bool = True, frame_split: Optional[str] = None, # 'train' | 'val' | None for all frames frame_val_ratio: float = 0.2, # fraction of frames reserved for val # Processing parameters scale_factor: float = 0.001, max_depth_m: float = 11.2, depth_resolution: Tuple[int, int] = (128, 256), use_rgb: bool = True, rgb_resolution: Tuple[int, int] = (128, 256), num_frames: int = 1, ): self.root_dir = Path(root_dir) self.frame_skip = max(1, frame_skip) self.depth_in_meters = depth_in_meters self.rgb_normalize = rgb_normalize self.frame_split = frame_split self.frame_val_ratio = frame_val_ratio self.num_frames = max(1, num_frames)
# Processing parameters self.proc_params = { "scale_factor": scale_factor, "max_depth_m": max_depth_m, "depth_res": depth_resolution, "use_rgb": use_rgb, "rgb_res": rgb_resolution, }
self.sequences = self._discover_sequences(sequences) self.index_map: List[Tuple[str, int]] = [] self._seq_arrays: Dict[str, Dict] = {}
self._build_index()
# Frame-level split: slice the flat index_map deterministically. # Sequences are sorted, so the order is identical on every DDP rank. if self.frame_split is not None: n_total = len(self.index_map) n_val = int(n_total * self.frame_val_ratio) n_train = n_total - n_val if self.frame_split == "train": self.index_map = self.index_map[:n_train] elif self.frame_split == "val": self.index_map = self.index_map[n_train:]
def _discover_sequences(self, sequences: Optional[List[str]] = None) -> List[str]: if not self.root_dir.is_dir(): raise FileNotFoundError(f"Root directory not found: {self.root_dir}")
all_seqs = sorted( d.name for d in self.root_dir.iterdir() if d.is_dir() and not d.name.startswith(".") )
required_base = ["radar.npy"]
valid = [ name for name in all_seqs if all((self.root_dir / name / f).exists() for f in required_base) and ( not self.proc_params["use_rgb"] or (self.root_dir / name / self.RGB_FILENAME).exists() ) ] if sequences is not None: valid = [s for s in valid if s in sequences] return valid
def _build_index(self) -> None: self.index_map.clear() for seq_name in self.sequences: seq_dir = self.root_dir / seq_name radar = np.load(seq_dir / "radar.npy", mmap_mode="r") n_frames = radar.shape[0] if self.proc_params["use_rgb"]: rgb = np.load(seq_dir / self.RGB_FILENAME, mmap_mode="r") n_frames = min(n_frames, rgb.shape[0]) for i in range(0, n_frames, self.frame_skip): self.index_map.append((seq_name, i))
def _load_sequence_arrays(self, seq_name: str) -> Dict: if seq_name not in self._seq_arrays: seq_dir = self.root_dir / seq_name arrays = { "radar": np.load(seq_dir / "radar.npy", mmap_mode="r"), } if self.proc_params["use_rgb"]: arrays["rgb"] = np.load( seq_dir / self.RGB_FILENAME, mmap_mode="r" ) self._seq_arrays[seq_name] = arrays return self._seq_arrays[seq_name]
def __len__(self) -> int: return len(self.index_map)
def _get_window_indices(self, frame_idx: int) -> List[int]: """Return causal window indices [i-(F-1), ..., i] with left-padding.
Frames before the start of the sequence are clamped to frame 0. """ indices = [] for offset in range(self.num_frames - 1, -1, -1): idx = frame_idx - offset indices.append(max(0, idx)) return indices
def _process_single_frame(self, arrs: Dict, fi: int) -> Dict[str, torch.Tensor]: """Process a single frame index and return processed tensors.""" # === Radar === radar = np.asarray(arrs["radar"][fi].copy()) radar_amp = torch.from_numpy(np.abs(radar).astype(np.float32)) radar_phase = torch.from_numpy( (np.angle(radar) / np.pi).astype(np.float32) )
processed_radar = radar_collator( radar_amp.unsqueeze(0), radar_phase.unsqueeze(0), scale_factor=self.proc_params["scale_factor"], ).squeeze(0)
frame_out: Dict[str, torch.Tensor] = {"radar": processed_radar}
# === RGB === if self.proc_params["use_rgb"]: rgb = np.asarray(arrs["rgb"][fi]) rgb = np.transpose(rgb, (2, 0, 1)) if self.rgb_normalize: rgb = rgb.astype(np.float32) / 255.0 rgb_tensor = torch.from_numpy(rgb)
frame_out["rgb"] = dji_rgb_collator( rgb_tensor.unsqueeze(0), target_size=self.proc_params["rgb_res"], ).squeeze(0)
return frame_out
def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]: seq_name, frame_idx = self.index_map[idx] arrs = self._load_sequence_arrays(seq_name)
# Always return tensors with a leading frame dimension (F, ...) window_indices = self._get_window_indices(frame_idx) frame_outs = [self._process_single_frame(arrs, fi) for fi in window_indices]
# Stack each key along a new leading frame dimension keys = frame_outs[0].keys() out = {k: torch.stack([f[k] for f in frame_outs], dim=0) for k in keys} out["sequence"] = seq_name out["frame_idx"] = frame_idx return out
.gitignoreAdded+4
README.mdAdded+111
SHA256SUMSAdded+4
checkpoints/grade/control.safetensorsAdded+3
checkpoints/grade/diffusion.safetensorsAdded+3
checkpoints/grade/radar.safetensorsAdded+3
checkpoints/misc/marigold_unet/config.jsonAdded+72
checkpoints/misc/taesd/config.jsonAdded+39
checkpoints/misc/taesd/diffusion_pytorch_model.safetensorsAdded+3
config.yamlAdded+14
requirements.txtAdded+9
src/GRADE/stage1_radar_depth_module/__init__.pyAdded+5
src/GRADE/stage1_radar_depth_module/radar_depth.pyAdded+406
src/GRADE/stage2_diffusion_refinement/collate_fn_helpers.pyAdded+287
src/GRADE/stage2_diffusion_refinement/inference.pyAdded+829
src/GRADE/stage2_diffusion_refinement/inference_full.pyAdded+15
src/GRADE/stage2_diffusion_refinement/models/radar_depth.pyAdded+22
src/GRADE/stage2_diffusion_refinement/models/unet.pyAdded+55
src/GRADE/stage2_diffusion_refinement/models/vae.pyAdded+66
src/GRADE/stage2_diffusion_refinement/rice_dataset.pyAdded+183