Spaces:
Running
on
Zero
Running
on
Zero
File size: 1,632 Bytes
3c00c76 77269e5 3c00c76 bdc707c 69da633 b3c4783 69da633 0326791 3c00c76 69da633 ff98280 69da633 932b692 69da633 3c00c76 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import numpy as np
import PIL.Image as Image
import spaces
import torch
from app import (
build_demo,
compute_gmm_likelihood,
load_model_from_hub,
plot_against_reference,
plot_heatmap,
)
@spaces.GPU
@torch.no_grad
def run_inference(model, img):
img = img.float().to('cuda')
model = model.to('cuda')
print("model on cuda:", next(model.scorenet.net.parameters()).is_cuda)
print("img on cuda:", img.is_cuda)
with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=True):
img = torch.nn.functional.interpolate(img, size=64, mode="bilinear")
score_norms = model.scorenet(img)
score_norms = score_norms.square().sum(dim=(2, 3, 4)) ** 0.5
img_likelihood = model(img).cpu().numpy()
score_norms = score_norms.cpu().numpy()
return img_likelihood, score_norms
def localize_anomalies(input_img, preset="edm2-img64-s-fid", load_from_hub=False):
input_img = input_img.resize(size=(64, 64), resample=Image.Resampling.LANCZOS)
img = np.array(input_img)
img = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0)
model, modeldir = load_model_from_hub(preset=preset, device='cpu')
img_likelihood, score_norms = run_inference(model, img)
nll, pct, ref_nll = compute_gmm_likelihood(
score_norms, model_dir=modeldir
)
outstr = f"Anomaly score: {nll:.3f} / {pct:.2f} percentile"
histplot = plot_against_reference(nll, ref_nll)
heatmapplot = plot_heatmap(input_img, img_likelihood)
return outstr, heatmapplot, histplot
demo = build_demo(localize_anomalies)
if __name__ == "__main__":
demo.launch()
|