register_grad_sampler for nn.Parameter layer
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

Thank you!
Thanks for raising this issue. I can confirm that I can duplicate this error message. We'll look further into this question.
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:
nn.Parameteris not a layer. It's a subclass oftorch.Tensor, whereasregister_grad_samplershould be called fornn.Modulesubclasses. In this particular case, asViTmodule has trainable parameters (pos_embeddingandcls_token), you'd need to write grad sampler for the entireViTmodule. 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 theViTmodule 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- 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