Repository navigation
fix: Promote mixed-dtype Jacobians before computing their Gramian - #847
Conversation
ValerianRey
left a comment
There was a problem hiding this comment.
Interesting edge case. I think we have two choices there:
- (what you did): compute jacobians in the parameter's dtype, and then, just before computing the gramian of this parameter, cast the jacobian to the promoted dtype. The gramian will thus be in the promoted dtype. Pros: A bit less precision lost during the higher precision matmul that computes the gramian. Cons: Larger memory cost (could be drastically larger if e.g. the parameter's dtype is fp16 and the gramian dtype is fp64, for a very large parameter).
- Compute jacobians in the parameter's dtype, then compute the related gramian in the parameter's dtype too, but cast it to the promoted dtype during gramian accumulation.
To implement 2, the changes to gramian_computer would have to be reverted, and gramian_accumulator would take a dtype at init, and accumulate the gramian always in the promoted dtype.
I'm not sure what's best between 1 and 2 honestly. Both seem quite easy to implement, and both have some pros and cons. What do you think @AryanRG ?
Also, this whole fix can be mirrored in jac_to_grad with optimize_gramian_computation=True, which currently suffers the same "bug", and for which we could also do either 1 or 2. I think to preserve uniformity between autojac and autogram it would be cool to make the same fix there too, in this PR or in another one (whatever you prefer).
|
I’d keep the cast before the Gram product. A finite FP16 derivative of I’ve made the same change in optimized |
ValerianRey
left a comment
There was a problem hiding this comment.
LGTM, thanks for the contribution!
A mixed-dtype
autogram.Enginecan return an infinite Gramian even when the explicit Jacobian product is finite. Each block is multiplied at its input dtype before accumulation.Promote each Jacobian block before multiplication and preserve the common dtype through accumulation. The regression compares both Engine paths against row-wise autograd.
CPU autogram and autojac passed 915 tests per dtype on float32 and float64. Ruff passed. CUDA remains unverified.