-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathEnzyme.jl
More file actions
571 lines (502 loc) · 17.1 KB
/
Enzyme.jl
File metadata and controls
571 lines (502 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
const enzyme_out = 0
const enzyme_dup = 1
const enzyme_const = 2
const enzyme_dupnoneed = 3
const enzyme_outnoneed = 4
const enzyme_constnoneed = 5
struct StackedBatchDuplicated{T,N,M,V<:AbstractArray{T,N},W<:AbstractArray{T,M}} <:
Annotation{V}
val::V
dval::W
function StackedBatchDuplicated(
val::V, dval::W
) where {T,N,M,V<:AbstractArray{T,N},W<:AbstractArray{T,M}}
@assert N == M - 1
@assert size(val) == size(dval)[1:(end - 1)]
return new{T,N,M,V,W}(val, dval)
end
end
@inline function Enzyme.same_or_one_rec(current, arg::StackedBatchDuplicated, args...)
return Enzyme.same_or_one_rec(
Enzyme.same_or_one_helper(current, size(arg.dval, ndims(arg.dval))), args...
)
end
@inline function Enzyme.same_or_one_rec(current, ::Type{<:StackedBatchDuplicated}, args...)
throw(AssertionError("BatchDuplicatedNoNeed not yet supported"))
end
struct StackedBatchDuplicatedNoNeed{T,N,M,V<:AbstractArray{T,N},W<:AbstractArray{T,M}} <:
Annotation{V}
val::V
dval::W
function StackedBatchDuplicatedNoNeed(
val::V, dval::W
) where {T,N,M,V<:AbstractArray{T,N},W<:AbstractArray{T,M}}
@assert N == M - 1
@assert size(val) == size(dval)[1:(end - 1)]
return new{T,N,M,V,W}(val, dval)
end
end
@inline function Enzyme.same_or_one_rec(current, arg::StackedBatchDuplicatedNoNeed, args...)
return Enzyme.same_or_one_rec(
Enzyme.same_or_one_helper(current, size(arg.dval, ndims(arg.dval))), args...
)
end
@inline function Enzyme.same_or_one_rec(
current, ::Type{<:StackedBatchDuplicatedNoNeed}, args...
)
throw(AssertionError("BatchDuplicatedNoNeed not yet supported"))
end
@inline function Enzyme.make_zero(x::RNumber)
return zero(Core.Typeof(x))
end
@inline function Enzyme.make_zero(x::RArray{FT,N})::RArray{FT,N} where {FT<:AbstractFloat,N}
return Base.zero(x)
end
@inline function Enzyme.make_zero(
x::RArray{Complex{FT},N}
)::RArray{Complex{FT},N} where {FT<:AbstractFloat,N}
return Base.zero(x)
end
macro register_make_zero_inplace(sym)
quote
@inline function $sym(prev::RArray{T,N})::Nothing where {T<:AbstractFloat,N}
$sym(prev, nothing)
return nothing
end
@inline function $sym(prev::RArray{T,N}, seen::ST)::Nothing where {T,N,ST}
if Enzyme.Compiler.guaranteed_const(T)
return nothing
end
if !isnothing(seen)
if prev in seen
return nothing
end
push!(seen, prev)
end
fill!(prev, zero(T))
return nothing
end
end
end
@register_make_zero_inplace(Enzyme.make_zero!)
@register_make_zero_inplace(Enzyme.remake_zero!)
function Enzyme.make_zero(
::Type{RT}, seen::IdDict, prev::RT, ::Val{copy_if_inactive}=Val(false)
)::RT where {copy_if_inactive,RT<:Union{RArray,RNumber}}
if haskey(seen, prev)
return seen[prev]
end
if Enzyme.Compiler.guaranteed_const(eltype(RT))
return copy_if_inactive ? Base.deepcopy_internal(prev, seen) : prev
end
res = zero(prev)
seen[prev] = res
return res
end
function Enzyme.onehot(x::TracedRArray{T,N}) where {T,N}
onehot_matrix = promote_to(TracedRArray{T,2}, LinearAlgebra.I(length(x)))
return Tuple(
materialize_traced_array(reshape(y, size(x))) for y in eachcol(onehot_matrix)
)
end
function EnzymeRules.inactive_noinl(::typeof(XLA.buffer_on_cpu), args...)
return nothing
end
function EnzymeRules.inactive_noinl(::typeof(XLA.addressable_devices), args...)
return nothing
end
function EnzymeRules.noalias(::typeof(Base.similar), a::ConcretePJRTArray, ::Type, args...)
return nothing
end
function EnzymeRules.noalias(::typeof(Base.similar), a::ConcreteIFRTArray, ::Type, args...)
return nothing
end
function EnzymeRules.augmented_primal(
config,
ofn::Const{typeof(Base.similar)},
::Type{RT},
uval::Annotation{<:ConcretePJRTArray},
T::Const{<:Type},
args...,
) where {RT}
primargs = ntuple(Val(length(args))) do i
Base.@_inline_meta
args[i].val
end
primal = if EnzymeCore.needs_primal(config)
ofn.val(uval.val, T.val, primargs...)
else
nothing
end
shadow = if EnzymeRules.needs_shadow(config)
if EnzymeRules.width(config) == 1
ConcretePJRTArray(
zeros(T.val, primargs...);
client=XLA.client(uval.val),
device=XLA.device(uval.val),
uval.val.sharding,
)
else
ntuple(Val(EnzymeRules.width(config))) do i
Base.@_inline_meta
ConcretePJRTArray(
zeros(T.val, primargs...);
client=XLA.client(uval.val),
device=XLA.device(uval.val),
uval.val.sharding,
)
end
end
else
nothing
end
return EnzymeRules.AugmentedReturn{
EnzymeRules.primal_type(config, RT),EnzymeRules.shadow_type(config, RT),Nothing
}(
primal, shadow, nothing
)
end
function EnzymeRules.reverse(
config,
ofn::Const{typeof(Base.similar)},
::Type{RT},
tape,
uval::Annotation{<:ConcretePJRTArray},
T::Const{<:Type},
args::Vararg{Annotation,N},
) where {RT,N}
ntuple(Val(N + 2)) do i
Base.@_inline_meta
nothing
end
end
@inline function act_from_type(::A, reverse, needs_primal=true) where {A<:Annotation}
return act_from_type(A, reverse, needs_primal)
end
@inline function act_from_type(::Type{<:Active}, reverse, needs_primal)
return needs_primal ? enzyme_out : enzyme_outnoneed
end
@inline function act_from_type(::Type{<:Const}, reverse, needs_primal)
return needs_primal ? enzyme_const : enzyme_constnoneed
end
@inline function act_from_type(::Type{<:Duplicated}, reverse, needs_primal)
if reverse
return needs_primal ? enzyme_out : enzyme_outnoneed
else
return needs_primal ? enzyme_dup : enzyme_dupnoneed
end
end
@inline function act_from_type(
::Type{<:Union{BatchDuplicated,StackedBatchDuplicated}}, reverse, needs_primal
)
return act_from_type(Duplicated, reverse, needs_primal)
end
@inline function act_from_type(::Type{<:DuplicatedNoNeed}, reverse, needs_primal)
return reverse ? enzyme_out : enzyme_dupnoneed
end
@inline function act_from_type(
::Type{<:Union{BatchDuplicatedNoNeed,StackedBatchDuplicatedNoNeed}},
reverse,
needs_primal,
)
return act_from_type(DuplicatedNoNeed, reverse, needs_primal)
end
function push_acts!(ad_inputs, x::Union{Const,Active}, path, reverse)
TracedUtils.push_val!(ad_inputs, x.val, path)
return nothing
end
function push_acts!(ad_inputs, x::Union{Duplicated,DuplicatedNoNeed}, path, reverse)
TracedUtils.push_val!(ad_inputs, x.val, path)
if !reverse
TracedUtils.push_val!(ad_inputs, x.dval, path)
end
end
function push_acts!(
ad_inputs, x::Union{BatchDuplicated,BatchDuplicatedNoNeed}, path, reverse
)
TracedUtils.push_val!(ad_inputs, x.val, path)
if !reverse
TracedUtils.push_val!(ad_inputs, call_with_reactant(stack, x.dval), path)
end
end
function push_acts!(
ad_inputs, x::Union{StackedBatchDuplicated,StackedBatchDuplicatedNoNeed}, path, reverse
)
TracedUtils.push_val!(ad_inputs, x.val, path)
if !reverse
TracedUtils.push_val!(ad_inputs, x.dval, path)
end
end
function set_act!(inp, path, reverse, tostore; emptypath=false, width=1)
x = if inp isa Active
inp.val
else
inp.dval
end
for p in path
x = traced_getfield(x, p)
end
if width == 1
TracedUtils.set_mlir_data!(x, tostore)
elseif x isa AbstractArray
TracedUtils.set_mlir_data!(x, tostore)
else
tostore_traced = TracedRArray(tostore)
@assert length(x) == size(tostore_traced, ndims(tostore_traced))
for (i, sl) in enumerate(eachslice(tostore_traced; dims=ndims(tostore_traced)))
TracedUtils.set_mlir_data!(x[i], TracedUtils.get_mlir_data(sl))
end
end
emptypath && TracedUtils.set_paths!(x, ())
return nothing
end
function act_attr(val)
return MLIR.IR.Attribute(MLIR.API.enzymeActivityAttrGet(MLIR.IR.current_context(), val))
end
function infer_activity(
mode::CMode, ::FA, args::Vararg{Annotation,Nargs}
) where {CMode<:Mode,FA<:Annotation,Nargs}
return Enzyme.guess_activity(
call_with_native(
primal_return_type,
mode isa ForwardMode ? Enzyme.Forward : Enzyme.Reverse,
eltype(FA),
Enzyme.vaEltypeof(args...),
),
mode,
)
end
function overload_autodiff(
mode::CMode, f::FA, args::Vararg{Annotation,Nargs}
) where {CMode<:Mode,FA<:Annotation,Nargs}
return overload_autodiff(mode, f, infer_activity(mode, f, args...), args...)
end
function overload_autodiff(
::CMode, f::FA, ::Type{A}, args::Vararg{Annotation,Nargs}
) where {CMode<:Mode,FA<:Annotation,A<:Annotation,Nargs}
reverse = CMode <: ReverseMode
width = Enzyme.same_or_one(1, args...)
if width == 0
throw(ErrorException("Cannot differentiate with a batch size of 0"))
end
primf = f.val
primargs = ((v.val for v in args)...,)
argprefix::Symbol = gensym("autodiffarg")
resprefix::Symbol = gensym("autodiffresult")
resargprefix::Symbol = gensym("autodiffresarg")
mlir_fn_res = TracedUtils.make_mlir_fn(
primf,
primargs,
(),
string(f) * "_autodiff",
false;
argprefix,
resprefix,
resargprefix,
)
(; result, linear_args, in_tys, linear_results) = mlir_fn_res
fnwrap = mlir_fn_res.fnwrapped
activity = Int32[]
ad_inputs = MLIR.IR.Value[]
reverse_seeds = Dict{Tuple,MLIR.IR.Value}()
for a in linear_args
idx, path = TracedUtils.get_argidx(a, argprefix)
arg = idx == 1 && fnwrap ? f : args[idx - fnwrap]
push!(activity, act_from_type(arg, reverse))
push_acts!(ad_inputs, arg, path[3:end], reverse)
if CMode <: ReverseMode && act_from_type(arg, false) == enzyme_dup
x = if width == 1
arg.dval
elseif arg.dval isa AbstractArray
arg.dval
else
call_with_reactant(stack, arg.dval)
end
for p in path[3:end]
x = Compiler.traced_getfield(x, p)
end
x = TracedUtils.get_mlir_data(x)
reverse_seeds[path] = x
end
end
outtys = MLIR.IR.Type[]
ret_activity = Int32[]
for a in linear_results
if TracedUtils.has_idx(a, resprefix)
if EnzymeCore.needs_primal(CMode)
push!(
outtys,
TracedUtils.transpose_ty(MLIR.IR.type(TracedUtils.get_mlir_data(a))),
)
end
if CMode <: ForwardMode && !(A <: Const)
push!(
outtys,
TracedUtils.batch_ty(
width,
TracedUtils.transpose_ty(
MLIR.IR.type(TracedUtils.get_mlir_data(a))
),
),
)
end
act = act_from_type(A, reverse, EnzymeCore.needs_primal(CMode))
cst = nothing
if act == enzyme_out || act == enzyme_outnoneed
if width == 1
cst = @opcall fill(one(unwrapped_eltype(a)), size(a))
else
cst = @opcall fill(one(unwrapped_eltype(a)), (size(a)..., width))
end
cst = cst.mlir_data
end
if CMode <: ReverseMode && TracedUtils.has_idx(a, argprefix)
idx, path = TracedUtils.get_argidx(a, argprefix)
arg = idx == 1 && fnwrap ? f : args[idx - fnwrap]
if act_from_type(arg, false) == enzyme_dup
seed = reverse_seeds[path]
if cst == nothing
if act == enzyme_const
act = enzyme_out
elseif act == enzyme_constnoneed
act = enzyme_outnoneed
else
@assert false
end
cst = seed
else
@assert act == enzyme_out || act == enzyme_outnoneed
cst = MLIR.IR.result(MLIR.Dialects.stablehlo.add(cst, seed), 1)
end
end
end
push!(ret_activity, act)
if cst != nothing
push!(ad_inputs, cst)
end
else
if TracedUtils.has_idx(a, argprefix)
idx, path = TracedUtils.get_argidx(a, argprefix)
arg = idx == 1 && fnwrap ? f : args[idx - fnwrap]
act = act_from_type(arg, reverse, true)
push!(ret_activity, act)
if act == enzyme_out || act == enzyme_outnoneed
seed = reverse_seeds[path]
push!(ad_inputs, seed)
end
else
act = act_from_type(Const, reverse, true)
push!(ret_activity, act)
end
push!(
outtys, TracedUtils.transpose_ty(MLIR.IR.type(TracedUtils.get_mlir_data(a)))
)
end
end
for (i, act) in enumerate(activity)
if act == enzyme_out || act == enzyme_dup || act == enzyme_dupnoneed
push!(outtys, TracedUtils.batch_ty(width, in_tys[i]))
end
end
fname = TracedUtils.get_attribute_by_name(mlir_fn_res.f, "sym_name")
fname = MLIR.IR.FlatSymbolRefAttribute(Base.String(fname))
res = (reverse ? MLIR.Dialects.enzyme.autodiff : MLIR.Dialects.enzyme.fwddiff)(
[TracedUtils.transpose_val(v) for v in ad_inputs];
outputs=outtys,
fn=fname,
width,
strong_zero=EnzymeCore.strong_zero(CMode),
activity=MLIR.IR.Attribute([act_attr(a) for a in activity]),
ret_activity=MLIR.IR.Attribute([act_attr(a) for a in ret_activity]),
)
residx = 1
dresult = if CMode <: ForwardMode && !(A <: Const)
if width == 1
deepcopy(result)
else
ntuple(Val(width)) do i
Base.@_inline_meta
deepcopy(result)
end
end
else
nothing
end
for a in linear_results
if TracedUtils.has_idx(a, resprefix)
if EnzymeCore.needs_primal(CMode)
path = TracedUtils.get_idx(a, resprefix)
tval = TracedUtils.transpose_val(MLIR.IR.result(res, residx))
TracedUtils.set!(result, path[2:end], tval)
residx += 1
end
if CMode <: ForwardMode && !(A <: Const)
path = TracedUtils.get_idx(a, resprefix)
tval = TracedUtils.transpose_val(MLIR.IR.result(res, residx))
if width == 1
TracedUtils.set!(dresult, path[2:end], tval)
else
ttval = TracedRArray(tval)
for (i, sl) in enumerate(eachslice(ttval; dims=ndims(ttval)))
TracedUtils.set!(
dresult[i],
path[2:end],
@allowscalar(TracedUtils.get_mlir_data(sl))
)
end
end
residx += 1
end
elseif TracedUtils.has_idx(a, argprefix)
idx, path = TracedUtils.get_argidx(a, argprefix)
arg = idx == 1 && fnwrap ? f : args[idx - fnwrap]
TracedUtils.set!(
arg.val, path[3:end], TracedUtils.transpose_val(MLIR.IR.result(res, residx))
)
residx += 1
else
TracedUtils.set!(a, (), TracedUtils.transpose_val(MLIR.IR.result(res, residx)))
residx += 1
end
end
restup = Any[(a isa Active) ? copy(a) : nothing for a in args]
for a in linear_args
idx, path = TracedUtils.get_argidx(a, argprefix)
arg = idx == 1 && fnwrap ? f : args[idx - fnwrap]
act_from_type(arg, reverse) != enzyme_out && continue
if idx == 1 && fnwrap && arg isa Active
@assert false
end
set_act!(
arg,
path[3:end],
reverse,
TracedUtils.transpose_val(MLIR.IR.result(res, residx));
width,
emptypath=arg isa Active,
)
residx += 1
end
if reverse
if EnzymeCore.needs_primal(CMode)
return ((restup...,), result)
else
return ((restup...,),)
end
else
if EnzymeCore.needs_primal(CMode)
if CMode <: ForwardMode && !(A <: Const)
return (dresult, result)
else
return (result,)
end
else
if CMode <: ForwardMode && !(A <: Const)
return (dresult,)
else
return ()
end
end
end
end
const ignore_derivatives = EnzymeCore.ignore_derivatives