cumo 0.15.0 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d6fcb0462dc2821749f43c243267e8eef32c5362d2a647769c3f93ccc048ddd0
4
- data.tar.gz: 131ec1045f331591fb3f1c522824ea1e14c56fad40091bccacde73bb7f64a649
3
+ metadata.gz: 6cf3505847ba8f6dd8c1e85537b8822772eadcb2201a04c955c40eb7e7119494
4
+ data.tar.gz: 8e0e112a1f00f2fdedc3dda076facad17d14d2f7d0cc908271eb3a17e8570fe8
5
5
  SHA512:
6
- metadata.gz: dfbb78f6f9ea625ae2848210722aa58106e6efd80af31d38e239585def253b7fb0e00426d18804e4177040492469d3498eaf61dca0cb7880ee482bd1c9669d0e
7
- data.tar.gz: 80c944b3b2a544c593a221c9600c2a8cc441b273e37dc77f3ca1bbb738e381e1fcc0db42cbc66265f6d75832ee0ca396b008ffec7ff666549db313d386b82e81
6
+ metadata.gz: 332e60af9f4bd379f3f0575e877d5d32f26b2b655551025355884d32315208b0c03e47fe9f12d7fa72f0b7e429d5d1844964b6fdf5e4d3a4c7a6ba74d5aa6fff
7
+ data.tar.gz: b8b86049ea712bb8890911709711c373e0a7187ce7a6a7fed531f88ed915cc7bb9f94c3c64529d0a5b32e04c32dff93e2913c6268818e88f0a136652ea0a360e
data/CHANGELOG.md CHANGED
@@ -1,3 +1,34 @@
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
+
1
32
  # 0.15.0 (2026/11/02)
2
33
 
3
34
  Breaking changes:
data/README.md CHANGED
@@ -392,6 +392,41 @@ A thread's plans also go when it ends, and when an allocation it makes from the
392
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.
393
393
  A 0-dimensional array raises `Cumo::NArray::DimensionError`, where numo-pocketfft fails on it in a different way in each function.
394
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
+
395
430
  ### Fused Operations
396
431
 
397
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.
@@ -834,9 +869,17 @@ squared_diff.call(x, 5) # => the same against a scalar
834
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.
835
870
  Outputs decide a letter before inputs do, and a letter that only a Ruby number reaches becomes `int64` or `float64`.
836
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.
837
873
  An input is read through its own strides, so a reversed or stepped view goes to the kernel as it is.
838
- 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.
839
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.
840
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.
841
884
  `preamble:` is placed before the kernel, after the typedefs of the letters, so a device function can be written in terms of `T`.
842
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/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
@@ -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
@@ -9,6 +9,7 @@
9
9
  #include "cumo/types/bf16_def_kernel.h"
10
10
 
11
11
  #include <cub/cub.cuh>
12
+ #include <cuda/std/tuple>
12
13
  #include <thrust/iterator/counting_iterator.h>
13
14
  #include <thrust/iterator/transform_iterator.h>
14
15
 
@@ -76,6 +77,79 @@ __global__ void float_key_kernel(const Float* in, typename float_key<Float>::typ
76
77
  }
77
78
  }
78
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
+
79
153
  // sort writes its answer back where it read it, so an in-place sort of a view
80
154
  // backed by an index array has to address that array; the other two callers
81
155
  // hand over an array they copied themselves and never do.
@@ -191,6 +265,36 @@ cudaError_t sort_keys(const Key* kin, Key* kout, int64_t total, int64_t n_rows,
191
265
  return st;
192
266
  }
193
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
+
194
298
  template <typename T, bool IS_FLOAT>
195
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) {
196
300
  int64_t total = (int64_t)indexer->total_size;
@@ -210,31 +314,35 @@ void sort_rows(cumo_na_iarray_stridx_t* a, cumo_na_indexer_t* indexer, int64_t n
210
314
  data = gathered;
211
315
  }
212
316
 
213
- 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);
214
320
  if constexpr (IS_FLOAT) {
215
- typedef typename float_key<T>::type key_t;
321
+ typedef typename float_order<T>::type key_t;
216
322
  key_t* kin = (key_t*)cumo_cuda_runtime_malloc(sizeof(key_t) * total);
217
323
  key_t* kout = (key_t*)cumo_cuda_runtime_malloc(sizeof(key_t) * total);
218
- 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);
219
328
  cumo_check_launch_holding(kin, kout, out, gathered);
220
- cumo_check_status_holding(sort_pairs(kin, kout, data, out, total, n_rows, row_len),
221
- kin, kout, out, gathered);
222
329
  cumo_cuda_runtime_free((char*)kout);
223
330
  cumo_cuda_runtime_free((char*)kin);
224
331
  } else {
225
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
+ }
226
336
  }
227
337
 
228
- if (flat) {
229
- cudaMemcpyAsync(data, out, sizeof(T) * total, cudaMemcpyDeviceToDevice, cumo_cuda_stream());
230
- } else {
338
+ if (!flat) {
231
339
  #define CUMO_SORT_L(N) scatter_kernel<N><<<grid_dim, block_dim, 0, cumo_cuda_stream()>>>(*a, *indexer, out)
232
340
  CUMO_SORT_BY_RANK(indexer->ndim, CUMO_SORT_L);
233
341
  #undef CUMO_SORT_L
342
+ cumo_check_launch_holding(out, gathered);
234
343
  }
235
- cumo_check_launch_holding(out, gathered);
236
344
  if (gathered) cumo_cuda_runtime_free((char*)gathered);
237
- cumo_cuda_runtime_free((char*)out);
345
+ if (out) cumo_cuda_runtime_free((char*)out);
238
346
  }
239
347
 
240
348
  // The rows are already sorted, so the middle of each is the answer. Trailing
@@ -302,13 +410,14 @@ void median_rows(cumo_na_reduction_arg_t* arg, int flat, int prnan) {
302
410
 
303
411
  T* sorted = (T*)cumo_cuda_runtime_malloc(sizeof(T) * total);
304
412
  if constexpr (IS_FLOAT) {
305
- typedef typename float_key<T>::type key_t;
413
+ typedef typename float_order<T>::type key_t;
306
414
  key_t* kin = (key_t*)cumo_cuda_runtime_malloc(sizeof(key_t) * total);
307
415
  key_t* kout = (key_t*)cumo_cuda_runtime_malloc(sizeof(key_t) * total);
308
- 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);
309
420
  cumo_check_launch_holding(kin, kout, sorted, gathered);
310
- cumo_check_status_holding(sort_pairs(kin, kout, data, sorted, total, n_rows, row_len),
311
- kin, kout, sorted, gathered);
312
421
  cumo_cuda_runtime_free((char*)kout);
313
422
  cumo_cuda_runtime_free((char*)kin);
314
423
  } else {
@@ -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 ) \
@@ -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;
@@ -636,7 +636,7 @@ cumo_na_flatten_dim(VALUE self, int sd)
636
636
  cumo_na_indexer_t indexer;
637
637
 
638
638
  idx2 = (size_t*)cumo_cuda_runtime_malloc(sizeof(size_t)*((shape[sd]==0) ? 1 : shape[sd]));
639
- cumo_na_index_own(na2,sd,idx2);
639
+ cumo_na_index_own(na2,sd,idx2,(shape[sd]==0) ? 1 : shape[sd]);
640
640
  fd = nd-sd;
641
641
  iarray.ptr = NULL;
642
642
  indexer.ndim = fd;
@@ -854,7 +854,7 @@ cumo_na_diagonal(int argc, VALUE *argv, VALUE self)
854
854
  } else {
855
855
  idx0 = CUMO_SDX_GET_INDEX(na1->stridx[i]);
856
856
  idx1 = (size_t*)cumo_cuda_runtime_malloc(sizeof(size_t)*na->shape[i]);
857
- cumo_na_index_own(na2,k,idx1);
857
+ cumo_na_index_own(na2,k,idx1,na->shape[i]);
858
858
  cumo_cuda_runtime_check_status(cudaMemcpyAsync(idx1,idx0,sizeof(size_t)*na->shape[i],cudaMemcpyDeviceToDevice,cumo_cuda_stream()));
859
859
  cumo_cuda_runtime_note_device_write();
860
860
  }
@@ -865,7 +865,7 @@ cumo_na_diagonal(int argc, VALUE *argv, VALUE self)
865
865
  idx0 = CUMO_SDX_GET_INDEX(na1->stridx[ax[0]]);
866
866
  // diag_idx = ALLOC_N(size_t, diag_size);
867
867
  diag_idx = (size_t*)cumo_cuda_runtime_malloc(sizeof(size_t)*diag_size);
868
- cumo_na_index_own(na2,nd-2,diag_idx);
868
+ cumo_na_index_own(na2,nd-2,diag_idx,diag_size);
869
869
  if (CUMO_SDX_IS_INDEX(na1->stridx[ax[1]])) {
870
870
  idx1 = CUMO_SDX_GET_INDEX(na1->stridx[ax[1]]);
871
871
  cumo_na_diagonal_index_index_kernel_launch(diag_idx, idx0, idx1, k0, k1, diag_size);
@@ -879,7 +879,7 @@ cumo_na_diagonal(int argc, VALUE *argv, VALUE self)
879
879
  idx1 = CUMO_SDX_GET_INDEX(na1->stridx[ax[1]]);
880
880
  // diag_idx = ALLOC_N(size_t, diag_size);
881
881
  diag_idx = (size_t*)cumo_cuda_runtime_malloc(sizeof(size_t)*diag_size);
882
- cumo_na_index_own(na2,nd-2,diag_idx);
882
+ cumo_na_index_own(na2,nd-2,diag_idx,diag_size);
883
883
  cumo_na_diagonal_stride_index_kernel_launch(diag_idx, stride0, idx1, k0, k1, diag_size);
884
884
  } else {
885
885
  stride1 = CUMO_SDX_GET_STRIDE(na1->stridx[ax[1]]);
@@ -58,6 +58,8 @@ TEMPLATE_KERNEL_PARTS = {
58
58
  "rand_norm" => %w[misc],
59
59
  "poly" => %w[misc],
60
60
  "quantize_symmetric" => %w[misc],
61
+ "searchsorted" => %w[misc],
62
+ "add_at" => %w[misc],
61
63
  "unary_ret2" => %w[misc],
62
64
  "sort" => %w[sort],
63
65
  }.freeze
@@ -426,6 +426,12 @@ if is_comparable && !is_object
426
426
  def_method "sort"
427
427
  def_method "sort_index"
428
428
  def_method "median"
429
+ # Cumo::NArray#searchsorted casts its operands before it calls this
430
+ def_method "insertion_points", "searchsorted", private: true
431
+ end
432
+
433
+ unless is_object
434
+ def_method "add_at"
429
435
  end
430
436
 
431
437
  # Math