Fix: Correct YOLO loss gradient for x,y coordinates#3088
Conversation
The gradient calculation for bounding box x and y coordinates in the `loss_yolo_` helper `impl::yolo_helper_impl::tensor_to_loss` was missing a factor of 2.0. This factor arises from the chain rule due to the coordinate transformation `output_scaled = network_output * 2.0 - 0.5`, where the loss is calculated based on `output_scaled`, but the gradient needs to be with respect to `network_output`. This commit multiplies the affected gradient terms by 2.0f to correctly apply the chain rule.
|
I just asked Jules to review the YOLO loss for gradient errors or other kinds of mistakes, and it found this. So asked it to provide a more detailed explanation of why we need a second 2.0 factor:
Either way I've just launched a training to check everything works (it should, since this change is equivalent to setting This kind of AI is great for code review because, even if it gets it wrong, it makes you think more deeply about confusing parts of the code. |
|
Well, isn't it still wrong though? So from the code: But that's not right. Since the derivative of |
|
Right, I am hesitant to make the change, it's something that can be tuned with the lambdas. But yes, I should probably add the 0.5 there, since after this change the loss almost doubles, so it would appear "transparent to the user". What do you think?
|
Yeah IDK. Whatever you think is best. You happy with what you have in the PR now? :D |
|
The main issue I have is that the loss almost doubles, so, by introducing the 0.5 in the loss, we get similar values as before, maybe I will add that. It's just for display purposes, it doesn't change the current behavior. |
|
Sounds good. Thanks for another PR :) |
The gradient calculation for bounding box x and y coordinates in the
loss_yolo_helperimpl::yolo_helper_impl::tensor_to_losswas missing a factor of 2.0. This factor arises from the chain rule due to the coordinate transformationoutput_scaled = network_output * 2.0 - 0.5, where the loss is calculated based onoutput_scaled, but the gradient needs to be with respect tonetwork_output.This commit multiplies the affected gradient terms by 2.0f to correctly apply the chain rule.