Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions .github/workflows/onnx_export.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
name: ONNX export

# Export the ONNX model on CPU and check it against the PyTorch implementation:
# dense perspective fields, confidences, and calibrated camera and gravity
# parameters.

on:
push:
branches: [main]
paths:
- "geocalib/**"
- "onnx/**"
- "requirements.txt"
- "pyproject.toml"
- ".github/workflows/onnx_export.yml"
pull_request:
paths:
- "geocalib/**"
- "onnx/**"
- "requirements.txt"
- "pyproject.toml"
- ".github/workflows/onnx_export.yml"

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
export-and-check:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4

- uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip

- name: Install dependencies
run: |
python -m pip install --upgrade pip
# CPU-only PyTorch; the export and its check depend on these versions.
python -m pip install torch==2.6.0 torchvision==0.21.0 --index-url https://download.pytorch.org/whl/cpu
python -m pip install numpy opencv-python-headless kornia matplotlib \
onnx==1.23.2 onnxruntime==1.23.2
python -m pip install --no-deps -e .

- name: Cache the weights
uses: actions/cache@v4
with:
path: ~/.cache/torch/hub/geocalib
key: geocalib-weights-v1.0

- name: Export the ONNX model
run: python onnx/export.py --weights distorted --output_dir /tmp/geocalib_onnx

- name: Check the ONNX model
run: |
python onnx/check.py --cpu \
--weights distorted \
--model /tmp/geocalib_onnx/geocalib_distorted.onnx
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,4 @@ dmypy.json

# Pyre type checker
.pyre/
onnx/models/
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,17 @@ If several cameras are rigidly mounted (known relative rotations), GeoCalib can
result = model.calibrate(batch, camera_R_rig=camera_R_rig) # add shared_intrinsics=True if the cameras are identical
```

## ONNX export

GeoCalib's perspective field network can be exported to [ONNX](https://onnx.ai/) and run with [ONNX Runtime](https://onnxruntime.ai/) without PyTorch, as used by [COLMAP](https://github.com/colmap/colmap).

To export the model (requires `onnx`) and check it against the PyTorch implementation (also requires `onnxruntime`):
```bash
python onnx/export.py
python onnx/check.py --model onnx/models/geocalib_distorted.onnx
```
`onnx/check.py` can check any exported model against a PyTorch checkpoint (`--weights`).

## Evaluation

The full evaluation and training code is provided in the single-image calibration library [`siclib`](siclib), which can be installed as:
Expand Down
17 changes: 14 additions & 3 deletions geocalib/geocalib.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from torch.nn import functional as F

from geocalib.lm_optimizer import LMOptimizer
from geocalib.modules import MSCAN, ConvModule, LightHamHead
from geocalib.modules import MSCAN, NMF2D, ConvModule, LightHamHead

# mypy: ignore-errors

Expand Down Expand Up @@ -105,10 +105,21 @@ def __init__(self, **optimizer_options):

self.optimizer = LMOptimizer({**optimizer_options})

def predict_fields(self, image: torch.Tensor) -> Dict[str, torch.Tensor]:
"""Predict perspective fields and confidences for a batch of images."""
data = {"image": image}
features = {"hl": self.backbone(data)["features"], "ll": self.ll_enc(data)["features"]}
return self.perspective_decoder({"features": features})

def freeze_nmf_bases(self, seed: int = 0) -> None:
"""Fix the initial NMF2D bases in the decoder to a deterministic tensor."""
for module in self.perspective_decoder.modules():
if isinstance(module, NMF2D):
module.freeze_bases(seed=seed)

def forward(self, data: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""Forward pass."""
features = {"hl": self.backbone(data)["features"], "ll": self.ll_enc(data)["features"]}
out = self.perspective_decoder({"features": features})
out = self.predict_fields(data["image"])

out |= {
k: data[k]
Expand Down
24 changes: 19 additions & 5 deletions geocalib/modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,17 @@ def __init__(self):
self.train_steps = 6
self.eval_steps = 7
self.inv_t = 1
self.register_buffer("fixed_bases", None, persistent=False)

def freeze_bases(self, seed: int = 0) -> None:
"""Fix the initial NMF bases to a deterministic tensor."""
gen = torch.Generator(device="cpu").manual_seed(seed)
bases = torch.rand((1, self.D, self.R), generator=gen, dtype=torch.float32)
self.fixed_bases = F.normalize(bases, dim=1)

def _build_bases(self, B: int, S: int, D: int, R: int, device: str = "cpu") -> torch.Tensor:
if self.fixed_bases is not None:
return self.fixed_bases.expand(B * S, D, R).to(device)
bases = torch.rand((B * S, D, R)).to(device)
return F.normalize(bases, dim=1)

Expand Down Expand Up @@ -264,10 +273,15 @@ def forward(self, features: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torc
inputs = [features["hl"][i] for i in self.in_index]

inputs = [
F.interpolate(
level, size=inputs[0].shape[2:], mode="bilinear", align_corners=self.align_corners
level
if i == 0
else F.interpolate(
level,
scale_factor=float(2**i),
mode="bilinear",
align_corners=self.align_corners,
)
for level in inputs
for i, level in enumerate(inputs)
]

inputs = torch.cat(inputs, dim=1)
Expand All @@ -278,9 +292,9 @@ def forward(self, features: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torc
feats = self.align(x)

assert "ll" in features, "Low-level features are required for this model"
feats = F.interpolate(feats, scale_factor=2, mode="bilinear", align_corners=False)
feats = F.interpolate(feats, scale_factor=2.0, mode="bilinear", align_corners=False)
feats = self.out_conv(feats)
feats = F.interpolate(feats, scale_factor=2, mode="bilinear", align_corners=False)
feats = F.interpolate(feats, scale_factor=2.0, mode="bilinear", align_corners=False)
feats = self.ll_fusion(feats, features["ll"].clone())

uncertainty = self.linear_pred_uncertainty(feats).squeeze(1)
Expand Down
Loading
Loading