Skip to content

Cannot specify type of list comprehension #1343

@LilithHafner

Description

@LilithHafner

Zygote can differentiate list comprehensions with automatically generated types ([i+1 for i in 1:10]), but not for explicitly specified types (Int[i+1 for i in 1:10] or Float64[i+1 for i in 1:10]).

MWE

julia> gradient(1.0) do x
           sum([x for _ in 1:10])
       end
(10.0,)

julia> gradient(1.0) do x
           sum(Float64[x for _ in 1:10])
       end
ERROR: Mutating arrays is not supported -- called setindex!(Vector{Float64}, ...)
This error occurs when you ask Zygote to differentiate operations that change
the elements of arrays in place (e.g. setting values with x .= ...)

Possible fixes:
- avoid mutating operations (preferred)
- or read the documentation and solutions for this error
  https://fluxml.ai/Zygote.jl/latest/limitations

Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:35
 [2] _throw_mutation_error(f::Function, args::Vector{Float64})
   @ Zygote ~/.julia/packages/Zygote/SmJK6/src/lib/array.jl:86
 [3] (::Zygote.var"#389#390"{Vector{Float64}})(#unused#::Nothing)
   @ Zygote ~/.julia/packages/Zygote/SmJK6/src/lib/array.jl:98
 [4] (::Zygote.var"#2509#back#391"{Zygote.var"#389#390"{Vector{Float64}}})(Δ::Nothing)
   @ Zygote ~/.julia/packages/ZygoteRules/AIbCs/src/adjoint.jl:67
 [5] Pullback
   @ ./REPL[49]:2 [inlined]
 [6] (::typeof((#47)))(Δ::Float64)
   @ Zygote ~/.julia/packages/Zygote/SmJK6/src/compiler/interface2.jl:0
 [7] (::Zygote.var"#60#61"{typeof((#47))})(Δ::Float64)
   @ Zygote ~/.julia/packages/Zygote/SmJK6/src/compiler/interface.jl:45
 [8] gradient(f::Function, args::Float64)
   @ Zygote ~/.julia/packages/Zygote/SmJK6/src/compiler/interface.jl:97
 [9] top-level scope
   @ REPL[49]:1

julia> VERSION
v"1.9.0-alpha1"

(jl_NHms0y) pkg> status
Status `/private/var/folders/hc/fn82kz1j5vl8w7lwd4l079y80000gn/T/jl_NHms0y/Project.toml`
  [e88e6eb3] Zygote v0.6.51

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions