argus-edge / argus_edge.py
phanerozoic's picture
argus_edge.py: fix stride list to [8,16,32,64,128]; correct module docstring
e0c0d2d verified
Raw History Blame Contribute Delete
17.1 kB
"""Argus-Edge: multi-task perception on a frozen EUPE-ViT-T backbone.
Five tasks on a 5.5M ViT-T backbone + ~9.6M of task heads = ~15.1M total.
The backbone is frozen throughout; each head is trained independently on
cached backbone features.
Tasks (same interface as argus / argus-lite):
- classification (1000 ImageNet classes, Linear(192, 1000) on CLS)
- semantic seg (150 ADE20K classes, DPT decoder over hooked blocks 2, 5, 8, 11)
- metric depth (DPT decoder, 256 log-depth bins, SILog loss)
- object detection (80 COCO classes, SplitTowerHead, FCOS-style targets)
- correspondence (cosine max on patch tokens, 0 extra params)
"""
import os
import sys
import time
from pathlib import Path
from typing import List, Optional, Union
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from safetensors.torch import load_file, save_file
try:
import argus as argus_module
HAS_ARGUS = True
except ImportError:
HAS_ARGUS = False
IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)
HOOK_BLOCKS = (2, 5, 8, 11)
N_PREFIX_TOKENS = 5 # 1 CLS + 4 storage tokens
EMBED_DIM = 192
DEPTH_RES = 416
SEG_RES = 512
DET_RES = 768
CLS_RES = 224
def _build_vitt16():
return argus_module.DinoVisionTransformer(
img_size=224, patch_size=16, in_chans=3,
pos_embed_rope_base=100, pos_embed_rope_normalize_coords='separate',
pos_embed_rope_rescale_coords=2, pos_embed_rope_dtype='fp32',
embed_dim=EMBED_DIM, depth=12, num_heads=3, ffn_ratio=4,
qkv_bias=True, drop_path_rate=0.0, layerscale_init=1e-5,
norm_layer='layernormbf16', ffn_layer='mlp',
ffn_bias=True, proj_bias=True, n_storage_tokens=4, mask_k_bias=True,
)
# ---- local copy of head module classes (mirrors heads_edge.py) ----
class _ResidualConvUnit(nn.Module):
def __init__(self, dim):
super().__init__()
self.conv1 = nn.Conv2d(dim, dim, 3, padding=1, padding_mode='reflect', bias=False)
self.bn1 = nn.BatchNorm2d(dim)
self.conv2 = nn.Conv2d(dim, dim, 3, padding=1, padding_mode='reflect', bias=False)
self.bn2 = nn.BatchNorm2d(dim)
self.act = nn.GELU()
def forward(self, x):
return x + self.bn2(self.conv2(self.act(self.bn1(self.conv1(x)))))
class _FeatureFusionBlock(nn.Module):
def __init__(self, dim, has_skip=True):
super().__init__()
self.rcu1 = _ResidualConvUnit(dim)
self.rcu2 = _ResidualConvUnit(dim)
self.skip_proj = nn.Conv2d(dim, dim, 1) if has_skip else None
def forward(self, x, skip=None):
if skip is not None and self.skip_proj is not None:
x = x + self.skip_proj(skip)
x = self.rcu1(x)
x = self.rcu2(x)
return F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)
class _DPTReassemble(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
self.norms = nn.ModuleList([nn.GroupNorm(1, in_dim) for _ in range(4)])
self.projs = nn.ModuleList([nn.Conv2d(in_dim, out_dim, 1) for _ in range(4)])
self.refine = nn.ModuleList([
nn.Sequential(
nn.Conv2d(out_dim, out_dim, 3, padding=1, padding_mode='reflect', bias=False),
nn.BatchNorm2d(out_dim),
nn.GELU(),
) for _ in range(4)
])
def forward(self, levels):
out = [r(p(n(f))) for f, n, p, r in
zip(levels, self.norms, self.projs, self.refine)]
l4 = F.interpolate(out[0], scale_factor=4, mode='bilinear', align_corners=False)
l8 = F.interpolate(out[1], scale_factor=2, mode='bilinear', align_corners=False)
l16 = out[2]
l32 = F.interpolate(out[3], scale_factor=0.5, mode='bilinear', align_corners=False)
return [l4, l8, l16, l32]
class _DPTDecoder(nn.Module):
def __init__(self, in_dim, dec_dim, out_channels, out_res):
super().__init__()
self.reassemble = _DPTReassemble(in_dim, dec_dim)
self.fusion = nn.ModuleList([
_FeatureFusionBlock(dec_dim, has_skip=True),
_FeatureFusionBlock(dec_dim, has_skip=True),
_FeatureFusionBlock(dec_dim, has_skip=True),
_FeatureFusionBlock(dec_dim, has_skip=False),
])
self.head = nn.Sequential(
nn.Conv2d(dec_dim, dec_dim, 3, padding=1, padding_mode='reflect', bias=False),
nn.BatchNorm2d(dec_dim),
nn.GELU(),
nn.Conv2d(dec_dim, out_channels, 1),
)
self.out_res = int(out_res)
def forward(self, levels):
rs = self.reassemble(levels)
x = self.fusion[3](rs[3])
x = self.fusion[2](x, skip=rs[2])
x = self.fusion[1](x, skip=rs[1])
x = self.fusion[0](x, skip=rs[0])
logits = self.head(x)
return F.interpolate(logits, size=(self.out_res, self.out_res),
mode='bilinear', align_corners=False)
# ---- Head wrappers ----
class ClassifierHead(nn.Module):
def __init__(self, in_dim=EMBED_DIM, n_classes=1000):
super().__init__()
self.fc = nn.Linear(in_dim, n_classes)
def forward(self, cls_token):
return self.fc(F.normalize(cls_token, dim=-1))
class SegHead(nn.Module):
def __init__(self, in_dim=EMBED_DIM, dec_dim=128, n_classes=150, out_res=SEG_RES):
super().__init__()
self.decoder = _DPTDecoder(in_dim, dec_dim, n_classes, out_res)
def forward(self, levels):
return self.decoder(levels)
class DepthHead(nn.Module):
def __init__(self, in_dim=EMBED_DIM, dec_dim=128, n_bins=256, out_res=DEPTH_RES,
min_depth=0.001, max_depth=10.0):
super().__init__()
self.decoder = _DPTDecoder(in_dim, dec_dim, n_bins, out_res)
bin_edges = torch.linspace(np.log(min_depth), np.log(max_depth), n_bins + 1).exp()
self.register_buffer('bin_centers', 0.5 * (bin_edges[:-1] + bin_edges[1:]))
def forward_logits(self, levels):
return self.decoder(levels)
def forward(self, levels):
logits = self.forward_logits(levels)
prob = F.softmax(logits, dim=1)
centers = self.bin_centers.view(1, -1, 1, 1)
return (prob * centers).sum(dim=1, keepdim=True)
def _build_detection_head(n_classes=80):
"""SplitTower detection head from the argus module, feat_dim=192 for ViT-T."""
if not HAS_ARGUS:
raise ImportError("argus_edge depends on argus.SplitTowerHead")
return argus_module.SplitTowerHead(
feat_dim=EMBED_DIM, hidden=160, n_std_layers=5, n_dw_layers=4,
n_scales=4, pos_emb_dim=64, num_classes=n_classes, text_embed_dim=768,
)
# ---- Main model ----
class ArgusEdge(nn.Module):
"""EUPE-ViT-T backbone (trainable) + 5 task heads."""
def __init__(self, class_names: Optional[List[str]] = None,
seg_classes: int = 150, det_num_classes: int = 80):
super().__init__()
if not HAS_ARGUS:
raise ImportError(
"argus_edge depends on the argus module for "
"DinoVisionTransformer (put argus.py on sys.path).")
self.backbone = _build_vitt16()
self.classifier = ClassifierHead(EMBED_DIM, 1000)
self.seg_head = SegHead(EMBED_DIM, 128, seg_classes, SEG_RES)
self.depth_head = DepthHead(EMBED_DIM, 128, 256, DEPTH_RES)
self.detection_head = _build_detection_head(det_num_classes)
self.class_names = class_names or [f'class_{i}' for i in range(1000)]
self.mean = torch.tensor(IMAGENET_MEAN).view(1, 3, 1, 1)
self.std = torch.tensor(IMAGENET_STD).view(1, 3, 1, 1)
self._hook_cache = {}
@classmethod
def from_pretrained(cls, repo_or_dir: str,
backbone_ckpt: Optional[str] = None, **kw):
model = cls(**kw)
if os.path.isdir(repo_or_dir):
fetch = lambda name: os.path.join(repo_or_dir, name)
else:
from huggingface_hub import hf_hub_download
fetch = lambda name: hf_hub_download(repo_or_dir, name)
def _try_fetch(fname):
try:
p = fetch(fname)
return p if os.path.isfile(p) else None
except Exception:
return None
def _maybe_load(module, fname):
p = _try_fetch(fname)
if p is not None:
module.load_state_dict(load_file(p))
_maybe_load(model.classifier, 'cls_head.safetensors')
_maybe_load(model.seg_head, 'seg_head.safetensors')
_maybe_load(model.depth_head, 'depth_head.safetensors')
_maybe_load(model.detection_head, 'det_head.safetensors')
bb_path = _try_fetch('backbone.safetensors')
if bb_path:
model.backbone.load_state_dict(load_file(bb_path), strict=False)
else:
if backbone_ckpt is None:
from huggingface_hub import hf_hub_download
backbone_ckpt = hf_hub_download('facebook/EUPE-ViT-T', 'EUPE-ViT-T.pt')
sd = torch.load(backbone_ckpt, map_location='cpu', weights_only=False)
sd_bb = {k: v for k, v in sd.items() if not k.startswith('projectors.')}
model.backbone.load_state_dict(sd_bb, strict=False)
return model
def save(self, out_dir):
os.makedirs(out_dir, exist_ok=True)
save_file(self.classifier.state_dict(), f'{out_dir}/cls_head.safetensors')
save_file(self.seg_head.state_dict(), f'{out_dir}/seg_head.safetensors')
save_file(self.depth_head.state_dict(), f'{out_dir}/depth_head.safetensors')
save_file(self.detection_head.state_dict(), f'{out_dir}/det_head.safetensors')
save_file(self.backbone.state_dict(), f'{out_dir}/backbone.safetensors')
def _to_image(self, image):
if isinstance(image, (str, Path)):
return Image.open(image).convert('RGB')
return image.convert('RGB')
def _preprocess(self, img, res):
img = img.resize((res, res), Image.BILINEAR)
arr = np.asarray(img.convert('RGB'), dtype=np.uint8).copy()
x = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).float() / 255.0
return (x - self.mean.to(x)) / self.std.to(x)
def _device(self):
return next(self.parameters()).device
def _register_hooks(self):
self._hook_cache.clear()
handles = []
for b in HOOK_BLOCKS:
def mk(i):
def hook(_m, _i, out):
while isinstance(out, (list, tuple)):
out = out[0]
self._hook_cache[i] = out
return hook
handles.append(self.backbone.blocks[b].register_forward_hook(mk(b)))
return handles
@staticmethod
def _tokens_to_spatial(tokens, n_prefix=N_PREFIX_TOKENS):
patches = tokens[:, n_prefix:, :]
B, HW, C = patches.shape
s = int(HW ** 0.5)
return patches.transpose(1, 2).reshape(B, C, s, s)
@torch.inference_mode()
def classify(self, image, top_k=5):
img = self._to_image(image)
x = self._preprocess(img, CLS_RES).to(self._device())
with torch.autocast('cuda', dtype=torch.bfloat16):
out = self.backbone.forward_features(x)
logits = self.classifier(out['x_norm_clstoken'].float()).squeeze(0)
probs = F.softmax(logits, dim=-1)
top = torch.topk(probs, top_k)
return {
'label': self.class_names[top.indices[0].item()],
'score': float(top.values[0].item()),
f'top{top_k}': [(self.class_names[i], float(v.item()))
for i, v in zip(top.indices.tolist(), top.values)],
}
@torch.inference_mode()
def segment(self, image):
img = self._to_image(image)
x = self._preprocess(img, SEG_RES).to(self._device())
handles = self._register_hooks()
try:
with torch.autocast('cuda', dtype=torch.bfloat16):
_ = self.backbone.forward_features(x)
finally:
for h in handles:
h.remove()
levels = [self._tokens_to_spatial(self._hook_cache[b].float()) for b in HOOK_BLOCKS]
logits = self.seg_head(levels)
return logits.argmax(dim=1).squeeze(0).cpu().numpy()
@torch.inference_mode()
def depth(self, image):
img = self._to_image(image)
x = self._preprocess(img, DEPTH_RES).to(self._device())
handles = self._register_hooks()
try:
with torch.autocast('cuda', dtype=torch.bfloat16):
_ = self.backbone.forward_features(x)
finally:
for h in handles:
h.remove()
levels = [self._tokens_to_spatial(self._hook_cache[b].float()) for b in HOOK_BLOCKS]
d = self.depth_head(levels)
return d.squeeze(0).squeeze(0).cpu().numpy()
@torch.inference_mode()
def detect(self, image, score_thresh=0.05, nms_iou=0.6, top_k=100):
from torchvision.ops import nms
img = self._to_image(image)
x = self._preprocess(img, DET_RES).to(self._device())
with torch.autocast('cuda', dtype=torch.bfloat16):
out = self.backbone.forward_features(x)
patches = out['x_norm_patchtokens'].float() # (B, HW, C) already patches-only
B_, HW, C_ = patches.shape
s = int(HW ** 0.5)
spatial = patches.transpose(1, 2).reshape(B_, C_, s, s)
cls_l, reg_l, ctr_l = self.detection_head(spatial)
strides = [8, 16, 32, 64, 128]
locs = []
for (c, s) in zip(cls_l, strides):
_, _, h, w = c.shape
ys = (torch.arange(h, device=x.device) + 0.5) * s
xs = (torch.arange(w, device=x.device) + 0.5) * s
gy, gx = torch.meshgrid(ys, xs, indexing='ij')
locs.append(torch.stack([gx.flatten(), gy.flatten()], -1))
locs = torch.cat(locs, 0)
n_classes = getattr(self.detection_head, 'num_classes',
getattr(self.detection_head, 'n_classes', 80))
cls_flat = torch.cat([c.permute(0, 2, 3, 1).reshape(-1, n_classes) for c in cls_l], 0)
reg_flat = torch.cat([r.permute(0, 2, 3, 1).reshape(-1, 4) for r in reg_l], 0)
ctr_flat = torch.cat([c.permute(0, 2, 3, 1).reshape(-1) for c in ctr_l], 0)
scores = cls_flat.sigmoid() * ctr_flat.sigmoid().unsqueeze(-1)
x1 = (locs[:, 0] - reg_flat[:, 0]).clamp(0, DET_RES)
y1 = (locs[:, 1] - reg_flat[:, 1]).clamp(0, DET_RES)
x2 = (locs[:, 0] + reg_flat[:, 2]).clamp(0, DET_RES)
y2 = (locs[:, 1] + reg_flat[:, 3]).clamp(0, DET_RES)
boxes = torch.stack([x1, y1, x2, y2], 1)
W0, H0 = img.size
sx, sy = W0 / DET_RES, H0 / DET_RES
dets = []
for c in range(n_classes):
m = scores[:, c] > score_thresh
if not m.any():
continue
b = boxes[m]; s = scores[m, c]
k = nms(b, s, nms_iou)[:top_k]
for j in k.tolist():
bx = b[j].tolist()
dets.append({'box': [bx[0]*sx, bx[1]*sy, bx[2]*sx, bx[3]*sy],
'score': float(s[j].item()), 'class_id': c})
dets.sort(key=lambda d: -d['score'])
return dets[:top_k]
@torch.inference_mode()
def correspond(self, image_a, image_b, res=SEG_RES):
a = self._to_image(image_a)
b = self._to_image(image_b)
dev = self._device()
xa = self._preprocess(a, res).to(dev)
xb = self._preprocess(b, res).to(dev)
with torch.autocast('cuda', dtype=torch.bfloat16):
oa = self.backbone.forward_features(xa)
ob = self.backbone.forward_features(xb)
pa = F.normalize(oa['x_norm_patchtokens'].float().squeeze(0), dim=-1)
pb = F.normalize(ob['x_norm_patchtokens'].float().squeeze(0), dim=-1)
sim = pa @ pb.t()
m = sim.argmax(dim=-1)
s = sim.max(dim=-1).values
grid = int(np.sqrt(pa.shape[0]))
return {'matches': m.cpu().numpy(), 'scores': s.cpu().numpy(), 'grid': grid}
@torch.inference_mode()
def perceive(self, image, image_b=None):
img = self._to_image(image)
t0 = time.time()
c = self.classify(img)
t1 = time.time()
s = self.segment(img)
t2 = time.time()
d = self.depth(img)
t3 = time.time()
det = self.detect(img)
t4 = time.time()
corr = self.correspond(img, image_b) if image_b is not None else None
t5 = time.time()
return {
'classification': c, 'segmentation': s, 'depth': d,
'detection': det, 'correspondence': corr,
'timings_ms': {'classify': (t1-t0)*1000, 'segment': (t2-t1)*1000,
'depth': (t3-t2)*1000, 'detect': (t4-t3)*1000,
'correspond': (t5-t4)*1000 if image_b is not None else None,
'total': (t5-t0)*1000},
}