|
| 1 | +import dash |
| 2 | +import dash_bootstrap_components as dbc |
| 3 | +import dash_labs as dl |
| 4 | +import plotly.express as px |
| 5 | +import plotly.graph_objs as go |
| 6 | +from plotly.subplots import make_subplots |
| 7 | +import requests |
| 8 | +import torch |
| 9 | +import torch.nn as nn |
| 10 | +from torchvision import transforms as pth_transforms |
| 11 | +from PIL import Image |
| 12 | +from flask_caching import Cache |
| 13 | + |
| 14 | + |
| 15 | +def download_img(url, size=(600, 600)): |
| 16 | + im = Image.open(requests.get(url, stream=True).raw).convert("RGB") |
| 17 | + im.thumbnail(size) |
| 18 | + return im |
| 19 | + |
| 20 | + |
| 21 | +# Source: https://github.com/facebookresearch/dino/blob/main/visualize_attention.py |
| 22 | +def compute_attentions(model, patch_size=16): |
| 23 | + def aux(img): |
| 24 | + # make the image divisible by the patch size |
| 25 | + w, h = ( |
| 26 | + img.shape[1] - img.shape[1] % patch_size, |
| 27 | + img.shape[2] - img.shape[2] % patch_size, |
| 28 | + ) |
| 29 | + img = img[:, :w, :h].unsqueeze(0) |
| 30 | + w_featmap = img.shape[-2] // patch_size |
| 31 | + h_featmap = img.shape[-1] // patch_size |
| 32 | + attentions = model.forward_selfattention(img) |
| 33 | + |
| 34 | + return attentions, w_featmap, h_featmap |
| 35 | + |
| 36 | + return aux |
| 37 | + |
| 38 | + |
| 39 | +# Source: https://github.com/facebookresearch/dino/blob/main/visualize_attention.py |
| 40 | +def apply_threshold(attentions, w_featmap, h_featmap, threshold, patch_size=16): |
| 41 | + nh = attentions.shape[1] # number of head |
| 42 | + # we keep only the output patch attention |
| 43 | + attentions = attentions[0, :, 0, 1:].reshape(nh, -1) |
| 44 | + # we keep only a certain percentage of the mass |
| 45 | + val, idx = torch.sort(attentions) |
| 46 | + val /= torch.sum(val, dim=1, keepdim=True) |
| 47 | + cumval = torch.cumsum(val, dim=1) |
| 48 | + th_attn = cumval > (1 - threshold) |
| 49 | + idx2 = torch.argsort(idx) |
| 50 | + for head in range(nh): |
| 51 | + th_attn[head] = th_attn[head][idx2[head]] |
| 52 | + th_attn = th_attn.reshape(nh, w_featmap, h_featmap).float() |
| 53 | + th_attn = nn.functional.interpolate( |
| 54 | + th_attn.unsqueeze(0), scale_factor=patch_size, mode="nearest" |
| 55 | + ) |
| 56 | + th_attn = th_attn[0].detach().cpu().numpy() |
| 57 | + |
| 58 | + attentions = attentions.reshape(nh, w_featmap, h_featmap) |
| 59 | + attentions = nn.functional.interpolate( |
| 60 | + attentions.unsqueeze(0), scale_factor=patch_size, mode="nearest" |
| 61 | + ) |
| 62 | + attentions = attentions[0].detach().cpu().numpy() |
| 63 | + |
| 64 | + return th_attn, attentions |
| 65 | + |
| 66 | + |
| 67 | +# VARS |
| 68 | +default_url = "https://dl.fbaipublicfiles.com/dino/img.png" |
| 69 | + |
| 70 | +# Load model |
| 71 | +torch.hub.set_dir("./") |
| 72 | +device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") |
| 73 | +print("Running on", device) |
| 74 | +model = torch.hub.load("facebookresearch/dino:main", "dino_deits16").to(device) |
| 75 | +transform = pth_transforms.Compose( |
| 76 | + [ |
| 77 | + pth_transforms.ToTensor(), |
| 78 | + pth_transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), |
| 79 | + ] |
| 80 | +) |
| 81 | + |
| 82 | +# Initialize dash app and dash-labs template |
| 83 | +title = "Zero-shot segmentation with DINO and Dash Labs" |
| 84 | +app = dash.Dash(__name__, title=title, plugins=[dl.plugins.FlexibleCallbacks()]) |
| 85 | +server = app.server |
| 86 | +tpl = dl.templates.DbcSidebar(title=title, theme=dbc.themes.DARKLY) |
| 87 | +cache = Cache( |
| 88 | + app.server, config={"CACHE_TYPE": "filesystem", "CACHE_DIR": "flask_cache"}, |
| 89 | +) |
| 90 | + |
| 91 | +# memoize functions |
| 92 | +predict = cache.memoize(timeout=300)(compute_attentions(model)) |
| 93 | +download_img = cache.memoize(timeout=300)(download_img) |
| 94 | + |
| 95 | +# Define callback function |
| 96 | +@app.callback( |
| 97 | + args=dict( |
| 98 | + url=tpl.textbox_input(default_url, label="Image URL", kind=dl.State), |
| 99 | + run=tpl.button_input("Run", label=""), |
| 100 | + head=tpl.dropdown_input(list(range(6)), value="0", label="Attention Head"), |
| 101 | + options=tpl.checklist_input(["use threshold", "overlay"], []), |
| 102 | + threshold=tpl.slider_input(0, 1, 0.6, 0.01), |
| 103 | + ), |
| 104 | + output=tpl.graph_output(), |
| 105 | + template=tpl, |
| 106 | +) |
| 107 | +def callback(url, run, threshold, head, options): |
| 108 | + try: |
| 109 | + im = download_img(url) |
| 110 | + except: |
| 111 | + return go.Figure().update_layout(title="Incorrect URL") |
| 112 | + |
| 113 | + ix = int(head) |
| 114 | + # Run model |
| 115 | + img = transform(im).to(device) |
| 116 | + attentions, w_featmap, h_featmap = predict(img) |
| 117 | + th_attn, scalar_attn = apply_threshold(attentions, w_featmap, h_featmap, threshold) |
| 118 | + |
| 119 | + attns = th_attn if "use threshold" in options else scalar_attn |
| 120 | + |
| 121 | + if "overlay" in options: |
| 122 | + fig = px.imshow(im) |
| 123 | + fig.add_trace(go.Heatmap(z=attns[ix], opacity=0.55)) |
| 124 | + else: |
| 125 | + fig = make_subplots(1, 2) |
| 126 | + fig.add_trace(go.Image(z=im), 1, 1) |
| 127 | + fig.add_trace(go.Heatmap(z=attns[ix]), 1, 2) |
| 128 | + fig.update_xaxes(matches="x") |
| 129 | + fig.update_yaxes(matches="y") |
| 130 | + |
| 131 | + return fig |
| 132 | + |
| 133 | + |
| 134 | +app.layout = tpl.layout(app) |
| 135 | + |
| 136 | + |
| 137 | +if __name__ == "__main__": |
| 138 | + app.run_server(debug=True) |
0 commit comments