tarekziade's picture
tarekziade HF Staff
Publish MIC usage, slim fixture and reviewed Transformers expectations
fef0512 verified
|
Raw History Blame Contribute Delete
4.39 kB

DPT: depth estimation with Transformers

This page is the Transformers contract of the DPT MIC and also a usage example. doc-builder renders the runnable blocks below as documentation, and its pytest plugin runs them as written against Intel/dpt-large. The MIC runner runs the same blocks against the slim fixture and the checkpoint in integration.json. Lines marked # doc-builder: hide only matter there: they swap in the pinned checkpoint or variant and print the result record.

Predict a depth map

import torch
from transformers import AutoImageProcessor, AutoModelForDepthEstimation, set_seed
import json  # doc-builder: hide
import os  # doc-builder: hide
import numpy as np  # doc-builder: hide

model_id = "Intel/dpt-large"
model_id = os.environ.get("MIC_MODEL", model_id)  # doc-builder: hide
variant = json.loads(os.environ.get("MIC_MODEL_KWARGS", "{}"))  # doc-builder: hide
device = "cuda" if torch.cuda.is_available() else "cpu"
set_seed(0)  # seeds torch, NumPy, and Python: loading and dropout draw random numbers

processor = AutoImageProcessor.from_pretrained(model_id)
model = AutoModelForDepthEstimation.from_pretrained(model_id).to(device)
if variant:  # doc-builder: hide
    del model  # doc-builder: hide
    model = AutoModelForDepthEstimation.from_pretrained(model_id, **variant).to(device)  # doc-builder: hide
model.eval()

# two small synthetic images: a gradient and a checkerboard, so the batch is meaningful
h, w = 64, 64
gradient = torch.linspace(0, 1, h).view(h, 1, 1).expand(h, w, 3)
checker = (torch.arange(h).view(h, 1) // 8 + torch.arange(w).view(1, w) // 8) % 2
checker = checker.float().unsqueeze(-1).expand(h, w, 3)
# uint8: the processor rescales by 1/255, which would flatten floats in [0, 1].
images = [(gradient * 255).byte().permute(2, 0, 1).numpy(), (checker * 255).byte().permute(2, 0, 1).numpy()]
inputs = processor(images=images, return_tensors="pt")
inputs = inputs.to(device, dtype=model.dtype)

with torch.no_grad():
    outputs = model(**inputs)
    predicted_depth = outputs.predicted_depth

post_processed = processor.post_process_depth_estimation(
    outputs, target_sizes=[(h, w), (h, w)]
)
print(predicted_depth.shape)

One training step

# depth targets: smooth ramps matching the synthetic images
labels = torch.stack([
    torch.linspace(0.1, 1.0, h).view(h, 1).expand(h, w),
    torch.linspace(1.0, 0.1, h).view(h, 1).expand(h, w),
]).to(device=device, dtype=model.dtype)

model.train()
optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=0.01)
# DPTForDepthEstimation implements no training loss: regress the predicted depth
# (at the pixel_values resolution) onto the resized targets with L1.
predicted = model(**inputs).predicted_depth
target = torch.nn.functional.interpolate(labels[:, None], size=predicted.shape[-2:], mode="bilinear")[:, 0]
loss = torch.nn.functional.l1_loss(predicted.float(), target.float())
loss.backward()
before = {n: p.detach().cpu().clone() for n, p in model.named_parameters() if p.requires_grad}  # doc-builder: hide
optimizer.step()
print(f"loss: {loss.item():.4f}")

if os.environ.get("MIC_RUNNER"):  # doc-builder: hide
    named = dict(model.named_parameters())
    checked = (
        "dpt.encoder.layer.0.attention.attention.query.weight",
        "dpt.encoder.layer.0.intermediate.dense.weight",
        "head.head.0.weight",
    )
    result = {
        "runtime": {
            "device": model.device.type,
            "dtype": str(model.dtype).removeprefix("torch."),
            "attn_implementation": model.config._attn_implementation,
        },
        "predicted_depth_probe": predicted_depth.flatten()[:4].float().tolist(),
        "post_processed_depth_probe": post_processed[0]["predicted_depth"].flatten()[:4].float().tolist(),
        "training": {
            "loss": loss.item(),
            "gradients": {
                n: bool(named[n].grad is not None and torch.count_nonzero(named[n].grad) > 0 and torch.isfinite(named[n].grad).all())
                for n in checked
            },
            "updated": any(not torch.equal(p.detach().cpu(), before[n]) for n, p in model.named_parameters() if n in before),
        },
    }
    print(json.dumps(result))