Toy Leksut commited on
Commit
1ed7d4b
·
1 Parent(s): c5c2555

remove unnecessary gradient tracking

Browse files
Files changed (1) hide show
  1. app.py +9 -5
app.py CHANGED
@@ -26,12 +26,14 @@ preprocess = transforms.Compose([
26
  transforms.Normalize(mean=pretrained_mean, std=pretrained_std),
27
  ])
28
 
 
29
  def undo_preprocess(processed_img):
30
  img = processed_img.mul(pretrained_std.view(-1,1,1)).add(pretrained_mean.view(-1,1,1))
31
  img = torch.clamp(img, 0, 1).squeeze()
32
- img = img.detach().numpy().transpose(1,2,0)
33
  return img
34
 
 
35
  def set_example_image(img):
36
  return gr.Image.update(value=img[0])
37
 
@@ -46,7 +48,8 @@ def generate_adversial_image(img, epsilon):
46
  output = model(processed_img)
47
 
48
  # get predictions
49
- probs = torch.nn.functional.softmax(output[0], dim=0)
 
50
  top5_prob, top5_idx = torch.topk(probs, 5)
51
  preds = {categories[idx]: prob.item() for idx, prob in zip(top5_idx, top5_prob)}
52
 
@@ -57,13 +60,14 @@ def generate_adversial_image(img, epsilon):
57
  loss.backward()
58
 
59
  # generate adversarial image
60
- adv_img = processed_img + epsilon*processed_img.grad.data.sign()
61
- adv_output = model(adv_img)
 
62
  adv_probs = torch.nn.functional.softmax(adv_output[0], dim=0)
63
  adv_top5_prob, adv_top5_idx = torch.topk(adv_probs, 5)
64
  adv_preds = {categories[idx]: prob.item() for idx, prob in zip(adv_top5_idx, adv_top5_prob)}
65
 
66
- return undo_preprocess(processed_img), undo_preprocess(adv_img), preds, adv_preds
67
 
68
 
69
  def main():
 
26
  transforms.Normalize(mean=pretrained_mean, std=pretrained_std),
27
  ])
28
 
29
+
30
  def undo_preprocess(processed_img):
31
  img = processed_img.mul(pretrained_std.view(-1,1,1)).add(pretrained_mean.view(-1,1,1))
32
  img = torch.clamp(img, 0, 1).squeeze()
33
+ img = img.numpy().transpose(1,2,0)
34
  return img
35
 
36
+
37
  def set_example_image(img):
38
  return gr.Image.update(value=img[0])
39
 
 
48
  output = model(processed_img)
49
 
50
  # get predictions
51
+ with torch.no_grad():
52
+ probs = torch.nn.functional.softmax(output[0], dim=0)
53
  top5_prob, top5_idx = torch.topk(probs, 5)
54
  preds = {categories[idx]: prob.item() for idx, prob in zip(top5_idx, top5_prob)}
55
 
 
60
  loss.backward()
61
 
62
  # generate adversarial image
63
+ with torch.no_grad():
64
+ adv_img = processed_img + epsilon*processed_img.grad.data.sign()
65
+ adv_output = model(adv_img)
66
  adv_probs = torch.nn.functional.softmax(adv_output[0], dim=0)
67
  adv_top5_prob, adv_top5_idx = torch.topk(adv_probs, 5)
68
  adv_preds = {categories[idx]: prob.item() for idx, prob in zip(adv_top5_idx, adv_top5_prob)}
69
 
70
+ return undo_preprocess(processed_img.detach()), undo_preprocess(adv_img), preds, adv_preds
71
 
72
 
73
  def main():