I am training a CNN in a custom training loop. I am updating the weights manually, and calculating the gradients with torch.autograd.grad and manually.
grads = torch.autograd.grad(outputs=model.fx, inputs=model.layers_weight, allow_unused=True, grad_outputs=[torch.ones_like(out) for out in model.fx])
model.fx are the outputs of all the linear functions except for the last element which is the loss. The inputs are the weights. Using these gradients I calculate back in the network dl/dw for each layer.
The resulting gradients are stored in a list for manual weight update in torch.no_grad later on. I use .sub_ for gradient descent.
The weights are then assigned as so:
model.conv1.weight.copy_(conv1_tmpw)
I dont think there is anything wrong with my calculations of gradients (dL/dw).
I am having trouble with exploding gradients. To solve this I have tried using pytorch built-in functions for gradient clipping. However I am ruing into issues using some proposed functions.
When using torch..utils.clip_grad_value_ with model.parameters() in the argument I get:
RuntimeError: errorclip_grad_value_ Expected !nested_tensorlist[0].empty() to be true, but got false.
For clip_grad_norm I set max_norm as 1 and norm_type 2. Works fine but then re-ruing it all the gradients are nan.
Does anyone know how I could clip gradients? I've searched online to no avail.
برچسب:
نویسنده: استخدام کار