Fixing the numerical instability when calculating the loss of the cri… #501
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
When training the step2 critic model, our current implementation has an issue where the loss calculation using -log(sigmoid(c_truncated_reward - r_truncated_reward)) could result in infinite loss when sigmoid returns 0. To fix this issue, I replaced it with -torch.nn.functional.logsigmoid(c_truncated_reward - r_truncated_reward), which is a numerically stable version of log(sigmoid(x)) implemented in PyTorch. I also tested other implementations, such as nn.functional.softplus( r_truncated_reward - c_truncated_reward), but so far logsigmoid provides the closest value to our current implementation while avoiding infinite loss.
Testing results:
i, -torch.log(torch.sigmoid(x)), torch.nn.functiona.softplus(-x), -torch.nn.functional.logsigmoid(x)
-100 , tensor(inf) tensor(100.) tensor(100.)
-90.0 , tensor(inf) tensor(90.) tensor(90.)
-80.0 , tensor(80.) tensor(80.) tensor(80.)
-70.0 , tensor(70.) tensor(70.) tensor(70.)
-60.0 , tensor(60.) tensor(60.) tensor(60.)
-50.0 , tensor(50.) tensor(50.) tensor(50.)
-40.0 , tensor(40.) tensor(40.) tensor(40.)
-30.0 , tensor(30.) tensor(30.) tensor(30.)
-20.0 , tensor(20.) tensor(20.) tensor(20.)
-10.0 , tensor(10.0000) tensor(10.0000) tensor(10.0000)
0.0 , tensor(0.6931) tensor(0.6931) tensor(0.6931)
10.0 , tensor(4.5420e-05) tensor(4.5399e-05) tensor(4.5418e-05)
20.0 , tensor(-0.) tensor(2.0612e-09) tensor(0.)
30.0 , tensor(-0.) tensor(9.3576e-14) tensor(0.)
40.0 , tensor(-0.) tensor(4.2484e-18) tensor(0.)
50.0 , tensor(-0.) tensor(1.9287e-22) tensor(0.)
60.0 , tensor(-0.) tensor(8.7565e-27) tensor(0.)
70.0 , tensor(-0.) tensor(3.9754e-31) tensor(0.)
80.0 , tensor(-0.) tensor(1.8049e-35) tensor(0.)
90.0 , tensor(-0.) tensor(8.1940e-40) tensor(0.)
100.0 , tensor(-0.) tensor(3.7835e-44) tensor(0.)