cumo 0.14.1 → 0.16.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 (47) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +52 -0
  3. data/README.md +68 -1
  4. data/Rakefile +3 -1
  5. data/ext/cumo/cuda/cub.cu +26 -0
  6. data/ext/cumo/cumo.c +0 -2
  7. data/ext/cumo/extconf.rb +1 -2
  8. data/ext/cumo/include/cumo/intern.h +2 -0
  9. data/ext/cumo/include/cumo/narray.h +31 -7
  10. data/ext/cumo/{narray/sort_kernel.cu → include/cumo/sort_kernel.h} +138 -29
  11. data/ext/cumo/include/cumo/template.h +3 -2
  12. data/ext/cumo/include/cumo/template_kernel.h +2 -0
  13. data/ext/cumo/narray/array.c +0 -6
  14. data/ext/cumo/narray/data.c +7 -4
  15. data/ext/cumo/narray/gen/cogen_kernel.rb +21 -10
  16. data/ext/cumo/narray/gen/kernel_parts.rb +5 -3
  17. data/ext/cumo/narray/gen/spec.rb +10 -0
  18. data/ext/cumo/narray/gen/tmpl/accum_arg_kernel.cu +2 -2
  19. data/ext/cumo/narray/gen/tmpl/accum_binary_kernel.cu +1 -1
  20. data/ext/cumo/narray/gen/tmpl/accum_index_kernel.cu +2 -2
  21. data/ext/cumo/narray/gen/tmpl/add_at.c +179 -0
  22. data/ext/cumo/narray/gen/tmpl/add_at_kernel.cu +122 -0
  23. data/ext/cumo/narray/gen/tmpl/allocate.c +1 -0
  24. data/ext/cumo/narray/gen/tmpl/bincount_kernel.cu +117 -2
  25. data/ext/cumo/narray/gen/tmpl/complex_accum_kernel.cu +17 -3
  26. data/ext/cumo/narray/gen/tmpl/cum_kernel.cu +2 -0
  27. data/ext/cumo/narray/gen/tmpl/float_accum_kernel.cu +15 -3
  28. data/ext/cumo/narray/gen/tmpl/real_accum_kernel.cu +19 -1
  29. data/ext/cumo/narray/gen/tmpl/searchsorted.c +89 -0
  30. data/ext/cumo/narray/gen/tmpl/searchsorted_kernel.cu +43 -0
  31. data/ext/cumo/narray/gen/tmpl/sort_kernel.cu +19 -0
  32. data/ext/cumo/narray/gen/tmpl/store_array.c +0 -12
  33. data/ext/cumo/narray/gen/tmpl_bit/allocate.c +1 -0
  34. data/ext/cumo/narray/gen/tmpl_bit/mask.c +10 -6
  35. data/ext/cumo/narray/gen/tmpl_bit/store_array.c +0 -4
  36. data/ext/cumo/narray/gen/tmpl_bit/where.c +36 -10
  37. data/ext/cumo/narray/gen/tmpl_bit/where2.c +8 -9
  38. data/ext/cumo/narray/index.c +227 -123
  39. data/ext/cumo/narray/index_kernel.cu +43 -11
  40. data/ext/cumo/narray/narray.c +16 -16
  41. data/ext/cumo/narray/ndloop.c +4 -0
  42. data/ext/cumo/narray/step.c +54 -187
  43. data/lib/cumo/cuda/elementwise_kernel.rb +13 -5
  44. data/lib/cumo/cuda/user_kernel.rb +11 -6
  45. data/lib/cumo/narray/extra.rb +108 -0
  46. data/lib/cumo/version.rb +1 -1
  47. metadata +10 -4
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: '0872662f2f59cb4486df50f2f9b6dee5fc62fe938f6c47bafdb1ebdfc744c2f6'
4
- data.tar.gz: 248f4ea1224ee0ff46069d16b424b1c90a98d81b33610506c58d45ffb9693c08
3
+ metadata.gz: 6cf3505847ba8f6dd8c1e85537b8822772eadcb2201a04c955c40eb7e7119494
4
+ data.tar.gz: 8e0e112a1f00f2fdedc3dda076facad17d14d2f7d0cc908271eb3a17e8570fe8
5
5
  SHA512:
6
- metadata.gz: caf8d608d673afd9e71d3c421d2c096db503bb0054bf1ca846f33de738ccb2662ab53a6c715e6003f9a27b48d148d1e8f60f509076d53eee1b1bebf56c023e97
7
- data.tar.gz: 78c2fd433b79741516f842b069adfa90c0452694a106554e99fd0ac5415684d6b82beb7f44dae63a09a745fc075bf21c1fb71276fa8ad691965f9ddd335e8d9a
6
+ metadata.gz: 332e60af9f4bd379f3f0575e877d5d32f26b2b655551025355884d32315208b0c03e47fe9f12d7fa72f0b7e429d5d1844964b6fdf5e4d3a4c7a6ba74d5aa6fff
7
+ data.tar.gz: b8b86049ea712bb8890911709711c373e0a7187ce7a6a7fed531f88ed915cc7bb9f94c3c64529d0a5b32e04c32dff93e2913c6268818e88f0a136652ea0a360e
data/CHANGELOG.md CHANGED
@@ -1,3 +1,55 @@
1
+ # 0.16.0 (2026/11/22)
2
+
3
+ Breaking changes:
4
+
5
+ * `ElementwiseKernel` raises `ArgumentError` when a raw output is left out, unless `size:` gives its length, as CuPy does. It allocated one with the shape of the loop, which the kernel could leave partly uninitialized or write past. A call that left out a raw output and wrote only inside the loop has to pass the output now (PR #650)
6
+ * `ElementwiseKernel` no longer broadcasts a raw output against the inputs or lets it decide how many elements the kernel runs over, as in CuPy. A raw output larger than the inputs gets only the elements the kernel writes, a raw output smaller than the loop is no longer refused, so the kernel has to stay inside it, and a call whose arrays are all raw needs `size:` (PR #648)
7
+
8
+ Fixes:
9
+
10
+ * Fix out-of-bounds reads and writes when the `to_int` of a subscript reshapes the array it indexes. With `x` of shape [3, 2] and an `i` that reshapes it to [1, 6], `x[[2, i], true]` read and wrote past the buffer. Indexing now raises `RuntimeError` when the shape changed while the subscripts were read. Indexing an array made by `Class#allocate` no longer crashes (PR #662)
11
+ * Fix out-of-bounds reads and writes when a 0-dimensional array is indexed by an index array. `Cumo::DFloat.cast(7)[Cumo::Int32[0, 0]]` read past the array, and `z[2][[0, 0]] = 1` also wrote to `z[3]`. Every entry now selects the one element, and an entry out of range raises `IndexError` as before (PR #661)
12
+ * Fix `Bit#where`, `Bit#where2` and indexing by a Bit array possibly writing into freed memory when the memory pool ran short, since the retry runs `GC.start` and a finalizer could free a buffer the kernels were about to fill (PR #657)
13
+ * Fix device memory growing without bound in a loop that drops views made by indexing. Such a view owns an index array that the GC was never told about, so reversing a view indexed by 10^7 Int64 values 50 times grew the memory pool by 4 GB without running the GC (PR #653)
14
+ * Fix `ElementwiseKernel` allocating a raw output it was not given with the shape of the loop (PR #650)
15
+ * Fix `ElementwiseKernel` reading a raw input in place while an output overwrites it. A raw input that overlaps any output is now read from a copy (PR #649)
16
+ * Fix `ElementwiseKernel` raising `ArgumentError` for a raw output shaped unlike its inputs, such as a larger array a kernel adds rows into with `atomicAdd`. An input that is not raw and shares memory with a raw output is read from a copy (PR #648)
17
+ * Fix a beginless range such as `a[..3]` or `a[(..3).step(2)]` raising `TypeError` as a subscript. It starts at the first element for a positive step and at the last for a negative one (PR #645)
18
+ * Fix an Enumerator subscript ignoring its step, so `(0..4).enum_for(:step, 2)` selected every element and `(4..0).enum_for(:step, -1)` none. The step of an Enumerator has to be a nonzero Integer, as that of an ArithmeticSequence does, so a step of 0 or 2.0 raises `ArgumentError` (PR #644)
19
+
20
+ Changes:
21
+
22
+ * Add `add_at(*index, values)`, numpy's `add.at`, which adds every value of a place selected more than once. It takes the subscripts of `[]=`, casts the values to the type of the array first, and takes no subscripts on a 0-dimensional array, as numpy does. An Int32 or Int64 index array into an array that is not a view is read where it sits, which for 10^7 indices into 1000 places is about 1.6 to 1.9 times faster than going through a view and runs no GC (PR #663, PR #659)
23
+ * Add `searchsorted`, numpy's `searchsorted`, with its `side:` and `sorter:`, its order with NaN after every number, and its promotion, which unlike Cumo's arithmetic compares UInt32 with Int32 in Int64 and SFloat with Int64 in DFloat. For 5 million sorted doubles and as many values it is about 8.7 times faster than a concatenation and `sort_index` (PR #658)
24
+ * On Ruby 3.3 and later, an array whose buffer is 1 MiB or more is not write-barrier protected, as every array was up to Ruby 3.2. A large temporary is freed by the next minor GC, where it could keep its device memory until a major GC and bring that major GC sooner. Steps that make many large temporaries run up to about 1.5 times faster, and an old container that holds such an array is scanned at every minor GC (PR #660)
25
+ * `Bit#where`, `Bit#where2` and indexing by a Bit array of fewer than 8192 elements compact on the device when the walk is one segment, where they walked the bits on the host. On 1000 elements this is about 22 to 34 times faster (PR #657)
26
+ * `sort` and `median` of float arrays sort the keys alone. Sorting 10^7 SFloat is about 1.6 times faster, 10^7 HFloat about 1.7 times and 10^6 DFloat about 1.6 times, and the median of 10^7 SFloat about 1.45 times. NaNs now come out in the order of their bits rather than their input order, so the median of a row of NaNs can be a NaN with other bits (PR #656)
27
+ * `bincount` with few bins counts in shared memory first. 10^8 items in 10 bins are counted about 4.3 times faster, 7.0 times with float weights and 5.8 times with double weights. Weighted sums are added per block, so their rounding differs from before, as the order of the atomic adds already made it vary (PR #655)
28
+ * An Int32 or Int64 index array is read where it is rather than copied into a new Int64 array. Gathering 10^7 elements by an Int64 index is about 1.66 times faster, 10^5 elements about 1.23 times, and storing through 10^7 indices about 1.17 times (PR #654)
29
+ * `diff` with `n` of 1 subtracts the two slices once on the built-in numeric types, about 2.5 to 3.9 times faster on SFloat and DFloat with the same bits for real and integer types. A complex result no longer gets a NaN part from an infinite operand, and a zero part can take the other sign, as in numpy (PR #652)
30
+ * Building an array from ranges or arithmetic sequences reads each one's end once, which is about 1.3 times faster for 20,000 ranges and about 1.24 times for 20,000 arithmetic sequences. A Range subclass that overrides `exclude_end?` is read in array data and axes as subscripts read it (PR #647)
31
+
32
+ # 0.15.0 (2026/11/02)
33
+
34
+ Breaking changes:
35
+
36
+ * A subscript of an empty array is read as it is for any other array, where every subscript of an empty array raised `Cumo::NArray::ShapeError`. `a[true, 1]` of a 0 x 3 array answers an empty view, and a subscript that names an element raises as it does for any array, so `a[0]` raises `IndexError`. An empty range now selects nothing when it starts where an element could be inserted, as with `Array#[]`, so `b[2...2, true]` of a 2 x 3 array answers a 0 x 3 view where it raised `RangeError`. The README lists where this differs from Numo (PR #641)
37
+ * `Cumo::RObject` no longer has `store_binary`, `to_string`, `hton` or `Cumo::RObject.from_string`, and `set` with a String raises `NoMethodError` for it. They read or wrote the object references of an RObject as raw bytes, so the next garbage collection could crash, and `to_string` gave out heap addresses. Calling the methods of `Cumo::NArray` on an RObject through `bind_call` raises `TypeError` (PR #638)
38
+
39
+ Fixes:
40
+
41
+ * Fix `require "cumo"` under `ruby -w` warning "method redefined; discarding old %". Cumo no longer defines `Range#%` again, which Ruby has had since 2.6 and which works the same (PR #643)
42
+ * Fix a crash, possible since 0.7.0, when storing an Array whose NArray row of another type is followed by a row that raises, such as one with the wrong number of dimensions. The garbage collector could free the cast copy of the row before the store let go of it (PR #642)
43
+ * Fix a range with a negative step and an excluded or missing end selecting the wrong elements: `(4...1).step(-1)` selected 5 elements of a 5-element array where it should select 3, and `(3..).step(-1)` none. Fix a stepped range that selects nothing returning elements, as `(1..0).step(2)` returned one and `(3...3).step(-1)` two (PR #641)
44
+ * Fix `to_a` and `format_to_a` aborting when Cumo is compiled with `RUBY_DEBUG` against a Ruby whose headers check the index of `RARRAY_AREF`, as Ruby master does since ruby/ruby@61261bf5c4 (PR #640)
45
+
46
+ Changes:
47
+
48
+ * CI builds against CUDA 13.4.3 on Ubuntu 26.04 where it built against 13.4.1 on Ubuntu 24.04, and the CUDA 12.9.2 job builds for sm_121 where it built for sm_120 (PR #639)
49
+ * The first `sort`, `median` or `sort_index` of a type loads the sort kernels of that type alone, where the first of a process loaded those of all twelve types. On SFloat the first `sort` is about 5.7 times faster, `median` about 9 times and `sort_index` about 3 times (PR #636)
50
+ * The first `cumsum` or `cumprod` of a process no longer loads every sort kernel, which makes the first SFloat `cumsum` about 2.1 times faster and keeps the peak RSS 57 MB lower (PR #635)
51
+ * `sum`, `mean`, `max`, `min` and the `dot` of two vectors have a kernel module of their own, so the first of them on a type no longer loads every reduction of the type. The first SFloat `sum` or vector `dot` of a process is about 8.6 times faster (PR #634)
52
+
1
53
  # 0.14.1 (2026/10/22)
2
54
 
3
55
  Fixes:
data/README.md CHANGED
@@ -198,6 +198,30 @@ Cumo::DFloat.new(1, 3).seq.transpose.contiguous? #=> true
198
198
  Code that runs against both libraries should not read `contiguous?` and expect the same answer.
199
199
  Where it wants a contiguous array it can ask for one, since `dup` answers one in either library.
200
200
 
201
+ #### Subscripts That Select Nothing
202
+
203
+ Numo raises `ShapeError` for every subscript of an empty array.
204
+ Cumo returns the empty view numpy does, and raises only for a subscript that names an element.
205
+
206
+ ```ruby
207
+ a = Cumo::DFloat.new(0, 3)
208
+ a[true, 1].shape #=> [0], where Numo raises ShapeError
209
+ a[0] # raises IndexError, where Numo raises ShapeError
210
+ ```
211
+
212
+ A range that selects nothing only has to start where an element could be inserted, as with `Array#[]`.
213
+ Numo raises `RangeError` when such a range starts at either end of an axis.
214
+
215
+ ```ruby
216
+ b = Cumo::DFloat.new(2, 3).seq
217
+ b[2...2, true].shape #=> [0, 3], where Numo raises RangeError
218
+ b[3...3, true] # raises RangeError in both
219
+ ```
220
+
221
+ A stepped range that selects nothing also selects nothing in Cumo.
222
+ Numo returns one element for `(1..0).step(2)` and two for `(3...3).step(-1)`.
223
+ `compatible_mode` does not change any of this.
224
+
201
225
  ### Keeping Scalars On The Device
202
226
 
203
227
  The 0-dimensional return is what lets an iterative loop stay on the GPU.
@@ -368,6 +392,41 @@ A thread's plans also go when it ends, and when an allocation it makes from the
368
392
  They keep its single positional argument, its double precision results and the `ArgumentError`s it raises, so code written for numo-pocketfft runs on the GPU after the replacement of `Numo` with `Cumo` above.
369
393
  A 0-dimensional array raises `Cumo::NArray::DimensionError`, where numo-pocketfft fails on it in a different way in each function.
370
394
 
395
+ ### Searching A Sorted Array
396
+
397
+ `searchsorted` answers where values would go in a sorted one-dimensional array to keep it sorted, as `numpy.searchsorted` does.
398
+ Numo has no such method.
399
+
400
+ ```ruby
401
+ a = Cumo::DFloat[1, 2, 2, 3]
402
+ a.searchsorted([0, 2, 9]) # => [0, 1, 4]
403
+ a.searchsorted([0, 2, 9], side: "right") # => [0, 3, 4]
404
+ x = Cumo::DFloat[3, 1, 2]
405
+ x.searchsorted(2.5, sorter: x.argsort) # => 2
406
+ ```
407
+
408
+ It takes numpy's keywords `side:` and `sorter:`, and answers a `Cumo::Int64` shaped like the values.
409
+ The array and the values are compared in the type numpy would promote them to, which holds both: `UInt32` and `Int32` in `Int64`, and `SFloat` and `Int64` in `DFloat`, where Cumo's arithmetic answers `Int32` and `SFloat`.
410
+ A Ruby number counts as an `Int32`, an `Int64` or a `DFloat`, by its value, and NaN sorts after every number, as in numpy.
411
+ A sorter index out of range raises `IndexError`, and complex and object arrays raise `TypeError`, since Cumo does not sort them.
412
+
413
+ ### Adding At Places That Repeat
414
+
415
+ `add_at` adds values in place at the places subscripts select, as `numpy.add.at` does: a place selected more than once gets every value added to it, where `a[idx] += b` adds only one of them.
416
+ Numo has no such method.
417
+
418
+ ```ruby
419
+ counts = Cumo::Int32.zeros(5)
420
+ counts.add_at(Cumo::Int32[1, 3, 1, 1], 1) # => [0, 3, 0, 1, 0]
421
+ grad = Cumo::SFloat.zeros(4, 3)
422
+ grad.add_at(Cumo::Int32[2, 0, 2], true, Cumo::SFloat.ones(3, 3)) # row 2 gets two rows, row 0 one
423
+ ```
424
+
425
+ The subscripts are those of `[]=`, so a single subscript of a multi-dimensional array counts its elements in order, where numpy would take its rows; a row is `a.add_at(i, true, values)`.
426
+ The values have to broadcast to the shape of the places selected, as in numpy.
427
+ They are cast to the receiver's type before they are added, where numpy adds in the type the two promote to and rounds each sum back: adding `-0.5` to an integer `1` leaves `1` here and gives `0` in numpy.
428
+ Every numeric type has it, Bit and RObject do not, and a floating-point sum comes out in whatever order the device adds, so its last bits can differ from run to run.
429
+
371
430
  ### Fused Operations
372
431
 
373
432
  `layer_norm`, `rms_norm` and `softmax` normalize along the last axis in one kernel each, and `quantize_symmetric` takes it to 8-bit integers in one more.
@@ -810,9 +869,17 @@ squared_diff.call(x, 5) # => the same against a scalar
810
869
  A type is one of `float64`, `float32`, `float16`, `bfloat16`, `int64`, `int32`, `int16`, `int8`, `uint64`, `uint32`, `uint16` and `uint8`, or a single letter that stands for whichever dtype the argument has.
811
870
  Outputs decide a letter before inputs do, and a letter that only a Ruby number reaches becomes `int64` or `float64`.
812
871
  Array arguments are broadcast against each other, and an output may be given after the inputs, or is allocated.
872
+ An output marked raw is left out of the broadcast, so it can have any shape and does not decide how many elements there are.
813
873
  An input is read through its own strides, so a reversed or stepped view goes to the kernel as it is.
814
- A transposed view is copied first, since the copy reorders it in tiles where the kernel would read it a row apart per thread, and so is a view built on an index array, or an input that shares memory with an output other than element for element, since the kernel would read what another thread has already written; a raw argument has to be contiguous and is copied when it is not.
874
+ A transposed view is copied first, since the copy reorders it in tiles where the kernel would read it a row apart per thread.
875
+ So is a view built on an index array.
876
+ An input that is not raw is also copied when it shares memory with a raw output, or with another output other than element for element, since the kernel would read what another thread has already written.
877
+ A raw input is copied when it is not contiguous, or when it shares memory with any output, since the operation may read any element of it.
878
+ CuPy reads such an input in place, so a kernel that reads only its own element of an array it also writes takes an extra copy of that array here.
879
+ A raw output has to be contiguous.
815
880
  An argument marked `raw T y` is handed over as a pointer for the operation to index itself, with `i` the element index and `_ind.size()` the element count, and when every argument is raw or a number, `size:` says how many elements there are.
881
+ A raw output has to be given, since nothing else says how long it is.
882
+ When `size:` is given, one that long is allocated instead, and the elements the operation does not write are left uninitialized.
816
883
  Inputs are `const`, so an operation that writes one does not compile, and a number handed to an integer type has to be an Integer that fits.
817
884
  `preamble:` is placed before the kernel, after the typedefs of the letters, so a device function can be written in terms of `T`.
818
885
  `float16` and `bfloat16` are CUDA's `__half` and `__nv_bfloat16`, compiled with the toolkit's `cuda_fp16.h` and `cuda_bf16.h`, which are found through `CUDA_PATH` or the `nvcc` on `PATH`.
data/Rakefile CHANGED
@@ -39,7 +39,9 @@ Rake::TestTask.new(:test) do |t|
39
39
  end
40
40
 
41
41
  require "rake/extensiontask"
42
- Rake::ExtensionTask.new("cumo")
42
+ ext = Rake::ExtensionTask.new("cumo")
43
+ # The Makefile lists an object for each kernel part, so a new part needs extconf.rb to run again.
44
+ file "#{ext.tmp_dir}/#{ext.platform}/#{ext.name}/#{RUBY_VERSION}/Makefile" => "ext/cumo/narray/gen/kernel_parts.rb"
43
45
 
44
46
  desc 'Build the C++ memory pool test harness without running it (running it needs a GPU)'
45
47
  task :build_ctest do
@@ -0,0 +1,26 @@
1
+ #include <cub/util_device.cuh>
2
+ #include "cumo/template_kernel.h"
3
+
4
+ namespace {
5
+
6
+ __global__ void cumo_cub_ptx_version_probe() {}
7
+
8
+ } // namespace
9
+
10
+ // CUB learns each device's PTX version once, from the attributes of an empty
11
+ // kernel. Each translation unit has its own empty kernel, but the link keeps
12
+ // one copy of the code that asks. The query loads the module that copy came
13
+ // from, which can be a large one the caller never runs. This module has one
14
+ // kernel built with the same flags, so it gives the same version at little cost.
15
+ extern "C" void
16
+ cumo_cuda_cub_prime_ptx_version(void)
17
+ {
18
+ cub::GetPerDeviceAttributeCache<cub::PtxVersionCacheTag>()(
19
+ [](int& ptx_version) {
20
+ cudaFuncAttributes attrs = {};
21
+ cudaError_t status = cudaFuncGetAttributes(&attrs, (const void*)cumo_cub_ptx_version_probe);
22
+ ptx_version = attrs.ptxVersion * 10;
23
+ return status;
24
+ },
25
+ cub::CurrentDevice());
26
+ }
data/ext/cumo/cumo.c CHANGED
@@ -27,7 +27,6 @@ void Init_cumo();
27
27
  void Init_cumo_narray();
28
28
  void Init_cumo_na_data();
29
29
  void Init_cumo_na_ndloop();
30
- void Init_cumo_na_step();
31
30
  void Init_cumo_na_index();
32
31
  void Init_cumo_bit();
33
32
  void Init_cumo_int8();
@@ -189,7 +188,6 @@ Init_cumo()
189
188
 
190
189
  Init_cumo_narray();
191
190
 
192
- Init_cumo_na_step();
193
191
  Init_cumo_na_index();
194
192
 
195
193
  Init_cumo_na_data();
data/ext/cumo/extconf.rb CHANGED
@@ -55,7 +55,6 @@ narray/ndloop
55
55
  narray/ndloop_kernel
56
56
  narray/data
57
57
  narray/data_kernel
58
- narray/sort_kernel
59
58
  narray/math
60
59
  narray/SFMT
61
60
  narray/struct
@@ -70,6 +69,7 @@ cuda/cudnn
70
69
  cuda/cudnn_impl
71
70
  cuda/cusolver
72
71
  cuda/cufft
72
+ cuda/cub
73
73
  )
74
74
  %w[bit int8 int16 int32 int64 uint8 uint16 uint32 uint64 hfloat bfloat sfloat dfloat scomplex dcomplex robject].each do |type_name|
75
75
  srcs << "narray/types/#{type_name}"
@@ -117,7 +117,6 @@ unless have_type("u_int64_t", stdint)
117
117
  have_type("uint64_t", stdint)
118
118
  end
119
119
  have_func("exp10")
120
- have_func("rb_arithmetic_sequence_extract")
121
120
  have_func("RTYPEDDATA_GET_DATA")
122
121
 
123
122
  have_var("rb_cComplex")
@@ -108,6 +108,8 @@ void cumo_na_index_mark_filled(cumo_narray_view_t *nv);
108
108
  void cumo_na_index_wait_fill(cumo_narray_view_t *nv);
109
109
  VALUE cumo_na_aref_main(int nidx, VALUE *idx, VALUE self, int keep_dim, int result_nd, size_t pos);
110
110
  VALUE cumo_na_at_main(int nidx, VALUE *idx, VALUE self, int keep_dim, int result_nd, size_t pos);
111
+ int cumo_na_index_in_place_width(VALUE idx);
112
+ void cumo_na_index_check_range_in_place(const char *p, int width, uint64_t n, ssize_t size);
111
113
 
112
114
  // defined in array, used in math
113
115
  VALUE cumo_na_ary_composition_dtype(VALUE ary);
@@ -205,9 +205,7 @@ extern VALUE cumo_cRObject;
205
205
  #ifndef HAVE_RB_CCOMPLEX
206
206
  extern VALUE rb_cComplex;
207
207
  #endif
208
- #ifdef HAVE_RB_ARITHMETIC_SEQUENCE_EXTRACT
209
208
  extern VALUE rb_cArithSeq;
210
- #endif
211
209
 
212
210
  extern VALUE cumo_sym_reduce;
213
211
  extern VALUE cumo_sym_option;
@@ -258,9 +256,11 @@ typedef struct {
258
256
  // A view made from another one can point at the index arrays it already
259
257
  // has rather than copy them. index_owner keeps that view alive for as long
260
258
  // as this one borrows from it, and index_owned says which dimensions are
261
- // this view's own to free.
259
+ // this view's own to free. index_bytes is what those take on the device,
260
+ // told to the GC when they are taken and when they are freed.
262
261
  VALUE index_owner;
263
262
  uint64_t index_owned;
263
+ size_t index_bytes;
264
264
  } cumo_narray_view_t;
265
265
 
266
266
 
@@ -521,14 +521,38 @@ typedef unsigned int CUMO_BIT_DIGIT;
521
521
  #include "cumo/ndloop.h"
522
522
  #include "cumo/intern.h"
523
523
 
524
- // An index array a view holds is freed only if it was set through here, so a
525
- // view that puts one in stridx any other way leaks it. The bit names the slot,
526
- // so code that permutes stridx has to permute index_owned with it.
524
+ // An index array a view holds is freed only if it was set through here or
525
+ // cumo_na_index_own, so a view that puts one in stridx any other way leaks it.
526
+ // The bit names the slot, so code that permutes stridx has to permute
527
+ // index_owned with it. n is the element count it was allocated with. This one
528
+ // takes an array the GC has already heard of, such as the buffer another array
529
+ // gives up, so only its release is counted.
527
530
  static inline void
528
- cumo_na_index_own(cumo_narray_view_t *nv, int i, size_t *idx)
531
+ cumo_na_index_adopt(cumo_narray_view_t *nv, int i, size_t *idx, size_t n)
529
532
  {
530
533
  CUMO_SDX_SET_INDEX(nv->stridx[i], idx);
531
534
  nv->index_owned |= (uint64_t)1 << i;
535
+ nv->index_bytes += sizeof(size_t) * n;
536
+ }
537
+
538
+ // Takes a freshly allocated index array. The GC has to hear of it, or nothing
539
+ // collects views that hold large index arrays and little else.
540
+ static inline void
541
+ cumo_na_index_own(cumo_narray_view_t *nv, int i, size_t *idx, size_t n)
542
+ {
543
+ cumo_na_index_adopt(nv, i, idx, n);
544
+ rb_gc_adjust_memory_usage((ssize_t)(sizeof(size_t) * n));
545
+ }
546
+
547
+ // Since Ruby 3.3 a temporary ages and can hold its device memory until a major
548
+ // GC. Unprotected, it stays young but is marked at every minor GC, which only a
549
+ // large buffer pays for. Ruby's per-Ractor GC requires shareable ones protected.
550
+ static inline void
551
+ cumo_na_keep_young_if_large(VALUE self, size_t bytes)
552
+ {
553
+ if (bytes >= ((size_t)1 << 20) && !RB_FL_TEST_RAW(self, RUBY_FL_SHAREABLE)) {
554
+ RB_OBJ_WB_UNPROTECT(self);
555
+ }
532
556
  }
533
557
 
534
558
  // One dimension of nv now points at an index array that from reaches, so from
@@ -1,3 +1,6 @@
1
+ #ifndef CUMO_SORT_KERNEL_H
2
+ #define CUMO_SORT_KERNEL_H
3
+
1
4
  #include "cumo/narray_kernel.h"
2
5
  #include "cumo/indexer.h"
3
6
  #include "cumo/template_kernel.h"
@@ -6,6 +9,7 @@
6
9
  #include "cumo/types/bf16_def_kernel.h"
7
10
 
8
11
  #include <cub/cub.cuh>
12
+ #include <cuda/std/tuple>
9
13
  #include <thrust/iterator/counting_iterator.h>
10
14
  #include <thrust/iterator/transform_iterator.h>
11
15
 
@@ -73,6 +77,79 @@ __global__ void float_key_kernel(const Float* in, typename float_key<Float>::typ
73
77
  }
74
78
  }
75
79
 
80
+ // A key that also gives the float back, so that sort and median can sort the
81
+ // keys alone instead of the keys with the values. The usual order of the bits
82
+ // puts a negative NaN first; rotating every key down by the number of negative
83
+ // NaNs wraps them round to follow the positive ones, so every NaN is last.
84
+ template <typename U>
85
+ __device__ static inline U rotated_key(U bits, U inf_bits) {
86
+ const U sign = (U)1 << (sizeof(U) * 8 - 1);
87
+ const U neg_nans = (U)((U)(sign - 1) - inf_bits);
88
+ return (U)(((bits & sign) ? (U)~bits : (U)(bits | sign)) - neg_nans);
89
+ }
90
+
91
+ template <typename U>
92
+ __device__ static inline U rotated_bits(U key, U inf_bits) {
93
+ const U sign = (U)1 << (sizeof(U) * 8 - 1);
94
+ const U neg_nans = (U)((U)(sign - 1) - inf_bits);
95
+ const U k = (U)(key + neg_nans);
96
+ return (k & sign) ? (U)(k & (U)~sign) : (U)~k;
97
+ }
98
+
99
+ template <typename Float> struct float_order;
100
+
101
+ template <> struct float_order<float> {
102
+ typedef uint32_t type;
103
+ __device__ static type key(float x) { return rotated_key<type>(__float_as_uint(x), 0x7f800000u); }
104
+ __device__ static float value(type k) { return __uint_as_float(rotated_bits<type>(k, 0x7f800000u)); }
105
+ };
106
+
107
+ template <> struct float_order<cumo_half> {
108
+ typedef uint16_t type;
109
+ __device__ static type key(cumo_half x) { return rotated_key<type>(__half_as_ushort(x), 0x7c00u); }
110
+ __device__ static cumo_half value(type k) { return __ushort_as_half(rotated_bits<type>(k, 0x7c00u)); }
111
+ };
112
+
113
+ template <> struct float_order<cumo_bfloat> {
114
+ typedef uint16_t type;
115
+ __device__ static type key(cumo_bfloat x) {
116
+ uint16_t bits;
117
+ memcpy(&bits, &x, sizeof(bits));
118
+ return rotated_key<type>(bits, 0x7f80u);
119
+ }
120
+ __device__ static cumo_bfloat value(type k) {
121
+ uint16_t bits = rotated_bits<type>(k, 0x7f80u);
122
+ cumo_bfloat x;
123
+ memcpy(&x, &bits, sizeof(bits));
124
+ return x;
125
+ }
126
+ };
127
+
128
+ template <> struct float_order<double> {
129
+ typedef uint64_t type;
130
+ __device__ static type key(double x) { return rotated_key<type>((type)__double_as_longlong(x), 0x7ff0000000000000ull); }
131
+ __device__ static double value(type k) {
132
+ type bits = rotated_bits<type>(k, 0x7ff0000000000000ull);
133
+ double x;
134
+ memcpy(&x, &bits, sizeof(bits));
135
+ return x;
136
+ }
137
+ };
138
+
139
+ template <typename Float>
140
+ __global__ void order_key_kernel(const Float* in, typename float_order<Float>::type* out, uint64_t n) {
141
+ for (uint64_t i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += blockDim.x * gridDim.x) {
142
+ out[i] = float_order<Float>::key(in[i]);
143
+ }
144
+ }
145
+
146
+ template <typename Float>
147
+ __global__ void order_value_kernel(const typename float_order<Float>::type* in, Float* out, uint64_t n) {
148
+ for (uint64_t i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += blockDim.x * gridDim.x) {
149
+ out[i] = float_order<Float>::value(in[i]);
150
+ }
151
+ }
152
+
76
153
  // sort writes its answer back where it read it, so an in-place sort of a view
77
154
  // backed by an index array has to address that array; the other two callers
78
155
  // hand over an array they copied themselves and never do.
@@ -146,6 +223,7 @@ cudaError_t sort_pairs(const Key* kin, Key* kout, const Value* vin, Value* vout,
146
223
  int64_t total, int64_t n_rows, int64_t row_len) {
147
224
  size_t bytes = 0;
148
225
  cudaError_t st = cudaSuccess;
226
+ cumo_cuda_cub_prime_ptx_version();
149
227
  if (n_rows == 1) {
150
228
  st = cub::DeviceRadixSort::SortPairs(nullptr, bytes, kin, kout, vin, vout, total, 0, sizeof(Key) * 8, cumo_cuda_stream());
151
229
  if (st != cudaSuccess) { return st; }
@@ -168,6 +246,7 @@ template <typename Key>
168
246
  cudaError_t sort_keys(const Key* kin, Key* kout, int64_t total, int64_t n_rows, int64_t row_len) {
169
247
  size_t bytes = 0;
170
248
  cudaError_t st = cudaSuccess;
249
+ cumo_cuda_cub_prime_ptx_version();
171
250
  if (n_rows == 1) {
172
251
  st = cub::DeviceRadixSort::SortKeys(nullptr, bytes, kin, kout, total, 0, sizeof(Key) * 8, cumo_cuda_stream());
173
252
  if (st != cudaSuccess) { return st; }
@@ -186,6 +265,36 @@ cudaError_t sort_keys(const Key* kin, Key* kout, int64_t total, int64_t n_rows,
186
265
  return st;
187
266
  }
188
267
 
268
+ // A bare uint32_t key makes SortKeys the same function as the UInt32 sort's,
269
+ // and the link keeps one, so SFloat would launch the kernels of the UInt32
270
+ // module. Wrapped in a type of this file, as position below does for sort_index.
271
+ template <typename U> struct order_bits { U bits; };
272
+ template <typename U> struct order_bits_decomposer {
273
+ __host__ __device__ ::cuda::std::tuple<U&> operator()(order_bits<U>& k) const { return {k.bits}; }
274
+ };
275
+
276
+ // The segmented sort takes iterators of this file already. A CUB without the
277
+ // decomposer, before 2.2, is left sharing the function.
278
+ template <typename U>
279
+ cudaError_t sort_order_keys(const U* kin, U* kout, int64_t total, int64_t n_rows, int64_t row_len) {
280
+ #if CUB_VERSION >= 200200
281
+ if (n_rows == 1) {
282
+ size_t bytes = 0;
283
+ cudaError_t st;
284
+ const order_bits<U>* in = (const order_bits<U>*)kin;
285
+ order_bits<U>* out = (order_bits<U>*)kout;
286
+ cumo_cuda_cub_prime_ptx_version();
287
+ st = cub::DeviceRadixSort::SortKeys(nullptr, bytes, in, out, total, order_bits_decomposer<U>{}, 0, (int)sizeof(U) * 8, cumo_cuda_stream());
288
+ if (st != cudaSuccess) { return st; }
289
+ char* tmp = cumo_cuda_runtime_malloc(bytes);
290
+ st = cub::DeviceRadixSort::SortKeys(tmp, bytes, in, out, total, order_bits_decomposer<U>{}, 0, (int)sizeof(U) * 8, cumo_cuda_stream());
291
+ cumo_cuda_runtime_free(tmp);
292
+ return st;
293
+ }
294
+ #endif
295
+ return sort_keys(kin, kout, total, n_rows, row_len);
296
+ }
297
+
189
298
  template <typename T, bool IS_FLOAT>
190
299
  void sort_rows(cumo_na_iarray_stridx_t* a, cumo_na_indexer_t* indexer, int64_t n_rows, int64_t row_len, int flat) {
191
300
  int64_t total = (int64_t)indexer->total_size;
@@ -205,31 +314,35 @@ void sort_rows(cumo_na_iarray_stridx_t* a, cumo_na_indexer_t* indexer, int64_t n
205
314
  data = gathered;
206
315
  }
207
316
 
208
- T* out = (T*)cumo_cuda_runtime_malloc(sizeof(T) * total);
317
+ // Rows laid out end to end take their floats back in place, so a float
318
+ // sort needs a buffer of its own only for the rows it gathered.
319
+ T* out = (IS_FLOAT && flat) ? 0 : (T*)cumo_cuda_runtime_malloc(sizeof(T) * total);
209
320
  if constexpr (IS_FLOAT) {
210
- typedef typename float_key<T>::type key_t;
321
+ typedef typename float_order<T>::type key_t;
211
322
  key_t* kin = (key_t*)cumo_cuda_runtime_malloc(sizeof(key_t) * total);
212
323
  key_t* kout = (key_t*)cumo_cuda_runtime_malloc(sizeof(key_t) * total);
213
- float_key_kernel<T><<<grid_dim, block_dim, 0, cumo_cuda_stream()>>>(data, kin, total);
324
+ order_key_kernel<T><<<grid_dim, block_dim, 0, cumo_cuda_stream()>>>(data, kin, total);
325
+ cumo_check_launch_holding(kin, kout, out, gathered);
326
+ cumo_check_status_holding(sort_order_keys(kin, kout, total, n_rows, row_len), kin, kout, out, gathered);
327
+ order_value_kernel<T><<<grid_dim, block_dim, 0, cumo_cuda_stream()>>>(kout, flat ? data : out, total);
214
328
  cumo_check_launch_holding(kin, kout, out, gathered);
215
- cumo_check_status_holding(sort_pairs(kin, kout, data, out, total, n_rows, row_len),
216
- kin, kout, out, gathered);
217
329
  cumo_cuda_runtime_free((char*)kout);
218
330
  cumo_cuda_runtime_free((char*)kin);
219
331
  } else {
220
332
  cumo_check_status_holding(sort_keys(data, out, total, n_rows, row_len), out, gathered);
333
+ if (flat) {
334
+ cudaMemcpyAsync(data, out, sizeof(T) * total, cudaMemcpyDeviceToDevice, cumo_cuda_stream());
335
+ }
221
336
  }
222
337
 
223
- if (flat) {
224
- cudaMemcpyAsync(data, out, sizeof(T) * total, cudaMemcpyDeviceToDevice, cumo_cuda_stream());
225
- } else {
338
+ if (!flat) {
226
339
  #define CUMO_SORT_L(N) scatter_kernel<N><<<grid_dim, block_dim, 0, cumo_cuda_stream()>>>(*a, *indexer, out)
227
340
  CUMO_SORT_BY_RANK(indexer->ndim, CUMO_SORT_L);
228
341
  #undef CUMO_SORT_L
342
+ cumo_check_launch_holding(out, gathered);
229
343
  }
230
- cumo_check_launch_holding(out, gathered);
231
344
  if (gathered) cumo_cuda_runtime_free((char*)gathered);
232
- cumo_cuda_runtime_free((char*)out);
345
+ if (out) cumo_cuda_runtime_free((char*)out);
233
346
  }
234
347
 
235
348
  // The rows are already sorted, so the middle of each is the answer. Trailing
@@ -297,13 +410,14 @@ void median_rows(cumo_na_reduction_arg_t* arg, int flat, int prnan) {
297
410
 
298
411
  T* sorted = (T*)cumo_cuda_runtime_malloc(sizeof(T) * total);
299
412
  if constexpr (IS_FLOAT) {
300
- typedef typename float_key<T>::type key_t;
413
+ typedef typename float_order<T>::type key_t;
301
414
  key_t* kin = (key_t*)cumo_cuda_runtime_malloc(sizeof(key_t) * total);
302
415
  key_t* kout = (key_t*)cumo_cuda_runtime_malloc(sizeof(key_t) * total);
303
- float_key_kernel<T><<<grid_dim, block_dim, 0, cumo_cuda_stream()>>>(data, kin, total);
416
+ order_key_kernel<T><<<grid_dim, block_dim, 0, cumo_cuda_stream()>>>(data, kin, total);
417
+ cumo_check_launch_holding(kin, kout, sorted, gathered);
418
+ cumo_check_status_holding(sort_order_keys(kin, kout, total, n_rows, row_len), kin, kout, sorted, gathered);
419
+ order_value_kernel<T><<<grid_dim, block_dim, 0, cumo_cuda_stream()>>>(kout, sorted, total);
304
420
  cumo_check_launch_holding(kin, kout, sorted, gathered);
305
- cumo_check_status_holding(sort_pairs(kin, kout, data, sorted, total, n_rows, row_len),
306
- kin, kout, sorted, gathered);
307
421
  cumo_cuda_runtime_free((char*)kout);
308
422
  cumo_cuda_runtime_free((char*)kin);
309
423
  } else {
@@ -329,6 +443,12 @@ __global__ void iota_kernel(I* out, int64_t n) {
329
443
  }
330
444
  }
331
445
 
446
+ // The positions go to CUB as this rather than as a bare integer, so that
447
+ // SortPairs is a function of this file alone. With a bare integer it is the
448
+ // same function for every type whose key has the same width, and the link
449
+ // keeps one, so SFloat would launch the kernels of the UInt32 module.
450
+ template <typename I> struct position { I value; };
451
+
332
452
  // perm[i] is the position the i-th smallest element sat at, and the index
333
453
  // array holds the number to answer for that position.
334
454
  template <int NDIM, typename I>
@@ -373,13 +493,13 @@ void sort_index_rows(cumo_na_iarray_t* a, cumo_na_indexer_t* indexer, cumo_na_ia
373
493
  key_t* kout = (key_t*)cumo_cuda_runtime_malloc(sizeof(key_t) * total);
374
494
  float_key_kernel<T><<<grid_dim, block_dim, 0, cumo_cuda_stream()>>>(data, kin, total);
375
495
  cumo_check_launch_holding(kin, kout, pin, pout, gathered);
376
- cumo_check_status_holding(sort_pairs(kin, kout, pin, pout, total, n_rows, row_len),
496
+ cumo_check_status_holding(sort_pairs(kin, kout, (const position<I>*)pin, (position<I>*)pout, total, n_rows, row_len),
377
497
  kin, kout, pin, pout, gathered);
378
498
  cumo_cuda_runtime_free((char*)kout);
379
499
  cumo_cuda_runtime_free((char*)kin);
380
500
  } else {
381
501
  T* kout = (T*)cumo_cuda_runtime_malloc(sizeof(T) * total);
382
- cumo_check_status_holding(sort_pairs(data, kout, pin, pout, total, n_rows, row_len),
502
+ cumo_check_status_holding(sort_pairs(data, kout, (const position<I>*)pin, (position<I>*)pout, total, n_rows, row_len),
383
503
  kout, pin, pout, gathered);
384
504
  cumo_cuda_runtime_free((char*)kout);
385
505
  }
@@ -396,7 +516,7 @@ void sort_index_rows(cumo_na_iarray_t* a, cumo_na_indexer_t* indexer, cumo_na_ia
396
516
 
397
517
  } // namespace
398
518
 
399
- // float_key is only defined for the two float types, so the integer entry
519
+ // float_key is only defined for the float types, so the integer entry
400
520
  // points must not instantiate it; the bool picks the branch at compile time.
401
521
  #define CUMO_DEF_SORT(name, type, is_float) \
402
522
  extern "C" void cumo_##name##_sort_kernel_launch( \
@@ -420,15 +540,4 @@ void sort_index_rows(cumo_na_iarray_t* a, cumo_na_indexer_t* indexer, cumo_na_ia
420
540
  } \
421
541
  }
422
542
 
423
- CUMO_DEF_SORT(int8, int8_t, false)
424
- CUMO_DEF_SORT(int16, int16_t, false)
425
- CUMO_DEF_SORT(int32, int32_t, false)
426
- CUMO_DEF_SORT(int64, int64_t, false)
427
- CUMO_DEF_SORT(uint8, u_int8_t, false)
428
- CUMO_DEF_SORT(uint16, u_int16_t, false)
429
- CUMO_DEF_SORT(uint32, u_int32_t, false)
430
- CUMO_DEF_SORT(uint64, u_int64_t, false)
431
- CUMO_DEF_SORT(hfloat, cumo_half, true)
432
- CUMO_DEF_SORT(bfloat, cumo_bfloat, true)
433
- CUMO_DEF_SORT(sfloat, float, true)
434
- CUMO_DEF_SORT(dfloat, double, true)
543
+ #endif /* ifndef CUMO_SORT_KERNEL_H */
@@ -65,8 +65,9 @@
65
65
  CUMO_REBASE_BIT_PTR(lp, i, ad, ps); \
66
66
  }
67
67
 
68
- // A where compaction takes three launches, so below this many elements walking
69
- // the bits on the host costs less. This is a tuning value, not a hard limit.
68
+ // A where compaction takes three launches a segment, so a walk that ndloop
69
+ // splits into segments shorter than this walks the bits on the host instead.
70
+ // This is a tuning value, not a hard limit.
70
71
  #define CUMO_BIT_WHERE_MIN_KERNEL_SIZE 8192
71
72
 
72
73
  #define CUMO_GET_DATA( ptr, type, val ) \
@@ -186,6 +186,8 @@ void cumo_cuda_runtime_check_kernel_launch(void);
186
186
  // The stream every launch and copy goes to. It is 0 until Stream#with says
187
187
  // otherwise, and thread local, so one thread's choice is not another's.
188
188
  struct CUstream_st* cumo_cuda_stream(void);
189
+ // Call before any CUB or Thrust algorithm. Defined in cuda/cub.cu, which says why.
190
+ void cumo_cuda_cub_prime_ptx_version(void);
189
191
 
190
192
  // The forms to call while scratch is held, which free what they are given
191
193
  // before they raise. Pass every buffer that is still outstanding, including the
@@ -103,12 +103,10 @@ static int cumo_na_mdai_object_type(int type, VALUE v)
103
103
  if (rb_obj_is_kind_of(v, rb_cRange)) {
104
104
  MDAI_ATTR_TYPE(type,v,begin);
105
105
  MDAI_ATTR_TYPE(type,v,end);
106
- #ifdef HAVE_RB_ARITHMETIC_SEQUENCE_EXTRACT
107
106
  } else if (rb_obj_is_kind_of(v, rb_cArithSeq)) {
108
107
  MDAI_ATTR_TYPE(type,v,begin);
109
108
  MDAI_ATTR_TYPE(type,v,end);
110
109
  MDAI_ATTR_TYPE(type,v,step);
111
- #endif
112
110
  } else {
113
111
  type = cumo_na_object_type(type,v);
114
112
  }
@@ -193,11 +191,7 @@ cumo_na_mdai_investigate(cumo_na_mdai_t *mdai, int ndim)
193
191
  }
194
192
  }
195
193
  else
196
- #ifdef HAVE_RB_ARITHMETIC_SEQUENCE_EXTRACT
197
194
  if (rb_obj_is_kind_of(v, rb_cRange) || rb_obj_is_kind_of(v, rb_cArithSeq))
198
- #else
199
- if (rb_obj_is_kind_of(v, rb_cRange) || rb_obj_is_kind_of(v, rb_cEnumerator))
200
- #endif
201
195
  {
202
196
  cumo_na_step_sequence(v,&length,&dbeg,&dstep);
203
197
  len += length-1;