LoopVGGT / modeling_loopvggt.py
yifei-liu's picture
Initial release of LoopVGGT training-free AutoModel wrapper and Model Card
cc84701 verified
Raw History Blame Contribute Delete
12.8 kB
"""Training-free looped inference wrapper for VGGT-1B on Hugging Face Hub."""
from __future__ import annotations
from contextlib import nullcontext
from pathlib import Path
from typing import Any, Sequence
import torch
from huggingface_hub import hf_hub_download
from transformers import PreTrainedModel
from .configuration_loopvggt import LoopVGGTConfig
class AlternatingAttentionEulerLoop:
"""Loop a contiguous sequence of VGGT ``frame -> global`` block pairs.
The ordinary forward pass supplies Euler stage 1. Subsequent stages reuse
the same frozen block weights, and every stage applies a ``1 / stages``
damped update.
"""
def __init__(
self,
aggregator: torch.nn.Module,
start: int,
end: int,
stages: int = 4,
) -> None:
frame_blocks = getattr(aggregator, "frame_blocks", None)
global_blocks = getattr(aggregator, "global_blocks", None)
if frame_blocks is None or global_blocks is None:
raise TypeError("expected a VGGT aggregator with frame_blocks/global_blocks")
if len(frame_blocks) != len(global_blocks):
raise ValueError("frame_blocks and global_blocks must have equal length")
if not 0 <= start <= end < len(frame_blocks):
raise ValueError(
f"invalid window [{start}, {end}] for {len(frame_blocks)} logical layers"
)
if stages < 1:
raise ValueError("stages must be >= 1")
cached = set(getattr(aggregator, "cached_layer_indices", ()))
overlap = cached.intersection(range(start, end + 1))
if overlap:
raise ValueError(
f"loop window overlaps cached DPT feature layers: {sorted(overlap)}"
)
self.frame_blocks = frame_blocks
self.global_blocks = global_blocks
self.start = start
self.end = end
self.stages = stages
self._handles: list[Any] = []
self._replaying = False
self._x0: torch.Tensor | None = None
self._frame_pos: torch.Tensor | None = None
self._global_pos: torch.Tensor | None = None
self._frame_shape: torch.Size | None = None
self._global_shape: torch.Size | None = None
def attach(self) -> "AlternatingAttentionEulerLoop":
if self._handles or self.stages == 1:
return self
self._handles.append(
self.frame_blocks[self.start].register_forward_pre_hook(
self._capture_frame, with_kwargs=True
)
)
self._handles.append(
self.global_blocks[self.start].register_forward_pre_hook(
self._capture_global, with_kwargs=True
)
)
self._handles.append(
self.global_blocks[self.end].register_forward_hook(
self._finish_window, with_kwargs=True
)
)
return self
def remove(self) -> None:
for handle in self._handles:
handle.remove()
self._handles.clear()
self._clear_call()
def __enter__(self) -> "AlternatingAttentionEulerLoop":
return self.attach()
def __exit__(self, *_args: Any) -> None:
self.remove()
def _capture_frame(
self,
_module: torch.nn.Module,
args: tuple[Any, ...],
kwargs: dict[str, Any],
) -> None:
if self._replaying:
return
if not args or not isinstance(args[0], torch.Tensor):
raise RuntimeError("frame block did not receive tensor tokens")
self._x0 = args[0]
self._frame_shape = args[0].shape
self._frame_pos = kwargs.get("pos")
def _capture_global(
self,
_module: torch.nn.Module,
args: tuple[Any, ...],
kwargs: dict[str, Any],
) -> None:
if self._replaying:
return
if not args or not isinstance(args[0], torch.Tensor):
raise RuntimeError("global block did not receive tensor tokens")
self._global_shape = args[0].shape
self._global_pos = kwargs.get("pos")
def _run_window(self, hidden: torch.Tensor) -> torch.Tensor:
assert self._frame_shape is not None
assert self._global_shape is not None
for index in range(self.start, self.end + 1):
hidden = self.frame_blocks[index](
hidden.reshape(self._frame_shape), pos=self._frame_pos
)
hidden = self.global_blocks[index](
hidden.reshape(self._global_shape), pos=self._global_pos
)
return hidden
def _finish_window(
self,
_module: torch.nn.Module,
_args: tuple[Any, ...],
_kwargs: dict[str, Any],
output: torch.Tensor,
) -> torch.Tensor:
if self._replaying:
return output
if self._x0 is None or self._frame_shape is None or self._global_shape is None:
raise RuntimeError("loop window inputs were not captured")
if self._x0.numel() != output.numel():
raise RuntimeError("loop window changed the number of token elements")
x0 = self._x0.reshape(self._global_shape)
hidden = x0 + (output - x0) / self.stages
self._replaying = True
try:
for _ in range(1, self.stages):
proposal = self._run_window(hidden)
hidden = hidden + (proposal - hidden) / self.stages
finally:
self._replaying = False
self._clear_call()
return hidden
def _clear_call(self) -> None:
self._x0 = None
self._frame_pos = None
self._global_pos = None
self._frame_shape = None
self._global_shape = None
def _import_vggt():
try:
from vggt.models.vggt import VGGT
except ImportError as exc:
raise ImportError(
"LoopVGGT requires upstream VGGT installed. Install the pinned revision with:\n"
" pip install 'git+https://github.com/facebookresearch/vggt.git@a288dd0f14786c93483e45524328726ab7b1b4ce'"
) from exc
return VGGT
class LoopVGGTModel(PreTrainedModel):
"""Training-free looped inference wrapper around frozen ``facebook/VGGT-1B``.
Default forward pass replays attention pairs ``[5, 8]`` for ``K = 4``
damped Euler iterations while preserving VGGT's native computation graph
and output dictionary (``pose_enc``, ``depth``, ``depth_conf``, ``world_points``,
``world_points_conf``).
"""
config_class = LoopVGGTConfig
def __init__(self, config: LoopVGGTConfig) -> None:
super().__init__(config)
VGGT = _import_vggt()
self.vggt = VGGT(
img_size=config.img_size,
patch_size=config.patch_size,
embed_dim=config.embed_dim,
enable_camera=config.enable_camera,
enable_depth=config.enable_depth,
enable_point=config.enable_point,
enable_track=config.enable_track,
)
@classmethod
def from_pretrained(
cls,
pretrained_model_name_or_path: str | Path,
*model_args: Any,
config: LoopVGGTConfig | None = None,
checkpoint_path: str | Path | None = None,
cache_dir: str | Path | None = None,
local_files_only: bool = False,
token: str | bool | None = None,
torch_dtype: torch.dtype | None = None,
**kwargs: Any,
) -> "LoopVGGTModel":
"""Load LoopVGGT config from Hub and fetch frozen upstream VGGT-1B weights."""
revision = kwargs.pop("revision", None)
kwargs.pop("trust_remote_code", None)
if config is None:
config = LoopVGGTConfig.from_pretrained(
pretrained_model_name_or_path,
cache_dir=cache_dir,
local_files_only=local_files_only,
token=token,
revision=revision,
**kwargs,
)
model = cls(config)
if checkpoint_path is not None:
weights_file = Path(checkpoint_path)
if not weights_file.is_file():
raise FileNotFoundError(f"checkpoint not found: {weights_file}")
else:
weights_file = Path(
hf_hub_download(
repo_id=config.base_model_repo_id,
filename=config.base_model_filename,
revision=config.base_model_revision,
cache_dir=cache_dir,
local_files_only=local_files_only,
token=token,
)
)
state = torch.load(weights_file, map_location="cpu", weights_only=True)
if isinstance(state, dict) and "model" in state:
state = state["model"]
missing, unexpected = model.vggt.load_state_dict(state, strict=False)
if missing:
raise RuntimeError(f"checkpoint is missing VGGT parameters: {missing[:8]}")
allowed_disabled = []
if not config.enable_camera:
allowed_disabled.append("camera_head.")
if not config.enable_depth:
allowed_disabled.append("depth_head.")
if not config.enable_point:
allowed_disabled.append("point_head.")
if not config.enable_track:
allowed_disabled.append("track_head.")
bad = [
key
for key in unexpected
if not (allowed_disabled and key.startswith(tuple(allowed_disabled)))
]
if bad:
raise RuntimeError(f"unexpected VGGT checkpoint parameters: {bad[:8]}")
if torch_dtype is not None and torch_dtype != "auto":
model = model.to(dtype=torch_dtype)
model.eval()
return model
def forward(
self,
images: torch.Tensor,
query_points: torch.Tensor | None = None,
*,
looped: bool = True,
start: int | None = None,
end: int | None = None,
K: int | None = None,
) -> dict[str, torch.Tensor]:
"""Run VGGT inference with optional training-free Euler looping.
Args:
images: Preprocessed tensor of shape ``(S, 3, H, W)`` or ``(B, S, 3, H, W)``.
query_points: Optional query points passed through to VGGT's track head.
looped: Set ``False`` to run the unlooped VGGT-1B baseline.
start: Override loop window start index (default: ``config.loop_start = 5``).
end: Override loop window end index (default: ``config.loop_end = 8``).
K: Override total window evaluations (default: ``config.loop_k = 4``).
"""
win_start = self.config.loop_start if start is None else int(start)
win_end = self.config.loop_end if end is None else int(end)
stages = self.config.loop_k if K is None else int(K)
ctx = (
AlternatingAttentionEulerLoop(self.vggt.aggregator, win_start, win_end, stages)
if looped and stages > 1
else nullcontext()
)
with ctx:
return self.vggt(images, query_points=query_points)
@torch.inference_mode()
def predict_images(
self,
image_paths: Sequence[str | Path],
*,
mode: str = "crop",
looped: bool = True,
start: int | None = None,
end: int | None = None,
K: int | None = None,
autocast_dtype: torch.dtype | None = None,
) -> dict[str, Any]:
"""Load image paths with VGGT's preprocessor and decode poses + depth."""
from vggt.utils.load_fn import load_and_preprocess_images
from vggt.utils.pose_enc import pose_encoding_to_extri_intri
device = next(self.vggt.parameters()).device
images = load_and_preprocess_images([str(p) for p in image_paths], mode=mode).to(device)
if autocast_dtype is None:
if device.type == "cuda":
autocast_dtype = (
torch.bfloat16
if torch.cuda.get_device_capability(device)[0] >= 8
else torch.float16
)
else:
autocast_dtype = torch.float32
use_amp = device.type == "cuda" and autocast_dtype != torch.float32
with torch.amp.autocast(device_type=device.type, dtype=autocast_dtype, enabled=use_amp):
predictions = self.forward(
images, looped=looped, start=start, end=end, K=K
)
extrinsics, intrinsics = pose_encoding_to_extri_intri(
predictions["pose_enc"].float(), image_size_hw=images.shape[-2:]
)
predictions["extrinsics"] = extrinsics[0].float()
predictions["intrinsics"] = intrinsics[0].float()
predictions["images"] = images
return predictions