Spaces:
Running
Running
+ grabbing gmm from hf hub
Browse files+ replacing inference with no_grad
app.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import json
|
|
|
|
| 2 |
from functools import cache
|
| 3 |
from pickle import load
|
| 4 |
|
|
@@ -17,7 +18,7 @@ from msma import ScoreFlow, build_model_from_pickle, config_presets
|
|
| 17 |
def load_model(modeldir, preset="edm2-img64-s-fid", device="cpu"):
|
| 18 |
scorenet = build_model_from_pickle(preset=preset)
|
| 19 |
model = ScoreFlow(scorenet, num_flows=8, device=device)
|
| 20 |
-
model.flow.load_state_dict(torch.load(f"{modeldir}/
|
| 21 |
return model
|
| 22 |
|
| 23 |
|
|
@@ -25,29 +26,27 @@ def load_model(modeldir, preset="edm2-img64-s-fid", device="cpu"):
|
|
| 25 |
def load_model_from_hub(preset, device):
|
| 26 |
scorenet = build_model_from_pickle(preset)
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
model_params = json.load(f)
|
| 36 |
print("Loaded:", model_params)
|
| 37 |
|
| 38 |
-
hf_checkpoint =
|
| 39 |
-
repo_id="ahsanMah/localizing-edm",
|
| 40 |
-
subfolder=preset,
|
| 41 |
-
filename="model.safetensors",
|
| 42 |
-
cache_dir="/tmp/",
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
print("HF SAVE DIR:", hf_checkpoint)
|
| 46 |
-
|
| 47 |
model = ScoreFlow(scorenet, device=device, **model_params["PatchFlow"])
|
| 48 |
model.load_state_dict(load_file(hf_checkpoint), strict=True)
|
| 49 |
model = model.eval().requires_grad_(False)
|
| 50 |
-
|
|
|
|
| 51 |
|
| 52 |
|
| 53 |
@cache
|
|
@@ -58,6 +57,8 @@ def load_reference_scores(model_dir):
|
|
| 58 |
|
| 59 |
|
| 60 |
def compute_gmm_likelihood(x_score, model_dir):
|
|
|
|
|
|
|
| 61 |
with open(f"{model_dir}/gmm.pkl", "rb") as f:
|
| 62 |
clf = load(f)
|
| 63 |
nll = -clf.score(x_score)
|
|
@@ -94,7 +95,7 @@ def plot_heatmap(img: Image, heatmap: np.array):
|
|
| 94 |
# fig.tight_layout()
|
| 95 |
return im
|
| 96 |
|
| 97 |
-
|
| 98 |
def run_inference(model, img):
|
| 99 |
img = torch.nn.functional.interpolate(img, size=64, mode="bilinear")
|
| 100 |
score_norms = model.scorenet(img)
|
|
@@ -114,13 +115,13 @@ def localize_anomalies(input_img, preset="edm2-img64-s-fid", load_from_hub=False
|
|
| 114 |
img = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0)
|
| 115 |
img = img.float().to(device)
|
| 116 |
if load_from_hub:
|
| 117 |
-
model = load_model_from_hub(preset=preset, device=device)
|
| 118 |
else:
|
|
|
|
| 119 |
model = load_model(modeldir="models", preset=preset, device=device)
|
| 120 |
-
|
| 121 |
img_likelihood, score_norms = run_inference(model, img)
|
| 122 |
nll, pct, ref_nll = compute_gmm_likelihood(
|
| 123 |
-
score_norms, model_dir=
|
| 124 |
)
|
| 125 |
|
| 126 |
outstr = f"Anomaly score: {nll:.3f} / {pct:.2f} percentile"
|
|
|
|
| 1 |
import json
|
| 2 |
+
import os
|
| 3 |
from functools import cache
|
| 4 |
from pickle import load
|
| 5 |
|
|
|
|
| 18 |
def load_model(modeldir, preset="edm2-img64-s-fid", device="cpu"):
|
| 19 |
scorenet = build_model_from_pickle(preset=preset)
|
| 20 |
model = ScoreFlow(scorenet, num_flows=8, device=device)
|
| 21 |
+
model.flow.load_state_dict(torch.load(f"{modeldir}/{preset}/flow.pt"))
|
| 22 |
return model
|
| 23 |
|
| 24 |
|
|
|
|
| 26 |
def load_model_from_hub(preset, device):
|
| 27 |
scorenet = build_model_from_pickle(preset)
|
| 28 |
|
| 29 |
+
for fname in ['config.json', 'gmm.pkl', 'refscores.npz', 'model.safetensors' ]:
|
| 30 |
+
cached_fname = hf_hub_download(
|
| 31 |
+
repo_id="ahsanMah/localizing-edm",
|
| 32 |
+
subfolder=preset,
|
| 33 |
+
filename=fname,
|
| 34 |
+
cache_dir="/tmp/",
|
| 35 |
+
)
|
| 36 |
+
modeldir = os.path.dirname(cached_fname)
|
| 37 |
+
print("HF Cache Dir:", modeldir)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
with open(f"{modeldir}/config.json", "rb") as f:
|
| 41 |
model_params = json.load(f)
|
| 42 |
print("Loaded:", model_params)
|
| 43 |
|
| 44 |
+
hf_checkpoint = f"{modeldir}/model.safetensors"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
model = ScoreFlow(scorenet, device=device, **model_params["PatchFlow"])
|
| 46 |
model.load_state_dict(load_file(hf_checkpoint), strict=True)
|
| 47 |
model = model.eval().requires_grad_(False)
|
| 48 |
+
|
| 49 |
+
return model, modeldir
|
| 50 |
|
| 51 |
|
| 52 |
@cache
|
|
|
|
| 57 |
|
| 58 |
|
| 59 |
def compute_gmm_likelihood(x_score, model_dir):
|
| 60 |
+
|
| 61 |
+
|
| 62 |
with open(f"{model_dir}/gmm.pkl", "rb") as f:
|
| 63 |
clf = load(f)
|
| 64 |
nll = -clf.score(x_score)
|
|
|
|
| 95 |
# fig.tight_layout()
|
| 96 |
return im
|
| 97 |
|
| 98 |
+
@torch.no_grad
|
| 99 |
def run_inference(model, img):
|
| 100 |
img = torch.nn.functional.interpolate(img, size=64, mode="bilinear")
|
| 101 |
score_norms = model.scorenet(img)
|
|
|
|
| 115 |
img = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0)
|
| 116 |
img = img.float().to(device)
|
| 117 |
if load_from_hub:
|
| 118 |
+
model, modeldir = load_model_from_hub(preset=preset, device=device)
|
| 119 |
else:
|
| 120 |
+
modeldir = f"models/{preset}"
|
| 121 |
model = load_model(modeldir="models", preset=preset, device=device)
|
|
|
|
| 122 |
img_likelihood, score_norms = run_inference(model, img)
|
| 123 |
nll, pct, ref_nll = compute_gmm_likelihood(
|
| 124 |
+
score_norms, model_dir=modeldir
|
| 125 |
)
|
| 126 |
|
| 127 |
outstr = f"Anomaly score: {nll:.3f} / {pct:.2f} percentile"
|
hfapp.py
CHANGED
|
@@ -13,6 +13,7 @@ from app import (
|
|
| 13 |
|
| 14 |
|
| 15 |
@spaces.GPU
|
|
|
|
| 16 |
def run_inference(model, img):
|
| 17 |
model = model.to('cuda')
|
| 18 |
img = img.to('cuda')
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
@spaces.GPU
|
| 16 |
+
@torch.no_grad
|
| 17 |
def run_inference(model, img):
|
| 18 |
model = model.to('cuda')
|
| 19 |
img = img.to('cuda')
|
msma.py
CHANGED
|
@@ -81,7 +81,7 @@ class EDMScorer(torch.nn.Module):
|
|
| 81 |
|
| 82 |
self.register_buffer("sigma_steps", t_steps.to(torch.float64))
|
| 83 |
|
| 84 |
-
|
| 85 |
def forward(
|
| 86 |
self,
|
| 87 |
x,
|
|
@@ -110,7 +110,7 @@ class ScoreFlow(torch.nn.Module):
|
|
| 110 |
self.flow = PatchFlow((num_sigmas, c, h, w), **flow_kwargs)
|
| 111 |
|
| 112 |
self.flow = self.flow.to(device)
|
| 113 |
-
self.scorenet = scorenet.to(device).requires_grad_(False)
|
| 114 |
self.flow.init_weights()
|
| 115 |
|
| 116 |
self.config = dict()
|
|
@@ -432,14 +432,15 @@ def train_flow(dataset_path, preset, outdir, epochs, **flow_kwargs):
|
|
| 432 |
# Squeeze the juice
|
| 433 |
best_ckpt = torch.load(f"{experiment_dir}/flow.pt")
|
| 434 |
model.flow.load_state_dict(best_ckpt)
|
| 435 |
-
pbar = tqdm(
|
| 436 |
-
for
|
| 437 |
-
x
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
|
|
|
| 443 |
|
| 444 |
# Save final model
|
| 445 |
torch.save(model.flow.state_dict(), f"{experiment_dir}/flow.pt")
|
|
|
|
| 81 |
|
| 82 |
self.register_buffer("sigma_steps", t_steps.to(torch.float64))
|
| 83 |
|
| 84 |
+
@torch.no_grad
|
| 85 |
def forward(
|
| 86 |
self,
|
| 87 |
x,
|
|
|
|
| 110 |
self.flow = PatchFlow((num_sigmas, c, h, w), **flow_kwargs)
|
| 111 |
|
| 112 |
self.flow = self.flow.to(device)
|
| 113 |
+
self.scorenet = scorenet.to(device).eval().requires_grad_(False)
|
| 114 |
self.flow.init_weights()
|
| 115 |
|
| 116 |
self.config = dict()
|
|
|
|
| 432 |
# Squeeze the juice
|
| 433 |
best_ckpt = torch.load(f"{experiment_dir}/flow.pt")
|
| 434 |
model.flow.load_state_dict(best_ckpt)
|
| 435 |
+
pbar = tqdm(range(10), desc="(Tuning) Step:? - Loss: ?")
|
| 436 |
+
for e in pbar:
|
| 437 |
+
for x, _ in testiter:
|
| 438 |
+
x = x.to(device)
|
| 439 |
+
scores = model.scorenet(x)
|
| 440 |
+
train_loss = train_step(scores, x)
|
| 441 |
+
writer.add_scalar("loss/train", train_loss, step)
|
| 442 |
+
pbar.set_description(f"(Tuning) Step: {step:d} - Loss: {train_loss:.3f}")
|
| 443 |
+
step += 1
|
| 444 |
|
| 445 |
# Save final model
|
| 446 |
torch.save(model.flow.state_dict(), f"{experiment_dir}/flow.pt")
|