fra31 / auto-attack

Code relative to "Reliable evaluation of adversarial robustness with an ensemble of diverse parameter-free attacks"
https://arxiv.org/abs/2003.01690
MIT License
639 stars 111 forks source link

replace '.view()' with '.reshape()' #66

Closed MariaMsu closed 3 years ago

MariaMsu commented 3 years ago

I had problems with my example:

image = tf.io.read_file('./cock.jpg')
image = tf.image.decode_image(image)
image = tf.image.convert_image_dtype(image, tf.float32)
image = tf.image.resize_with_pad(image, target_height=224, target_width=224)
images = tf.keras.applications.resnet50.preprocess_input( image[None,:] * 255)
labels = tf.constant([7])  # imagenet label  "cock"

model = tf.keras.applications.resnet50.ResNet50(include_top=True, weights="imagenet", input_tensor=None,
                                        input_shape=(224, 224, 3), pooling=None, classes=1000)
torch_images = torch.from_numpy( np.transpose(images_1.numpy(), (0, 3, 1, 2)) ).float().cuda()
torch_labels = torch.from_numpy( labels.numpy() ).float()

model_adapted = utils_tf2.ModelAdapter(model)

adversary = AutoAttack(model_adapted, norm='Linf', eps=(8. / 255.), version='standard', is_tf_model=True)
x_adv = adversary.run_standard_evaluation(torch_images, torch_labels, bs=1)

error:

RuntimeError                              Traceback (most recent call last)
<ipython-input-12-d3e8159c6748> in <module>
      2 
      3 adversary = AutoAttack(model_adapted, norm='Linf', eps=epsilon, version='standard', is_tf_model=True)
----> 4 x_adv = adversary.run_standard_evaluation(torch_images, torch_labels, bs=1)
      5 np_x_adv = np.moveaxis(x_adv.cpu().numpy(), 1, 3)
/dump/mcherepnina/auto-attack/autoattack/autoattack.py in run_standard_evaluation(self, x_orig, y_orig, bs)
--> 187                     res = (x_adv - x_orig).abs().view(x_orig.shape[0], -1).max(1)[0]
    188                 elif self.norm == 'L2':
    189                     res = ((x_adv - x_orig) ** 2).view(x_orig.shape[0], -1).sum(-1).sqrt()
RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.

I read about such problem here and replaced '.view()' with '.reshape()'. After that my example starts to work