carray 3.0.6 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.yardopts +1 -1
- data/CHANGELOG.md +7 -1830
- data/README.md +62 -35
- data/carray.gemspec +16 -4
- data/docs/changelogs/CHANGELOG-3.0.md +2464 -0
- data/ext/ca_array_pool.c +4 -5
- data/ext/ca_axis_descriptor.h +45 -30
- data/ext/ca_axis_dispatch.c +7 -4
- data/ext/ca_axis_group.c +12 -15
- data/ext/ca_bincmp_dispatch.h +16 -38
- data/ext/ca_binop_dispatch.c +35 -0
- data/ext/ca_binop_dispatch.h +22 -46
- data/ext/ca_categorical_iterator.c +36 -34
- data/ext/ca_compare.c +0 -1
- data/ext/ca_compare.h +8 -1
- data/ext/ca_composite_dispatch.h +6 -0
- data/ext/ca_for_buffer.h +6 -1
- data/ext/ca_group_iter.c +17 -18
- data/ext/ca_iter_state_fields.h +196 -0
- data/ext/ca_iter_substrate.h +84 -103
- data/ext/ca_kernel_iterator.c +125 -89
- data/ext/ca_kernel_iterator.h +229 -1504
- data/ext/ca_kernel_iterator_internal.h +1167 -0
- data/ext/ca_moncmp_dispatch.h +17 -24
- data/ext/ca_monop_dispatch.h +25 -74
- data/ext/ca_obj_array.c +92 -165
- data/ext/ca_obj_bincmp.c +65 -48
- data/ext/ca_obj_binop.c +74 -49
- data/ext/ca_obj_bitarray.c +7 -21
- data/ext/ca_obj_bitfield.c +93 -26
- data/ext/ca_obj_block.c +11 -12
- data/ext/ca_obj_byte_swap.c +34 -34
- data/ext/ca_obj_const_string.c +464 -304
- data/ext/ca_obj_face.c +167 -121
- data/ext/ca_obj_face.h +32 -170
- data/ext/ca_obj_fake.c +127 -34
- data/ext/ca_obj_farray.c +13 -9
- data/ext/ca_obj_field.c +17 -13
- data/ext/ca_obj_fixlen_string.c +57 -34
- data/ext/ca_obj_grid.c +149 -113
- data/ext/ca_obj_meld.c +28 -26
- data/ext/ca_obj_moncmp.c +10 -21
- data/ext/ca_obj_monop.c +88 -73
- data/ext/ca_obj_object.c +60 -46
- data/ext/ca_obj_record.c +74 -22
- data/ext/ca_obj_reduce.c +10 -14
- data/ext/ca_obj_refer.c +146 -39
- data/ext/ca_obj_remap.c +11 -29
- data/ext/ca_obj_repeat.c +41 -23
- data/ext/ca_obj_roll.c +20 -28
- data/ext/ca_obj_select.c +17 -27
- data/ext/ca_obj_select_axis.c +35 -42
- data/ext/ca_obj_shift.c +22 -42
- data/ext/ca_obj_source.c +1 -5
- data/ext/ca_obj_stack.c +33 -29
- data/ext/ca_obj_stride.c +99 -62
- data/ext/ca_obj_string.c +8 -20
- data/ext/ca_obj_tile.c +14 -16
- data/ext/ca_obj_time.c +12 -23
- data/ext/ca_obj_timedelta.c +12 -23
- data/ext/ca_obj_transpose.c +8 -10
- data/ext/ca_obj_triop.c +48 -49
- data/ext/ca_obj_window.c +87 -99
- data/ext/ca_op_cmplx64.h +4 -0
- data/ext/ca_op_ipower.c +97 -27
- data/ext/ca_op_powi.h +9 -28
- data/ext/ca_pow5_table.h +2 -1
- data/ext/ca_rng_normal.h +4 -0
- data/ext/ca_rng_xoshiro256pp.h +3 -0
- data/ext/ca_sort_kernels.h +23 -26
- data/ext/ca_sweep_engine.c +92 -26
- data/ext/ca_sweep_engine.h +22 -15
- data/ext/ca_transform_common.c +3 -8
- data/ext/ca_triop_dispatch.h +20 -32
- data/ext/caframe_csv_reader.c +12 -12
- data/ext/carray.h +300 -1009
- data/ext/carray_access.c +320 -207
- data/ext/carray_address_basis.c +128 -59
- data/ext/carray_attribute.c +81 -104
- data/ext/carray_bincount.c +12 -14
- data/ext/carray_broadcast.c +31 -27
- data/ext/carray_call_cfunc.c +174 -285
- data/ext/carray_call_cfunc.h +36 -28
- data/ext/carray_cast.c +1191 -351
- data/ext/carray_cast_func.rb +68 -8
- data/ext/carray_class.c +6 -11
- data/ext/carray_conversion.c +98 -39
- data/ext/carray_copy.c +52 -26
- data/ext/carray_core.c +286 -132
- data/ext/carray_count.c +53 -22
- data/ext/carray_element.c +49 -28
- data/ext/carray_factorize.c +64 -63
- data/ext/carray_generate.c +26 -19
- data/ext/carray_histogram.c +9 -11
- data/ext/carray_hold.c +7 -9
- data/ext/carray_index_classifier.c +127 -230
- data/ext/carray_index_classifier.h +11 -10
- data/ext/carray_integer_total.c +523 -0
- data/ext/carray_internal.h +1364 -156
- data/ext/carray_key_windows.c +3 -3
- data/ext/carray_lazy.c +37 -37
- data/ext/carray_loop.c +27 -23
- data/ext/carray_mask.c +235 -150
- data/ext/carray_math_kernel.h +23 -47
- data/ext/carray_mathfunc.c +10 -3
- data/ext/carray_median_percentile.c +106 -100
- data/ext/carray_memory_view.c +83 -69
- data/ext/carray_operator.c +490 -128
- data/ext/carray_order.c +163 -84
- data/ext/carray_partition.c +14 -16
- data/ext/carray_random.c +48 -42
- data/ext/carray_round.c +33 -5
- data/ext/carray_scatter.c +57 -39
- data/ext/carray_segment.c +42 -46
- data/ext/carray_slab.c +77 -51
- data/ext/carray_slab.h +44 -33
- data/ext/carray_sort.c +37 -31
- data/ext/carray_sort_kernel.c +36 -10
- data/ext/carray_struct.c +44 -34
- data/ext/carray_test.c +131 -81
- data/ext/carray_time_text.c +30 -31
- data/ext/carray_undef.c +50 -7
- data/ext/carray_utils.c +373 -139
- data/ext/extconf.rb +24 -17
- data/ext/mk_call_cfunc.rb +25 -31
- data/ext/mk_pow5_table.rb +2 -1
- data/ext/mkkernel.rb +819 -488
- data/ext/ruby_carray.c +47 -42
- data/ext/version.h +7 -5
- data/lib/carray/attribute.rb +19 -18
- data/lib/carray/autoload_carray.rb +20 -15
- data/lib/carray/autoload_method_extension.rb +64 -57
- data/lib/carray/axis_group.rb +272 -185
- data/lib/carray/basics.rb +298 -56
- data/lib/carray/bincount_nd.rb +41 -18
- data/lib/carray/block_iterator.rb +167 -119
- data/lib/carray/boolean_reduce.rb +7 -4
- data/lib/carray/categorical.rb +84 -59
- data/lib/carray/categorical_iterator.rb +90 -67
- data/lib/carray/complex.rb +61 -41
- data/lib/carray/conditional.rb +98 -23
- data/lib/carray/const_string.rb +112 -46
- data/lib/carray/core_extensions.rb +20 -69
- data/lib/carray/distance_limit.rb +7 -5
- data/lib/carray/factories.rb +269 -0
- data/lib/carray/fixlen_string.rb +95 -12
- data/lib/carray/frame/column_verbs.rb +76 -9
- data/lib/carray/frame/concat.rb +51 -7
- data/lib/carray/frame/convert.rb +2 -1
- data/lib/carray/frame/csv_parser.rb +20 -5
- data/lib/carray/frame/frame.rb +73 -31
- data/lib/carray/frame/group.rb +247 -187
- data/lib/carray/frame/io.rb +36 -12
- data/lib/carray/frame/join.rb +56 -17
- data/lib/carray/frame/records.rb +7 -5
- data/lib/carray/frame/reshape.rb +27 -7
- data/lib/carray/frame/sort.rb +10 -8
- data/lib/carray/frame/verbs.rb +217 -134
- data/lib/carray/frame/windows.rb +254 -19
- data/lib/carray/frame.rb +1 -2
- data/lib/carray/fuse_source.rb +28 -23
- data/lib/carray/fusion.rb +30 -30
- data/lib/carray/histogram.rb +35 -16
- data/lib/carray/inspect.rb +7 -7
- data/lib/carray/iterator.rb +104 -23
- data/lib/carray/key_windows.rb +93 -61
- data/lib/carray/lazy.rb +208 -111
- data/lib/carray/limits.rb +80 -0
- data/lib/carray/mask_gap_fill.rb +21 -16
- data/lib/carray/math.rb +87 -50
- data/lib/carray/meld_reduce.rb +30 -8
- data/lib/carray/methods/align_addr.rb +29 -17
- data/lib/carray/methods/bin.rb +8 -1
- data/lib/carray/methods/bincount.rb +4 -2
- data/lib/carray/methods/bit_string.rb +19 -31
- data/lib/carray/methods/broadcast.rb +8 -3
- data/lib/carray/methods/choose.rb +5 -5
- data/lib/carray/methods/composition.rb +73 -72
- data/lib/carray/methods/{index.rb → coordinate.rb} +13 -13
- data/lib/carray/methods/discovery_along.rb +3 -3
- data/lib/carray/methods/factorize.rb +2 -0
- data/lib/carray/methods/gather_nd.rb +106 -103
- data/lib/carray/methods/insert_block.rb +2 -2
- data/lib/carray/methods/is_between.rb +6 -4
- data/lib/carray/methods/is_in.rb +183 -143
- data/lib/carray/methods/join.rb +2 -1
- data/lib/carray/methods/lag.rb +6 -2
- data/lib/carray/methods/locate_addr.rb +157 -94
- data/lib/carray/methods/mask_duplicates.rb +1 -1
- data/lib/carray/methods/meshgrid.rb +28 -16
- data/lib/carray/methods/mode.rb +67 -67
- data/lib/carray/methods/nunique.rb +9 -7
- data/lib/carray/methods/repeat.rb +23 -13
- data/lib/carray/methods/resize.rb +1 -1
- data/lib/carray/methods/snap.rb +24 -20
- data/lib/carray/methods/string_format.rb +2 -2
- data/lib/carray/methods/unique.rb +4 -2
- data/lib/carray/methods/value_counts.rb +1 -1
- data/lib/carray/mkmf.rb +25 -28
- data/lib/carray/percentile_arguments.rb +82 -0
- data/lib/carray/record_order.rb +50 -20
- data/lib/carray/rng.rb +1 -0
- data/lib/carray/runtime.rb +195 -17
- data/lib/carray/segment_iterator.rb +262 -137
- data/lib/carray/serialize.rb +635 -566
- data/lib/carray/slab_iterator.rb +114 -114
- data/lib/carray/stack.rb +14 -15
- data/lib/carray/string.rb +16 -22
- data/lib/carray/string_operation_extension.rb +97 -52
- data/lib/carray/struct.rb +122 -164
- data/lib/carray/struct_builder.rb +247 -73
- data/lib/carray/time.rb +663 -365
- data/lib/carray/window_iterator.rb +232 -155
- data/lib/carray.rb +6 -11
- data/yard-stubs/ca_obj_array.rb +20 -135
- data/yard-stubs/ca_obj_bitarray.rb +1 -8
- data/yard-stubs/ca_obj_bitfield.rb +6 -2
- data/yard-stubs/ca_obj_byte_swap.rb +21 -7
- data/yard-stubs/ca_obj_fake.rb +3 -1
- data/yard-stubs/ca_obj_farray.rb +1 -1
- data/yard-stubs/ca_obj_field.rb +8 -6
- data/yard-stubs/ca_obj_refer.rb +10 -5
- data/yard-stubs/ca_obj_roll.rb +7 -6
- data/yard-stubs/ca_obj_shift.rb +2 -3
- data/yard-stubs/ca_obj_stride.rb +5 -7
- data/yard-stubs/ca_obj_tile.rb +1 -1
- data/yard-stubs/ca_obj_time.rb +43 -0
- data/yard-stubs/ca_obj_transpose.rb +1 -1
- data/yard-stubs/ca_obj_window.rb +28 -16
- data/yard-stubs/carray_access.rb +55 -6
- data/yard-stubs/carray_attribute.rb +26 -38
- data/yard-stubs/carray_cast.rb +121 -162
- data/yard-stubs/carray_class.rb +3 -4
- data/yard-stubs/carray_conversion.rb +6 -7
- data/yard-stubs/carray_copy.rb +2 -1
- data/yard-stubs/carray_count.rb +10 -5
- data/yard-stubs/carray_element.rb +4 -3
- data/yard-stubs/carray_limits.rb +100 -0
- data/yard-stubs/carray_loop.rb +0 -20
- data/yard-stubs/carray_mask.rb +59 -41
- data/yard-stubs/carray_math.rb +162 -100
- data/yard-stubs/carray_mathfunc.rb +415 -3
- data/yard-stubs/carray_median_percentile.rb +29 -11
- data/yard-stubs/carray_memory_view.rb +2 -2
- data/yard-stubs/carray_order.rb +72 -33
- data/yard-stubs/carray_random.rb +6 -6
- data/yard-stubs/carray_reduce.rb +353 -0
- data/yard-stubs/carray_rng.rb +92 -0
- data/yard-stubs/carray_scatter.rb +12 -3
- data/yard-stubs/carray_slab.rb +7 -4
- data/yard-stubs/carray_sort.rb +7 -6
- data/yard-stubs/carray_test.rb +18 -5
- data/yard-stubs/carray_undef.rb +44 -5
- data/yard-stubs/ruby_carray.rb +75 -40
- metadata +63 -25
- data/CHANGELOG.v1.md +0 -126
- data/ext/carray_build_flags.h +0 -3
- data/ext/carray_config.h +0 -28
- data/ext/carray_data_type.c +0 -90
- data/ext/carray_kernels_bincmp.c +0 -6457
- data/ext/carray_kernels_binop.c +0 -31534
- data/ext/carray_kernels_init.c +0 -1734
- data/ext/carray_kernels_moncmp.c +0 -2104
- data/ext/carray_kernels_monop.c +0 -25387
- data/ext/carray_kernels_reduce_aggregate.c +0 -27545
- data/ext/carray_kernels_reduce_boolean.c +0 -1924
- data/ext/carray_kernels_reduce_cumulative.c +0 -11646
- data/ext/carray_kernels_reduce_extreme.c +0 -21631
- data/ext/carray_kernels_reduce_variance.c +0 -5981
- data/ext/carray_kernels_scan.c +0 -4302
- data/ext/carray_kernels_search.c +0 -37776
- data/ext/carray_kernels_sort.c +0 -10814
- data/ext/carray_kernels_triop.c +0 -1864
- data/lib/carray/construct.rb +0 -360
- data/lib/carray/data_type_extension.rb +0 -261
- data/lib/carray/data_type_limits.rb +0 -91
data/ext/mkkernel.rb
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
#
|
|
3
3
|
# mkkernel.rb -- code generator for kernel_iterator-based reduction kernels
|
|
4
4
|
#
|
|
5
|
-
# Sibling generator to mkmath.rb, but targeting the
|
|
5
|
+
# Sibling generator to mkmath.rb, but targeting the kernel_iterator
|
|
6
6
|
# surface instead of the legacy eager-materialise operators. Clean slate:
|
|
7
7
|
# no dependency on carray_config.h, no complex/long-double remnants, no
|
|
8
8
|
# per-cell fetch/store template.
|
|
@@ -41,7 +41,7 @@ module MkKernel
|
|
|
41
41
|
# full numeric span of CArray (CA_BOOLEAN is reduction-special and
|
|
42
42
|
# CA_CMPLX* / CA_OBJECT / CA_FIXLEN are deferred to future dialects).
|
|
43
43
|
# `num2c` is the Ruby VALUE -> C type conversion macro used by
|
|
44
|
-
# value_arg: dispatchers
|
|
44
|
+
# value_arg: dispatchers to cast a positional Ruby argument to
|
|
45
45
|
# the kernel's T_IN type. Signed integers use NUM2LL, unsigned
|
|
46
46
|
# NUM2ULL, floats NUM2DBL, with the dispatcher adding the per-type cast.
|
|
47
47
|
# `c` of a multi-byte type is its unaligned typedef from carray.h
|
|
@@ -68,7 +68,7 @@ module MkKernel
|
|
|
68
68
|
limit_hi: "INFINITY", limit_lo: "-INFINITY" },
|
|
69
69
|
f64: { c: "ca_u_float64_t", ca: "CA_FLOAT64", ruby: "rb_float_new", num2c: "NUM2DBL",
|
|
70
70
|
limit_hi: "INFINITY", limit_lo: "-INFINITY" },
|
|
71
|
-
#
|
|
71
|
+
# Boolean as a first-class source DTYPE.
|
|
72
72
|
# Intentionally NOT included in ALL_NUMERIC -- kernels opt boolean in
|
|
73
73
|
# explicitly via `source: [..., :bool]` (with a `bool:` body entry
|
|
74
74
|
# since the :numeric family alias does not match :bool). Boolean
|
|
@@ -81,13 +81,13 @@ module MkKernel
|
|
|
81
81
|
# domain, so min/max init reuse them directly.
|
|
82
82
|
bool: { c: "boolean8_t", ca: "CA_BOOLEAN", ruby: "INT2NUM",
|
|
83
83
|
limit_hi: "1", limit_lo: "0" },
|
|
84
|
-
#
|
|
84
|
+
# ca_size_t output data_type for sort_index_ki etc.
|
|
85
85
|
# CA_SIZE = CA_INT64 on 64-bit, CA_INT32 on 32-bit (platform-dependent).
|
|
86
86
|
# Used as the output data_type of position-returning kernels (= :sort kind).
|
|
87
87
|
# Intentionally NOT in ALL_NUMERIC -- only sort family uses it as output.
|
|
88
88
|
ca_size: { c: "ca_size_t", ca: "CA_SIZE", ruby: "SIZE2NUM",
|
|
89
89
|
limit_hi: "0", limit_lo: "0" }, # limits unused for sort
|
|
90
|
-
# -----
|
|
90
|
+
# ----- math family DTYPE extensions ------
|
|
91
91
|
# `MkKernel.monop` / `.binop` / `.moncmp` / `.bincmp` emit eager-style
|
|
92
92
|
# kernels matching the existing mkmath calling convention. For full
|
|
93
93
|
# CA_NTYPE coverage parity with mkmath, mkkernel needs to know the
|
|
@@ -99,7 +99,7 @@ module MkKernel
|
|
|
99
99
|
num2c: "NUM2CC", limit_hi: "0", limit_lo: "0" },
|
|
100
100
|
object: { c: "VALUE", ca: "CA_OBJECT", ruby: "(VALUE)",
|
|
101
101
|
num2c: "(VALUE)", limit_hi: "0", limit_lo: "0" },
|
|
102
|
-
#
|
|
102
|
+
# Fixlen for bincmp (= match, eq/ne/gt/lt/ge/le against
|
|
103
103
|
# fixed-byte strings). The c: type is `char` because fixlen kernels
|
|
104
104
|
# operate on raw byte pointers with explicit `b1` byte-width. Opt-in
|
|
105
105
|
# via explicit `source: [..., :fixlen]` in bincmp declarations.
|
|
@@ -189,6 +189,17 @@ module MkKernel
|
|
|
189
189
|
}
|
|
190
190
|
end
|
|
191
191
|
|
|
192
|
+
# A power body: the exponents -2 .. 4 take at most two roundings
|
|
193
|
+
# (x * x, x * x * x, (x * x) * (x * x), 1 / x, 1 / (x * x)), the rest go
|
|
194
|
+
# to `general`. The Integer exponent kernel (ext/ca_op_ipower.c) takes
|
|
195
|
+
# the same ones, so an exponent answers alike as a scalar and as an array.
|
|
196
|
+
def self.pow_short(general)
|
|
197
|
+
"(#3) = (#2) == 2 ? (#1) * (#1) : (#2) == 3 ? (#1) * (#1) * (#1) : " \
|
|
198
|
+
"(#2) == 4 ? ((#1) * (#1)) * ((#1) * (#1)) : (#2) == 1 ? (#1) : " \
|
|
199
|
+
"(#2) == 0 ? 1 : (#2) == -1 ? 1 / (#1) : (#2) == -2 ? 1 / ((#1) * (#1)) : " \
|
|
200
|
+
"#{general};"
|
|
201
|
+
end
|
|
202
|
+
|
|
192
203
|
# Substitute the width markers in a kernel body.
|
|
193
204
|
def self.at_width(body, suffix, real_type)
|
|
194
205
|
body.gsub("<f>", suffix).gsub("<t>", real_type)
|
|
@@ -216,11 +227,11 @@ module MkKernel
|
|
|
216
227
|
# search-family kernels for fuzzy float comparison. Integer data_types get
|
|
217
228
|
# "0" so eps is effectively ignored (exact equality semantics). Float
|
|
218
229
|
# data_types get FLT_EPSILON / DBL_EPSILON from <float.h> (legacy convention
|
|
219
|
-
# `defeps * fabs(val)
|
|
230
|
+
# `defeps * fabs(val)`).
|
|
220
231
|
def self.eps_default_for(src)
|
|
221
232
|
case src
|
|
222
|
-
when :f32 then "FLT_EPSILON"
|
|
223
|
-
when :f64 then "DBL_EPSILON"
|
|
233
|
+
when :f32, :cmplx64 then "FLT_EPSILON"
|
|
234
|
+
when :f64, :cmplx128 then "DBL_EPSILON"
|
|
224
235
|
else "0"
|
|
225
236
|
end
|
|
226
237
|
end
|
|
@@ -232,7 +243,7 @@ module MkKernel
|
|
|
232
243
|
|
|
233
244
|
KERNELS = []
|
|
234
245
|
|
|
235
|
-
#
|
|
246
|
+
# Arbitrary C code injected at the top of the generated
|
|
236
247
|
# carray_kernels.c, after the standard `#include` block but before
|
|
237
248
|
# the first kernel. Used for shared macros that multiple kernels
|
|
238
249
|
# reference (e.g. op_powi for the `power` binop).
|
|
@@ -289,8 +300,7 @@ module MkKernel
|
|
|
289
300
|
# default). With min_count: K (K > 0), output cell
|
|
290
301
|
# is UNDEF when valid_cnt < K (= "need K valid cells").
|
|
291
302
|
# :fill_value substitutes for UNDEF in the result.
|
|
292
|
-
# This is the mode
|
|
293
|
-
# legacy rb_ca_sum / mean / variance etc.
|
|
303
|
+
# This is the mode sum / mean / variance etc. use.
|
|
294
304
|
#
|
|
295
305
|
# When mask_policy is set, the generator:
|
|
296
306
|
# - uses CA_SLAB_REDUCE_T_EX so the kernel sees masked_cnt
|
|
@@ -298,9 +308,9 @@ module MkKernel
|
|
|
298
308
|
# - writes the mask bit for the offending output cell
|
|
299
309
|
# - returns Object::UNDEF for the full-reduction case when the
|
|
300
310
|
# single output cell is masked, instead of the Ruby scalar.
|
|
301
|
-
# value_arg: (
|
|
311
|
+
# value_arg: (count family) -- accept one positional Ruby argument
|
|
302
312
|
# at runtime and bind it to the kernel as a C variable named `value_arg`
|
|
303
|
-
# of type T_IN (the source data_type's C type
|
|
313
|
+
# of type T_IN (the source data_type's C type).
|
|
304
314
|
#
|
|
305
315
|
# DSL:
|
|
306
316
|
# value_arg: { target: :T_IN } # current only supported form
|
|
@@ -312,7 +322,7 @@ module MkKernel
|
|
|
312
322
|
# casts via DTYPES[src][:num2c] inside each per-src switch case.
|
|
313
323
|
# - The reduce: body can reference `value_arg` as a plain C identifier.
|
|
314
324
|
#
|
|
315
|
-
# array_arg: (
|
|
325
|
+
# array_arg: (weighted reduction family) -- accept one positional
|
|
316
326
|
# Ruby CArray argument at runtime as a same-shape second operand
|
|
317
327
|
# (= "weights" for wsum/wmean, future wvariance/wstddev). Walked in
|
|
318
328
|
# lockstep with the source slab via the CA_SLAB_REDUCE_ARRAY_T_EX
|
|
@@ -331,7 +341,7 @@ module MkKernel
|
|
|
331
341
|
# shape: :rev5_strict, # W-A1 scalar / W-A4 shape of the reduced axes /
|
|
332
342
|
# # W-A3 self.shape (:match_source = W-A3 only)
|
|
333
343
|
# mask: :overlay, # weights.mask OR'd into self.mask before
|
|
334
|
-
# # kernel call
|
|
344
|
+
# # kernel call
|
|
335
345
|
# }
|
|
336
346
|
#
|
|
337
347
|
# Generator effects:
|
|
@@ -346,8 +356,8 @@ module MkKernel
|
|
|
346
356
|
# the CA_SLAB_REDUCE_ARRAY_T_EX second type param (T_W), decoupled from T.
|
|
347
357
|
#
|
|
348
358
|
# Incompatibilities:
|
|
349
|
-
# - array_arg + value_arg in the same kernel is rejected (
|
|
350
|
-
#
|
|
359
|
+
# - array_arg + value_arg in the same kernel is rejected (only
|
|
360
|
+
# wsum / wmean take an array_arg).
|
|
351
361
|
def self.reduce(name, source:, output:, init: nil,
|
|
352
362
|
reduce: nil, state: nil, finish: nil,
|
|
353
363
|
ruby_scalar: :auto, fallback: :raise,
|
|
@@ -360,6 +370,8 @@ module MkKernel
|
|
|
360
370
|
fixlen: nil,
|
|
361
371
|
face_gate: nil,
|
|
362
372
|
object_escape: nil,
|
|
373
|
+
integer_total: nil,
|
|
374
|
+
bool_as: nil,
|
|
363
375
|
identity_on_empty: false,
|
|
364
376
|
all_nan_result: nil,
|
|
365
377
|
undefined_if: nil,
|
|
@@ -376,13 +388,12 @@ module MkKernel
|
|
|
376
388
|
# walks each slab twice (Pass 1: Σx -> mean, Pass 2:
|
|
377
389
|
# Σ(x-mean)² -> M2) and produces variance = M2/divisor,
|
|
378
390
|
# optionally sqrt-clamped for stddev. Both passes reuse
|
|
379
|
-
# the
|
|
391
|
+
# the CA_SLAB_REDUCE_T_PLUS_EX macro so
|
|
380
392
|
# SIMD :plus reduction license carries over. Cancellation-
|
|
381
393
|
# free even at absolute values >= 1e6 (= the one-pass
|
|
382
394
|
# Σx² - (Σx)²/n form loses relative precision there and
|
|
383
395
|
# drops the sign for >= 1e8; two-pass centred stays at
|
|
384
|
-
# ε-close over the entire f64 range).
|
|
385
|
-
# devel/PROPOSAL_VARIANCE_STABLE_KERNEL.md.
|
|
396
|
+
# ε-close over the entire f64 range).
|
|
386
397
|
# state_from_slab_size: [:cnt, ...]
|
|
387
398
|
# Names of state vars whose per-cell increment in REDUCE
|
|
388
399
|
# is equivalent to `st.slab_elements - masked_cnt` at
|
|
@@ -429,6 +440,21 @@ module MkKernel
|
|
|
429
440
|
raise "#{name}: object_escape and source: :object are mutually exclusive" \
|
|
430
441
|
if source.include?(:object)
|
|
431
442
|
end
|
|
443
|
+
# integer_total: the name of a kernel that folds an integer array in
|
|
444
|
+
# int64 / uint64, wrapping. The generated dispatcher sends an integer
|
|
445
|
+
# array to ca_integer_total (carray_integer_total.c), which answers with
|
|
446
|
+
# that exact integer total where it is in range and with this kernel's
|
|
447
|
+
# float64 total where it is not.
|
|
448
|
+
if integer_total
|
|
449
|
+
raise "#{name}: integer_total must be a Symbol" unless integer_total.is_a?(Symbol)
|
|
450
|
+
end
|
|
451
|
+
# bool_as: the data type a boolean array is read as at the dispatcher
|
|
452
|
+
# entry (its 0/1 cells, mask kept), for a kernel whose source list has
|
|
453
|
+
# no :bool body. The answer is then the one that data type gives.
|
|
454
|
+
if bool_as
|
|
455
|
+
raise "#{name}: bool_as must be a source data_type" unless source.include?(bool_as)
|
|
456
|
+
raise "#{name}: bool_as and source: :bool are mutually exclusive" if source.include?(:bool)
|
|
457
|
+
end
|
|
432
458
|
raise "duplicate kernel #{name}" if KERNELS.any? { |k| k[:name] == name }
|
|
433
459
|
source.each do |s|
|
|
434
460
|
raise "unknown source data_type #{s}" unless DTYPES.key?(s)
|
|
@@ -436,7 +462,7 @@ module MkKernel
|
|
|
436
462
|
raise "unknown output #{output}" unless output == :preserve || DTYPES.key?(output) || output.is_a?(Hash)
|
|
437
463
|
raise "unknown fallback #{fallback}" unless %i[raise wrap_to_f64].include?(fallback)
|
|
438
464
|
raise "unknown mask_policy #{mask_policy}" unless [nil, :strict, :all_masked, :min_count].include?(mask_policy)
|
|
439
|
-
#
|
|
465
|
+
# identity_on_empty makes empty / all-masked slabs emit the
|
|
440
466
|
# reduction identity (= acc_init via finish: "acc") instead of UNDEF,
|
|
441
467
|
# for the default min_count (< 0). Only meaningful for :min_count
|
|
442
468
|
# kernels whose finish returns the accumulator unchanged (sum/prod/
|
|
@@ -451,20 +477,22 @@ module MkKernel
|
|
|
451
477
|
# satisfy this; multi-state ratio kernels (mean {acc,cnt} / variance
|
|
452
478
|
# {acc,sumsq,cnt} / wmean {sum,den}) and multi-output (minmax) divide
|
|
453
479
|
# or combine in finish and MUST stay UNDEF on empty (0/0 undefined).
|
|
480
|
+
# An outputs: 2 kernel whose finish hands each state back as it is
|
|
481
|
+
# (sum_parts) also qualifies; its author says so by giving
|
|
482
|
+
# identity_on_empty, which minmax does not.
|
|
454
483
|
single_acc = state.nil? || (state.is_a?(Hash) && state.size == 1)
|
|
455
|
-
raise "#{name}: identity_on_empty requires a single-accumulator reduction (sum/prod/count/accumulate/wsum); mean/variance/wmean/minmax are excluded" \
|
|
456
|
-
unless single_acc && outputs == 1
|
|
484
|
+
raise "#{name}: identity_on_empty requires a single-accumulator reduction (sum/prod/count/accumulate/wsum) or an outputs: 2 one whose finish hands its states back; mean/variance/wmean/minmax are excluded" \
|
|
485
|
+
unless (single_acc && outputs == 1) || outputs == 2
|
|
457
486
|
end
|
|
458
487
|
if settled
|
|
459
488
|
raise "#{name}: settled requires a single-accumulator reduction without mask_policy, value_arg or array_arg" \
|
|
460
489
|
unless state.nil? && mask_policy.nil? && value_arg.nil? && array_arg.nil? && outputs == 1
|
|
461
490
|
end
|
|
462
|
-
#
|
|
491
|
+
# reduction_kind: licenses a SIMD-friendly contig-branch macro
|
|
463
492
|
# variant (CA_SLAB_REDUCE_T_{PLUS,MIN,MAX,STAR,VAR}_EX). default
|
|
464
493
|
# :none keeps the existing CA_SLAB_REDUCE_T_EX path (= unchanged
|
|
465
494
|
# behavior for argmin/argmax/any/all/etc). Multi-acc variants pass
|
|
466
495
|
# a Hash (= variance: { sum: :plus, sumsq: :plus, cnt: :induction }).
|
|
467
|
-
# See PROPOSAL_REDUCTION_SIMD_LICENSE §2.3.
|
|
468
496
|
unless reduction_kind == :none ||
|
|
469
497
|
%i[plus min max star induction].include?(reduction_kind) ||
|
|
470
498
|
reduction_kind.is_a?(Hash)
|
|
@@ -550,31 +578,32 @@ module MkKernel
|
|
|
550
578
|
raise "#{name}: source includes :fixlen but no fixlen: spec given"
|
|
551
579
|
end
|
|
552
580
|
|
|
553
|
-
#
|
|
581
|
+
# Multi-output reduce (= fused minmax etc).
|
|
554
582
|
# outputs: 2 is the only non-default form supported. Compatibility gates:
|
|
555
583
|
# - finish must be Hash with exactly 2 entries (e.g. {min: "lo", max: "hi"})
|
|
556
584
|
# — the Hash keys are informational only (= used as Ruby return-shape
|
|
557
585
|
# placeholders); the values are the per-output finish expressions.
|
|
558
|
-
# - mask_policy: nil
|
|
559
|
-
#
|
|
560
|
-
# - value_arg / array_arg / view_flat: rejected in FM.1.0 (= no demand,
|
|
561
|
-
# scope creep avoidance per PROPOSAL §2.2).
|
|
586
|
+
# - mask_policy: nil or :min_count.
|
|
587
|
+
# - value_arg / array_arg / view_flat: rejected.
|
|
562
588
|
# - reduction_kind: must be :none (= multi-output uses
|
|
563
589
|
# CA_SLAB_REDUCE_T_EX baseline, SIMD license per reduction is future
|
|
564
|
-
# work
|
|
590
|
+
# work).
|
|
565
591
|
raise "#{name}: outputs must be Integer 1 or 2 (got #{outputs.inspect})" \
|
|
566
592
|
unless outputs.is_a?(Integer) && (1..2).include?(outputs)
|
|
567
593
|
if outputs == 2
|
|
568
594
|
raise "#{name}: outputs: 2 requires finish: Hash with exactly 2 entries" \
|
|
569
595
|
unless finish.is_a?(Hash) && finish.size == 2
|
|
570
|
-
raise "#{name}: outputs: 2 with mask_policy supports only nil or :min_count
|
|
596
|
+
raise "#{name}: outputs: 2 with mask_policy supports only nil or :min_count" \
|
|
571
597
|
unless [nil, :min_count].include?(mask_policy)
|
|
572
|
-
raise "#{name}: outputs: 2 currently does not support value_arg / array_arg
|
|
598
|
+
raise "#{name}: outputs: 2 currently does not support value_arg / array_arg" \
|
|
573
599
|
if value_arg || array_arg
|
|
574
|
-
raise "#{name}: outputs: 2 requires semantics: :fiber_local
|
|
600
|
+
raise "#{name}: outputs: 2 requires semantics: :fiber_local" \
|
|
575
601
|
unless semantics == :fiber_local
|
|
576
|
-
|
|
577
|
-
|
|
602
|
+
# A Hash of :plus states licenses the loop interchange along a
|
|
603
|
+
# non-innermost axis (emit_reduce_native_multi).
|
|
604
|
+
raise "#{name}: outputs: 2 requires reduction_kind: :none, or a Hash of :plus states" \
|
|
605
|
+
unless reduction_kind == :none ||
|
|
606
|
+
(reduction_kind.is_a?(Hash) && reduction_kind.values.all?(:plus))
|
|
578
607
|
end
|
|
579
608
|
if array_arg
|
|
580
609
|
raise "#{name}: array_arg must be a Hash" unless array_arg.is_a?(Hash)
|
|
@@ -586,19 +615,20 @@ module MkKernel
|
|
|
586
615
|
# against an int source must not be truncated to the source type.
|
|
587
616
|
# :match_source (legacy) reads the weight at the source type -- kept only
|
|
588
617
|
# for forward-compat in the DSL grammar (no production kernel uses it).
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
#
|
|
618
|
+
# :int64 reads the weight as an int64 (the integer fold behind wsum).
|
|
619
|
+
raise "#{name}: array_arg: data_type must be :promote, :int64 or :match_source" \
|
|
620
|
+
unless [:promote, :int64, :match_source].include?(array_arg[:data_type])
|
|
621
|
+
# Accepted shapes: W-A1 (scalar) / W-A4 (shape of the reduced axes) /
|
|
622
|
+
# W-A3 (self.shape).
|
|
593
623
|
# :match_source = legacy W-A3 only (kept for forward-compat in DSL).
|
|
594
|
-
# :rev5_strict = W-A1 + W-A4 + W-A3 acceptance (=
|
|
624
|
+
# :rev5_strict = W-A1 + W-A4 + W-A3 acceptance (= what wsum / wmean use).
|
|
595
625
|
raise "#{name}: array_arg: shape must be :match_source or :rev5_strict" \
|
|
596
626
|
unless [:match_source, :rev5_strict].include?(array_arg[:shape])
|
|
597
|
-
raise "#{name}: array_arg: mask must be :overlay
|
|
627
|
+
raise "#{name}: array_arg: mask must be :overlay" \
|
|
598
628
|
unless array_arg[:mask] == :overlay
|
|
599
|
-
raise "#{name}: array_arg + value_arg in same kernel is not supported
|
|
629
|
+
raise "#{name}: array_arg + value_arg in same kernel is not supported" \
|
|
600
630
|
if value_arg
|
|
601
|
-
raise "#{name}: array_arg + :wrap_to_f64 fallback is not supported
|
|
631
|
+
raise "#{name}: array_arg + :wrap_to_f64 fallback is not supported; use :raise" \
|
|
602
632
|
if fallback == :wrap_to_f64
|
|
603
633
|
end
|
|
604
634
|
|
|
@@ -669,6 +699,8 @@ module MkKernel
|
|
|
669
699
|
fixlen: fixlen,
|
|
670
700
|
face_gate: face_gate,
|
|
671
701
|
object_escape: object_escape,
|
|
702
|
+
integer_total: integer_total,
|
|
703
|
+
bool_as: bool_as,
|
|
672
704
|
identity_on_empty: identity_on_empty,
|
|
673
705
|
all_nan_result: all_nan_result,
|
|
674
706
|
undefined_if: undefined_if,
|
|
@@ -729,12 +761,22 @@ module MkKernel
|
|
|
729
761
|
# the reduction contract (empty max / min = UNDEF, no
|
|
730
762
|
# identity) and the axis-group scan family.
|
|
731
763
|
# private:
|
|
732
|
-
# false (default) -> bound as the
|
|
764
|
+
# false (default) -> bound as the private `<name>_ki`, or not at all when
|
|
765
|
+
# axis_default: :flatten binds the public `<name>`
|
|
733
766
|
# true -> bound only as the private method `<name>`, a part
|
|
734
767
|
# that lib reaches with `send` (not user surface)
|
|
768
|
+
# integer_total:
|
|
769
|
+
# nil -> an integer array scans in this kernel's output type
|
|
770
|
+
# :<kernel> -> an integer array goes to ca_integer_scan, which runs
|
|
771
|
+
# that kernel (the running value in int64 / uint64,
|
|
772
|
+
# wrapping) and, where a running value may be out of
|
|
773
|
+
# range, this kernel's own float64 scan, and answers
|
|
774
|
+
# with the integer scan unless it wrapped -- the rule
|
|
775
|
+
# sum and prod follow (carray_integer_total.c).
|
|
776
|
+
# The kind (sum or prod) is read from the name.
|
|
735
777
|
def self.scan(name, source:, output:, init:, step:, fallback: :raise,
|
|
736
778
|
acc_type: nil, axis_default: nil, empty: nil, face_gate: nil,
|
|
737
|
-
private: false)
|
|
779
|
+
private: false, integer_total: nil)
|
|
738
780
|
raise "duplicate kernel #{name}" if KERNELS.any? { |k| k[:name] == name }
|
|
739
781
|
source.each do |s|
|
|
740
782
|
raise "unknown source data_type #{s}" unless DTYPES.key?(s)
|
|
@@ -777,6 +819,7 @@ module MkKernel
|
|
|
777
819
|
empty: empty,
|
|
778
820
|
face_gate: face_gate,
|
|
779
821
|
private: private,
|
|
822
|
+
integer_total: integer_total,
|
|
780
823
|
}
|
|
781
824
|
end
|
|
782
825
|
|
|
@@ -784,7 +827,7 @@ module MkKernel
|
|
|
784
827
|
# input shape == output shape, one axis at a time). Generated method
|
|
785
828
|
# takes exactly one axis argument.
|
|
786
829
|
#
|
|
787
|
-
# Semantics
|
|
830
|
+
# Semantics:
|
|
788
831
|
# :fiber_local -> output[cell] in 0..dim[axis]-1 (sort index
|
|
789
832
|
# along axis). Used by sort_index_ki, the user-
|
|
790
833
|
# facing sort-index entry.
|
|
@@ -805,16 +848,15 @@ module MkKernel
|
|
|
805
848
|
# (= Linux glibc qsort is msort-based, so stable in practice).
|
|
806
849
|
#
|
|
807
850
|
# Sort kind selection (:quicksort / :mergesort / :stable / :heapsort) is
|
|
808
|
-
# NOT exposed on the Ruby surface
|
|
809
|
-
#
|
|
851
|
+
# NOT exposed on the Ruby surface; it can be added
|
|
852
|
+
# via a kind_options field.
|
|
810
853
|
#
|
|
811
854
|
# bind_ruby:
|
|
812
855
|
# true (default) -> rb_define_method(rb_cCArray, "<name>_ki", ...).
|
|
813
856
|
# false -> emit rb_ca_<name>_ki C entry but DO NOT bind
|
|
814
857
|
# a Ruby method. Used by sort_addr_ki which is
|
|
815
858
|
# consumed only at the C level by the public
|
|
816
|
-
# `sort(axis:)` method
|
|
817
|
-
# defers `sort_addr(axis:)` public form).
|
|
859
|
+
# `sort(axis:)` method.
|
|
818
860
|
#
|
|
819
861
|
# DSL:
|
|
820
862
|
# MkKernel.sort :sort_index,
|
|
@@ -832,7 +874,7 @@ module MkKernel
|
|
|
832
874
|
# fallback: :raise,
|
|
833
875
|
# bind_ruby: false # internal-only kernel
|
|
834
876
|
#
|
|
835
|
-
# algorithm:
|
|
877
|
+
# algorithm:
|
|
836
878
|
# :full (default) -> full stable sort (qsort/mergesort). Ruby
|
|
837
879
|
# method takes 1 positional arg (axis).
|
|
838
880
|
# :partition -> quickselect: ensures arr[kth] is the kth-smallest;
|
|
@@ -842,7 +884,7 @@ module MkKernel
|
|
|
842
884
|
# positional args (axis, kth). Used by
|
|
843
885
|
# partition_index_ki / partition_addr_ki.
|
|
844
886
|
#
|
|
845
|
-
# mask_self:
|
|
887
|
+
# mask_self:
|
|
846
888
|
# :raise -> ca_has_mask(self) raises ArgumentError before dispatch;
|
|
847
889
|
# the kernel body never sees a masked source.
|
|
848
890
|
# :skip -> masked cells are excluded from the sort entirely (used
|
|
@@ -916,12 +958,7 @@ module MkKernel
|
|
|
916
958
|
# tail-append rule for incompatible shapes). Generated method takes
|
|
917
959
|
# a `val` argument (scalar or CArray) and `axis:` keyword.
|
|
918
960
|
#
|
|
919
|
-
#
|
|
920
|
-
# is implemented in S.1.2. Registering a :search kernel before S.1.2
|
|
921
|
-
# lands will fail at `MkKernel.emit` time (unknown kind in dispatch),
|
|
922
|
-
# which is the intended guard rail.
|
|
923
|
-
#
|
|
924
|
-
# Author surface (Q1=B sparring confirmed): the author writes the
|
|
961
|
+
# Author surface: the author writes the
|
|
925
962
|
# inner per-slab kernel body in C, the generator emits the outer
|
|
926
963
|
# (query × base) walk. This is needed because:
|
|
927
964
|
# - bsearch family calls libc bsearch() directly
|
|
@@ -931,7 +968,7 @@ module MkKernel
|
|
|
931
968
|
# author convenience (~15 lines of C body) for production flexibility
|
|
932
969
|
# across all 5 families.
|
|
933
970
|
#
|
|
934
|
-
# Broadcast rule
|
|
971
|
+
# Broadcast rule:
|
|
935
972
|
# base_shape = self.shape with axis removed
|
|
936
973
|
# if val.shape broadcasts against base_shape:
|
|
937
974
|
# output.shape = broadcast(base_shape, val.shape)
|
|
@@ -998,13 +1035,16 @@ module MkKernel
|
|
|
998
1035
|
when String
|
|
999
1036
|
# uniform body
|
|
1000
1037
|
when Hash
|
|
1001
|
-
allowed = %i[int float object fixlen]
|
|
1038
|
+
allowed = %i[int float complex object fixlen]
|
|
1002
1039
|
unless (body.keys - allowed).empty? && body.key?(:int) && body.key?(:float)
|
|
1003
|
-
raise "search: body Hash must have :int and :float keys (plus optional :object / :fixlen), got #{body.keys.inspect}"
|
|
1040
|
+
raise "search: body Hash must have :int and :float keys (plus optional :complex / :object / :fixlen), got #{body.keys.inspect}"
|
|
1004
1041
|
end
|
|
1005
1042
|
unless body.values.all? { |v| v.is_a?(String) }
|
|
1006
1043
|
raise "search: body Hash values must be String"
|
|
1007
1044
|
end
|
|
1045
|
+
if (source & CMPLX_DTYPES).any? && !body.key?(:complex)
|
|
1046
|
+
raise "search: a complex source needs a :complex body"
|
|
1047
|
+
end
|
|
1008
1048
|
else
|
|
1009
1049
|
raise "search: body must be a String or Hash {int:, float:}, got #{body.class}"
|
|
1010
1050
|
end
|
|
@@ -1028,7 +1068,7 @@ module MkKernel
|
|
|
1028
1068
|
# no_match sentinel) marks the corresponding output cell UNDEF (masked)
|
|
1029
1069
|
# instead of writing the raw -1 sentinel. This unifies the "not found"
|
|
1030
1070
|
# representation with the no-axis flat path, which already returns UNDEF
|
|
1031
|
-
# for array queries
|
|
1071
|
+
# for array queries. Only valid for
|
|
1032
1072
|
# the default-sentinel family (no_match_check == nil); the NAN-sentinel
|
|
1033
1073
|
# interpolation kernels (linear_section / linear_fetch) keep their in-band
|
|
1034
1074
|
# float sentinel and must not set this flag.
|
|
@@ -1058,7 +1098,7 @@ module MkKernel
|
|
|
1058
1098
|
}
|
|
1059
1099
|
end
|
|
1060
1100
|
|
|
1061
|
-
# ----
|
|
1101
|
+
# ---- math family DSL ----------------------
|
|
1062
1102
|
#
|
|
1063
1103
|
# Eager monop: `<op>` is a per-element function `T -> T` (preserve) or
|
|
1064
1104
|
# `T -> Twider` (widening; widening is handled in carray_math.rb's
|
|
@@ -1134,7 +1174,7 @@ module MkKernel
|
|
|
1134
1174
|
KERNELS << { kind: :monop_alias, op: op.to_s, name: name.to_s }
|
|
1135
1175
|
end
|
|
1136
1176
|
|
|
1137
|
-
# ----
|
|
1177
|
+
# ---- binop DSL ------------------------------------------------
|
|
1138
1178
|
#
|
|
1139
1179
|
# Eager binop: per-element function `(T, T) -> T` (preserve data_type). The
|
|
1140
1180
|
# emitted kernel signature matches mkmath's calling convention:
|
|
@@ -1158,6 +1198,8 @@ module MkKernel
|
|
|
1158
1198
|
# Pass `op: "+"` etc. to use a different operator method name; pass
|
|
1159
1199
|
# `op: nil` to skip the Ruby method registration entirely (= internal
|
|
1160
1200
|
# kernels like and_i / or_i / xor_i exposed via hand-written wrappers).
|
|
1201
|
+
# `bind: false` registers neither: the C functions are left for other C
|
|
1202
|
+
# code to call.
|
|
1161
1203
|
# `kleene: :and | :or` makes the (non-bang) wrapper apply the boolean
|
|
1162
1204
|
# three-valued mask fixup after the value kernel (see ca_kleene_bool_fixup).
|
|
1163
1205
|
op = name.to_s if op == :auto
|
|
@@ -1209,7 +1251,7 @@ module MkKernel
|
|
|
1209
1251
|
}
|
|
1210
1252
|
end
|
|
1211
1253
|
|
|
1212
|
-
# ----
|
|
1254
|
+
# ---- moncmp DSL ------------------------------------------------
|
|
1213
1255
|
#
|
|
1214
1256
|
# Eager moncmp: per-element predicate `T -> bool`. Kernel signature:
|
|
1215
1257
|
#
|
|
@@ -1231,7 +1273,7 @@ module MkKernel
|
|
|
1231
1273
|
}
|
|
1232
1274
|
end
|
|
1233
1275
|
|
|
1234
|
-
# ----
|
|
1276
|
+
# ---- bincmp DSL ------------------------------------------------
|
|
1235
1277
|
#
|
|
1236
1278
|
# Eager bincmp: per-element predicate `(T, T) -> bool`. Kernel
|
|
1237
1279
|
# signature includes byte-width parameters b1/b2/b3 for FIXLEN cmp:
|
|
@@ -1293,7 +1335,7 @@ module MkKernel
|
|
|
1293
1335
|
# wants for its complex family: the magnitude of a cmplx64 is a
|
|
1294
1336
|
# float32, the same width `.real` and `.imag` already return. Naming
|
|
1295
1337
|
# :f64 there would hand cmplx64 the real width of cmplx128.
|
|
1296
|
-
#
|
|
1338
|
+
# Resolve the reduce macro suffix for a given kernel entry,
|
|
1297
1339
|
# driven by reduction_kind. Returns "" for :none (= legacy
|
|
1298
1340
|
# CA_SLAB_REDUCE_T_EX), or "_PLUS" / "_MIN" / "_MAX" / "_STAR" to
|
|
1299
1341
|
# license a SIMD-friendly contig-branch variant.
|
|
@@ -1304,8 +1346,7 @@ module MkKernel
|
|
|
1304
1346
|
# inline by REDUCE) are auto-vectorised by the compiler when
|
|
1305
1347
|
# appropriate.
|
|
1306
1348
|
#
|
|
1307
|
-
#
|
|
1308
|
-
# Horizontal 8-way accumulator split (2026-07-19, extension of the
|
|
1349
|
+
# Horizontal 8-way accumulator split (extension of the
|
|
1309
1350
|
# variance/stddev SUM8 fix): eligibility gate for the standard reducer
|
|
1310
1351
|
# emit path. Returns true when the caller should emit CA_SLAB_REDUCE_
|
|
1311
1352
|
# {SUM,MIN,MAX,STAR}8_EX instead of the legacy single-accumulator
|
|
@@ -1353,7 +1394,7 @@ module MkKernel
|
|
|
1353
1394
|
# -> smin.4s / smin.16b on arm64, gcc -> vpminsd on AVX2) is
|
|
1354
1395
|
# already excellent — a manual 8-way scalar split *prevents* that
|
|
1355
1396
|
# specific packed-min lowering by fragmenting the conditional
|
|
1356
|
-
# across 8 independent lanes. Observed
|
|
1397
|
+
# across 8 independent lanes. Observed: M4 int32 min
|
|
1357
1398
|
# regressed 2.5x (36 -> 90 us) under 8-way while f64 min improved
|
|
1358
1399
|
# 3.7x (459 -> 123 us) because the compiler wasn't vectorizing FP
|
|
1359
1400
|
# min in the first place. Restrict 8-way min/max to floating-point
|
|
@@ -1385,10 +1426,11 @@ module MkKernel
|
|
|
1385
1426
|
when "_STAR" then "CA_SLAB_REDUCE_STAR8_EX"
|
|
1386
1427
|
end
|
|
1387
1428
|
acc_c = resolve_state_type(k[:state][acc_var], oi, si, src)
|
|
1388
|
-
# An 8- or 16-bit integer cell
|
|
1429
|
+
# An 8- or 16-bit integer cell widened to an 8-byte accumulator does not
|
|
1430
|
+
# vectorize well, whether the accumulator is a double or an integer;
|
|
1389
1431
|
# the narrow form sums blocks in int32 first.
|
|
1390
1432
|
if macro8 == "CA_SLAB_REDUCE_SUM8_EX" && %i[i8 u8 i16 u16].include?(src) &&
|
|
1391
|
-
|
|
1433
|
+
[DTYPES[:f64][:c], DTYPES[:i64][:c], DTYPES[:u64][:c]].include?(acc_c)
|
|
1392
1434
|
macro8 = "CA_SLAB_REDUCE_SUM8_NARROW_EX"
|
|
1393
1435
|
end
|
|
1394
1436
|
expr_macro = "__#{k[:name]}_#{src}_EXPR"
|
|
@@ -1715,7 +1757,8 @@ module MkKernel
|
|
|
1715
1757
|
# aggregate: arithmetic folds (sum / prod / mean and their weighted
|
|
1716
1758
|
# variants)
|
|
1717
1759
|
sum: :aggregate, prod: :aggregate, mean: :aggregate,
|
|
1718
|
-
|
|
1760
|
+
sum_wrapping: :aggregate, sum_parts: :aggregate, prod_wrapping: :aggregate,
|
|
1761
|
+
wsum: :aggregate, wsum_wrapping: :aggregate, wmean: :aggregate,
|
|
1719
1762
|
# extreme: order-based (min / max, argmin / argmax, minmax)
|
|
1720
1763
|
min: :extreme, max: :extreme, minmax: :extreme,
|
|
1721
1764
|
argmin: :extreme, argmax: :extreme,
|
|
@@ -1795,13 +1838,12 @@ module MkKernel
|
|
|
1795
1838
|
#include "carray.h"
|
|
1796
1839
|
#include "ca_kernel_iterator.h"
|
|
1797
1840
|
#include "ca_sort_kernels.h" /* sort kernels: internal, not via the carray.h umbrella */
|
|
1798
|
-
#include "carray_internal.h" /* ca_lazy_arena_*, ca_is_lazy_view (streaming reduce) */
|
|
1799
1841
|
#include "ca_obj_face.h" /* rb_ca_strip_face_value (Face ordering gate) */
|
|
1800
1842
|
#include <math.h>
|
|
1801
1843
|
#include <stdint.h>
|
|
1802
1844
|
#include <stdlib.h> /* qsort, mergesort (HAVE_MERGESORT) -- for :sort kind */
|
|
1803
1845
|
|
|
1804
|
-
/*
|
|
1846
|
+
/* CAStack identity (for the CAStack reduce fast path) is
|
|
1805
1847
|
probed by operation-table function pointer (obj_type is runtime-
|
|
1806
1848
|
assigned, so no CA_OBJ_STACK compile-time constant exists). */
|
|
1807
1849
|
extern ca_operation_function_t ca_stack_func;
|
|
@@ -1930,7 +1972,7 @@ module MkKernel
|
|
|
1930
1972
|
end
|
|
1931
1973
|
|
|
1932
1974
|
def self.emit_reduce_native(io, k, src)
|
|
1933
|
-
#
|
|
1975
|
+
# Multi-output reduce delegates to dedicated emitter. outputs:2
|
|
1934
1976
|
# path is simpler than the single-output path (= no streaming, view_flat,
|
|
1935
1977
|
# array_arg, mask_policy support yet — gated by reduce DSL validation).
|
|
1936
1978
|
return emit_reduce_native_multi(io, k, src) if k[:outputs] == 2
|
|
@@ -1982,10 +2024,10 @@ module MkKernel
|
|
|
1982
2024
|
extra_args += ", #{si[:c]} value_arg" if k[:value_arg]
|
|
1983
2025
|
extra_args += ", ca_size_t min_count" if k[:mask_policy] == :min_count
|
|
1984
2026
|
|
|
1985
|
-
#
|
|
2027
|
+
# Streaming branch emitted before the SRC_ATTACH path.
|
|
1986
2028
|
# Conditions for streaming:
|
|
1987
2029
|
# - flat reduction (naxes == ca->ndim)
|
|
1988
|
-
# - any ndim >= 1 (
|
|
2030
|
+
# - any ndim >= 1 (N-D via outer-axis chunking)
|
|
1989
2031
|
# - lazy view source (CAMonOp/CABinOp/CABinCmp/CAMonCmp)
|
|
1990
2032
|
# - no mask source — masked operands fall back to SRC_ATTACH
|
|
1991
2033
|
# - no array_arg (weighted reductions) — wsum/wmean fall back
|
|
@@ -2012,23 +2054,23 @@ module MkKernel
|
|
|
2012
2054
|
emit_reduce_streaming_call(io, k, src)
|
|
2013
2055
|
end
|
|
2014
2056
|
|
|
2015
|
-
#
|
|
2057
|
+
# Loop interchange:
|
|
2016
2058
|
# Non-innermost single-axis reduce on row-major entity gets a
|
|
2017
2059
|
# loop-interchange fast path -- contig load, contig output accumulator,
|
|
2018
|
-
# SIMD-vectorised inner loop.
|
|
2019
|
-
#
|
|
2060
|
+
# SIMD-vectorised inner loop. Without it this case walks the strided
|
|
2061
|
+
# axis in the inner loop; the interchange reorders iteration
|
|
2020
2062
|
# so the inner loop walks the contig (innermost) axis instead of the
|
|
2021
2063
|
# strided reduce axis.
|
|
2022
2064
|
#
|
|
2023
2065
|
# Eligible kernels:
|
|
2024
|
-
#
|
|
2066
|
+
# - single :plus state (sum / accumulate / count / count_true /
|
|
2025
2067
|
# count_false / count_not_masked)
|
|
2026
|
-
#
|
|
2068
|
+
# - :plus + :induction (mean) -- induction var (= cnt) is
|
|
2027
2069
|
# precomputed as __li_M outside the SIMD loop
|
|
2028
|
-
#
|
|
2070
|
+
# - N :plus + 0 or 1 :induction (variance / stddev) -- multi-
|
|
2029
2071
|
# buffer path, one out_buf per :plus state
|
|
2030
|
-
#
|
|
2031
|
-
# (array_arg)
|
|
2072
|
+
# - single :min / :max / :star (min / max / prod)
|
|
2073
|
+
# wsum / wmean (array_arg) do not take this path.
|
|
2032
2074
|
# Buf-kinds = reduction kinds whose per-cell update is independent
|
|
2033
2075
|
# across output positions and thus benefit from a per-cell out_buf
|
|
2034
2076
|
# in the interchange path: :plus (sum), :star (prod), :min, :max.
|
|
@@ -2047,7 +2089,7 @@ module MkKernel
|
|
|
2047
2089
|
else
|
|
2048
2090
|
buf_count = induction_count = other_count = 0
|
|
2049
2091
|
end
|
|
2050
|
-
#
|
|
2092
|
+
# Limit multi-buffer support to single-kind groups (= all bufs
|
|
2051
2093
|
# are :plus, or single :min, or single :max, or single :star).
|
|
2052
2094
|
# Mixed :plus + :min (no real kernel today) would need careful
|
|
2053
2095
|
# finish ordering; reject for now.
|
|
@@ -2088,7 +2130,7 @@ module MkKernel
|
|
|
2088
2130
|
end
|
|
2089
2131
|
|
|
2090
2132
|
io.puts <<~C
|
|
2091
|
-
VALUE
|
|
2133
|
+
volatile VALUE vout = rb_ca_new_reduced(self, slab_axes, naxes, #{oi[:ca]}, keep_axis);
|
|
2092
2134
|
CArray *co;
|
|
2093
2135
|
GetCArray(vout, co);
|
|
2094
2136
|
#{oi[:c]} *op = (#{oi[:c]} *) co->ptr;
|
|
@@ -2168,12 +2210,12 @@ module MkKernel
|
|
|
2168
2210
|
if k[:mask_policy]
|
|
2169
2211
|
io.puts " ca_size_t masked_cnt = 0;"
|
|
2170
2212
|
if k[:array_arg]
|
|
2171
|
-
#
|
|
2213
|
+
# The array_arg path dispatches via suffix. Only :plus
|
|
2172
2214
|
# variant is implemented at the array level (CA_SLAB_REDUCE_ARRAY_
|
|
2173
2215
|
# T_PLUS_EX); other kinds fall back to legacy ARRAY_T_EX.
|
|
2174
2216
|
suffix = MkKernel.reduce_macro_suffix(k, src)
|
|
2175
2217
|
suffix = "" unless suffix == "_PLUS" # only PLUS landed for array_arg
|
|
2176
|
-
wc = (k[:array_arg][:data_type]
|
|
2218
|
+
wc = { promote: "double", int64: "int64_t" }.fetch(k[:array_arg][:data_type], si[:c])
|
|
2177
2219
|
io.puts " CA_SLAB_REDUCE_ARRAY_T#{suffix}_EX(#{si[:c]}, #{wc}, st, p, m, st_w, p_w, #{acc_var}, #{acc_init}, #{reduce_stmt}, masked_cnt);"
|
|
2178
2220
|
else
|
|
2179
2221
|
suffix = MkKernel.reduce_macro_suffix(k, src)
|
|
@@ -2222,7 +2264,7 @@ module MkKernel
|
|
|
2222
2264
|
io.puts " }"
|
|
2223
2265
|
else
|
|
2224
2266
|
if k[:array_arg]
|
|
2225
|
-
wc = (k[:array_arg][:data_type]
|
|
2267
|
+
wc = { promote: "double", int64: "int64_t" }.fetch(k[:array_arg][:data_type], si[:c])
|
|
2226
2268
|
io.puts " ca_size_t __sra_throwaway_mc = 0;"
|
|
2227
2269
|
io.puts " CA_SLAB_REDUCE_ARRAY_T_EX(#{si[:c]}, #{wc}, st, p, m, st_w, p_w, #{acc_var}, #{acc_init}, #{reduce_stmt}, __sra_throwaway_mc);"
|
|
2228
2270
|
io.puts " (void) __sra_throwaway_mc;"
|
|
@@ -2305,9 +2347,9 @@ module MkKernel
|
|
|
2305
2347
|
io.puts "{"
|
|
2306
2348
|
io.puts " ca_size_t K = ca->bytes; /* uniform fixlen byte width */"
|
|
2307
2349
|
if index_out
|
|
2308
|
-
io.puts " VALUE
|
|
2350
|
+
io.puts " volatile VALUE vout = rb_ca_new_reduced(self, slab_axes, naxes, CA_INT64, keep_axis);"
|
|
2309
2351
|
else
|
|
2310
|
-
io.puts " VALUE
|
|
2352
|
+
io.puts " volatile VALUE vout = rb_ca_new_reduced_bytes(self, slab_axes, naxes, CA_FIXLEN, K, keep_axis);"
|
|
2311
2353
|
end
|
|
2312
2354
|
io.puts " CArray *co;"
|
|
2313
2355
|
io.puts " GetCArray(vout, co);"
|
|
@@ -2403,7 +2445,7 @@ module MkKernel
|
|
|
2403
2445
|
io.puts "}"
|
|
2404
2446
|
end
|
|
2405
2447
|
|
|
2406
|
-
#
|
|
2448
|
+
# Emit the loop-interchange
|
|
2407
2449
|
# fast-path body inside name_ki_native_<src>. Runtime-eligible when the
|
|
2408
2450
|
# source is a row-major entity (no mask, single reduce axis, axis is not
|
|
2409
2451
|
# the innermost). Output buffer holds T_OUT accumulators sized to the
|
|
@@ -2413,7 +2455,7 @@ module MkKernel
|
|
|
2413
2455
|
#
|
|
2414
2456
|
# Threshold gate (INNER >= 64 && INNER*M >= 1024) skips the path when
|
|
2415
2457
|
# the size cannot amortise the alloc + 2-pass init/finish overhead.
|
|
2416
|
-
# The
|
|
2458
|
+
# The values are seed estimates.
|
|
2417
2459
|
# Two-pass centred variance / stddev emitter.
|
|
2418
2460
|
#
|
|
2419
2461
|
# Layout per slab:
|
|
@@ -2444,7 +2486,7 @@ module MkKernel
|
|
|
2444
2486
|
oi = output_info(k, src)
|
|
2445
2487
|
ruby_wrap = ruby_scalar(k, oi)
|
|
2446
2488
|
|
|
2447
|
-
# Per-src
|
|
2489
|
+
# Per-src types and literals.
|
|
2448
2490
|
# sum_c : C type of sum / mean
|
|
2449
2491
|
# sum_init : init literal for sum
|
|
2450
2492
|
# p1_body : Pass 1 reduce statement (populates `sum`)
|
|
@@ -2461,8 +2503,8 @@ module MkKernel
|
|
|
2461
2503
|
sum_c = "VALUE"
|
|
2462
2504
|
sum_init = "INT2FIX(0)"
|
|
2463
2505
|
p1_body = 'sum = rb_funcall(sum, rb_intern("+"), 1, v)'
|
|
2464
|
-
# mean = sum / n_valid
|
|
2465
|
-
mean_setup = 'VALUE mean =
|
|
2506
|
+
# mean = sum / n_valid, exact for Integer (ca_object_quo)
|
|
2507
|
+
mean_setup = 'VALUE mean = ca_object_quo(sum, LONG2NUM(n_valid));'
|
|
2466
2508
|
# d = v - mean; M2 += d * d; all VALUE arithmetic.
|
|
2467
2509
|
p2_body = <<~C.chomp
|
|
2468
2510
|
VALUE __d = rb_funcall(v, rb_intern("-"), 1, mean);
|
|
@@ -2473,7 +2515,7 @@ module MkKernel
|
|
|
2473
2515
|
# variance = M2 / divisor
|
|
2474
2516
|
# divisor is int (n_valid or n_valid - 1)
|
|
2475
2517
|
var_expr = ->(divisor_expr) {
|
|
2476
|
-
%Q[
|
|
2518
|
+
%Q[ca_object_quo(M2, LONG2NUM(#{divisor_expr}))]
|
|
2477
2519
|
}
|
|
2478
2520
|
out_zero = "INT2FIX(0)"
|
|
2479
2521
|
elsif src == :bool
|
|
@@ -2561,13 +2603,13 @@ module MkKernel
|
|
|
2561
2603
|
# statistic undefined, so the cell is UNDEF: the sample variance of one
|
|
2562
2604
|
# value is 0/0.
|
|
2563
2605
|
|
|
2564
|
-
# Reduce-call
|
|
2606
|
+
# Reduce-call setup. :object keeps the scalar rb_funcall loop
|
|
2565
2607
|
# (CA_SLAB_REDUCE_T_EX). Every other src uses the 8-way accumulator
|
|
2566
2608
|
# split (CA_SLAB_REDUCE_SUM8_EX) driven by function-like EXPR macros,
|
|
2567
2609
|
# defined at file scope with a per-kernel/src-unique name so the P2
|
|
2568
2610
|
# macro's `mean` reference resolves inside the emitted function and no
|
|
2569
2611
|
# preprocessor directive lands inside the heredoc body. This is the
|
|
2570
|
-
# variance/stddev AVX2-regression fix
|
|
2612
|
+
# variance/stddev AVX2-regression fix: GCC won't split the
|
|
2571
2613
|
# pragma-simd FMA reduction into multiple accumulators, so we write the
|
|
2572
2614
|
# split in source (see the CA_SLAB_REDUCE_SUM8_EX header comment).
|
|
2573
2615
|
if src == :object
|
|
@@ -2599,7 +2641,7 @@ module MkKernel
|
|
|
2599
2641
|
static VALUE
|
|
2600
2642
|
#{name}_ki_native_#{src} (VALUE self, CArray *ca, int8_t *slab_axes, int8_t naxes, int keep_axis#{extra_args})
|
|
2601
2643
|
{
|
|
2602
|
-
VALUE
|
|
2644
|
+
volatile VALUE vout = rb_ca_new_reduced(self, slab_axes, naxes, #{oi[:ca]}, keep_axis);
|
|
2603
2645
|
CArray *co;
|
|
2604
2646
|
GetCArray(vout, co);
|
|
2605
2647
|
#{out_c} *op = (#{out_c} *) co->ptr;
|
|
@@ -2662,7 +2704,8 @@ module MkKernel
|
|
|
2662
2704
|
# is the loop interchange's (same reduction kinds, no mask, an alias
|
|
2663
2705
|
# attach); a fiber longer than 32 cells (16 for min / max) goes to the
|
|
2664
2706
|
# general walk, which is already faster than this loop there.
|
|
2665
|
-
def self.emit_reduce_short_fiber(io, k, si, oi, src, reduce_stmt, finish_expr
|
|
2707
|
+
def self.emit_reduce_short_fiber(io, k, si, oi, src, reduce_stmt, finish_expr,
|
|
2708
|
+
multi_finishes: nil)
|
|
2666
2709
|
buf_kinds = %i[plus star min max]
|
|
2667
2710
|
rk = k[:reduction_kind]
|
|
2668
2711
|
if buf_kinds.include?(rk)
|
|
@@ -2680,14 +2723,27 @@ module MkKernel
|
|
|
2680
2723
|
init: resolve_init_expr(k[:init][v], oi, si, src) }
|
|
2681
2724
|
end
|
|
2682
2725
|
|
|
2683
|
-
reduce_sf
|
|
2684
|
-
|
|
2726
|
+
reduce_sf = reduce_stmt.dup
|
|
2727
|
+
finish_sfs = (multi_finishes || [finish_expr]).map(&:dup)
|
|
2685
2728
|
if induction_var
|
|
2686
2729
|
ind_pat = Regexp.escape(induction_var.to_s)
|
|
2687
2730
|
reduce_sf = reduce_sf.gsub(/\b#{ind_pat}\+\+/, "0")
|
|
2688
2731
|
.gsub(/\+\+\b#{ind_pat}\b/, "0")
|
|
2689
|
-
|
|
2690
|
-
end
|
|
2732
|
+
finish_sfs = finish_sfs.map { |f| f.gsub(/\b#{ind_pat}\b/, "((int64_t)__sf_M)") }
|
|
2733
|
+
end
|
|
2734
|
+
# One output, or a pair of them (an outputs: 2 kernel).
|
|
2735
|
+
outs = multi_finishes ? %w[a b] : [nil]
|
|
2736
|
+
vout_decls = outs.map do |o|
|
|
2737
|
+
sfx = o ? "_#{o}" : ""
|
|
2738
|
+
"VALUE vout#{sfx} = rb_ca_new_reduced(self, slab_axes, naxes, #{oi[:ca]}, keep_axis);\n" \
|
|
2739
|
+
" CArray *co#{sfx};\n" \
|
|
2740
|
+
" GetCArray(vout#{sfx}, co#{sfx});\n" \
|
|
2741
|
+
" #{oi[:c]} *op#{sfx} = (#{oi[:c]} *) co#{sfx}->ptr;"
|
|
2742
|
+
end.join("\n ")
|
|
2743
|
+
writes = outs.zip(finish_sfs).map do |o, f|
|
|
2744
|
+
"op#{o ? "_#{o}" : ""}[__sf_o] = (#{oi[:c]}) (#{f});"
|
|
2745
|
+
end.join("\n ")
|
|
2746
|
+
ret = multi_finishes ? "rb_ary_new_from_args(2, vout_a, vout_b)" : "vout"
|
|
2691
2747
|
|
|
2692
2748
|
decls = info.map { |i| "#{i[:c_type]} #{i[:var]} = (#{i[:c_type]}) (#{i[:init]});" }
|
|
2693
2749
|
.join("\n ")
|
|
@@ -2724,11 +2780,8 @@ module MkKernel
|
|
|
2724
2780
|
&& ca_fast_path(CA_SC_SHORT_FIBER_REDUCE) ) {
|
|
2725
2781
|
ca_size_t __sf_M = ca->dim[ca->ndim - 1];
|
|
2726
2782
|
ca_size_t __sf_OUTER = ca->elements / __sf_M;
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
GetCArray(vout, co);
|
|
2730
|
-
#{oi[:c]} *op = (#{oi[:c]} *) co->ptr;
|
|
2731
|
-
ca_attach(ca); /* window: numeric lanes only, nothing raises inside; O(1) alias attach */
|
|
2783
|
+
#{vout_decls}
|
|
2784
|
+
ca_attach(ca); /* attach: numeric lanes only, nothing raises before the detach; O(1) alias attach */
|
|
2732
2785
|
const #{si[:c]} *p_root = (const #{si[:c]} *) ca->ptr;
|
|
2733
2786
|
for ( ca_size_t __sf_o = 0; __sf_o < __sf_OUTER; __sf_o++ ) {
|
|
2734
2787
|
const #{si[:c]} *__sf_row = p_root + __sf_o * __sf_M;
|
|
@@ -2739,16 +2792,17 @@ module MkKernel
|
|
|
2739
2792
|
(void) v;
|
|
2740
2793
|
}
|
|
2741
2794
|
#{nan_fixup}
|
|
2742
|
-
|
|
2795
|
+
#{writes}
|
|
2743
2796
|
}
|
|
2744
2797
|
ca_detach(ca);
|
|
2745
|
-
return
|
|
2798
|
+
return #{ret};
|
|
2746
2799
|
}
|
|
2747
2800
|
C
|
|
2748
2801
|
end
|
|
2749
2802
|
|
|
2750
2803
|
def self.emit_reduce_loop_interchange(io, k, si, oi, ruby_wrap, src,
|
|
2751
|
-
acc_var, acc_init, reduce_stmt, finish_expr
|
|
2804
|
+
acc_var, acc_init, reduce_stmt, finish_expr,
|
|
2805
|
+
multi_finishes: nil)
|
|
2752
2806
|
# Classify state vars by reduction_kind:
|
|
2753
2807
|
# :plus / :star / :min / :max -> per-cell out_buf (one buffer per var)
|
|
2754
2808
|
# :induction -> precomputed scalar (__li_M), drop ++
|
|
@@ -2772,12 +2826,13 @@ module MkKernel
|
|
|
2772
2826
|
end
|
|
2773
2827
|
|
|
2774
2828
|
# Substitute each plus var -> buf_<var>[__j] in reduce + finish.
|
|
2775
|
-
|
|
2776
|
-
|
|
2829
|
+
# An outputs: 2 kernel (multi_finishes) writes one output per finish.
|
|
2830
|
+
reduce_li = reduce_stmt.dup
|
|
2831
|
+
finish_lis = (multi_finishes || [finish_expr]).map(&:dup)
|
|
2777
2832
|
plus_info.each do |pi|
|
|
2778
2833
|
pat = /\b#{Regexp.escape(pi[:var].to_s)}\b/
|
|
2779
|
-
reduce_li
|
|
2780
|
-
|
|
2834
|
+
reduce_li = reduce_li.gsub(pat, "#{pi[:buf]}[__j]")
|
|
2835
|
+
finish_lis = finish_lis.map { |f| f.gsub(pat, "#{pi[:buf]}[__j]") }
|
|
2781
2836
|
end
|
|
2782
2837
|
|
|
2783
2838
|
if induction_var
|
|
@@ -2788,10 +2843,10 @@ module MkKernel
|
|
|
2788
2843
|
reduce_li = reduce_li.gsub(/\b#{ind_pat}\+\+/, "0")
|
|
2789
2844
|
.gsub(/\+\+\b#{ind_pat}\b/, "0")
|
|
2790
2845
|
# In finish: cnt -> __li_M (cast to int64_t to match state type).
|
|
2791
|
-
|
|
2846
|
+
finish_lis = finish_lis.map { |f| f.gsub(/\b#{ind_pat}\b/, "((int64_t)__li_M)") }
|
|
2792
2847
|
end
|
|
2793
2848
|
|
|
2794
|
-
#
|
|
2849
|
+
# Tile INNER into L1d-friendly chunks (TILE = 512 f64 cells =
|
|
2795
2850
|
# 4 KiB). Output buffer fits in L1d regardless of INNER size; rows
|
|
2796
2851
|
# read are streaming (= each iteration's row is a fresh contig read).
|
|
2797
2852
|
# Buffer always stack-allocated (no heap path), one per :plus state.
|
|
@@ -2851,21 +2906,17 @@ module MkKernel
|
|
|
2851
2906
|
" }\n"
|
|
2852
2907
|
end.join
|
|
2853
2908
|
|
|
2854
|
-
# The
|
|
2909
|
+
# The tiled core (OUTER / INNER-tile / M nested loops): parametrized by
|
|
2855
2910
|
# the source base pointer, output base pointer, and outer count so it
|
|
2856
2911
|
# can be emitted once for the Tier 1 single-buffer path (entity / alias
|
|
2857
2912
|
# view) and once per parent for the Tier 2 CAStack path. __li_M,
|
|
2858
2913
|
# __li_INNER, __li_TILE, __li_plane_elems and the buffers are shared
|
|
2859
2914
|
# C scope, so only the three operands vary.
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
ca_size_t __li_tile_len = (__li_INNER - __li_tile < __li_TILE)
|
|
2866
|
-
? (__li_INNER - __li_tile) : __li_TILE;
|
|
2867
|
-
#{init_loops.rstrip}
|
|
2868
|
-
for ( ca_size_t __li_i = 0; __li_i < __li_M; __li_i++ ) {
|
|
2915
|
+
# The M loop. An outputs: 2 kernel keeps two buffers, so a cell costs
|
|
2916
|
+
# two buffer loads and stores; it folds four rows per pass over the
|
|
2917
|
+
# tile, which keeps the buffers in registers across them.
|
|
2918
|
+
one_row = <<~C.rstrip
|
|
2919
|
+
for ( ; __li_i < __li_M; __li_i++ ) {
|
|
2869
2920
|
const #{si[:c]} *__li_row = __li_plane + __li_i * __li_INNER + __li_tile;
|
|
2870
2921
|
_Pragma("omp simd")
|
|
2871
2922
|
for ( ca_size_t __j = 0; __j < __li_tile_len; __j++ ) {
|
|
@@ -2874,20 +2925,90 @@ module MkKernel
|
|
|
2874
2925
|
(void) v;
|
|
2875
2926
|
}
|
|
2876
2927
|
}
|
|
2928
|
+
C
|
|
2929
|
+
rows_loop =
|
|
2930
|
+
if multi_finishes
|
|
2931
|
+
four = (0..3).map { |r| "{ #{si[:c]} v = __li_row#{r}[__j]; #{reduce_li}; (void) v; }" }
|
|
2932
|
+
.join("\n" + " " * 24)
|
|
2933
|
+
<<~C.rstrip
|
|
2934
|
+
ca_size_t __li_i = 0;
|
|
2935
|
+
for ( ; __li_i + 4 <= __li_M; __li_i += 4 ) {
|
|
2936
|
+
const #{si[:c]} *__li_row0 = __li_plane + __li_i * __li_INNER + __li_tile;
|
|
2937
|
+
const #{si[:c]} *__li_row1 = __li_row0 + __li_INNER;
|
|
2938
|
+
const #{si[:c]} *__li_row2 = __li_row1 + __li_INNER;
|
|
2939
|
+
const #{si[:c]} *__li_row3 = __li_row2 + __li_INNER;
|
|
2940
|
+
_Pragma("omp simd")
|
|
2941
|
+
for ( ca_size_t __j = 0; __j < __li_tile_len; __j++ ) {
|
|
2942
|
+
#{four}
|
|
2943
|
+
}
|
|
2944
|
+
}
|
|
2945
|
+
#{one_row}
|
|
2946
|
+
C
|
|
2947
|
+
else
|
|
2948
|
+
" ca_size_t __li_i = 0;\n" + one_row
|
|
2949
|
+
end
|
|
2950
|
+
|
|
2951
|
+
core = lambda do |pr, opv, outer|
|
|
2952
|
+
writes = Array(opv).zip(finish_lis).map do |o, f|
|
|
2953
|
+
"#{o}[__li_o * __li_INNER + __li_tile + __j] = (#{oi[:c]}) (#{f});"
|
|
2954
|
+
end.join("\n" + " " * 22)
|
|
2955
|
+
<<~C.rstrip
|
|
2956
|
+
for ( ca_size_t __li_o = 0; __li_o < #{outer}; __li_o++ ) {
|
|
2957
|
+
const #{si[:c]} *__li_plane = #{pr} + __li_o * __li_plane_elems;
|
|
2958
|
+
for ( ca_size_t __li_tile = 0; __li_tile < __li_INNER; __li_tile += __li_TILE ) {
|
|
2959
|
+
ca_size_t __li_tile_len = (__li_INNER - __li_tile < __li_TILE)
|
|
2960
|
+
? (__li_INNER - __li_tile) : __li_TILE;
|
|
2961
|
+
#{init_loops.rstrip}
|
|
2962
|
+
#{rows_loop}
|
|
2877
2963
|
#{li_nan_fixup.call("__li_INNER")}
|
|
2878
2964
|
for ( ca_size_t __j = 0; __j < __li_tile_len; __j++ ) {
|
|
2879
|
-
#{
|
|
2965
|
+
#{writes}
|
|
2880
2966
|
}
|
|
2881
2967
|
}
|
|
2882
2968
|
}
|
|
2883
2969
|
C
|
|
2884
2970
|
end
|
|
2885
2971
|
|
|
2972
|
+
if multi_finishes
|
|
2973
|
+
# outputs: 2: the Tier 1 path only (an entity or a contiguous alias
|
|
2974
|
+
# view), into a pair of reduced arrays.
|
|
2975
|
+
io.puts <<~C
|
|
2976
|
+
if ( naxes == 1
|
|
2977
|
+
&& slab_axes[0] != (int8_t)(ca->ndim - 1)
|
|
2978
|
+
&& ! ca_has_mask(ca)
|
|
2979
|
+
&& ca_attach_is_alias(ca)
|
|
2980
|
+
&& ca_fast_path(CA_SC_LOOP_INTERCHANGE) ) {
|
|
2981
|
+
int8_t __li_ax = slab_axes[0];
|
|
2982
|
+
ca_size_t __li_M = ca->dim[__li_ax];
|
|
2983
|
+
ca_size_t __li_INNER = 1;
|
|
2984
|
+
for ( int8_t __k = (int8_t)(__li_ax + 1); __k < ca->ndim; __k++ ) __li_INNER *= ca->dim[__k];
|
|
2985
|
+
ca_size_t __li_OUTER = 1;
|
|
2986
|
+
for ( int8_t __k = 0; __k < __li_ax; __k++ ) __li_OUTER *= ca->dim[__k];
|
|
2987
|
+
if ( __li_INNER >= 64 && __li_M * __li_INNER >= 1024 ) {
|
|
2988
|
+
volatile VALUE vout_a = rb_ca_new_reduced(self, slab_axes, naxes, #{oi[:ca]}, keep_axis);
|
|
2989
|
+
volatile VALUE vout_b = rb_ca_new_reduced(self, slab_axes, naxes, #{oi[:ca]}, keep_axis);
|
|
2990
|
+
CArray *co_a, *co_b;
|
|
2991
|
+
GetCArray(vout_a, co_a);
|
|
2992
|
+
GetCArray(vout_b, co_b);
|
|
2993
|
+
#{oi[:c]} *op_a = (#{oi[:c]} *) co_a->ptr;
|
|
2994
|
+
#{oi[:c]} *op_b = (#{oi[:c]} *) co_b->ptr;
|
|
2995
|
+
ca_attach(ca); /* attach: numeric lanes only, nothing raises before the detach; O(1) alias attach */
|
|
2996
|
+
const #{si[:c]} *p_root = (const #{si[:c]} *) ca->ptr;
|
|
2997
|
+
#{buf_decls.rstrip}
|
|
2998
|
+
ca_size_t __li_plane_elems = __li_M * __li_INNER;
|
|
2999
|
+
const ca_size_t __li_TILE = 512;
|
|
3000
|
+
#{core.call("p_root", %w[op_a op_b], "__li_OUTER")}
|
|
3001
|
+
ca_detach(ca);
|
|
3002
|
+
return rb_ary_new_from_args(2, vout_a, vout_b);
|
|
3003
|
+
}
|
|
3004
|
+
}
|
|
3005
|
+
C
|
|
3006
|
+
return
|
|
3007
|
+
end
|
|
3008
|
+
|
|
2886
3009
|
io.puts <<~C
|
|
2887
|
-
/*
|
|
2888
|
-
(
|
|
2889
|
-
MEMO_REDUCTION_FASTPATH_ENTITY_ONLY_GUARD Tier 1: extend from
|
|
2890
|
-
entity-only to any contig row-major buffer. ca_attach_is_alias
|
|
3010
|
+
/* Loop-interchange fast path with inner-tiling, for any contig
|
|
3011
|
+
row-major buffer (not only an entity). ca_attach_is_alias
|
|
2891
3012
|
is true for CA_OBJ_ARRAY and for CAStride-family views whose
|
|
2892
3013
|
composed strides are row-major contiguous (CARefer reshape,
|
|
2893
3014
|
contig CABlock, CAFarray, alias CAStride, ...); ca_attach then
|
|
@@ -2906,11 +3027,11 @@ module MkKernel
|
|
|
2906
3027
|
|
|
2907
3028
|
/* Threshold gate: skip when too small to amortise alloc + 2-pass overhead. */
|
|
2908
3029
|
if ( __li_INNER >= 64 && __li_M * __li_INNER >= 1024 ) {
|
|
2909
|
-
VALUE
|
|
3030
|
+
volatile VALUE vout = rb_ca_new_reduced(self, slab_axes, naxes, #{oi[:ca]}, keep_axis);
|
|
2910
3031
|
CArray *co;
|
|
2911
3032
|
GetCArray(vout, co);
|
|
2912
3033
|
#{oi[:c]} *op = (#{oi[:c]} *) co->ptr;
|
|
2913
|
-
ca_attach(ca); /*
|
|
3034
|
+
ca_attach(ca); /* attach: numeric lanes only, nothing raises before the detach; O(1) alias attach */
|
|
2914
3035
|
const #{si[:c]} *p_root = (const #{si[:c]} *) ca->ptr;
|
|
2915
3036
|
|
|
2916
3037
|
/* Per-buffer stack accumulators (one per :plus state, sized
|
|
@@ -2927,13 +3048,13 @@ module MkKernel
|
|
|
2927
3048
|
}
|
|
2928
3049
|
}
|
|
2929
3050
|
|
|
2930
|
-
/*
|
|
3051
|
+
/* CAStack source.
|
|
2931
3052
|
view.reduce(axis: ax>=1) is exactly K independent per-parent
|
|
2932
3053
|
reduces over (ax - 1) of each contiguous parent; output row k
|
|
2933
|
-
= parent k's reduced plane. Run the
|
|
3054
|
+
= parent k's reduced plane. Run the tiled core per parent (each
|
|
2934
3055
|
attach is O(1) for entity parents), no whole-view materialise.
|
|
2935
3056
|
|
|
2936
|
-
|
|
3057
|
+
Gated to k_axis == 0
|
|
2937
3058
|
because the per-parent output layout in dst assumes K is the
|
|
2938
3059
|
outermost output axis (= each parent contributes a contiguous
|
|
2939
3060
|
block of parent_OUTER * parent_INNER cells). For k_axis != 0
|
|
@@ -2964,7 +3085,7 @@ module MkKernel
|
|
|
2964
3085
|
}
|
|
2965
3086
|
|
|
2966
3087
|
if ( __li_ok && __li_INNER >= 64 && __li_M * __li_INNER >= 1024 ) {
|
|
2967
|
-
VALUE
|
|
3088
|
+
volatile VALUE vout = rb_ca_new_reduced(self, slab_axes, naxes, #{oi[:ca]}, keep_axis);
|
|
2968
3089
|
CArray *co;
|
|
2969
3090
|
GetCArray(vout, co);
|
|
2970
3091
|
#{oi[:c]} *op = (#{oi[:c]} *) co->ptr;
|
|
@@ -2975,7 +3096,7 @@ module MkKernel
|
|
|
2975
3096
|
ca_size_t __li_parent_out = __li_OUTER * __li_INNER;
|
|
2976
3097
|
const ca_size_t __li_TILE = 512;
|
|
2977
3098
|
for ( int32_t __kk = 0; __kk < __li_st->n_parents; __kk++ ) {
|
|
2978
|
-
ca_attach(__li_st->parents[__kk]); /*
|
|
3099
|
+
ca_attach(__li_st->parents[__kk]); /* attach: a parent may run Ruby to fill itself (a CAObject's copy_data); a raising attach holds nothing and the earlier parents are already detached, and the numeric loop after it does not raise */
|
|
2979
3100
|
const #{si[:c]} *p_root = (const #{si[:c]} *) __li_st->parents[__kk]->ptr;
|
|
2980
3101
|
#{oi[:c]} *__li_op_k = op + (ca_size_t) __kk * __li_parent_out;
|
|
2981
3102
|
#{core.call("p_root", "__li_op_k", "__li_OUTER")}
|
|
@@ -2986,8 +3107,7 @@ module MkKernel
|
|
|
2986
3107
|
}
|
|
2987
3108
|
}
|
|
2988
3109
|
|
|
2989
|
-
/*
|
|
2990
|
-
Tier 2 fast path for CAStack with k_axis > 0, covering two
|
|
3110
|
+
/* Fast path for CAStack with k_axis > 0, covering two
|
|
2991
3111
|
structurally-equivalent cases:
|
|
2992
3112
|
|
|
2993
3113
|
M.1 ax > k_axis parent INNER all post-K in output
|
|
@@ -3033,7 +3153,7 @@ module MkKernel
|
|
|
3033
3153
|
}
|
|
3034
3154
|
|
|
3035
3155
|
if ( __li_ok && __li_INNER >= 64 && __li_M * __li_INNER >= 1024 ) {
|
|
3036
|
-
VALUE
|
|
3156
|
+
volatile VALUE vout = rb_ca_new_reduced(self, slab_axes, naxes, #{oi[:ca]}, keep_axis);
|
|
3037
3157
|
CArray *co;
|
|
3038
3158
|
GetCArray(vout, co);
|
|
3039
3159
|
#{oi[:c]} *op = (#{oi[:c]} *) co->ptr;
|
|
@@ -3070,7 +3190,7 @@ module MkKernel
|
|
|
3070
3190
|
ca_size_t __li_plane_elems = __li_M * __li_INNER;
|
|
3071
3191
|
const ca_size_t __li_TILE = 512;
|
|
3072
3192
|
for ( int32_t __kk = 0; __kk < __li_st->n_parents; __kk++ ) {
|
|
3073
|
-
ca_attach(__li_st->parents[__kk]); /*
|
|
3193
|
+
ca_attach(__li_st->parents[__kk]); /* attach: a parent may run Ruby to fill itself (a CAObject's copy_data); a raising attach holds nothing and the earlier parents are already detached, and the numeric loop after it does not raise */
|
|
3074
3194
|
const #{si[:c]} *p_root = (const #{si[:c]} *) __li_st->parents[__kk]->ptr;
|
|
3075
3195
|
ca_size_t __li_k_base = (ca_size_t) __kk * __li_k_stride;
|
|
3076
3196
|
|
|
@@ -3100,7 +3220,7 @@ module MkKernel
|
|
|
3100
3220
|
}
|
|
3101
3221
|
#{li_nan_fixup.call("__li_INNER")}
|
|
3102
3222
|
for ( ca_size_t __j = 0; __j < __li_tile_len; __j++ ) {
|
|
3103
|
-
__li_op_k[__li_tile + __j] = (#{oi[:c]}) (#{
|
|
3223
|
+
__li_op_k[__li_tile + __j] = (#{oi[:c]}) (#{finish_lis[0]});
|
|
3104
3224
|
}
|
|
3105
3225
|
}
|
|
3106
3226
|
/* Carry-increment OUTER multi-index (row-major over parent PRE dims). */
|
|
@@ -3116,14 +3236,13 @@ module MkKernel
|
|
|
3116
3236
|
}
|
|
3117
3237
|
}
|
|
3118
3238
|
|
|
3119
|
-
/* M.
|
|
3120
|
-
Case M.2b (ax < k_axis - 1): parent INNER axes are split by K
|
|
3239
|
+
/* Case M.2b (ax < k_axis - 1): parent INNER axes are split by K
|
|
3121
3240
|
in the output. Strategy C (effective OUTER expansion): treat
|
|
3122
3241
|
INNER_pre_K dims (parent dims [pa+1..k_axis-1]) as part of an
|
|
3123
3242
|
extended effective OUTER, and use effective INNER = parent dims
|
|
3124
3243
|
[k_axis..pndim-1] (= INNER_post_K, contig at output tail).
|
|
3125
3244
|
|
|
3126
|
-
|
|
3245
|
+
Tiled core variant: M-step stride in parent = full parent INNER
|
|
3127
3246
|
total (= Π pdim[pa+1..pndim-1]), separate from the tile loop
|
|
3128
3247
|
bound (= eff_INNER). Inner read stride 1 in parent + output
|
|
3129
3248
|
write stride 1 (= contig output tail) both preserved -> SIMD
|
|
@@ -3135,15 +3254,14 @@ module MkKernel
|
|
|
3135
3254
|
= 2.38x slow. Root cause is the multi-parent data layout
|
|
3136
3255
|
(= 5 separate 9 MB regions instead of one contig 46 MB),
|
|
3137
3256
|
which costs DRAM/TLB/prefetcher efficiency irrespective of
|
|
3138
|
-
strategy. Strategy A (temp buf + scatter
|
|
3139
|
-
|
|
3257
|
+
strategy. Strategy A (temp buf + scatter)
|
|
3258
|
+
was implemented and benched at 3783 us
|
|
3140
3259
|
= within noise of Strategy C, confirming the bottleneck is
|
|
3141
3260
|
structural, NOT cache-stride from this branch. Strategy C
|
|
3142
|
-
is shipped here (= simpler emit, no malloc)
|
|
3143
|
-
sparring decision; the 3.94x win vs generic fallback
|
|
3261
|
+
is shipped here (= simpler emit, no malloc); the 3.94x win vs generic fallback
|
|
3144
3262
|
(.copy.sum at 14872 us) justifies landing despite missing
|
|
3145
|
-
eager-entity parity. Strategy A
|
|
3146
|
-
|
|
3263
|
+
eager-entity parity. Strategy A remains a possible later
|
|
3264
|
+
optimization (= multi-level tile-M + tile-
|
|
3147
3265
|
INNER could reclaim DRAM efficiency if revisited).
|
|
3148
3266
|
|
|
3149
3267
|
Threshold eff_INNER >= 32 auto-bypasses at = -1 (k_axis =
|
|
@@ -3178,7 +3296,7 @@ module MkKernel
|
|
|
3178
3296
|
}
|
|
3179
3297
|
|
|
3180
3298
|
if ( __li_ok && __li_eff_INNER >= 32 && __li_M * __li_eff_INNER >= 1024 ) {
|
|
3181
|
-
VALUE
|
|
3299
|
+
volatile VALUE vout = rb_ca_new_reduced(self, slab_axes, naxes, #{oi[:ca]}, keep_axis);
|
|
3182
3300
|
CArray *co;
|
|
3183
3301
|
GetCArray(vout, co);
|
|
3184
3302
|
#{oi[:c]} *op = (#{oi[:c]} *) co->ptr;
|
|
@@ -3228,7 +3346,7 @@ module MkKernel
|
|
|
3228
3346
|
|
|
3229
3347
|
const ca_size_t __li_TILE = 512;
|
|
3230
3348
|
for ( int32_t __kk = 0; __kk < __li_st->n_parents; __kk++ ) {
|
|
3231
|
-
ca_attach(__li_st->parents[__kk]); /*
|
|
3349
|
+
ca_attach(__li_st->parents[__kk]); /* attach: a parent may run Ruby to fill itself (a CAObject's copy_data); a raising attach holds nothing and the earlier parents are already detached, and the numeric loop after it does not raise */
|
|
3232
3350
|
const #{si[:c]} *p_root = (const #{si[:c]} *) __li_st->parents[__kk]->ptr;
|
|
3233
3351
|
ca_size_t __li_k_base = (ca_size_t) __kk * __li_k_stride;
|
|
3234
3352
|
|
|
@@ -3244,7 +3362,7 @@ module MkKernel
|
|
|
3244
3362
|
}
|
|
3245
3363
|
#{oi[:c]} *__li_op_k = op + __li_obase;
|
|
3246
3364
|
const #{si[:c]} *__li_plane = p_root + __li_pbase;
|
|
3247
|
-
/*
|
|
3365
|
+
/* Tiled core variant: M-step uses __li_M_stride, tile loop uses __li_eff_INNER. */
|
|
3248
3366
|
for ( ca_size_t __li_tile = 0; __li_tile < __li_eff_INNER; __li_tile += __li_TILE ) {
|
|
3249
3367
|
ca_size_t __li_tile_len = (__li_eff_INNER - __li_tile < __li_TILE)
|
|
3250
3368
|
? (__li_eff_INNER - __li_tile) : __li_TILE;
|
|
@@ -3260,7 +3378,7 @@ module MkKernel
|
|
|
3260
3378
|
}
|
|
3261
3379
|
#{li_nan_fixup.call("__li_M_stride")}
|
|
3262
3380
|
for ( ca_size_t __j = 0; __j < __li_tile_len; __j++ ) {
|
|
3263
|
-
__li_op_k[__li_tile + __j] = (#{oi[:c]}) (#{
|
|
3381
|
+
__li_op_k[__li_tile + __j] = (#{oi[:c]}) (#{finish_lis[0]});
|
|
3264
3382
|
}
|
|
3265
3383
|
}
|
|
3266
3384
|
/* Carry-increment effective OUTER multi-index. */
|
|
@@ -3278,12 +3396,12 @@ module MkKernel
|
|
|
3278
3396
|
C
|
|
3279
3397
|
end
|
|
3280
3398
|
|
|
3281
|
-
#
|
|
3282
|
-
#
|
|
3283
|
-
#
|
|
3284
|
-
# Scope
|
|
3399
|
+
# Multi-output (outputs: 2) reduce emitter. Allocates 2 output CArrays,
|
|
3400
|
+
# writes both inside the slab loop, returns a Ruby Array [out1, out2]
|
|
3401
|
+
# (`[min, max]` for minmax).
|
|
3402
|
+
# Scope:
|
|
3285
3403
|
# - 2 outputs only (= asserted by reduce DSL validation)
|
|
3286
|
-
# - mask_policy: nil or :min_count (
|
|
3404
|
+
# - mask_policy: nil or :min_count (the latter propagates the
|
|
3287
3405
|
# input mask to both output cells with identical bits since both
|
|
3288
3406
|
# reductions consume the same slab)
|
|
3289
3407
|
# - no streaming / view_flat / array_arg / value_arg
|
|
@@ -3323,8 +3441,22 @@ module MkKernel
|
|
|
3323
3441
|
static VALUE
|
|
3324
3442
|
#{name}_ki_native_#{src} (VALUE self, CArray *ca, int8_t *slab_axes, int8_t naxes, int keep_axis#{extra_args})
|
|
3325
3443
|
{
|
|
3326
|
-
|
|
3327
|
-
|
|
3444
|
+
C
|
|
3445
|
+
# Loop interchange for a reduction along a non-innermost axis, where
|
|
3446
|
+
# every state is a :plus sum (sum_parts).
|
|
3447
|
+
rk = k[:reduction_kind]
|
|
3448
|
+
if rk.is_a?(Hash) && rk.keys.sort == k[:state].keys.sort && rk.values.all?(:plus) &&
|
|
3449
|
+
src != :object
|
|
3450
|
+
io.puts " if ( naxes != 1 || ! ca_too_few_present(ca->dim[slab_axes[0]], min_count, 0) ) {" if min_count
|
|
3451
|
+
emit_reduce_loop_interchange(io, k, si, oi, ruby_wrap, src, acc_var, acc_init,
|
|
3452
|
+
reduce_stmt, nil, multi_finishes: finish_exprs)
|
|
3453
|
+
emit_reduce_short_fiber(io, k, si, oi, src, reduce_stmt, nil,
|
|
3454
|
+
multi_finishes: finish_exprs)
|
|
3455
|
+
io.puts " }" if min_count
|
|
3456
|
+
end
|
|
3457
|
+
io.puts <<~C
|
|
3458
|
+
volatile VALUE vout_a = rb_ca_new_reduced(self, slab_axes, naxes, #{oi[:ca]}, keep_axis);
|
|
3459
|
+
volatile VALUE vout_b = rb_ca_new_reduced(self, slab_axes, naxes, #{oi[:ca]}, keep_axis);
|
|
3328
3460
|
CArray *co_a, *co_b;
|
|
3329
3461
|
GetCArray(vout_a, co_a);
|
|
3330
3462
|
GetCArray(vout_b, co_b);
|
|
@@ -3354,7 +3486,7 @@ module MkKernel
|
|
|
3354
3486
|
emit_all_nan_fixup(io, k, src, si, limit_init_state_vars(k, si, oi, src),
|
|
3355
3487
|
"masked_cnt < st.slab_elements", indent: " ")
|
|
3356
3488
|
end
|
|
3357
|
-
trigger = "ca_too_few_present(st.slab_elements - masked_cnt, min_count, 1)"
|
|
3489
|
+
trigger = "ca_too_few_present(st.slab_elements - masked_cnt, min_count, #{k[:identity_on_empty] ? 0 : 1})"
|
|
3358
3490
|
io.puts " if ( #{trigger} ) {"
|
|
3359
3491
|
io.puts " if ( ! op_mask_a ) {"
|
|
3360
3492
|
io.puts " ca_create_mask(co_a);"
|
|
@@ -3392,11 +3524,11 @@ module MkKernel
|
|
|
3392
3524
|
# UNDEF, still as a pair -- the shape of the answer does not depend on
|
|
3393
3525
|
# the data. (Both op_mask_a and op_mask_b share the same bit since
|
|
3394
3526
|
# both reductions consume the same slab, so checking _a is sufficient.)
|
|
3395
|
-
io.puts " if ( op_mask_a && op_mask_a[0] ) return
|
|
3527
|
+
io.puts " if ( op_mask_a && op_mask_a[0] ) return rb_ary_new_from_args(2, CA_UNDEF, CA_UNDEF);"
|
|
3396
3528
|
end
|
|
3397
|
-
io.puts " return
|
|
3529
|
+
io.puts " return rb_ary_new_from_args(2, #{ruby_wrap}(op_a[0]), #{ruby_wrap}(op_b[0]));"
|
|
3398
3530
|
io.puts " }"
|
|
3399
|
-
io.puts " return
|
|
3531
|
+
io.puts " return rb_ary_new_from_args(2, vout_a, vout_b);"
|
|
3400
3532
|
io.puts " }"
|
|
3401
3533
|
end
|
|
3402
3534
|
|
|
@@ -3459,7 +3591,7 @@ module MkKernel
|
|
|
3459
3591
|
# all-NaN fix-up, streaming variant. The other two paths confirm a
|
|
3460
3592
|
# suspicious answer by re-reading the data; here re-reading means
|
|
3461
3593
|
# evaluating the lazy chain a second time, so the flag rides along in
|
|
3462
|
-
# the chunk loop instead. The loop already
|
|
3594
|
+
# the chunk loop instead. The loop already does the work of producing each
|
|
3463
3595
|
# cell, which is what makes one more compare affordable here and not
|
|
3464
3596
|
# in the tiled core.
|
|
3465
3597
|
all_nan_stream = k[:all_nan_result] == :nan && FLOAT_DTYPES.include?(src)
|
|
@@ -3593,11 +3725,37 @@ module MkKernel
|
|
|
3593
3725
|
# rb_ca_count, future cross-file callers) can forward-declare and
|
|
3594
3726
|
# call directly via C entry instead of going through Ruby method
|
|
3595
3727
|
# dispatch. Native helpers above remain static (per-src specialised).
|
|
3596
|
-
|
|
3597
|
-
|
|
3728
|
+
if k[:integer_total]
|
|
3729
|
+
# An integer array goes to ca_integer_total, which runs the wrapping
|
|
3730
|
+
# integer fold and, where the total may be out of range, this
|
|
3731
|
+
# kernel's own float64 fold (the _general function below).
|
|
3732
|
+
general = "rb_ca_#{name}_ki_general"
|
|
3733
|
+
io.puts "VALUE rb_ca_#{k[:integer_total]}_ki (int argc, VALUE *argv, volatile VALUE self);"
|
|
3734
|
+
io.puts "static VALUE #{general} (int argc, VALUE *argv, volatile VALUE self);"
|
|
3735
|
+
io.puts
|
|
3736
|
+
io.puts "VALUE"
|
|
3737
|
+
io.puts "rb_ca_#{name}_ki (int argc, VALUE *argv, volatile VALUE self)"
|
|
3738
|
+
io.puts "{"
|
|
3739
|
+
io.puts " CArray *src;"
|
|
3740
|
+
io.puts " GetCArray(self, src);"
|
|
3741
|
+
emit_reduce_bool_as(io, k[:bool_as]) if k[:bool_as]
|
|
3742
|
+
io.puts " if ( ca_is_integer_type(src) && ! ca_is_face(src) ) {"
|
|
3743
|
+
io.puts " return ca_integer_total(argc, argv, self, #{general},"
|
|
3744
|
+
io.puts " rb_ca_#{k[:integer_total]}_ki, CA_INTEGER_TOTAL_#{name.to_s.upcase});"
|
|
3745
|
+
io.puts " }"
|
|
3746
|
+
io.puts " return #{general}(argc, argv, self);"
|
|
3747
|
+
io.puts "}"
|
|
3748
|
+
io.puts
|
|
3749
|
+
io.puts "static VALUE"
|
|
3750
|
+
io.puts "#{general} (int argc, VALUE *argv, volatile VALUE self)"
|
|
3751
|
+
else
|
|
3752
|
+
io.puts "VALUE"
|
|
3753
|
+
io.puts "rb_ca_#{name}_ki (int argc, VALUE *argv, volatile VALUE self)"
|
|
3754
|
+
end
|
|
3598
3755
|
io.puts "{"
|
|
3599
3756
|
io.puts " CArray *src;"
|
|
3600
3757
|
io.puts " GetCArray(self, src);"
|
|
3758
|
+
emit_reduce_bool_as(io, k[:bool_as]) if k[:bool_as] && ! k[:integer_total]
|
|
3601
3759
|
|
|
3602
3760
|
if k[:object_escape]
|
|
3603
3761
|
# CA_OBJECT escape: the Ruby composition helper gets the original
|
|
@@ -3620,26 +3778,33 @@ module MkKernel
|
|
|
3620
3778
|
emit_reduce_face_gate(io, name, k[:face_gate] == :relift)
|
|
3621
3779
|
end
|
|
3622
3780
|
|
|
3623
|
-
#
|
|
3624
|
-
# pop trailing kwargs hash exactly once. axis: lives in this hash
|
|
3781
|
+
# Pop trailing kwargs hash exactly once. axis: lives in this hash
|
|
3625
3782
|
# along with min_count: / fill_value:. Positional args carry weights
|
|
3626
|
-
# (array_arg) and value (value_arg) only.
|
|
3627
|
-
#
|
|
3783
|
+
# (array_arg) and value (value_arg) only. There is no variadic axis
|
|
3784
|
+
# form.
|
|
3628
3785
|
io.puts " volatile VALUE ropt = rb_pop_options(&argc, &argv);"
|
|
3629
3786
|
# PoC scan-merge: scan every accepted option key in a single
|
|
3630
3787
|
# rb_scan_options call up front, instead of a second scan in the
|
|
3631
3788
|
# min_count section below. Variables for the later sections are
|
|
3632
3789
|
# declared here and consumed where they are needed.
|
|
3633
3790
|
if min_count
|
|
3634
|
-
io.puts "
|
|
3791
|
+
io.puts " VALUE raxis = Qnil, rkeep_axis = Qnil, rmin_count = Qnil, rfval = Qnil;"
|
|
3635
3792
|
io.puts " rb_scan_options(ropt, \"axis,keep_axis,min_count,fill_value\", &raxis, &rkeep_axis, &rmin_count, &rfval);"
|
|
3636
3793
|
else
|
|
3637
|
-
io.puts "
|
|
3794
|
+
io.puts " VALUE raxis = Qnil, rkeep_axis = Qnil;"
|
|
3638
3795
|
io.puts " rb_scan_options(ropt, \"axis,keep_axis\", &raxis, &rkeep_axis);"
|
|
3639
3796
|
end
|
|
3640
|
-
io.puts " int keep_axis =
|
|
3797
|
+
io.puts " int keep_axis = ca_bool_arg(rkeep_axis, \"keep_axis\");"
|
|
3641
3798
|
io.puts " int8_t slab_axes[CA_RANK_MAX];"
|
|
3642
3799
|
io.puts " int8_t naxes = rb_ca_parse_reduce_axes_kw(raxis, src, slab_axes);"
|
|
3800
|
+
if has_aarg
|
|
3801
|
+
# UNDEF is no weight: it marks a missing cell where a value is
|
|
3802
|
+
# written, and a weight is not written. A masked weight is a masked
|
|
3803
|
+
# array (a one-element array included).
|
|
3804
|
+
io.puts " if ( argc >= 1 && argv[0] == CA_UNDEF ) {"
|
|
3805
|
+
io.puts %Q[ rb_raise(rb_eTypeError, "%s: UNDEF can't be coerced into Float", ca_calling_method_name());]
|
|
3806
|
+
io.puts " }"
|
|
3807
|
+
end
|
|
3643
3808
|
if k[:object_escape]
|
|
3644
3809
|
io.puts " if ( src->data_type == CA_OBJECT ) {"
|
|
3645
3810
|
if min_count
|
|
@@ -3659,17 +3824,21 @@ module MkKernel
|
|
|
3659
3824
|
# legacy source-type storage. waca is the CA_* constant the three
|
|
3660
3825
|
# materialization sites (W-A1 / W-A4 / W-A3) allocate/wrap against, and
|
|
3661
3826
|
# must agree with the T_W the reduce macro reads (double for :promote).
|
|
3662
|
-
waca = (k[:array_arg][:data_type]
|
|
3663
|
-
#
|
|
3664
|
-
#
|
|
3827
|
+
waca = { promote: "CA_FLOAT64", int64: "CA_INT64" }.fetch(k[:array_arg][:data_type], "src->data_type")
|
|
3828
|
+
# Weights are accepted in 3 forms (W-A1 scalar / W-A4 shape of the
|
|
3829
|
+
# reduced axes / W-A3
|
|
3665
3830
|
# full per-element). W-A1 / W-A4 are materialized to W-A3 form
|
|
3666
|
-
# at dispatch (= simple, uniform kernel path).
|
|
3667
|
-
# mirrors PROPOSAL_LINEAR_INTERP_PER_FIBER_MATCHED rev5 in spirit.
|
|
3831
|
+
# at dispatch (= simple, uniform kernel path).
|
|
3668
3832
|
io.puts " if ( argc < 1 ) {"
|
|
3669
3833
|
io.puts %Q[ rb_raise(rb_eArgError, "%s: missing weights argument (1+ required, got 0)", ca_calling_method_name());]
|
|
3670
3834
|
io.puts " }"
|
|
3671
3835
|
io.puts " volatile VALUE rweights = argv[0];"
|
|
3672
3836
|
io.puts " argc--; argv++;"
|
|
3837
|
+
# nil is no weight. The cell-value refusal it would reach below
|
|
3838
|
+
# suggests UNDEF to mask a cell, which is not what a weight asks.
|
|
3839
|
+
io.puts " if ( NIL_P(rweights) ) {"
|
|
3840
|
+
io.puts %Q[ rb_raise(rb_eTypeError, "%s: nil is not a weight; give a number, or a CArray of weights", ca_calling_method_name());]
|
|
3841
|
+
io.puts " }"
|
|
3673
3842
|
# A CScalar is a scalar weight. Any other array, one with a single
|
|
3674
3843
|
# element included, is held to the shape rules below.
|
|
3675
3844
|
io.puts " if ( rb_obj_is_carray(rweights) ) {"
|
|
@@ -3751,7 +3920,7 @@ module MkKernel
|
|
|
3751
3920
|
wio.puts " if ( ca_has_mask(cv) ) {"
|
|
3752
3921
|
wio.puts " ca_create_mask(cw);"
|
|
3753
3922
|
wio.puts " }"
|
|
3754
|
-
wio.puts " ca_attach(cv); /*
|
|
3923
|
+
wio.puts " ca_attach(cv); /* attach: nothing raises before the detach */"
|
|
3755
3924
|
wio.puts " {"
|
|
3756
3925
|
wio.puts " ca_size_t idx[CA_RANK_MAX], wstep[CA_RANK_MAX];"
|
|
3757
3926
|
wio.puts " ca_size_t step = 1;"
|
|
@@ -3797,12 +3966,12 @@ module MkKernel
|
|
|
3797
3966
|
wio.puts " }"
|
|
3798
3967
|
# Attached last, after the overlay's copy of the source (which can
|
|
3799
3968
|
# raise), and detached right after the switch.
|
|
3800
|
-
wio.puts " ca_attach(cw); /*
|
|
3969
|
+
wio.puts " ca_attach(cw); /* attach: nothing raises before the detach; the kernels are numeric */"
|
|
3801
3970
|
weights_io = wio
|
|
3802
3971
|
end
|
|
3803
3972
|
|
|
3804
3973
|
if has_varg
|
|
3805
|
-
#
|
|
3974
|
+
# Pop the first positional argument as the
|
|
3806
3975
|
# runtime value_arg (e.g. `a.count_equal(5, 0)` -- 5 is value_arg,
|
|
3807
3976
|
# 0 is axis). Per-src cast happens inside the switch case below.
|
|
3808
3977
|
io.puts " if ( argc < 1 ) {"
|
|
@@ -3825,21 +3994,20 @@ module MkKernel
|
|
|
3825
3994
|
io.puts " keep_axis = 1;"
|
|
3826
3995
|
io.puts " fill_whole = 1;"
|
|
3827
3996
|
io.puts " }"
|
|
3828
|
-
io.puts " VALUE result;"
|
|
3997
|
+
io.puts " volatile VALUE result;"
|
|
3829
3998
|
elsif has_aarg
|
|
3830
3999
|
# array_arg without min_count: still need a single exit so we can
|
|
3831
4000
|
# detach cw before returning. Use the same `VALUE result; ...; break;`
|
|
3832
4001
|
# pattern as min_count, then return result after the switch.
|
|
3833
|
-
io.puts " VALUE result;"
|
|
4002
|
+
io.puts " volatile VALUE result;"
|
|
3834
4003
|
end
|
|
3835
4004
|
|
|
3836
4005
|
use_result_var = min_count || has_aarg
|
|
3837
4006
|
|
|
3838
|
-
#
|
|
3839
|
-
#
|
|
3840
|
-
# hint pointing at the kwarg form.
|
|
4007
|
+
# After the weights / value, no positional argument is taken: the axis
|
|
4008
|
+
# is a keyword. `a.sum(0, 1)` raises here, naming the keyword form.
|
|
3841
4009
|
io.puts " if ( argc > 0 ) {"
|
|
3842
|
-
io.puts %Q[ rb_raise(rb_eArgError, "%s:
|
|
4010
|
+
io.puts %Q[ rb_raise(rb_eArgError, "%s: takes no positional arguments (given %d); give the axis as a keyword, e.g. a.%s(axis: 0) or a.%s(axis: [0, 1])", ca_calling_method_name(), argc, ca_calling_method_name(), ca_calling_method_name());]
|
|
3843
4011
|
io.puts " }"
|
|
3844
4012
|
|
|
3845
4013
|
if weights_io
|
|
@@ -3882,20 +4050,19 @@ module MkKernel
|
|
|
3882
4050
|
io.print varg_decl unless varg_decl.empty?
|
|
3883
4051
|
if use_result_var
|
|
3884
4052
|
io.puts " result = #{name}_ki_native_#{s}(self, src, slab_axes, naxes, keep_axis#{extra_call});"
|
|
3885
|
-
io.puts " RB_GC_GUARD(self);"
|
|
3886
4053
|
io.puts " break;"
|
|
3887
4054
|
else
|
|
3888
|
-
io.puts "
|
|
4055
|
+
io.puts " { volatile VALUE answer = #{name}_ki_native_#{s}(self, src, slab_axes, naxes, keep_axis#{extra_call}); return answer; }"
|
|
3889
4056
|
end
|
|
3890
4057
|
io.puts " }"
|
|
3891
4058
|
else
|
|
3892
|
-
io.puts " case #{si[:ca]}:
|
|
4059
|
+
io.puts " case #{si[:ca]}: { volatile VALUE answer = #{name}_ki_native_#{s}(self, src, slab_axes, naxes, keep_axis); return answer; }"
|
|
3893
4060
|
end
|
|
3894
4061
|
end
|
|
3895
4062
|
case k[:fallback]
|
|
3896
4063
|
when :wrap_to_f64
|
|
3897
4064
|
io.puts " default: {"
|
|
3898
|
-
io.puts " /*
|
|
4065
|
+
io.puts " /* Only wrap data_types that have a meaningful float64"
|
|
3899
4066
|
io.puts " representation. Complex / fixlen / object would lose"
|
|
3900
4067
|
io.puts " structure (e.g. complex -> float strips imaginary part)"
|
|
3901
4068
|
io.puts " so reject explicitly, matching legacy DataTypeError. */"
|
|
@@ -3905,7 +4072,7 @@ module MkKernel
|
|
|
3905
4072
|
io.puts %Q[ ca_face_refuse_numeric(self, ca_calling_method_name(), rb_eCADataTypeError);]
|
|
3906
4073
|
io.puts %Q[ rb_raise(rb_eCADataTypeError, "%s: source data_type :%s not supported (expected one of: #{MkKernel.type_names(k[:source])}, or boolean)", ca_calling_method_name(), ca_type_name[src->data_type]);]
|
|
3907
4074
|
io.puts " }"
|
|
3908
|
-
io.puts " VALUE
|
|
4075
|
+
io.puts " volatile VALUE vsrc = rb_ca_wrap_readonly(self, INT2NUM(CA_FLOAT64));"
|
|
3909
4076
|
io.puts " CArray *casted;"
|
|
3910
4077
|
io.puts " GetCArray(vsrc, casted);"
|
|
3911
4078
|
if has_varg
|
|
@@ -3915,10 +4082,9 @@ module MkKernel
|
|
|
3915
4082
|
end
|
|
3916
4083
|
if use_result_var
|
|
3917
4084
|
io.puts " result = #{name}_ki_native_f64(vsrc, casted, slab_axes, naxes, keep_axis#{extra_call});"
|
|
3918
|
-
io.puts " RB_GC_GUARD(vsrc);"
|
|
3919
4085
|
io.puts " break;"
|
|
3920
4086
|
else
|
|
3921
|
-
io.puts "
|
|
4087
|
+
io.puts " { volatile VALUE answer = #{name}_ki_native_f64(vsrc, casted, slab_axes, naxes, keep_axis#{extra_call}); return answer; }"
|
|
3922
4088
|
end
|
|
3923
4089
|
io.puts " }"
|
|
3924
4090
|
when :raise
|
|
@@ -4028,7 +4194,7 @@ module MkKernel
|
|
|
4028
4194
|
static VALUE
|
|
4029
4195
|
#{name}_ki_native_#{src} (VALUE self, CArray *ca, int axis)
|
|
4030
4196
|
{
|
|
4031
|
-
VALUE
|
|
4197
|
+
volatile VALUE vout = rb_ca_template_with_type(self, INT2NUM(#{oi[:ca]}),
|
|
4032
4198
|
INT2NUM(sizeof(#{oi[:c]})));
|
|
4033
4199
|
CArray *co;
|
|
4034
4200
|
GetCArray(vout, co);
|
|
@@ -4071,21 +4237,21 @@ module MkKernel
|
|
|
4071
4237
|
def self.emit_scan_dispatch(io, k)
|
|
4072
4238
|
name = k[:name]
|
|
4073
4239
|
io.puts
|
|
4074
|
-
#
|
|
4075
|
-
# Array form is rejected at the caller side
|
|
4240
|
+
# Scan kernels accept `axis:` kwarg only.
|
|
4241
|
+
# Array form is rejected at the caller side because
|
|
4076
4242
|
# multi-axis scan is semantically ambiguous (flatten-and-cumsum vs
|
|
4077
4243
|
# 2D prefix sum); users must chain explicitly. Arity flips from 1
|
|
4078
4244
|
# (positional Integer axis) to -1 (kwarg dispatcher).
|
|
4079
4245
|
if k[:face_gate]
|
|
4080
4246
|
# The scan proper runs on the storage; the bound entry below gates the
|
|
4081
4247
|
# Face and re-lifts the result.
|
|
4082
|
-
io.puts "static VALUE rb_ca_#{name}_ki_storage (int argc, VALUE *argv, VALUE self);"
|
|
4248
|
+
io.puts "static VALUE rb_ca_#{name}_ki_storage (int argc, VALUE *argv, volatile VALUE self);"
|
|
4083
4249
|
io.puts
|
|
4084
4250
|
io.puts "static VALUE"
|
|
4085
|
-
io.puts "rb_ca_#{name}_ki (int argc, VALUE *argv, VALUE self)"
|
|
4251
|
+
io.puts "rb_ca_#{name}_ki (int argc, VALUE *argv, volatile VALUE self)"
|
|
4086
4252
|
io.puts "{"
|
|
4087
4253
|
io.puts " CArray *src;"
|
|
4088
|
-
io.puts " VALUE result;"
|
|
4254
|
+
io.puts " volatile VALUE result;"
|
|
4089
4255
|
io.puts " GetCArray(self, src);"
|
|
4090
4256
|
emit_reduce_face_gate(io, name, true)
|
|
4091
4257
|
io.puts " result = rb_ca_#{name}_ki_storage(argc, argv, self);"
|
|
@@ -4094,20 +4260,42 @@ module MkKernel
|
|
|
4094
4260
|
io.puts "}"
|
|
4095
4261
|
io.puts
|
|
4096
4262
|
io.puts "static VALUE"
|
|
4097
|
-
io.puts "rb_ca_#{name}_ki_storage (int argc, VALUE *argv, VALUE self)"
|
|
4263
|
+
io.puts "rb_ca_#{name}_ki_storage (int argc, VALUE *argv, volatile VALUE self)"
|
|
4264
|
+
elsif k[:integer_total]
|
|
4265
|
+
# An integer array scans in int64 / uint64 by ca_integer_scan, which
|
|
4266
|
+
# falls back to the float64 scan below (_general) where it wrapped.
|
|
4267
|
+
general = "rb_ca_#{name}_ki_general"
|
|
4268
|
+
kind = name.to_s.include?("prod") ? "CA_INTEGER_TOTAL_PROD" : "CA_INTEGER_TOTAL_SUM"
|
|
4269
|
+
io.puts "static VALUE rb_ca_#{k[:integer_total]}_ki (int argc, VALUE *argv, volatile VALUE self);"
|
|
4270
|
+
io.puts "static VALUE #{general} (int argc, VALUE *argv, volatile VALUE self);"
|
|
4271
|
+
io.puts
|
|
4272
|
+
io.puts "static VALUE"
|
|
4273
|
+
io.puts "rb_ca_#{name}_ki (int argc, VALUE *argv, volatile VALUE self)"
|
|
4274
|
+
io.puts "{"
|
|
4275
|
+
io.puts " CArray *src;"
|
|
4276
|
+
io.puts " GetCArray(self, src);"
|
|
4277
|
+
io.puts " if ( ca_is_integer_type(src) && ! ca_is_face(src) ) {"
|
|
4278
|
+
io.puts " return ca_integer_scan(argc, argv, self, #{general},"
|
|
4279
|
+
io.puts " rb_ca_#{k[:integer_total]}_ki, #{kind});"
|
|
4280
|
+
io.puts " }"
|
|
4281
|
+
io.puts " return #{general}(argc, argv, self);"
|
|
4282
|
+
io.puts "}"
|
|
4283
|
+
io.puts
|
|
4284
|
+
io.puts "static VALUE"
|
|
4285
|
+
io.puts "#{general} (int argc, VALUE *argv, volatile VALUE self)"
|
|
4098
4286
|
else
|
|
4099
4287
|
io.puts "static VALUE"
|
|
4100
|
-
io.puts "rb_ca_#{name}_ki (int argc, VALUE *argv, VALUE self)"
|
|
4288
|
+
io.puts "rb_ca_#{name}_ki (int argc, VALUE *argv, volatile VALUE self)"
|
|
4101
4289
|
end
|
|
4102
4290
|
io.puts "{"
|
|
4103
4291
|
io.puts " CArray *src;"
|
|
4104
4292
|
io.puts " GetCArray(self, src);"
|
|
4105
4293
|
emit_lazy_evaluated(io)
|
|
4106
4294
|
io.puts " volatile VALUE ropt = rb_pop_options(&argc, &argv);"
|
|
4107
|
-
io.puts "
|
|
4295
|
+
io.puts " VALUE raxis = Qnil;"
|
|
4108
4296
|
io.puts " rb_scan_options(ropt, \"axis\", &raxis);"
|
|
4109
4297
|
io.puts " if ( argc > 0 ) {"
|
|
4110
|
-
io.puts %Q[ rb_raise(rb_eArgError, "%s:
|
|
4298
|
+
io.puts %Q[ rb_raise(rb_eArgError, "%s: takes no positional arguments (given %d); give the axis as a keyword, e.g. a.#{name}(axis: 0)", ca_calling_method_name(), argc);]
|
|
4111
4299
|
io.puts " }"
|
|
4112
4300
|
if k[:axis_default] == :flatten
|
|
4113
4301
|
# Legacy compat: nil/omitted axis: flatten source and scan axis 0.
|
|
@@ -4119,15 +4307,15 @@ module MkKernel
|
|
|
4119
4307
|
io.puts " switch ( fsrc->data_type ) {"
|
|
4120
4308
|
k[:source].each do |s|
|
|
4121
4309
|
si = DTYPES[s]
|
|
4122
|
-
io.puts " case #{si[:ca]}:
|
|
4310
|
+
io.puts " case #{si[:ca]}: { volatile VALUE answer = #{name}_ki_native_#{s}(vflat, fsrc, 0); return answer; }"
|
|
4123
4311
|
end
|
|
4124
4312
|
case k[:fallback]
|
|
4125
4313
|
when :wrap_to_f64
|
|
4126
4314
|
io.puts " default: {"
|
|
4127
|
-
io.puts " VALUE
|
|
4315
|
+
io.puts " volatile VALUE vsrc = rb_ca_wrap_readonly(vflat, INT2NUM(CA_FLOAT64));"
|
|
4128
4316
|
io.puts " CArray *casted;"
|
|
4129
4317
|
io.puts " GetCArray(vsrc, casted);"
|
|
4130
|
-
io.puts "
|
|
4318
|
+
io.puts " { volatile VALUE answer = #{name}_ki_native_f64(vsrc, casted, 0); return answer; }"
|
|
4131
4319
|
io.puts " }"
|
|
4132
4320
|
when :raise
|
|
4133
4321
|
io.puts " default:"
|
|
@@ -4147,19 +4335,19 @@ module MkKernel
|
|
|
4147
4335
|
io.puts " if ( TYPE(raxis) == T_ARRAY ) {"
|
|
4148
4336
|
io.puts %Q[ rb_raise(rb_eArgError, "%s: axis must be a single Integer (got Array); a scan over several axes is ambiguous, chain explicitly: a.#{name}(axis: 0).#{name}(axis: 1)", ca_calling_method_name());]
|
|
4149
4337
|
io.puts " }"
|
|
4150
|
-
io.puts " int axis =
|
|
4338
|
+
io.puts " int axis = rb_ca_normalize_axis_arg(raxis, src->ndim, NULL);"
|
|
4151
4339
|
io.puts " switch ( src->data_type ) {"
|
|
4152
4340
|
k[:source].each do |s|
|
|
4153
4341
|
si = DTYPES[s]
|
|
4154
|
-
io.puts " case #{si[:ca]}:
|
|
4342
|
+
io.puts " case #{si[:ca]}: { volatile VALUE answer = #{name}_ki_native_#{s}(self, src, axis); return answer; }"
|
|
4155
4343
|
end
|
|
4156
4344
|
case k[:fallback]
|
|
4157
4345
|
when :wrap_to_f64
|
|
4158
4346
|
io.puts " default: {"
|
|
4159
|
-
io.puts " VALUE
|
|
4347
|
+
io.puts " volatile VALUE vsrc = rb_ca_wrap_readonly(self, INT2NUM(CA_FLOAT64));"
|
|
4160
4348
|
io.puts " CArray *casted;"
|
|
4161
4349
|
io.puts " GetCArray(vsrc, casted);"
|
|
4162
|
-
io.puts "
|
|
4350
|
+
io.puts " { volatile VALUE answer = #{name}_ki_native_f64(vsrc, casted, axis); return answer; }"
|
|
4163
4351
|
io.puts " }"
|
|
4164
4352
|
when :raise
|
|
4165
4353
|
io.puts " default:"
|
|
@@ -4187,7 +4375,7 @@ module MkKernel
|
|
|
4187
4375
|
emit_sort_dispatch(io, k)
|
|
4188
4376
|
end
|
|
4189
4377
|
|
|
4190
|
-
#
|
|
4378
|
+
# Per-(kernel, data_type) quickselect on the (value, idx) pair
|
|
4191
4379
|
# array. After return: arr[kth] is the kth-smallest by cmp; arr[lo..kth-1]
|
|
4192
4380
|
# all compare <= arr[kth]; arr[kth+1..hi] all compare >= arr[kth].
|
|
4193
4381
|
# Median-of-three pivot; small-range insertion sort (n < 8); Hoare
|
|
@@ -4406,8 +4594,8 @@ module MkKernel
|
|
|
4406
4594
|
rank = (k[:algorithm] == :rank)
|
|
4407
4595
|
mask_skip = (k[:mask_self] == :skip)
|
|
4408
4596
|
mask_sentinel = (k[:mask_self] == :sentinel)
|
|
4409
|
-
#
|
|
4410
|
-
#
|
|
4597
|
+
# :full and :rank algorithms accept `do_stable` parameter (= 0 for
|
|
4598
|
+
# quicksort, 1 for
|
|
4411
4599
|
# bottom-up mergesort). :partition has no kind concept (partial sort).
|
|
4412
4600
|
has_kind = (k[:algorithm] != :partition)
|
|
4413
4601
|
extra = partition ? ", ca_size_t kth" : (has_kind ? ", int do_stable" : "")
|
|
@@ -4417,7 +4605,7 @@ module MkKernel
|
|
|
4417
4605
|
io.puts "static VALUE"
|
|
4418
4606
|
io.puts "#{name}_ki_native_#{src} (VALUE self, CArray *ca, int axis#{extra})"
|
|
4419
4607
|
io.puts "{"
|
|
4420
|
-
io.puts " VALUE
|
|
4608
|
+
io.puts " volatile VALUE vout = rb_ca_template_with_type(self, INT2NUM(#{oi[:ca]}),"
|
|
4421
4609
|
io.puts " INT2NUM(0));"
|
|
4422
4610
|
io.puts " CArray *co;"
|
|
4423
4611
|
io.puts " GetCArray(vout, co);"
|
|
@@ -4605,7 +4793,7 @@ module MkKernel
|
|
|
4605
4793
|
# shared ca_pair_/ca_sort_*_pair_ helpers through u8 (the per-kernel
|
|
4606
4794
|
# #{name}_pair_bool buffer keeps boolean8_t v and casts cleanly).
|
|
4607
4795
|
pair_src = (src == :bool) ? :u8 : src
|
|
4608
|
-
io.puts " /*
|
|
4796
|
+
io.puts " /* Portable textbook pair quick or merge"
|
|
4609
4797
|
io.puts " sort. Both forms use the (value, fiber-local index) pair"
|
|
4610
4798
|
io.puts " layout (= ca_pair_#{src}) with index tie-break, so both are"
|
|
4611
4799
|
io.puts " algorithmically stable; do_stable: 1 selects bottom-up"
|
|
@@ -4635,7 +4823,7 @@ module MkKernel
|
|
|
4635
4823
|
io.puts " (void) do_stable;"
|
|
4636
4824
|
io.puts " qsort(#{buf_expr}, (size_t) #{sort_n_expr}, sizeof(#{name}_pair_#{src}), #{name}_cmp_#{src});"
|
|
4637
4825
|
elsif is_fp_kernel
|
|
4638
|
-
io.puts " /*
|
|
4826
|
+
io.puts " /* NaN pre-partition for float argsort -- NaN pairs are"
|
|
4639
4827
|
io.puts " pushed to the tail (= NaN-at-end policy, matches sort_copy"
|
|
4640
4828
|
io.puts " AC8). Only the finite slice is sorted. */"
|
|
4641
4829
|
io.puts " ca_size_t finite_n = ca_partition_nan_pair_#{src}((ca_pair_#{src} *) #{buf_expr}, (ca_size_t) #{sort_n_expr}, (ca_pair_#{src} *) aux);"
|
|
@@ -4690,7 +4878,7 @@ module MkKernel
|
|
|
4690
4878
|
io.puts " }"
|
|
4691
4879
|
io.puts " *(#{oi[:c]} *) (po + buf[r].i * ostride) = (#{oi[:c]}) out_r;"
|
|
4692
4880
|
io.puts " }"
|
|
4693
|
-
# dense == 2 (from
|
|
4881
|
+
# dense == 2 (from rank_index(descending: true, method: :dense)): descending dense ranks, the
|
|
4694
4882
|
# largest value 0, the NaN cells (sorted to the end) after the numbers.
|
|
4695
4883
|
nan_test = if is_object then "CA_OBJ_ISNAN(buf[nan_start - 1].v)"
|
|
4696
4884
|
elsif FLOAT_DTYPES.include?(src) then "isnan(buf[nan_start - 1].v)"
|
|
@@ -4770,13 +4958,22 @@ module MkKernel
|
|
|
4770
4958
|
# self/src are rebound to storage. When
|
|
4771
4959
|
# `relift` is set (value-returning kernels), the original Face is saved to
|
|
4772
4960
|
# the function-scope `_reduce_face` so the dispatcher can re-lift the output.
|
|
4961
|
+
# A boolean array is read as `bool_as` (its 0/1 cells, mask kept), so the
|
|
4962
|
+
# answer is the one that data type gives.
|
|
4963
|
+
def self.emit_reduce_bool_as(io, bool_as)
|
|
4964
|
+
io.puts " if ( src->data_type == CA_BOOLEAN && ! ca_is_face(src) ) {"
|
|
4965
|
+
io.puts " self = rb_ca_wrap_readonly(self, INT2NUM(#{DTYPES[bool_as][:ca]}));"
|
|
4966
|
+
io.puts " GetCArray(self, src);"
|
|
4967
|
+
io.puts " }"
|
|
4968
|
+
end
|
|
4969
|
+
|
|
4773
4970
|
def self.emit_reduce_face_gate(io, name, relift)
|
|
4774
4971
|
if relift
|
|
4775
4972
|
io.puts " volatile VALUE _reduce_face = Qnil; /* original Face, for output re-lift */"
|
|
4776
4973
|
end
|
|
4777
4974
|
io.puts " if ( ca_is_face(src) ) {"
|
|
4778
4975
|
io.puts " VALUE _face = self;"
|
|
4779
|
-
io.puts " VALUE _st;"
|
|
4976
|
+
io.puts " volatile VALUE _st;"
|
|
4780
4977
|
io.puts " CArray *_sc;"
|
|
4781
4978
|
io.puts %Q[ ca_face_require_orderable(_face, ca_calling_method_name(), "order");]
|
|
4782
4979
|
io.puts " _st = rb_ca_strip_face_value(self);"
|
|
@@ -4829,7 +5026,7 @@ module MkKernel
|
|
|
4829
5026
|
name = k[:name]
|
|
4830
5027
|
partition = (k[:algorithm] == :partition)
|
|
4831
5028
|
rank = (k[:algorithm] == :rank)
|
|
4832
|
-
has_kind = !partition # :full and :rank gain kind: dispatch
|
|
5029
|
+
has_kind = !partition # :full and :rank gain kind: dispatch
|
|
4833
5030
|
mask_sentinel = (k[:mask_self] == :sentinel)
|
|
4834
5031
|
# bind_ruby: false kernels are consumed by other .c files at the C
|
|
4835
5032
|
# level (carray_sort.c / carray_partition.c call the _mp twins).
|
|
@@ -4848,20 +5045,19 @@ module MkKernel
|
|
|
4848
5045
|
# through their _mp twins, so the fixed-masked_last entries below
|
|
4849
5046
|
# would have no caller.
|
|
4850
5047
|
mp_only = (k[:mask_self] == :sentinel && k[:bind_ruby] == false)
|
|
4851
|
-
# PROPOSAL_PORTABLE_TEXTBOOK_SORT §9.5.2 Option γ:
|
|
4852
5048
|
# For algorithm :full / :rank, dispatch emits THREE C-level entries:
|
|
4853
5049
|
# rb_ca_<name>_ki_quick (self, vaxis) -> do_stable=0
|
|
4854
5050
|
# rb_ca_<name>_ki_stable (self, vaxis) -> do_stable=1
|
|
4855
5051
|
# rb_ca_<name>_ki (self, vaxis) -> alias of _ki_quick
|
|
4856
5052
|
# All arity 2 (C-level); _ki binds to Ruby at arity 1 -- same as
|
|
4857
|
-
# before.
|
|
4858
|
-
#
|
|
5053
|
+
# before. One signature in one place keeps the entries from
|
|
5054
|
+
# disagreeing on arity.
|
|
4859
5055
|
#
|
|
4860
5056
|
# For algorithm :partition (kth, no kind concept): unchanged,
|
|
4861
5057
|
# rb_ca_<name>_ki (self, vaxis, vkth).
|
|
4862
5058
|
#
|
|
4863
5059
|
# mask_self: :sentinel kernels additionally thread a `masked_last`
|
|
4864
|
-
# runtime parameter through the dispatcher (see
|
|
5060
|
+
# runtime parameter through the dispatcher (see the mask_self:
|
|
4865
5061
|
# doc on MkKernel.sort above). The 2-/3-arg convenience entries
|
|
4866
5062
|
# (_ki_quick / _ki_stable / _ki) hardcode masked_last=1 (:last) so
|
|
4867
5063
|
# existing C-level callers (carray_order.c topk / order) keep their
|
|
@@ -4880,7 +5076,7 @@ module MkKernel
|
|
|
4880
5076
|
dispatch_extra += rank ? ", int dense" : ""
|
|
4881
5077
|
io.puts
|
|
4882
5078
|
io.puts "static VALUE"
|
|
4883
|
-
io.puts "#{name}_ki_dispatch (VALUE self, VALUE vaxis, int do_stable#{dispatch_extra})"
|
|
5079
|
+
io.puts "#{name}_ki_dispatch (volatile VALUE self, VALUE vaxis, int do_stable#{dispatch_extra})"
|
|
4884
5080
|
io.puts "{"
|
|
4885
5081
|
io.puts " CArray *src;"
|
|
4886
5082
|
io.puts " GetCArray(self, src);"
|
|
@@ -4897,13 +5093,13 @@ module MkKernel
|
|
|
4897
5093
|
io.puts %Q[ rb_raise(rb_eArgError, "%s: masked input not supported (use ca.value or ca.strip_mask(fill))", ca_calling_method_name());]
|
|
4898
5094
|
io.puts " }"
|
|
4899
5095
|
end
|
|
4900
|
-
io.puts " int axis =
|
|
5096
|
+
io.puts " int axis = rb_ca_normalize_axis_arg(vaxis, src->ndim, NULL);"
|
|
4901
5097
|
io.puts " switch ( src->data_type ) {"
|
|
4902
5098
|
k[:source].each do |s|
|
|
4903
5099
|
si = DTYPES[s]
|
|
4904
5100
|
native_extra = mask_sentinel ? ", masked_last" : ""
|
|
4905
5101
|
native_extra += rank ? ", dense" : ""
|
|
4906
|
-
io.puts " case #{si[:ca]}:
|
|
5102
|
+
io.puts " case #{si[:ca]}: { volatile VALUE answer = #{name}_ki_native_#{s}(self, src, axis, do_stable#{native_extra}); return answer; }"
|
|
4907
5103
|
end
|
|
4908
5104
|
io.puts " default:"
|
|
4909
5105
|
io.puts %Q[ ca_face_refuse_numeric(self, ca_calling_method_name(), rb_eCADataTypeError);]
|
|
@@ -4988,7 +5184,7 @@ module MkKernel
|
|
|
4988
5184
|
dispatch_extra = mask_sentinel ? ", int masked_last" : ""
|
|
4989
5185
|
io.puts
|
|
4990
5186
|
io.puts "static VALUE"
|
|
4991
|
-
io.puts "#{name}_ki_dispatch (VALUE self, VALUE vaxis, VALUE vkth#{dispatch_extra})"
|
|
5187
|
+
io.puts "#{name}_ki_dispatch (volatile VALUE self, VALUE vaxis, VALUE vkth#{dispatch_extra})"
|
|
4992
5188
|
io.puts "{"
|
|
4993
5189
|
io.puts " CArray *src;"
|
|
4994
5190
|
io.puts " GetCArray(self, src);"
|
|
@@ -5002,7 +5198,7 @@ module MkKernel
|
|
|
5002
5198
|
io.puts %Q[ rb_raise(rb_eArgError, "%s: masked input not supported (use ca.value or ca.strip_mask(fill))", ca_calling_method_name());]
|
|
5003
5199
|
io.puts " }"
|
|
5004
5200
|
end
|
|
5005
|
-
io.puts " int axis =
|
|
5201
|
+
io.puts " int axis = rb_ca_normalize_axis_arg(vaxis, src->ndim, NULL);"
|
|
5006
5202
|
io.puts " ca_size_t kth_raw = (ca_size_t) ca_integer_arg(vkth, \"kth\", NULL);"
|
|
5007
5203
|
io.puts " ca_size_t kth = kth_raw;"
|
|
5008
5204
|
io.puts " ca_size_t axis_n = src->dim[axis];"
|
|
@@ -5014,7 +5210,7 @@ module MkKernel
|
|
|
5014
5210
|
k[:source].each do |s|
|
|
5015
5211
|
si = DTYPES[s]
|
|
5016
5212
|
native_extra = mask_sentinel ? ", masked_last" : ""
|
|
5017
|
-
io.puts " case #{si[:ca]}:
|
|
5213
|
+
io.puts " case #{si[:ca]}: { volatile VALUE answer = #{name}_ki_native_#{s}(self, src, axis, kth#{native_extra}); return answer; }"
|
|
5018
5214
|
end
|
|
5019
5215
|
io.puts " default:"
|
|
5020
5216
|
io.puts %Q[ ca_face_refuse_numeric(self, ca_calling_method_name(), rb_eCADataTypeError);]
|
|
@@ -5056,22 +5252,22 @@ module MkKernel
|
|
|
5056
5252
|
legacy_name = k[:public_method].to_s
|
|
5057
5253
|
io.puts
|
|
5058
5254
|
io.puts "static VALUE"
|
|
5059
|
-
io.puts "rb_ca_#{name}_kw (int argc, VALUE *argv, VALUE self)"
|
|
5255
|
+
io.puts "rb_ca_#{name}_kw (int argc, VALUE *argv, volatile VALUE self)"
|
|
5060
5256
|
io.puts "{"
|
|
5061
5257
|
io.puts " volatile VALUE ropt = rb_pop_options(&argc, &argv);"
|
|
5062
|
-
io.puts "
|
|
5258
|
+
io.puts " VALUE raxis = Qnil;"
|
|
5063
5259
|
scan_keys = ["axis"]
|
|
5064
5260
|
scan_keys << "kind" if has_kind
|
|
5065
5261
|
scan_keys << "masked_position" if mask_sentinel
|
|
5066
5262
|
scan_keys << "method" if rank
|
|
5067
5263
|
if has_kind
|
|
5068
|
-
io.puts "
|
|
5264
|
+
io.puts " VALUE rkind = Qnil;"
|
|
5069
5265
|
end
|
|
5070
5266
|
if mask_sentinel
|
|
5071
|
-
io.puts "
|
|
5267
|
+
io.puts " VALUE rmasked_position = Qnil;"
|
|
5072
5268
|
end
|
|
5073
5269
|
if rank
|
|
5074
|
-
io.puts "
|
|
5270
|
+
io.puts " VALUE rmethod = Qnil;"
|
|
5075
5271
|
end
|
|
5076
5272
|
scan_targets = ["&raxis"]
|
|
5077
5273
|
scan_targets << "&rkind" if has_kind
|
|
@@ -5099,7 +5295,7 @@ module MkKernel
|
|
|
5099
5295
|
# position); :dense assigns tied values the same rank (no gaps),
|
|
5100
5296
|
# the standard "dense rank" used to compose rank as a sort_addr
|
|
5101
5297
|
# priority key without silently dropping lower-priority keys on
|
|
5102
|
-
# ties
|
|
5298
|
+
# ties.
|
|
5103
5299
|
io.puts " int dense = NIL_P(rmethod) ? 0 : ca_symbol_choice(rmethod, \"method\", \"ordinal\", \"dense\", NULL);"
|
|
5104
5300
|
end
|
|
5105
5301
|
if mask_sentinel
|
|
@@ -5122,7 +5318,7 @@ module MkKernel
|
|
|
5122
5318
|
# sort_index(axis: nil, kind: :quick, masked_position: :last) --
|
|
5123
5319
|
# no positional, kwargs only.
|
|
5124
5320
|
io.puts " if ( argc != 0 ) {"
|
|
5125
|
-
io.puts %Q[ rb_raise(rb_eArgError, "#{legacy_name}:
|
|
5321
|
+
io.puts %Q[ rb_raise(rb_eArgError, "#{legacy_name}: takes no positional arguments (given %d); give the axis and the other options as keywords, e.g. a.#{legacy_name}(axis: 0)", argc);]
|
|
5126
5322
|
io.puts " }"
|
|
5127
5323
|
# kind: dispatch (:quick default, :stable optional).
|
|
5128
5324
|
io.puts " int do_stable = NIL_P(rkind) ? 0 : ca_symbol_choice(rkind, \"kind\", \"quick\", \"stable\", NULL);"
|
|
@@ -5158,7 +5354,7 @@ module MkKernel
|
|
|
5158
5354
|
# Generated signature: rb_ca_<name>_ki(VALUE self, VALUE rval, VALUE raxis)
|
|
5159
5355
|
# bound as `<name>_ki(val, axis)` (2 positional args).
|
|
5160
5356
|
#
|
|
5161
|
-
# Author body bindings (per the kernel author surface
|
|
5357
|
+
# Author body bindings (per the kernel author surface):
|
|
5162
5358
|
# slab_ptr char * per-slab base pointer (slab axis = search axis)
|
|
5163
5359
|
# slab_n ca_size_t slab length (= ca->dim[axis])
|
|
5164
5360
|
# slab_stride ca_size_t byte stride along slab axis
|
|
@@ -5194,6 +5390,12 @@ module MkKernel
|
|
|
5194
5390
|
is_float = float_data_type?(src)
|
|
5195
5391
|
is_object = (src == :object)
|
|
5196
5392
|
is_fixlen = (src == :fixlen)
|
|
5393
|
+
is_cmplx = CMPLX_DTYPES.include?(src)
|
|
5394
|
+
# The default tolerance is eps_def times the size of the query: |q| for
|
|
5395
|
+
# a real query, the modulus for a complex one.
|
|
5396
|
+
eps_scale = is_cmplx ?
|
|
5397
|
+
"(isfinite(creal(query_val)) && isfinite(cimag(query_val)) ? (double)(EPS) * cabs((ca_u_cmplx128_t) query_val) : 0.0)" :
|
|
5398
|
+
"(isfinite((double)query_val) ? (double)(EPS) * fabs((double)query_val) : 0.0)"
|
|
5197
5399
|
# eps / distance arithmetic is ill-defined for both CA_OBJECT and
|
|
5198
5400
|
# CA_FIXLEN (arbitrary objects / byte blobs), so they share the
|
|
5199
5401
|
# "no eps" branches below.
|
|
@@ -5202,13 +5404,14 @@ module MkKernel
|
|
|
5202
5404
|
|
|
5203
5405
|
# body: Hash form picks per-data_type-kind branch (= :int / :float /
|
|
5204
5406
|
# :object / :fixlen); String form is uniform.
|
|
5205
|
-
#
|
|
5206
|
-
#
|
|
5207
|
-
#
|
|
5407
|
+
# The :object branch serves CA_OBJECT (equality via ca_obj_equal,
|
|
5408
|
+
# ordering via rb_funcall(<=>)).
|
|
5409
|
+
# The :fixlen branch serves CA_FIXLEN
|
|
5208
5410
|
# (the cell is a runtime-width byte blob; comparison is memcmp over
|
|
5209
5411
|
# ca->bytes, the same total order fixlen bincmp uses).
|
|
5210
5412
|
body_kind = if is_object then :object
|
|
5211
5413
|
elsif is_fixlen then :fixlen
|
|
5414
|
+
elsif is_cmplx then :complex
|
|
5212
5415
|
elsif is_float then :float
|
|
5213
5416
|
else :int
|
|
5214
5417
|
end
|
|
@@ -5228,7 +5431,7 @@ module MkKernel
|
|
|
5228
5431
|
mask_unused_decl_bc = (k[:mask_self] == :skip) ? "" : " (void) mask_in;\n (void) slab_mask_stride; /* mask_self: :raise rejects upstream */"
|
|
5229
5432
|
|
|
5230
5433
|
# eps resolution boilerplate (only emitted when runtime_args includes :eps)
|
|
5231
|
-
#
|
|
5434
|
+
# CA_OBJECT has no
|
|
5232
5435
|
# meaningful eps semantic (= arbitrary Ruby objects, no scalar
|
|
5233
5436
|
# multiplier on query_val). When src == :object, eps is silently
|
|
5234
5437
|
# treated as 0 (= exact equality only) regardless of user-supplied
|
|
@@ -5237,7 +5440,7 @@ module MkKernel
|
|
|
5237
5440
|
<<~C.chomp
|
|
5238
5441
|
int eps_is_default = NIL_P(reps);
|
|
5239
5442
|
double user_eps = eps_is_default ? 0.0 : NUM2DBL(reps);
|
|
5240
|
-
double query_eps = eps_is_default ?
|
|
5443
|
+
double query_eps = eps_is_default ? #{eps_scale.sub("EPS", eps_def)} : user_eps;
|
|
5241
5444
|
C
|
|
5242
5445
|
elsif has_eps && no_eps
|
|
5243
5446
|
"(void) reps; /* #{is_fixlen ? "CA_FIXLEN" : "CA_OBJECT"}: eps ignored, exact match only */\n double query_eps = 0.0; (void) query_eps;"
|
|
@@ -5252,7 +5455,7 @@ module MkKernel
|
|
|
5252
5455
|
""
|
|
5253
5456
|
end
|
|
5254
5457
|
eps_percell = if has_eps && !no_eps
|
|
5255
|
-
"double query_eps = eps_is_default ?
|
|
5458
|
+
"double query_eps = eps_is_default ? #{eps_scale.sub("EPS", eps_def)} : user_eps;"
|
|
5256
5459
|
else
|
|
5257
5460
|
"double query_eps = 0.0; (void) query_eps;"
|
|
5258
5461
|
end
|
|
@@ -5333,7 +5536,7 @@ module MkKernel
|
|
|
5333
5536
|
? "(result == (#{oi[:c]})(#{no_match})) ? (#{oi[:c]})(#{no_match}) : (#{oi[:c]})(outer_off + (ca_size_t)result * axis_vstride)" \
|
|
5334
5537
|
: "result"
|
|
5335
5538
|
|
|
5336
|
-
# undef_no_match
|
|
5539
|
+
# undef_no_match: a per-fiber /
|
|
5337
5540
|
# per-cell no-match marks the output cell UNDEF (masked) instead of
|
|
5338
5541
|
# writing the raw -1 sentinel, unifying "not found" with the no-axis
|
|
5339
5542
|
# flat array path. op_mask is lazily allocated on the first no-match.
|
|
@@ -5350,7 +5553,7 @@ module MkKernel
|
|
|
5350
5553
|
undef_query_a = <<~C.chomp
|
|
5351
5554
|
if ( rval == CA_UNDEF ) {
|
|
5352
5555
|
int8_t undef_axes[1] = { (int8_t) axis };
|
|
5353
|
-
VALUE
|
|
5556
|
+
volatile VALUE voutu = rb_ca_new_reduced(self, undef_axes, 1, #{oi[:ca]}, 0);
|
|
5354
5557
|
CArray *cou;
|
|
5355
5558
|
GetCArray(voutu, cou);
|
|
5356
5559
|
MEMZERO((#{oi[:c]} *) cou->ptr, #{oi[:c]}, cou->elements);
|
|
@@ -5417,9 +5620,9 @@ module MkKernel
|
|
|
5417
5620
|
io.puts
|
|
5418
5621
|
io.puts <<~C
|
|
5419
5622
|
static VALUE
|
|
5420
|
-
#{name}_ki_native_#{src} (VALUE self, CArray *ca, VALUE rval, int axis#{extra_params})
|
|
5623
|
+
#{name}_ki_native_#{src} (VALUE self, CArray *ca, volatile VALUE rval, int axis#{extra_params})
|
|
5421
5624
|
{
|
|
5422
|
-
/*
|
|
5625
|
+
/* A1 via single-element CArray: convert CScalar / [1] 1-D /
|
|
5423
5626
|
all dim==1 etc. to a Ruby Float and route it through the Case A
|
|
5424
5627
|
scalar path. The data type matches ca (= rb_ca_obj2ptr coerces it
|
|
5425
5628
|
downstream). */
|
|
@@ -5437,7 +5640,7 @@ module MkKernel
|
|
|
5437
5640
|
#{eps_setup_a}
|
|
5438
5641
|
|
|
5439
5642
|
int8_t slab_axes[1] = { (int8_t) axis };
|
|
5440
|
-
VALUE
|
|
5643
|
+
volatile VALUE vout = rb_ca_new_reduced(self, slab_axes, 1, #{oi[:ca]}, 0);
|
|
5441
5644
|
CArray *co;
|
|
5442
5645
|
GetCArray(vout, co);
|
|
5443
5646
|
#{oi[:c]} *op = (#{oi[:c]} *) co->ptr;
|
|
@@ -5535,9 +5738,8 @@ module MkKernel
|
|
|
5535
5738
|
end
|
|
5536
5739
|
|
|
5537
5740
|
io.puts <<~C
|
|
5538
|
-
/* ===== case B/C: CArray val
|
|
5539
|
-
|
|
5540
|
-
outer product / implicit broadcast fallback removed.
|
|
5741
|
+
/* ===== case B/C: CArray val =====
|
|
5742
|
+
5 forms only, outer product / implicit broadcast fallback removed.
|
|
5541
5743
|
|
|
5542
5744
|
A1 scalar / 0-D -> handled in Case A above
|
|
5543
5745
|
A2 1-D length M (shared) -> axis k replaced by M
|
|
@@ -5567,8 +5769,8 @@ module MkKernel
|
|
|
5567
5769
|
if ( i != axis ) { base_dim[j] = ca->dim[i]; base_to_self[j] = i; j++; }
|
|
5568
5770
|
}
|
|
5569
5771
|
|
|
5570
|
-
/*
|
|
5571
|
-
|
|
5772
|
+
/* Form detection (= A1 -> A3 -> A2 -> A2.5 priority, the same
|
|
5773
|
+
rule across all self.ndim).
|
|
5572
5774
|
|
|
5573
5775
|
A3 (cv.ndim == ca.ndim): commit on non-target match, raise on mismatch
|
|
5574
5776
|
A2 (cv.ndim == 1): commit for M >= 1 (= 1-D is unconditionally shared)
|
|
@@ -5577,9 +5779,8 @@ module MkKernel
|
|
|
5577
5779
|
excludes a dispatch collision with a 1-D val)
|
|
5578
5780
|
else raise
|
|
5579
5781
|
|
|
5580
|
-
|
|
5581
|
-
|
|
5582
|
-
preserving the §3.1 unified rule).
|
|
5782
|
+
A 1-D val is placed above A2.5, so that a 1-D val means the
|
|
5783
|
+
same thing whatever self.ndim is.
|
|
5583
5784
|
*/
|
|
5584
5785
|
enum { CV_FORM_A3, CV_FORM_A25, CV_FORM_A2 } cv_form;
|
|
5585
5786
|
int cv_form_set = 0;
|
|
@@ -5603,7 +5804,7 @@ module MkKernel
|
|
|
5603
5804
|
}
|
|
5604
5805
|
|
|
5605
5806
|
if ( ! cv_form_set && cv->ndim == 1 ) {
|
|
5606
|
-
/* A2: 1-D shared M-query (M >= 1); placed above A2.5
|
|
5807
|
+
/* A2: 1-D shared M-query (M >= 1); placed above A2.5 */
|
|
5607
5808
|
if ( cv->dim[0] < 1 ) {
|
|
5608
5809
|
rb_raise(rb_eArgError,
|
|
5609
5810
|
"%s: empty query (val.dim[0] = 0)", ca_calling_method_name());
|
|
@@ -5614,7 +5815,7 @@ module MkKernel
|
|
|
5614
5815
|
|
|
5615
5816
|
if ( ! cv_form_set && cv->ndim >= 2 && cv->ndim == base_ndim ) {
|
|
5616
5817
|
/* A2.5: per-fiber scalar query, restricted to ndim>=2. A collision
|
|
5617
|
-
with a 1-D val is structurally excluded by cv->ndim >= 2
|
|
5818
|
+
with a 1-D val is structurally excluded by cv->ndim >= 2. */
|
|
5618
5819
|
int match = 1;
|
|
5619
5820
|
for ( int8_t k = 0; k < base_ndim; k++ ) {
|
|
5620
5821
|
if ( cv->dim[k] != base_dim[k] ) { match = 0; break; }
|
|
@@ -5656,21 +5857,22 @@ module MkKernel
|
|
|
5656
5857
|
/* out_ndim == 0 is unreachable here (A1 handled above; A2.5 with
|
|
5657
5858
|
base_ndim == 0 means self is 1-D, but then ca->ndim == 1 routes
|
|
5658
5859
|
to A3 candidate path, leaving base_ndim path inaccessible). */
|
|
5659
|
-
VALUE
|
|
5860
|
+
volatile VALUE vout = rb_carray_new(#{oi[:ca]}, out_ndim, out_dim, 0, NULL);
|
|
5660
5861
|
CArray *co;
|
|
5661
5862
|
GetCArray(vout, co);
|
|
5662
5863
|
#{oi[:c]} *op = (#{oi[:c]} *) co->ptr;
|
|
5663
5864
|
#{op_mask_decl}
|
|
5664
5865
|
|
|
5665
5866
|
#{entity_bc}
|
|
5666
|
-
/* The output mask is made before
|
|
5667
|
-
allocates; it comes off again below when no cell needed
|
|
5867
|
+
/* The output mask is made before anything is attached, since
|
|
5868
|
+
making it allocates; it comes off again below when no cell needed
|
|
5869
|
+
it. */
|
|
5668
5870
|
if ( #{undef_nm ? "1" : "ca_has_mask(cv)"} ) {
|
|
5669
5871
|
ca_create_mask(co);
|
|
5670
5872
|
op_mask = (boolean8_t *) co->mask->ptr;
|
|
5671
5873
|
}
|
|
5672
|
-
/* Attach self + val;
|
|
5673
|
-
ca_attach_n(2, ca, cv); /*
|
|
5874
|
+
/* Attach self + val; raw row-major byte addressing. */
|
|
5875
|
+
ca_attach_n(2, ca, cv); /* attach: numeric bodies do not raise; the object lane reads entities */
|
|
5674
5876
|
|
|
5675
5877
|
/* self_byte_stride[j] = bytes to advance along self axis j (row-major). */
|
|
5676
5878
|
ca_size_t self_byte_stride[CA_RANK_MAX];
|
|
@@ -5796,9 +5998,9 @@ module MkKernel
|
|
|
5796
5998
|
io.puts
|
|
5797
5999
|
io.puts "VALUE"
|
|
5798
6000
|
if has_eps
|
|
5799
|
-
io.puts "rb_ca_#{name}_ki (int argc, VALUE *argv, VALUE self)"
|
|
6001
|
+
io.puts "rb_ca_#{name}_ki (int argc, VALUE *argv, volatile VALUE self)"
|
|
5800
6002
|
else
|
|
5801
|
-
io.puts "rb_ca_#{name}_ki (VALUE self, VALUE rval, VALUE raxis)"
|
|
6003
|
+
io.puts "rb_ca_#{name}_ki (volatile VALUE self, volatile VALUE rval, VALUE raxis)"
|
|
5802
6004
|
end
|
|
5803
6005
|
io.puts "{"
|
|
5804
6006
|
io.puts " CArray *src;"
|
|
@@ -5815,17 +6017,16 @@ module MkKernel
|
|
|
5815
6017
|
|
|
5816
6018
|
if has_eps
|
|
5817
6019
|
# arity = -1, accept (val, axis) or (val, axis, eps). eps is the
|
|
5818
|
-
# only runtime arg
|
|
5819
|
-
# 3.0 breaking from positional to keyword postponed to S.5).
|
|
6020
|
+
# only runtime arg.
|
|
5820
6021
|
io.puts " rb_check_arity(argc, 2, 3);"
|
|
5821
|
-
io.puts " VALUE rval
|
|
6022
|
+
io.puts " volatile VALUE rval = argv[0];"
|
|
5822
6023
|
io.puts " VALUE raxis = argv[1];"
|
|
5823
6024
|
io.puts " VALUE reps = (argc >= 3) ? argv[2] : Qnil;"
|
|
5824
6025
|
io.puts " /* A tolerance is a distance: a negative one (or NaN) means nothing. */"
|
|
5825
6026
|
io.puts " if ( ! NIL_P(reps) ) {"
|
|
5826
6027
|
io.puts " double eps_given = NUM2DBL(reps);"
|
|
5827
6028
|
io.puts " if ( ! ( eps_given >= 0.0 ) ) {"
|
|
5828
|
-
io.puts %Q[ rb_raise(rb_eArgError, "%s:
|
|
6029
|
+
io.puts %Q[ rb_raise(rb_eArgError, "%s: tol: must be zero or positive (got %"PRIsVALUE")", ca_calling_method_name(), rb_inspect(reps));]
|
|
5829
6030
|
io.puts " }"
|
|
5830
6031
|
io.puts " }"
|
|
5831
6032
|
end
|
|
@@ -5864,11 +6065,11 @@ module MkKernel
|
|
|
5864
6065
|
# body handles mask_in or ignores it
|
|
5865
6066
|
end
|
|
5866
6067
|
|
|
5867
|
-
io.puts " int axis =
|
|
6068
|
+
io.puts " int axis = rb_ca_normalize_axis_arg(raxis, src->ndim, NULL);"
|
|
5868
6069
|
io.puts " switch ( src->data_type ) {"
|
|
5869
6070
|
k[:source].each do |s|
|
|
5870
6071
|
si = DTYPES[s]
|
|
5871
|
-
io.puts " case #{si[:ca]}:
|
|
6072
|
+
io.puts " case #{si[:ca]}: { volatile VALUE answer = #{name}_ki_native_#{s}(self, src, rval, axis#{extra_arg}); return answer; }"
|
|
5872
6073
|
end
|
|
5873
6074
|
io.puts " default:"
|
|
5874
6075
|
io.puts %Q[ ca_face_refuse_numeric(self, ca_calling_method_name(), rb_eCADataTypeError);]
|
|
@@ -5878,7 +6079,7 @@ module MkKernel
|
|
|
5878
6079
|
io.puts "}"
|
|
5879
6080
|
end
|
|
5880
6081
|
|
|
5881
|
-
# ----
|
|
6082
|
+
# ---- monop emit (mkmath-compatible) ------------------------------
|
|
5882
6083
|
|
|
5883
6084
|
# Per-data_type suffix used in math family symbol names
|
|
5884
6085
|
# (`ca_monop_<name>_<suffix>`). mkmath uses typedef names
|
|
@@ -5936,6 +6137,8 @@ module MkKernel
|
|
|
5936
6137
|
when :bool then src == :bool
|
|
5937
6138
|
when :numeric then ALL_NUMERIC.include?(src)
|
|
5938
6139
|
when :int then ALL_NUMERIC.include?(src) && (src.to_s.start_with?("i") || src.to_s.start_with?("u"))
|
|
6140
|
+
when :sint then SINT_DTYPES.include?(src)
|
|
6141
|
+
when :uint then UINT_DTYPES.include?(src)
|
|
5939
6142
|
when :float then FLOAT_DTYPES.include?(src)
|
|
5940
6143
|
when :complex then CMPLX_DTYPES.include?(src)
|
|
5941
6144
|
when :object then src == :object
|
|
@@ -5968,8 +6171,7 @@ module MkKernel
|
|
|
5968
6171
|
# Some monops (e.g. zero / one / frac-int) don't read input — emit a leaner
|
|
5969
6172
|
# body without p1/q1 to avoid -Wunused-but-set-variable on p1.
|
|
5970
6173
|
uses_input = raw.include?("#1")
|
|
5971
|
-
#
|
|
5972
|
-
# 3-way split (mask / contig / strided) symmetric with binop SL.2.x phase 1.
|
|
6174
|
+
# 3-way split (mask / contig / strided), symmetric with the binop emit.
|
|
5973
6175
|
# contig branch (i1==1 && i2==1) uses index form + `omp simd` (`__restrict__`
|
|
5974
6176
|
# only when input and output are apart).
|
|
5975
6177
|
# strided branch uses `p += i` increment form (per-iter multiply removed).
|
|
@@ -6121,7 +6323,7 @@ module MkKernel
|
|
|
6121
6323
|
|
|
6122
6324
|
def self.emit_monop_wrappers(io, k)
|
|
6123
6325
|
name = k[:name]
|
|
6124
|
-
#
|
|
6326
|
+
# rb_ca_<name> is emitted as non-static (= ABI-visible across
|
|
6125
6327
|
# translation units) so hand-written wrappers in ext/carray_math.c
|
|
6126
6328
|
# (e.g. rb_ca_abs which dispatches to rb_ca_abs_i) can still link
|
|
6127
6329
|
# against kernels now living in ext/carray_kernels.c.
|
|
@@ -6139,11 +6341,11 @@ module MkKernel
|
|
|
6139
6341
|
current source family resolves to :preserve in the Hash output
|
|
6140
6342
|
form, e.g. numeric abs). For source data_types where output data_type
|
|
6141
6343
|
differs (e.g. complex abs -> f64), raise. */
|
|
6142
|
-
VALUE rb_ca_#{name}_bang (VALUE self)
|
|
6344
|
+
VALUE rb_ca_#{name}_bang (volatile VALUE self)
|
|
6143
6345
|
{
|
|
6144
6346
|
CArray *ca;
|
|
6145
6347
|
int8_t in_dt;
|
|
6146
|
-
|
|
6348
|
+
GetCArray(self, ca);
|
|
6147
6349
|
in_dt = ca->data_type;
|
|
6148
6350
|
if ( ca_monop_#{name}_out_data_type[in_dt] <= CA_NONE ) {
|
|
6149
6351
|
rb_raise(rb_eCADataTypeError,
|
|
@@ -6168,7 +6370,7 @@ module MkKernel
|
|
|
6168
6370
|
return rb_ca_call_monop(self, ca_monop_#{name});
|
|
6169
6371
|
}
|
|
6170
6372
|
|
|
6171
|
-
VALUE rb_ca_#{name}_bang (VALUE self)
|
|
6373
|
+
VALUE rb_ca_#{name}_bang (volatile VALUE self)
|
|
6172
6374
|
{ return rb_ca_call_monop_bang(self, ca_monop_#{name}); }
|
|
6173
6375
|
C
|
|
6174
6376
|
else
|
|
@@ -6176,7 +6378,7 @@ module MkKernel
|
|
|
6176
6378
|
VALUE rb_ca_#{name} (VALUE self)
|
|
6177
6379
|
{ return rb_ca_call_monop(self, ca_monop_#{name}); }
|
|
6178
6380
|
|
|
6179
|
-
VALUE rb_ca_#{name}_bang (VALUE self)
|
|
6381
|
+
VALUE rb_ca_#{name}_bang (volatile VALUE self)
|
|
6180
6382
|
{ return rb_ca_call_monop_bang(self, ca_monop_#{name}); }
|
|
6181
6383
|
C
|
|
6182
6384
|
end
|
|
@@ -6189,7 +6391,7 @@ module MkKernel
|
|
|
6189
6391
|
end
|
|
6190
6392
|
end
|
|
6191
6393
|
|
|
6192
|
-
# ----
|
|
6394
|
+
# ---- binop emit (mkmath-compatible) ------------------------------
|
|
6193
6395
|
|
|
6194
6396
|
def self.emit_binop(io, k)
|
|
6195
6397
|
io.puts
|
|
@@ -6209,7 +6411,7 @@ module MkKernel
|
|
|
6209
6411
|
suffix = math_suffix(src)
|
|
6210
6412
|
raw = monop_expr_for(k, src)
|
|
6211
6413
|
# binop uses #1, #2 for inputs and #3 for output
|
|
6212
|
-
#
|
|
6414
|
+
# Also substitute <type> placeholder (= mkmath idiom, e.g.
|
|
6213
6415
|
# `op_powi_<type>` resolves to `op_powi_int8_t` for int8 source).
|
|
6214
6416
|
# Substitution uses math_suffix (= typedef name, matches the suffix
|
|
6215
6417
|
# used in op_powi macro instantiations in ca_op_powi.h).
|
|
@@ -6217,11 +6419,10 @@ module MkKernel
|
|
|
6217
6419
|
# pragma there only adds a "loop not vectorized" warning.
|
|
6218
6420
|
simd = ( src == :object ) ? "" : "#pragma omp simd"
|
|
6219
6421
|
expr_body = raw.gsub(/#1/, "*p1").gsub(/#2/, "*p2").gsub(/#3/, "*p3").gsub(/<type>/, suffix)
|
|
6220
|
-
# Option B+C pilot (binop emit substrate hardening, MEMO_BINOP_STRIDED_AUDIT.md):
|
|
6221
6422
|
# The no-mask body is split into a contig branch (i1==i2==i3==1) using the
|
|
6222
6423
|
# `q[k]` index form with `#pragma omp simd` (`__restrict__`-qualified only
|
|
6223
6424
|
# when the output is apart from both inputs)
|
|
6224
|
-
# (
|
|
6425
|
+
# (insurance for auto-vectorisation; element-wise has no reassoc -> ε-close unaffected),
|
|
6225
6426
|
# and a strided branch using `p += i` increment form (numo-shape inner loop).
|
|
6226
6427
|
# `i1`/`i2`/`i3` remain element units (NOT byte) -- byte-flip is Option A scope.
|
|
6227
6428
|
# The mask branch is left unchanged: masked binop is not a hot path and
|
|
@@ -6506,7 +6707,7 @@ module MkKernel
|
|
|
6506
6707
|
C
|
|
6507
6708
|
end
|
|
6508
6709
|
|
|
6509
|
-
# ----
|
|
6710
|
+
# ---- moncmp / bincmp emit (mkmath-compatible) ---------------------
|
|
6510
6711
|
|
|
6511
6712
|
# Substitute mkmath placeholders `<type>` and `<epsilon>` for a given
|
|
6512
6713
|
# source data_type. Used by feq and any future bincmp using these macros.
|
|
@@ -6739,7 +6940,7 @@ module MkKernel
|
|
|
6739
6940
|
io.print <<~C
|
|
6740
6941
|
VALUE rb_ca_#{name} (VALUE self, VALUE other, VALUE tol_val)
|
|
6741
6942
|
{
|
|
6742
|
-
double tol =
|
|
6943
|
+
double tol = ca_tolerance_arg(tol_val, "#{name}");
|
|
6743
6944
|
if ( ! rb_ca_test_castable(other) ) {
|
|
6744
6945
|
return rb_funcall(other, rb_intern("#{op_intern}"), 2, self, tol_val);
|
|
6745
6946
|
}
|
|
@@ -6799,11 +7000,14 @@ module MkKernel
|
|
|
6799
7000
|
|
|
6800
7001
|
# Kernels written outside this generator that a lazy expression can still
|
|
6801
7002
|
# hold. A Float or Complex array to an Integer power is CABinOp's ipow
|
|
6802
|
-
# (ext/ca_op_ipower.c,
|
|
6803
|
-
#
|
|
6804
|
-
EXTRA_BODY_ROWS =
|
|
6805
|
-
["binop", "ipow",
|
|
6806
|
-
|
|
7003
|
+
# (ext/ca_op_ipower.c, ca_ipow_<type>): #2 is an int64, converted as an
|
|
7004
|
+
# int64 cell is converted to the base's type, then the power body.
|
|
7005
|
+
EXTRA_BODY_ROWS = [
|
|
7006
|
+
["binop", "ipow", "float32", pow_short("powf((#1), (float)(double)(#2))")],
|
|
7007
|
+
["binop", "ipow", "float64", pow_short("pow((#1), (double)(#2))")],
|
|
7008
|
+
["binop", "ipow", "cmplx64", pow_short("cpow((#1), (float)(double)(#2))")],
|
|
7009
|
+
["binop", "ipow", "cmplx128", pow_short("cpow((#1), (double)(#2))")],
|
|
7010
|
+
].freeze
|
|
6807
7011
|
|
|
6808
7012
|
# The helpers the bodies call that are not in the C standard library:
|
|
6809
7013
|
# the part of ca_op_powi.h between its markers, as it stands.
|
|
@@ -6895,9 +7099,9 @@ module MkKernel
|
|
|
6895
7099
|
static VALUE
|
|
6896
7100
|
rb_ca_s_kernel_body (VALUE klass, VALUE rkind, VALUE rname, VALUE rtype)
|
|
6897
7101
|
{
|
|
6898
|
-
VALUE kind = rb_obj_as_string(rkind);
|
|
6899
|
-
VALUE name = rb_obj_as_string(rname);
|
|
6900
|
-
VALUE type = rb_obj_as_string(rtype);
|
|
7102
|
+
volatile VALUE kind = rb_obj_as_string(rkind);
|
|
7103
|
+
volatile VALUE name = rb_obj_as_string(rname);
|
|
7104
|
+
volatile VALUE type = rb_obj_as_string(rtype);
|
|
6901
7105
|
const char *k = StringValueCStr(kind);
|
|
6902
7106
|
const char *n = StringValueCStr(name);
|
|
6903
7107
|
const char *t = StringValueCStr(type);
|
|
@@ -6968,16 +7172,24 @@ module MkKernel
|
|
|
6968
7172
|
# One kernel's registration line, shared by the single-stream and split
|
|
6969
7173
|
# forms. `next` inside a method returns nil, which is the same skip the
|
|
6970
7174
|
# KERNELS.each loop used to express.
|
|
7175
|
+
# A kernel named `<x>_i` is an internal part (the type-keeping magnitude
|
|
7176
|
+
# behind `.real`, the lazy `arg`, the object-only `quo`, the kernel behind
|
|
7177
|
+
# `&` `|` `^`): its own name and its bang are bound privately. The
|
|
7178
|
+
# operator a binop is bound to (`&` for bit_and_i) stays public.
|
|
7179
|
+
def self.define_fn(name)
|
|
7180
|
+
name.to_s.match?(/_i!?\z/) ? "rb_define_private_method" : "rb_define_method"
|
|
7181
|
+
end
|
|
7182
|
+
|
|
6971
7183
|
def self.emit_init_line(io, k)
|
|
6972
|
-
#
|
|
7184
|
+
# Monop kernels register as `<op>` / `<op>!` (= mkmath
|
|
6973
7185
|
# surface) + optional CAMath module function, NOT as `<name>_ki`.
|
|
6974
7186
|
if k[:kind] == :monop
|
|
6975
|
-
io.puts %Q[
|
|
6976
|
-
io.puts %Q[
|
|
6977
|
-
io.puts %Q[ rb_define_module_function(rb_mCAMath, "#{k[:name]}", rb_cmath_#{k[:name]}, 1);] if k[:cmath]
|
|
7187
|
+
io.puts %Q[ #{define_fn(k[:op])}(rb_cCArray, "#{k[:op]}", rb_ca_#{k[:name]}, 0);] if k[:bind]
|
|
7188
|
+
io.puts %Q[ #{define_fn("#{k[:name]}!")}(rb_cCArray, "#{k[:name]}!", rb_ca_#{k[:name]}_bang, 0);] if k[:bang]
|
|
7189
|
+
io.puts %Q[ rb_define_module_function(rb_mCAMath, "#{k[:name]}", rb_cmath_#{k[:name]}, 1);] if k[:cmath] && define_fn(k[:name]) == "rb_define_method"
|
|
6978
7190
|
return
|
|
6979
7191
|
end
|
|
6980
|
-
#
|
|
7192
|
+
# Monop alias = rb_define_alias to an existing monop method
|
|
6981
7193
|
# (e.g. "-@" alias of "neg"). rb_define_alias requires the source
|
|
6982
7194
|
# method to already be registered, so declarations must order
|
|
6983
7195
|
# alias_monop AFTER the corresponding monop.
|
|
@@ -6985,37 +7197,37 @@ module MkKernel
|
|
|
6985
7197
|
io.puts %Q[ rb_define_alias(rb_cCArray, "#{k[:op]}", "#{k[:name]}");]
|
|
6986
7198
|
return
|
|
6987
7199
|
end
|
|
6988
|
-
#
|
|
7200
|
+
# Binop kernel = `<op>` + `<name>!` (= mkmath surface).
|
|
6989
7201
|
if k[:kind] == :binop
|
|
6990
|
-
io.puts %Q[
|
|
6991
|
-
io.puts %Q[
|
|
7202
|
+
io.puts %Q[ #{define_fn(k[:op])}(rb_cCArray, "#{k[:op]}", rb_ca_#{k[:name]}, 1);] if k[:op] && k[:bind]
|
|
7203
|
+
io.puts %Q[ #{define_fn("#{k[:name]}!")}(rb_cCArray, "#{k[:name]}!", rb_ca_#{k[:name]}_bang, 1);] if k[:bind]
|
|
6992
7204
|
return
|
|
6993
7205
|
end
|
|
6994
7206
|
# triop kernel = `<op>` (arity 2) + `<name>!` (arity 2). Self is
|
|
6995
7207
|
# the implicit receiver; the two extra operands are explicit.
|
|
6996
7208
|
if k[:kind] == :triop
|
|
6997
7209
|
io.puts %Q[ rb_define_method(rb_cCArray, "#{k[:op]}", rb_ca_#{k[:name]}, 2);] if k[:op] && k[:bind]
|
|
6998
|
-
io.puts %Q[
|
|
7210
|
+
io.puts %Q[ #{define_fn("#{k[:name]}!")}(rb_cCArray, "#{k[:name]}!", rb_ca_#{k[:name]}_bang, 2);] if k[:bang] != false
|
|
6999
7211
|
return
|
|
7000
7212
|
end
|
|
7001
|
-
#
|
|
7213
|
+
# Binop alias = rb_define_alias (e.g. "add" alias of "+").
|
|
7002
7214
|
if k[:kind] == :binop_alias
|
|
7003
7215
|
io.puts %Q[ rb_define_alias(rb_cCArray, "#{k[:alias_name]}", "#{k[:target_name]}");]
|
|
7004
7216
|
return
|
|
7005
7217
|
end
|
|
7006
|
-
#
|
|
7218
|
+
# Moncmp kernel = `<op>` only (no bang form; predicate).
|
|
7007
7219
|
if k[:kind] == :moncmp
|
|
7008
7220
|
io.puts %Q[ rb_define_method(rb_cCArray, "#{k[:op]}", rb_ca_#{k[:name]}, 0);] if k[:op]
|
|
7009
7221
|
return
|
|
7010
7222
|
end
|
|
7011
|
-
#
|
|
7223
|
+
# Bincmp kernel = `<op>` (no bang form; predicate).
|
|
7012
7224
|
# IC.1: tolerance ops take 2 args (other + tol).
|
|
7013
7225
|
if k[:kind] == :bincmp
|
|
7014
7226
|
bincmp_arity = k[:tolerance] ? 2 : 1
|
|
7015
7227
|
io.puts %Q[ rb_define_method(rb_cCArray, "#{k[:op]}", rb_ca_#{k[:name]}, #{bincmp_arity});] if k[:op]
|
|
7016
7228
|
return
|
|
7017
7229
|
end
|
|
7018
|
-
#
|
|
7230
|
+
# Bincmp alias.
|
|
7019
7231
|
if k[:kind] == :bincmp_alias
|
|
7020
7232
|
io.puts %Q[ rb_define_alias(rb_cCArray, "#{k[:alias_name]}", "#{k[:target_name]}");]
|
|
7021
7233
|
return
|
|
@@ -7024,27 +7236,22 @@ module MkKernel
|
|
|
7024
7236
|
when :reduce then -1 # axis: kwarg + optional weights/value positional
|
|
7025
7237
|
when :scan then -1 # axis: kwarg (Integer required)
|
|
7026
7238
|
when :sort
|
|
7027
|
-
#
|
|
7239
|
+
# :partition algorithm takes (axis, kth) = arity 2
|
|
7028
7240
|
(k[:algorithm] == :partition) ? 2 : 1
|
|
7029
7241
|
when :search
|
|
7030
7242
|
# (val, axis) base; runtime_args adds optional positionals
|
|
7031
7243
|
# -> variadic argc when any runtime arg is configured.
|
|
7032
7244
|
k[:runtime_args].empty? ? 2 : -1
|
|
7033
7245
|
end
|
|
7034
|
-
#
|
|
7035
|
-
#
|
|
7036
|
-
# bench A/B comparison during Phase E (E.1-E.5); after E.7 they
|
|
7037
|
-
# are retired. Maps and scans keep their `_ki` names because
|
|
7038
|
-
# they have no user-facing equivalent yet (cumsum etc. pending
|
|
7039
|
-
# rewire).
|
|
7246
|
+
# Reductions do not expose a `<name>_ki` Ruby binding. Maps and
|
|
7247
|
+
# scans keep their `_ki` names.
|
|
7040
7248
|
#
|
|
7041
|
-
#
|
|
7249
|
+
# Sort kernels can opt out of the _ki
|
|
7042
7250
|
# binding via bind_ruby: false (= internal-only kernels consumed
|
|
7043
7251
|
# only at the C level). Used by sort_addr_ki which feeds the
|
|
7044
7252
|
# public sort(axis:) method without exposing its own surface.
|
|
7045
7253
|
# bind_ruby resolves per-kind:
|
|
7046
|
-
# reduce: default false
|
|
7047
|
-
# (used by CF.1 count_equal smoke + future kernel testing)
|
|
7254
|
+
# reduce: default false, opt-in via bind_ruby: true
|
|
7048
7255
|
# sort: default true, opt-out via bind_ruby: false
|
|
7049
7256
|
# scan: bound as <name>_ki, or only privately as <name> (private:)
|
|
7050
7257
|
bind = case k[:kind]
|
|
@@ -7057,10 +7264,16 @@ module MkKernel
|
|
|
7057
7264
|
io.puts %Q[ rb_define_private_method(rb_cCArray, "#{k[:name]}", rb_ca_#{k[:name]}_ki, #{arity});]
|
|
7058
7265
|
end
|
|
7059
7266
|
# Smoke kernels (e.g. count_equal) expose their _ki binding only
|
|
7060
|
-
# in dev builds, gated by CARRAY_DEV_BUILD.
|
|
7061
|
-
#
|
|
7267
|
+
# in dev builds, gated by CARRAY_DEV_BUILD.
|
|
7268
|
+
# `<name>_ki` is the kernel's own name, not a public method. When a
|
|
7269
|
+
# public name below reaches the same function (a scan with
|
|
7270
|
+
# axis_default: :flatten, or public_method: outside sort), the `_ki`
|
|
7271
|
+
# name is not bound at all; otherwise it is bound privately, for the
|
|
7272
|
+
# lib wrappers and the C callers that reach it by name.
|
|
7273
|
+
bind = false if (k[:kind] == :scan && k[:axis_default] == :flatten && ! k[:private]) ||
|
|
7274
|
+
(k[:public_method] && k[:kind] != :sort)
|
|
7062
7275
|
io.puts "#ifdef CARRAY_DEV_BUILD" if bind && k[:smoke]
|
|
7063
|
-
io.puts %Q[
|
|
7276
|
+
io.puts %Q[ rb_define_private_method(rb_cCArray, "#{k[:name]}_ki", rb_ca_#{k[:name]}_ki, #{arity});] if bind
|
|
7064
7277
|
io.puts "#endif /* CARRAY_DEV_BUILD */" if bind && k[:smoke]
|
|
7065
7278
|
# Scan kernels with axis_default: :flatten also bind the public
|
|
7066
7279
|
# name (= same kernel name without the _ki suffix) so the pre-3.0
|
|
@@ -7071,9 +7284,8 @@ module MkKernel
|
|
|
7071
7284
|
if k[:kind] == :scan && k[:axis_default] == :flatten && ! k[:private]
|
|
7072
7285
|
io.puts %Q[ rb_define_method(rb_cCArray, "#{k[:name]}", rb_ca_#{k[:name]}_ki, #{arity});]
|
|
7073
7286
|
end
|
|
7074
|
-
#
|
|
7075
|
-
#
|
|
7076
|
-
# function in carray_stat_proc.c was removed in E.7.
|
|
7287
|
+
# When this kernel is the implementation of a public CArray method,
|
|
7288
|
+
# bind the public name to the ki entry.
|
|
7077
7289
|
#
|
|
7078
7290
|
# Sort form uses a kwarg trampoline (_kw) instead of the positional
|
|
7079
7291
|
# _ki so the public surface is `name(axis: 0)` / `name(kth, axis: 0)`.
|
|
@@ -7083,7 +7295,7 @@ module MkKernel
|
|
|
7083
7295
|
io.puts %Q[ /* Sort kwarg surface: '#{legacy_name}' dispatches via #{k[:name]}_kw trampoline */]
|
|
7084
7296
|
io.puts %Q[ rb_define_method(rb_cCArray, "#{legacy_name}", rb_ca_#{k[:name]}_kw, -1);]
|
|
7085
7297
|
else
|
|
7086
|
-
io.puts %Q[ /*
|
|
7298
|
+
io.puts %Q[ /* '#{legacy_name}' dispatches via #{k[:name]}_ki */]
|
|
7087
7299
|
io.puts %Q[ rb_define_method(rb_cCArray, "#{legacy_name}", rb_ca_#{k[:name]}_ki, #{arity});]
|
|
7088
7300
|
end
|
|
7089
7301
|
end
|
|
@@ -7092,45 +7304,93 @@ end
|
|
|
7092
7304
|
|
|
7093
7305
|
# ---- kernel definitions ------------------------------------------------
|
|
7094
7306
|
|
|
7095
|
-
#
|
|
7096
|
-
#
|
|
7097
|
-
# (count of true cells). Comment in DTYPES[:bool] (line ~68)
|
|
7098
|
-
# is still relevant for min/max/variance — those stay rejected because
|
|
7099
|
-
# they overlap semantically with .all / .any / Bernoulli-variance which
|
|
7100
|
-
# users should request explicitly. sum / mean are the "natural numeric
|
|
7101
|
-
# extension" cases (= count / proportion).
|
|
7307
|
+
# :bool source has u64 output (= count of true cells), so `(a > 0).sum`
|
|
7308
|
+
# counts the true cells.
|
|
7102
7309
|
MkKernel.reduce :sum,
|
|
7103
7310
|
init: { numeric: "0", complex: "0", bool: "0",
|
|
7104
7311
|
object: "INT2FIX(0)" },
|
|
7105
7312
|
reduce: { numeric: "acc += v", complex: "acc += v", bool: "acc += v",
|
|
7106
7313
|
object: 'acc = rb_funcall(acc, rb_intern("+"), 1, v)' },
|
|
7107
|
-
reduction_kind: :plus,
|
|
7314
|
+
reduction_kind: :plus,
|
|
7108
7315
|
source: MkKernel::ALL_NUMERIC + MkKernel::CMPLX_DTYPES + [:bool, :object],
|
|
7109
7316
|
output: { numeric: :f64, complex: :cmplx128, bool: :u64,
|
|
7110
7317
|
object: :object },
|
|
7111
7318
|
ruby_scalar: :auto, # per-output-data_type: f64 -> rb_float_new, cmplx128 -> CC2NUM, u64 -> ULL2NUM, object -> (VALUE)
|
|
7112
7319
|
fallback: :raise, # was :wrap_to_f64 (silent NUM2DBL on bool/object); 3.0 breaking
|
|
7113
|
-
mask_policy: :min_count, #
|
|
7114
|
-
identity_on_empty: true, #
|
|
7115
|
-
|
|
7320
|
+
mask_policy: :min_count, # accept :min_count / :fill_value opts
|
|
7321
|
+
identity_on_empty: true, # empty / all-masked -> 0 (additive identity), not UNDEF
|
|
7322
|
+
integer_total: :sum_wrapping, # an integer array: the exact total, float64 past the range
|
|
7323
|
+
public_method: true # bind "sum" -> rb_ca_sum_ki
|
|
7116
7324
|
|
|
7117
7325
|
MkKernel.reduce :prod,
|
|
7118
7326
|
init: { numeric: "1", complex: "1", bool: "1",
|
|
7119
7327
|
object: "INT2FIX(1)" },
|
|
7120
7328
|
reduce: { numeric: "acc *= v", complex: "acc *= v", bool: "acc *= v",
|
|
7121
7329
|
object: 'acc = rb_funcall(acc, rb_intern("*"), 1, v)' },
|
|
7122
|
-
reduction_kind: :star,
|
|
7330
|
+
reduction_kind: :star,
|
|
7123
7331
|
source: MkKernel::ALL_NUMERIC + MkKernel::CMPLX_DTYPES + [:bool, :object],
|
|
7124
7332
|
output: { numeric: :f64, complex: :cmplx128, bool: :u64, object: :object },
|
|
7125
7333
|
ruby_scalar: :auto,
|
|
7126
7334
|
fallback: :raise,
|
|
7127
|
-
mask_policy: :min_count,
|
|
7128
|
-
identity_on_empty: true, #
|
|
7129
|
-
|
|
7335
|
+
mask_policy: :min_count,
|
|
7336
|
+
identity_on_empty: true, # empty / all-masked -> 1 (multiplicative identity)
|
|
7337
|
+
integer_total: :prod_wrapping, # an integer array: the exact product, float64 past the range
|
|
7338
|
+
public_method: true # bind "prod" -> rb_ca_prod_ki
|
|
7339
|
+
|
|
7340
|
+
# The integer folds behind sum and prod (integer_total:), not bound to Ruby;
|
|
7341
|
+
# ca_integer_total (carray_integer_total.c) reads them.
|
|
7342
|
+
#
|
|
7343
|
+
# sum_wrapping: a signed array folds in int64 and an unsigned one in uint64,
|
|
7344
|
+
# wrapping at 2**64. For cells of 4 bytes or fewer and fewer than 2**31 of
|
|
7345
|
+
# them, the total cannot wrap.
|
|
7346
|
+
MkKernel.reduce :sum_wrapping,
|
|
7347
|
+
init: "0",
|
|
7348
|
+
reduce: "acc += v",
|
|
7349
|
+
reduction_kind: :plus,
|
|
7350
|
+
source: MkKernel::INT_DTYPES,
|
|
7351
|
+
output: { sint: :i64, uint: :u64 },
|
|
7352
|
+
ruby_scalar: :auto,
|
|
7353
|
+
fallback: :raise,
|
|
7354
|
+
mask_policy: :min_count,
|
|
7355
|
+
identity_on_empty: true
|
|
7356
|
+
|
|
7357
|
+
# sum_parts: the exact sum of 8-byte cells, as its low 64 bits `low` and
|
|
7358
|
+
# the bits above them `top` (T = top * 2**64 + low), in one pass. It keeps
|
|
7359
|
+
# the wrapping sum acc (= T mod 2**64) and the sum hi of each cell's high
|
|
7360
|
+
# 32 bits, which does not wrap for fewer than 2**31 cells. T = hi * 2**32 +
|
|
7361
|
+
# lo, lo the sum of the low 32 bits (below 2**63), so with X = (hi mod
|
|
7362
|
+
# 2**32) * 2**32, T = (hi >> 32) * 2**64 + X + lo, and X + lo passed 2**64
|
|
7363
|
+
# exactly where acc < X. T is in range where top is the sign extension of
|
|
7364
|
+
# low (0 for an unsigned array).
|
|
7365
|
+
MkKernel.reduce :sum_parts,
|
|
7366
|
+
state: { acc: "uint64_t", hi: "int64_t" },
|
|
7367
|
+
init: { acc: "0", hi: "0" },
|
|
7368
|
+
reduce: "acc += (uint64_t) v; hi += (int64_t) (v >> 32);",
|
|
7369
|
+
outputs: 2,
|
|
7370
|
+
finish: { low: "(int64_t) acc",
|
|
7371
|
+
top: "(hi >> 32) + (int64_t) (acc < ((uint64_t) hi << 32))" },
|
|
7372
|
+
reduction_kind: { acc: :plus, hi: :plus },
|
|
7373
|
+
source: %i[i64 u64],
|
|
7374
|
+
output: { sint: :i64, uint: :u64 },
|
|
7375
|
+
ruby_scalar: :auto,
|
|
7376
|
+
fallback: :raise,
|
|
7377
|
+
mask_policy: :min_count,
|
|
7378
|
+
identity_on_empty: true
|
|
7379
|
+
|
|
7380
|
+
# prod_wrapping: the product in int64 / uint64, wrapping at 2**64.
|
|
7381
|
+
MkKernel.reduce :prod_wrapping,
|
|
7382
|
+
init: "1",
|
|
7383
|
+
reduce: "acc *= v",
|
|
7384
|
+
reduction_kind: :star,
|
|
7385
|
+
source: MkKernel::INT_DTYPES,
|
|
7386
|
+
output: { sint: :i64, uint: :u64 },
|
|
7387
|
+
ruby_scalar: :auto,
|
|
7388
|
+
fallback: :raise,
|
|
7389
|
+
mask_policy: :min_count,
|
|
7390
|
+
identity_on_empty: true
|
|
7130
7391
|
|
|
7131
7392
|
MkKernel.reduce :min,
|
|
7132
|
-
#
|
|
7133
|
-
# sentinel + "first cell as init" pattern (Q1 case A). No identity
|
|
7393
|
+
# :object uses a Qundef sentinel + "first cell as init" pattern. No identity
|
|
7134
7394
|
# value exists for arbitrary Comparable; the first reduce() call
|
|
7135
7395
|
# adopts v as acc. mask_policy: :min_count ensures masked cells are
|
|
7136
7396
|
# skipped before reduce() fires, so the sentinel check fires exactly
|
|
@@ -7138,7 +7398,7 @@ MkKernel.reduce :min,
|
|
|
7138
7398
|
# reach finish (= min_count trigger writes UNDEF), so the dangling
|
|
7139
7399
|
# Qundef is safe.
|
|
7140
7400
|
init: { numeric: "T_LIMIT_HI", bool: "T_LIMIT_HI", object: "Qundef" },
|
|
7141
|
-
#
|
|
7401
|
+
# Ternary form (= branchless) lets clang vectorize under
|
|
7142
7402
|
# `#pragma omp simd reduction(min:acc)`. The `if (v < acc) acc = v`
|
|
7143
7403
|
# form is semantically equivalent but clang does not pattern-match
|
|
7144
7404
|
# it for SIMD reduction; ternary is canonical for the OpenMP min:
|
|
@@ -7153,7 +7413,7 @@ MkKernel.reduce :min,
|
|
|
7153
7413
|
# load to match and avoid a signed/unsigned compare.
|
|
7154
7414
|
bool: "acc = ((uint64_t) v < acc) ? (uint64_t) v : acc",
|
|
7155
7415
|
object: 'if (acc == Qundef || ca_obj_extremum_replaces(v, acc, rb_intern("<"))) acc = v;' },
|
|
7156
|
-
reduction_kind: :min,
|
|
7416
|
+
reduction_kind: :min,
|
|
7157
7417
|
all_nan_result: :nan,
|
|
7158
7418
|
# CA_FIXLEN: memcmp lexicographic min (byte order == the fixlen sort
|
|
7159
7419
|
# order); the numeric reduce/init above are unused for fixlen (bespoke
|
|
@@ -7163,22 +7423,22 @@ MkKernel.reduce :min,
|
|
|
7163
7423
|
output: { numeric: :preserve, bool: :u64, object: :preserve },
|
|
7164
7424
|
ruby_scalar: :auto,
|
|
7165
7425
|
fallback: :raise,
|
|
7166
|
-
mask_policy: :min_count,
|
|
7426
|
+
mask_policy: :min_count,
|
|
7167
7427
|
# An ORDERABLE Face descends to numeric storage, then the result is
|
|
7168
7428
|
# re-lifted into the Face (scalar via storage_to_element, per-axis via
|
|
7169
7429
|
# ca_face_relift_entity). This replaces per-Face lib overrides.
|
|
7170
7430
|
face_gate: :relift,
|
|
7171
|
-
public_method: true #
|
|
7431
|
+
public_method: true # bind "min" -> rb_ca_min_ki
|
|
7172
7432
|
|
|
7173
7433
|
MkKernel.reduce :max,
|
|
7174
7434
|
init: { numeric: "T_LIMIT_LO", bool: "T_LIMIT_LO", object: "Qundef" },
|
|
7175
|
-
#
|
|
7435
|
+
# Ternary form for clang OpenMP `reduction(max:acc)`
|
|
7176
7436
|
# vectorization. See :min for rationale. bool: u64 output (Integer
|
|
7177
7437
|
# 0/1); the boolean-returning twin is `any` (= bool max).
|
|
7178
7438
|
reduce: { numeric: "acc = (v > acc) ? v : acc",
|
|
7179
7439
|
bool: "acc = ((uint64_t) v > acc) ? (uint64_t) v : acc",
|
|
7180
7440
|
object: 'if (acc == Qundef || ca_obj_extremum_replaces(v, acc, rb_intern(">"))) acc = v;' },
|
|
7181
|
-
reduction_kind: :max,
|
|
7441
|
+
reduction_kind: :max,
|
|
7182
7442
|
all_nan_result: :nan,
|
|
7183
7443
|
# CA_FIXLEN: memcmp lexicographic max (byte order == the fixlen sort order).
|
|
7184
7444
|
fixlen: :max,
|
|
@@ -7186,15 +7446,14 @@ MkKernel.reduce :max,
|
|
|
7186
7446
|
output: { numeric: :preserve, bool: :u64, object: :preserve },
|
|
7187
7447
|
ruby_scalar: :auto,
|
|
7188
7448
|
fallback: :raise,
|
|
7189
|
-
mask_policy: :min_count,
|
|
7449
|
+
mask_policy: :min_count,
|
|
7190
7450
|
face_gate: :relift,
|
|
7191
|
-
public_method: true #
|
|
7451
|
+
public_method: true # bind "max" -> rb_ca_max_ki
|
|
7192
7452
|
|
|
7193
7453
|
# all / any reduce: bool input -> bool output, axis-aware. Replaces the
|
|
7194
7454
|
# flat-only hand-written rb_ca_all_equal_p / rb_ca_any_equal_p /
|
|
7195
7455
|
# all_close? / any_close? / all_equiv? / any_equiv? in carray_stat.c
|
|
7196
|
-
# (
|
|
7197
|
-
# thin wrappers; canonical idiom is `a.eq(v).all` / `a.is_close(v, t).any`).
|
|
7456
|
+
# (there are no predicate bridge methods; the canonical idiom is `a.eq(v).all` / `a.is_close(v, t).any`).
|
|
7198
7457
|
#
|
|
7199
7458
|
# Mask policy: default (no propagation flag) -- masked input cells are
|
|
7200
7459
|
# simply skipped by CA_SLAB_REDUCE_T's mask-aware branch, so acc keeps
|
|
@@ -7214,6 +7473,21 @@ MkKernel.header_block <<~C
|
|
|
7214
7473
|
#endif
|
|
7215
7474
|
C
|
|
7216
7475
|
|
|
7476
|
+
MkKernel.header_block <<~C
|
|
7477
|
+
/* An object mean or variance divides by a count with quo where the
|
|
7478
|
+
value has it, so an Integer total gives an exact Rational (3/2, not
|
|
7479
|
+
the floor 1) and a Float or a BigDecimal one stays in its kind; a
|
|
7480
|
+
value without quo divides with /. */
|
|
7481
|
+
#ifndef CARRAY_OBJECT_QUO_DEFINED
|
|
7482
|
+
#define CARRAY_OBJECT_QUO_DEFINED
|
|
7483
|
+
static inline VALUE ca_object_quo (VALUE a, VALUE b)
|
|
7484
|
+
{
|
|
7485
|
+
ID id_quo = rb_intern("quo");
|
|
7486
|
+
return rb_funcall(a, rb_respond_to(a, id_quo) ? id_quo : rb_intern("/"), 1, b);
|
|
7487
|
+
}
|
|
7488
|
+
#endif
|
|
7489
|
+
C
|
|
7490
|
+
|
|
7217
7491
|
MkKernel.header_block <<~C
|
|
7218
7492
|
/* BOOL2VAL: bool -> Ruby (Qtrue/Qfalse). Used as ruby_scalar wrapper
|
|
7219
7493
|
for the all/any flat-reduction Ruby surface so `a.all` / `a.any`
|
|
@@ -7268,8 +7542,8 @@ MkKernel.reduce :none,
|
|
|
7268
7542
|
# mean_ki — sum / count, with mask-aware count.
|
|
7269
7543
|
# REDUCE updates two state vars per cell; finish does the division
|
|
7270
7544
|
# (guarded against empty / all-masked slabs).
|
|
7271
|
-
#
|
|
7272
|
-
#
|
|
7545
|
+
# :bool source has f64 output (= proportion of true cells, Bernoulli
|
|
7546
|
+
# mean). Companion
|
|
7273
7547
|
# to bool sum above.
|
|
7274
7548
|
MkKernel.reduce :mean,
|
|
7275
7549
|
state: { acc: :acc_type, cnt: :int64_t },
|
|
@@ -7280,8 +7554,8 @@ MkKernel.reduce :mean,
|
|
|
7280
7554
|
complex: "(acc += v, cnt++)",
|
|
7281
7555
|
bool: "(acc += v, cnt++)",
|
|
7282
7556
|
object: '(acc = rb_funcall(acc, rb_intern("+"), 1, v), cnt++)' },
|
|
7283
|
-
reduction_kind: { acc: :plus, cnt: :induction },
|
|
7284
|
-
# 8-way accumulator split follow-up
|
|
7557
|
+
reduction_kind: { acc: :plus, cnt: :induction },
|
|
7558
|
+
# 8-way accumulator split follow-up: mean's cnt is the
|
|
7285
7559
|
# count of valid (non-masked) cells, which equals slab_elements minus
|
|
7286
7560
|
# masked_cnt at slab end. Declaring cnt as state_from_slab_size lets
|
|
7287
7561
|
# the 8-way emit path drop `cnt++` from the per-cell reduce (which
|
|
@@ -7293,13 +7567,13 @@ MkKernel.reduce :mean,
|
|
|
7293
7567
|
finish: { numeric: "cnt ? acc / (T_OUT) cnt : 0",
|
|
7294
7568
|
complex: "cnt ? acc / (T_OUT) cnt : 0",
|
|
7295
7569
|
bool: "cnt ? acc / (T_OUT) cnt : 0",
|
|
7296
|
-
object: 'cnt ?
|
|
7570
|
+
object: 'cnt ? ca_object_quo(acc, LONG2NUM(cnt)) : Qnil' },
|
|
7297
7571
|
source: MkKernel::ALL_NUMERIC + MkKernel::CMPLX_DTYPES + [:bool, :object],
|
|
7298
7572
|
output: { numeric: :f64, complex: :cmplx128, bool: :f64, object: :object },
|
|
7299
7573
|
ruby_scalar: :auto,
|
|
7300
7574
|
fallback: :raise,
|
|
7301
|
-
mask_policy: :min_count,
|
|
7302
|
-
public_method: true #
|
|
7575
|
+
mask_policy: :min_count,
|
|
7576
|
+
public_method: true # bind "mean" -> rb_ca_mean_ki
|
|
7303
7577
|
|
|
7304
7578
|
# variancep / variance / stddevp / stddev — centred two-pass algorithm.
|
|
7305
7579
|
#
|
|
@@ -7308,13 +7582,13 @@ MkKernel.reduce :mean,
|
|
|
7308
7582
|
# variance = M2 / n (population) or M2 / (n-1) (sample)
|
|
7309
7583
|
# stddev = sqrt(fmax(variance, 0.0))
|
|
7310
7584
|
#
|
|
7311
|
-
#
|
|
7585
|
+
# Why two passes: the one-pass sum-of-squares
|
|
7312
7586
|
# form Σx² - (Σx)²/n loses precision catastrophically for large absolute
|
|
7313
7587
|
# values (e.g. mean=1e5 K temperatures with variance 1.0 -> rel_err 1e-2;
|
|
7314
7588
|
# mean >= 1e8 flips the sign of the raw diff and produces sqrt(neg)=NaN
|
|
7315
7589
|
# or values off by orders of magnitude). Two-pass centred subtracts the
|
|
7316
7590
|
# mean first, so (x - mean) is O(spread) and its square has no
|
|
7317
|
-
# cancellation. Both passes use the
|
|
7591
|
+
# cancellation. Both passes use the SIMD :plus macro
|
|
7318
7592
|
# so vectorization is preserved; PoC (M2 Max, 1M f64) shows 1.75x
|
|
7319
7593
|
# slowdown vs the one-pass form -- much smaller than Welford's 31x.
|
|
7320
7594
|
#
|
|
@@ -7377,21 +7651,19 @@ MkKernel.reduce :stddev,
|
|
|
7377
7651
|
mask_policy: :min_count,
|
|
7378
7652
|
public_method: true
|
|
7379
7653
|
|
|
7380
|
-
# ---- minmax
|
|
7654
|
+
# ---- minmax --------------------------------------------------------
|
|
7381
7655
|
|
|
7382
7656
|
# minmax_ki -- single-pass fused min+max reduction. Returns Ruby Array
|
|
7383
7657
|
# [min_val, max_val] for flat reduction, [min_ca, max_ca] for per-axis.
|
|
7384
7658
|
#
|
|
7385
|
-
# PoC
|
|
7659
|
+
# A PoC showed i64 1.73x / f64 2.00x speedup over
|
|
7386
7660
|
# `a.min; a.max` separate calls on Apple Silicon M2 (clang -O3 -march=native
|
|
7387
|
-
# -fopenmp-simd). The 2x f64 speedup survives
|
|
7661
|
+
# -fopenmp-simd). The 2x f64 speedup survives the reduction(min/max:)
|
|
7388
7662
|
# vectorizer reject because fminnm + fmaxnm dual-issue on M2's two FP pipes.
|
|
7389
7663
|
#
|
|
7390
7664
|
# if-form discipline for multi-reduction fused kernels:
|
|
7391
7665
|
# the body uses `if (v < lo) lo = v;` etc, NOT ternary `lo = (v < lo) ? v : lo;`.
|
|
7392
7666
|
# DO NOT change to ternary — pragma-less ILP path depends on if-form.
|
|
7393
|
-
#
|
|
7394
|
-
# FM.1.0 scope: mask not yet propagated (FM.1.5). Numeric data types only.
|
|
7395
7667
|
|
|
7396
7668
|
MkKernel.reduce :minmax,
|
|
7397
7669
|
state: { lo: :load_type, hi: :load_type },
|
|
@@ -7399,7 +7671,6 @@ MkKernel.reduce :minmax,
|
|
|
7399
7671
|
hi: { numeric: "T_LIMIT_LO", bool: "T_LIMIT_LO", object: "Qundef" } },
|
|
7400
7672
|
reduce: { numeric: "if (v < lo) lo = v; if (v > hi) hi = v;",
|
|
7401
7673
|
bool: "if (v < lo) lo = v; if (v > hi) hi = v;",
|
|
7402
|
-
# PROPOSAL_MKKERNEL_OBJECT_DTYPE_BRANCH Phase 3.5:
|
|
7403
7674
|
# CA_OBJECT minmax via Qundef sentinel + first-cell-init.
|
|
7404
7675
|
# One sentinel guards both lo + hi (they go Qundef
|
|
7405
7676
|
# together on init, get set together on first reduce).
|
|
@@ -7413,7 +7684,7 @@ MkKernel.reduce :minmax,
|
|
|
7413
7684
|
output: { bool: :u64, default: :preserve },
|
|
7414
7685
|
ruby_scalar: :auto,
|
|
7415
7686
|
fallback: :raise,
|
|
7416
|
-
mask_policy: :min_count, #
|
|
7687
|
+
mask_policy: :min_count, # match min / max
|
|
7417
7688
|
face_gate: :relift,
|
|
7418
7689
|
public_method: :minmax # bind public name `minmax` -> rb_ca_minmax_ki
|
|
7419
7690
|
# (= surface-name override, no actual legacy)
|
|
@@ -7433,8 +7704,7 @@ MkKernel.reduce :minmax,
|
|
|
7433
7704
|
# Exposed as Ruby `min_index` / `max_index` (= the naming rule that a
|
|
7434
7705
|
# method returning a position uses the `_index` suffix; see the rules
|
|
7435
7706
|
# table in guides/devel/00_glossary.md). These
|
|
7436
|
-
# replace the
|
|
7437
|
-
# retire (commit f5c7ecd). 3.0 breaking: name change from `*_addr` to
|
|
7707
|
+
# replace the 2.x `min_addr` / `max_addr`; the name change from `*_addr` to
|
|
7438
7708
|
# `*_index` is intentional.
|
|
7439
7709
|
#
|
|
7440
7710
|
# best_i starts at -1 (no cell taken yet), so the first unmasked non-NaN
|
|
@@ -7502,11 +7772,9 @@ MkKernel.reduce :argmax,
|
|
|
7502
7772
|
# view-flat row-major), no transform needed
|
|
7503
7773
|
# - 1 < naxes < ndim: raises ArgumentError (multi-axis partial
|
|
7504
7774
|
# view_flat would require slab→view-flat decomposition; not
|
|
7505
|
-
# implemented
|
|
7775
|
+
# implemented)
|
|
7506
7776
|
#
|
|
7507
|
-
# Replaces
|
|
7508
|
-
# PROPOSAL_TAKE_ALONG_AXIS rev2 follow-up commit (now removed; the
|
|
7509
|
-
# kernel below is the canonical impl).
|
|
7777
|
+
# Replaces a Ruby-side _argaddr_along_axis helper (now removed).
|
|
7510
7778
|
|
|
7511
7779
|
MkKernel.reduce :argmin_addr,
|
|
7512
7780
|
state: { best_v: :load_type, best_i: :int64_t },
|
|
@@ -7544,8 +7812,8 @@ MkKernel.reduce :argmax_addr,
|
|
|
7544
7812
|
all_nan_result: :undef,
|
|
7545
7813
|
public_method: :max_addr
|
|
7546
7814
|
|
|
7547
|
-
# accumulate -- sum that preserves input data_type (
|
|
7548
|
-
#
|
|
7815
|
+
# accumulate -- sum that preserves input data_type (the 2.x rb_ca_accum).
|
|
7816
|
+
# Same machinery as sum_ki but output: :preserve so
|
|
7549
7817
|
# int8 stays int8 (will overflow on long arrays = legacy behaviour).
|
|
7550
7818
|
# Use :sum for the safe widening f64 variant.
|
|
7551
7819
|
#
|
|
@@ -7566,17 +7834,17 @@ MkKernel.reduce :accumulate,
|
|
|
7566
7834
|
object: "INT2FIX(0)" },
|
|
7567
7835
|
reduce: { numeric: "acc += v", complex: "acc += v", bool: "acc ^= v",
|
|
7568
7836
|
object: 'acc = rb_funcall(acc, rb_intern("+"), 1, v)' },
|
|
7569
|
-
reduction_kind: :plus, #
|
|
7837
|
+
reduction_kind: :plus, # same mechanism as :sum, output preserve
|
|
7570
7838
|
no_simd_src: [:bool], # boolean lane is XOR, not the `+` :plus implies
|
|
7571
7839
|
source: MkKernel::ALL_NUMERIC + MkKernel::CMPLX_DTYPES + [:bool, :object],
|
|
7572
7840
|
output: :preserve,
|
|
7573
7841
|
ruby_scalar: :auto,
|
|
7574
7842
|
fallback: :raise,
|
|
7575
7843
|
mask_policy: :min_count,
|
|
7576
|
-
identity_on_empty: true, #
|
|
7844
|
+
identity_on_empty: true, # empty / all-masked -> 0 (additive identity)
|
|
7577
7845
|
public_method: true
|
|
7578
7846
|
|
|
7579
|
-
# count_true / count_false -- boolean-only reduction
|
|
7847
|
+
# count_true / count_false -- boolean-only reduction.
|
|
7580
7848
|
# Per-axis support via the standard mkkernel reduction machinery; flatten
|
|
7581
7849
|
# (= no axis arg) returns Ruby Integer directly via :LL2NUM ruby_scalar.
|
|
7582
7850
|
# Output data_type = :i64, matching count_equal (= count(v) numeric): a
|
|
@@ -7602,13 +7870,13 @@ MkKernel.reduce :accumulate,
|
|
|
7602
7870
|
MkKernel.reduce :count_true,
|
|
7603
7871
|
init: "0",
|
|
7604
7872
|
reduce: "acc += v",
|
|
7605
|
-
reduction_kind: :plus,
|
|
7873
|
+
reduction_kind: :plus,
|
|
7606
7874
|
source: [:bool],
|
|
7607
7875
|
output: :i64,
|
|
7608
7876
|
ruby_scalar: :LL2NUM,
|
|
7609
7877
|
mask_policy: :min_count,
|
|
7610
|
-
identity_on_empty: true #
|
|
7611
|
-
#
|
|
7878
|
+
identity_on_empty: true # empty / all-masked -> 0 (count over the empty set)
|
|
7879
|
+
# No public_method here -- the user-facing
|
|
7612
7880
|
# entry is `a.count(true)` on bool data_type which dispatches to this
|
|
7613
7881
|
# kernel via rb_ca_count in carray_count.c. The kernel itself stays
|
|
7614
7882
|
# bound only for internal C dispatch (no Ruby surface).
|
|
@@ -7616,15 +7884,15 @@ MkKernel.reduce :count_true,
|
|
|
7616
7884
|
MkKernel.reduce :count_false,
|
|
7617
7885
|
init: "0",
|
|
7618
7886
|
reduce: "acc += !v",
|
|
7619
|
-
reduction_kind: :plus,
|
|
7887
|
+
reduction_kind: :plus,
|
|
7620
7888
|
source: [:bool],
|
|
7621
7889
|
output: :i64,
|
|
7622
7890
|
ruby_scalar: :LL2NUM,
|
|
7623
7891
|
mask_policy: :min_count,
|
|
7624
|
-
identity_on_empty: true #
|
|
7625
|
-
#
|
|
7892
|
+
identity_on_empty: true # empty / all-masked -> 0 (count over the empty set)
|
|
7893
|
+
# See count_true above; `a.count(false)` is the user-facing entry.
|
|
7626
7894
|
|
|
7627
|
-
# count_equal --
|
|
7895
|
+
# count_equal -- a user of the value_arg: DSL framework.
|
|
7628
7896
|
# Numeric value-comparison count: counts cells where v == value_arg.
|
|
7629
7897
|
# value_arg is cast to the source data_type at the dispatcher boundary so
|
|
7630
7898
|
# integer == comparisons stay in integer space (no f64 round-trip),
|
|
@@ -7644,7 +7912,7 @@ MkKernel.reduce :count_equal,
|
|
|
7644
7912
|
# the same object.
|
|
7645
7913
|
reduce: { numeric: "if (v == value_arg) acc += 1",
|
|
7646
7914
|
object: "if (ca_obj_equal(v, value_arg)) acc += 1" },
|
|
7647
|
-
reduction_kind: :plus, #
|
|
7915
|
+
reduction_kind: :plus, # conditional predication (clang predicates safely under reduction(+:acc))
|
|
7648
7916
|
source: MkKernel::ALL_NUMERIC + [:object, :fixlen],
|
|
7649
7917
|
fixlen: :count_equal, # bespoke memcmp walk (a blob has no scalar C type)
|
|
7650
7918
|
output: :i64,
|
|
@@ -7652,18 +7920,16 @@ MkKernel.reduce :count_equal,
|
|
|
7652
7920
|
fallback: :raise,
|
|
7653
7921
|
value_arg: { target: :T_IN },
|
|
7654
7922
|
mask_policy: :min_count,
|
|
7655
|
-
identity_on_empty: true, #
|
|
7923
|
+
identity_on_empty: true, # empty / all-masked -> 0 (count of matches in the empty set)
|
|
7656
7924
|
bind_ruby: false # internal-only; count(v) dispatcher in carray_count.c
|
|
7657
7925
|
# is the user-facing entry
|
|
7658
7926
|
|
|
7659
|
-
# ---- weighted reduction family
|
|
7927
|
+
# ---- weighted reduction family ---------------------------------------
|
|
7660
7928
|
#
|
|
7661
|
-
#
|
|
7662
|
-
#
|
|
7663
|
-
# serves as the sole array_arg DSL contract pin via spec_ai/test_w2_wsum.rb.
|
|
7929
|
+
# The kernel below is what pins the array_arg DSL contract, via
|
|
7930
|
+
# spec_ai/test_w2_wsum.rb.
|
|
7664
7931
|
|
|
7665
|
-
# wsum --
|
|
7666
|
-
# proc_wsum macro retired in same commit). array_arg framework user.
|
|
7932
|
+
# wsum -- weighted sum. array_arg framework user.
|
|
7667
7933
|
#
|
|
7668
7934
|
# 3.0 breaking semantic changes vs legacy:
|
|
7669
7935
|
# - **calling convention**: legacy `wsum(weights, min_count, fill_value)`
|
|
@@ -7673,7 +7939,7 @@ MkKernel.reduce :count_equal,
|
|
|
7673
7939
|
# the old form now means "reduce axis 0" (= per-axis).
|
|
7674
7940
|
# - **min_count semantic**: legacy was "max masked tolerable" (count >
|
|
7675
7941
|
# min_count -> UNDEF), new is "min valid required" (valid_count <
|
|
7676
|
-
# min_count -> UNDEF)
|
|
7942
|
+
# min_count -> UNDEF), as for sum / mean (= feature_mask_spec
|
|
7677
7943
|
# line 371-374 documents the mapping).
|
|
7678
7944
|
# - **complex / CA_OBJECT dropped**: legacy CMPLX64/CMPLX128/CA_OBJECT
|
|
7679
7945
|
# paths removed (= ALL_NUMERIC + :raise fallback). Re-add via demand-
|
|
@@ -7688,7 +7954,7 @@ MkKernel.reduce :count_equal,
|
|
|
7688
7954
|
MkKernel.reduce :wsum,
|
|
7689
7955
|
init: "0.0",
|
|
7690
7956
|
reduce: "acc += (double) v * (double) w",
|
|
7691
|
-
reduction_kind: :plus, #
|
|
7957
|
+
reduction_kind: :plus, # FMA-friendly weighted sum
|
|
7692
7958
|
source: MkKernel::ALL_NUMERIC,
|
|
7693
7959
|
output: :f64,
|
|
7694
7960
|
ruby_scalar: :rb_float_new,
|
|
@@ -7696,12 +7962,31 @@ MkKernel.reduce :wsum,
|
|
|
7696
7962
|
array_arg: { name: :weights, data_type: :promote,
|
|
7697
7963
|
shape: :rev5_strict, mask: :overlay },
|
|
7698
7964
|
mask_policy: :min_count,
|
|
7699
|
-
identity_on_empty: true, #
|
|
7965
|
+
identity_on_empty: true, # empty / all-masked -> 0.0 (weighted sum identity)
|
|
7700
7966
|
object_escape: :wsum_object, # CA_OBJECT -> (w*self).sum (runtime.rb)
|
|
7967
|
+
bool_as: :u8, # a boolean array weighs its 0/1 cells
|
|
7968
|
+
integer_total: :wsum_wrapping, # integer values and weights: the exact total, float64 past the range
|
|
7701
7969
|
bind_ruby: true,
|
|
7702
7970
|
public_method: true
|
|
7703
7971
|
|
|
7704
|
-
#
|
|
7972
|
+
# wsum_wrapping: the weighted sum of an integer array with integer weights,
|
|
7973
|
+
# in int64 / uint64, wrapping at 2**64. Each product is taken modulo 2**64
|
|
7974
|
+
# too, so the total is exact modulo 2**64. The weights are read as int64,
|
|
7975
|
+
# which keeps the bits of a uint64 weight. ca_integer_total reads it.
|
|
7976
|
+
MkKernel.reduce :wsum_wrapping,
|
|
7977
|
+
init: "0",
|
|
7978
|
+
reduce: "acc += (uint64_t) v * (uint64_t) w",
|
|
7979
|
+
reduction_kind: :plus,
|
|
7980
|
+
source: MkKernel::INT_DTYPES,
|
|
7981
|
+
output: { sint: :i64, uint: :u64 },
|
|
7982
|
+
ruby_scalar: :auto,
|
|
7983
|
+
fallback: :raise,
|
|
7984
|
+
array_arg: { name: :weights, data_type: :int64,
|
|
7985
|
+
shape: :rev5_strict, mask: :overlay },
|
|
7986
|
+
mask_policy: :min_count,
|
|
7987
|
+
identity_on_empty: true
|
|
7988
|
+
|
|
7989
|
+
# wmean -- weighted mean. Same array_arg
|
|
7705
7990
|
# framework as wsum, but uses state+finish form (= sum + den) for the
|
|
7706
7991
|
# normalisation `mean = Σv*w / Σw` semantic.
|
|
7707
7992
|
#
|
|
@@ -7709,9 +7994,9 @@ MkKernel.reduce :wsum,
|
|
|
7709
7994
|
# both signs) leave the mean undefined: the cell is UNDEF, as for a slab
|
|
7710
7995
|
# with no valid cell, rather than 0/0 = NaN or x/0 = +-Infinity.
|
|
7711
7996
|
#
|
|
7712
|
-
# 3.0 breaking semantic changes vs legacy (= identical to wsum
|
|
7997
|
+
# 3.0 breaking semantic changes vs legacy (= identical to wsum):
|
|
7713
7998
|
# - calling convention positional -> kwargs (axes positional, opts kw)
|
|
7714
|
-
# - min_count semantic "max masked" -> "min valid required"
|
|
7999
|
+
# - min_count semantic "max masked" -> "min valid required"
|
|
7715
8000
|
# - complex (CMPLX64/128) dropped (= ALL_NUMERIC + :raise)
|
|
7716
8001
|
# - per-axis support gained
|
|
7717
8002
|
# CA_OBJECT is handled via object_escape (runtime.rb wmean_object), not
|
|
@@ -7722,7 +8007,7 @@ MkKernel.reduce :wmean,
|
|
|
7722
8007
|
state: { sum: :acc_type, den: :acc_type },
|
|
7723
8008
|
init: { sum: "0", den: "0" },
|
|
7724
8009
|
reduce: "(sum += (double) v * (double) w, den += (double) w)",
|
|
7725
|
-
reduction_kind: { sum: :plus, den: :plus },
|
|
8010
|
+
reduction_kind: { sum: :plus, den: :plus },
|
|
7726
8011
|
finish: "sum / den",
|
|
7727
8012
|
undefined_if: "den == 0",
|
|
7728
8013
|
source: MkKernel::ALL_NUMERIC,
|
|
@@ -7733,13 +8018,14 @@ MkKernel.reduce :wmean,
|
|
|
7733
8018
|
shape: :rev5_strict, mask: :overlay },
|
|
7734
8019
|
mask_policy: :min_count,
|
|
7735
8020
|
object_escape: :wmean_object, # CA_OBJECT -> weighted mean via runtime.rb
|
|
8021
|
+
bool_as: :u8, # a boolean array weighs its 0/1 cells
|
|
7736
8022
|
bind_ruby: true,
|
|
7737
8023
|
public_method: true
|
|
7738
8024
|
|
|
7739
8025
|
# ---- scan kernels (cumulative / prefix scan along one axis) ----------
|
|
7740
8026
|
|
|
7741
8027
|
# cumsum / cumprod: data_type-conditional output (numeric -> f64 widening,
|
|
7742
|
-
# complex -> cmplx128 widening). Matches the
|
|
8028
|
+
# complex -> cmplx128 widening). Matches the earlier hand-written
|
|
7743
8029
|
# rb_ca_cumsum / rb_ca_cumprod which widened cmplx64/cmplx128 inputs to
|
|
7744
8030
|
# cmplx128 outputs. Object / bool / fixlen raise explicitly via
|
|
7745
8031
|
# fallback: :raise (3.0 breaking from the old :wrap_to_f64 that silently
|
|
@@ -7755,7 +8041,20 @@ MkKernel.scan :cumsum,
|
|
|
7755
8041
|
bool: "acc += v; r = acc",
|
|
7756
8042
|
object: 'acc = rb_funcall(acc, rb_intern("+"), 1, v); r = acc' },
|
|
7757
8043
|
fallback: :raise,
|
|
7758
|
-
axis_default: :flatten
|
|
8044
|
+
axis_default: :flatten,
|
|
8045
|
+
integer_total: :cumsum_wrapping
|
|
8046
|
+
|
|
8047
|
+
# The running sum of an integer array in int64 / uint64, wrapping: the
|
|
8048
|
+
# integer half of cumsum (ca_integer_scan checks it against the float64
|
|
8049
|
+
# scan where it may have wrapped).
|
|
8050
|
+
MkKernel.scan :cumsum_wrapping,
|
|
8051
|
+
source: MkKernel::INT_DTYPES,
|
|
8052
|
+
output: { sint: :i64, uint: :u64 },
|
|
8053
|
+
init: "0",
|
|
8054
|
+
step: "acc += v; r = acc",
|
|
8055
|
+
fallback: :raise,
|
|
8056
|
+
axis_default: :flatten,
|
|
8057
|
+
private: true
|
|
7759
8058
|
|
|
7760
8059
|
# The running sum in the source's own integer type, added without a range
|
|
7761
8060
|
# check (int64 wraps, as accumulate does). CATimedelta#cumsum reads it
|
|
@@ -7778,7 +8077,19 @@ MkKernel.scan :cumprod,
|
|
|
7778
8077
|
bool: "acc *= v; r = acc",
|
|
7779
8078
|
object: 'acc = rb_funcall(acc, rb_intern("*"), 1, v); r = acc' },
|
|
7780
8079
|
fallback: :raise,
|
|
7781
|
-
axis_default: :flatten
|
|
8080
|
+
axis_default: :flatten,
|
|
8081
|
+
integer_total: :cumprod_wrapping
|
|
8082
|
+
|
|
8083
|
+
# The running product of an integer array in int64 / uint64, wrapping: the
|
|
8084
|
+
# integer half of cumprod.
|
|
8085
|
+
MkKernel.scan :cumprod_wrapping,
|
|
8086
|
+
source: MkKernel::INT_DTYPES,
|
|
8087
|
+
output: { sint: :i64, uint: :u64 },
|
|
8088
|
+
init: "1",
|
|
8089
|
+
step: "acc *= v; r = acc",
|
|
8090
|
+
fallback: :raise,
|
|
8091
|
+
axis_default: :flatten,
|
|
8092
|
+
private: true
|
|
7782
8093
|
|
|
7783
8094
|
# cummax / cummin: running extremum with no identity. Until a fiber's
|
|
7784
8095
|
# first present (unmasked) cell, the running extremum is undefined, so the
|
|
@@ -7854,8 +8165,7 @@ MkKernel.scan :cumcount,
|
|
|
7854
8165
|
# masked positions are already set).
|
|
7855
8166
|
#
|
|
7856
8167
|
# Designed for use AFTER sort_addr(axis:) gather, so equal values
|
|
7857
|
-
# already cluster together adjacent along the scan axis.
|
|
7858
|
-
# PROPOSAL_UNIQ_AXIS.md §3 for the full pipeline.
|
|
8168
|
+
# already cluster together adjacent along the scan axis.
|
|
7859
8169
|
#
|
|
7860
8170
|
# acc_type: :load_type -> acc carries T_LOAD (= last seen input value).
|
|
7861
8171
|
# STEP additionally sees `first` (int) marking the first live cell of
|
|
@@ -7874,7 +8184,7 @@ MkKernel.scan :uniq_scan,
|
|
|
7874
8184
|
step: "if (first) { acc = v; r = 0; } else if (v == acc) { r = 1; } else { acc = v; r = 0; }",
|
|
7875
8185
|
fallback: :raise
|
|
7876
8186
|
|
|
7877
|
-
# ---- Sort family kernels
|
|
8187
|
+
# ---- Sort family kernels -----------------------------------------------
|
|
7878
8188
|
#
|
|
7879
8189
|
# sort_index: per-axis sort index. Returns CA_SIZE array of fiber-local
|
|
7880
8190
|
# indices (= 0..dim[axis]-1) giving the sorted order along axis k.
|
|
@@ -7897,8 +8207,6 @@ MkKernel.sort :sort_index,
|
|
|
7897
8207
|
# fiber-local indices, so the output can feed directly into
|
|
7898
8208
|
# ca_remap_new as a CARemap.idx. Internal-only (bind_ruby: false):
|
|
7899
8209
|
# used by `a.sort(axis: k)` at the C level via rb_ca_sort_addr_ki_*_mp.
|
|
7900
|
-
# rev3 of PROPOSAL_SORT_AXIS defers `sort_addr(axis: k)` as a public
|
|
7901
|
-
# method to a future phase; here we just need the kernel machinery.
|
|
7902
8210
|
MkKernel.sort :sort_addr,
|
|
7903
8211
|
source: MkKernel::ALL_NUMERIC + [:bool] + [:object] + [:fixlen],
|
|
7904
8212
|
output: :ca_size,
|
|
@@ -7955,8 +8263,8 @@ MkKernel.sort :partition_addr,
|
|
|
7955
8263
|
#
|
|
7956
8264
|
# Algorithmic identity: rank = sort_index ** -1 (inverse permutation),
|
|
7957
8265
|
# computed in one pass as "sort by value, then scatter rank at original
|
|
7958
|
-
# axis-local position".
|
|
7959
|
-
#
|
|
8266
|
+
# axis-local position". The public CArray#rank_index (with descending: and
|
|
8267
|
+
# method:) is bound in carray_order.c on top of this kernel.
|
|
7960
8268
|
MkKernel.sort :rank_index,
|
|
7961
8269
|
source: MkKernel::ALL_NUMERIC + [:bool] + [:object] + [:fixlen],
|
|
7962
8270
|
output: :ca_size,
|
|
@@ -7965,17 +8273,10 @@ MkKernel.sort :rank_index,
|
|
|
7965
8273
|
fallback: :raise,
|
|
7966
8274
|
algorithm: :rank,
|
|
7967
8275
|
mask_self: :skip,
|
|
7968
|
-
|
|
7969
|
-
c_callable: true # extern linkage for carray_order.c (order method)
|
|
8276
|
+
c_callable: true # extern linkage for carray_order.c (rank_index)
|
|
7970
8277
|
|
|
7971
8278
|
# ---- search family ------------------------------------------------------
|
|
7972
8279
|
#
|
|
7973
|
-
# Phase S.1 (PROPOSAL_SEARCH_AXIS_S1.md): demo kernel for the search form.
|
|
7974
|
-
# S.1.2a scope: case A (= scalar query) only. S.1.2b will extend case B
|
|
7975
|
-
# (val.shape append to output tail) and case C (val.shape == base_shape).
|
|
7976
|
-
# S.2-S.4 will land production family kernels (bsearch / search /
|
|
7977
|
-
# search_nearest) using this same DSL form.
|
|
7978
|
-
#
|
|
7979
8280
|
# find_value_index_ki: per-slice linear scan returning the first matching
|
|
7980
8281
|
# position (first index where slice == v). No-match returns
|
|
7981
8282
|
# -1 sentinel (mapped to nil in scalar return path). mask_self: :raise
|
|
@@ -8030,8 +8331,7 @@ MkKernel.search :find_value_index,
|
|
|
8030
8331
|
#
|
|
8031
8332
|
# Source coverage: ALL_NUMERIC + object (rb_funcall <=> ordering) + fixlen
|
|
8032
8333
|
# (memcmp lexicographic). This is the sole bsearch implementation: the
|
|
8033
|
-
# no-axis (flat) surface routes here via flatten + axis 0
|
|
8034
|
-
# (PROPOSAL_SEARCH_SEMANTICS_UNIFY S2/S3; the legacy flat scan was removed).
|
|
8334
|
+
# no-axis (flat) surface routes here via flatten + axis 0.
|
|
8035
8335
|
MkKernel.search :bsearch,
|
|
8036
8336
|
source: MkKernel::ALL_NUMERIC + [:bool, :object, :fixlen],
|
|
8037
8337
|
output: :ca_size,
|
|
@@ -8112,10 +8412,9 @@ MkKernel.search :bsearch,
|
|
|
8112
8412
|
# uses `fabs(v - query_val) <= query_eps` (eps_default = FLT_EPSILON*|val|
|
|
8113
8413
|
# or DBL_EPSILON*|val|); object uses ca_obj_equal (eps ignored); fixlen uses
|
|
8114
8414
|
# memcmp exact match (eps ignored). Sole search implementation: the
|
|
8115
|
-
# no-axis (flat) surface routes here via flatten + axis 0
|
|
8116
|
-
# (PROPOSAL_SEARCH_SEMANTICS_UNIFY S2/S3; the legacy flat scan was removed).
|
|
8415
|
+
# no-axis (flat) surface routes here via flatten + axis 0.
|
|
8117
8416
|
MkKernel.search :search,
|
|
8118
|
-
source: MkKernel::ALL_NUMERIC + [:bool, :object, :fixlen],
|
|
8417
|
+
source: MkKernel::ALL_NUMERIC + MkKernel::CMPLX_DTYPES + [:bool, :object, :fixlen],
|
|
8119
8418
|
output: :ca_size,
|
|
8120
8419
|
body: {
|
|
8121
8420
|
int: <<~C,
|
|
@@ -8135,6 +8434,15 @@ MkKernel.search :search,
|
|
|
8135
8434
|
if ( v == query_val || fabs((double)(v - query_val)) <= query_eps ) { result = i; break; }
|
|
8136
8435
|
}
|
|
8137
8436
|
C
|
|
8437
|
+
complex: <<~C,
|
|
8438
|
+
/* complex: equal, or within query_eps of the query in modulus */
|
|
8439
|
+
result = (ca_size_t) -1;
|
|
8440
|
+
for ( ca_size_t i = 0; i < slab_n; i++ ) {
|
|
8441
|
+
if ( mask_in && mask_in[i * slab_mask_stride] ) continue;
|
|
8442
|
+
T_LOAD v = *(T_LOAD *)(slab_ptr + i * slab_stride);
|
|
8443
|
+
if ( v == query_val || cabs((ca_u_cmplx128_t)(v - query_val)) <= query_eps ) { result = i; break; }
|
|
8444
|
+
}
|
|
8445
|
+
C
|
|
8138
8446
|
object: <<~C,
|
|
8139
8447
|
/* CA_OBJECT search: exact equality via ca_obj_equal. eps is silently
|
|
8140
8448
|
ignored (= no meaningful tolerance on arbitrary Ruby objects). */
|
|
@@ -8333,7 +8641,7 @@ MkKernel.search :bsearch_addr,
|
|
|
8333
8641
|
semantics: :view_flat
|
|
8334
8642
|
|
|
8335
8643
|
MkKernel.search :search_addr,
|
|
8336
|
-
source: MkKernel::ALL_NUMERIC + [:bool, :object, :fixlen],
|
|
8644
|
+
source: MkKernel::ALL_NUMERIC + MkKernel::CMPLX_DTYPES + [:bool, :object, :fixlen],
|
|
8337
8645
|
output: :ca_size,
|
|
8338
8646
|
body: {
|
|
8339
8647
|
int: <<~C,
|
|
@@ -8353,6 +8661,15 @@ MkKernel.search :search_addr,
|
|
|
8353
8661
|
if ( v == query_val || fabs((double)v - (double)query_val) <= query_eps ) { result = i; break; }
|
|
8354
8662
|
}
|
|
8355
8663
|
C
|
|
8664
|
+
complex: <<~C,
|
|
8665
|
+
/* complex: equal, or within query_eps of the query in modulus */
|
|
8666
|
+
result = (ca_size_t) -1;
|
|
8667
|
+
for ( ca_size_t i = 0; i < slab_n; i++ ) {
|
|
8668
|
+
if ( mask_in && mask_in[i * slab_mask_stride] ) continue;
|
|
8669
|
+
T_LOAD v = *(T_LOAD *)(slab_ptr + i * slab_stride);
|
|
8670
|
+
if ( v == query_val || cabs((ca_u_cmplx128_t)(v - query_val)) <= query_eps ) { result = i; break; }
|
|
8671
|
+
}
|
|
8672
|
+
C
|
|
8356
8673
|
object: <<~C,
|
|
8357
8674
|
result = (ca_size_t) -1;
|
|
8358
8675
|
(void) query_eps;
|
|
@@ -8456,7 +8773,7 @@ MkKernel.search :search_nearest_addr,
|
|
|
8456
8773
|
fallback: :raise,
|
|
8457
8774
|
semantics: :view_flat
|
|
8458
8775
|
|
|
8459
|
-
# ---- LINEAR_INTERP_AXIS
|
|
8776
|
+
# ---- LINEAR_INTERP_AXIS ---------------------------------------------------
|
|
8460
8777
|
#
|
|
8461
8778
|
# Per-axis 1-D linear interpolation family, replacing legacy section /
|
|
8462
8779
|
# section_linear / vectorized_section{,_linear} / fetch_linear_addr{,_*} /
|
|
@@ -8474,13 +8791,12 @@ MkKernel.search :search_nearest_addr,
|
|
|
8474
8791
|
# Integer self is cast in the Ruby wrapper (lib/carray/ordering.rb).
|
|
8475
8792
|
#
|
|
8476
8793
|
# No-match sentinel = NaN. Scalar return path uses isnan() detection
|
|
8477
|
-
# (= via the no_match_check: DSL hook
|
|
8794
|
+
# (= via the no_match_check: DSL hook) to return Qnil.
|
|
8478
8795
|
# Array return path leaves NaN in the output cell (= matches existing
|
|
8479
|
-
# search family pattern, no mask creation
|
|
8796
|
+
# search family pattern, no mask creation).
|
|
8480
8797
|
#
|
|
8481
|
-
# SLAB API (= MkKernel.search form)
|
|
8482
|
-
#
|
|
8483
|
-
# verdict for the same kind of early-break + scalar-output kernels.
|
|
8798
|
+
# Written with the SLAB API (= MkKernel.search form), as the other
|
|
8799
|
+
# early-break + scalar-output kernels are.
|
|
8484
8800
|
|
|
8485
8801
|
MkKernel.search :linear_section_binary,
|
|
8486
8802
|
source: [:f64],
|
|
@@ -8634,10 +8950,9 @@ MkKernel.search :linear_fetch,
|
|
|
8634
8950
|
C
|
|
8635
8951
|
fallback: :raise
|
|
8636
8952
|
|
|
8637
|
-
# ----
|
|
8953
|
+
# ---- math family (monop / monfunc / binop / moncmp / bincmp) ----
|
|
8638
8954
|
#
|
|
8639
|
-
#
|
|
8640
|
-
# ext/carray_math.rb to mkkernel.rb so a single op definition emits both
|
|
8955
|
+
# The eager math kernel declarations live here so a single op definition emits both
|
|
8641
8956
|
# the eager surface (= `rb_ca_<name>` + `ca_<form>_<name>[CA_NTYPE]`
|
|
8642
8957
|
# table) AND, via ca_<form>_dispatch.c which extern-references the
|
|
8643
8958
|
# tables, the lazy (CAMonOp / CABinOp / CAMonCmp / CABinCmp) dispatch
|
|
@@ -8733,7 +9048,7 @@ MkKernel.monop :abs,
|
|
|
8733
9048
|
# the cabs() sqrt. Provided as a first-class primitive so that code
|
|
8734
9049
|
# working over either real or complex arrays can use the same idiom, and
|
|
8735
9050
|
# so that "distance squared" style expressions (Mandelbrot escape,
|
|
8736
|
-
# optics, signal processing) do not
|
|
9051
|
+
# optics, signal processing) do not compute a sqrt they immediately
|
|
8737
9052
|
# square away.
|
|
8738
9053
|
#
|
|
8739
9054
|
# Output data_type follows :abs: numeric preserved, complex demoted to
|
|
@@ -8821,6 +9136,14 @@ MkKernel.monop :imag_i,
|
|
|
8821
9136
|
object: '(#2) = rb_funcall((#1), rb_intern("imaginary"), 0);',
|
|
8822
9137
|
}.merge(MkKernel.cmplx_widths("(#2) = cimag<f>(#1);"))
|
|
8823
9138
|
|
|
9139
|
+
# real_i: each cell's `real`, for an object array (a numeric or complex
|
|
9140
|
+
# array's real part is a view of it, which CArray#real returns instead).
|
|
9141
|
+
MkKernel.monop :real_i,
|
|
9142
|
+
source: [:object],
|
|
9143
|
+
expr: {
|
|
9144
|
+
object: '(#2) = rb_funcall((#1), rb_intern("real"), 0);',
|
|
9145
|
+
}
|
|
9146
|
+
|
|
8824
9147
|
# arg_i: data_type-preserving kernel that writes the complex argument
|
|
8825
9148
|
# (phase angle) into the slot. For complex input, cassignment from a
|
|
8826
9149
|
# double zeros the imag, so cimag stays 0 (same trick as abs_i / imag_i);
|
|
@@ -9068,21 +9391,18 @@ MkKernel.monfunc :deg_360,
|
|
|
9068
9391
|
expr: {
|
|
9069
9392
|
float: <<~C,
|
|
9070
9393
|
{
|
|
9071
|
-
double
|
|
9072
|
-
|
|
9073
|
-
(#2)
|
|
9074
|
-
? (_fa - floor(_fa)) * 360.0
|
|
9075
|
-
: (_fa - ceil(_fa) + 1.0) * 360.0;
|
|
9394
|
+
double _fa = (double)(#1) / 360.0;
|
|
9395
|
+
(#2) = (_fa - floor(_fa)) * 360.0;
|
|
9396
|
+
if ( (#2) >= 360.0 ) (#2) = 0.0; /* a tiny negative rounds to the top */
|
|
9076
9397
|
}
|
|
9077
9398
|
C
|
|
9078
9399
|
object: <<~SNIPPET,
|
|
9079
9400
|
{
|
|
9080
9401
|
VALUE _obj_arg = (#1);
|
|
9081
9402
|
if (RB_FLOAT_TYPE_P(_obj_arg) || RB_INTEGER_TYPE_P(_obj_arg) || RB_TYPE_P(_obj_arg, T_RATIONAL)) {
|
|
9082
|
-
double
|
|
9083
|
-
double
|
|
9084
|
-
(#2) = DBL2NUM(
|
|
9085
|
-
: (_fa - ceil(_fa) + 1.0) * 360.0);
|
|
9403
|
+
double _fa = NUM2DBL(_obj_arg) / 360.0;
|
|
9404
|
+
double _r = (_fa - floor(_fa)) * 360.0;
|
|
9405
|
+
(#2) = DBL2NUM(_r >= 360.0 ? 0.0 : _r);
|
|
9086
9406
|
} else {
|
|
9087
9407
|
(#2) = rb_funcall(_obj_arg, rb_intern("deg_360"), 0);
|
|
9088
9408
|
}
|
|
@@ -9090,7 +9410,7 @@ MkKernel.monfunc :deg_360,
|
|
|
9090
9410
|
SNIPPET
|
|
9091
9411
|
}
|
|
9092
9412
|
|
|
9093
|
-
# deg_180: fold into
|
|
9413
|
+
# deg_180: fold into (-180, 180]. Preserves trailing `if (b <= -180)
|
|
9094
9414
|
# b += 360` guard from the legacy implementation.
|
|
9095
9415
|
MkKernel.monfunc :deg_180,
|
|
9096
9416
|
source: MkKernel::FLOAT_DTYPES + [:object],
|
|
@@ -9130,11 +9450,9 @@ MkKernel.monfunc :rad_2pi,
|
|
|
9130
9450
|
float: <<~C,
|
|
9131
9451
|
{
|
|
9132
9452
|
double _two_pi = 2.0 * M_PI;
|
|
9133
|
-
double
|
|
9134
|
-
|
|
9135
|
-
(#2)
|
|
9136
|
-
? (_fa - floor(_fa)) * _two_pi
|
|
9137
|
-
: (_fa - ceil(_fa) + 1.0) * _two_pi;
|
|
9453
|
+
double _fa = (double)(#1) / _two_pi;
|
|
9454
|
+
(#2) = (_fa - floor(_fa)) * _two_pi;
|
|
9455
|
+
if ( (#2) >= _two_pi ) (#2) = 0.0; /* a tiny negative rounds to the top */
|
|
9138
9456
|
}
|
|
9139
9457
|
C
|
|
9140
9458
|
object: <<~SNIPPET,
|
|
@@ -9142,10 +9460,9 @@ MkKernel.monfunc :rad_2pi,
|
|
|
9142
9460
|
VALUE _obj_arg = (#1);
|
|
9143
9461
|
if (RB_FLOAT_TYPE_P(_obj_arg) || RB_INTEGER_TYPE_P(_obj_arg) || RB_TYPE_P(_obj_arg, T_RATIONAL)) {
|
|
9144
9462
|
double _two_pi = 2.0 * M_PI;
|
|
9145
|
-
double
|
|
9146
|
-
double
|
|
9147
|
-
(#2) = DBL2NUM(
|
|
9148
|
-
: (_fa - ceil(_fa) + 1.0) * _two_pi);
|
|
9463
|
+
double _fa = NUM2DBL(_obj_arg) / _two_pi;
|
|
9464
|
+
double _r = (_fa - floor(_fa)) * _two_pi;
|
|
9465
|
+
(#2) = DBL2NUM(_r >= _two_pi ? 0.0 : _r);
|
|
9149
9466
|
} else {
|
|
9150
9467
|
(#2) = rb_funcall(_obj_arg, rb_intern("rad_2pi"), 0);
|
|
9151
9468
|
}
|
|
@@ -9187,15 +9504,12 @@ MkKernel.monfunc :rad_pi,
|
|
|
9187
9504
|
SNIPPET
|
|
9188
9505
|
}
|
|
9189
9506
|
|
|
9190
|
-
# ----
|
|
9507
|
+
# ---- binop family --------------------------------------------------
|
|
9191
9508
|
|
|
9192
|
-
# Pair-wise max / min —
|
|
9509
|
+
# Pair-wise max / min — two flavours:
|
|
9193
9510
|
#
|
|
9194
9511
|
# pmax / pmin CArray legacy names (kept for backwards compat),
|
|
9195
9512
|
# NaN-skip semantics, as C99 fmax / fmin.
|
|
9196
|
-
# fmax / fmin Ruby-level aliases of pmax / pmin (= same kernel,
|
|
9197
|
-
# same NaN-skip behaviour). Matches the C99 library
|
|
9198
|
-
# function of the same name.
|
|
9199
9513
|
# maximum / minimum NaN-propagate semantics: if either operand is
|
|
9200
9514
|
# NaN the result is NaN. Distinct kernel — cannot be
|
|
9201
9515
|
# aliased onto pmax.
|
|
@@ -9404,7 +9718,9 @@ MkKernel.binop :bit_or_i,
|
|
|
9404
9718
|
kleene: :or,
|
|
9405
9719
|
source: MkKernel::INT_DTYPES + [:bool, :object],
|
|
9406
9720
|
expr: {
|
|
9407
|
-
|
|
9721
|
+
# 0 / 1 even when a side is a masked cell: its byte is not defined, and
|
|
9722
|
+
# an OR that Kleene resolves to true keeps the value written here.
|
|
9723
|
+
bool: "(#3) = ((#1) | (#2)) ? 1 : 0;",
|
|
9408
9724
|
int: "(#3) = (#1) | (#2);",
|
|
9409
9725
|
object: '(#3) = rb_funcall((#1), rb_intern("|"), 1, (#2));',
|
|
9410
9726
|
}
|
|
@@ -9497,13 +9813,6 @@ MkKernel.binop :xor,
|
|
|
9497
9813
|
}
|
|
9498
9814
|
|
|
9499
9815
|
# Binop aliases (= rb_define_alias of the Ruby operator method).
|
|
9500
|
-
# `fmax` / `fmin` — Ruby-level aliases of `pmax` / `pmin`. Same
|
|
9501
|
-
# kernel, same NaN-skip semantics. Provides a name that C-stdlib
|
|
9502
|
-
# users will recognise (= `<math.h>` `fmax`).
|
|
9503
|
-
# NaN-propagate variants are the separate `maximum` / `minimum`
|
|
9504
|
-
# kernels registered above.
|
|
9505
|
-
MkKernel.alias_binop :fmax, :pmax
|
|
9506
|
-
MkKernel.alias_binop :fmin, :pmin
|
|
9507
9816
|
|
|
9508
9817
|
MkKernel.alias_binop :add, :"+"
|
|
9509
9818
|
MkKernel.alias_binop :sub, :"-"
|
|
@@ -9516,9 +9825,10 @@ MkKernel.alias_binop :bit_xor, :"^"
|
|
|
9516
9825
|
MkKernel.alias_binop :bit_lshift, :"<<"
|
|
9517
9826
|
MkKernel.alias_binop :bit_rshift, :">>"
|
|
9518
9827
|
|
|
9519
|
-
#
|
|
9828
|
+
# Power binop. Integer variants use `op_powi_<type>` from
|
|
9520
9829
|
# ca_op_powi.h (binary exponentiation, O(log p)). Float / complex use
|
|
9521
|
-
# pow / cpow. Object uses Ruby's `**`.
|
|
9830
|
+
# pow / cpow. Object uses Ruby's `**`. No Ruby method: CArray#pow,
|
|
9831
|
+
# #** and #pow! (ext/ca_op_ipower.c) call rb_ca_power / rb_ca_power_bang.
|
|
9522
9832
|
MkKernel.header_block <<~C
|
|
9523
9833
|
#include "ca_op_powi.h"
|
|
9524
9834
|
#include "ca_op_cmplx64.h"
|
|
@@ -9603,13 +9913,13 @@ MkKernel.triop :select,
|
|
|
9603
9913
|
}
|
|
9604
9914
|
|
|
9605
9915
|
MkKernel.binop :power,
|
|
9606
|
-
|
|
9916
|
+
bind: false,
|
|
9607
9917
|
source: MkKernel::MATH_NUMERIC + [:object],
|
|
9608
9918
|
expr: {
|
|
9609
9919
|
int: "(#3) = op_powi_<type>((#1), (#2));",
|
|
9610
|
-
complex: "
|
|
9920
|
+
complex: MkKernel.pow_short("cpow((#1), (#2))"), # see exp2 on why cpow stays wide
|
|
9611
9921
|
object: '(#3) = rb_funcall((#1), rb_intern("**"), 1, (#2));',
|
|
9612
|
-
}.merge(MkKernel.float_widths("
|
|
9922
|
+
}.merge(MkKernel.float_widths(MkKernel.pow_short("pow<f>((#1), (#2))")))
|
|
9613
9923
|
|
|
9614
9924
|
# ---- M.2 + M.3 (PyTorch alignment): float-only binop family --------------
|
|
9615
9925
|
#
|
|
@@ -9671,7 +9981,7 @@ MkKernel.binop :logaddexp,
|
|
|
9671
9981
|
}.merge(MkKernel.float_widths(
|
|
9672
9982
|
"(#3) = fmax<f>((#1), (#2)) + log1p<f>(exp<f>(-fabs<f>((#1) - (#2))));"))
|
|
9673
9983
|
|
|
9674
|
-
# ----
|
|
9984
|
+
# ---- moncmp family (predicates returning bool) ----------------
|
|
9675
9985
|
|
|
9676
9986
|
MkKernel.moncmp :is_nan,
|
|
9677
9987
|
source: MkKernel::MATH_NUMERIC + [:object],
|
|
@@ -9737,7 +10047,7 @@ MkKernel.moncmp :signbit,
|
|
|
9737
10047
|
'(RTEST(rb_funcall((#1), rb_intern("negative?"), 0)) ? 1 : 0);',
|
|
9738
10048
|
}
|
|
9739
10049
|
|
|
9740
|
-
# ----
|
|
10050
|
+
# ---- bincmp family (predicates returning bool) ----------------
|
|
9741
10051
|
|
|
9742
10052
|
# feq: float-only fuzzy equality using <epsilon> placeholder.
|
|
9743
10053
|
MkKernel.bincmp :feq,
|
|
@@ -9853,14 +10163,27 @@ MkKernel.alias_bincmp :"=~", :match
|
|
|
9853
10163
|
# NaN-safe via (#1) == (#2) short-circuit for identical values
|
|
9854
10164
|
# including 0 / 0 (= legacy semantics).
|
|
9855
10165
|
#
|
|
9856
|
-
# Integer ops
|
|
9857
|
-
#
|
|
10166
|
+
# Integer ops take the difference exactly. Below 8 bytes it is a double
|
|
10167
|
+
# (|a - b| < 2**33); for 8-byte types it is a uint64 (|a - b| of two cells
|
|
10168
|
+
# of one type is below 2**64), compared with tol without rounding it to
|
|
10169
|
+
# double. Operands no single integer type holds are answered before the
|
|
10170
|
+
# kernel (ca_bincmp_tolerance_integer_prepare).
|
|
10171
|
+
# Complex ops use cabs().
|
|
9858
10172
|
|
|
9859
10173
|
MkKernel.bincmp :is_close,
|
|
9860
10174
|
source: MkKernel::ALL_NUMERIC + MkKernel::CMPLX_DTYPES,
|
|
9861
10175
|
tolerance: true,
|
|
9862
10176
|
expr: {
|
|
9863
|
-
int:
|
|
10177
|
+
int: %{
|
|
10178
|
+
if ( sizeof(<type>) < 8 ) {
|
|
10179
|
+
(#3) = ( fabs((double)(#1) - (double)(#2)) <= tol ) ? 1 : 0;
|
|
10180
|
+
}
|
|
10181
|
+
else {
|
|
10182
|
+
uint64_t d = ( (#1) >= (#2) ) ? (uint64_t)(#1) - (uint64_t)(#2)
|
|
10183
|
+
: (uint64_t)(#2) - (uint64_t)(#1);
|
|
10184
|
+
(#3) = ( tol >= 18446744073709551616.0 || d <= (uint64_t) tol ) ? 1 : 0;
|
|
10185
|
+
}
|
|
10186
|
+
},
|
|
9864
10187
|
float: "(#3) = (fabs((#1) - (#2)) <= tol) ? 1 : 0;",
|
|
9865
10188
|
complex: "(#3) = (cabs((#1) - (#2)) <= tol) ? 1 : 0;",
|
|
9866
10189
|
}
|
|
@@ -9873,7 +10196,15 @@ MkKernel.bincmp :is_equiv,
|
|
|
9873
10196
|
double a = (double)(#1), b = (double)(#2);
|
|
9874
10197
|
double aa = fabs(a), ab = fabs(b);
|
|
9875
10198
|
double m = (aa > ab) ? aa : ab;
|
|
9876
|
-
|
|
10199
|
+
double d;
|
|
10200
|
+
if ( sizeof(<type>) < 8 ) {
|
|
10201
|
+
d = fabs(a - b);
|
|
10202
|
+
}
|
|
10203
|
+
else {
|
|
10204
|
+
d = (double) ( ( (#1) >= (#2) ) ? (uint64_t)(#1) - (uint64_t)(#2)
|
|
10205
|
+
: (uint64_t)(#2) - (uint64_t)(#1) );
|
|
10206
|
+
}
|
|
10207
|
+
(#3) = ( (#1) == (#2) || (m > 0 && d / m <= tol) ) ? 1 : 0;
|
|
9877
10208
|
},
|
|
9878
10209
|
float: %{
|
|
9879
10210
|
<type> aa = fabs((#1)), ab = fabs((#2));
|