JuliaDiff / JuliaDiff/ForwardDiff.jl

Can't differentiatate through StepRangeLen due to TwicePrecision

Open
#380 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Julia
Stars
1k
Forks
160
PR merge metrics
No merged PRs in 30d

Description

There is one very common data type that we can't differentiate through - StepRangeLen, which is what we usually get back from range.

julia> using ForwardDiff

julia> f1v(x::Vector) = sum(range(0; step=0.1, stop=2)*x[1]);  # edited not to clash with definitions below

julia> g1v = x -> ForwardDiff.gradient(f1v, x);

julia> f1v([1.0])
31.5

julia>  g1v([1.0])
MethodError: no method matching twiceprecision(::Base.TwicePrecision{ForwardDiff.Dual{ForwardDiff.Tag{typeof(f1),Float64},Float64,1}}, ::Int64)
Closest candidates are:
  twiceprecision(!Matched::T<:Union{Float16, Float32, Float64}, ::Integer) where T<:Union{Float16, Float32, Float64} at twiceprecision.jl:220
  twiceprecision(!Matched::Base.TwicePrecision{T<:Union{Float16, Float32, Float64}}, ::Integer) where T<:Union{Float16, Float32, Float64} at twiceprecision.jl:225

This problem does not arise with numerically equivalent data types which do not use TwicePrecision, such as LinRange:

julia> using ForwardDiff

julia> f2(x::Vector) = sum(LinRange(0, 2, 21)*x[1]);

julia> g2 = x -> ForwardDiff.gradient(f2, x);

julia> f2([1.0]), g2([1.0])
(21.0, [21.0])

Related: https://github.com/JuliaMath/Interpolations.jl/issues/293

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the ForwardDiff.gradient example using range and compare it with the working LinRange case. Then inspect how StepRangeLen and Base.TwicePrecision are handled during differentiation, using the reported twiceprecision method error as the guide; done means the range example differentiates successfully like the LinRange example.

Written by the indexing model from the issue text.

Assessment

Tech stack
julia
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.