JuliaPhysics / JuliaPhysics/Unitful.jl
Need an adjoint for constructor for Zygote compatibility
- Dominant language
- Julia
- Stars
- 675
- Forks
- 124
- Avg merge
- 3h 38m
- Merged PRs (30d)
- 1
Description
I'm trying to use Zygote with Unitful. If I use standard units like m, s and m/s, everything works:
```julia
using Zygote
using Unitful
# Works:
struct Foo
x::Number
t::Number
c::Number
end
function bar(f::Foo)
return f.x - f.c*f.t
end
foo = Foo(2u"m", 3u"s", 3e8u"m/s")
g = Zygote.gradient(f -> bar(f), foo)
println(g)
```
However, if I use a custom unit (in this case Euros) I get an error about requiring an adjoint for the constructor:
```
ERROR: LoadError: Need an adjoint for constructor Quantity{Float64, 𝐓, Unitful.FreeUnits{(yr,), 𝐓, nothing}}. Gradient is of type Quantity{Float64, 𝐓⁻¹, Unitful.FreeUnits{(€, yr⁻¹), 𝐓⁻¹, nothing}}
```
Apologies if my google-fu has failed me, but I have searched the Unitful docs, but did not manage to find anything about defining an adjoint for a constructor. How can I define one?
Code to reproduce:
```julia
using Zygote
using Unitful
@unit € "€" Euro 1.0 false
struct Loan
loan_amount::Number
interest_rate::Number
loan_term::Number
end
function monthly_payment(l::Loan)
r = l.interest_rate*1.0u"yr"/12.0 # use monthly interest rate for monthly payment
# Number of payments:
n = l.loan_term*12.0/1.0u"yr"
return l.loan_amount*r*(1+r)^n/((1+r)^n - 1)
end
loan = Loan(500000.0*€, 0.025/1.0u"yr", 30.0u"yr")
g = Zygote.gradient(l -> monthly_payment(l), loan)
println(g)
```
Contributor guide
No contributing guide indexed for this repository
Research direction
Start by running the provided Loan and custom-€ reproduction with Julia, Unitful, and Zygote, then trace the constructor-related error reported during gradient computation. Done means the reproduction computes a gradient without requiring an adjoint for the Quantity constructor; no specific source file or test is named in the issue.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- julia
- Domain
- developer-experience
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100