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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e052fd85b01164a6147a30ca655b8997ba7c87ac9c7ec8354d73447d1208b5ca
4
- data.tar.gz: 2a6ebb524fb6afee5c871c0a45ed13ecf2f120f9ef0194e36f486ac3b015b378
3
+ metadata.gz: 3ae3ede69271790a17fe3311aefd5614a70d4e5aff72a744a87792441eba8ade
4
+ data.tar.gz: 8ec8d53664a22c8345609e45d206ac3d894757c6a155f80455d05148d27c6609
5
5
  SHA512:
6
- metadata.gz: bd5017f5251ad7b9f4263bfc25091a938d3bccd7f18ef5d83a5a68b63f57e0df6c1ee4278ccd1b903a68cb77a5a156a47c98cbc4832edabbf144593778fed1b5
7
- data.tar.gz: d8d2733f8a98376561ccb183895e1e963eff8a1caea636d066e88ce4852f167fb8755c6f1225beaf0c89aea51bf18dab4482bde0a079983ff507e9cd66769b2f
6
+ metadata.gz: c9d8df5108e11db1e9349ee128a06e19387da87150630e41c18e6ff852878b53c2b51fba390170ff171c521205f0a526ed250f4b8b3316f4ade19da9d8edce87
7
+ data.tar.gz: 89c4a746948fd3a939c03ee801e5f909162a7321082da5f9f8f1ba8d3ca9d9adaaa162543cda694b88fd7f32e93a124d7e92b222e960a54dde1d1ac8a5713920
data/CHANGELOG.md CHANGED
@@ -37,6 +37,97 @@ version you have and a newer one.
37
37
  a release needs is said in the gemspec, and an entry says so only
38
38
  when the answer changes. -->
39
39
 
40
+ ## 0.2.0
41
+
42
+ - New: under `fastmath`, a math function in a kernel (`Math.exp`,
43
+ `Math.log`, `Math.sin`, `**` with real operands and the others the C
44
+ library covers) is computed by its vector form on x86_64 Linux with
45
+ glibc. The answer can differ from `Math`'s in the last few bits; NaN
46
+ and infinity are computed as they were. `fastmath: false` on the call,
47
+ or `CARRAY_JIT_FASTMATH=0` for the process, asks for the scalar
48
+ functions. Nothing changes on other platforms.
49
+
50
+ - New: `jit_each`, `jit_map`, `jit_stencil`, `jit_contract` and
51
+ `jit_function` take `fastmath:`, as `jit_for` and `jit_init` do. A
52
+ call without the keyword follows `CArray::JIT.fastmath`, as before.
53
+
54
+ - New: `jit_stencil` computes an array that is narrower than the window
55
+ under `border: :zero`, `:clamp` and `:wrap`; it was refused. Under
56
+ `:mask` and `:skip` such an array is still refused, because no cell of
57
+ it would be computed.
58
+
59
+ - Change: `reassociate` is now `fastmath`. Write `fastmath:` for the
60
+ keyword `reassociate:` of `jit_for` and `jit_init`,
61
+ `CArray::JIT.fastmath` for `CArray::JIT.reassociate`, and
62
+ `CARRAY_JIT_FASTMATH` for the environment variable
63
+ `CARRAY_JIT_REASSOCIATE`. The old keyword and the old method raise,
64
+ and the old variable is not read. The default is still true.
65
+
66
+ - Change: a C function called from Ruby with `call`, or through
67
+ `jit_call`, refuses an argument it cannot take. A pointer parameter
68
+ takes a CArray, `nil` for a null pointer, or an address object;
69
+ anything else raises `TypeError`, and so does `nil` for a pointer the
70
+ body indexes without asking whether one came. An Integer outside the
71
+ range of its parameter raises `RangeError`; it was wrapped. A number
72
+ or `nil` for such a pointer used to stop the process.
73
+
74
+ - Change: kernels and C functions are compiled with `-march=native`
75
+ where CArray itself was built with it, so they may use every
76
+ instruction of the machine they run on. Set `CARRAY_MARCH_NATIVE=0`
77
+ before the gem is loaded to compile without it.
78
+
79
+ - Change: kernels are compiled with `-fno-math-errno`, as CArray is.
80
+ With gcc a loop that calls `Math.sqrt` is now vectorised. The answers
81
+ are the same.
82
+
83
+ - Change: a `jit_` method called in a Ractor other than the main one
84
+ raises `CArray::JIT::Unsupported`, saying that kernels are compiled
85
+ and called in the main Ractor only. It raised
86
+ `Ractor::IsolationError`.
87
+
88
+ - Change: `CArray#dim`, which CArray marks as deprecated, is no longer
89
+ called. No answer changes.
90
+
91
+ ## 0.1.8
92
+
93
+ - Change: a local array in a block is made under the width names,
94
+ `CArray.float64(n)`, `CArray.int32(n)` and the rest. The C type names
95
+ (`CArray.double`, `CArray.float`, `CArray.int`, `CArray.complex` and
96
+ their kin) raise `Unsupported`, naming the width name to write instead.
97
+ Note that `CArray.float` is a float32 and `CArray.complex` a cmplx64.
98
+
99
+ - Change: needs CArray 3.1.0 or later in the 3.1 series, where 0.1.7
100
+ needed the 3.0 series.
101
+
102
+ - Change: a Complex scalar beside a float32 array gives a cmplx64, as
103
+ CArray from 3.0.9 does; it was a cmplx128.
104
+
105
+ - Fix: the `carray-jit` cache command, run with a CArray checkout on the
106
+ load path through `-I`, names that checkout's version and looks after
107
+ its kernels. It took the version of the installed CArray gem instead.
108
+
109
+ ## 0.1.7
110
+
111
+ - Change: needs CArray 3.0.6 or later in the 3.0 series; install it
112
+ alongside this release. An element-wise pass is handed to
113
+ `CArray::AddressBasis.sweep`, which 3.0.6 is the first to have.
114
+
115
+ - Change: the kernel cache keeps 2000 kernels per environment by
116
+ default, up from 512, which is about 60 MB on disk. A program that
117
+ compiled more than 512 rebuilt the ones evicted each time it ran. Set
118
+ `CARRAY_JIT_CACHE_LIMIT` for a different bound.
119
+
120
+ - Change: `jit_for` and `jit_init` cost less per call when called again
121
+ with operands that agree in name, type and mask, and a kernel writing
122
+ an `int64` array is vectorised as a `float64` one is.
123
+
124
+ - Fix: a lazy expression or `CArray.fuse` computed here keeps the sign of
125
+ a NaN as CArray does: `(a * -1).signbit` and a NaN fill of `shift`
126
+ gave other bits with the evaluator registered.
127
+
128
+ - Fix: kernels built at once by several threads, or in Ractors, no
129
+ longer raise `Errno::ENOENT`.
130
+
40
131
  ## 0.1.6
41
132
 
42
133
  - Change: needs CArray 3.0.5 or later in the 3.0 series; install it
data/README.md CHANGED
@@ -6,10 +6,6 @@ This library was written to make explicit, cell-by-cell work on CArray arrays fa
6
6
 
7
7
  The block is read with Prism, translated to C if it falls inside that subset, compiled with the system C compiler and called through Fiddle. The compiled object is cached on disk, so a kernel is compiled once.
8
8
 
9
- ## Status
10
-
11
- 0.1.6 is the current release, and it still moves: behaviour can change between releases.
12
-
13
9
  ## Features
14
10
 
15
11
  - **A JIT compiler for C-level loops.** A block becomes one C function over CArray's own memory, built by the system C compiler and called through Fiddle.
@@ -35,9 +31,9 @@ gem "carray-jit"
35
31
  Requires:
36
32
 
37
33
  - Ruby >= 3.2
38
- - CArray >= 3.0.5, < 3.1
34
+ - CArray >= 3.1.0, < 3.2
39
35
  - A C compiler
40
- - Prism and Fiddle (both ship with Ruby; Fiddle is a bundled gem)
36
+ - Prism and Fiddle, which RubyGems installs with this gem where Ruby does not ship them (Prism on Ruby 3.2)
41
37
 
42
38
  ## Example
43
39
 
@@ -47,7 +43,7 @@ Requires:
47
43
  # loop has just written.
48
44
 
49
45
  x = 0.5
50
- legendre = CArray.double(24)
46
+ legendre = CArray.float64(24)
51
47
  legendre[0] = 1.0 # P_0(x) = 1
52
48
  legendre[1] = x # P_1(x) = x
53
49
 
data/carray-jit.gemspec CHANGED
@@ -32,8 +32,16 @@ Gem::Specification.new do |spec|
32
32
  spec.bindir = "bin"
33
33
  spec.executables = ["carray-jit"]
34
34
 
35
- # A kernel reaches CArray's C by address, so the ceiling is the next minor.
36
- spec.add_dependency "carray", ">= 3.0.5", "< 3.1"
35
+ # The floor is the first CArray whose surface this release uses. The
36
+ # ceiling is the next minor: this gem reaches into CArray below its public
37
+ # methods (the expression tree, the address basis, the generator's source),
38
+ # and those may change with a minor version of CArray.
39
+ spec.add_dependency "carray", ">= 3.1.0", "< 3.2"
40
+ # The block reader requires prism. Ruby ships it from 3.3; on Ruby 3.2 it
41
+ # is a gem to install. CArray depends on it too, with the same floor.
42
+ spec.add_dependency "prism", ">= 1.0"
37
43
  # fiddle ships as a bundled gem; depend on it explicitly so Ruby 3.5+ resolves it.
38
- spec.add_dependency "fiddle"
44
+ # 1.1.1, which Ruby 3.2 ships, is the first with TYPE_UCHAR and the other
45
+ # unsigned types.
46
+ spec.add_dependency "fiddle", ">= 1.1.1"
39
47
  end
@@ -2,7 +2,7 @@
2
2
 
3
3
  The block's parameters are the loop indices. Arrays and scalars are the variables it closes over -- `legendre` and `x` here -- so nothing is named twice, and the body reads like the Ruby loop it replaces.
4
4
 
5
- An extent is a `Range`, an `Integer` standing for `0...n`, or an `Enumerator::ArithmeticSequence` -- what `(high - 1).step(low, -1)` returns -- one per index. A whole array is therefore `CArray.jit_for(*array.dim) { ... }`.
5
+ An extent is a `Range`, an `Integer` standing for `0...n`, or an `Enumerator::ArithmeticSequence` -- what `(high - 1).step(low, -1)` returns -- one per index. A whole array is therefore `CArray.jit_for(*array.shape) { ... }`.
6
6
 
7
7
  ```ruby
8
8
  CArray.jit_for(1...(rows-1), 1...(columns-1)) { |i, j|
@@ -17,7 +17,7 @@ The assignment is Ruby's own. Every name in the block is a cell -- the loop is t
17
17
  `CScalar` is the one-cell `CArray` it subclasses, minus the index: `s[]` is the value, and `s[] = ...` puts one back. CArray's own operators read that one cell for every cell of everything else, and so does this:
18
18
 
19
19
  ```ruby
20
- gain = CScalar.double() { 2.0 }
20
+ gain = CScalar.float64() { 2.0 }
21
21
  CArray.jit_each { out = signal * gain } # gain read at every cell
22
22
  CArray.jit_each { gain = gain + 0.5 } # and written like any cell
23
23
  ```
@@ -28,7 +28,7 @@ An indexed kernel reaches it too, and there the missing index is the whole point
28
28
  CArray.jit_for(n) { |i| out[i] = signal[i] * gain[] }
29
29
  ```
30
30
 
31
- `CScalar.int()` with no block is that one cell zero-filled, as `CArray.int(1)` is, which is enough for an accumulator that starts at zero; the block form says the starting value out loud, and is what to write where the value is part of what the code means.
31
+ `CScalar.int32()` with no block is that one cell zero-filled, as `CArray.int32(1)` is, which is enough for an accumulator that starts at zero; the block form says the starting value out loud, and is what to write where the value is part of what the code means.
32
32
 
33
33
  The two routes differ in how they get there. `jit_each` stretches it as it stretches a one-cell `CArray` -- a stride of zero -- while `jit_for` reads it where it lies. They compute the same thing, and `s[0]` keeps working in both, since it is still the one-cell array it is. Writing a wider expression into one is refused, with the shapes named, exactly as CArray refuses it.
34
34
 
@@ -46,7 +46,7 @@ It is the same shape of block `CArray.jit_function` takes, and not the same thin
46
46
 
47
47
  #### Who drives the loop
48
48
 
49
- An element-wise pass is the one shape that is a *sweep* -- nothing reaches a neighbour, nothing chooses an order -- so CArray can drive it instead. Where this CArray has `ca_call_cslab` (3.0.1 and later), `jit_each` hands it the compiled body and lets it acquire the operands.
49
+ An element-wise pass is the one shape that is a *sweep* -- nothing reaches a neighbour, nothing chooses an order -- so CArray can drive it instead: `jit_each` hands its chunked sweep (`ca_call_cslab`) the compiled body and lets it acquire the operands.
50
50
 
51
51
  The body is the same either way. The sweep entry point is a wrapper that calls the same kernel with the chunk as its bounds, so what changes is who opens the arrays, not what they compute.
52
52
 
@@ -56,7 +56,7 @@ A **strided view** is the case where there is. A column, a transpose, every othe
56
56
 
57
57
  The rank does not stand in the way, and the arrays are not reshaped to get it out of the way. CArray's acquire reads an operand's element count and element size and never looks at its shape, so a chunk is already a flat run of cells; what has to be flat is the *kernel*, and it is compiled at rank one over the same cells rather than as a nest over the axes. One such kernel then serves whatever rank it is given, because the rank has left the loop.
58
58
 
59
- Four things keep the driver here. An operand that is a **strided view**, for the reason just measured: it is walked in place here, and re-gathered there for nothing. A **stretched operand**, which is the one thing that cannot be flattened: broadcasting arrives as a stride of zero on an axis, and a flat run has no axes, so cell k of the output would stop lining up with cell k of the operand. A body that **asks about a mask**, because a chunk carries no per-cell mask to ask it of -- CArray ORs and propagates the masks, but `a[i] == UNDEF` is a question about one cell. A CArray **without the family** at all, which is asked for by symbol rather than assumed, so an older one falls back without the caller hearing about it.
59
+ Four things keep the driver here. An operand that is a **strided view**, for the reason just measured: it is walked in place here, and re-gathered there for nothing. A **stretched operand**, which is the one thing that cannot be flattened: broadcasting arrives as a stride of zero on an axis, and a flat run has no axes, so cell k of the output would stop lining up with cell k of the operand. A body that **asks about a mask**, because a chunk carries no per-cell mask to ask it of -- CArray ORs and propagates the masks, but `a[i] == UNDEF` is a question about one cell. And **more than seven operands**, because seven is the widest the sweep family is generated for.
60
60
 
61
61
  Whichever drives it, an operand that is **read while the pass writes the array it is a view of** is copied once before the loop. `a = b * 2.0` reads the whole right-hand side and then assigns; a kernel walks cell by cell, which is the same thing until a cell it reads is one it has written -- `hi = lo * 2.0` over two blocks that share six cells, a transpose written over itself. The copy is what makes those read the values the expression started with, as CArray's own operators do, and it is what lets the chunked sweep take them: what it re-gathers per chunk is then a copy nothing is writing to. Sharing a root is the test rather than overlapping cells, a view knowing what it is a view of; `a = a + 1.0` is not that case, the cell read being the cell written.
62
62
 
@@ -179,8 +179,8 @@ The offsets are written out — a literal, or arithmetic over literals — becau
179
179
  Written with the indices named, the same thing is [`jit_for`](#extents-steps-and-subscripts)'s:
180
180
 
181
181
  ```ruby
182
- rows, columns = image.dim
183
- smoothed = CArray.double(rows, columns)
182
+ rows, columns = image.shape
183
+ smoothed = CArray.float64(rows, columns)
184
184
  CArray.jit_for(1...(rows-1), 1...(columns-1)) { |i, j|
185
185
  smoothed[i, j] = 0.25 * (image[i-1, j] + image[i+1, j] +
186
186
  image[i, j-1] + image[i, j+1])
@@ -205,6 +205,8 @@ The default is `:mask` because CArray can say "not computed", and that is what t
205
205
 
206
206
  The other three are answers about the read rather than about the cell, so the border cells are computed after all — `:wrap` is what makes a Game of Life board a torus, and `:clamp` what an image filter usually wants at the edge.
207
207
 
208
+ An array narrower than the window along some axis has no cell whose whole window is inside it. Under `:zero`, `:clamp` and `:wrap` every cell of such an array is computed by the rule: a 3x3 window over a 2x2 array under `:wrap` reads each neighbour from the other side, however many times that goes round. Under `:mask` and `:skip` no cell would be computed, and the array is refused.
209
+
208
210
  ### What it costs
209
211
 
210
212
  Two loops, not one with a question in it. The interior is the loop the written-out spelling compiles to, with nothing about the border in it; the frame is walked afterwards, by the same statements with the rule woven into their reads. Over a 2000x2000 five-point stencil:
@@ -263,7 +265,7 @@ CArray.jit_for(rows) { |i|
263
265
  }
264
266
  ```
265
267
 
266
- The accumulator is split into partial sums, which is faster than the serial chain and usually the more accurate answer, and is not the order the same loop would take in Ruby. `reassociate: false` asks for that order; see "The order a reduction takes its terms in" below.
268
+ The accumulator is split into partial sums, which is faster than the serial chain and usually the more accurate answer, and is not the order the same loop would take in Ruby. `fastmath: false` asks for that order; see "The order a reduction takes its terms in" below.
267
269
 
268
270
  What makes it expressible is `(from...to).each { |j| ... }` -- or `n.times { |j| ... }`, which is the same loop from zero. The accumulator is then an ordinary block-local, which is why sum, maximum, product, count and a dot product all fall out without a primitive each -- and why a matrix multiply does too:
269
271
 
@@ -313,13 +315,13 @@ A constant subscript pins an axis: `a[i, 0]` and `a[i, j]` on the same array is
313
315
  ```
314
316
  row sums over 2000 x 500
315
317
  jit_for 0.3 ms 0.25 ns/cell
316
- jit_for, reassociate: false 0.9 ms 0.92 ns/cell 3.61x
318
+ jit_for, fastmath: false 0.9 ms 0.92 ns/cell 3.61x
317
319
  Ruby loop 50.7 ms 50.75 ns/cell 200x
318
320
  sum(axis: 1) 0.1 ms 0.10 ns/cell 0.40x
319
321
 
320
322
  matrix multiply 300 x 300 x 300
321
323
  jit_for 6.5 ms 0.24 ns per multiply-add 8.37 GFLOP/s
322
- jit_for, reassociate: false 15.3 ms 0.57 ns per multiply-add 3.53 GFLOP/s
324
+ jit_for, fastmath: false 15.3 ms 0.57 ns per multiply-add 3.53 GFLOP/s
323
325
  ```
324
326
 
325
327
  #### The order a reduction takes its terms in
@@ -330,24 +332,38 @@ A kernel splits the accumulator by default, into eight chains combined pairwise
330
332
 
331
333
  ```
332
334
  Ruby's serial sum 204800000000.0 4247d78400000000
333
- jit_for, reassociate: false 204800000000.0 4247d78400000000
335
+ jit_for, fastmath: false 204800000000.0 4247d78400000000
334
336
  jit_for 204800000000.0042 4247d7840000008a
335
337
  sum(axis: 1) 204800000000.0074 4247d784000000f2
336
338
  ```
337
339
 
338
- That is not a trade of accuracy for speed. Splitting the accumulation is what limits the cancellation, so the partial sums are usually the *more* accurate answer -- on this row, which cancels, the licensed kernel is nearer the true sum than the serial one is. What it is not is the order Ruby's loop would have taken, and that is what `reassociate: false` asks for:
340
+ That is not a trade of accuracy for speed. Splitting the accumulation is what limits the cancellation, so the partial sums are usually the *more* accurate answer -- on this row, which cancels, the licensed kernel is nearer the true sum than the serial one is. What it is not is the order Ruby's loop would have taken, and that is what `fastmath: false` asks for:
339
341
 
340
342
  ```ruby
341
- CArray.jit_for(rows, reassociate: false) { |i|
343
+ CArray.jit_for(rows, fastmath: false) { |i|
342
344
  accumulator = 0.0
343
345
  (0...columns).each { |j| accumulator = accumulator + source[i, j] }
344
346
  total[i] = accumulator
345
347
  }
346
348
  ```
347
349
 
348
- Two reasons to ask for it. A **compensated summation** -- Kahan's, or any error-free transformation -- *is* its order: reassociating it does not make it less accurate, it deletes the algorithm. And **checking a kernel against the loop it replaces** needs the two to be comparable to the last bit, which is how this gem's own tests are written; `CARRAY_JIT_REASSOCIATE=0` sets it for a whole process.
350
+ Two reasons to ask for it. A **compensated summation** -- Kahan's, or any error-free transformation -- *is* its order: reassociating it does not make it less accurate, it deletes the algorithm. And **checking a kernel against the loop it replaces** needs the two to be comparable to the last bit, which is how this gem's own tests are written; `CARRAY_JIT_FASTMATH=0` sets it for a whole process.
351
+
352
+ What is licensed in a reduction is the order the *iterations* are grouped in, and nothing else. Each term is computed in the operand order it was written in, and everything outside a reduction keeps its order: a recurrence is serial by definition, and a stencil's cells are independent, so neither has an order to give up.
353
+
354
+ #### The math functions under `fastmath`
355
+
356
+ `fastmath` allows one more thing, in every kernel and not only in a reduction. A math function -- `Math.exp`, `Math.log`, `Math.sin`, `**` with real operands, and the others the C library covers -- is computed by its vector form where the library has one. That is glibc on x86_64 Linux. On other platforms, macOS among them, there is no such form and the kernel calls the scalar function, with `fastmath` or without it.
357
+
358
+ A loop that calls a math function is then vectorised like any other loop. Measured on one x86_64 machine (gcc 13.3, glibc 2.39, AVX2) over a million cells, a kernel of one call ran 3.4 times as fast for `exp`, 4.5 times for `sin`, 2.5 times for `log` and 2.2 times for `x ** 1.5`.
359
+
360
+ The answer is not the scalar function's answer. A vector form is correct to within a few units in the last place; the largest difference measured was 4, on `cos`. The cells at the end of a loop that do not fill a vector are computed by the scalar function, so the same input can give two different last bits depending on where in the array it sits. NaN, infinity, the sign and zero come out as the scalar function gives them.
361
+
362
+ `fastmath: false` on a call asks for the scalar functions in the kernel of that call. `jit_for`, `jit_init`, `jit_each`, `jit_map`, `jit_stencil` and `jit_contract` all take the keyword. A call without the keyword follows `CArray::JIT.fastmath`, which `CARRAY_JIT_FASTMATH=0` makes false for a whole process.
363
+
364
+ `jit_function` takes the keyword too. It decides the math functions in the loops of the function when the function is called on its own, from Ruby or from a C library, and the answer is taken once, when the function is compiled. A kernel that calls the function compiles the body into itself, and there the kernel's `fastmath` decides.
349
365
 
350
- What is licensed is the order the *iterations* are grouped in, and nothing else. Each term is computed exactly as it was written, in the operand order it was written in, and everything outside a reduction is untouched: a recurrence is serial by definition, and a stencil's cells are independent, so neither has an order to give up.
366
+ `fastmath` is these two things and no others. It does not assume that NaN and infinity are absent, and it does not fuse a multiply and an add into one rounding.
351
367
 
352
368
  The licence is part of the kernel rather than of the call -- it decides what C is emitted -- so the two spellings compile to two kernels and the cache keeps them apart. `#c_source` shows which one ran; the chains are named `<accumulator>__p0` and up.
353
369
 
@@ -385,7 +401,7 @@ A row of a captured array is one place to put it, and the body makes one itself
385
401
 
386
402
  ```ruby
387
403
  median = CArray.jit_stencil(image, border: :clamp) { |a|
388
- w = CArray.double(9) # nine doubles on this cell's stack
404
+ w = CArray.float64(9) # nine doubles on this cell's stack
389
405
  w[0] = a[-1,-1]; w[1] = a[-1, 0]; w[2] = a[-1, 1]
390
406
  w[3] = a[ 0,-1]; w[4] = a[ 0, 0]; w[5] = a[ 0, 1]
391
407
  w[6] = a[ 1,-1]; w[7] = a[ 1, 0]; w[8] = a[ 1, 1]
@@ -396,7 +412,7 @@ median = CArray.jit_stencil(image, border: :clamp) { |a|
396
412
 
397
413
  `sort(w)` is one of the functions the compiler brings with it (see [Intrinsics](03_SupportedFeatures.md#intrinsics)); at nine cells it is a comparator network with no branch in it. Written against a row of captured workspace instead, the same filter needs `work[rows, cols, 9]` -- 288 MB over a 2000x2000 image to hold 72 bytes at a time -- and `jit_stencil` cannot use one at all, its block having no index.
398
414
 
399
- **What the clearing costs.** `CArray.double(9)` starts its cells at zero every time the line runs, which for a body that writes all nine before reading any is work nobody asked for. Measured over the filter above on 2000x2000: **41.3 ns a cell, against `CArray.empty(:float64, [9])`'s 42.2** -- no difference, because the compiler sees the nine stores that follow and drops the clearing as dead. So the zeroed spelling is the one to write here, and it is the one that reads correctly.
415
+ **What the clearing costs.** `CArray.float64(9)` starts its cells at zero every time the line runs, which for a body that writes all nine before reading any is work nobody asked for. Measured over the filter above on 2000x2000: **41.3 ns a cell, against `CArray.empty(:float64, [9])`'s 42.2** -- no difference, because the compiler sees the nine stores that follow and drops the clearing as dead. So the zeroed spelling is the one to write here, and it is the one that reads correctly.
400
416
 
401
417
  Where the clearing is *not* dead it costs about what clearing that many bytes costs, and nothing else. Over 1000x1000, with a histogram built per cell and a body that reads back a cell it did not write:
402
418
 
@@ -534,4 +550,4 @@ There is no BLAS for an arbitrary contraction, which is rather the point: this c
534
550
 
535
551
  Its sum is split into partial ones, as `jit_for`'s reduction is and as CArray's own reduce kernels are. A contraction is a sum with no loop written anywhere for its order to agree with -- the notation says which indices are summed and nothing about in what order -- so there is nothing being overridden, which is a weaker claim than the one `jit_for` makes over a loop somebody wrote. It is also the whole of the difference between a contraction and that loop: a 400 x 400 x 400 product took 47 ms serial against `jit_for`'s 16, and takes 16 split (`benchmark/contraction.rb`).
536
552
 
537
- `CArray::JIT.reassociate = false`, and `CARRAY_JIT_REASSOCIATE=0` for a whole process, ask for the serial order here as they do everywhere -- which is the order a Ruby loop takes, and what to use to compare one against the other. Unlike `jit_for`, `jit_contract` has no per-call licence: a contraction names no loop, so there is no loop at the call site to license.
553
+ `CArray::JIT.fastmath = false`, and `CARRAY_JIT_FASTMATH=0` for a whole process, ask for the serial order here as they do everywhere -- which is the order a Ruby loop takes, and what to use to compare one against the other. `jit_contract(fastmath: false) { ... }` asks for it in one call.
@@ -126,17 +126,17 @@ Three spellings are taken, and they are CArray's own:
126
126
 
127
127
  The types are the ones CArray has, minus the two a kernel computes with neither of: `int8` `int16` `int32` `int64`, `uint8` `uint16` `uint32` `uint64`, `float32` `float64`, `cmplx64` `cmplx128`, `boolean`. `object` and `fixlen` are refused.
128
128
 
129
- The aliases are CArray's too, and two of them are worth reading twice: **`CArray.float` is a float32** and **`CArray.complex` is a cmplx64** -- single precision, the opposite of what Ruby's own `Float` and `Complex` would suggest. `CArray.double` is float64 and `CArray.dcomplex` is cmplx128. `byte`, `short` and `int` are uint8, int16 and int32.
129
+ The C type names -- `float`, `double`, `complex`, `dcomplex`, `byte`, `short` and `int` -- are refused, in `CArray.double(n)` and in `CArray.new(:double, [n])` alike: a block is written in the width names, and the message names the one to write. Two of them are worth reading twice: `float` is a float32 and `complex` is a cmplx64, the opposite of what Ruby's own `Float` and `Complex` would suggest.
130
130
 
131
- `CArray.empty(data_type, dim)` is carray 3.0.2's spelling. A block is read rather than run, so a kernel takes it whatever version of CArray is loaded -- but calling it outside a kernel needs 3.0.2.
131
+ `CArray.empty(data_type, shape)` is carray 3.0.2's spelling. A block is read rather than run, so a kernel takes it whatever version of CArray is loaded -- but calling it outside a kernel needs 3.0.2.
132
132
 
133
- The shape is **written out**: an integer, or integers joined by `+`, `-` and `*`, so `CArray.double(2 * 4 + 1)` is a nine-cell array. A length worked out from the integers the block captured is computed when the kernel starts, and that array is allocated on the heap (see below). A length from an index, a local or a cell is refused -- there would be no C array to declare and no bound to check against -- and so is a length of zero or less.
133
+ The shape is **written out**: an integer, or integers joined by `+`, `-` and `*`, so `CArray.float64(2 * 4 + 1)` is a nine-cell array. A length worked out from the integers the block captured is computed when the kernel starts, and that array is allocated on the heap (see below). A length from an index, a local or a cell is refused -- there would be no C array to declare and no bound to check against -- and so is a length of zero or less.
134
134
 
135
135
  **More than one axis** is written the way CArray writes it, and each axis is checked against its own extent:
136
136
 
137
137
  ```ruby
138
138
  CArray.jit_for(ny, nx) { |i, j|
139
- m = CArray.double(3, 4) # double m[12]; packed row-major
139
+ m = CArray.float64(3, 4) # double m[12]; packed row-major
140
140
  3.times { |r| 4.times { |c| m[r, c] = coef[i, j, r, c] } }
141
141
  ...
142
142
  }
@@ -147,7 +147,7 @@ The shape is literal, so the strides are constants the compiler can see: `m[r, c
147
147
  Per-axis checking is the thing this buys, and the reason to write `m[r, c]` rather than flattening by hand. Write `m[r * 4 + c]` yourself and a `c` of 4 is a cell of the next row -- a real read, of the wrong number, saying nothing. Write `m[r, c]` and the column is held to four:
148
148
 
149
149
  ```ruby
150
- m = CArray.double(3, 4)
150
+ m = CArray.float64(3, 4)
151
151
  3.times { |r| 5.times { |c| m[r, c] = 1.0 } }
152
152
  #=> the subscript `c` on axis 1 of `m`, which is 3 x 4, reaches cell 4 of that
153
153
  # axis's 4 cells, whose cells are 0 to 3: `c` runs 0 to 4 here.
@@ -155,16 +155,16 @@ m = CArray.double(3, 4)
155
155
 
156
156
  A column the kernel works out is checked where it is reached, per axis as well, so a write past one axis raises rather than landing in the next row.
157
157
 
158
- The size counts cells rather than axes: `CArray.double(32, 32)` is 8 KiB, past what a frame holds, so it is allocated at the kernel's entry instead (see "Larger, and lengths the kernel works out").
158
+ The size counts cells rather than axes: `CArray.float64(32, 32)` is 8 KiB, past what a frame holds, so it is allocated at the kernel's entry instead (see "Larger, and lengths the kernel works out").
159
159
 
160
160
  To a C function a local array goes as what it is -- one flat run of cells, row after row -- so a `double[3][4]` is handed to `const double a[12]`, and the length is matched over every cell.
161
161
 
162
- The compatibility layer is not taken. `CArray.zeros(4)`, `CArray.ones(4)`, `CArray.full(4, 1.0)`, `CArray.empty(4)` and the Numo spellings `CArray::Int64.zeros(4)` / `CArray::Int64.empty(4)` are all refused, each naming the carray spelling it stands for. `data_type_extension.rb` opens by calling itself "Numo / NumPy-style" and "not the 'main' carray API"; the words inside a block are carray's own.
162
+ The compatibility layer is not taken. `CArray.zeros(4)`, `CArray.ones(4)`, `CArray.full(4, 1.0)`, and `CArray.empty(4)` are all refused, each naming the carray spelling it stands for. `factories.rb` opens by calling itself "Numo / NumPy-style" and "not the 'main' carray API"; the words inside a block are carray's own.
163
163
 
164
164
  **A subscript is checked, and where depends on what it is made of.** Where the position is an inner loop's index at a literal offset and that loop states its range in literals, the reach is known as the block is read, and the C carries no test:
165
165
 
166
166
  ```ruby
167
- t = CArray.double(4)
167
+ t = CArray.float64(4)
168
168
  (0...4).each { |k| t[k + 1] = 0.0 }
169
169
  #=> `t[k + 1]` reaches cell 4 of a local array of 4 cells, where the cells are
170
170
  # 0 to 3: `k` runs 0 to 3 here.
@@ -178,7 +178,7 @@ Every other position -- a plain local, a value read out of an array, an index wh
178
178
  out = CArray.int64(1)
179
179
 
180
180
  CArray.jit_for(1) { |i|
181
- w = CArray.double(4)
181
+ w = CArray.float64(4)
182
182
  j = 0
183
183
  while w[j] == 0.0 # reads off the end on the fifth pass
184
184
  j += 1
@@ -191,7 +191,7 @@ CArray.jit_for(1) { |i|
191
191
  **A local array is a workspace and not a value.** It has no methods and is not read bare:
192
192
 
193
193
  ```ruby
194
- w = CArray.double(4)
194
+ w = CArray.float64(4)
195
195
  x = w #=> `w` is a local array; index it, as in `w[0]`
196
196
  x = w.sum #=> `sum` is a method CArray answers outside a kernel
197
197
  ```
@@ -215,8 +215,8 @@ Two kinds of local array do not stand in the frame: one whose cells come to more
215
215
  ```ruby
216
216
  # n is an Integer the block closed over; 4096 doubles is 32 KiB
217
217
  CArray.jit_for(rows) { |i|
218
- w = CArray.double(n) # allocated at the entry, freed at the exit
219
- big = CArray.double(4096) # the same, for its size alone
218
+ w = CArray.float64(n) # allocated at the entry, freed at the exit
219
+ big = CArray.float64(4096) # the same, for its size alone
220
220
  ...
221
221
  }
222
222
  ```
@@ -240,12 +240,12 @@ A `jit_function` body allocates nothing. It is called once per cell, so an alloc
240
240
  A kernel that carries masks gives every local array a **shadow** of one byte a cell, declared beside the cells, and a cell of the array carries a mask the way a plain local carries one beside its value: what the expression written into it carried, and the masks of the branches the write stands in. So a window copied into a workspace keeps its holes, and reading a cell back is reading what it was made of.
241
241
 
242
242
  ```ruby
243
- field = CArray.double(8).seq!(1.0)
243
+ field = CArray.float64(8).seq!(1.0)
244
244
  field[2] = UNDEF
245
- out = CArray.double(8)
245
+ out = CArray.float64(8)
246
246
 
247
247
  CArray.jit_for(1...7) { |i|
248
- w = CArray.double(3)
248
+ w = CArray.float64(3)
249
249
  w[0] = field[i-1]; w[1] = field[i]; w[2] = field[i+1]
250
250
  out[i] = w[0] + w[1] + w[2]
251
251
  }
@@ -290,7 +290,7 @@ The name does not collide with anything the block writes. `sum = 0.0` beside `su
290
290
  **`min` and `max`** answer what CArray's own `min` and `max` answer. A NaN never displaces the accumulator, so it is skipped wherever it stands -- first, middle or last:
291
291
 
292
292
  ```ruby
293
- CArray.double(3) { [Float::NAN, 1.0, 2.0] }.min #=> 1.0
293
+ CArray.float64(3) { [Float::NAN, 1.0, 2.0] }.min #=> 1.0
294
294
  ```
295
295
 
296
296
  and an array of nothing but NaN comes back `NaN`, there being no number left to win, which is again CArray's answer. Of two cells that compare equal the first is kept, so `0.0` and `-0.0` come back in whichever order they stood, as they do from CArray -- which is why the fold is a comparison rather than C99 `fmin` / `fmax`, whose NaN rule is the same but which leave the choice between two zeros to the library. Over an integer array, which has no NaN, it is a comparison against the limit of the type. `sort` does not skip a NaN, for the reason the fold does: skipping drops a cell -- right for a fold, wrong for a sort. A Complex array is refused, Ruby not ordering Complex numbers either, and so is a boolean one.
@@ -538,9 +538,9 @@ A masked cell means "no value here". A plain CArray has no mask at all -- one co
538
538
  When some array does carry one, the mask propagates the way CArray's own operators propagate it: any cell that fed a result masks that result, and an array that is written gets a mask if it did not have one.
539
539
 
540
540
  ```ruby
541
- source = CArray.double(7).seq!(1.0)
541
+ source = CArray.float64(7).seq!(1.0)
542
542
  source[2] = UNDEF
543
- result = CArray.double(7)
543
+ result = CArray.float64(7)
544
544
 
545
545
  CArray.jit_for(1...6) { |i| result[i] = source[i-1] + source[i+1] }
546
546
  #=> result[1] and result[3] are UNDEF; they are the cells that read source[2]
@@ -559,7 +559,7 @@ Where a kernel leaves the masking implicit, the reference is CArray's operators
559
559
  **A compare-exchange spreads a mask further than anything else does.** A branch decided by a missing cell masks what it writes, which is the rule everywhere; a swap writes two cells rather than one, and a sort runs compare-exchange over every cell again and again. So one missing cell does not stay one:
560
560
 
561
561
  ```ruby
562
- row = CA_DOUBLE([[5, 1, 4, 2, 3]])
562
+ row = CA_FLOAT64([[5, 1, 4, 2, 3]])
563
563
  row[0, 2] = UNDEF
564
564
 
565
565
  CArray.jit_for(1) { |i| # a bubble sort over the row
@@ -738,7 +738,7 @@ Neville's interpolation is the shape that wants it. It walks a workspace of the
738
738
  NEVILLE = CArray.jit_function(
739
739
  "double neville(double x, const double xs[4], const double ys[4])"
740
740
  ) { |x, xs, ys|
741
- t = CArray.double(4)
741
+ t = CArray.float64(4)
742
742
  4.times { |k| t[k] = ys[k] }
743
743
  (1...4).each { |m|
744
744
  (0...4-m).each { |k|
@@ -777,13 +777,13 @@ DOT4 = CArray.jit_function("double dot4(const double x[4], const double y[4])")
777
777
  }
778
778
 
779
779
  CArray.jit_for(0...(n - 3)) { |i|
780
- w = CArray.double(4)
780
+ w = CArray.float64(4)
781
781
  w[0] = signal[i]; w[1] = signal[i+1]; w[2] = signal[i+2]; w[3] = signal[i+3]
782
782
  smoothed[i] = DOT4.call(w, weights)
783
783
  }
784
784
  ```
785
785
 
786
- **What the declaration says is matched as the block is read**, not at the call. Both halves are written in the block -- the element type is the constructor and the length is a literal -- so `CArray.float32(4)` against `const double x[4]`, or `CArray.double(3)` against it, is refused before anything is compiled. A captured array is matched at the call instead (there is no array to look at until then), and the rules are the same ones: the element type exactly, and at least as many cells as a sized declarator asks for. More cells than it asks for is fine, as it is for a captured array -- the callee reads the four it was promised.
786
+ **What the declaration says is matched as the block is read**, not at the call. Both halves are written in the block -- the element type is the constructor and the length is a literal -- so `CArray.float32(4)` against `const double x[4]`, or `CArray.float64(3)` against it, is refused before anything is compiled. A captured array is matched at the call instead (there is no array to look at until then), and the rules are the same ones: the element type exactly, and at least as many cells as a sized declarator asks for. More cells than it asks for is fine, as it is for a captured array -- the callee reads the four it was promised.
787
787
 
788
788
  The length check is doing real work here rather than tidying up. A subscript on a pointer parameter is unchecked by design, and a local array is on the stack: a declaration that read more cells than the array holds would walk over the frame the return address is in.
789
789
 
@@ -793,8 +793,8 @@ A parameter that is not `const` may be written through, and the line after the c
793
793
  SOLVE3 = CArray.jit_function("void solve3(const double a[12], double x[3])") { |a, x| ... }
794
794
 
795
795
  CArray.jit_for(ny, nx) { |i, j|
796
- rhs = CArray.double(12)
797
- sol = CArray.double(3)
796
+ rhs = CArray.float64(12)
797
+ sol = CArray.float64(3)
798
798
  ...
799
799
  SOLVE3.call(rhs, sol)
800
800
  out[i, j] = sol[0]
@@ -810,8 +810,8 @@ Passing the same local array to two parameters -- `DOT4.call(w, w)` -- is well-f
810
810
  In `jit_each`, `jit_map` and `jit_stencil` the block names no index, so a bare array name is the cell the loop is on and every operand has to line up with every other. An array handed to a C function is not one of those: it goes over whole, so its own length is nobody else's business.
811
811
 
812
812
  ```ruby
813
- weights = CArray.double(4).seq # four coefficients
814
- a = CArray.double(1000).seq # a thousand cells to compute
813
+ weights = CArray.float64(4).seq # four coefficients
814
+ a = CArray.float64(1000).seq # a thousand cells to compute
815
815
 
816
816
  CArray.jit_each { out = a + DOT4.call(weights, weights) }
817
817
  ```
@@ -854,7 +854,7 @@ A window may be opened inside a window, and `#call` may be made inside one: both
854
854
 
855
855
  One flag per compiled object and one per thread, so two functions never share a window and neither do two threads. The second half matters more than it sounds: the object is shared whether or not anybody meant to share it, because two blocks with the same text compile to one function. So a program that never mentions threads can open two windows on one body, and one flag between them is a window neither of them can read -- the second to open puts down what the first had already recorded. The flag and the hook are `_Thread_local`, which costs about half a nanosecond a call, and only on a body that has a flag at all.
856
856
 
857
- The thread is the native one, which for Ruby is the thread that opened the window -- except under the M:N scheduler (a non-main Ractor's threads, or `RUBY_MN_THREADS=1`), where a Ruby thread is not tied to one native thread and the window cannot be relied on to be the same copy throughout.
857
+ The thread is the native one, which for Ruby is the thread that opened the window -- except under the M:N scheduler, where a Ruby thread is not tied to one native thread and the window cannot be relied on to be the same copy throughout. Which threads that is depends on `RUBY_MN_THREADS`: unset or `0`, a non-main Ractor's threads; `1`, the main Ractor's threads other than the main thread as well; and from Ruby 4.1, `2`, the main thread too, so that no thread is outside it. `-1`, also from Ruby 4.1, takes every thread out of it.
858
858
 
859
859
  What this leaves outside the window is a library that calls the body from threads of its own. The flag such a call raises belongs to the thread that raised it: the body stops answering there, as it should, and the window watching from Ruby sees nothing and raises nothing. A library that calls back on the thread it was called from -- which is what GSL and NLopt do -- is inside the window.
860
860
 
@@ -1046,7 +1046,7 @@ A pointer that points at numbers is indexed, and takes a CArray:
1046
1046
  poly = CArray.jit_function("double (*)(double x, const double coef[3])") { |x, c|
1047
1047
  c[0] + c[1] * x + c[2] * x * x
1048
1048
  }
1049
- poly.call(2.0, CArray.double(3) { |i| [1.0, 2.0, 3.0][i] }) # => 17.0
1049
+ poly.call(2.0, CArray.float64(3) { |i| [1.0, 2.0, 3.0][i] }) # => 17.0
1050
1050
  ```
1051
1051
 
1052
1052
  Nothing about the spelling had to be settled: C settled it long ago. `const` says a parameter may only be read, so `dydt[0] = ...` compiles and `coef[0] = ...` is refused; a declarator carries a length where there is one, so `coef[3]` is checked against the array it is given and `coef[]` is the caller's business, as it is in C. The whole ODE signature is therefore sayable, with no half of it invented here:
@@ -1139,7 +1139,7 @@ The other side of that: the address has to arrive with the call rather than with
1139
1139
  ```ruby
1140
1140
  def moving_average (values, window)
1141
1141
  n = values.elements
1142
- out = CArray.double(n)
1142
+ out = CArray.float64(n)
1143
1143
  CArray.jit_call("void (*)(double *out, const double *values, " \
1144
1144
  "size_t n, size_t window)") {
1145
1145
  n.times { |i|
@@ -1211,7 +1211,8 @@ Everything else: `for` and `until`, `begin ... end while`, strings, hashes, symb
1211
1211
  - **Object arrays are not handled.** `CA_OBJECT` holds Ruby values rather than numbers, and reaching into Ruby from inside a kernel would give up what compiling it was for.
1212
1212
  - **`**` on a Complex is the one place the answer is not bit-for-bit Ruby's.** It is within a few machine epsilons, growing with the exponent. What is refused on a Complex is what Ruby refuses -- ordering comparisons, `%`, the rounding methods, the bit operators. See [Complex arrays](#complex-arrays).
1213
1213
  - **A sine and a cosine of the same argument are one `sincos` call.** The C compiler merges them, and its sine differs from `sin` in the last bit for some arguments, where Ruby calls `sin`. Either flag that stops it costs more elsewhere than the bit is worth here, so it is documented rather than disabled; see [Design notes](05_DesignNotes.md#a-sine-beside-a-cosine-is-sincos-and-is-allowed-to-be).
1214
- - **A reduction does not take Ruby's order.** An accumulator is split into partial sums by default, which is usually the more accurate answer and is not the Ruby loop's; `reassociate: false` asks for that order back. `sum(axis:)`, whose kernels are written for the shape, is still faster at the reductions it covers.
1214
+ - **A reduction does not take Ruby's order.** An accumulator is split into partial sums by default, which is usually the more accurate answer and is not the Ruby loop's; `fastmath: false` asks for that order back. `sum(axis:)`, whose kernels are written for the shape, is still faster at the reductions it covers.
1215
+ - **A math function may be computed by its vector form.** On x86_64 Linux with glibc, `Math.exp`, `Math.sin` and the others are computed several cells at a time by default, and the answer can differ from Ruby's in the last few bits; `fastmath: false` on the call, or `CArray::JIT.fastmath = false` for every call that does not say, asks for the scalar functions.
1215
1216
  - **A `while` may fail to return, and nothing can interrupt it.** The loop is in the subset now, and the bound that used to be compulsory is not: a compiler-invented cap would be a number nobody could choose, since the loops whose bound is knowable are already `(0...cap).each` with a `break`. What comes with that is C's bargain, the one a `jit_function` recursing too deep already takes. It bites harder here than it would in Ruby: a generated loop has no interrupt check in it, so `Ctrl-C` does not reach a running kernel -- whether or not it holds the GVL -- and a runaway pass ends with a signal from another terminal. The one case that can be read off the page, `while true` with no `break` and no `raise` in it, is refused.
1216
1217
  - **`until` is not in the subset.** `while` with the condition negated is the same loop, and one spelling of it is enough to keep.
1217
1218
  - **A range written over another index is read at its widest.** `(p+1...3)` gives `k` a different start for every `p`, and a subscript is held to its array with one pair of numbers, so what that pair covers is every pass the loop could take. It is the safe direction -- a subscript this calls inside really is -- but a reach nothing actually makes can still be refused, and where it is, the message says which index the range was written over and that it was read at its widest. Narrowing the range, or the array's use, is what says it is safe.
data/docs/04_Compiling.md CHANGED
@@ -67,7 +67,7 @@ In `~/.cache/carray-jit` (honouring `XDG_CACHE_HOME`), one directory per version
67
67
 
68
68
  A kernel is only good for the version that generated it and the architecture it was built for, so those get their own directories. CArray's version is there for the same reason and one of its own: a kernel is handed CArray's memory, on layouts CArray decides, so one compiled against one version and run against the next would answer wrongly rather than fail to load.
69
69
 
70
- The two numbers say different things and move on their own clocks: the first is the version that generated the kernel, the second the version it was generated against. This gem is not versioned with CArray, and one release of it meets more than one -- the dependency is `>= 3.0.5, < 3.1`, so 3.0.5 and 3.0.6 both satisfy it -- and a layout the kernel reaches into can move between them. A new release does not spend its cache budget on entries nothing can reach any more, and a home directory shared between machines -- over NFS, or between Rosetta and native -- does not have one architecture evicting the other's kernels. A directory whose newest entry has not been touched in 30 days (`CARRAY_JIT_CACHE_MAX_AGE_DAYS`) is removed.
70
+ The two numbers say different things and move on their own clocks: the first is the version that generated the kernel, the second the version it was generated against. This gem is not versioned with CArray, and one release of it meets more than one -- the dependency is `>= 3.1.0, < 3.2`, so every version in the 3.1 series satisfies it -- and a layout the kernel reaches into can move between them. A new release does not spend its cache budget on entries nothing can reach any more, and a home directory shared between machines -- over NFS, or between Rosetta and native -- does not have one architecture evicting the other's kernels. A directory whose newest entry has not been touched in 30 days (`CARRAY_JIT_CACHE_MAX_AGE_DAYS`) is removed.
71
71
 
72
72
  ```ruby
73
73
  CArray::JIT.cache_root #=> "/home/you/.cache/carray-jit"
@@ -99,7 +99,7 @@ The path is expanded where it is given, so a relative one does not move when the
99
99
 
100
100
  `CARRAY_JIT_CACHE` and `CARRAY_JIT_NO_CACHE` still come first, so whoever runs the program has the last word on where a cache may be written and whether there is one at all. `CArray::JIT.cache_root = nil` restores the default.
101
101
 
102
- The cache is **bounded**: past `CARRAY_JIT_CACHE_LIMIT` kernels per environment (512 by default, so about 9 MB) the least recently used are evicted, source and object together. Reuse updates an entry's timestamp, so what a program actually runs stays. This is the one place carray-jit deliberately parts with RubyInline, whose `~/.ruby_inline` has no eviction at all and grows for the life of the account.
102
+ The cache is **bounded**: past `CARRAY_JIT_CACHE_LIMIT` kernels per environment (2000 by default, so about 60 MB) the least recently used are evicted, source and object together. Reuse updates an entry's timestamp, so what a program actually runs stays. This is the one place carray-jit deliberately parts with RubyInline, whose `~/.ruby_inline` has no eviction at all and grows for the life of the account.
103
103
 
104
104
  Removing a cached object never breaks a kernel already in use: unlinking a loaded shared object leaves its mapping intact.
105
105
 
@@ -143,7 +143,7 @@ carray_jit_contiguous (char **pointers, int64_t *strides, int64_t *bounds, ...)
143
143
  const int64_t legendre_s0 = strides[0];
144
144
  const double x = reals[0];
145
145
 
146
- for (int64_t i = bounds[0]; i < bounds[1]; i++) {
146
+ for (int64_t i = bounds[0], i__limit = bounds[1]; i < i__limit; i++) {
147
147
  double w;
148
148
  double wy;
149
149
  w = x * ((double *)(p_legendre))[i - 1];
@@ -165,7 +165,7 @@ root /home/you/.cache/carray-jit
165
165
  environment 0.1.0-carray3.0.1-arm64-darwin24
166
166
  kernels 3
167
167
  size 50.1 KB
168
- limit 512 kernels
168
+ limit 2000 kernels
169
169
 
170
170
  other environments:
171
171
  0.0.9-carray3.0.1-arm64-darwin24 1.2 MB last used 2026-01-01
@@ -217,10 +217,13 @@ carray_jit_contiguous (char **pointers, int64_t *strides, int64_t *bounds, ...)
217
217
  | `CARRAY_JIT_DUMP` | Print generated C to stderr before compiling |
218
218
  | `CARRAY_JIT_CACHE` | Cache directory (default `~/.cache/carray-jit`, or what `CArray::JIT.cache_root=` named), or `none` |
219
219
  | `CARRAY_JIT_NO_CACHE` | Keep the cache in a temporary directory, removed on exit |
220
- | `CARRAY_JIT_CACHE_LIMIT` | Kernels retained on disk, per environment (default 512) |
220
+ | `CARRAY_JIT_CACHE_LIMIT` | Kernels retained on disk, per environment (default 2000) |
221
221
  | `CARRAY_JIT_CACHE_MAX_AGE_DAYS` | Days an unused environment's directory is kept (default 30) |
222
222
  | `CARRAY_JIT_CC` | C compiler (default `RbConfig::CONFIG["CC"]`) |
223
- | `CARRAY_JIT_REASSOCIATE` | `0` makes the serial accumulator the default for the process |
223
+ | `CARRAY_JIT_FASTMATH` | `0` makes `fastmath` false for the process: serial accumulators and scalar math functions |
224
+ | `CARRAY_MARCH_NATIVE` | `0` compiles without `-march=native` |
225
+
226
+ Kernels, C functions and the expression evaluator are compiled with `-march=native` when CArray itself was built with it, which is CArray's default. The flag lets the compiler use the instruction sets of the machine it runs on. A CArray installed with `CARRAY_MARCH_NATIVE=0` or `--disable-march-native` was built without the flag, and carray-jit then compiles without it too. `CARRAY_MARCH_NATIVE` is the variable CArray reads when it is installed. carray-jit compiles when the program runs, and it reads the same variable when the gem is loaded: `CARRAY_MARCH_NATIVE=0` in the environment of a program leaves the flag out of everything carray-jit compiles, also where CArray was built with it.
224
227
 
225
228
  ## A site answered from somewhere else
226
229
 
@@ -254,7 +257,7 @@ rake test
254
257
  rake benchmark
255
258
  ```
256
259
 
257
- Every kernel in the suite is checked against the same computation written as an ordinary Ruby loop -- except the masked ones, which are checked against CArray's operators -- and the float comparisons are exact rather than within a tolerance -- a tolerance would hide the two bugs most worth catching, FMA contraction and computing in the wrong precision. A test whose kernel reduces says `reassociate: false`, which is what makes its answer comparable to a Ruby loop's at all.
260
+ Every kernel in the suite is checked against the same computation written as an ordinary Ruby loop -- except the masked ones, which are checked against CArray's operators -- and the float comparisons are exact rather than within a tolerance -- a tolerance would hide the two bugs most worth catching, FMA contraction and computing in the wrong precision. The suite runs with `CArray::JIT.fastmath = false`, which is what makes a kernel's answer comparable to a Ruby loop's at all; the tests about what `fastmath` does turn it on for themselves.
258
261
 
259
262
  The tridiagonal solver in `test/test_thomas.rb` is the case the design had to be able to express: two sweeps in opposite directions, one of them writing two arrays that share a denominator. It is checked bit for bit against a plain Ruby solver, and by the residual of `A x - d`.
260
263
 
@@ -27,9 +27,7 @@ Narrowing them was tried and dropped, because it would change the answer and buy
27
27
 
28
28
  `uint64` is neither: it is the width that cannot fold into `int64_t` at all, since the values it holds above 2^63 are the ones `int64_t` cannot carry, so it computes in a `uint64_t` of its own. See [Types](03_SupportedFeatures.md#unsigned-64-bit).
29
29
 
30
- **A value with no data type follows Ruby.** A literal and a captured Numeric have no width of their own, so `2.0` is a double and `2` an Integer -- until they meet an array of their own kind, which lends them its width: `f32 * 2.0` is float32. What an array can lend is a width, never a kind, so `i32 * 2.0` is a float64 and `f32 * 1i` a cmplx128. A local that wants a particular type is seeded from a `CScalar`, which is a value with a data type. See [Locals](03_SupportedFeatures.md#locals-types-and-postfix-math).
31
-
32
- `CArray.float` is float32; `CArray.double` is float64.
30
+ **A value with no data type follows Ruby.** A literal and a captured Numeric have no width of their own, so `2.0` is a double and `2` an Integer -- until they meet an array of their own kind, which lends them its width: `f32 * 2.0` is float32. What an array can lend is a width: an integer array has no width of a float to lend, so `i32 * 2.0` is a float64, and a float32 array lends its width to a Complex, so `f32 * 1i` is a cmplx64, as in CArray. A local that wants a particular type is seeded from a `CScalar`, which is a value with a data type. See [Locals](03_SupportedFeatures.md#locals-types-and-postfix-math).
33
31
 
34
32
  ## `-ffp-contract=off` is mandatory
35
33