opacus icon indicating copy to clipboard operation
opacus copied to clipboard

register_grad_sampler for nn.Parameter layer

Open anibadde opened this issue 5 years ago • 2 comments

I implemented a function to compute the per-sample gradient for the nn.Parameter layer and called opacus_utils.register_grad_sampler for this layer. However, when using a model with the privacy engine I get the following error:

'IncompatibleModuleException: Model contains incompatible modules. grad_sampler method is not yet supported for this module.: ['_module (ViT)']'

However, all the other layers used in the ViT module are supported by opacus, so with the nn.Parameter layer registered this should work as expected. What could be a possible issue for this error? I have attached a link to a colab notebook to reproduce the error as well:

https://colab.research.google.com/drive/1E-5PR-C5d_EkLGgO1ZbwC3L_7fZYPh6q#scrollTo=87ymx5RSJ9d8

image

Thank you!

anibadde avatar Oct 31 '21 17:10 anibadde

Thanks for raising this issue. I can confirm that I can duplicate this error message. We'll look further into this question.

gcormode avatar Nov 01 '21 08:11 gcormode

Hi @anibadde Thanks for trying out opacus and its extended features, such as custom per sample gradient methods.

Unfortunately, the way you've implemented custom grad sampler will not produce the expected results. We're working on a better documentation on how to write your own grad samplers, but here's the short version relevant to your issue:

  1. nn.Parameter is not a layer. It's a subclass of torch.Tensor, whereas register_grad_sampler should be called for nn.Module subclasses. In this particular case, as ViT module has trainable parameters (pos_embedding and cls_token), you'd need to write grad sampler for the entire ViT module. When a module has non-recursive trainable parameters, you always need to understand the behaviour of the entire module and provide the correct way to calculate per sample gradients for those parameters. Other nested layers (e.g. nn.Linear in your case) can affect the gradient computations of the top-level module's parameters, therefore you can't consider them in isolation. Alternatively, you can re-write the ViT module and it's forward method so that all trainable parameters are part of supported modules - in this case you won't need to write custom grad sampler
  2. If you do go ahead with a custom grad sampler, I highly recommend writing a unit test for it - writing unit test is very simple (look at opacus/tests/grad_samples/* for examples) and will ensure your per sample gradients are correct. Writing custom grad samplers can br tricky, so double checking the correctness is totally worth it.

If you have any further questions, feel free to ask them on PyTorch forums: https://discuss.pytorch.org/c/opacus/29

igorshh avatar Nov 02 '21 22:11 igorshh