You would somehow have to access each parameter, but a custom method and the usage of model.apply might be more convenient:
def add_noise_to_weights(m):
    with torch.no_grad():
        if hasattr(m, 'weight'):
            m.weight.add_(torch.randn(m.weight.size()) * 0.1)

model.apply(add_noise_to_weights)




 sirius:

Moreover, I am not quite sure how to use this piece of code. Adding these codes to the training loop?


It depends on your use case, so you could call this method after each iteration, in each epoch, etc.