carray-jit 0.1.6 → 0.2.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.
Files changed (65) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +91 -0
  3. data/README.md +3 -7
  4. data/carray-jit.gemspec +11 -3
  5. data/docs/01_GettingStarted.md +1 -1
  6. data/docs/02_KernelShapes.md +33 -17
  7. data/docs/03_SupportedFeatures.md +31 -30
  8. data/docs/04_Compiling.md +10 -7
  9. data/docs/05_DesignNotes.md +1 -3
  10. data/docs/06_Cheatsheet.md +31 -21
  11. data/docs/07_StepByStep.ja.md +45 -45
  12. data/docs/07_StepByStep.md +45 -45
  13. data/docs/08_LanguageReference.md +2 -1
  14. data/examples/applications/alarm.rb +2 -2
  15. data/examples/applications/cubic_spline.rb +20 -20
  16. data/examples/applications/dithering.rb +8 -8
  17. data/examples/applications/game_of_life.rb +1 -1
  18. data/examples/applications/group_stats.rb +4 -4
  19. data/examples/applications/heat_equation.rb +6 -6
  20. data/examples/applications/kepler.rb +10 -10
  21. data/examples/applications/lookup.rb +3 -3
  22. data/examples/applications/median_filter.rb +7 -7
  23. data/examples/applications/moving_average.rb +6 -6
  24. data/examples/applications/parcel_ascent.rb +12 -12
  25. data/examples/applications/partial_sums.rb +6 -6
  26. data/examples/applications/point_cloud.rb +4 -4
  27. data/examples/applications/point_in_polygon.rb +4 -4
  28. data/examples/applications/quicksort.rb +1 -1
  29. data/examples/applications/relaxation.rb +1 -1
  30. data/examples/applications/sensor_gaps.rb +3 -3
  31. data/examples/applications/sobel_edges.rb +6 -6
  32. data/examples/applications/van_der_pol.rb +3 -3
  33. data/examples/applications/wet_bulb.rb +5 -5
  34. data/examples/features/01_element_wise.rb +8 -8
  35. data/examples/features/02_stencil.rb +4 -4
  36. data/examples/features/03_recurrence.rb +1 -1
  37. data/examples/features/04_thomas.rb +8 -8
  38. data/examples/features/05_reduction.rb +8 -8
  39. data/examples/features/06_jit_contract.rb +10 -10
  40. data/examples/features/07_masks.rb +4 -4
  41. data/examples/features/08_views.rb +6 -6
  42. data/examples/features/09_inspecting.rb +2 -2
  43. data/examples/features/10_complex.rb +7 -7
  44. data/examples/features/11_c_functions.rb +17 -17
  45. data/examples/features/12_sweep.rb +20 -25
  46. data/examples/features/13_cscalar.rb +12 -12
  47. data/examples/features/14_stencil_window.rb +6 -6
  48. data/examples/features/15_loops.rb +6 -6
  49. data/examples/features/16_raising.rb +4 -4
  50. data/lib/carray/jit/analyzer.rb +48 -34
  51. data/lib/carray/jit/c_function.rb +213 -153
  52. data/lib/carray/jit/c_generator.rb +33 -12
  53. data/lib/carray/jit/call.rb +1 -1
  54. data/lib/carray/jit/compiler.rb +115 -47
  55. data/lib/carray/jit/errors.rb +22 -0
  56. data/lib/carray/jit/expression.rb +78 -32
  57. data/lib/carray/jit/kernel.rb +28 -53
  58. data/lib/carray/jit/native.rb +171 -0
  59. data/lib/carray/jit/node.rb +1 -1
  60. data/lib/carray/jit/sweep.rb +14 -64
  61. data/lib/carray/jit/type_assignment.rb +9 -4
  62. data/lib/carray/jit/vector_math.rb +111 -0
  63. data/lib/carray/jit/version.rb +1 -1
  64. data/lib/carray/jit.rb +257 -106
  65. metadata +148 -122
data/lib/carray/jit.rb CHANGED
@@ -51,13 +51,23 @@ class CArray
51
51
  # subset is. An expression over whole arrays that needs no compiler is
52
52
  # CArray.fuse's.
53
53
  #
54
- # `reassociate:` says whether a reduction's accumulator may be split into
55
- # partial sums. It defaults to CArray::JIT.reassociate, which is true:
56
- # the answer is then not the one a serial Ruby loop reaches, and is usually
57
- # the more accurate of the two, because splitting the accumulation is what
58
- # limits the cancellation. Pass false for the serial order -- for a
59
- # compensated summation, whose algorithm *is* the order, or to check a
60
- # kernel against the loop it replaces.
54
+ # `fastmath:` says whether the kernel may compute an answer that differs
55
+ # in its last bits from the one a serial Ruby loop reaches. It defaults to
56
+ # CArray::JIT.fastmath, which is true, and it allows two things:
57
+ #
58
+ # - A reduction's accumulator is split into partial sums. That is usually
59
+ # the more accurate answer as well as the faster one, because splitting
60
+ # the accumulation is what limits the cancellation.
61
+ # - A math function (`Math.exp`, `Math.sin`, `**`, ...) is computed by its
62
+ # vector form where the C library has one, which is glibc on x86_64.
63
+ # That answer is within a few units in the last place of the scalar
64
+ # function's, and one input can give two last bits depending on where in
65
+ # the array it sits.
66
+ #
67
+ # It allows nothing else: NaN and infinity are computed as they were, and
68
+ # a multiply and an add are not fused. Pass false for the answer of the
69
+ # Ruby loop -- for a compensated summation, whose algorithm *is* the order,
70
+ # or to check a kernel against the loop it replaces.
61
71
  #
62
72
  # Returns the compiled kernel, whose {CArray::JIT::CompiledKernel#c_source} is the
63
73
  # C that ran.
@@ -66,12 +76,13 @@ class CArray
66
76
  #
67
77
  # @param extents [Array<Range, Integer>] one per loop index, an Integer
68
78
  # standing for `0...n`.
69
- # @param reassociate [Boolean, nil] whether a reduction's accumulator may be
70
- # split into partial sums; `nil` defers to {CArray::JIT.reassociate}.
79
+ # @param fastmath [Boolean, nil] whether a reduction may be split into
80
+ # partial sums and a math function computed by its vector form; `nil`
81
+ # defers to {CArray::JIT.fastmath}.
71
82
  # @return [CArray::JIT::CompiledKernel]
72
83
  # @raise [CArray::JIT::Unsupported] when the block falls outside the
73
84
  # recognized subset, or the extents do not match its parameters.
74
- def self.jit_for (*extents, reassociate: nil, &block)
85
+ def self.jit_for (*extents, fastmath: nil, &block)
75
86
  unless block
76
87
  raise JIT::Unsupported, "jit_for needs a block"
77
88
  end
@@ -81,7 +92,7 @@ class CArray
81
92
  "indices as its parameters; a block that names none is " \
82
93
  "element-wise and belongs to jit_each"
83
94
  end
84
- JIT.run(extents, block, reassociate)
95
+ JIT.run(extents, block, fastmath)
85
96
  end
86
97
 
87
98
  # Returns the kernel compiled from `block` and run at every cell.
@@ -119,10 +130,13 @@ class CArray
119
130
  #
120
131
  # The block is read and compiled, never called, so it is not yielded to.
121
132
  #
133
+ # @param fastmath [Boolean, nil] whether the math functions may be the
134
+ # vector forms, as {CArray.jit_for} says; `nil` defers to
135
+ # {CArray::JIT.fastmath}. There is no reduction here to split.
122
136
  # @return [CArray::JIT::CompiledKernel]
123
137
  # @raise [CArray::JIT::Unsupported] when the block falls outside the
124
138
  # recognized subset, or names any parameter.
125
- def self.jit_each (&block)
139
+ def self.jit_each (fastmath: nil, &block)
126
140
  unless block
127
141
  raise JIT::Unsupported, "jit_each needs a block"
128
142
  end
@@ -131,7 +145,7 @@ class CArray
131
145
  "this block names the arrays it reaches, so it takes no " \
132
146
  "parameters; for a loop that names its indices, see `jit_for`"
133
147
  end
134
- JIT.run_over_whole_arrays(block)
148
+ JIT.run_over_whole_arrays(block, fastmath: fastmath)
135
149
  end
136
150
 
137
151
  # Returns a new array holding `block`'s value at every cell.
@@ -148,10 +162,11 @@ class CArray
148
162
  #
149
163
  # The block is read and compiled, never called, so it is not yielded to.
150
164
  #
165
+ # @param fastmath [Boolean, nil] as {CArray.jit_each}.
151
166
  # @return [CArray] a new array, typed from the block's value.
152
167
  # @raise [CArray::JIT::Unsupported] when the block falls outside the
153
168
  # recognized subset, or names any parameter.
154
- def self.jit_map (&block)
169
+ def self.jit_map (fastmath: nil, &block)
155
170
  unless block
156
171
  raise JIT::Unsupported, "jit_map needs a block"
157
172
  end
@@ -160,7 +175,7 @@ class CArray
160
175
  "this block names the arrays it reaches, so it takes no " \
161
176
  "parameters; for a loop that names its indices, see `jit_for`"
162
177
  end
163
- JIT.run_over_whole_arrays(block, map: true)
178
+ JIT.run_over_whole_arrays(block, map: true, fastmath: fastmath)
164
179
  end
165
180
 
166
181
  # Returns a new array holding `block`'s value at every cell, computed from
@@ -202,11 +217,14 @@ class CArray
202
217
  # block's value's.
203
218
  # @param into [CArray, nil] an array of yours to write into, which then
204
219
  # decides the type.
220
+ # @param fastmath [Boolean, nil] as {CArray.jit_each}. A sum over a
221
+ # window stays in the order it was written.
205
222
  # @return [CArray] `into` when it is given, otherwise a new array.
206
223
  # @raise [CArray::JIT::Unsupported] when the block falls outside the
207
224
  # recognized subset, when no array is given, or when both `type` and
208
225
  # `into` are.
209
- def self.jit_stencil (*arrays, border: :mask, type: nil, into: nil, &block)
226
+ def self.jit_stencil (*arrays, border: :mask, type: nil, into: nil,
227
+ fastmath: nil, &block)
210
228
  unless block
211
229
  raise JIT::Unsupported, "jit_stencil needs a block"
212
230
  end
@@ -215,7 +233,7 @@ class CArray
215
233
  "jit_stencil takes the arrays its block has windows onto, as in " \
216
234
  "`CArray.jit_stencil(image) { |a| ... }`"
217
235
  end
218
- JIT.run_stencil(arrays, block, border, type, into)
236
+ JIT.run_stencil(arrays, block, border, type, into, fastmath)
219
237
  end
220
238
 
221
239
  # Returns the contraction the block writes: a repeated index is summed.
@@ -271,18 +289,22 @@ class CArray
271
289
  #
272
290
  # The sum is split into partial ones, as `jit_for`'s reduction is: a
273
291
  # contraction says which indices are summed and nothing about the order, so
274
- # there is no order here to override. `CArray::JIT.reassociate = false`
275
- # asks for the serial one, which is what a Ruby loop would take.
292
+ # there is no order here to override. `fastmath: false` asks for the
293
+ # serial one, which is what a Ruby loop would take, and for the scalar
294
+ # math functions; without the keyword the call follows
295
+ # `CArray::JIT.fastmath`.
276
296
  #
277
297
  # The block is read and compiled, never called, so it is not yielded to.
278
298
  #
279
299
  # @param free_indices [Array<Symbol>] the result's axes, in order; empty to
280
300
  # let the convention decide, which is an index appearing once.
301
+ # @param fastmath [Boolean, nil] as {CArray.jit_for}; `nil` defers to
302
+ # {CArray::JIT.fastmath}.
281
303
  # @return [CArray, CArray::JIT::CompiledKernel] the allocated result when the block
282
304
  # assigns into nothing, otherwise the compiled kernel.
283
305
  # @raise [CArray::JIT::Unsupported] when the block falls outside the
284
306
  # recognized subset, or an index's axes disagree.
285
- def self.jit_contract (*free_indices, &block)
307
+ def self.jit_contract (*free_indices, fastmath: nil, &block)
286
308
  unless block
287
309
  raise JIT::Unsupported, "jit_contract needs a block"
288
310
  end
@@ -299,7 +321,8 @@ class CArray
299
321
  end
300
322
  # Nothing named is the convention; naming none of them is a contraction
301
323
  # to a single number, and the two are different statements.
302
- JIT.run_contraction(block, free_indices.empty? ? nil : free_indices)
324
+ JIT.run_contraction(block, free_indices.empty? ? nil : free_indices,
325
+ fastmath)
303
326
  end
304
327
 
305
328
  # @!endgroup
@@ -315,9 +338,9 @@ class CArray
315
338
  # CArray.jit_each { out = j0.call(x) }
316
339
  #
317
340
  # Nothing is compiled here: `extern` is C's word for a body that lives
318
- # elsewhere, and finding it is Fiddle's job. What this gem adds is that the
319
- # kernel calls the address directly instead of reaching it per cell through
320
- # Fiddle.
341
+ # elsewhere, and finding it is the dynamic loader's job. What this gem adds
342
+ # is that the kernel calls the address directly instead of reaching it per
343
+ # cell through a foreign-function call from Ruby.
321
344
  #
322
345
  # @param prototype [String] the function's C declaration, as C writes it.
323
346
  # @param from [String, nil] the library to open; `nil` searches the process.
@@ -335,14 +358,23 @@ class CArray
335
358
  # can be factored and named, and its address may be handed to a C library
336
359
  # that knows nothing about Ruby.
337
360
  #
361
+ # `fastmath:` says whether a math function in a loop of the body may be
362
+ # computed by its vector form, as {CArray.jit_for} says. The answer is
363
+ # taken when the function is compiled, and it stays with the function. It
364
+ # is about the function called on its own, from Ruby or from a C library.
365
+ # A kernel that calls the function compiles the body into itself, and
366
+ # there the kernel's own `fastmath` decides.
367
+ #
338
368
  # The block is read and compiled, never called, so it is not yielded to.
339
369
  #
340
370
  # @param prototype [String] the function's C declaration, as C writes it.
371
+ # @param fastmath [Boolean, nil] whether the math functions may be the
372
+ # vector forms; `nil` defers to {CArray::JIT.fastmath}.
341
373
  # @return [CArray::JIT::CFunction]
342
374
  # @raise [CArray::JIT::Unsupported] when the block falls outside the
343
375
  # recognized subset.
344
- def self.jit_function (prototype, &block)
345
- JIT.function(prototype, &block)
376
+ def self.jit_function (prototype, fastmath: nil, &block)
377
+ JIT.function(prototype, fastmath: fastmath, &block)
346
378
  end
347
379
 
348
380
  # Gives every cell of `self` the block's value at its indices, and returns
@@ -381,12 +413,12 @@ class CArray
381
413
  #
382
414
  # The block is read and compiled, never called, so it is not yielded to.
383
415
  #
384
- # @param reassociate [Boolean, nil] as {CArray.jit_for}; `nil` defers to
385
- # {CArray::JIT.reassociate}.
416
+ # @param fastmath [Boolean, nil] as {CArray.jit_for}; `nil` defers to
417
+ # {CArray::JIT.fastmath}.
386
418
  # @return [CArray] `self`
387
419
  # @raise [CArray::JIT::Unsupported] when the block falls outside the
388
420
  # recognized subset, or names a number of indices other than `ndim`.
389
- def jit_init (reassociate: nil, &block)
421
+ def jit_init (fastmath: nil, &block)
390
422
  unless block
391
423
  raise JIT::Unsupported, "jit_init needs a block"
392
424
  end
@@ -413,46 +445,50 @@ class CArray
413
445
  "#{block.arity == 1 ? 'index' : 'indices'}; jit_init fills every " \
414
446
  "cell, so there is one index per axis"
415
447
  end
416
- JIT.run(dim, block, reassociate, into: self)
448
+ JIT.run(shape, block, fastmath, into: self)
417
449
  end
418
450
 
419
451
  # @!endgroup
420
452
 
421
453
  # The compiler behind `CArray.jit_*`: it reads a block, generates C for it,
422
- # builds it and calls it. What is public here is the reassociation default
454
+ # builds it and calls it. What is public here is the `fastmath` default
423
455
  # and the kernel cache; the rest is the machinery.
424
456
  module JIT
425
457
 
426
458
  class << self
427
459
 
428
- # Whether a reduction's accumulator may be split into partial sums when
429
- # the call site does not say. True: a kernel is here to be fast, and
430
- # splitting the accumulation is usually the more accurate answer as well
431
- # as the faster one.
460
+ # Whether a kernel may compute an answer that differs in its last bits
461
+ # from a serial Ruby loop's, when the call site does not say. True: a
462
+ # kernel is here to be fast.
463
+ #
464
+ # It is two things. A reduction's accumulator is split into partial
465
+ # sums, in `jit_for`, `jit_init` and a contraction. And in every
466
+ # kernel, a math function is computed by its vector form where the C
467
+ # library has one (see VectorMath). Every `jit_` method that
468
+ # compiles a kernel, and `jit_function`, takes `fastmath:` per call;
469
+ # this is the answer for a call that does not say.
432
470
  #
433
- # What it does not give is the order a serial Ruby loop takes, so it is
434
- # false that says "compute this exactly as the loop would" -- for a
471
+ # False says "compute this exactly as the loop would" -- for a
435
472
  # compensated summation, or to check one against the other.
436
- # CARRAY_JIT_REASSOCIATE=0 sets it false for a whole process, which is
437
- # how this gem's own tests compare against Ruby.
438
- # @!attribute [w] reassociate
439
- # Sets whether a reduction's accumulator may be split into partial
440
- # sums when the call site does not say.
473
+ # CARRAY_JIT_FASTMATH=0 sets it false for a whole process.
474
+ # @!attribute [w] fastmath
475
+ # Sets whether a kernel may split a reduction and use the vector forms
476
+ # of the math functions when the call site does not say.
441
477
  # @return [Boolean]
442
- attr_writer :reassociate
478
+ attr_writer :fastmath
443
479
 
444
- # @return [Boolean] whether a reduction's accumulator may be split when
445
- # the call site does not say.
446
- def reassociate
447
- return @reassociate unless @reassociate.nil?
448
- @reassociate = ENV["CARRAY_JIT_REASSOCIATE"] != "0"
480
+ # @return [Boolean] whether a kernel may split a reduction and use the
481
+ # vector forms of the math functions when the call site does not say.
482
+ def fastmath
483
+ return @fastmath unless @fastmath.nil?
484
+ @fastmath = ENV["CARRAY_JIT_FASTMATH"] != "0"
449
485
  end
450
486
 
451
487
  # @private
452
488
  RESULT = :__contraction_result
453
489
 
454
490
  # @private
455
- def run_contraction (block, free_indices = nil)
491
+ def run_contraction (block, free_indices = nil, fastmath = nil)
456
492
  node, source, origin = read_block(block)
457
493
  # An index named at the call site is not a parameter of the block, so
458
494
  # the block reaches for it the way it reaches for a captured value.
@@ -464,7 +500,8 @@ class CArray
464
500
  "and runs once per term, so a draw in it would be one per term " \
465
501
  "rather than one per cell of the result")
466
502
  contract(source, arrays, free_indices, node: node, origin: origin,
467
- scalars: scalars, c_functions: c_functions)
503
+ scalars: scalars, c_functions: c_functions,
504
+ fastmath: fastmath)
468
505
  end
469
506
 
470
507
  # Reads a block as a contraction and returns the terms it is a product
@@ -706,7 +743,8 @@ class CArray
706
743
  # is the same whatever recovered them, which is what lets
707
744
  # `contract_terms` reach it with a source it wrote itself.
708
745
  def contract (source, arrays, free_indices,
709
- node: nil, origin: nil, scalars: {}, c_functions: {})
746
+ node: nil, origin: nil, scalars: {}, c_functions: {},
747
+ fastmath: nil)
710
748
  result = allocate_result(source, node, arrays, scalars, free_indices,
711
749
  c_functions)
712
750
  arrays = arrays.merge(RESULT => result) if result
@@ -725,7 +763,7 @@ class CArray
725
763
  # in is not something the caller wrote, so splitting
726
764
  # the sum into partial ones does not change what the
727
765
  # contraction means. Same licence `jit_for` takes.
728
- reassociate: JIT.reassociate,
766
+ fastmath: fastmath.nil? ? JIT.fastmath : fastmath,
729
767
  free_indices: free_indices,
730
768
  cell_names: cell_names(arrays))
731
769
 
@@ -785,7 +823,7 @@ class CArray
785
823
  free, index_axes, type = probe
786
824
  shape = free.map do |index|
787
825
  extents = index_axes.fetch(index).map { |array, axis|
788
- [arrays.fetch(array).dim[axis], array, axis]
826
+ [arrays.fetch(array).shape[axis], array, axis]
789
827
  }
790
828
  distinct = extents.map(&:first).uniq
791
829
  if distinct.size > 1
@@ -865,7 +903,7 @@ class CArray
865
903
  order = kernel.index_names + kernel.contracted_names
866
904
  order.map do |index|
867
905
  places = kernel.index_axes[index]
868
- extents = places.map { |array, axis| [arrays.fetch(array).dim[axis], array, axis] }
906
+ extents = places.map { |array, axis| [arrays.fetch(array).shape[axis], array, axis] }
869
907
  distinct = extents.map(&:first).uniq
870
908
  if distinct.size > 1
871
909
  described = extents.map { |extent, array, axis|
@@ -905,11 +943,10 @@ class CArray
905
943
  # that every operand already has the shape the pass covers, which is
906
944
  # stricter than agreeing on the count of cells.
907
945
  def sweepable_pass? (arrays, shape, masked)
908
- return false unless Sweep.available?
909
946
  return false if masked
910
947
  return false if arrays.empty? || arrays.size > Sweep::MAX_ARITY
911
948
  return false unless arrays.each_value.all? { |array|
912
- array.ndim.zero? || array.dim == shape
949
+ array.ndim.zero? || array.shape == shape
913
950
  }
914
951
  walkable_in_place?(arrays.each_value)
915
952
  end
@@ -976,7 +1013,7 @@ class CArray
976
1013
  COMPUTED_BORDERS = [:zero, :clamp, :wrap].freeze
977
1014
 
978
1015
  # @private
979
- def run_stencil (arrays, block, border, type, into)
1016
+ def run_stencil (arrays, block, border, type, into, fastmath = nil)
980
1017
  unless FRAME_BORDERS.include?(border) || COMPUTED_BORDERS.include?(border)
981
1018
  raise Unsupported,
982
1019
  "`border:` is " \
@@ -1005,15 +1042,15 @@ class CArray
1005
1042
  "#{array.class}"
1006
1043
  end
1007
1044
  end
1008
- shape = arrays.first.dim
1045
+ shape = arrays.first.shape
1009
1046
  arrays.each_with_index do |array, position|
1010
- next if array.dim == shape
1047
+ next if array.shape == shape
1011
1048
  # Shapes are required to agree rather than broadcast: a stretched
1012
1049
  # axis has no neighbour to reach, so what a window would mean on one
1013
1050
  # is a question this does not have to answer yet.
1014
1051
  raise Unsupported,
1015
1052
  "`#{windows.first}` has shape #{shape.inspect} and " \
1016
- "`#{windows[position]}` #{array.dim.inspect}; a stencil's " \
1053
+ "`#{windows[position]}` #{array.shape.inspect}; a stencil's " \
1017
1054
  "arrays have the same shape"
1018
1055
  end
1019
1056
 
@@ -1052,6 +1089,7 @@ class CArray
1052
1089
  rank: shape.size,
1053
1090
  windows: windows,
1054
1091
  border: COMPUTED_BORDERS.include?(border) ? border : nil,
1092
+ vector_math: fastmath,
1055
1093
  map: true,
1056
1094
  result: MAP_RESULT)
1057
1095
 
@@ -1062,11 +1100,18 @@ class CArray
1062
1100
  low, high = reach[axis]
1063
1101
  [-low, extent - high, 1]
1064
1102
  }
1065
- if bounds.any? { |from, to, _| from >= to }
1103
+ # An array narrower than the window along some axis has no interior.
1104
+ # Under a rule that computes the frame every cell is then a frame
1105
+ # cell, and the frame's body answers for a read however far outside
1106
+ # it falls. Under `:mask` and `:skip` no cell would be computed at
1107
+ # all, which is refused.
1108
+ no_interior = bounds.any? { |from, to, _| from >= to }
1109
+ if no_interior && !COMPUTED_BORDERS.include?(border)
1066
1110
  raise Unsupported,
1067
1111
  "the window reaches #{reach.inspect} and the arrays are " \
1068
1112
  "#{shape.inspect}, so there is no cell where the window is " \
1069
- "inside the array"
1113
+ "inside the array, and `border: #{border.inspect}` computes " \
1114
+ "only those; `:zero`, `:clamp` and `:wrap` compute every cell"
1070
1115
  end
1071
1116
  # Writing into an array a window reads is not a pass over the array:
1072
1117
  # a cell written here is a neighbour a later cell reads, so what comes
@@ -1095,9 +1140,12 @@ class CArray
1095
1140
  result.mask = 0 if (kernel.masked || border == :mask) && !result.has_mask?
1096
1141
  mark_frame(result, bounds, shape) if border == :mask
1097
1142
  operands = given.merge(MAP_RESULT => result)
1098
- kernel.call(operands, scalars, bounds, c_functions)
1143
+ kernel.call(operands, scalars, bounds, c_functions) unless no_interior
1099
1144
  if COMPUTED_BORDERS.include?(border)
1100
- frame_boxes(bounds, shape).each do |box|
1145
+ boxes = if no_interior then [shape.map { |extent| [0, extent, 1] }]
1146
+ else frame_boxes(bounds, shape)
1147
+ end
1148
+ boxes.each do |box|
1101
1149
  kernel.call(operands, scalars, box, c_functions, border: true)
1102
1150
  end
1103
1151
  end
@@ -1155,7 +1203,7 @@ class CArray
1155
1203
  def stencil_result (source, node, arrays, scalars, c_functions, windows,
1156
1204
  shape, type, into)
1157
1205
  if into
1158
- unless into.is_a?(CArray) && into.dim == shape
1206
+ unless into.is_a?(CArray) && into.shape == shape
1159
1207
  raise Unsupported,
1160
1208
  "`into:` takes an array of the stencil's own shape " \
1161
1209
  "#{shape.inspect}"
@@ -1232,8 +1280,12 @@ class CArray
1232
1280
  RUN_PLAN_LIMIT = 8
1233
1281
 
1234
1282
  # @private
1235
- def run_over_whole_arrays (block, map: false)
1283
+ def run_over_whole_arrays (block, map: false, fastmath: nil)
1236
1284
  node, source, origin = read_block(block)
1285
+ # After the block is read, which is where another Ractor is refused:
1286
+ # asking for the default writes this module's state.
1287
+ fastmath = JIT.fastmath if fastmath.nil?
1288
+ fastmath = fastmath ? true : false
1237
1289
  free, assigned = free_and_assigned_names(source, node)
1238
1290
  # One Binding for the three questions asked of it. `Proc#binding`
1239
1291
  # allocates one every time it is asked, and this method is re-entered
@@ -1268,11 +1320,11 @@ class CArray
1268
1320
  # plan leaves to the call is what it has to: the operands themselves,
1269
1321
  # the views the broadcast makes of them, a generator's state, the
1270
1322
  # map's result, and the masks.
1271
- key = run_key(arrays, scalars, c_functions, randoms, map)
1323
+ key = run_key(arrays, scalars, c_functions, randoms, map, fastmath)
1272
1324
  plan = key && found_run_plan(source, key)
1273
1325
  unless plan
1274
1326
  plan = plan_run(source, node, origin, arrays, scalars, c_functions,
1275
- randoms, map)
1327
+ randoms, map, fastmath)
1276
1328
  keep_run_plan(source, key, plan) if key
1277
1329
  end
1278
1330
 
@@ -1353,27 +1405,26 @@ class CArray
1353
1405
  #
1354
1406
  # Then the type of each scalar, each C function's signature and each
1355
1407
  # generator's kind, which is what the kernel is compiled for of those.
1408
+ # And the call's answer about `fastmath`, which decides the C.
1356
1409
  # Not a scalar's value: a clock or a coefficient changes every step,
1357
1410
  # and keying on it would miss on every call of the loop this is for.
1358
1411
  #
1359
1412
  # Values only, never an operand: a block's plans live as long as the
1360
- # process, and holding an array would hold its memory as long. Shapes
1361
- # from `ndim`, `elements` and `dim0`.. rather than `dim`, which builds
1362
- # an Array on every call.
1413
+ # process, and holding an array would hold its memory as long. A 1-D
1414
+ # shape is its `elements`, which builds no Array.
1363
1415
  #
1364
1416
  # nil where a scalar is not one a kernel takes, so that the call is
1365
1417
  # refused where and as it always was rather than here.
1366
- def run_key (arrays, scalars, c_functions, randoms, map)
1367
- key = [map, arrays.size]
1418
+ def run_key (arrays, scalars, c_functions, randoms, map, fastmath)
1419
+ key = [map, fastmath, arrays.size]
1368
1420
  arrays.each do |name, array|
1369
1421
  rank = array.ndim
1370
1422
  key << name << array.data_type << rank << array.is_a?(CScalar) <<
1371
1423
  array.has_mask? << Access.tier(array)
1372
- case rank
1373
- when 1 then key << array.elements
1374
- when 2 then key << array.dim0 << array.dim1
1375
- when 3 then key << array.dim0 << array.dim1 << array.dim2
1376
- else key.concat(array.dim)
1424
+ if rank == 1
1425
+ key << array.elements
1426
+ else
1427
+ key.concat(array.shape)
1377
1428
  end
1378
1429
  end
1379
1430
  key << scalars.size
@@ -1389,8 +1440,12 @@ class CArray
1389
1440
  end
1390
1441
 
1391
1442
  # @private
1443
+ # Two stores, one for each answer of `fastmath`: a plan holds the
1444
+ # kernel that was compiled under one of them, and the process default
1445
+ # can be changed between two calls of the same block.
1392
1446
  def run_plans
1393
- @run_plans ||= {}
1447
+ @run_plans ||= { true => {}, false => {} }
1448
+ @run_plans[JIT.fastmath ? true : false]
1394
1449
  end
1395
1450
 
1396
1451
  # The block's plan for this key, if it has one. The list a plan sits
@@ -1433,7 +1488,7 @@ class CArray
1433
1488
  # met here, before a plan exists, so a plan is only ever of a call that
1434
1489
  # ran.
1435
1490
  def plan_run (source, node, origin, arrays, scalars, c_functions,
1436
- randoms, map)
1491
+ randoms, map, fastmath = nil)
1437
1492
  # An array the block only hands to a C function whole is not walked,
1438
1493
  # so the expression's shape has nothing to say about it -- and it has
1439
1494
  # a shape of its own that need not line up with anything. Left in,
@@ -1486,15 +1541,16 @@ class CArray
1486
1541
  randoms: randoms,
1487
1542
  masked: masked,
1488
1543
  rank: sweeping ? 1 : shape.size,
1544
+ vector_math: fastmath,
1489
1545
  map: map,
1490
1546
  result: map ? MAP_RESULT : nil)
1491
1547
 
1492
1548
  kernel.written_arrays.each do |name|
1493
1549
  next if name == MAP_RESULT
1494
1550
  written = arrays.fetch(name)
1495
- unless written.dim == shape
1551
+ unless written.shape == shape
1496
1552
  raise Unsupported,
1497
- "`#{name}` has shape #{written.dim.inspect}, but the " \
1553
+ "`#{name}` has shape #{written.shape.inspect}, but the " \
1498
1554
  "expression covers #{shape.inspect}; a stretched array " \
1499
1555
  "cannot be written to"
1500
1556
  end
@@ -1526,6 +1582,16 @@ class CArray
1526
1582
  written = written_names.filter_map { |name| aligned[name] }
1527
1583
  return aligned if written.empty?
1528
1584
  roots = written.map { |array| root_of(array) }
1585
+ # Asked first without building anything, because the answer is nearly
1586
+ # always that nothing is shared, and this runs on every call. The
1587
+ # root is compared first since it is what nearly always says no.
1588
+ shared = aligned.any? { |name, array|
1589
+ next false if written_names.include?(name)
1590
+ root = root_of(array)
1591
+ roots.any? { |one| one.equal?(root) } &&
1592
+ written.none? { |one| one.equal?(array) }
1593
+ }
1594
+ return aligned unless shared
1529
1595
  aligned.to_h do |name, array|
1530
1596
  next [name, array] if written_names.include?(name)
1531
1597
  next [name, array] if written.any? { |other| other.equal?(array) }
@@ -1598,7 +1664,7 @@ class CArray
1598
1664
  value.is_a?(CScalar) ? value.refer(value.data_type, [1] * rank) : value
1599
1665
  }
1600
1666
  aligned = values.size == 1 ? values : CArray.broadcast(*values)
1601
- [arrays.keys.zip(aligned).to_h, aligned.first.dim]
1667
+ [arrays.keys.zip(aligned).to_h, aligned.first.shape]
1602
1668
  end
1603
1669
 
1604
1670
  # An indexed kernel addresses what it is handed, so a CScalar among the
@@ -1619,7 +1685,7 @@ class CArray
1619
1685
  # statement is what the cell of `into` gets, as jit_map's is what the
1620
1686
  # cell of its own result gets. Without it the block writes the arrays
1621
1687
  # it names, which is jit_for.
1622
- def run (extents, block, reassociate = nil, into: nil)
1688
+ def run (extents, block, fastmath = nil, into: nil)
1623
1689
  node, source, origin = read_block(block)
1624
1690
  names = capture_names(source, node)
1625
1691
  arrays, scalars, c_functions, randoms =
@@ -1645,21 +1711,23 @@ class CArray
1645
1711
  end
1646
1712
  pairs = bounds(extents, extents.size)
1647
1713
  steps = pairs.map { |triple, _| triple[2] }
1714
+ fastmath = JIT.fastmath if fastmath.nil?
1715
+
1716
+ # Which kernel runs, and whether any operand would be transferred,
1717
+ # answer the same for two calls whose operands agree on name, type,
1718
+ # mask and tier -- so they are worked out once per such agreement,
1719
+ # as an element-wise pass does (#run_over_whole_arrays).
1720
+ key = indexed_run_key(arrays, scalars, c_functions, randoms, steps,
1721
+ into, fastmath)
1722
+ plan = key && found_run_plan(source, key)
1723
+ unless plan
1724
+ plan = plan_indexed_run(source, node, origin, arrays, scalars,
1725
+ c_functions, randoms, steps, into,
1726
+ fastmath)
1727
+ keep_run_plan(source, key, plan) if key
1728
+ end
1648
1729
 
1649
- kernel = compile(source,
1650
- node: node,
1651
- origin: origin,
1652
- array_names: arrays.keys,
1653
- storage_types: arrays.transform_values(&:data_type_name),
1654
- scalar_values: scalars,
1655
- c_functions: c_functions,
1656
- randoms: randoms,
1657
- masked: arrays.each_value.any? { |array| array.has_mask? },
1658
- steps: steps,
1659
- cell_names: cell_names(arrays),
1660
- map: into ? true : false,
1661
- result: into ? INIT_TARGET : nil,
1662
- reassociate: reassociate.nil? ? JIT.reassociate : reassociate)
1730
+ kernel = plan.kernel
1663
1731
  # The kernel decides, not the caller: mentioning UNDEF makes it a
1664
1732
  # masked kernel even when no array carries a mask yet.
1665
1733
  if kernel.masked
@@ -1675,11 +1743,77 @@ class CArray
1675
1743
  "#{pairs.size} #{pairs.size == 1 ? 'extent was' : 'extents were'} " \
1676
1744
  "given"
1677
1745
  end
1678
- refuse_a_transferred_alias(kernel, arrays)
1746
+ # Only an operand opened at the xfer tier can be refused, and the tier
1747
+ # is in the key; which arrays share a root is not, and is asked here.
1748
+ refuse_a_transferred_alias(kernel, arrays) if plan.transferred
1679
1749
  kernel.call(arrays, scalars, pairs.map(&:first), c_functions)
1680
1750
  into || kernel
1681
1751
  end
1682
1752
 
1753
+ # What an indexed pass works out from its operands without their data
1754
+ # or their shapes: the kernel, and whether any operand is opened at the
1755
+ # xfer tier. The shapes are the kernel's own plan to keep, since they
1756
+ # are what its bounds are checked against (CompiledKernel#call).
1757
+ #
1758
+ # @private
1759
+ IndexedRunPlan = Data.define(:kernel, :transferred)
1760
+
1761
+ # What two calls of one indexed block have to agree on for one to run
1762
+ # the other's kernel: what #compile is keyed on, read off the operands
1763
+ # rather than built. Each operand's name and type, whether it is a
1764
+ # CScalar (read at its one cell rather than walked) and whether it has
1765
+ # a mask; and its tier, because whether a transferred operand has to be
1766
+ # refused depends on it. Not its shape: the kernel is the same over
1767
+ # any shape, and a caller that grows its arrays would miss on every
1768
+ # call. Not a scalar's value, for the reason #run_key gives.
1769
+ #
1770
+ # The leading symbol keeps these apart from an element-wise pass's
1771
+ # keys, which share the store.
1772
+ #
1773
+ # nil where a scalar is not one a kernel takes, so that the call is
1774
+ # refused where and as it always was rather than here.
1775
+ def indexed_run_key (arrays, scalars, c_functions, randoms, steps, into,
1776
+ fastmath)
1777
+ key = [:indexed, into ? true : false, fastmath, steps, arrays.size]
1778
+ arrays.each do |name, array|
1779
+ key << name << array.data_type << array.is_a?(CScalar) <<
1780
+ array.has_mask? << Access.tier(array)
1781
+ end
1782
+ key << scalars.size
1783
+ scalars.each do |name, value|
1784
+ key << name << TypeAssignment.scalar_type(value)
1785
+ end
1786
+ key << c_functions.size
1787
+ c_functions.each { |name, function| key << name << function.kernel_key }
1788
+ randoms.each { |name, generator| key << name << generator.generator }
1789
+ key
1790
+ rescue Unsupported
1791
+ nil
1792
+ end
1793
+
1794
+ # @private
1795
+ def plan_indexed_run (source, node, origin, arrays, scalars, c_functions,
1796
+ randoms, steps, into, fastmath)
1797
+ kernel = compile(source,
1798
+ node: node,
1799
+ origin: origin,
1800
+ array_names: arrays.keys,
1801
+ storage_types: arrays.transform_values(&:data_type_name),
1802
+ scalar_values: scalars,
1803
+ c_functions: c_functions,
1804
+ randoms: randoms,
1805
+ masked: arrays.each_value.any? { |array| array.has_mask? },
1806
+ steps: steps,
1807
+ cell_names: cell_names(arrays),
1808
+ map: into ? true : false,
1809
+ result: into ? INIT_TARGET : nil,
1810
+ fastmath: fastmath)
1811
+ transferred = arrays.each_value.any? { |array|
1812
+ Access.tier(array) == Access::TIER_XFER
1813
+ }
1814
+ IndexedRunPlan.new(kernel: kernel, transferred: transferred)
1815
+ end
1816
+
1683
1817
  # Compiles for one set of array data types and one set of scalar types,
1684
1818
  # and returns the same CompiledKernel for every later call with the
1685
1819
  # same ones. Nothing on this path is cheap relative to running the
@@ -1687,11 +1821,24 @@ class CArray
1687
1821
  def compile (source, node: nil, origin: nil, array_names:, storage_types:,
1688
1822
  scalar_values:, c_functions: {}, masked: false, rank: nil,
1689
1823
  steps: nil, contract: false, result: nil, map: false,
1690
- reassociate: false, cell_names: [], windows: [], border: nil,
1691
- free_indices: nil, randoms: {})
1824
+ fastmath: nil, cell_names: [], windows: [], border: nil,
1825
+ free_indices: nil, randoms: {}, vector_math: nil)
1692
1826
  # A kernel that mentions UNDEF is a masked one whatever its arrays
1693
1827
  # carry, and deciding that here means no caller has to remember it.
1694
1828
  masked ||= mentions_undef(source, node)
1829
+ # `fastmath` is two things here. A reduction is split into partial
1830
+ # sums only where the caller said true: `jit_for`, `jit_init` and a
1831
+ # contraction pass their answer as `fastmath`, and the other kernels
1832
+ # leave it nil and keep the serial accumulator. The math.h functions
1833
+ # in their vector forms are for every kernel: those other kernels
1834
+ # pass their answer as `vector_math`, and a caller that says nothing
1835
+ # follows the process. The second is only true where there are such
1836
+ # forms, so that the key and the C are the same with and without it
1837
+ # everywhere else.
1838
+ reassociate = fastmath ? true : false
1839
+ vector_math = fastmath if vector_math.nil?
1840
+ vector_math = JIT.fastmath if vector_math.nil?
1841
+ vector_math &&= VectorMath.available?
1695
1842
  key = [source, storage_types,
1696
1843
  scalar_values.transform_values { |value|
1697
1844
  TypeAssignment.scalar_type(value)
@@ -1725,14 +1872,16 @@ class CArray
1725
1872
  # The licence is part of the kernel, not of the call: it
1726
1873
  # decides what C is emitted, so the two spellings are two
1727
1874
  # kernels and the cache keeps them apart.
1728
- reassociate]
1875
+ reassociate,
1876
+ # And so is its other half.
1877
+ vector_math]
1729
1878
  found = registry[key]
1730
1879
  return found if found
1731
1880
  registry[key] = build(source, node, array_names, storage_types,
1732
1881
  scalar_values, c_functions, masked, rank, steps,
1733
1882
  contract, result, origin, map, reassociate,
1734
1883
  cell_names, windows, border, free_indices,
1735
- randoms)
1884
+ randoms, vector_math)
1736
1885
  end
1737
1886
 
1738
1887
  # A kernel that mentions UNDEF is a masked kernel whatever its arrays
@@ -1856,7 +2005,7 @@ class CArray
1856
2005
  @local_array_name_cache = {}
1857
2006
  # A plan holds the kernel it runs, so one left behind would hand the
1858
2007
  # next call a kernel the registry no longer has.
1859
- @run_plans = {}
2008
+ @run_plans = nil
1860
2009
  end
1861
2010
 
1862
2011
  # @return [String] the directory this environment's kernels are kept in,
@@ -1924,7 +2073,7 @@ class CArray
1924
2073
  masked, rank = nil, steps = nil, contract = false, result = nil,
1925
2074
  origin = nil, map = false, reassociate = false,
1926
2075
  cell_names = [], windows = [], border = nil, free_indices = nil,
1927
- randoms = {})
2076
+ randoms = {}, vector_math = false)
1928
2077
  analyzer = Analyzer.new(source, node: node, array_names: array_names,
1929
2078
  c_functions: c_functions,
1930
2079
  rank: rank, steps: steps, contract: contract,
@@ -1938,6 +2087,7 @@ class CArray
1938
2087
  c_functions: c_functions,
1939
2088
  randoms: randoms,
1940
2089
  masked: masked, reassociate: reassociate,
2090
+ vector_math: vector_math,
1941
2091
  steps: steps, border: border,
1942
2092
  origin: origin, block_source: source)
1943
2093
  CompiledKernel.new(source: source, generator: generator,
@@ -1947,6 +2097,7 @@ class CArray
1947
2097
  # Recovering a block's source means parsing the whole file it lives in,
1948
2098
  # which is far too expensive to repeat per call.
1949
2099
  def read_block (block)
2100
+ refuse_outside_the_main_ractor
1950
2101
  sequence = RubyVM::InstructionSequence.of(block) if
1951
2102
  defined?(RubyVM::InstructionSequence)
1952
2103
  return BlockReader.read(block) unless sequence
@@ -1974,7 +2125,7 @@ class CArray
1974
2125
  }
1975
2126
  return unless shadowed
1976
2127
  raise Unsupported,
1977
- "`#{shadowed}` is made in this block with `CArray.double` or " \
2128
+ "`#{shadowed}` is made in this block with `CArray.float64` or " \
1978
2129
  "its kin, and the block also closes over an array named " \
1979
2130
  "`#{shadowed}`; in this spelling an assignment writes that " \
1980
2131
  "array's cell, so the line means one thing to a reader and " \