Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support vector mode AD #519

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions src/Interpreter.jl
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,11 @@ function push_acts!(ad_inputs, x::BatchDuplicated, path, reverse)
predims = size(x.val)
cval = MLIR.IR.result(
MLIR.Dialects.stablehlo.concatenate(
[Ops.reshape(v, Int64[1, predims...]) for v in x.dval]; dimension=Int64(0)
[
TracedUtils.get_mlir_data(Ops.reshape(v, Int64[1, predims...])) for
v in x.dval
];
dimension=Int64(0),
),
)
tval = TracedRArray{ET,length(predims) + 1}((), cval, (length(x.dval), predims...))
Expand Down Expand Up @@ -244,12 +248,6 @@ function overload_autodiff(
width = Enzyme.same_or_one(1, args...)
if width == 0
throw(ErrorException("Cannot differentiate with a batch size of 0"))
elseif width != 1
throw(
ErrorException(
"EnzymeMLIR does not presently support width=$width, please rewrite your code to not use BatchDuplicated and/or call gradient(; chunk=1)",
),
)
end

primf = f.val
Expand Down Expand Up @@ -381,6 +379,7 @@ function overload_autodiff(
[TracedUtils.transpose_val(v) for v in ad_inputs];
outputs=outtys,
fn=fname,
width,
activity=MLIR.IR.Attribute([act_attr(a) for a in activity]),
ret_activity=MLIR.IR.Attribute([act_attr(a) for a in ret_activity]),
)
Expand Down Expand Up @@ -423,8 +422,10 @@ function overload_autodiff(
push!(starts, 0)
push!(limits, v)
end
sval = Ops.slice(sval, starts, limits)
TracedUtils.set!(dresult[i], path[2:end], sval)
sval = Ops.slice(TracedRArray(tval), starts, limits)
TracedUtils.set!(
dresult[i], path[2:end], TracedUtils.get_mlir_data(sval)
)
end
end
residx += 1
Expand Down
14 changes: 14 additions & 0 deletions test/autodiff.jl
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,20 @@ end
@test res2 ≈ 4 * 3 * 3.1^2
end

fn(x) = sum(abs2, x)

function vector_forward_ad(x, dx1, dx2)
return Enzyme.autodiff(Forward, fn, BatchDuplicated(x, (dx1, dx2)))
end

@testset "Vector Mode AD" begin
x = Reactant.to_rarray([1.0, 3.0])
dx1 = Reactant.to_rarray([1.0, 0.0])
dx2 = Reactant.to_rarray([0.0, 1.0])

res = @jit vector_forward_ad(x, dx1, dx2)
end

@testset "Seed initialization of Complex arrays on matmul: Issue #593" begin
a = ones(ComplexF64, 2, 2)
b = 2.0 * ones(ComplexF64, 2, 2)
Expand Down
Loading