carray 3.0.5 → 3.0.7

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.
Files changed (173) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +343 -0
  3. data/README.md +25 -4
  4. data/carray.gemspec +3 -2
  5. data/ext/ca_axis_dispatch.c +6 -0
  6. data/ext/ca_axis_group.c +7 -7
  7. data/ext/ca_binop_dispatch.c +8 -0
  8. data/ext/ca_binop_dispatch.h +1 -0
  9. data/ext/ca_categorical_iterator.c +14 -14
  10. data/ext/ca_kernel_iterator.c +116 -231
  11. data/ext/ca_kernel_iterator.h +416 -258
  12. data/ext/ca_obj_array.c +4 -4
  13. data/ext/ca_obj_bincmp.c +28 -4
  14. data/ext/ca_obj_binop.c +46 -12
  15. data/ext/ca_obj_bitarray.c +2 -4
  16. data/ext/ca_obj_bitfield.c +88 -4
  17. data/ext/ca_obj_byte_swap.c +4 -4
  18. data/ext/ca_obj_const_string.c +422 -257
  19. data/ext/ca_obj_face.c +73 -33
  20. data/ext/ca_obj_fake.c +114 -13
  21. data/ext/ca_obj_farray.c +7 -1
  22. data/ext/ca_obj_fixlen_string.c +51 -17
  23. data/ext/ca_obj_grid.c +179 -19
  24. data/ext/ca_obj_meld.c +74 -118
  25. data/ext/ca_obj_moncmp.c +9 -1
  26. data/ext/ca_obj_monop.c +100 -36
  27. data/ext/ca_obj_object.c +63 -29
  28. data/ext/ca_obj_reduce.c +17 -5
  29. data/ext/ca_obj_refer.c +162 -23
  30. data/ext/ca_obj_remap.c +69 -10
  31. data/ext/ca_obj_repeat.c +1 -1
  32. data/ext/ca_obj_roll.c +3 -4
  33. data/ext/ca_obj_select.c +12 -7
  34. data/ext/ca_obj_select_axis.c +9 -6
  35. data/ext/ca_obj_shift.c +1 -0
  36. data/ext/ca_obj_stack.c +315 -116
  37. data/ext/ca_obj_stride.c +177 -53
  38. data/ext/ca_obj_string.c +20 -4
  39. data/ext/ca_obj_tile.c +3 -4
  40. data/ext/ca_obj_triop.c +24 -13
  41. data/ext/ca_obj_window.c +23 -15
  42. data/ext/ca_op_ipower.c +71 -23
  43. data/ext/ca_op_powi.h +6 -29
  44. data/ext/ca_sort_kernels.h +3 -0
  45. data/ext/ca_sweep_engine.c +90 -23
  46. data/ext/ca_sweep_engine.h +5 -6
  47. data/ext/caframe_csv_reader.c +2 -2
  48. data/ext/carray.h +5 -2
  49. data/ext/carray_access.c +125 -103
  50. data/ext/carray_address_basis.c +209 -1
  51. data/ext/carray_attribute.c +8 -0
  52. data/ext/carray_broadcast.c +5 -6
  53. data/ext/carray_build_flags.h +1 -1
  54. data/ext/carray_call_cfunc.c +5 -8
  55. data/ext/carray_cast.c +319 -48
  56. data/ext/carray_cast_func.rb +37 -5
  57. data/ext/carray_conversion.c +65 -7
  58. data/ext/carray_copy.c +24 -0
  59. data/ext/carray_core.c +874 -72
  60. data/ext/carray_count.c +28 -9
  61. data/ext/carray_element.c +22 -12
  62. data/ext/carray_factorize.c +11 -11
  63. data/ext/carray_histogram.c +27 -5
  64. data/ext/carray_index_classifier.c +7 -5
  65. data/ext/carray_internal.h +241 -12
  66. data/ext/carray_kernels_bincmp.c +2007 -3
  67. data/ext/carray_kernels_binop.c +25502 -5336
  68. data/ext/carray_kernels_init.c +22 -22
  69. data/ext/carray_kernels_monop.c +10739 -3771
  70. data/ext/carray_kernels_reduce_aggregate.c +4429 -702
  71. data/ext/carray_kernels_reduce_boolean.c +1533 -15
  72. data/ext/carray_kernels_reduce_cumulative.c +1808 -248
  73. data/ext/carray_kernels_reduce_extreme.c +4508 -511
  74. data/ext/carray_kernels_reduce_variance.c +2284 -152
  75. data/ext/carray_kernels_scan.c +240 -240
  76. data/ext/carray_kernels_search.c +4211 -264
  77. data/ext/carray_kernels_sort.c +367 -450
  78. data/ext/carray_lazy.c +63 -1
  79. data/ext/carray_loop.c +10 -3
  80. data/ext/carray_mask.c +247 -149
  81. data/ext/carray_median_percentile.c +17 -12
  82. data/ext/carray_memory_view.c +54 -29
  83. data/ext/carray_operator.c +219 -55
  84. data/ext/carray_order.c +55 -11
  85. data/ext/carray_partition.c +1 -1
  86. data/ext/carray_random.c +5 -2
  87. data/ext/carray_round.c +24 -1
  88. data/ext/carray_scatter.c +4 -0
  89. data/ext/carray_segment.c +1 -1
  90. data/ext/carray_slab.c +110 -25
  91. data/ext/carray_sort.c +7 -4
  92. data/ext/carray_sort_kernel.c +24 -0
  93. data/ext/carray_struct.c +21 -6
  94. data/ext/carray_test.c +154 -53
  95. data/ext/carray_time_text.c +8 -2
  96. data/ext/carray_utils.c +124 -54
  97. data/ext/extconf.rb +11 -0
  98. data/ext/mk_call_cfunc.rb +6 -11
  99. data/ext/mkkernel.rb +383 -121
  100. data/ext/ruby_carray.c +4 -1
  101. data/ext/version.h +4 -4
  102. data/lib/carray/attribute.rb +25 -1
  103. data/lib/carray/autoload_carray.rb +3 -3
  104. data/lib/carray/autoload_method_extension.rb +5 -3
  105. data/lib/carray/axis_group.rb +22 -13
  106. data/lib/carray/basics.rb +27 -9
  107. data/lib/carray/bincount_nd.rb +8 -2
  108. data/lib/carray/block_iterator.rb +65 -24
  109. data/lib/carray/categorical.rb +27 -16
  110. data/lib/carray/categorical_iterator.rb +4 -3
  111. data/lib/carray/complex.rb +2 -2
  112. data/lib/carray/conditional.rb +55 -6
  113. data/lib/carray/const_string.rb +74 -0
  114. data/lib/carray/construct.rb +2 -2
  115. data/lib/carray/core_extensions.rb +19 -68
  116. data/lib/carray/data_type_extension.rb +1 -0
  117. data/lib/carray/fixlen_string.rb +83 -1
  118. data/lib/carray/frame/column_verbs.rb +102 -16
  119. data/lib/carray/frame/concat.rb +50 -6
  120. data/lib/carray/frame/convert.rb +19 -0
  121. data/lib/carray/frame/csv_parser.rb +45 -36
  122. data/lib/carray/frame/describe.rb +4 -2
  123. data/lib/carray/frame/frame.rb +436 -83
  124. data/lib/carray/frame/group.rb +731 -78
  125. data/lib/carray/frame/io.rb +216 -73
  126. data/lib/carray/frame/join.rb +166 -43
  127. data/lib/carray/frame/records.rb +9 -7
  128. data/lib/carray/frame/reshape.rb +109 -11
  129. data/lib/carray/frame/sort.rb +57 -9
  130. data/lib/carray/frame/verbs.rb +448 -60
  131. data/lib/carray/frame/windows.rb +71 -9
  132. data/lib/carray/fuse_source.rb +4 -2
  133. data/lib/carray/inspect.rb +7 -2
  134. data/lib/carray/iterator.rb +40 -0
  135. data/lib/carray/key_windows.rb +10 -4
  136. data/lib/carray/lazy.rb +28 -24
  137. data/lib/carray/mask_gap_fill.rb +37 -17
  138. data/lib/carray/meld_reduce.rb +1 -1
  139. data/lib/carray/methods/bin.rb +3 -0
  140. data/lib/carray/methods/choose.rb +3 -2
  141. data/lib/carray/methods/composition.rb +1 -1
  142. data/lib/carray/methods/factorize.rb +2 -0
  143. data/lib/carray/methods/gather_nd.rb +4 -1
  144. data/lib/carray/methods/is_in.rb +23 -3
  145. data/lib/carray/methods/locate_addr.rb +63 -12
  146. data/lib/carray/methods/meshgrid.rb +3 -1
  147. data/lib/carray/methods/repeat.rb +11 -1
  148. data/lib/carray/record_order.rb +35 -6
  149. data/lib/carray/runtime.rb +57 -8
  150. data/lib/carray/segment_iterator.rb +42 -24
  151. data/lib/carray/serialize.rb +56 -17
  152. data/lib/carray/slab_iterator.rb +1 -1
  153. data/lib/carray/stack.rb +21 -9
  154. data/lib/carray/string.rb +6 -6
  155. data/lib/carray/string_operation_extension.rb +25 -4
  156. data/lib/carray/struct_builder.rb +4 -1
  157. data/lib/carray/time.rb +195 -46
  158. data/lib/carray/window_iterator.rb +64 -16
  159. data/yard-stubs/ca_obj_array.rb +26 -1
  160. data/yard-stubs/ca_obj_bitfield.rb +4 -1
  161. data/yard-stubs/ca_obj_refer.rb +3 -0
  162. data/yard-stubs/ca_obj_window.rb +2 -1
  163. data/yard-stubs/carray_access.rb +4 -2
  164. data/yard-stubs/carray_cast.rb +14 -5
  165. data/yard-stubs/carray_conversion.rb +8 -2
  166. data/yard-stubs/carray_count.rb +6 -3
  167. data/yard-stubs/carray_mask.rb +20 -1
  168. data/yard-stubs/carray_math.rb +36 -16
  169. data/yard-stubs/carray_memory_view.rb +7 -0
  170. data/yard-stubs/carray_order.rb +6 -0
  171. data/yard-stubs/carray_scatter.rb +2 -1
  172. data/yard-stubs/carray_test.rb +23 -7
  173. metadata +17 -3
data/ext/mkkernel.rb CHANGED
@@ -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)
@@ -328,8 +339,8 @@ module MkKernel
328
339
  # # :match_source (legacy) reads the weight at
329
340
  # # the source type -- wrong for fractional
330
341
  # # weights, kept only for DSL forward-compat.
331
- # shape: :rev5_strict, # W-A1 scalar / W-A2 1-D axis-broadcast / W-A3
332
- # # same-shape (:match_source = W-A3 only)
342
+ # shape: :rev5_strict, # W-A1 scalar / W-A4 shape of the reduced axes /
343
+ # # W-A3 self.shape (:match_source = W-A3 only)
333
344
  # mask: :overlay, # weights.mask OR'd into self.mask before
334
345
  # # kernel call (= legacy parity, Q3 (A))
335
346
  # }
@@ -362,6 +373,13 @@ module MkKernel
362
373
  object_escape: nil,
363
374
  identity_on_empty: false,
364
375
  all_nan_result: nil,
376
+ undefined_if: nil,
377
+ # settled: a C expression over `acc` that is true once no
378
+ # further cell can change the result (any: "acc", all:
379
+ # "!acc"). The slab walk then stops at the first block
380
+ # where it holds (CA_SLAB_REDUCE_T_SETTLE). Only for a
381
+ # single-accumulator reduction without mask_policy.
382
+ settled: nil,
365
383
  outputs: 1,
366
384
  # Two-pass centred algorithm (variance / stddev family).
367
385
  # When algorithm: :two_pass_centred is set, `state / init /
@@ -448,6 +466,10 @@ module MkKernel
448
466
  raise "#{name}: identity_on_empty requires a single-accumulator reduction (sum/prod/count/accumulate/wsum); mean/variance/wmean/minmax are excluded" \
449
467
  unless single_acc && outputs == 1
450
468
  end
469
+ if settled
470
+ raise "#{name}: settled requires a single-accumulator reduction without mask_policy, value_arg or array_arg" \
471
+ unless state.nil? && mask_policy.nil? && value_arg.nil? && array_arg.nil? && outputs == 1
472
+ end
451
473
  # SL.1.0: reduction_kind: licenses a SIMD-friendly contig-branch macro
452
474
  # variant (CA_SLAB_REDUCE_T_{PLUS,MIN,MAX,STAR,VAR}_EX). default
453
475
  # :none keeps the existing CA_SLAB_REDUCE_T_EX path (= unchanged
@@ -491,6 +513,14 @@ module MkKernel
491
513
  raise "#{name}: all_nan_result: :undef needs a mask_policy " \
492
514
  "(UNDEF is written through the mask_policy trigger)"
493
515
  end
516
+ # undefined_if: a C expression over the state that, when true for a
517
+ # slab, leaves the answer undefined though cells contributed -- wmean's
518
+ # weights summing to 0, whose quotient has no value. It is folded into
519
+ # the mask_policy trigger, so the cell is UNDEF (or fill_value).
520
+ if undefined_if && mask_policy.nil?
521
+ raise "#{name}: undefined_if needs a mask_policy " \
522
+ "(UNDEF is written through the mask_policy trigger)"
523
+ end
494
524
  if value_arg
495
525
  raise "#{name}: value_arg must be a Hash" unless value_arg.is_a?(Hash)
496
526
  raise "#{name}: value_arg: target must be :T_IN" unless value_arg[:target] == :T_IN
@@ -570,9 +600,9 @@ module MkKernel
570
600
  raise "#{name}: array_arg: data_type must be :promote or :match_source" \
571
601
  unless [:promote, :match_source].include?(array_arg[:data_type])
572
602
  # PROPOSAL_REDUCTION_PER_FIBER_AUX_OPERAND rev1: shape acceptance expanded
573
- # to W-A1 (scalar) / W-A2 (1-D axis-broadcast) / W-A3 (same shape).
603
+ # to W-A1 (scalar) / W-A4 (shape of the reduced axes) / W-A3 (self.shape).
574
604
  # :match_source = legacy W-A3 only (kept for forward-compat in DSL).
575
- # :rev5_strict = W-A1 + W-A2 + W-A3 acceptance (= new default for wsum/wmean).
605
+ # :rev5_strict = W-A1 + W-A4 + W-A3 acceptance (= new default for wsum/wmean).
576
606
  raise "#{name}: array_arg: shape must be :match_source or :rev5_strict" \
577
607
  unless [:match_source, :rev5_strict].include?(array_arg[:shape])
578
608
  raise "#{name}: array_arg: mask must be :overlay (W.1 MVP)" \
@@ -652,6 +682,8 @@ module MkKernel
652
682
  object_escape: object_escape,
653
683
  identity_on_empty: identity_on_empty,
654
684
  all_nan_result: all_nan_result,
685
+ undefined_if: undefined_if,
686
+ settled: settled,
655
687
  outputs: outputs,
656
688
  algorithm: algorithm,
657
689
  divisor: divisor,
@@ -1057,11 +1089,14 @@ module MkKernel
1057
1089
  # => ...` form).
1058
1090
  #
1059
1091
  # `bind:` defaults to true (= register CArray#<name> + CArray#<name>!).
1092
+ # `bang: false` leaves CArray#<name>! unregistered too, for a method whose
1093
+ # Ruby surface is defined by hand on top of the generated rb_ca_<name> and
1094
+ # rb_ca_<name>_bang.
1060
1095
  # `op:` defaults to name (= the public method name; some mkmath ops
1061
1096
  # use a different operator name from the kernel suffix, e.g. operator
1062
1097
  # methods).
1063
- def self.monop(name, source:, expr:, op: nil, bind: true, cmath: true,
1064
- widening: nil, output: :preserve)
1098
+ def self.monop(name, source:, expr:, op: nil, bind: true, bang: true,
1099
+ cmath: true, widening: nil, output: :preserve)
1065
1100
  op ||= name
1066
1101
  # widening = true => emit wrapper that auto-casts integer input to
1067
1102
  # CA_FLOAT64 (= mkmath monfunc behavior). Default: auto-detect based
@@ -1084,6 +1119,7 @@ module MkKernel
1084
1119
  source: source,
1085
1120
  expr: expr,
1086
1121
  bind: bind,
1122
+ bang: bang,
1087
1123
  cmath: cmath,
1088
1124
  widening: widening,
1089
1125
  output: output,
@@ -1095,8 +1131,10 @@ module MkKernel
1095
1131
  # of integer input to f64 is decided by `monop`'s widening auto-detect
1096
1132
  # based on whether `source:` includes integer data_types — matching mkmath's
1097
1133
  # rule "if no INT_TYPES key, auto-cast; otherwise rely on integer kernel".
1098
- def self.monfunc(name, source:, expr:, op: nil, bind: true, cmath: true)
1099
- monop(name, source: source, expr: expr, op: op, bind: bind, cmath: cmath)
1134
+ def self.monfunc(name, source:, expr:, op: nil, bind: true, bang: true,
1135
+ cmath: true)
1136
+ monop(name, source: source, expr: expr, op: op, bind: bind, bang: bang,
1137
+ cmath: cmath)
1100
1138
  end
1101
1139
 
1102
1140
  # Register an alias of an existing monop method under a different
@@ -1358,6 +1396,12 @@ module MkKernel
1358
1396
  when "_STAR" then "CA_SLAB_REDUCE_STAR8_EX"
1359
1397
  end
1360
1398
  acc_c = resolve_state_type(k[:state][acc_var], oi, si, src)
1399
+ # An 8- or 16-bit integer cell converted to double does not vectorize;
1400
+ # the narrow form sums blocks in int32 first.
1401
+ if macro8 == "CA_SLAB_REDUCE_SUM8_EX" && %i[i8 u8 i16 u16].include?(src) &&
1402
+ acc_c == DTYPES[:f64][:c]
1403
+ macro8 = "CA_SLAB_REDUCE_SUM8_NARROW_EX"
1404
+ end
1361
1405
  expr_macro = "__#{k[:name]}_#{src}_EXPR"
1362
1406
  io.puts "#define #{expr_macro}(__x) ((#{acc_c})(__x))"
1363
1407
  io.puts "#{indent}#{macro8}(#{si[:c]}, #{acc_c}, st, p, m, #{acc_var}, #{acc_init}, #{expr_macro}, #{masked_cnt_var});"
@@ -1877,7 +1921,11 @@ module MkKernel
1877
1921
  out.puts "{"
1878
1922
  out.puts " #{frame} fr;"
1879
1923
  params.each { |_, name| out.puts " fr.#{name} = #{name};" }
1880
- out.puts " return ca_iter_ensure(#{states.size}, fr.states, #{fn}_body, (VALUE) &fr);"
1924
+ if params.any? { |type, name| name == "ca" && type.include?("CArray") } && fn.end_with?("_object")
1925
+ out.puts " return ca_iter_ensure_computing(ca, #{states.size}, fr.states, #{fn}_body, (VALUE) &fr);"
1926
+ else
1927
+ out.puts " return ca_iter_ensure(#{states.size}, fr.states, #{fn}_body, (VALUE) &fr);"
1928
+ end
1881
1929
  out.puts "}"
1882
1930
  out.print rest
1883
1931
  out.string
@@ -2035,6 +2083,7 @@ module MkKernel
2035
2083
  io.puts " if ( naxes != 1 || ! ca_too_few_present(ca->dim[slab_axes[0]], min_count, 0) ) {" if li_gate
2036
2084
  emit_reduce_loop_interchange(io, k, si, oi, ruby_wrap, src,
2037
2085
  acc_var, acc_init, reduce_stmt, finish_expr)
2086
+ emit_reduce_short_fiber(io, k, si, oi, src, reduce_stmt, finish_expr)
2038
2087
  io.puts " }" if li_gate
2039
2088
  end
2040
2089
 
@@ -2168,6 +2217,7 @@ module MkKernel
2168
2217
  "#{k[:identity_on_empty] ? 0 : 1})"
2169
2218
  end
2170
2219
  trigger = "(#{trigger}) || #{all_nan_flag}" if all_nan_flag
2220
+ trigger = "(#{trigger}) || (#{k[:undefined_if]})" if k[:undefined_if]
2171
2221
  finish_emit = view_flat \
2172
2222
  ? "(transform_active ? (outer_off + ((ca_size_t)(#{finish_expr})) * axis_vstride) : ((ca_size_t)(#{finish_expr})))" \
2173
2223
  : "(#{finish_expr})"
@@ -2192,7 +2242,9 @@ module MkKernel
2192
2242
  # Non-mask_policy path: the slab macros always take a masked_cnt,
2193
2243
  # so hand them a throwaway. The generic form (suffix "", the
2194
2244
  # :object lane) has a wrapper that hides it.
2195
- if suffix == ""
2245
+ if k[:settled]
2246
+ io.puts " CA_SLAB_REDUCE_T_SETTLE(#{si[:c]}, st, p, m, #{acc_var}, #{acc_init}, #{reduce_stmt}, #{k[:settled]});"
2247
+ elsif suffix == ""
2196
2248
  io.puts " CA_SLAB_REDUCE_T(#{si[:c]}, st, p, m, #{acc_var}, #{acc_init}, #{reduce_stmt});"
2197
2249
  else
2198
2250
  io.puts " ca_size_t __sr_throwaway_mc = 0;"
@@ -2540,8 +2592,16 @@ module MkKernel
2540
2592
  expr_macro_defs = "#define #{p1_macro}(__x) #{p1_expr}\n" \
2541
2593
  "#define #{p2_macro}(__x) #{p2_expr}\n"
2542
2594
  expr_macro_undefs = "#undef #{p1_macro}\n#undef #{p2_macro}\n"
2543
- p1_reduce_call = "CA_SLAB_REDUCE_SUM8_EX(#{si[:c]}, #{sum_c}, st, p, m, sum, #{sum_init}, #{p1_macro}, masked_cnt);"
2544
- p2_reduce_call = "CA_SLAB_REDUCE_SUM8_EX(#{si[:c]}, #{m2_c}, st, p, m, M2, #{m2_init}, #{p2_macro}, __unused_mc);"
2595
+ if %i[i8 u8 i16 u16].include?(src)
2596
+ # Per-cell conversion to double does not vectorize for these widths
2597
+ # (see the CA_SLAB_REDUCE_*_NARROW_EX header comments).
2598
+ q_c = %i[i8 u8].include?(src) ? "int32_t" : "int64_t"
2599
+ p1_reduce_call = "CA_SLAB_REDUCE_SUM8_NARROW_EX(#{si[:c]}, #{sum_c}, st, p, m, sum, #{sum_init}, #{p1_macro}, masked_cnt);"
2600
+ p2_reduce_call = "CA_SLAB_REDUCE_M2_NARROW_EX(#{si[:c]}, #{q_c}, st, p, m, M2, #{m2_init}, mean, #{p2_macro}, __unused_mc);"
2601
+ else
2602
+ p1_reduce_call = "CA_SLAB_REDUCE_SUM8_EX(#{si[:c]}, #{sum_c}, st, p, m, sum, #{sum_init}, #{p1_macro}, masked_cnt);"
2603
+ p2_reduce_call = "CA_SLAB_REDUCE_SUM8_EX(#{si[:c]}, #{m2_c}, st, p, m, M2, #{m2_init}, #{p2_macro}, __unused_mc);"
2604
+ end
2545
2605
  end
2546
2606
 
2547
2607
  io.puts
@@ -2603,6 +2663,101 @@ module MkKernel
2603
2663
  io.print expr_macro_undefs
2604
2664
  end
2605
2665
 
2666
+ # Short-fiber fast path (shortcut short_fiber_reduce): a single-axis
2667
+ # reduction over the innermost axis of a row-major buffer whose fibers are
2668
+ # short. The general walk asks the kernel iterator for each fiber, and for
2669
+ # fibers of a few cells that per-fiber step costs more than the cells
2670
+ # (1M fibers of 4 float64 cells: 12.6 ms against 1.0 ms for a plain loop,
2671
+ # M2 Max). Here every fiber is folded in place from the buffer, in the
2672
+ # order the general walk folds it, into scalar accumulators. Eligibility
2673
+ # is the loop interchange's (same reduction kinds, no mask, an alias
2674
+ # attach); a fiber longer than 32 cells (16 for min / max) goes to the
2675
+ # general walk, which is already faster than this loop there.
2676
+ def self.emit_reduce_short_fiber(io, k, si, oi, src, reduce_stmt, finish_expr)
2677
+ buf_kinds = %i[plus star min max]
2678
+ rk = k[:reduction_kind]
2679
+ if buf_kinds.include?(rk)
2680
+ acc_vars = [k[:state].keys.first]
2681
+ induction_var = nil
2682
+ else
2683
+ acc_vars = k[:state].keys.select { |v| buf_kinds.include?(rk[v]) }
2684
+ ind_pair = rk.find { |_, kind| kind == :induction }
2685
+ induction_var = ind_pair && ind_pair[0]
2686
+ end
2687
+
2688
+ info = acc_vars.map do |v|
2689
+ { var: v,
2690
+ c_type: resolve_state_type(k[:state][v], oi, si, src),
2691
+ init: resolve_init_expr(k[:init][v], oi, si, src) }
2692
+ end
2693
+
2694
+ reduce_sf = reduce_stmt.dup
2695
+ finish_sf = finish_expr.dup
2696
+ if induction_var
2697
+ ind_pat = Regexp.escape(induction_var.to_s)
2698
+ reduce_sf = reduce_sf.gsub(/\b#{ind_pat}\+\+/, "0")
2699
+ .gsub(/\+\+\b#{ind_pat}\b/, "0")
2700
+ finish_sf = finish_sf.gsub(/\b#{ind_pat}\b/, "((int64_t)__sf_M)")
2701
+ end
2702
+
2703
+ decls = info.map { |i| "#{i[:c_type]} #{i[:var]} = (#{i[:c_type]}) (#{i[:init]});" }
2704
+ .join("\n ")
2705
+
2706
+ # A float min / max whose accumulator is still at the init saw only NaN
2707
+ # or only +/-INFINITY; the fiber is re-read to tell which, as the
2708
+ # general walk's all-NaN rule answers NaN for the first.
2709
+ nan_fixup =
2710
+ if k[:all_nan_result] == :nan && FLOAT_DTYPES.include?(src) && info.size == 1
2711
+ i = info.first
2712
+ <<~C.rstrip
2713
+ if ( #{i[:var]} == (#{i[:c_type]}) (#{i[:init]}) ) {
2714
+ int __sf_seen = 0;
2715
+ for ( ca_size_t __j = 0; __j < __sf_M; __j++ ) __sf_seen |= (__sf_row[__j] == __sf_row[__j]);
2716
+ if ( ! __sf_seen ) #{i[:var]} = (#{i[:c_type]}) NAN;
2717
+ }
2718
+ C
2719
+ else
2720
+ ""
2721
+ end
2722
+
2723
+ # A min / max fold is a compare per cell that the general walk splits
2724
+ # eight ways; past 16 cells that split is faster than this loop.
2725
+ max_m = info.any? { |i| %i[min max].include?(buf_kinds.include?(rk) ? rk : rk[i[:var]]) } ? 16 : 32
2726
+
2727
+ io.puts <<~C
2728
+ if ( naxes == 1
2729
+ && ca->ndim >= 2
2730
+ && slab_axes[0] == (int8_t)(ca->ndim - 1)
2731
+ && ca->dim[ca->ndim - 1] >= 1
2732
+ && ca->dim[ca->ndim - 1] <= #{max_m}
2733
+ && ! ca_has_mask(ca)
2734
+ && ca_attach_is_alias(ca)
2735
+ && ca_fast_path(CA_SC_SHORT_FIBER_REDUCE) ) {
2736
+ ca_size_t __sf_M = ca->dim[ca->ndim - 1];
2737
+ ca_size_t __sf_OUTER = ca->elements / __sf_M;
2738
+ VALUE vout = rb_ca_new_reduced(self, slab_axes, naxes, #{oi[:ca]}, keep_axis);
2739
+ CArray *co;
2740
+ GetCArray(vout, co);
2741
+ #{oi[:c]} *op = (#{oi[:c]} *) co->ptr;
2742
+ ca_attach(ca); /* window: numeric lanes only, nothing raises inside; O(1) alias attach */
2743
+ const #{si[:c]} *p_root = (const #{si[:c]} *) ca->ptr;
2744
+ for ( ca_size_t __sf_o = 0; __sf_o < __sf_OUTER; __sf_o++ ) {
2745
+ const #{si[:c]} *__sf_row = p_root + __sf_o * __sf_M;
2746
+ #{decls}
2747
+ for ( ca_size_t __j = 0; __j < __sf_M; __j++ ) {
2748
+ #{si[:c]} v = __sf_row[__j];
2749
+ #{reduce_sf};
2750
+ (void) v;
2751
+ }
2752
+ #{nan_fixup}
2753
+ op[__sf_o] = (#{oi[:c]}) (#{finish_sf});
2754
+ }
2755
+ ca_detach(ca);
2756
+ return vout;
2757
+ }
2758
+ C
2759
+ end
2760
+
2606
2761
  def self.emit_reduce_loop_interchange(io, k, si, oi, ruby_wrap, src,
2607
2762
  acc_var, acc_init, reduce_stmt, finish_expr)
2608
2763
  # Classify state vars by reduction_kind:
@@ -2752,7 +2907,7 @@ module MkKernel
2752
2907
  && slab_axes[0] != (int8_t)(ca->ndim - 1)
2753
2908
  && ! ca_has_mask(ca)
2754
2909
  && ca_attach_is_alias(ca)
2755
- && ca_fast_paths_enabled() ) {
2910
+ && ca_fast_path(CA_SC_LOOP_INTERCHANGE) ) {
2756
2911
  int8_t __li_ax = slab_axes[0];
2757
2912
  ca_size_t __li_M = ca->dim[__li_ax];
2758
2913
  ca_size_t __li_INNER = 1;
@@ -2803,7 +2958,7 @@ module MkKernel
2803
2958
  && ! ca_has_mask(ca)
2804
2959
  && ca_func[ca->obj_type].attach == ca_stack_func.attach
2805
2960
  && ((CAStack *) ca)->k_axis == 0
2806
- && ca_fast_paths_enabled() ) {
2961
+ && ca_fast_path(CA_SC_STACK_LOOP_INTERCHANGE) ) {
2807
2962
  CAStack *__li_st = (CAStack *) ca;
2808
2963
  int8_t __li_ax = slab_axes[0];
2809
2964
  ca_size_t __li_M = ca->dim[__li_ax];
@@ -2831,7 +2986,7 @@ module MkKernel
2831
2986
  ca_size_t __li_parent_out = __li_OUTER * __li_INNER;
2832
2987
  const ca_size_t __li_TILE = 512;
2833
2988
  for ( int32_t __kk = 0; __kk < __li_st->n_parents; __kk++ ) {
2834
- ca_attach(__li_st->parents[__kk]); /* window: numeric lanes only, nothing raises inside */
2989
+ ca_attach(__li_st->parents[__kk]); /* window: 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 */
2835
2990
  const #{si[:c]} *p_root = (const #{si[:c]} *) __li_st->parents[__kk]->ptr;
2836
2991
  #{oi[:c]} *__li_op_k = op + (ca_size_t) __kk * __li_parent_out;
2837
2992
  #{core.call("p_root", "__li_op_k", "__li_OUTER")}
@@ -2869,7 +3024,7 @@ module MkKernel
2869
3024
  && ((CAStack *) ca)->k_axis > 0
2870
3025
  && ( slab_axes[0] > ((CAStack *) ca)->k_axis
2871
3026
  || slab_axes[0] + 1 == ((CAStack *) ca)->k_axis )
2872
- && ca_fast_paths_enabled() ) {
3027
+ && ca_fast_path(CA_SC_STACK_LOOP_INTERCHANGE) ) {
2873
3028
  CAStack *__li_st = (CAStack *) ca;
2874
3029
  int8_t __li_ax = slab_axes[0];
2875
3030
  int8_t __li_kax = (int8_t) __li_st->k_axis;
@@ -2926,7 +3081,7 @@ module MkKernel
2926
3081
  ca_size_t __li_plane_elems = __li_M * __li_INNER;
2927
3082
  const ca_size_t __li_TILE = 512;
2928
3083
  for ( int32_t __kk = 0; __kk < __li_st->n_parents; __kk++ ) {
2929
- ca_attach(__li_st->parents[__kk]); /* window: numeric lanes only, nothing raises inside */
3084
+ ca_attach(__li_st->parents[__kk]); /* window: 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 */
2930
3085
  const #{si[:c]} *p_root = (const #{si[:c]} *) __li_st->parents[__kk]->ptr;
2931
3086
  ca_size_t __li_k_base = (ca_size_t) __kk * __li_k_stride;
2932
3087
 
@@ -3012,7 +3167,7 @@ module MkKernel
3012
3167
  && ca_func[ca->obj_type].attach == ca_stack_func.attach
3013
3168
  && ((CAStack *) ca)->k_axis > 0
3014
3169
  && slab_axes[0] + 1 < ((CAStack *) ca)->k_axis
3015
- && ca_fast_paths_enabled() ) {
3170
+ && ca_fast_path(CA_SC_STACK_LOOP_INTERCHANGE) ) {
3016
3171
  CAStack *__li_st = (CAStack *) ca;
3017
3172
  int8_t __li_ax = slab_axes[0];
3018
3173
  int8_t __li_kax = (int8_t) __li_st->k_axis;
@@ -3084,7 +3239,7 @@ module MkKernel
3084
3239
 
3085
3240
  const ca_size_t __li_TILE = 512;
3086
3241
  for ( int32_t __kk = 0; __kk < __li_st->n_parents; __kk++ ) {
3087
- ca_attach(__li_st->parents[__kk]); /* window: numeric lanes only, nothing raises inside */
3242
+ ca_attach(__li_st->parents[__kk]); /* window: 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 */
3088
3243
  const #{si[:c]} *p_root = (const #{si[:c]} *) __li_st->parents[__kk]->ptr;
3089
3244
  ca_size_t __li_k_base = (ca_size_t) __kk * __li_k_stride;
3090
3245
 
@@ -3394,7 +3549,7 @@ module MkKernel
3394
3549
  io.puts " ca->elements > 0 &&"
3395
3550
  io.puts " ! ca_too_few_present(ca->elements, min_count, 0) &&" if k[:mask_policy] == :min_count
3396
3551
  io.puts " ca_is_lazy_view(ca) && ! ca_has_mask(ca) &&"
3397
- io.puts " ca_fast_paths_enabled() ) {"
3552
+ io.puts " ca_fast_path(CA_SC_LAZY_STREAMING_REDUCE) ) {"
3398
3553
  io.puts " #{fn}_t __ctx;"
3399
3554
  io.puts " __ctx.chunk = NULL;"
3400
3555
  io.puts " __ctx.ca = ca;"
@@ -3513,12 +3668,12 @@ module MkKernel
3513
3668
  # computation type (so a float weight against an int source is not
3514
3669
  # truncated -- the body reads it as `double`); :match_source keeps the
3515
3670
  # legacy source-type storage. waca is the CA_* constant the three
3516
- # materialization sites (W-A1 / W-A2 / W-A3) allocate/wrap against, and
3671
+ # materialization sites (W-A1 / W-A4 / W-A3) allocate/wrap against, and
3517
3672
  # must agree with the T_W the reduce macro reads (double for :promote).
3518
3673
  waca = (k[:array_arg][:data_type] == :promote) ? "CA_FLOAT64" : "src->data_type"
3519
3674
  # PROPOSAL_REDUCTION_PER_FIBER_AUX_OPERAND rev1: weights acceptance
3520
- # expanded to 3 forms (W-A1 scalar / W-A2 1-D axis-broadcast / W-A3
3521
- # full per-element). W-A1 / W-A2 are materialized to W-A3 form
3675
+ # expanded to 3 forms (W-A1 scalar / W-A4 shape of the reduced axes / W-A3
3676
+ # full per-element). W-A1 / W-A4 are materialized to W-A3 form
3522
3677
  # at dispatch (= simple, uniform kernel path). rev5 strict acceptance
3523
3678
  # mirrors PROPOSAL_LINEAR_INTERP_PER_FIBER_MATCHED rev5 in spirit.
3524
3679
  io.puts " if ( argc < 1 ) {"
@@ -3526,13 +3681,18 @@ module MkKernel
3526
3681
  io.puts " }"
3527
3682
  io.puts " volatile VALUE rweights = argv[0];"
3528
3683
  io.puts " argc--; argv++;"
3529
- # rev5 A1: convert a single-element CArray (CScalar / [1] 1-D / all
3530
- # dim==1) to a Ruby Numeric and route it through the scalar path.
3684
+ # A CScalar is a scalar weight. Any other array, one with a single
3685
+ # element included, is held to the shape rules below.
3531
3686
  io.puts " if ( rb_obj_is_carray(rweights) ) {"
3532
3687
  io.puts " CArray *cv_pre_;"
3533
3688
  io.puts " GetCArray(rweights, cv_pre_);"
3534
- io.puts " if ( cv_pre_->elements == 1 ) {"
3689
+ io.puts " if ( ca_is_scalar(cv_pre_) ) {"
3690
+ io.puts " int8_t wtype_ = cv_pre_->data_type;"
3535
3691
  io.puts " rweights = rb_funcall(rweights, rb_intern(\"[]\"), 1, INT2NUM(0));"
3692
+ # A boolean cell reads as true / false; as a weight it is 1 / 0.
3693
+ io.puts " if ( wtype_ == CA_BOOLEAN && rweights != CA_UNDEF ) {"
3694
+ io.puts " rweights = INT2FIX(RTEST(rweights) ? 1 : 0);"
3695
+ io.puts " }"
3536
3696
  io.puts " }"
3537
3697
  io.puts " }"
3538
3698
  # The weights are attached from here to the end of the call, so they
@@ -3545,7 +3705,16 @@ module MkKernel
3545
3705
  wio.puts " /* W-A1: Ruby Numeric scalar -> full-shape constant weight CArray */"
3546
3706
  wio.puts " vcw = rb_carray_new(#{waca}, src->ndim, src->dim, 0, NULL);"
3547
3707
  wio.puts " GetCArray(vcw, cw); /* a new entity: its ptr needs no attach */"
3548
- wio.puts " rb_ca_obj2ptr(vcw, rweights, cw->ptr); /* fill first cell */"
3708
+ wio.puts " if ( rweights == CA_UNDEF ) {"
3709
+ wio.puts " /* A masked weight (UNDEF, or a one-element array masked): every"
3710
+ wio.puts " cell's weight is masked, so no cell contributes. */"
3711
+ wio.puts " memset(cw->ptr, 0, (size_t) cw->elements * cw->bytes);"
3712
+ wio.puts " ca_create_mask(cw);"
3713
+ wio.puts " memset(cw->mask->ptr, 1, (size_t) cw->elements);"
3714
+ wio.puts " }"
3715
+ wio.puts " else {"
3716
+ wio.puts " rb_ca_obj2ptr(vcw, rweights, cw->ptr); /* fill first cell */"
3717
+ wio.puts " }"
3549
3718
  wio.puts " /* broadcast first cell to all elements (= constant fill) */"
3550
3719
  wio.puts " {"
3551
3720
  wio.puts " char *p0 = cw->ptr;"
@@ -3557,72 +3726,75 @@ module MkKernel
3557
3726
  wio.puts " else {"
3558
3727
  wio.puts " /* CArray val: coerce to the weight storage type (f64 for :promote, so a"
3559
3728
  wio.puts " float weight against an int source is not truncated) */"
3560
- wio.puts " /* vcv holds the view while cv is read: W-A2 below moves vcw on to"
3729
+ wio.puts " /* vcv holds the view while cv is read: W-A4 below moves vcw on to"
3561
3730
  wio.puts " the materialised copy before it is done with cv. */"
3562
3731
  wio.puts " volatile VALUE vcv = rb_ca_wrap_readonly(rweights, INT2NUM(#{waca}));"
3563
3732
  wio.puts " CArray *cv;"
3564
3733
  wio.puts " GetCArray(vcv, cv);"
3565
3734
  wio.puts " vcw = vcv;"
3566
3735
  wio.puts ""
3567
- wio.puts " /* rev5 form detection: A3 (same ndim) -> A2 (1-D axis-broadcast) -> raise */"
3568
- wio.puts " if ( cv->ndim == src->ndim ) {"
3569
- wio.puts " /* W-A3 commit-or-raise: shape strict match */"
3570
- wio.puts " for ( int8_t i = 0; i < src->ndim; i++ ) {"
3571
- wio.puts " if ( cv->dim[i] != src->dim[i] ) {"
3572
- wio.puts %Q[ rb_raise(rb_eArgError, "%s: weights shape mismatch (dim[%d]=%ld != self.dim[%d]=%ld; expected a scalar, a 1-D array along the reduced axis, or self.shape)", ca_calling_method_name(), (int)i, (long)cv->dim[i], (int)i, (long)src->dim[i]);]
3573
- wio.puts " }"
3574
- wio.puts " }"
3575
- wio.puts " /* W-A3 path: use cv directly (= existing) */"
3736
+ wio.puts " /* form detection: W-A3 (self.shape) -> W-A4 (shape of the reduced axes,"
3737
+ wio.puts " taken in ascending axis order whatever order axis: lists them) -> raise */"
3738
+ wio.puts " int8_t wax[CA_RANK_MAX];"
3739
+ wio.puts " for ( int8_t i = 0; i < naxes; i++ ) {"
3740
+ wio.puts " int8_t a = slab_axes[i], j = i;"
3741
+ wio.puts " while ( j > 0 && wax[j-1] > a ) { wax[j] = wax[j-1]; j--; }"
3742
+ wio.puts " wax[j] = a;"
3743
+ wio.puts " }"
3744
+ wio.puts " int is_full_shape = ( cv->ndim == src->ndim );"
3745
+ wio.puts " for ( int8_t i = 0; is_full_shape && i < src->ndim; i++ ) {"
3746
+ wio.puts " if ( cv->dim[i] != src->dim[i] ) is_full_shape = 0;"
3747
+ wio.puts " }"
3748
+ wio.puts " int is_reduced_shape = ( ! is_full_shape && naxes >= 1 && cv->ndim == naxes );"
3749
+ wio.puts " for ( int8_t i = 0; is_reduced_shape && i < naxes; i++ ) {"
3750
+ wio.puts " if ( cv->dim[i] != src->dim[wax[i]] ) is_reduced_shape = 0;"
3751
+ wio.puts " }"
3752
+ wio.puts " if ( is_full_shape ) {"
3753
+ wio.puts " /* W-A3: per-element weights, used as they are */"
3576
3754
  wio.puts " cw = cv;"
3577
3755
  wio.puts " }"
3578
- wio.puts " else if ( naxes == 1 && cv->ndim == 1 && cv->dim[0] == src->dim[slab_axes[0]] ) {"
3579
- wio.puts " /* W-A2: 1-D axis-broadcast -> materialize to full shape. cw and"
3580
- wio.puts " its mask are made before cv is attached: making them allocates. */"
3756
+ wio.puts " else if ( is_reduced_shape ) {"
3757
+ wio.puts " /* W-A4: one weight per cell of the reduced axes, repeated along the"
3758
+ wio.puts " kept axes; materialized to self.shape. cw and its mask are made"
3759
+ wio.puts " before cv is attached: making them allocates. */"
3581
3760
  wio.puts " vcw = rb_carray_new(#{waca}, src->ndim, src->dim, 0, NULL);"
3582
3761
  wio.puts " GetCArray(vcw, cw);"
3583
3762
  wio.puts " if ( ca_has_mask(cv) ) {"
3584
3763
  wio.puts " ca_create_mask(cw);"
3585
3764
  wio.puts " }"
3586
3765
  wio.puts " ca_attach(cv); /* window: nothing raises inside */"
3587
- wio.puts " /* broadcast cv (1-D, length src->dim[slab_axes[0]]) along reduce axis */"
3588
3766
  wio.puts " {"
3589
- wio.puts " int8_t baxis = slab_axes[0];"
3590
- wio.puts " ca_size_t inner_stride = 1;"
3591
- wio.puts " for ( int8_t ii = baxis + 1; ii < src->ndim; ii++ ) inner_stride *= src->dim[ii];"
3592
- wio.puts " ca_size_t axis_n = src->dim[baxis];"
3593
- wio.puts " ca_size_t outer = ( axis_n && inner_stride ) ? src->elements / (axis_n * inner_stride) : 0; /* a zero-length axis leaves nothing to fill */"
3594
- wio.puts " for ( ca_size_t o = 0; o < outer; o++ ) {"
3595
- wio.puts " for ( ca_size_t a = 0; a < axis_n; a++ ) {"
3596
- wio.puts " for ( ca_size_t in = 0; in < inner_stride; in++ ) {"
3597
- wio.puts " ca_size_t flat = (o * axis_n + a) * inner_stride + in;"
3598
- wio.puts " memcpy(cw->ptr + flat * cw->bytes, cv->ptr + a * cv->bytes, cw->bytes);"
3599
- wio.puts " }"
3600
- wio.puts " }"
3767
+ wio.puts " ca_size_t idx[CA_RANK_MAX], wstep[CA_RANK_MAX];"
3768
+ wio.puts " ca_size_t step = 1;"
3769
+ wio.puts " boolean8_t *cw_m = ca_has_mask(cv) ? (boolean8_t *) cw->mask->ptr : NULL;"
3770
+ wio.puts " boolean8_t *cv_m = ca_has_mask(cv) ? (boolean8_t *) cv->mask->ptr : NULL;"
3771
+ wio.puts " for ( int8_t i = 0; i < src->ndim; i++ ) {"
3772
+ wio.puts " idx[i] = 0;"
3773
+ wio.puts " wstep[i] = 0; /* kept axes: the weight repeats */"
3601
3774
  wio.puts " }"
3602
- wio.puts " }"
3603
- wio.puts " /* Propagate cv mask via W-A3 overlay path below (= mask materialize) */"
3604
- wio.puts " if ( ca_has_mask(cv) ) {"
3605
- wio.puts " /* broadcast cv mask along axis */"
3606
- wio.puts " boolean8_t *cw_m = (boolean8_t *)cw->mask->ptr;"
3607
- wio.puts " boolean8_t *cv_m = (boolean8_t *)cv->mask->ptr;"
3608
- wio.puts " int8_t baxis = slab_axes[0];"
3609
- wio.puts " ca_size_t inner_stride = 1;"
3610
- wio.puts " for ( int8_t ii = baxis + 1; ii < src->ndim; ii++ ) inner_stride *= src->dim[ii];"
3611
- wio.puts " ca_size_t axis_n = src->dim[baxis];"
3612
- wio.puts " ca_size_t outer = ( axis_n && inner_stride ) ? src->elements / (axis_n * inner_stride) : 0; /* a zero-length axis leaves nothing to fill */"
3613
- wio.puts " for ( ca_size_t o = 0; o < outer; o++ ) {"
3614
- wio.puts " for ( ca_size_t a = 0; a < axis_n; a++ ) {"
3615
- wio.puts " for ( ca_size_t in = 0; in < inner_stride; in++ ) {"
3616
- wio.puts " ca_size_t flat = (o * axis_n + a) * inner_stride + in;"
3617
- wio.puts " cw_m[flat] = cv_m[a];"
3618
- wio.puts " }"
3775
+ wio.puts " for ( int8_t i = naxes - 1; i >= 0; i-- ) {"
3776
+ wio.puts " wstep[wax[i]] = step;"
3777
+ wio.puts " step *= cv->dim[i];"
3778
+ wio.puts " }"
3779
+ wio.puts " for ( ca_size_t flat = 0; flat < src->elements; flat++ ) {"
3780
+ wio.puts " ca_size_t w = 0;"
3781
+ wio.puts " for ( int8_t i = 0; i < src->ndim; i++ ) w += idx[i] * wstep[i];"
3782
+ wio.puts " memcpy(cw->ptr + flat * cw->bytes, cv->ptr + w * cv->bytes, cw->bytes);"
3783
+ wio.puts " if ( cw_m ) cw_m[flat] = cv_m[w];"
3784
+ wio.puts " for ( int8_t i = src->ndim - 1; i >= 0; i-- ) {"
3785
+ wio.puts " if ( ++idx[i] < src->dim[i] ) break;"
3786
+ wio.puts " idx[i] = 0;"
3619
3787
  wio.puts " }"
3620
3788
  wio.puts " }"
3621
3789
  wio.puts " }"
3622
3790
  wio.puts " ca_detach(cv);"
3623
3791
  wio.puts " }"
3624
3792
  wio.puts " else {"
3625
- wio.puts %Q[ rb_raise(rb_eArgError, "%s: w shape not accepted (val.ndim=%d, val.dim[0]=%ld; expected scalar / [M=%ld] / self.shape)", ca_calling_method_name(), (int)cv->ndim, (long)(cv->ndim >= 1 ? cv->dim[0] : 0), (long)(naxes == 1 ? src->dim[slab_axes[0]] : -1));]
3793
+ wio.puts " volatile VALUE rexpect = rb_ary_new();"
3794
+ wio.puts " for ( int8_t i = 0; i < naxes; i++ ) {"
3795
+ wio.puts " rb_ary_push(rexpect, SIZE2NUM(src->dim[wax[i]]));"
3796
+ wio.puts " }"
3797
+ wio.puts %Q[ rb_raise(rb_eArgError, "%s: weights of shape %"PRIsVALUE" not accepted (expected a scalar, the shape of the reduced axes %"PRIsVALUE", or self.shape %"PRIsVALUE")", ca_calling_method_name(), rb_funcall(vcv, rb_intern("shape"), 0), rexpect, rb_funcall(self, rb_intern("shape"), 0));]
3626
3798
  wio.puts " }"
3627
3799
  wio.puts " }"
3628
3800
  # Mask overlay (= legacy W-A3 path; if the materialized cw carries a mask, overlay it)
@@ -5116,15 +5288,16 @@ module MkKernel
5116
5288
  # The object lane calls Ruby for every cell of the case B/C walk, which
5117
5289
  # runs between a direct attach and detach of self and val; a raise there
5118
5290
  # would leave both attached. An entity holds no attach, so the lane
5119
- # reads an entity copy of whichever is a view.
5291
+ # reads an entity copy of whichever is a view, or an entity that leaves
5292
+ # ptr NULL at rest (a CASource).
5120
5293
  entity_bc = if is_object
5121
5294
  <<~C.chomp
5122
5295
  volatile VALUE vca_entity = self;
5123
- if ( ! ca_is_entity(ca) ) {
5296
+ if ( ! ca_is_entity(ca) || ! ca->ptr ) {
5124
5297
  vca_entity = rb_ca_copy(self);
5125
5298
  GetCArray(vca_entity, ca);
5126
5299
  }
5127
- if ( ! ca_is_entity(cv) ) {
5300
+ if ( ! ca_is_entity(cv) || ! cv->ptr ) {
5128
5301
  vsrc_val = rb_ca_copy(vsrc_val);
5129
5302
  GetCArray(vsrc_val, cv);
5130
5303
  }
@@ -6051,6 +6224,9 @@ module MkKernel
6051
6224
  # `op_powi_<type>` resolves to `op_powi_int8_t` for int8 source).
6052
6225
  # Substitution uses math_suffix (= typedef name, matches the suffix
6053
6226
  # used in op_powi macro instantiations in ca_op_powi.h).
6227
+ # An object body calls Ruby on every cell and does not vectorize; the
6228
+ # pragma there only adds a "loop not vectorized" warning.
6229
+ simd = ( src == :object ) ? "" : "#pragma omp simd"
6054
6230
  expr_body = raw.gsub(/#1/, "*p1").gsub(/#2/, "*p2").gsub(/#3/, "*p3").gsub(/<type>/, suffix)
6055
6231
  # Option B+C pilot (binop emit substrate hardening, MEMO_BINOP_STRIDED_AUDIT.md):
6056
6232
  # The no-mask body is split into a contig branch (i1==i2==i3==1) using the
@@ -6103,7 +6279,7 @@ module MkKernel
6103
6279
  #{c_type} * __restrict__ r1 = q1;
6104
6280
  #{c_type} * __restrict__ r2 = q2;
6105
6281
  #{c_type} * __restrict__ r3 = q3;
6106
- #pragma omp simd
6282
+ #{simd}
6107
6283
  for (k=0; k<n; k++) {
6108
6284
  p1 = r1 + k; p2 = r2 + k; p3 = r3 + k;
6109
6285
  { #{expr_body} }
@@ -6111,7 +6287,7 @@ module MkKernel
6111
6287
  }
6112
6288
  else if ( ( apart1 || a1 == a3 ) && ( apart2 || a2 == a3 ) ) {
6113
6289
  /* in place: an iteration reads and writes only its own cell */
6114
- #pragma omp simd
6290
+ #{simd}
6115
6291
  for (k=0; k<n; k++) {
6116
6292
  p1 = q1 + k; p2 = q2 + k; p3 = q3 + k;
6117
6293
  { #{expr_body} }
@@ -6123,6 +6299,66 @@ module MkKernel
6123
6299
  { #{expr_body} }
6124
6300
  }
6125
6301
  }
6302
+ } else if ( i3 == 1 && ( ( i1 == 1 && i2 == 0 ) || ( i1 == 0 && i2 == 1 ) ) ) {
6303
+ /* scalar branch: one operand is a scalar (stride 0). It is read
6304
+ into a local before the loop, so a store to the output cannot
6305
+ change it and the loop vectorizes like the contig branch. */
6306
+ #{c_type} sv = ( i1 == 0 ) ? *q1 : *q2;
6307
+ #{c_type} *qa = ( i1 == 0 ) ? q2 : q1;
6308
+ #{c_type} *p1, *p2, *p3;
6309
+ uintptr_t aa = (uintptr_t) qa, a3 = (uintptr_t) q3;
6310
+ uintptr_t nb = (uintptr_t) n * sizeof(*q3);
6311
+ (void)p1; (void)p2; (void)p3;
6312
+ if ( i1 == 0 ) {
6313
+ p1 = &sv;
6314
+ if ( a3 + nb <= aa || aa + nb <= a3 ) {
6315
+ #{c_type} * __restrict__ ra = qa;
6316
+ #{c_type} * __restrict__ r3 = q3;
6317
+ #{simd}
6318
+ for (k=0; k<n; k++) {
6319
+ p2 = ra + k; p3 = r3 + k;
6320
+ { #{expr_body} }
6321
+ }
6322
+ }
6323
+ else if ( aa == a3 ) {
6324
+ #{simd}
6325
+ for (k=0; k<n; k++) {
6326
+ p2 = qa + k; p3 = q3 + k;
6327
+ { #{expr_body} }
6328
+ }
6329
+ }
6330
+ else {
6331
+ for (k=0; k<n; k++) {
6332
+ p2 = qa + k; p3 = q3 + k;
6333
+ { #{expr_body} }
6334
+ }
6335
+ }
6336
+ }
6337
+ else {
6338
+ p2 = &sv;
6339
+ if ( a3 + nb <= aa || aa + nb <= a3 ) {
6340
+ #{c_type} * __restrict__ ra = qa;
6341
+ #{c_type} * __restrict__ r3 = q3;
6342
+ #{simd}
6343
+ for (k=0; k<n; k++) {
6344
+ p1 = ra + k; p3 = r3 + k;
6345
+ { #{expr_body} }
6346
+ }
6347
+ }
6348
+ else if ( aa == a3 ) {
6349
+ #{simd}
6350
+ for (k=0; k<n; k++) {
6351
+ p1 = qa + k; p3 = q3 + k;
6352
+ { #{expr_body} }
6353
+ }
6354
+ }
6355
+ else {
6356
+ for (k=0; k<n; k++) {
6357
+ p1 = qa + k; p3 = q3 + k;
6358
+ { #{expr_body} }
6359
+ }
6360
+ }
6361
+ }
6126
6362
  } else {
6127
6363
  /* strided branch: numo-shape `p += s` increment form. */
6128
6364
  #{c_type} *p1 = q1, *p2 = q2, *p3 = q3;
@@ -6455,6 +6691,24 @@ module MkKernel
6455
6691
  { #{expr_body} }
6456
6692
  }
6457
6693
  }
6694
+ } else if ( i3 == 1 && i1 == 1 && i2 == 0 ) {
6695
+ /* scalar on the right: read it once, so the boolean store
6696
+ cannot be taken to change it and the loop vectorizes */
6697
+ #{c_type} sv = *q2;
6698
+ p2 = &sv;
6699
+ for (k=0; k<n; k++) {
6700
+ p1 = q1 + k;
6701
+ p3 = q3 + k;
6702
+ { #{expr_body} }
6703
+ }
6704
+ } else if ( i3 == 1 && i1 == 0 && i2 == 1 ) {
6705
+ #{c_type} sv = *q1;
6706
+ p1 = &sv;
6707
+ for (k=0; k<n; k++) {
6708
+ p2 = q2 + k;
6709
+ p3 = q3 + k;
6710
+ { #{expr_body} }
6711
+ }
6458
6712
  } else {
6459
6713
  for (k=0; k<n; k++) {
6460
6714
  p1 = q1 + k*i1;
@@ -6556,11 +6810,14 @@ module MkKernel
6556
6810
 
6557
6811
  # Kernels written outside this generator that a lazy expression can still
6558
6812
  # hold. A Float or Complex array to an Integer power is CABinOp's ipow
6559
- # (ext/ca_op_ipower.c, which applies op_powi_<type> cell by cell); its
6560
- # body is that call.
6561
- EXTRA_BODY_ROWS = %w[float32 float64 cmplx64 cmplx128].map { |t|
6562
- ["binop", "ipow", t, "(#3) = op_powi_<type>((#1), (#2));"]
6563
- }.freeze
6813
+ # (ext/ca_op_ipower.c, ca_ipow_<type>): #2 is an int64, converted as an
6814
+ # int64 cell is converted to the base's type, then the power body.
6815
+ EXTRA_BODY_ROWS = [
6816
+ ["binop", "ipow", "float32", pow_short("powf((#1), (float)(double)(#2))")],
6817
+ ["binop", "ipow", "float64", pow_short("pow((#1), (double)(#2))")],
6818
+ ["binop", "ipow", "cmplx64", pow_short("cpow((#1), (float)(double)(#2))")],
6819
+ ["binop", "ipow", "cmplx128", pow_short("cpow((#1), (double)(#2))")],
6820
+ ].freeze
6564
6821
 
6565
6822
  # The helpers the bodies call that are not in the C standard library:
6566
6823
  # the part of ca_op_powi.h between its markers, as it stands.
@@ -6730,7 +6987,7 @@ module MkKernel
6730
6987
  # surface) + optional CAMath module function, NOT as `<name>_ki`.
6731
6988
  if k[:kind] == :monop
6732
6989
  io.puts %Q[ rb_define_method(rb_cCArray, "#{k[:op]}", rb_ca_#{k[:name]}, 0);] if k[:bind]
6733
- io.puts %Q[ rb_define_method(rb_cCArray, "#{k[:name]}!", rb_ca_#{k[:name]}_bang, 0);]
6990
+ io.puts %Q[ rb_define_method(rb_cCArray, "#{k[:name]}!", rb_ca_#{k[:name]}_bang, 0);] if k[:bang]
6734
6991
  io.puts %Q[ rb_define_module_function(rb_mCAMath, "#{k[:name]}", rb_cmath_#{k[:name]}, 1);] if k[:cmath]
6735
6992
  return
6736
6993
  end
@@ -6958,11 +7215,10 @@ MkKernel.reduce :max,
6958
7215
  # its identity value (1 for all, 0 for any) for those cells. An all-
6959
7216
  # masked slab returns the identity (all([]) == true, any([]) == false).
6960
7217
  #
6961
- # Early-break is intentionally NOT implemented; idempotent acc &= v /
6962
- # acc |= v is SIMD-friendly and the branch-free form usually wins on
6963
- # modern CPUs. For dramatically lopsided inputs (= mostly-false `all`
6964
- # or mostly-true `any`) a profile-driven early-break variant can be
6965
- # added later as a separate kernel.
7218
+ # The walk stops once the answer is settled (settled:): any at the first
7219
+ # true, all and none at the first false / true. The test runs between
7220
+ # blocks of branch-free `acc |= v` / `acc &= v`, so a slab that never
7221
+ # settles keeps the speed of the plain fold.
6966
7222
  MkKernel.header_block <<~C
6967
7223
  /* The square root of a variance: an ε-negative from rounding becomes 0,
6968
7224
  a NaN stays NaN (fmax(NaN, 0.0) is 0.0). */
@@ -6986,6 +7242,8 @@ C
6986
7242
  MkKernel.reduce :all,
6987
7243
  init: "1",
6988
7244
  reduce: "acc &= v",
7245
+ settled: "!acc",
7246
+ reduction_kind: :min,
6989
7247
  source: [:bool],
6990
7248
  output: :bool,
6991
7249
  ruby_scalar: :BOOL2VAL,
@@ -6995,6 +7253,8 @@ MkKernel.reduce :all,
6995
7253
  MkKernel.reduce :any,
6996
7254
  init: "0",
6997
7255
  reduce: "acc |= v",
7256
+ settled: "acc",
7257
+ reduction_kind: :max,
6998
7258
  source: [:bool],
6999
7259
  output: :bool,
7000
7260
  ruby_scalar: :BOOL2VAL,
@@ -7009,6 +7269,8 @@ MkKernel.reduce :any,
7009
7269
  MkKernel.reduce :none,
7010
7270
  init: "1",
7011
7271
  reduce: "acc &= !v",
7272
+ settled: "!acc",
7273
+ reduction_kind: :min,
7012
7274
  source: [:bool],
7013
7275
  output: :bool,
7014
7276
  ruby_scalar: :BOOL2VAL,
@@ -7457,9 +7719,9 @@ MkKernel.reduce :wsum,
7457
7719
  # framework as wsum, but uses state+finish form (= sum + den) for the
7458
7720
  # normalisation `mean = Σv*w / Σw` semantic.
7459
7721
  #
7460
- # Edge case: if all valid weights sum to zero (= den == 0 but some cells
7461
- # valid), finish evaluates 0/0 -> NaN. Legacy proc_wmean had the same
7462
- # undefined behavior (no division check); mkkernel preserves it.
7722
+ # Weights summing to zero (den == 0 with cells present, weights of 0 or of
7723
+ # both signs) leave the mean undefined: the cell is UNDEF, as for a slab
7724
+ # with no valid cell, rather than 0/0 = NaN or x/0 = +-Infinity.
7463
7725
  #
7464
7726
  # 3.0 breaking semantic changes vs legacy (= identical to wsum W.2):
7465
7727
  # - calling convention positional -> kwargs (axes positional, opts kw)
@@ -7476,6 +7738,7 @@ MkKernel.reduce :wmean,
7476
7738
  reduce: "(sum += (double) v * (double) w, den += (double) w)",
7477
7739
  reduction_kind: { sum: :plus, den: :plus }, # SL.1.4b
7478
7740
  finish: "sum / den",
7741
+ undefined_if: "den == 0",
7479
7742
  source: MkKernel::ALL_NUMERIC,
7480
7743
  output: :f64,
7481
7744
  ruby_scalar: :rb_float_new,
@@ -8632,7 +8895,11 @@ MkKernel.monfunc :floor,
8632
8895
  object: '(#2) = rb_funcall((#1), rb_intern("floor"), 0);',
8633
8896
  }
8634
8897
 
8898
+ # round: the Ruby methods `round(ndigits)` / `round!(ndigits)` are defined in
8899
+ # carray_round.c on top of this kernel, so none is registered here.
8635
8900
  MkKernel.monfunc :round,
8901
+ bind: false,
8902
+ bang: false,
8636
8903
  source: MkKernel::ALL_NUMERIC + [:object],
8637
8904
  expr: {
8638
8905
  int: "(#2) = (#1);",
@@ -8815,21 +9082,18 @@ MkKernel.monfunc :deg_360,
8815
9082
  expr: {
8816
9083
  float: <<~C,
8817
9084
  {
8818
- double _a = (double)(#1);
8819
- double _fa = _a / 360.0;
8820
- (#2) = (_a >= 0)
8821
- ? (_fa - floor(_fa)) * 360.0
8822
- : (_fa - ceil(_fa) + 1.0) * 360.0;
9085
+ double _fa = (double)(#1) / 360.0;
9086
+ (#2) = (_fa - floor(_fa)) * 360.0;
9087
+ if ( (#2) >= 360.0 ) (#2) = 0.0; /* a tiny negative rounds to the top */
8823
9088
  }
8824
9089
  C
8825
9090
  object: <<~SNIPPET,
8826
9091
  {
8827
9092
  VALUE _obj_arg = (#1);
8828
9093
  if (RB_FLOAT_TYPE_P(_obj_arg) || RB_INTEGER_TYPE_P(_obj_arg) || RB_TYPE_P(_obj_arg, T_RATIONAL)) {
8829
- double _a = NUM2DBL(_obj_arg);
8830
- double _fa = _a / 360.0;
8831
- (#2) = DBL2NUM((_a >= 0) ? (_fa - floor(_fa)) * 360.0
8832
- : (_fa - ceil(_fa) + 1.0) * 360.0);
9094
+ double _fa = NUM2DBL(_obj_arg) / 360.0;
9095
+ double _r = (_fa - floor(_fa)) * 360.0;
9096
+ (#2) = DBL2NUM(_r >= 360.0 ? 0.0 : _r);
8833
9097
  } else {
8834
9098
  (#2) = rb_funcall(_obj_arg, rb_intern("deg_360"), 0);
8835
9099
  }
@@ -8837,7 +9101,7 @@ MkKernel.monfunc :deg_360,
8837
9101
  SNIPPET
8838
9102
  }
8839
9103
 
8840
- # deg_180: fold into [-180, 180). Preserves trailing `if (b <= -180)
9104
+ # deg_180: fold into (-180, 180]. Preserves trailing `if (b <= -180)
8841
9105
  # b += 360` guard from the legacy implementation.
8842
9106
  MkKernel.monfunc :deg_180,
8843
9107
  source: MkKernel::FLOAT_DTYPES + [:object],
@@ -8877,11 +9141,9 @@ MkKernel.monfunc :rad_2pi,
8877
9141
  float: <<~C,
8878
9142
  {
8879
9143
  double _two_pi = 2.0 * M_PI;
8880
- double _a = (double)(#1);
8881
- double _fa = _a / _two_pi;
8882
- (#2) = (_a >= 0)
8883
- ? (_fa - floor(_fa)) * _two_pi
8884
- : (_fa - ceil(_fa) + 1.0) * _two_pi;
9144
+ double _fa = (double)(#1) / _two_pi;
9145
+ (#2) = (_fa - floor(_fa)) * _two_pi;
9146
+ if ( (#2) >= _two_pi ) (#2) = 0.0; /* a tiny negative rounds to the top */
8885
9147
  }
8886
9148
  C
8887
9149
  object: <<~SNIPPET,
@@ -8889,10 +9151,9 @@ MkKernel.monfunc :rad_2pi,
8889
9151
  VALUE _obj_arg = (#1);
8890
9152
  if (RB_FLOAT_TYPE_P(_obj_arg) || RB_INTEGER_TYPE_P(_obj_arg) || RB_TYPE_P(_obj_arg, T_RATIONAL)) {
8891
9153
  double _two_pi = 2.0 * M_PI;
8892
- double _a = NUM2DBL(_obj_arg);
8893
- double _fa = _a / _two_pi;
8894
- (#2) = DBL2NUM((_a >= 0) ? (_fa - floor(_fa)) * _two_pi
8895
- : (_fa - ceil(_fa) + 1.0) * _two_pi);
9154
+ double _fa = NUM2DBL(_obj_arg) / _two_pi;
9155
+ double _r = (_fa - floor(_fa)) * _two_pi;
9156
+ (#2) = DBL2NUM(_r >= _two_pi ? 0.0 : _r);
8896
9157
  } else {
8897
9158
  (#2) = rb_funcall(_obj_arg, rb_intern("rad_2pi"), 0);
8898
9159
  }
@@ -8952,22 +9213,23 @@ MkKernel.monfunc :rad_pi,
8952
9213
  # Float NaN included), maximum / minimum let it win. In both flavours, of
8953
9214
  # two zeros the max is +0 and the min is -0 in either order. C's fmax /
8954
9215
  # fmin leave that choice to the library (glibc and macOS answer
8955
- # differently), so the float branch does not call them.
9216
+ # differently), so the float branch does not call them. The sign of a
9217
+ # zero is read with copysign(1, x) rather than signbit(x): GCC does not
9218
+ # vectorize signbit on a double, which left the float64 kernels 17x
9219
+ # slower than float32. NaN is handled before, so copysign never sees one.
8956
9220
  MkKernel.binop :pmax,
8957
9221
  source: MkKernel::ALL_NUMERIC + [:object],
8958
9222
  expr: {
8959
9223
  int: "(#3) = (#1) > (#2) ? (#1) : (#2);",
8960
- float: "(#3) = isnan(#1) ? (#2) : isnan(#2) ? (#1) : ((#1) > (#2) || ((#1) == (#2) && !signbit(#1))) ? (#1) : (#2);",
8961
9224
  object: '(#3) = ca_obj_extremum_replaces((#2), (#1), rb_intern(">")) ? (#2) : (#1);',
8962
- }
9225
+ }.merge(MkKernel.float_widths("(#3) = isnan(#1) ? (#2) : isnan(#2) ? (#1) : ((#1) > (#2) || ((#1) == (#2) && copysign<f>(1, (#1)) > 0)) ? (#1) : (#2);"))
8963
9226
 
8964
9227
  MkKernel.binop :pmin,
8965
9228
  source: MkKernel::ALL_NUMERIC + [:object],
8966
9229
  expr: {
8967
9230
  int: "(#3) = (#1) < (#2) ? (#1) : (#2);",
8968
- float: "(#3) = isnan(#1) ? (#2) : isnan(#2) ? (#1) : ((#1) < (#2) || ((#1) == (#2) && signbit(#1))) ? (#1) : (#2);",
8969
9231
  object: '(#3) = ca_obj_extremum_replaces((#2), (#1), rb_intern("<")) ? (#2) : (#1);',
8970
- }
9232
+ }.merge(MkKernel.float_widths("(#3) = isnan(#1) ? (#2) : isnan(#2) ? (#1) : ((#1) < (#2) || ((#1) == (#2) && copysign<f>(1, (#1)) < 0)) ? (#1) : (#2);"))
8971
9233
 
8972
9234
  # NaN-propagate variants. Float
8973
9235
  # branch tests both operands for NaN and short-circuits to NaN; non-
@@ -8978,17 +9240,15 @@ MkKernel.binop :maximum,
8978
9240
  source: MkKernel::ALL_NUMERIC + [:object],
8979
9241
  expr: {
8980
9242
  int: "(#3) = (#1) > (#2) ? (#1) : (#2);",
8981
- float: "(#3) = isnan(#1) ? (#1) : isnan(#2) ? (#2) : ((#1) > (#2) || ((#1) == (#2) && !signbit(#1))) ? (#1) : (#2);",
8982
9243
  object: '(#3) = CA_OBJ_ISNAN(#1) ? (#1) : CA_OBJ_ISNAN(#2) ? (#2) : ca_obj_cmp((#2), (#1)) > 0 ? (#2) : (#1);',
8983
- }
9244
+ }.merge(MkKernel.float_widths("(#3) = isnan(#1) ? (#1) : isnan(#2) ? (#2) : ((#1) > (#2) || ((#1) == (#2) && copysign<f>(1, (#1)) > 0)) ? (#1) : (#2);"))
8984
9245
 
8985
9246
  MkKernel.binop :minimum,
8986
9247
  source: MkKernel::ALL_NUMERIC + [:object],
8987
9248
  expr: {
8988
9249
  int: "(#3) = (#1) < (#2) ? (#1) : (#2);",
8989
- float: "(#3) = isnan(#1) ? (#1) : isnan(#2) ? (#2) : ((#1) < (#2) || ((#1) == (#2) && signbit(#1))) ? (#1) : (#2);",
8990
9250
  object: '(#3) = CA_OBJ_ISNAN(#1) ? (#1) : CA_OBJ_ISNAN(#2) ? (#2) : ca_obj_cmp((#2), (#1)) < 0 ? (#2) : (#1);',
8991
- }
9251
+ }.merge(MkKernel.float_widths("(#3) = isnan(#1) ? (#1) : isnan(#2) ? (#2) : ((#1) < (#2) || ((#1) == (#2) && copysign<f>(1, (#1)) < 0)) ? (#1) : (#2);"))
8992
9252
 
8993
9253
  # + and - work on the parts independently, so one generic expression
8994
9254
  # covers every numeric data_type at any width.
@@ -9152,7 +9412,9 @@ MkKernel.binop :bit_or_i,
9152
9412
  kleene: :or,
9153
9413
  source: MkKernel::INT_DTYPES + [:bool, :object],
9154
9414
  expr: {
9155
- bool: "(#3) = (#1) | (#2);",
9415
+ # 0 / 1 even when a side is a masked cell: its byte is not defined, and
9416
+ # an OR that Kleene resolves to true keeps the value written here.
9417
+ bool: "(#3) = ((#1) | (#2)) ? 1 : 0;",
9156
9418
  int: "(#3) = (#1) | (#2);",
9157
9419
  object: '(#3) = rb_funcall((#1), rb_intern("|"), 1, (#2));',
9158
9420
  }
@@ -9355,9 +9617,9 @@ MkKernel.binop :power,
9355
9617
  source: MkKernel::MATH_NUMERIC + [:object],
9356
9618
  expr: {
9357
9619
  int: "(#3) = op_powi_<type>((#1), (#2));",
9358
- complex: "(#3) = cpow((#1), (#2));", # see exp2 on why cpow stays wide
9620
+ complex: MkKernel.pow_short("cpow((#1), (#2))"), # see exp2 on why cpow stays wide
9359
9621
  object: '(#3) = rb_funcall((#1), rb_intern("**"), 1, (#2));',
9360
- }.merge(MkKernel.float_widths("(#3) = pow<f>((#1), (#2));"))
9622
+ }.merge(MkKernel.float_widths(MkKernel.pow_short("pow<f>((#1), (#2))")))
9361
9623
 
9362
9624
  # ---- M.2 + M.3 (PyTorch alignment): float-only binop family --------------
9363
9625
  #