-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathEvaluate.jl
More file actions
1002 lines (941 loc) · 34.7 KB
/
Evaluate.jl
File metadata and controls
1002 lines (941 loc) · 34.7 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
module EvaluateModule
using DispatchDoctor: @stable, @unstable
import ..NodeModule: AbstractExpressionNode, constructorof, GraphNode, topological_sort
import ..StringsModule: string_tree
import ..OperatorEnumModule: OperatorEnum, GenericOperatorEnum
import ..UtilsModule: fill_similar, counttuple, ResultOk
import ..NodeUtilsModule: is_constant
import ..ExtensionInterfaceModule: bumper_eval_tree_array, _is_loopvectorization_loaded
import ..ValueInterfaceModule: is_valid, is_valid_array
const OPERATOR_LIMIT_BEFORE_SLOWDOWN = 15
macro return_on_nonfinite_val(eval_options, val, X)
:(
if $(esc(eval_options)).early_exit isa Val{true} && !is_valid($(esc(val)))
return $(ResultOk)(similar($(esc(X)), axes($(esc(X)), 2)), false)
end
)
end
macro return_on_nonfinite_array(eval_options, array)
:(
if $(esc(eval_options)).early_exit isa Val{true} && !is_valid_array($(esc(array)))
return $(ResultOk)($(esc(array)), false)
end
)
end
"""
EvalOptions{T,B,E}
This holds options for expression evaluation, such as evaluation backend.
# Fields
- `turbo::Val{T}=Val(false)`: If `Val{true}`, use LoopVectorization.jl for faster
evaluation.
- `bumper::Val{B}=Val(false)`: If `Val{true}`, use Bumper.jl for faster evaluation.
- `early_exit::Val{E}=Val(true)`: If `Val{true}`, any element of any step becoming
`NaN` or `Inf` will terminate the computation. For `eval_tree_array`, this will
result in the second return value, the completion flag, being `false`. For
calling an expression using `tree(X)`, this will result in `NaN`s filling
the entire buffer. This early exit is performed to avoid wasting compute cycles.
Setting `Val{false}` will continue the computation as usual and thus result in
`NaN`s only in the elements that actually have `NaN`s.
"""
struct EvalOptions{T,B,E}
turbo::Val{T}
bumper::Val{B}
early_exit::Val{E}
end
@unstable @inline _to_bool_val(x::Bool) = x ? Val(true) : Val(false)
@inline _to_bool_val(x::Val{T}) where {T} = Val(T::Bool)
@unstable function EvalOptions(;
turbo::Union{Bool,Val}=Val(false),
bumper::Union{Bool,Val}=Val(false),
early_exit::Union{Bool,Val}=Val(true),
)
return EvalOptions(_to_bool_val(turbo), _to_bool_val(bumper), _to_bool_val(early_exit))
end
@unstable function _process_deprecated_kws(eval_options, deprecated_kws)
turbo = get(deprecated_kws, :turbo, nothing)
bumper = get(deprecated_kws, :bumper, nothing)
if any(Base.Fix2(∉, (:turbo, :bumper)), keys(deprecated_kws))
throw(ArgumentError("Invalid keyword argument(s): $(keys(deprecated_kws))"))
end
if !isempty(deprecated_kws)
@assert(
eval_options === nothing,
"Cannot use both `eval_options` and deprecated flags `turbo` and `bumper`."
)
# TODO: We don't do a depwarn as it can GREATLY bottleneck the search speed.
end
if eval_options !== nothing
return eval_options
else
return EvalOptions(;
turbo=turbo === nothing ? Val(false) : turbo,
bumper=bumper === nothing ? Val(false) : bumper,
)
end
end
"""
eval_tree_array(
tree::AbstractExpressionNode{T},
cX::AbstractMatrix{T},
operators::OperatorEnum;
eval_options::Union{EvalOptions,Nothing}=nothing,
) where {T}
Evaluate a binary tree (equation) over a given input data matrix. The
operators contain all of the operators used. This function fuses doublets
and triplets of operations for lower memory usage.
# Arguments
- `tree::AbstractExpressionNode`: The root node of the tree to evaluate.
- `cX::AbstractMatrix{T}`: The input data to evaluate the tree on.
- `operators::OperatorEnum`: The operators used in the tree.
- `eval_options::Union{EvalOptions,Nothing}`: See [`EvalOptions`](@ref) for documentation
on the different evaluation modes.
# Returns
- `(output, complete)::Tuple{AbstractVector{T}, Bool}`: the result,
which is a 1D array, as well as if the evaluation completed
successfully (true/false). A `false` complete means an infinity
or nan was encountered, and a large loss should be assigned
to the equation.
# Notes
This function can be represented by the following pseudocode:
```
def eval(current_node)
if current_node is leaf
return current_node.value
elif current_node is degree 1
return current_node.operator(eval(current_node.left_child))
else
return current_node.operator(eval(current_node.left_child), eval(current_node.right_child))
```
The bulk of the code is for optimizations and pre-emptive NaN/Inf checks,
which speed up evaluation significantly.
"""
function eval_tree_array(
tree::AbstractExpressionNode{T},
cX::AbstractMatrix{T},
operators::OperatorEnum;
eval_options::Union{EvalOptions,Nothing}=nothing,
_deprecated_kws...,
) where {T}
_eval_options = _process_deprecated_kws(eval_options, _deprecated_kws)
if _eval_options.turbo isa Val{true} || _eval_options.bumper isa Val{true}
@assert T in (Float32, Float64)
end
if _eval_options.turbo isa Val{true}
_is_loopvectorization_loaded(0) ||
error("Please load the LoopVectorization.jl package to use this feature.")
end
if (_eval_options.turbo isa Val{true} || _eval_options.bumper isa Val{true}) &&
!(T <: Number)
error(
"Bumper and LoopVectorization features are only compatible with numeric element types",
)
end
if _eval_options.bumper isa Val{true}
return bumper_eval_tree_array(tree, cX, operators, _eval_options)
end
result = _eval_tree_array(tree, cX, operators, _eval_options)
return (
result.x,
result.ok && (_eval_options.early_exit isa Val{false} || is_valid_array(result.x)),
)
end
function eval_tree_array(
tree::AbstractExpressionNode{T}, cX::AbstractVector{T}, operators::OperatorEnum; kws...
) where {T}
return eval_tree_array(tree, reshape(cX, (size(cX, 1), 1)), operators; kws...)
end
function eval_tree_array(
tree::AbstractExpressionNode{T1},
cX::AbstractMatrix{T2},
operators::OperatorEnum;
kws...,
) where {T1,T2}
T = promote_type(T1, T2)
@warn "Warning: eval_tree_array received mixed types: tree=$(T1) and data=$(T2)."
tree = convert(constructorof(typeof(tree)){T}, tree)
cX = Base.Fix1(convert, T).(cX)
return eval_tree_array(tree, cX, operators; kws...)
end
# These are marked unstable due to issues discussed on
# https://github.com/JuliaLang/julia/issues/55147
@unstable get_nuna(::Type{<:OperatorEnum{B,U}}) where {B,U} = counttuple(U)
@unstable get_nbin(::Type{<:OperatorEnum{B}}) where {B} = counttuple(B)
function _eval_tree_array(
tree::AbstractExpressionNode{T},
cX::AbstractMatrix{T},
operators::OperatorEnum,
eval_options::EvalOptions,
)::ResultOk where {T}
# First, we see if there are only constants in the tree - meaning
# we can just return the constant result.
if tree.degree == 0
return deg0_eval(tree, cX)
elseif is_constant(tree)
# Speed hack for constant trees.
const_result = dispatch_constant_tree(tree, operators)::ResultOk{Vector{T}}
!const_result.ok && return ResultOk(similar(cX, axes(cX, 2)), false)
return ResultOk(fill_similar(const_result.x[], cX, axes(cX, 2)), true)
elseif tree.degree == 1
op_idx = tree.op
return dispatch_deg1_eval(tree, cX, op_idx, operators, eval_options)
else
# TODO - add op(op2(x, y), z) and op(x, op2(y, z))
# op(x, y), where x, y are constants or variables.
op_idx = tree.op
return dispatch_deg2_eval(tree, cX, op_idx, operators, eval_options)
end
end
function deg2_eval(
cumulator_l::AbstractVector{T},
cumulator_r::AbstractVector{T},
op::F,
::EvalOptions{false},
)::ResultOk where {T,F}
@inbounds @simd for j in eachindex(cumulator_l)
x = op(cumulator_l[j], cumulator_r[j])::T
cumulator_l[j] = x
end
return ResultOk(cumulator_l, true)
end
function deg1_eval(
cumulator::AbstractVector{T}, op::F, ::EvalOptions{false}
)::ResultOk where {T,F}
@inbounds @simd for j in eachindex(cumulator)
x = op(cumulator[j])::T
cumulator[j] = x
end
return ResultOk(cumulator, true)
end
function deg0_eval(
tree::AbstractExpressionNode{T}, cX::AbstractMatrix{T}
)::ResultOk where {T}
if tree.constant
return ResultOk(fill_similar(tree.val, cX, axes(cX, 2)), true)
else
return ResultOk(cX[tree.feature, :], true)
end
end
@generated function dispatch_deg2_eval(
tree::AbstractExpressionNode{T},
cX::AbstractMatrix{T},
op_idx::Integer,
operators::OperatorEnum,
eval_options::EvalOptions,
) where {T}
nbin = get_nbin(operators)
long_compilation_time = nbin > OPERATOR_LIMIT_BEFORE_SLOWDOWN
if long_compilation_time
return quote
result_l = _eval_tree_array(tree.l, cX, operators, eval_options)
!result_l.ok && return result_l
@return_on_nonfinite_array(eval_options, result_l.x)
result_r = _eval_tree_array(tree.r, cX, operators, eval_options)
!result_r.ok && return result_r
@return_on_nonfinite_array(eval_options, result_r.x)
# op(x, y), for any x or y
deg2_eval(result_l.x, result_r.x, operators.binops[op_idx], eval_options)
end
end
return quote
return Base.Cartesian.@nif(
$nbin,
i -> i == op_idx,
i -> let op = operators.binops[i]
if tree.l.degree == 0 && tree.r.degree == 0
deg2_l0_r0_eval(tree, cX, op, eval_options)
elseif tree.r.degree == 0
result_l = _eval_tree_array(tree.l, cX, operators, eval_options)
!result_l.ok && return result_l
@return_on_nonfinite_array(eval_options, result_l.x)
# op(x, y), where y is a constant or variable but x is not.
deg2_r0_eval(tree, result_l.x, cX, op, eval_options)
elseif tree.l.degree == 0
result_r = _eval_tree_array(tree.r, cX, operators, eval_options)
!result_r.ok && return result_r
@return_on_nonfinite_array(eval_options, result_r.x)
# op(x, y), where x is a constant or variable but y is not.
deg2_l0_eval(tree, result_r.x, cX, op, eval_options)
else
result_l = _eval_tree_array(tree.l, cX, operators, eval_options)
!result_l.ok && return result_l
@return_on_nonfinite_array(eval_options, result_l.x)
result_r = _eval_tree_array(tree.r, cX, operators, eval_options)
!result_r.ok && return result_r
@return_on_nonfinite_array(eval_options, result_r.x)
# op(x, y), for any x or y
deg2_eval(result_l.x, result_r.x, op, eval_options)
end
end
)
end
end
@generated function dispatch_deg1_eval(
tree::AbstractExpressionNode{T},
cX::AbstractMatrix{T},
op_idx::Integer,
operators::OperatorEnum,
eval_options::EvalOptions,
) where {T}
nuna = get_nuna(operators)
long_compilation_time = nuna > OPERATOR_LIMIT_BEFORE_SLOWDOWN
if long_compilation_time
return quote
result = _eval_tree_array(tree.l, cX, operators, eval_options)
!result.ok && return result
@return_on_nonfinite_array(eval_options, result.x)
deg1_eval(result.x, operators.unaops[op_idx], eval_options)
end
end
# This @nif lets us generate an if statement over choice of operator,
# which means the compiler will be able to completely avoid type inference on operators.
return quote
Base.Cartesian.@nif(
$nuna,
i -> i == op_idx,
i -> let op = operators.unaops[i]
if tree.l.degree == 2 && tree.l.l.degree == 0 && tree.l.r.degree == 0
# op(op2(x, y)), where x, y, z are constants or variables.
l_op_idx = tree.l.op
dispatch_deg1_l2_ll0_lr0_eval(
tree, cX, op, l_op_idx, operators.binops, eval_options
)
elseif tree.l.degree == 1 && tree.l.l.degree == 0
# op(op2(x)), where x is a constant or variable.
l_op_idx = tree.l.op
dispatch_deg1_l1_ll0_eval(
tree, cX, op, l_op_idx, operators.unaops, eval_options
)
else
# op(x), for any x.
result = _eval_tree_array(tree.l, cX, operators, eval_options)
!result.ok && return result
@return_on_nonfinite_array(eval_options, result.x)
deg1_eval(result.x, op, eval_options)
end
end
)
end
end
@generated function dispatch_deg1_l2_ll0_lr0_eval(
tree::AbstractExpressionNode{T},
cX::AbstractMatrix{T},
op::F,
l_op_idx::Integer,
binops,
eval_options::EvalOptions,
) where {T,F}
nbin = counttuple(binops)
# (Note this is only called from dispatch_deg1_eval, which has already
# checked for long compilation times, so we don't need to check here)
quote
Base.Cartesian.@nif(
$nbin,
j -> j == l_op_idx,
j -> let op_l = binops[j]
deg1_l2_ll0_lr0_eval(tree, cX, op, op_l, eval_options)
end,
)
end
end
@generated function dispatch_deg1_l1_ll0_eval(
tree::AbstractExpressionNode{T},
cX::AbstractMatrix{T},
op::F,
l_op_idx::Integer,
unaops,
eval_options::EvalOptions,
)::ResultOk where {T,F}
nuna = counttuple(unaops)
quote
Base.Cartesian.@nif(
$nuna,
j -> j == l_op_idx,
j -> let op_l = unaops[j]
deg1_l1_ll0_eval(tree, cX, op, op_l, eval_options)
end,
)
end
end
function deg1_l2_ll0_lr0_eval(
tree::AbstractExpressionNode{T},
cX::AbstractMatrix{T},
op::F,
op_l::F2,
eval_options::EvalOptions{false,false},
) where {T,F,F2}
if tree.l.l.constant && tree.l.r.constant
val_ll = tree.l.l.val
val_lr = tree.l.r.val
@return_on_nonfinite_val(eval_options, val_ll, cX)
@return_on_nonfinite_val(eval_options, val_lr, cX)
x_l = op_l(val_ll, val_lr)::T
@return_on_nonfinite_val(eval_options, x_l, cX)
x = op(x_l)::T
@return_on_nonfinite_val(eval_options, x, cX)
return ResultOk(fill_similar(x, cX, axes(cX, 2)), true)
elseif tree.l.l.constant
val_ll = tree.l.l.val
@return_on_nonfinite_val(eval_options, val_ll, cX)
feature_lr = tree.l.r.feature
cumulator = similar(cX, axes(cX, 2))
@inbounds @simd for j in axes(cX, 2)
x_l = op_l(val_ll, cX[feature_lr, j])::T
x = is_valid(x_l) ? op(x_l)::T : T(Inf)
cumulator[j] = x
end
return ResultOk(cumulator, true)
elseif tree.l.r.constant
feature_ll = tree.l.l.feature
val_lr = tree.l.r.val
@return_on_nonfinite_val(eval_options, val_lr, cX)
cumulator = similar(cX, axes(cX, 2))
@inbounds @simd for j in axes(cX, 2)
x_l = op_l(cX[feature_ll, j], val_lr)::T
x = is_valid(x_l) ? op(x_l)::T : T(Inf)
cumulator[j] = x
end
return ResultOk(cumulator, true)
else
feature_ll = tree.l.l.feature
feature_lr = tree.l.r.feature
cumulator = similar(cX, axes(cX, 2))
@inbounds @simd for j in axes(cX, 2)
x_l = op_l(cX[feature_ll, j], cX[feature_lr, j])::T
x = is_valid(x_l) ? op(x_l)::T : T(Inf)
cumulator[j] = x
end
return ResultOk(cumulator, true)
end
end
# op(op2(x)) for x variable or constant
function deg1_l1_ll0_eval(
tree::AbstractExpressionNode{T},
cX::AbstractMatrix{T},
op::F,
op_l::F2,
eval_options::EvalOptions{false,false},
) where {T,F,F2}
if tree.l.l.constant
val_ll = tree.l.l.val
@return_on_nonfinite_val(eval_options, val_ll, cX)
x_l = op_l(val_ll)::T
@return_on_nonfinite_val(eval_options, x_l, cX)
x = op(x_l)::T
@return_on_nonfinite_val(eval_options, x, cX)
return ResultOk(fill_similar(x, cX, axes(cX, 2)), true)
else
feature_ll = tree.l.l.feature
cumulator = similar(cX, axes(cX, 2))
@inbounds @simd for j in axes(cX, 2)
x_l = op_l(cX[feature_ll, j])::T
x = is_valid(x_l) ? op(x_l)::T : T(Inf)
cumulator[j] = x
end
return ResultOk(cumulator, true)
end
end
# op(x, y) for x and y variable/constant
function deg2_l0_r0_eval(
tree::AbstractExpressionNode{T},
cX::AbstractMatrix{T},
op::F,
eval_options::EvalOptions{false,false},
) where {T,F}
if tree.l.constant && tree.r.constant
val_l = tree.l.val
@return_on_nonfinite_val(eval_options, val_l, cX)
val_r = tree.r.val
@return_on_nonfinite_val(eval_options, val_r, cX)
x = op(val_l, val_r)::T
@return_on_nonfinite_val(eval_options, x, cX)
return ResultOk(fill_similar(x, cX, axes(cX, 2)), true)
elseif tree.l.constant
cumulator = similar(cX, axes(cX, 2))
val_l = tree.l.val
@return_on_nonfinite_val(eval_options, val_l, cX)
feature_r = tree.r.feature
@inbounds @simd for j in axes(cX, 2)
x = op(val_l, cX[feature_r, j])::T
cumulator[j] = x
end
return ResultOk(cumulator, true)
elseif tree.r.constant
cumulator = similar(cX, axes(cX, 2))
feature_l = tree.l.feature
val_r = tree.r.val
@return_on_nonfinite_val(eval_options, val_r, cX)
@inbounds @simd for j in axes(cX, 2)
x = op(cX[feature_l, j], val_r)::T
cumulator[j] = x
end
return ResultOk(cumulator, true)
else
cumulator = similar(cX, axes(cX, 2))
feature_l = tree.l.feature
feature_r = tree.r.feature
@inbounds @simd for j in axes(cX, 2)
x = op(cX[feature_l, j], cX[feature_r, j])::T
cumulator[j] = x
end
return ResultOk(cumulator, true)
end
end
# op(x, y) for x variable/constant, y arbitrary
function deg2_l0_eval(
tree::AbstractExpressionNode{T},
cumulator::AbstractVector{T},
cX::AbstractArray{T},
op::F,
eval_options::EvalOptions{false,false},
) where {T,F}
if tree.l.constant
val = tree.l.val
@return_on_nonfinite_val(eval_options, val, cX)
@inbounds @simd for j in eachindex(cumulator)
x = op(val, cumulator[j])::T
cumulator[j] = x
end
return ResultOk(cumulator, true)
else
feature = tree.l.feature
@inbounds @simd for j in eachindex(cumulator)
x = op(cX[feature, j], cumulator[j])::T
cumulator[j] = x
end
return ResultOk(cumulator, true)
end
end
# op(x, y) for x arbitrary, y variable/constant
function deg2_r0_eval(
tree::AbstractExpressionNode{T},
cumulator::AbstractVector{T},
cX::AbstractArray{T},
op::F,
eval_options::EvalOptions{false,false},
) where {T,F}
if tree.r.constant
val = tree.r.val
@return_on_nonfinite_val(eval_options, val, cX)
@inbounds @simd for j in eachindex(cumulator)
x = op(cumulator[j], val)::T
cumulator[j] = x
end
return ResultOk(cumulator, true)
else
feature = tree.r.feature
@inbounds @simd for j in eachindex(cumulator)
x = op(cumulator[j], cX[feature, j])::T
cumulator[j] = x
end
return ResultOk(cumulator, true)
end
end
"""
dispatch_constant_tree(tree::AbstractExpressionNode{T}, operators::OperatorEnum) where {T}
Evaluate a tree which is assumed to not contain any variable nodes. This
gives better performance, as we do not need to perform computation
over an entire array when the values are all the same.
"""
@generated function dispatch_constant_tree(
tree::AbstractExpressionNode{T}, operators::OperatorEnum
) where {T}
nuna = get_nuna(operators)
nbin = get_nbin(operators)
deg1_branch = if nuna > OPERATOR_LIMIT_BEFORE_SLOWDOWN
quote
deg1_eval_constant(tree, operators.unaops[op_idx], operators)::ResultOk{Vector{T}}
end
else
quote
Base.Cartesian.@nif(
$nuna,
i -> i == op_idx,
i -> deg1_eval_constant(
tree, operators.unaops[i], operators
)::ResultOk{Vector{T}}
)
end
end
deg2_branch = if nbin > OPERATOR_LIMIT_BEFORE_SLOWDOWN
quote
deg2_eval_constant(tree, operators.binops[op_idx], operators)::ResultOk{Vector{T}}
end
else
quote
Base.Cartesian.@nif(
$nbin,
i -> i == op_idx,
i -> deg2_eval_constant(
tree, operators.binops[i], operators
)::ResultOk{Vector{T}}
)
end
end
return quote
if tree.degree == 0
return deg0_eval_constant(tree)::ResultOk{Vector{T}}
elseif tree.degree == 1
op_idx = tree.op
return $deg1_branch
else
op_idx = tree.op
return $deg2_branch
end
end
end
@inline function deg0_eval_constant(tree::AbstractExpressionNode{T}) where {T}
output = tree.val
return ResultOk([output], true)::ResultOk{Vector{T}}
end
function deg1_eval_constant(
tree::AbstractExpressionNode{T}, op::F, operators::OperatorEnum
) where {T,F}
result = dispatch_constant_tree(tree.l, operators)
!result.ok && return result
output = op(result.x[])::T
return ResultOk([output], is_valid(output))::ResultOk{Vector{T}}
end
function deg2_eval_constant(
tree::AbstractExpressionNode{T}, op::F, operators::OperatorEnum
) where {T,F}
cumulator = dispatch_constant_tree(tree.l, operators)
!cumulator.ok && return cumulator
result_r = dispatch_constant_tree(tree.r, operators)
!result_r.ok && return result_r
output = op(cumulator.x[], result_r.x[])::T
return ResultOk([output], is_valid(output))::ResultOk{Vector{T}}
end
"""
differentiable_eval_tree_array(tree::AbstractExpressionNode, cX::AbstractMatrix, operators::OperatorEnum)
Evaluate an expression tree in a way that can be auto-differentiated.
"""
function differentiable_eval_tree_array(
tree::AbstractExpressionNode{T1}, cX::AbstractMatrix{T}, operators::OperatorEnum
) where {T<:Number,T1}
result = _differentiable_eval_tree_array(tree, cX, operators)
return (result.x, result.ok)
end
@generated function _differentiable_eval_tree_array(
tree::AbstractExpressionNode{T1}, cX::AbstractMatrix{T}, operators::OperatorEnum
)::ResultOk where {T<:Number,T1}
nuna = get_nuna(operators)
nbin = get_nbin(operators)
quote
if tree.degree == 0
if tree.constant
ResultOk(fill_similar(one(T), cX, axes(cX, 2)) .* tree.val, true)
else
ResultOk(cX[tree.feature, :], true)
end
elseif tree.degree == 1
op_idx = tree.op
Base.Cartesian.@nif(
$nuna,
i -> i == op_idx,
i -> deg1_diff_eval(tree, cX, operators.unaops[i], operators)
)
else
op_idx = tree.op
Base.Cartesian.@nif(
$nbin,
i -> i == op_idx,
i -> deg2_diff_eval(tree, cX, operators.binops[i], operators)
)
end
end
end
function deg1_diff_eval(
tree::AbstractExpressionNode{T1}, cX::AbstractMatrix{T}, op::F, operators::OperatorEnum
)::ResultOk where {T<:Number,F,T1}
left = _differentiable_eval_tree_array(tree.l, cX, operators)
!left.ok && return left
out = op.(left.x)
return ResultOk(out, all(isfinite, out))
end
function deg2_diff_eval(
tree::AbstractExpressionNode{T1}, cX::AbstractMatrix{T}, op::F, operators::OperatorEnum
)::ResultOk where {T<:Number,F,T1}
left = _differentiable_eval_tree_array(tree.l, cX, operators)
!left.ok && return left
right = _differentiable_eval_tree_array(tree.r, cX, operators)
!right.ok && return right
out = op.(left.x, right.x)
return ResultOk(out, all(isfinite, out))
end
"""
eval_tree_array(tree::AbstractExpressionNode, cX::AbstractMatrix, operators::GenericOperatorEnum; throw_errors::Bool=true)
Evaluate a generic binary tree (equation) over a given input data,
whatever that input data may be. The `operators` enum contains all
of the operators used. Unlike `eval_tree_array` with the normal
`OperatorEnum`, the array `cX` is sliced only along the first dimension.
i.e., if `cX` is a vector, then the output of a feature node
will be a scalar. If `cX` is a 3D tensor, then the output
of a feature node will be a 2D tensor.
Note also that `tree.feature` will index along the first axis of `cX`.
However, there is no requirement about input and output types in general.
You may set up your tree such that some operator nodes work on tensors, while
other operator nodes work on scalars. `eval_tree_array` will simply
return `nothing` if a given operator is not defined for the given input type.
This function can be represented by the following pseudocode:
```
function eval(current_node)
if current_node is leaf
return current_node.value
elif current_node is degree 1
return current_node.operator(eval(current_node.left_child))
else
return current_node.operator(eval(current_node.left_child), eval(current_node.right_child))
```
# Arguments
- `tree::AbstractExpressionNode`: The root node of the tree to evaluate.
- `cX::AbstractArray`: The input data to evaluate the tree on.
- `operators::GenericOperatorEnum`: The operators used in the tree.
- `throw_errors::Bool=true`: Whether to throw errors
if they occur during evaluation. Otherwise,
MethodErrors will be caught before they happen and
evaluation will return `nothing`,
rather than throwing an error. This is useful in cases
where you are unsure if a particular tree is valid or not,
and would prefer to work with `nothing` as an output.
# Returns
- `(output, complete)::Tuple{Any, Bool}`: the result,
as well as if the evaluation completed successfully (true/false).
If evaluation failed, `nothing` will be returned for the first argument.
A `false` complete means an operator was called on input types
that it was not defined for.
"""
@unstable function eval_tree_array(
tree::AbstractExpressionNode{T1},
cX::AbstractArray{T2,N},
operators::GenericOperatorEnum;
throw_errors::Union{Val,Bool}=Val(true),
) where {T1,T2,N}
v_throw_errors = _to_bool_val(throw_errors)
try
return _eval_tree_array_generic(tree, cX, operators, v_throw_errors)
catch e
if v_throw_errors isa Val{false}
return nothing, false
end
tree_s = string_tree(tree, operators)
error_msg = "Failed to evaluate tree $(tree_s)."
if isa(e, MethodError)
error_msg *= (
" Note that you can efficiently skip MethodErrors" *
" beforehand by passing `throw_errors=false` to " *
" `eval_tree_array`."
)
end
throw(ErrorException(error_msg))
end
end
@unstable function _eval_tree_array_generic(
tree::AbstractExpressionNode{T1},
cX::AbstractArray{T2,N},
operators::GenericOperatorEnum,
::Val{throw_errors},
) where {T1,T2,N,throw_errors}
if tree.degree == 0
if tree.constant
if N == 1
return (tree.val::T1), true
else
return fill(tree.val::T1, size(cX)[2:N]), true
end
else
if N == 1
return (cX[tree.feature]), true
else
return selectdim(cX, 1, tree.feature), true
end
end
elseif tree.degree == 1
return deg1_eval_generic(
tree, cX, operators.unaops[tree.op], operators, Val(throw_errors)
)
else
return deg2_eval_generic(
tree, cX, operators.binops[tree.op], operators, Val(throw_errors)
)
end
end
@unstable function deg1_eval_generic(
tree::AbstractExpressionNode{T1},
cX::AbstractArray{T2,N},
op::F,
operators::GenericOperatorEnum,
::Val{throw_errors},
) where {F,T1,T2,N,throw_errors}
left, complete = _eval_tree_array_generic(tree.l, cX, operators, Val(throw_errors))
!throw_errors && !complete && return nothing, false
!throw_errors &&
!hasmethod(op, N == 1 ? Tuple{typeof(left)} : Tuple{eltype(left)}) &&
return nothing, false
if N == 1
return op(left), true
else
return op.(left), true
end
end
@unstable function deg2_eval_generic(
tree::AbstractExpressionNode{T1},
cX::AbstractArray{T2,N},
op::F,
operators::GenericOperatorEnum,
::Val{throw_errors},
) where {F,T1,T2,N,throw_errors}
left, complete = _eval_tree_array_generic(tree.l, cX, operators, Val(throw_errors))
!throw_errors && !complete && return nothing, false
right, complete = _eval_tree_array_generic(tree.r, cX, operators, Val(throw_errors))
!throw_errors && !complete && return nothing, false
!throw_errors &&
!hasmethod(
op,
N == 1 ? Tuple{typeof(left),typeof(right)} : Tuple{eltype(left),eltype(right)},
) &&
return nothing, false
if N == 1
return op(left, right), true
else
return op.(left, right), true
end
end
# Parametric arguments don't use dynamic dispatch, calls with turbo/bumper won't resolve properly
# overwritten in ext/DynamicExpressionsLoopVectorizationExt.jl
function _eval_graph_array(
root::GraphNode{T},
cX::AbstractMatrix{T},
operators::OperatorEnum,
loopVectorization::Val{true}
) where {T}
error("_is_loopvectorization_loaded(0) is true but _eval_graph_array has not been overwritten")
end
function _eval_graph_array(
root::GraphNode{T},
cX::AbstractMatrix{T},
operators::OperatorEnum,
loopVectorization::Val{false}
) where {T}
order = topological_sort(root)
for node in order
if node.degree == 0 && !node.constant
node.cache = view(cX, node.feature, :)
elseif node.degree == 1
if node.l.constant
node.constant = true
node.val = operators.unaops[node.op](node.l.val)
if !is_valid(node.val) return ResultOk(Vector{T}(undef, size(cX, 2)), false) end
else
node.constant = false
node.cache = map(operators.unaops[node.op], node.l.cache)
if !is_valid_array(node.cache) return ResultOk(node.cache, false) end
end
elseif node.degree == 2
if node.l.constant
if node.r.constant
node.constant = true
node.val = operators.binops[node.op](node.l.val, node.r.val)
if !is_valid(node.val) return ResultOk(Vector{T}(undef, size(cX, 2)), false) end
else
node.constant = false
node.cache = map(Base.Fix1(operators.binops[node.op], node.l.val), node.r.cache)
if !is_valid_array(node.cache) return ResultOk(node.cache, false) end
end
else
if node.r.constant
node.constant = false
node.cache = map(Base.Fix2(operators.binops[node.op], node.r.val), node.l.cache)
if !is_valid_array(node.cache) return ResultOk(node.cache, false) end
else
node.constant = false
node.cache = map(operators.binops[node.op], node.l.cache, node.r.cache)
if !is_valid_array(node.cache) return ResultOk(node.cache, false) end
end
end
end
end
if root.constant
return ResultOk(fill(root.val, size(cX, 2)), true)
else
return ResultOk(root.cache, true)
end
end
function eval_tree_array(
root::GraphNode{T},
cX::AbstractMatrix{T},
operators::OperatorEnum,
) where {T}
return _eval_graph_array(root, cX, operators, Val(_is_loopvectorization_loaded(0)))
end
function eval_graph_array_diff(
root::GraphNode{T},
cX::AbstractMatrix{T},
operators::OperatorEnum,
) where {T}
# vmap is faster with small cX sizes
# vmapnt (non-temporal) is faster with larger cX sizes (too big so not worth caching?)
dp = Dict{GraphNode, AbstractArray{T}}()
order = topological_sort(root)
for node in order
if node.degree == 0 && !node.constant
dp[node] = view(cX, node.feature, :)
elseif node.degree == 1
if node.l.constant
node.constant = true
node.val = operators.unaops[node.op](node.l.val)
if !is_valid(node.val) return false end
else
node.constant = false
dp[node] = map(operators.unaops[node.op], dp[node.l])
if !is_valid_array(dp[node]) return false end
end
elseif node.degree == 2
if node.l.constant
if node.r.constant
node.constant = true
node.val = operators.binops[node.op](node.l.val, node.r.val)
if !is_valid(node.val) return false end
else
node.constant = false
dp[node] = map(Base.Fix1(operators.binops[node.op], node.l.val), dp[node.r])
if !is_valid_array(dp[node]) return false end
end
else
if node.r.constant
node.constant = false
dp[node] = map(Base.Fix2(operators.binops[node.op], node.r.val), dp[node.l])
if !is_valid_array(dp[node]) return false end
else
node.constant = false
dp[node] = map(operators.binops[node.op], dp[node.l], dp[node.r])
if !is_valid_array(dp[node]) return false end
end
end
end
end
if root.constant
return fill(root.val, size(cX, 2))
else
return dp[root]
end
end
function eval_graph_single(
root::GraphNode{T},
cX::AbstractArray{T},
operators::OperatorEnum
) where {T}
order = topological_sort(root)
for node in order
if node.degree == 0 && !node.constant
node.val = cX[node.feature]
elseif node.degree == 1
node.val = operators.unaops[node.op](node.l.val)
if !is_valid(node.val) return false end
elseif node.degree == 2
node.val = operators.binops[node.op](node.l.val, node.r.val)
if !is_valid(node.val) return false end
end
end
return root.val
end