-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathTracedUtils.jl
More file actions
1374 lines (1232 loc) · 43.6 KB
/
TracedUtils.jl
File metadata and controls
1374 lines (1232 loc) · 43.6 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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Functions within this module and Ops do not get forcibly re-compiled to be within our interpreter.
# This means that replacements, for example, for autodiff/random/kernels/etc do not get applied here when
# within compilation. However, it means these functions are a _lot_ faster to compile.
module TracedUtils
using ..Reactant:
Reactant,
MLIR,
TracedRArray,
TracedRNumber,
AnyTracedRArray,
MissingTracedValue,
OrderedIdDict,
Ops,
promote_to, # keep this to avoid breaking external code
broadcast_to_size # keep this to avoid breaking external code
using ..Ops: @opcall
using GPUArraysCore: @allowscalar
using ReactantCore: ReactantCore
using ReactantCore: MissingTracedValue, is_traced, materialize_traced_array
ReactantCore.materialize_traced_array(x::AbstractArray) = x
ReactantCore.materialize_traced_array(x::TracedRArray) = x
function ReactantCore.materialize_traced_array(x::AbstractRange)
return Reactant.aos_to_soa(collect(x))
end
function ReactantCore.materialize_traced_array(r::LinRange)
T = Reactant.unwrapped_eltype(r)
idxs = @opcall iota(T, [length(r)]; iota_dimension=1)
t = idxs ./ r.lendiv
return T.((1 .- t) .* r.start .+ t .* r.stop)
end
function ReactantCore.materialize_traced_array(x::Base.OneTo)
return @opcall iota(Reactant.unwrapped_eltype(x), [length(x)]; iota_dimension=1)
end
function ReactantCore.materialize_traced_array(x::UnitRange)
return @opcall add(
@opcall(iota(Reactant.unwrapped_eltype(x), [length(x)]; iota_dimension=1)),
@opcall(fill(first(x), [length(x)])),
)
end
function ReactantCore.materialize_traced_array(x::SubArray)
return materialize_traced_array(parent(x))[Base.reindex(parentindices(x), axes(x))...]
end
function ReactantCore.materialize_traced_array(x::Base.ReshapedArray)
if Base.prod(size(parent(x))) != Base.prod(size(x))
throw(
AssertionError(
"Invalid reshape array, original size $(size(parent(x))) not compatible with new size $(size(x))",
),
)
end
return @opcall reshape(materialize_traced_array(parent(x)), size(x)...)
end
function ReactantCore.materialize_traced_array(
x::PermutedDimsArray{<:Any,<:Any,perm}
) where {perm}
return permutedims(materialize_traced_array(parent(x)), perm)
end
function ReactantCore.materialize_traced_array(x::AbstractArray{TracedRNumber{T}}) where {T}
as = Reactant.aos_to_soa(x)
if as === x
as = x[axes(x)...]
end
return ReactantCore.materialize_traced_array(as)
end
get_mlir_data(x::TracedRNumber) = x.mlir_data
set_mlir_data!(x::TracedRNumber, data) = (x.mlir_data = data; return x)
get_paths(x::TracedRNumber) = x.paths
set_paths!(x::TracedRNumber, paths) = (x.paths = paths; return x)
get_mlir_data(x::TracedRArray) = x.mlir_data
get_mlir_data(x::AnyTracedRArray) = get_mlir_data(materialize_traced_array(x))
get_paths(x::TracedRArray) = x.paths
set_paths!(x::TracedRArray, paths) = (x.paths = paths; return x)
get_paths(x::MissingTracedValue) = x.paths
set_paths!(x::MissingTracedValue, paths) = (x.paths = paths; return x)
function set_mlir_data!(x::TracedRArray, data)
x.mlir_data = data
return x
end
function set_mlir_data!(x::Base.ReshapedArray{TracedRNumber{T}}, data) where {T}
set_mlir_data!(
parent(x),
get_mlir_data(@opcall(reshape(TracedRArray{T}(data), size(parent(x))...))),
)
return x
end
function get_ancestor_and_indices(
x::Base.ReshapedArray{TracedRNumber{T},N}, indices::Vector{CartesianIndex{N}}
) where {T,N}
linear_indices = LinearIndices(size(x))[indices]
parent_linear_indices = LinearIndices(size(parent(x)))[linear_indices]
return (parent(x), (parent_linear_indices,))
end
function get_ancestor_and_indices(
x::Base.ReshapedArray{TracedRNumber{T},N}, indices...
) where {T,N}
@assert length(indices) == N "Expected $N indices, got $(length(indices))"
indices = Base.to_indices(x, indices)
if any(is_traced, indices)
indices, integer_indices, result_size, _, flattened_size = traced_indices(
indices...
)
linear_indices = mapreduce(+, enumerate(indices)) do (i, idx)
bcasted_idxs = @opcall broadcast_in_dim(
idx, ndims(idx) == 0 ? Int64[] : Int64[i], flattened_size
)
Base.stride(x, i) .* (bcasted_idxs .- 1)
end
linear_indices = linear_indices .+ 1
parent_linear_indices_all = collect(LinearIndices(size(parent(x))))
parent_linear_indices = promote_to(
TracedRArray{Int64,ndims(parent_linear_indices_all)}, parent_linear_indices_all
)[linear_indices]
isempty(integer_indices) || (
parent_linear_indices = materialize_traced_array(
dropdims(parent_linear_indices; dims=integer_indices)
)
)
parent_linear_indices = @opcall reshape(parent_linear_indices, result_size)
return (parent(x), (parent_linear_indices,))
else
# Have this as a separate code-path since we can generate non-dynamic indexing
cartesian_indices = CartesianIndex.(Iterators.product(indices...))
linear_indices = LinearIndices(size(x))[cartesian_indices]
parent_linear_indices = LinearIndices(size(parent(x)))[linear_indices]
return (parent(x), (parent_linear_indices,))
end
end
function set_mlir_data!(
x::PermutedDimsArray{TracedRNumber{T},N,perm,iperm}, data
) where {T,N,perm,iperm}
set_mlir_data!(parent(x), get_mlir_data(permutedims(TracedRArray{T}(data), iperm)))
return x
end
function set_mlir_data!(x::AnyTracedRArray{T}, data) where {T}
ancestor, ancestor_indices = get_ancestor_and_indices(x, axes(x)...)
setindex!(Reactant.ancestor(x), TracedRArray{T}(data), ancestor_indices...)
return x
end
get_ancestor_and_indices(a::TracedRArray, indices) = (a, indices)
get_ancestor_and_indices(a::TracedRArray, indices, args...) = (a, (indices, args...))
get_ancestor_and_indices(a::Array{<:TracedRNumber}, indices...) = (a, indices)
function get_ancestor_and_indices(a::Array{<:TracedRNumber}, indices, args...)
return (a, (indices, args...))
end
function get_ancestor_and_indices(x::AnyTracedRArray, indices...)
return get_ancestor_and_indices_inner(x, indices...) # redirect to avoid ambiguity
end
function get_ancestor_and_indices(x::AnyTracedRArray, indices, args...)
return get_ancestor_and_indices_inner(x, indices, args...) # redirect to avoid ambiguity
end
function get_ancestor_and_indices_inner(
x::AnyTracedRArray{T,N}, indices::Vararg{Any,N}
) where {T,N}
return get_ancestor_and_indices(parent(x), Base.reindex(parentindices(x), indices)...)
end
function get_ancestor_and_indices_inner(x::AnyTracedRArray{T,1}, indices) where {T}
return get_ancestor_and_indices(parent(x), Base.reindex(parentindices(x), indices))
end
function get_ancestor_and_indices_inner(
x::AnyTracedRArray{T,N}, linear_indices::AbstractArray
) where {T,N}
a, idxs = _get_ancestor_and_indices_linear(x, linear_indices)
return a, (idxs isa Tuple ? idxs : (idxs,))
end
function get_ancestor_and_indices_inner(
x::AnyTracedRArray{T,1}, linear_indices::AbstractArray
) where {T}
a, idxs = _get_ancestor_and_indices_linear(x, linear_indices)
return a, (idxs isa Tuple ? idxs : (idxs,))
end
function _get_ancestor_and_indices_linear(x::AnyTracedRArray, indices::AbstractArray)
indices = CartesianIndices(x)[indices]
pidxs = parentindices(x)
parent_indices = map(indices) do idx
CartesianIndex(Base.reindex(pidxs, (idx.I...,)))
end
return get_ancestor_and_indices(parent(x), parent_indices)
end
Base.@nospecializeinfer function batch_ty(
width::Int, @nospecialize(mlirty::MLIR.IR.Type)
)::MLIR.IR.Type
width == 1 && return mlirty
return MLIR.IR.TensorType(Int[width, size(mlirty)...], eltype(mlirty))
end
Base.@nospecializeinfer function transpose_ty(
@nospecialize(mlirty::MLIR.IR.Type)
)::MLIR.IR.Type
return MLIR.IR.TensorType(Int[reverse(size(mlirty))...], eltype(mlirty))
end
Base.@nospecializeinfer function transpose_val(
@nospecialize(val::MLIR.IR.Value)
)::MLIR.IR.Value
val_size = size(MLIR.IR.type(val))
val_size == () && return val
attr = MLIR.IR.DenseArrayAttribute(Int64[reverse(0:(length(val_size) - 1))...])
return MLIR.IR.result(MLIR.Dialects.stablehlo.transpose(val; permutation=attr), 1)
end
Base.@nospecializeinfer function unpad_val_op(
@nospecialize(val::MLIR.IR.Value), padding, sz
)::MLIR.IR.Operation
start_indices = zeros(Int64, length(padding))
limit_indices = collect(Int64, sz) .- padding
return MLIR.Dialects.stablehlo.slice(
val;
start_indices=MLIR.IR.DenseArrayAttribute(start_indices),
limit_indices=MLIR.IR.DenseArrayAttribute(limit_indices),
strides=MLIR.IR.DenseArrayAttribute(ones(Int64, length(padding))),
)
end
mutable struct CompiledMlirFnResult{F,TR,Re,Rt,LA,LR,PA,CR,M,MA,RS,GD,DA}
fnwrapped::Bool
f::F
traced_result::TR
result::Re
seen_args::OrderedIdDict
ret::Rt
linear_args::Vector{LA}
skipped_args::Vector{LA}
in_tys::Vector{MLIR.IR.Type}
linear_results::Vector{LR}
skipped_results::Vector{LR}
num_partitions::Int
num_replicas::Int
is_sharded::Bool
preserved_args::PA
concrete_result::CR
unique_meshes::M
mutated_args::MA
use_shardy_partitioner::Bool
result_shardings::RS
global_device_ids::GD # only populated if is_sharded
donated_args_mask::DA
is_pure::Bool
end
function is_pure(func)
attr = MLIR.IR.attr(func, "enzymexla.memory_effects")
# conservatively assume is not pure
if attr isa Nothing
return false
end
any(at -> String(at) == "write", attr) && return false
return true
end
function make_mlir_fn(
f,
args,
kwargs,
name="main",
concretein=true;
toscalar=false,
return_dialect=:func,
args_in_result::Symbol=:all,
construct_function_without_args::Bool=false,
do_transpose=true,
within_autodiff=false,
input_shardings=nothing, # This is not meant to be used by the user.
output_shardings=nothing, # This is not meant to be used by the user.
runtime=nothing,
verify_arg_names=nothing,
argprefix::Symbol=:args,
resprefix::Symbol=:result,
resargprefix::Symbol=:resargs,
num_replicas=1,
optimize_then_pad::Bool=true,
)
if sizeof(typeof(f)) != 0 || f isa Base.BroadcastFunction
mlir_fn_res = make_mlir_fn(
Reactant.apply,
(f, args...),
kwargs,
name,
concretein;
toscalar,
return_dialect,
args_in_result,
construct_function_without_args,
do_transpose,
input_shardings,
output_shardings,
runtime,
verify_arg_names,
argprefix,
resprefix,
resargprefix,
num_replicas,
)
mlir_fn_res.fnwrapped = true
return mlir_fn_res
end
(; N, traced_args, linear_args, inv_map, in_tys, sym_visibility, mod, traced_args_to_shardings, func, fnbody, seen_args, skipped_args) = prepare_mlir_fn_args(
args,
name,
concretein,
toscalar,
argprefix,
runtime,
optimize_then_pad,
do_transpose,
input_shardings,
verify_arg_names,
)
Ops.activate_constant_context!(fnbody)
@assert MLIR.IR._has_block()
# Explicitly don't use block! to avoid creating a closure, which creates
# both compile-time and relocatability issues
MLIR.IR.activate!(fnbody)
result = try
process_linear_args!(linear_args, fnbody, do_transpose, optimize_then_pad, inv_map)
if isempty(kwargs)
Reactant.call_with_reactant(f, traced_args...)
else
Reactant.call_with_reactant(Core.kwcall, kwargs, f, traced_args...)
end
finally
MLIR.IR.deactivate!(fnbody)
Ops.deactivate_constant_context!(fnbody)
end
# check which arguments have been mutated
mutated_args = Int[]
if !construct_function_without_args
for (i, arg) in enumerate(linear_args)
if get_mlir_data(arg) != MLIR.IR.argument(fnbody, i)
# mutation occured!
push!(mutated_args, i)
end
end
end
(func2, traced_result, ret, linear_args, in_tys, linear_results, skipped_results, num_partitions, is_sharded, unique_meshes, mutated_args, global_device_ids) = finalize_mlir_fn(
result,
traced_args,
linear_args,
skipped_args,
seen_args,
fnbody,
func,
mod,
name,
in_tys,
do_transpose,
optimize_then_pad,
inv_map,
args_in_result,
resprefix,
argprefix,
resargprefix,
verify_arg_names,
return_dialect,
traced_args_to_shardings,
output_shardings,
sym_visibility,
num_replicas,
runtime,
construct_function_without_args,
args,
N,
concretein,
toscalar,
)
return CompiledMlirFnResult(
false,
func2,
traced_result,
result,
seen_args,
ret,
linear_args,
skipped_args,
in_tys,
linear_results,
skipped_results,
num_partitions,
num_replicas,
is_sharded,
nothing,
nothing,
unique_meshes,
mutated_args,
true,
missing,
global_device_ids,
nothing, # populated later in `compile_mlir!`
is_pure(func2),
)
end
function prepare_mlir_fn_args(
args,
name,
concretein,
toscalar,
argprefix,
runtime,
optimize_then_pad,
do_transpose,
input_shardings,
verify_arg_names,
)
N = length(args)
traced_args = Vector{Any}(undef, N)
inmode = if concretein
@assert !toscalar
Reactant.ConcreteToTraced
else
Reactant.TracedSetPath
end
fnbody = MLIR.IR.Block(MLIR.IR.Type[], MLIR.IR.Location[])
MLIR.IR.activate!(fnbody)
Ops.activate_constant_context!(fnbody)
seen_args0 = OrderedIdDict()
try
for i in 1:N
@inbounds traced_args[i] = Reactant.make_tracer(
seen_args0, args[i], (argprefix, i), inmode; toscalar, runtime
)
end
finally
MLIR.IR.deactivate!(fnbody)
Ops.deactivate_constant_context!(fnbody)
end
seen_args = OrderedIdDict()
linear_args = Reactant.TracedType[]
skipped_args = Reactant.TracedType[]
inv_map = IdDict()
for (k, v) in seen_args0
v isa Reactant.TracedType || continue
arg = get_mlir_data(v)
if (arg isa MLIR.IR.Value) &&
MLIR.IR.is_op_res(arg) &&
MLIR.IR.block(MLIR.IR.op_owner(arg)) == fnbody
push!(skipped_args, v)
continue
end
seen_args[k] = v
push!(linear_args, v)
inv_map[v] = k
end
in_tys = Vector{MLIR.IR.Type}(undef, length(linear_args))
for (i, arg) in enumerate(linear_args)
elT = MLIR.IR.Type(Reactant.unwrapped_eltype(arg))
if toscalar
in_tys[i] = MLIR.IR.TensorType(Int[], elT)
else
sz = collect(Int, size(arg))
if !optimize_then_pad
carg = inv_map[arg]
Reactant.has_padding(carg) && (sz .+= Reactant.get_padding(carg))
end
typ = MLIR.IR.TensorType(sz, elT)
do_transpose && (typ = transpose_ty(typ))
in_tys[i] = typ
end
end
sym_visibility = nothing
if !concretein
sym_visibility = MLIR.IR.Attribute("private")
end
mod = MLIR.IR.mmodule()
# Insert meshes for the sharded arguments
traced_args_to_shardings = OrderedIdDict()
for (k, v) in seen_args
if k isa Reactant.AbstractConcreteNumber || k isa Reactant.AbstractConcreteArray
if Reactant.Sharding.is_sharded(k)
@opcall mesh(k.sharding.mesh)
traced_args_to_shardings[v] = k.sharding
elseif input_shardings !== nothing && haskey(input_shardings, k)
@opcall mesh(input_shardings[k].mesh)
traced_args_to_shardings[v] = input_shardings[k]
end
end
end
func = MLIR.IR.block!(MLIR.IR.body(mod)) do
return MLIR.Dialects.func.func_(;
sym_name=name * "_tmp",
function_type=MLIR.IR.FunctionType(in_tys, Vector{MLIR.IR.Type}(undef, 0)),
body=MLIR.IR.Region(),
)
end
for (i, arg) in enumerate(linear_args)
path = get_idx(arg, argprefix)
stridx = if verify_arg_names isa Nothing
"arg" * string(path[2])
else
string(verify_arg_names[path[2]])
end
aval = args[path[2]]
for idx in path[3:end]
if aval isa Array || aval isa Dict
aval = getindex(aval, idx)
stridx = stridx * "[" * string(idx) * "]"
else
fldname = if idx isa Integer
string(fieldname(Core.Typeof(aval), idx))
else
string(idx)
end
stridx *= "." * fldname
aval = Reactant.Compiler.traced_getfield(aval, idx)
end
end
MLIR.IR.push_argument!(
fnbody,
in_tys[i];
location=MLIR.IR.Location(stridx * " (path=$path)", MLIR.IR.Location()),
)
end
push!(MLIR.IR.region(func, 1), fnbody)
return (;
N,
traced_args,
linear_args,
inv_map,
in_tys,
sym_visibility,
mod,
traced_args_to_shardings,
func,
fnbody,
seen_args,
skipped_args,
)
end
function process_linear_args!(linear_args, fnbody, do_transpose, optimize_then_pad, inv_map)
for (i, arg) in enumerate(linear_args)
raw_arg = MLIR.IR.argument(fnbody, i)
row_maj_arg = do_transpose ? transpose_val(raw_arg) : raw_arg
if !optimize_then_pad
carg = inv_map[arg]
if Reactant.has_padding(carg)
padding = Reactant.get_padding(carg)
sz = size(carg) .+ padding
if !do_transpose
padding = reverse(padding)
sz = reverse(sz)
end
row_maj_arg = MLIR.IR.result(unpad_val_op(row_maj_arg, padding, sz), 1)
end
end
set_mlir_data!(arg, row_maj_arg)
end
end
function finalize_mlir_fn(
result,
traced_args,
linear_args,
skipped_args,
seen_args,
fnbody,
func,
mod,
name,
in_tys,
do_transpose,
optimize_then_pad,
inv_map,
args_in_result,
resprefix,
argprefix,
resargprefix,
verify_arg_names,
return_dialect,
traced_args_to_shardings,
output_shardings,
sym_visibility,
num_replicas,
runtime,
construct_function_without_args,
args,
N,
concretein,
toscalar,
)
# check which arguments have been mutated
mutated_args = Int[]
if !construct_function_without_args
for (i, arg) in enumerate(linear_args)
if get_mlir_data(arg) != MLIR.IR.argument(fnbody, i)
# mutation occured!
push!(mutated_args, i)
end
end
end
outmode = if concretein
@assert !toscalar
Reactant.NoStopTracedTrack
else
Reactant.TracedTrack
end
seen_results = OrderedIdDict()
MLIR.IR.activate!(fnbody)
traced_result = try
traced_result = Reactant.make_tracer(
seen_results, result, (resprefix,), outmode; runtime
)
# marks buffers to be donated
for i in 1:N
Reactant.make_tracer(
seen_results,
traced_args[i],
(resargprefix, i),
Reactant.NoStopTracedTrack;
runtime,
)
end
traced_result
finally
MLIR.IR.deactivate!(fnbody)
end
linear_results = Reactant.TracedType[]
skipped_results = Reactant.TracedType[]
for (k, v) in seen_results
v isa Reactant.TracedType || continue
if Reactant.looped_any(Base.Fix1(===, k), skipped_args)
push!(skipped_results, v)
_, argpath = get_argidx(v, argprefix)
@assert has_idx(v, argprefix)
newpaths = Tuple[]
for path in v.paths
if length(path) == 0
continue
end
if path[1] == argprefix
continue
end
if path[1] == resargprefix
original_arg = args[path[2]]
for p in path[3:end]
original_arg = Reactant.Compiler.traced_getfield(original_arg, p)
end
if !(
original_arg isa Union{
Reactant.ConcreteRNumber,
Reactant.ConcreteRArray,
Reactant.TracedType,
}
)
continue
end
push!(newpaths, path)
end
if path[1] == resprefix
push!(newpaths, path)
end
end
if length(newpaths) != 0
push!(linear_results, Reactant.repath(v, (newpaths...,)))
end
continue
end
if args_in_result != :all
if has_idx(v, argprefix)
if !(args_in_result == :result && has_idx(v, resprefix))
continue
end
end
end
push!(linear_results, v)
end
if args_in_result == :mutated
append!(linear_results, linear_args[mutated_args])
end
if !isnothing(verify_arg_names) && typeof.(linear_args) != typeof.(linear_results)
argis = []
for arg in linear_args
for path in arg.paths
if length(path) == 0
continue
end
if path[1] != argprefix
continue
end
push!(argis, path[2:end])
end
end
resis = []
for arg in linear_results
for path in arg.paths
if length(path) == 0
continue
end
if path[1] != resargprefix
continue
end
push!(resis, path[2:end])
end
end
# this can be more efficient
err1 = []
err2 = []
for (errs, prev, post) in ((err1, resis, argis), (err2, argis, resis))
conflicts = setdiff(prev, post)
for conflict in conflicts
stridx = string(verify_arg_names[conflict[1]])
aval = args[conflict[1]]
for (cidx, idx) in enumerate(Base.tail(conflict))
if aval isa Array || aval isa Dict
aval = Reactant.@allowscalar getindex(aval, idx)
stridx = stridx * "[" * string(idx) * "]"
else
fldname = if idx isa Integer
string(fieldname(Core.Typeof(aval), idx))
else
string(idx)
end
if cidx == 1
# Don't include the ref
if idx != 1
throw(
AssertionError(
"expected first path to be a ref lookup, found idx=$idx conflict=$conflict, cidx=$cidx",
),
)
end
else
stridx *= "." * fldname
end
aval = getfield(aval, idx)
end
end
push!(errs, stridx * " (path=$conflict, type=$(typeof(aval)))")
end
end
arg_info = sort([(Base.pointer_from_objref(arg), arg.paths) for arg in linear_args])
res_info = sort([
(Base.pointer_from_objref(arg), arg.paths) for arg in linear_results
])
arg_info_ni = [ai for ai in arg_info if !(ai in res_info)]
res_info_ni = [ai for ai in res_info if !(ai in arg_info)]
error("""Types do not match between function arguments and results.
The following arguments should be traced but were not: $(join(err1, ", "))
The following arguments should be returned but were not: $(join(err2, ", "))
argprefix = $argprefix
resprefix = $resprefix
verify_arg_names = $verify_arg_names
argtys = $(Core.Typeof.(args))
Traced Arg Paths: \n$(join(arg_info, "\n"))\n
Traced Res Paths: \n$(join(res_info, "\n"))\n
Traced Arg NI Paths: \n$(join(arg_info_ni, "\n"))\n
Traced Res NI Paths: \n$(join(res_info_ni, "\n"))\n
traced_result : $(Core.Typeof.(traced_result))
""")
end
out_tys = Vector{MLIR.IR.Type}(undef, length(linear_results))
MLIR.IR.activate!(fnbody)
ret = try
vals = Vector{MLIR.IR.Value}(undef, length(linear_results))
for (i, res) in enumerate(linear_results)
if !optimize_then_pad && haskey(inv_map, res) && Reactant.has_padding(inv_map[res])
carg = inv_map[res]
padding = Reactant.get_padding(carg)
sz = size(carg) .+ padding
if !do_transpose
padding = reverse(padding)
sz = reverse(sz)
end
res = @opcall pad(
res,
promote_to(TracedRNumber{Reactant.unwrapped_eltype(res)}, 0);
high=collect(Int, padding),
)
end
if res isa MissingTracedValue
col_maj = get_mlir_data(broadcast_to_size(false, ()))
out_ty = Ops.mlir_type(TracedRArray{Bool,0}, ())
else
col_maj = get_mlir_data(res)
out_ty = Ops.mlir_type(res)
if do_transpose
col_maj = transpose_val(col_maj)
out_ty = transpose_ty(out_ty)
end
end
vals[i] = col_maj
out_tys[i] = out_ty
end
args_in_result == :all && @assert length(vals) == length(linear_results)
dialect = getfield(MLIR.Dialects, return_dialect)
dialect.return_(vals)
finally
MLIR.IR.deactivate!(fnbody)
end
func2 = MLIR.IR.block!(MLIR.IR.body(mod)) do
return MLIR.Dialects.func.func_(;
sym_name=__lookup_unique_name_in_module(mod, name),
function_type=MLIR.IR.FunctionType(in_tys, out_tys),
body=MLIR.IR.Region(),
arg_attrs=MLIR.IR.attr(func, "arg_attrs"),
res_attrs=MLIR.IR.attr(func, "res_attrs"),
no_inline=MLIR.IR.attr(func, "no_inline"),
sym_visibility,
)
end
mem = MLIR.IR.attr(func, "enzymexla.memory_effects")
if !(mem isa Nothing)
MLIR.IR.attr!(func2, "enzymexla.memory_effects", mem)
end
MLIR.API.mlirRegionTakeBody(MLIR.IR.region(func2, 1), MLIR.IR.region(func, 1))
mesh_cache = Reactant.Compiler.sdycache()
is_sharded =
!isempty(mesh_cache) || (output_shardings !== nothing && !isempty(output_shardings))
if is_sharded
linear_arg_shardings = Vector{Tuple{MLIR.IR.Attribute,Symbol}}(
undef, length(linear_args)
)
# If an argument is mutated but is not sharded (aka sharding is NoSharding), we
# need to force a replicated sharding.
for i in mutated_args
arg = linear_args[i]
if !haskey(traced_args_to_shardings, arg) && !isempty(mesh_cache)
# Force a replicated sharding (it doesn't matter with mesh we use)
traced_args_to_shardings[arg] = Reactant.Sharding.Replicated(
first(values(mesh_cache)).mesh
)
end
end
ctx = MLIR.IR.context()
# Attach `sdy.sharding` attribute to the argument
for (i, arg) in enumerate(linear_args)
if haskey(traced_args_to_shardings, arg)
sharding = traced_args_to_shardings[arg]
(; sym_name, mesh_attr) = mesh_cache[(
sharding.mesh.logical_device_ids,
sharding.mesh.axis_names,
size(sharding.mesh),
)]
attr, dialect = Reactant.Sharding.get_tensor_sharding_attribute(
sharding, ctx, sym_name, mesh_attr, size(arg)
)
linear_arg_shardings[i] = (attr, dialect)
if dialect == :sdy
MLIR.API.mlirFuncSetArgAttr(func2, i - 1, "sdy.sharding", attr)
elseif dialect == :mhlo
MLIR.API.mlirFuncSetArgAttr(func2, i - 1, "mhlo.sharding", attr)
else
error("Unsupported dialect for tensor sharding: $(dialect)")
end
end
end
# Ensure the sharding of the mutated arguments is propagated to the results
for i in mutated_args
arg = linear_args[i]
if haskey(traced_args_to_shardings, arg) &&
(has_idx(arg, resprefix) || has_idx(arg, resargprefix))
idx = findfirst(Base.Fix1(===, arg), linear_results)
@assert idx !== nothing
attr, dialect = linear_arg_shardings[i]
if dialect == :sdy
MLIR.API.mlirFuncSetResultAttr(func2, idx - 1, "sdy.sharding", attr)
elseif dialect == :mhlo
MLIR.API.mlirFuncSetResultAttr(func2, idx - 1, "mhlo.sharding", attr)
else
error("Unsupported dialect for tensor sharding: $(dialect)")
end
end
end
for (i, res) in enumerate(linear_results)
if has_idx(res, argprefix) && haskey(traced_args_to_shardings, res)
argidx = findfirst(Base.Fix1(===, res), linear_args)
@assert argidx !== nothing
attr, dialect = linear_arg_shardings[argidx]
if dialect == :sdy
MLIR.API.mlirFuncSetResultAttr(func2, i - 1, "sdy.sharding", attr)
elseif dialect == :mhlo
MLIR.API.mlirFuncSetResultAttr(func2, i - 1, "mhlo.sharding", attr)
else
error("Unsupported dialect for tensor sharding: $(dialect)")
end
end
end
# XXX: Generalize the output shardings and expose it to the user
# output_shardings is a Int -> Sharding mapping
if output_shardings !== nothing
for (i, arg) in enumerate(linear_results)
if haskey(output_shardings, i)
sharding = output_shardings[i]
key = (
sharding.mesh.logical_device_ids,
sharding.mesh.axis_names,
size(sharding.mesh),
)
haskey(mesh_cache, key) || @opcall(mesh(sharding.mesh))
(; sym_name, mesh_attr) = mesh_cache[key]
attr, dialect = Reactant.Sharding.get_tensor_sharding_attribute(
sharding, ctx, sym_name, mesh_attr, size(arg)
)
if dialect == :sdy
MLIR.API.mlirFuncSetResultAttr(func2, i - 1, "sdy.sharding", attr)
elseif dialect == :mhlo
MLIR.API.mlirFuncSetResultAttr(func2, i - 1, "mhlo.sharding", attr)
else
error("Unsupported dialect for tensor sharding: $(dialect)")
end
end
end
end
unique_meshes = [m.mesh for m in values(mesh_cache)]
sorted_devices = [m.device_ids for m in unique_meshes]
@assert allequal(sorted_devices) "All meshes must have the same device ids"
global_device_ids = first(sorted_devices)
num_partitions = length(first(unique_meshes)) ÷ num_replicas
else
global_device_ids = ()
unique_meshes = nothing
num_partitions = 1
end
MLIR.API.mlirOperationDestroy(func.operation)
func.operation = MLIR.API.MlirOperation(C_NULL)
return (
func2,
traced_result,
ret,