-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathCompiler.jl
1695 lines (1546 loc) · 54 KB
/
Compiler.jl
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
module Compiler
using Reactant_jll
using Libdl: dlsym
import ..Reactant:
Reactant,
MLIR,
XLA,
ConcretePJRTArray,
ConcretePJRTNumber,
TracedRArray,
TracedRNumber,
RArray,
RNumber,
OrderedIdDict,
make_tracer,
TracedToConcrete,
append_path,
ancestor,
TracedType
import ..ReactantCore: correct_maybe_bcast_call
@inline function traced_getfield(@nospecialize(obj::Dict), field)
return Base.getindex(obj, field)
end
@inline function traced_getfield(@nospecialize(obj), field)
return Base.getfield(obj, field)
end
@inline function traced_getfield(@nospecialize(obj::AbstractArray{T}), field) where {T}
(isbitstype(T) || ancestor(obj) isa RArray) && return Base.getfield(obj, field)
return Base.getindex(obj, field)
end
@inline traced_setfield!(@nospecialize(obj), field, val) = Base.setfield!(obj, field, val)
@inline function traced_setfield!(
@nospecialize(obj::AbstractArray{T}), field, val
) where {T}
ancestor_obj = ancestor(obj)
(isbitstype(T) || ancestor_obj isa RArray) && return Base.setfield!(obj, field, val)
return Base.setindex!(obj, val, field)
end
@inline function traced_setfield!(@nospecialize(obj::Dict), field, val)
return Base.setindex!(obj, field, val)
end
function create_result(
tocopy::T, path, result_stores, path_to_shard_info, sharding_mesh
) where {T}
if !isstructtype(typeof(tocopy))
error("cannot copy $tocopy of type $(Core.Typeof(tocopy))")
end
elems = Union{Symbol,Expr}[]
for i in 1:fieldcount(T)
# If the field is undefined we don't set it. A common example for this is `du2`
# for Tridiagonal
isdefined(tocopy, i) || continue
ev = create_result(
getfield(tocopy, i),
append_path(path, i),
result_stores,
path_to_shard_info,
sharding_mesh,
)
push!(elems, ev)
end
return Expr(:new, T, elems...)
end
function __reconstruct_shardinfo(path, path_to_shard_info, sharding_mesh, N::Integer)
device_to_array_slices, hlo_sharding = path_to_shard_info[path]
delete!(path_to_shard_info, path)
sharding = Reactant.Sharding.HloSharding(
hlo_sharding, sharding_mesh, ntuple(Returns(true), N), ntuple(Returns(-1), N)
)
return Reactant.Sharding.ShardInfo(sharding, device_to_array_slices)
end
function create_result(
tocopy::ConcretePJRTNumber{T,D,S},
path,
result_stores,
path_to_shard_info,
sharding_mesh,
) where {T,D,S}
if haskey(result_stores, path)
restore = result_stores[path]
delete!(result_stores, path)
if path_to_shard_info !== nothing # restore sharding
sharding = __reconstruct_shardinfo(
path, path_to_shard_info, sharding_mesh, ndims(tocopy)
)
return :(ConcretePJRTNumber{$T,length($(restore)),$(typeof(sharding))}(
($(restore)...,), $sharding
))
else
return :(ConcretePJRTNumber{$T}($restore))
end
end
if path_to_shard_info !== nothing # restore sharding
sharding = __reconstruct_shardinfo(
path, path_to_shard_info, sharding_mesh, ndims(tocopy)
)
return :(ConcretePJRTNumber{$T,length($(tocopy.data)),$(typeof(sharding))}(
($(tocopy.data...,)), $sharding
))
end
# We will set the data for this later
return :(ConcretePJRTNumber{$T}($(tocopy.data)))
end
function create_result(
tocopy::ConcretePJRTArray{T,N,D,S},
path,
result_stores,
path_to_shard_info,
sharding_mesh,
) where {T,N,D,S}
if haskey(result_stores, path)
restore = result_stores[path]
delete!(result_stores, path)
if path_to_shard_info !== nothing # restore sharding
sharding = __reconstruct_shardinfo(
path, path_to_shard_info, sharding_mesh, ndims(tocopy)
)
return :(ConcretePJRTArray{$T,$N,length($(restore)),$(typeof(sharding))}(
($(restore)...,), $(tocopy.shape), $sharding
))
else
return :(ConcretePJRTArray{$T,$N}($restore, $(tocopy.shape)))
end
end
if path_to_shard_info !== nothing # restore sharding
sharding = __reconstruct_shardinfo(
path, path_to_shard_info, sharding_mesh, ndims(tocopy)
)
return :(ConcretePJRTArray{$T,$N,length($(tocopy.data)),$(typeof(sharding))}(
($(tocopy.data)...,), $(tocopy.shape), $sharding
))
end
# We will set the data for this later
return :(ConcretePJRTArray{$T,$N,$D,$S}(
$(tocopy.data), $(tocopy.shape), $(tocopy.sharding)
))
end
function create_result(
tocopy::Array{T,N}, path, result_stores, path_to_shard_info, sharding_mesh
) where {T,N}
elems = Expr[]
for (i, v) in enumerate(tocopy)
push!(
elems,
create_result(
v, append_path(path, i), result_stores, path_to_shard_info, sharding_mesh
),
)
end
# TODO is there a way to not call `reshape` here? what expr is used for array literals?
return :(reshape($T[$(elems...)], $(size(tocopy))...))
end
function create_result(
tocopy::Tuple, path, result_stores, path_to_shard_info, sharding_mesh
)
elems = Union{Symbol,Expr}[]
for (k, v) in pairs(tocopy)
push!(
elems,
create_result(
v, append_path(path, k), result_stores, path_to_shard_info, sharding_mesh
),
)
end
return :(($(elems...),))
end
function create_result(
tocopy::NamedTuple{K,T}, path, result_stores, path_to_shard_info, sharding_mesh
) where {K,T}
elems = Union{Symbol,Expr}[]
for (i, (k, v)) in enumerate(pairs(tocopy))
push!(
elems,
create_result(
v, append_path(path, i), result_stores, path_to_shard_info, sharding_mesh
),
)
end
return :(NamedTuple{$K}(($(elems...),)))
end
function create_result(
tocopy::D, path, result_stores, path_to_shard_info, sharding_mesh
) where {K,V,D<:AbstractDict{K,V}}
elems = Expr[]
for (i, p) in enumerate(pairs(tocopy))
push!(
elems,
create_result(
p, append_path(path, i), result_stores, path_to_shard_info, sharding_mesh
),
)
end
return :($D([$(elems...)]))
end
function create_result(
tocopy::Union{Integer,AbstractFloat,AbstractString,Nothing,Type,Symbol,Char},
path,
result_stores,
path_to_shard_info,
sharding_mesh,
)
return Meta.quot(tocopy)
end
# Optimization passes via transform dialect
function optimization_passes(; no_nan::Bool=false, sroa::Bool=false, inline::Bool=true)
transform_passes_list = [
"patterns=compare_op_canon<16>",
"transpose_transpose<16>",
"broadcast_in_dim_op_canon<16>",
"convert_op_canon<16>",
"dynamic_broadcast_in_dim_op_not_actually_dynamic<16>",
"chained_dynamic_broadcast_in_dim_canonicalization<16>",
"dynamic_broadcast_in_dim_all_dims_non_expanding<16>",
"noop_reduce_op_canon<16>",
"empty_reduce_op_canon<16>",
"dynamic_reshape_op_canon<16>",
"get_tuple_element_op_canon<16>",
"real_op_canon<16>",
"imag_op_canon<16>",
"conj_complex_negate<16>",
"get_dimension_size_op_canon<16>",
"gather_op_canon<16>",
"reshape_op_canon<16>",
"merge_consecutive_reshapes<16>",
"transpose_is_reshape<16>",
"zero_extent_tensor_canon<16>",
"reorder_elementwise_and_shape_op<16>",
"chlo_inf_const_prop<16>",
"gamma_const_prop<16>",
"cse_broadcast_in_dim<16>",
"cse_slice<16>",
"cse_transpose<16>",
"cse_convert<16>",
"cse_pad<16>",
"cse_dot_general<16>",
"cse_reshape<16>",
"cse_mul<16>",
"cse_div<16>",
"cse_add<16>",
"cse_subtract<16>",
"cse_min<16>",
"cse_max<16>",
"cse_neg<16>",
"cse_concatenate<16>",
"concatenate_op_canon<16>(1024)",
"select_op_canon<16>(1024)",
"add_simplify<16>",
"sub_simplify<16>",
"and_simplify<16>",
"max_simplify<16>",
"min_simplify<16>",
"or_simplify<16>",
"negate_simplify<16>",
"mul_simplify<16>",
"div_simplify<16>",
"rem_simplify<16>",
"pow_simplify<16>",
"sqrt_simplify<16>",
"cos_simplify<16>",
"sin_simplify<16>",
"noop_slice<16>",
"noop_reverse<16>",
"const_prop_through_barrier<16>",
"slice_slice<16>",
"shift_right_logical_simplify<16>",
"pad_simplify<16>",
"negative_pad_to_slice<16>",
"tanh_simplify<16>",
"exp_simplify<16>",
"slice_simplify<16>",
"convert_simplify<16>",
"dynamic_slice_to_static<16>",
"dynamic_update_slice_elim<16>",
"concat_to_broadcast<16>",
"reduce_to_reshape<16>",
"broadcast_to_reshape<16>",
"gather_simplify<16>",
"iota_simplify<16>(1024)",
"broadcast_in_dim_simplify<16>(1024)",
"convert_concat<1>",
"dynamic_update_to_concat<1>",
"slice_of_dynamic_update<1>",
"slice_elementwise<1>",
"slice_pad<1>",
"dot_reshape_dot<1>",
"concat_const_prop<1>",
"concat_fuse<1>",
"pad_reshape_pad<1>",
"pad_pad<1>",
"concat_push_binop_add<1>",
"concat_push_binop_mul<1>",
"scatter_to_dynamic_update_slice<1>",
"reduce_concat<1>",
"slice_concat<1>",
"concat_slice<1>",
"select_op_used_within_if<1>",
"bin_broadcast_splat_add<1>",
"bin_broadcast_splat_subtract<1>",
"bin_broadcast_splat_div<1>",
"bin_broadcast_splat_mul<1>",
"reshape_iota<16>",
"slice_reshape_slice<1>",
"dot_general_simplify<16>",
"transpose_simplify<16>",
"reshape_empty_broadcast<1>",
"add_pad_pad_to_concat<1>",
"broadcast_reshape<1>",
"slice_reshape_concat<1>",
"slice_reshape_elementwise<1>",
"slice_reshape_transpose<1>",
"slice_reshape_dot_general<1>",
"concat_pad<1>",
"reduce_pad<1>",
"broadcast_pad<1>",
"zero_product_reshape_pad<1>",
"mul_zero_pad<1>",
"div_zero_pad<1>",
"binop_const_reshape_pad<1>",
"binop_const_pad_add<1>",
"binop_const_pad_subtract<1>",
"binop_const_pad_mul<1>",
"binop_const_pad_div<1>",
"slice_reshape_pad<1>",
"binop_binop_pad_pad_add<1>",
"binop_binop_pad_pad_mul<1>",
"binop_pad_pad_add<1>",
"binop_pad_pad_subtract<1>",
"binop_pad_pad_mul<1>",
"binop_pad_pad_div<1>",
"binop_pad_pad_min<1>",
"binop_pad_pad_max<1>",
"unary_pad_push_convert<1>",
"unary_pad_push_tanh<1>",
"unary_pad_push_exp<1>",
"transpose_pad<1>",
"transpose_dot_reorder<1>",
"dot_transpose<1>",
"transpose_einsum<1>",
"einsum_transpose<1>",
"transpose_convolution<1>",
"convolution_transpose<1>",
"convert_convert_float<1>",
"concat_to_pad<1>",
"concat_appending_reshape<1>",
"reshape_iota<1>",
"broadcast_reduce<1>",
"slice_dot_general<1>",
"dot_reshape_pad<1>",
"pad_dot_general<1>(0)",
"dot_reshape_pad<1>",
"pad_dot_general<1>(1)",
"if_inline<1>",
"if_to_select<1>",
"dynamic_update_slice_const_prop",
"dynamic_gather_op_is_not_dynamic<16>",
"divide_sqrt_to_multiply_rsqrt<16>",
"binary_op_transpose_simplify_add",
"binary_op_transpose_simplify_sub",
"binary_op_transpose_simplify_mul",
"binary_op_transpose_simplify_div",
"binary_op_transpose_simplify_min",
"binary_op_transpose_simplify_max",
"binary_op_transpose_simplify_pow",
"binary_op_transpose_simplify_rem",
"binary_op_transpose_simplify_or",
"binary_op_transpose_simplify_and",
"binary_op_transpose_simplify_xor",
"associative_binary_op_reordering<1>",
"transpose_unary_transpose_abs",
"transpose_unary_transpose_neg",
"transpose_unary_transpose_sqrt",
"transpose_unary_transpose_rsqrt",
"transpose_unary_transpose_ceil",
"transpose_unary_transpose_convert",
"transpose_unary_transpose_cosine",
"transpose_unary_transpose_exp",
"transpose_unary_transpose_expm1",
"transpose_unary_transpose_log",
"transpose_unary_transpose_log1p",
"transpose_unary_transpose_sign",
"transpose_unary_transpose_sine",
"transpose_unary_transpose_tanh",
"transpose_broadcast_in_dim_to_broadcast_in_dim<16>",
"scatter_indices_are_unique",
"transpose_reduce_simplify",
"replace_neg_add_with_subtract",
"log_const_prop<1>",
"log_plus_one_const_prop<1>",
"binop_const_simplify",
"transpose_broadcast_in_dim_to_broadcast_in_dim",
"not_select_simplify",
"scatter_update_computation_const_prop",
"common_compare_expression_rewrite",
"compare_select_simplify",
"while_simplify<1>",
"scatter_update_computation_const_prop",
"if_remove_unused",
]
if no_nan
append!(
transform_passes_list,
["no_nan", "no_nan_self_sub_simplify", "no_nan_add_sub_simplify(1)"],
)
else
push!(transform_passes_list, "no_nan_add_sub_simplify(0)")
end
transform_passes = join(
[
"enzyme-hlo-generate-td{" * join(transform_passes_list, ';') * "}",
"transform-interpreter",
"enzyme-hlo-remove-transform",
],
",",
)
func_passes = join(["canonicalize", "cse", "canonicalize", transform_passes], ",")
passes = String[]
if inline
push!(passes, "inline{default-pipeline=canonicalize max-iterations=4}")
end
if sroa
push!(passes, "propagate-constant-bounds")
if DUMP_LLVMIR[]
push!(
passes,
"sroa-wrappers{dump_prellvm=true dump_postllvm=true instcombine=false instsimplify=true}",
)
else
push!(passes, "sroa-wrappers{instcombine=false instsimplify=true}")
end
push!(passes, "canonicalize")
push!(passes, "sroa-wrappers{instcombine=false instsimplify=true}")
push!(passes, "libdevice-funcs-raise")
push!(passes, "canonicalize")
push!(passes, "remove-duplicate-func-def")
end
push!(passes, func_passes)
return join(passes, ',')
end
# TODO we want to be able to run the more advanced passes via transform dialect as an enzyme intermediate
# However, this errs as we cannot attach the transform with to the funcop itself [as we run a functionpass].
const enzyme_pass::String = "enzyme{postpasses=\"arith-raise{stablehlo=true},canonicalize,cse,canonicalize,remove-unnecessary-enzyme-ops,enzyme-simplify-math,canonicalize,cse,canonicalize\"}"
function run_pass_pipeline!(mod, pass_pipeline; enable_verifier=true)
pm = MLIR.IR.PassManager()
MLIR.IR.enable_verifier!(pm, enable_verifier)
opm = MLIR.IR.OpPassManager(pm)
MLIR.IR.add_pipeline!(opm, pass_pipeline)
MLIR.IR.run!(pm, mod)
return mod
end
const context_gc_vector = Dict{MLIR.IR.Context,Vector{TracedRArray}}()
# helper for debug purposes: String -> Text
function run_pass_pipeline_on_source(source, pass_pipeline; enable_verifier=true)
ctx = MLIR.IR.Context(Reactant.registry[], false)
context_gc_vector[ctx] = Vector{TracedRArray}(undef, 0)
@ccall MLIR.API.mlir_c.RegisterDialects(ctx::MLIR.API.MlirContext)::Cvoid
result = MLIR.IR.context!(ctx) do
mod = parse(MLIR.IR.Module, source)
run_pass_pipeline!(mod, pass_pipeline; enable_verifier)
MLIR.IR.verifyall(MLIR.IR.Operation(mod); debug=true)
Text(repr(mod))
end
Base.delete!(context_gc_vector, ctx)
return result
end
function compile_mlir(f, args; client=nothing, kwargs...)
ctx = MLIR.IR.Context(Reactant.registry[], false)
context_gc_vector[ctx] = Vector{TracedRArray}(undef, 0)
@ccall MLIR.API.mlir_c.RegisterDialects(ctx::MLIR.API.MlirContext)::Cvoid
backend = XLA.platform_name(client !== nothing ? client : XLA.default_backend())
if backend == "CUDA"
backend = "GPU"
elseif backend == "CPU"
backend = "cpu"
end
results = MLIR.IR.context!(ctx) do
mod = MLIR.IR.Module(MLIR.IR.Location())
mlir_fn_res = compile_mlir!(mod, f, args; backend, kwargs...)
# Attach a name, and partitioning attributes to the module
__add_mhlo_attributes_and_name!(
mod, f; mlir_fn_res.num_partitions, mlir_fn_res.num_replicas
)
return mod, mlir_fn_res
end
Base.delete!(context_gc_vector, ctx)
return results
end
const PartitionKA = Ref{Bool}(true)
const cubinChip = Ref{String}("sm_60")
const cubinFormat = Ref{String}("bin")
const cuindexBitWidth = Ref{Int}(32)
const cuOptLevel = Ref{Int}(2)
# Wgatever the relevant highest version from our LLVM is within NVPTX.td
# Or more specifically looking at clang/lib/Driver/ToolChains/Cuda.cpp:684
# We see relevant ptx version is CUDA 12.6 -> 85
# 12.2 -> 82
# 11.8 -> 78
function cubinFeatures()
ver = @ccall MLIR.API.mlir_c.ReactantCudaDriverGetVersion()::UInt32
# No cuda available
if ver == 0
return "+ptx86"
end
ver2 = @ccall MLIR.API.mlir_c.ReactantHermeticCudaGetVersion()::UInt32
ver = min(ver, ver2)
major, ver = divrem(ver, 1000)
minor, patch = divrem(ver, 10)
version = VersionNumber(major, minor, patch)
# From https://github.com/llvm/llvm-project/blob/106c483a102e1328f11e2b1d9398f4ad2826b59f/clang/lib/Driver/ToolChains/Cuda.cpp#L685
cuver_map = Dict([
(126, 85),
(125, 85),
(124, 84),
(123, 83),
(122, 82),
(121, 81),
(120, 80),
(118, 78),
(117, 77),
(116, 76),
(115, 75),
(114, 74),
(113, 73),
(112, 72),
(111, 71),
(110, 70),
(102, 65),
(101, 64),
(100, 63),
(92, 61),
(91, 61),
(90, 60),
])
mver = major * 10 + minor
if mver > 126
return 86
end
ptx = cuver_map[mver]
return "+ptx$ptx"
end
const DEBUG_KERNEL = Ref{Bool}(false)
const DUMP_LLVMIR = Ref{Bool}(false)
const Raise = Ref{Bool}(false)
function compile_mlir!(
mod,
f,
args,
callcache=Dict{
Vector,
@NamedTuple{
f_name::String,
mlir_result_types::Vector{MLIR.IR.Type},
traced_result::Any,
mutated_args::Vector{Int},
}
}();
optimize::Union{Bool,Symbol}=true,
no_nan::Bool=false,
backend="gpu",
fn_kwargs=(),
)
# Explicitly don't use block! to avoid creating a closure, which creates
# both compile-time and relocatability issues
MLIR.IR.activate!(mod)
MLIR.IR.activate!(MLIR.IR.body(mod))
activate_callcache!(callcache)
mlir_fn_res = try
Reactant.TracedUtils.make_mlir_fn(f, args, fn_kwargs, "main", true)
finally
deactivate_callcache!(callcache)
MLIR.IR.deactivate!(MLIR.IR.body(mod))
MLIR.IR.deactivate!(mod)
end
(; fnwrapped, traced_result, seen_args, ret, linear_args, in_tys, linear_results) =
mlir_fn_res
compiled_f = mlir_fn_res.f
concrete_seen = OrderedIdDict()
concrete_result = make_tracer(
concrete_seen, traced_result, ("result",), TracedToConcrete
)
optimize isa Bool && (optimize = ifelse(optimize, :all, :none))
toolkit = ""
if isdefined(Reactant_jll, :ptxas_path)
toolkit = Reactant_jll.ptxas_path[1:(end - length("/bin/ptxas"))]
end
if backend == "cpu"
kern = "lower-kernel{backend=cpu},canonicalize"
jit = "lower-jit{openmp=true backend=cpu},symbol-dce"
elseif DEBUG_KERNEL[]
curesulthandler = dlsym(
Reactant_jll.libReactantExtra_handle, "ReactantHandleCuResult"
)
@assert curesulthandler !== nothing
curesulthandler = Base.reinterpret(UInt, curesulthandler)
kern = if Raise[]
"lower-kernel{backend=cpu},symbol-dce,canonicalize"
else
"lower-kernel,canonicalize"
end
jit = "lower-jit{debug=true cuResultHandlerPtr=$curesulthandler cuOptLevel=$(cuOptLevel[]) cubinFormat=$(cubinFormat[]) indexBitWidth=$(cuindexBitWidth[]) cubinChip=$(cubinChip[]) cubinFeatures=$(cubinFeatures()) run_init=true toolkitPath=$toolkit},symbol-dce"
else
kern = if Raise[]
"lower-kernel{backend=cpu},symbol-dce,canonicalize"
else
"lower-kernel,canonicalize"
end
jit = "lower-jit{cuOptLevel=$(cuOptLevel[]) indexBitWidth=$(cuindexBitWidth[]) cubinFormat=$(cubinFormat[]) cubinChip=$(cubinChip[]) cubinFeatures=$(cubinFeatures()) run_init=true toolkitPath=$toolkit},symbol-dce"
end
opt_passes = optimization_passes(; no_nan, sroa=true)
opt_passes2 = optimization_passes(; no_nan, sroa=false)
raise = if Raise[]
"canonicalize,llvm-to-memref-access,canonicalize,convert-llvm-to-cf,canonicalize,enzyme-lift-cf-to-scf,canonicalize,func.func(canonicalize-loops),canonicalize-scf-for,canonicalize,affine-cfg,canonicalize,func.func(canonicalize-loops),canonicalize,llvm-to-affine-access,canonicalize,delinearize-indexing,canonicalize,raise-affine-to-stablehlo,arith-raise{stablehlo=true}," *
opt_passes2
else
"canonicalize"
end
if optimize === :all
run_pass_pipeline!(mod, join([opt_passes, "enzyme-batch", opt_passes2], ","))
run_pass_pipeline!(
mod, "$enzyme_pass,arith-raise{stablehlo=true}"; enable_verifier=false
)
run_pass_pipeline!(
mod,
join(
[
"canonicalize",
"remove-unnecessary-enzyme-ops",
"enzyme-simplify-math",
opt_passes2,
kern,
raise,
jit,
],
',',
),
)
elseif optimize === :before_kernel
run_pass_pipeline!(mod, join([opt_passes, "enzyme-batch", opt_passes2], ","))
run_pass_pipeline!(
mod, "$enzyme_pass,arith-raise{stablehlo=true}"; enable_verifier=false
)
run_pass_pipeline!(
mod,
join(
[
"canonicalize",
"remove-unnecessary-enzyme-ops",
"enzyme-simplify-math",
opt_passes2,
],
',',
),
)
elseif optimize === :before_jit
run_pass_pipeline!(mod, join([opt_passes, "enzyme-batch", opt_passes2], ","))
run_pass_pipeline!(
mod, "$enzyme_pass,arith-raise{stablehlo=true}"; enable_verifier=false
)
run_pass_pipeline!(
mod,
join(
[
"canonicalize",
"remove-unnecessary-enzyme-ops",
"enzyme-simplify-math",
opt_passes2,
kern,
raise,
],
',',
),
)
elseif optimize === :before_raise
run_pass_pipeline!(mod, join([opt_passes, "enzyme-batch", opt_passes2], ","))
run_pass_pipeline!(
mod, "$enzyme_pass,arith-raise{stablehlo=true}"; enable_verifier=false
)
run_pass_pipeline!(
mod,
join(
[
"canonicalize",
"remove-unnecessary-enzyme-ops",
"enzyme-simplify-math",
opt_passes2,
kern,
],
',',
),
)
elseif optimize === :no_enzyme
run_pass_pipeline!(mod, join([opt_passes, "enzyme-batch", opt_passes2], ","))
run_pass_pipeline!(mod, "arith-raise{stablehlo=true}"; enable_verifier=false)
run_pass_pipeline!(
mod,
join(
[
"canonicalize",
"remove-unnecessary-enzyme-ops",
"enzyme-simplify-math",
opt_passes2,
],
',',
),
)
elseif optimize === :only_enzyme
run_pass_pipeline!(mod, "enzyme-batch")
run_pass_pipeline!(
mod, "$enzyme_pass,arith-raise{stablehlo=true}"; enable_verifier=false
)
run_pass_pipeline!(
mod,
join(
["canonicalize", "remove-unnecessary-enzyme-ops", "enzyme-simplify-math"],
',',
),
)
elseif optimize === :after_enzyme
run_pass_pipeline!(mod, "enzyme-batch")
run_pass_pipeline!(
mod, "$enzyme_pass,arith-raise{stablehlo=true}"; enable_verifier=false
)
run_pass_pipeline!(
mod,
join(
[
"canonicalize",
"remove-unnecessary-enzyme-ops",
"enzyme-simplify-math",
opt_passes2,
kern,
raise,
jit,
],
',',
),
)
elseif optimize === :before_enzyme
run_pass_pipeline!(mod, join([opt_passes, "enzyme-batch", opt_passes2], ","))
run_pass_pipeline!(
mod, "$enzyme_pass,arith-raise{stablehlo=true}"; enable_verifier=false
)
run_pass_pipeline!(
mod,
join(
[
"canonicalize,remove-unnecessary-enzyme-ops,enzyme-simplify-math",
kern,
raise,
jit,
],
',',
),
)
elseif optimize === :canonicalize
run_pass_pipeline!(mod, "canonicalize")
elseif optimize === :just_batch
run_pass_pipeline!(mod, "enzyme-batch")
elseif optimize !== :none
error("Invalid optimize option: $(Meta.quot(optimize))")
end
preserved_args = Tuple{TracedType,Int}[]
results = [MLIR.IR.operand(ret, i) for i in 1:MLIR.IR.noperands(ret)]
nresults = MLIR.IR.Value[]
linear_results2 = TracedType[]
results_mask = falses(length(results))
for (i, op) in enumerate(results)
if !MLIR.IR.is_block_arg(op)
push!(nresults, op)
push!(linear_results2, linear_results[i])
results_mask[i] = true
continue
end
push!(preserved_args, (linear_results[i], MLIR.IR.block_arg_num(op)))
end
fnbody = MLIR.IR.block(ret)
MLIR.API.mlirOperationDestroy(ret.operation)
ret.operation = MLIR.API.MlirOperation(C_NULL)
MLIR.IR.block!(fnbody) do
return MLIR.Dialects.func.return_(nresults)
end
out_tys2 = [MLIR.IR.type(a) for a in nresults]
res_attrs = MLIR.IR.attr(compiled_f, "res_attrs")
if res_attrs isa MLIR.IR.Attribute
res_attrs = [
res_attrs[i - 1] for (i, present) in enumerate(results_mask) if present
]
end
func3 = MLIR.Dialects.func.func_(;
sym_name="main",
function_type=MLIR.IR.FunctionType(in_tys, out_tys2),
arg_attrs=MLIR.IR.attr(compiled_f, "arg_attrs"),
res_attrs,
no_inline=MLIR.IR.attr(compiled_f, "no_inline"),
body=MLIR.IR.Region(),
)
MLIR.API.mlirRegionTakeBody(MLIR.IR.region(func3, 1), MLIR.IR.region(compiled_f, 1))
push!(MLIR.IR.body(mod), func3)
MLIR.API.mlirOperationDestroy(compiled_f.operation)
compiled_f.operation = MLIR.API.MlirOperation(C_NULL)
return Reactant.TracedUtils.CompiledMlirFnResult(
fnwrapped,
func3,
traced_result,
mlir_fn_res.result,
seen_args,
ret,
linear_args,
in_tys,
linear_results2,
mlir_fn_res.num_partitions,
mlir_fn_res.num_replicas,
mlir_fn_res.is_sharded,
preserved_args,
concrete_result,
mlir_fn_res.sharding_mesh,
mlir_fn_res.mutated_args,
)
end
"""
@code_hlo [optimize = ...] [no_nan = <true/false>] f(args...)
See also [`@code_xla`](@ref), [`@code_mhlo`](@ref).
"""
macro code_hlo(args...)
default_options = Dict{Symbol,Any}(
:optimize => true, :no_nan => false, :client => nothing
)
compile_expr, (; compiled) = compile_call_expr(
__module__, compile_mlir, default_options, args...
)
#! format: off
return esc(
:(
$(compile_expr);
$(first)($(compiled))
)
)
#! format: on
end
"""
@code_mhlo [optimize = ...] [no_nan = <true/false>] f(args...)
Similar to `@code_hlo`, but prints the module after running the XLA compiler.
See also [`@code_xla`](@ref), [`@code_hlo`](@ref).
"""
macro code_mhlo(args...)
default_options = Dict{Symbol,Any}(
:optimize => true, :no_nan => false, :client => nothing
)
compile_expr, (; compiled) = compile_call_expr(
__module__, compile_xla, default_options, args...
)
#! format: off
return esc(
:(
$(compile_expr);
$(first)($(compiled))
)
)
#! format: on
end
"""
@code_xla [optimize = ...] [no_nan = <true/false>] f(args...)
Similar to `@code_hlo`, but prints the HLO module.
See also [`@code_mhlo`](@ref), [`@code_hlo`](@ref).
"""
macro code_xla(args...)
default_options = Dict{Symbol,Any}(
:optimize => true, :no_nan => false, :client => nothing
)
compile_expr, (; compiled) = compile_call_expr(
__module__, compile_xla, default_options, args...
)
#! format: off
return esc(
:(
$(compile_expr);
exec = $(compiled)[2];
hlo_modules = $(XLA.get_hlo_modules)(exec);
length(hlo_modules) == 1 ? only(hlo_modules) : hlo_modules
)
)
#! format: on
end
"""
@compile [optimize = ...] [no_nan = <true/false>] [sync = <true/false>] f(args...)
"""
macro compile(args...)
default_options = Dict{Symbol,Any}(
:optimize => true, :sync => false, :no_nan => false, :client => nothing
)
return esc(first(compile_call_expr(__module__, compile, default_options, args...)))
end
"""
@jit [optimize = ...] [no_nan = <true/false>] [sync = <true/false>] f(args...)
Run @compile f(args..) then immediately execute it
"""
macro jit(args...)
default_options = Dict{Symbol,Any}(
:optimize => true, :sync => false, :no_nan => false, :client => nothing
)
compile_expr, (; compiled, args) = compile_call_expr(
__module__, compile, default_options, args...
)
#! format: off
return esc(
:(
$(compile_expr);
$(compiled)($(args)...)
)
)
#! format: on
end
function compile_call_expr(mod, compiler, options, args...)
while length(args) > 1
option, args = args[1], args[2:end]
if !Meta.isexpr(option, :(=))
error("Invalid option $(option)")
else
option_name = option.args[1]
@assert haskey(options, option_name) "Invalid option $(option_name)"
options[option_name] = option.args[2]
end
end
call = only(args)
f_symbol = gensym(:f)
args_symbol = gensym(:args)
kwargs_symbol = gensym(:kwargs)
compiled_symbol = gensym(:compiled)
if Meta.isexpr(call, :call)
bcast, fname, fname_full = correct_maybe_bcast_call(call.args[1])