xobjects 0.7.3__tar.gz → 0.8.0__tar.gz

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 (102) hide show
  1. {xobjects-0.7.3/xobjects.egg-info → xobjects-0.8.0}/PKG-INFO +1 -1
  2. xobjects-0.8.0/tests/test_align.py +249 -0
  3. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_buffer.py +37 -3
  4. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_nplike_arrays.py +24 -0
  5. xobjects-0.8.0/xobjects/_version.py +1 -0
  6. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/array.py +28 -19
  7. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/context.py +4 -4
  8. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/context_cupy.py +49 -2
  9. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/context_pyopencl.py +15 -1
  10. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/headers/atomicadd.h +3 -3
  11. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/raw_union.py +9 -1
  12. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/ref.py +3 -1
  13. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/scalar.py +2 -0
  14. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/settings.py +17 -0
  15. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/string.py +2 -1
  16. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/struct.py +27 -21
  17. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/typeutils.py +5 -3
  18. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/union.py +16 -5
  19. {xobjects-0.7.3 → xobjects-0.8.0/xobjects.egg-info}/PKG-INFO +1 -1
  20. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects.egg-info/SOURCES.txt +0 -39
  21. xobjects-0.7.3/.github/workflows/black.yml +0 -10
  22. xobjects-0.7.3/.gitignore +0 -13
  23. xobjects-0.7.3/.pre-commit-config.yaml +0 -12
  24. xobjects-0.7.3/.readthedocs.yaml +0 -20
  25. xobjects-0.7.3/contributors_and_credits.txt +0 -7
  26. xobjects-0.7.3/docs/Makefile +0 -20
  27. xobjects-0.7.3/docs/architecture/contexts.rst +0 -164
  28. xobjects-0.7.3/docs/architecture/types.rst +0 -179
  29. xobjects-0.7.3/docs/architecture.rst +0 -16
  30. xobjects-0.7.3/docs/conf.py +0 -278
  31. xobjects-0.7.3/docs/index.rst +0 -79
  32. xobjects-0.7.3/docs/make.bat +0 -35
  33. xobjects-0.7.3/docs/quickstart.rst +0 -2
  34. xobjects-0.7.3/docs/reference.rst +0 -8
  35. xobjects-0.7.3/examples/api_def.py +0 -28
  36. xobjects-0.7.3/examples/api_init.py +0 -101
  37. xobjects-0.7.3/examples/capi_example.c +0 -100
  38. xobjects-0.7.3/examples/check_assembly.c +0 -101
  39. xobjects-0.7.3/examples/ex_array_init_perf.py +0 -42
  40. xobjects-0.7.3/examples/ex_cpugpu.py +0 -46
  41. xobjects-0.7.3/examples/ex_nested_ref.py +0 -49
  42. xobjects-0.7.3/examples/ex_ref_cpu.py +0 -52
  43. xobjects-0.7.3/examples/ex_struct_cpu.py +0 -39
  44. xobjects-0.7.3/examples/ex_unionref_cpu.py +0 -49
  45. xobjects-0.7.3/examples/ex_unionref_method.py +0 -120
  46. xobjects-0.7.3/examples/init_soa.py +0 -67
  47. xobjects-0.7.3/examples/issue_with_two_pyopencl_contexts.py +0 -18
  48. xobjects-0.7.3/examples/kernel_basics/kernel_cffi.py +0 -54
  49. xobjects-0.7.3/examples/kernel_basics/kernel_cupy.py +0 -42
  50. xobjects-0.7.3/examples/kernel_basics/kernel_pyopencl.py +0 -48
  51. xobjects-0.7.3/examples/opencl_offsets.py +0 -38
  52. xobjects-0.7.3/examples/simple_kernel.py +0 -59
  53. xobjects-0.7.3/examples/sixtracklib.py +0 -80
  54. xobjects-0.7.3/mktest +0 -1
  55. xobjects-0.7.3/release.sh +0 -20
  56. xobjects-0.7.3/requirements.txt +0 -3
  57. xobjects-0.7.3/tests/__init__.py +0 -4
  58. xobjects-0.7.3/tests/notest_capi.py +0 -208
  59. xobjects-0.7.3/tests/test_align.py +0 -18
  60. xobjects-0.7.3/update_cprght_statement.py +0 -49
  61. xobjects-0.7.3/xobjects/_version.py +0 -1
  62. {xobjects-0.7.3 → xobjects-0.8.0}/Architecture.md +0 -0
  63. {xobjects-0.7.3 → xobjects-0.8.0}/LICENSE +0 -0
  64. {xobjects-0.7.3 → xobjects-0.8.0}/MANIFEST.in +0 -0
  65. {xobjects-0.7.3 → xobjects-0.8.0}/README.md +0 -0
  66. {xobjects-0.7.3 → xobjects-0.8.0}/pyproject.toml +0 -0
  67. {xobjects-0.7.3 → xobjects-0.8.0}/setup.cfg +0 -0
  68. {xobjects-0.7.3 → xobjects-0.8.0}/setup.py +0 -0
  69. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_array.py +0 -0
  70. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_capi.py +0 -0
  71. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_chunk.py +0 -0
  72. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_common.py +0 -0
  73. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_context_opencl.py +0 -0
  74. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_general.py +0 -0
  75. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_hybrid_class.py +0 -0
  76. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_kernel.py +0 -0
  77. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_linked_array.py +0 -0
  78. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_raw_union.py +0 -0
  79. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_ref.py +0 -0
  80. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_scalars.py +0 -0
  81. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_settings.py +0 -0
  82. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_shared_memory.py +0 -0
  83. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_strides.py +0 -0
  84. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_string.py +0 -0
  85. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_struct.py +0 -0
  86. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_to_dict.py +0 -0
  87. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_typeutils.py +0 -0
  88. {xobjects-0.7.3 → xobjects-0.8.0}/tests/test_unionref.py +0 -0
  89. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/__init__.py +0 -0
  90. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/_patch_pyopencl_array.py +0 -0
  91. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/capi.py +0 -0
  92. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/context_cpu.py +0 -0
  93. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/general.py +0 -0
  94. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/headers/common.h +0 -0
  95. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/hybrid_class.py +0 -0
  96. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/linkedarray.py +0 -0
  97. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/specialize_source.py +0 -0
  98. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects/test_helpers.py +0 -0
  99. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects.egg-info/dependency_links.txt +0 -0
  100. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects.egg-info/entry_points.txt +0 -0
  101. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects.egg-info/requires.txt +0 -0
  102. {xobjects-0.7.3 → xobjects-0.8.0}/xobjects.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: xobjects
3
- Version: 0.7.3
3
+ Version: 0.8.0
4
4
  Summary: In-memory serialization and code generator for CPU and GPU
5
5
  Home-page: https://xsuite.readthedocs.io/
6
6
  Download-URL: https://pypi.python.org/pypi/xobjects
@@ -0,0 +1,249 @@
1
+ # copyright ################################# #
2
+ # This file is part of the Xobjects Package. #
3
+ # Copyright (c) CERN, 2021. #
4
+ # ########################################### #
5
+
6
+ import xobjects as xo
7
+ import ctypes
8
+ import numpy as np
9
+ import pytest
10
+
11
+ from xobjects.scalar import Complex64, Complex128
12
+ from xobjects.test_helpers import for_all_test_contexts
13
+
14
+
15
+ @for_all_test_contexts
16
+ def test_create_aligned_objects(test_context):
17
+ for Arr in xo.Float64[3], xo.Float64[16], xo.Float64[17]:
18
+ buff = test_context.new_buffer(10)
19
+ assert buff.default_alignment == test_context.minimum_alignment
20
+ for i in range(4):
21
+ aa = Arr(_buffer=buff, _offset="aligned")
22
+ print(test_context, Arr._size, aa._offset)
23
+ assert aa._offset % test_context.minimum_alignment == 0
24
+
25
+
26
+ @pytest.mark.parametrize(
27
+ "scalar, alignment",
28
+ [
29
+ (xo.UInt8, 1),
30
+ (xo.Int16, 2),
31
+ (xo.Int32, 4),
32
+ (xo.Float64, 8),
33
+ (Complex64, 4),
34
+ (Complex128, 8),
35
+ ],
36
+ )
37
+ def test_type_alignment(scalar, alignment):
38
+ assert scalar._alignment == alignment
39
+ assert scalar[13]._alignment == scalar._alignment
40
+ assert scalar[13]._size == 13 * scalar._size
41
+ assert scalar[:]._alignment == max(8, scalar._alignment)
42
+
43
+
44
+ def test_struct_matches_native_layout():
45
+ class Native(ctypes.Structure):
46
+ _fields_ = [
47
+ ("a", ctypes.c_uint8),
48
+ ("b", ctypes.c_uint8),
49
+ ("c", ctypes.c_int16),
50
+ ("d", ctypes.c_float),
51
+ ("e", ctypes.c_double),
52
+ ("f", ctypes.c_uint8 * 13),
53
+ ("g", ctypes.c_uint8),
54
+ ]
55
+
56
+ class Compact(xo.Struct):
57
+ a = xo.UInt8
58
+ b = xo.UInt8
59
+ c = xo.Int16
60
+ d = xo.Float32
61
+ e = xo.Float64
62
+ f = xo.UInt8[13]
63
+ g = xo.UInt8
64
+
65
+ assert Compact._alignment == ctypes.alignment(Native)
66
+ assert Compact._size == ctypes.sizeof(Native)
67
+ for field in Compact._fields:
68
+ assert field.offset == getattr(Native, field.name).offset
69
+
70
+ values = dict(a=1, b=2, c=3, d=4, e=5, f=list(range(13)), g=6)
71
+ obj = Compact(**values)
72
+ native = Native.from_buffer_copy(
73
+ obj._buffer.to_bytearray(obj._offset, obj._size)
74
+ )
75
+ assert list(native.f) == values["f"]
76
+ assert native.g == 6
77
+
78
+
79
+ @for_all_test_contexts
80
+ def test_nested_complex_alignment(test_context):
81
+ class Inner(xo.Struct):
82
+ flag = xo.UInt8
83
+ small = Complex64
84
+ large = Complex128
85
+ tail = xo.UInt8
86
+
87
+ class Outer(xo.Struct):
88
+ flag = xo.UInt8
89
+ items = Inner[2]
90
+ tail = xo.UInt8
91
+
92
+ assert [ff.offset for ff in Inner._fields] == [0, 4, 16, 32]
93
+ assert Inner._alignment == 8
94
+ assert Inner._size == 40
95
+ assert Outer.items.offset == 8
96
+ assert Outer._alignment == 8
97
+ assert Outer._size == 96
98
+ values = dict(flag=1, small=2 + 3j, large=4 + 5j, tail=6)
99
+ obj = Outer(items=[values, values], _context=test_context)
100
+ for item in obj.items:
101
+ assert item._offset % 8 == 0
102
+ assert item.small == values["small"]
103
+ assert item.large == values["large"]
104
+ assert item.tail == 6
105
+
106
+
107
+ @pytest.mark.parametrize(
108
+ "shape, data_offset", [((None,), 16), ((2, None), 32), ((None, None), 40)]
109
+ )
110
+ @for_all_test_contexts
111
+ def test_dynamic_complex_array_alignment(shape, data_offset, test_context):
112
+ array_type = Complex128[shape]
113
+ values = np.arange(6).reshape((6,) if len(shape) == 1 else (2, 3))
114
+ values = values.astype("complex128") + 2j
115
+ array = array_type(values, _context=test_context)
116
+ assert array_type._data_offset == data_offset
117
+ np.testing.assert_array_equal(array.to_nparray(), values)
118
+ restored = array_type._from_buffer(array._buffer, array._offset)
119
+ np.testing.assert_array_equal(restored.to_nparray(), values)
120
+
121
+
122
+ @for_all_test_contexts
123
+ def test_dynamic_struct_alignment(test_context):
124
+ class Dynamic(xo.Struct):
125
+ tag = xo.UInt8
126
+ tail = xo.UInt8
127
+ text = xo.String
128
+ values = Complex128[:]
129
+
130
+ assert Dynamic._alignment == 8
131
+ assert Dynamic.tag.offset == 8
132
+ assert Dynamic.tail.offset == 9
133
+ assert Dynamic.values.offset == 16 # Int64 offset slot
134
+ assert Dynamic.text.offset == 24
135
+ values = dict(tag=1, tail=2, text="x", values=[3 + 4j])
136
+ obj = Dynamic(**values, _context=test_context)
137
+ assert obj.values._offset - obj._offset == 40
138
+ assert obj._size == 72
139
+ assert obj.text == "x"
140
+ assert obj.values[0] == 3 + 4j
141
+ for array_type in (Dynamic[2], Dynamic[3], Dynamic[:]):
142
+ count = array_type._shape[0] or 3
143
+ array = array_type([values] * count, _context=test_context)
144
+ restored = array_type._from_buffer(array._buffer, array._offset)
145
+ assert isinstance(restored._offsets, np.ndarray)
146
+ for item in restored:
147
+ assert item._offset % 8 == 0
148
+ assert item.values._offset % 8 == 0
149
+ assert item.text == "x"
150
+ assert item.values[0] == 3 + 4j
151
+
152
+
153
+ @pytest.mark.parametrize("default_alignment", [1, 8, 128, 512])
154
+ @pytest.mark.parametrize("offset", [None, "aligned"])
155
+ def test_allocation_honors_type_and_buffer_alignment(
156
+ default_alignment, offset
157
+ ):
158
+ buffer = xo.ContextCpu().new_buffer(1)
159
+ buffer.default_alignment = default_alignment
160
+ xo.UInt8[1](_buffer=buffer)
161
+ obj = Complex128[1]([1 + 2j], _buffer=buffer, _offset=offset)
162
+ assert obj._offset == max(8, default_alignment)
163
+ assert obj[0] == 1 + 2j
164
+
165
+
166
+ @pytest.mark.parametrize("offset", ["packed", 1])
167
+ def test_explicit_offsets_bypass_allocation_alignment(offset):
168
+ buffer = xo.ContextCpu().new_buffer(128)
169
+ buffer.default_alignment = 128
170
+ xo.UInt8[1](_buffer=buffer)
171
+ obj = Complex128[1]([1 + 2j], _buffer=buffer, _offset=offset)
172
+ assert obj._offset == 1
173
+ assert obj[0] == 1 + 2j
174
+
175
+
176
+ @for_all_test_contexts
177
+ def test_first_dynamic_field_alignment(test_context):
178
+ class FirstDynamic(xo.Struct):
179
+ tag = xo.UInt8
180
+ values = Complex128[:]
181
+
182
+ assert FirstDynamic.values.offset == 16
183
+ obj = FirstDynamic(tag=1, values=[2 + 3j], _context=test_context)
184
+ assert obj.values._offset % 8 == 0
185
+ assert obj.values[0] == 2 + 3j
186
+
187
+
188
+ def test_fixed_string_array_stride():
189
+ string_type = xo.String.fixed(10)
190
+ for array_type in (string_type[3], string_type[:]):
191
+ array = array_type([0, 0, 0])
192
+ assert array._strides == (16,)
193
+ for index in range(3):
194
+ assert array._get_offset(index) % 8 == 0
195
+
196
+
197
+ def test_reference_and_union_alignment():
198
+ class ByteStruct(xo.Struct):
199
+ value = xo.UInt8
200
+
201
+ class WideUnion(xo.RawUnion):
202
+ byte = xo.UInt8
203
+ complex = Complex128
204
+
205
+ assert xo.Ref[ByteStruct]._alignment == 8
206
+ assert xo.UnionRef._alignment == 8
207
+ assert xo.String._alignment == 8
208
+ assert WideUnion._alignment == 8
209
+ assert WideUnion._size == 16
210
+
211
+
212
+ @for_all_test_contexts
213
+ def test_compact_struct_generated_accessors(test_context):
214
+ class CompactKernel(xo.Struct):
215
+ a = xo.UInt8
216
+ b = xo.Int16
217
+ bytes = xo.UInt8[3]
218
+ tail = xo.UInt8
219
+
220
+ source = """
221
+ /*gpukern*/ void check_compact_accessors(
222
+ CompactKernel obj, /*gpuglmem*/ int64_t* result) {
223
+ result[0] = CompactKernel_get_b(obj);
224
+ result[1] = CompactKernel_get_bytes(obj, 2);
225
+ CompactKernel_set_tail(obj, 7);
226
+ }
227
+ """
228
+ test_context.add_kernels(
229
+ sources=[source],
230
+ kernels={
231
+ "check_compact_accessors": xo.Kernel(
232
+ args=[
233
+ xo.Arg(CompactKernel, name="obj"),
234
+ xo.Arg(xo.Int64, pointer=True, name="result"),
235
+ ],
236
+ n_threads=1,
237
+ ),
238
+ },
239
+ )
240
+ obj = CompactKernel(
241
+ a=1, b=2, bytes=[3, 4, 5], tail=6, _context=test_context
242
+ )
243
+ assert CompactKernel._size == 8
244
+ result = test_context.zeros(2, dtype=np.int64)
245
+ test_context.kernels.check_compact_accessors(obj=obj, result=result)
246
+ np.testing.assert_array_equal(
247
+ test_context.nparray_from_context_array(result), [2, 5]
248
+ )
249
+ assert obj.tail == 7
@@ -62,6 +62,19 @@ def test_new_buffer(test_context):
62
62
  _ = test_context.new_buffer(capacity=200)
63
63
 
64
64
 
65
+ @for_all_test_contexts
66
+ def test_new_buffer_is_zeroed(test_context):
67
+ buff = test_context.new_buffer(capacity=200)
68
+ assert buff.to_bytearray(0, 200) == bytearray(200)
69
+
70
+ # The capacity added when growing must be zeroed too, while the existing
71
+ # data is kept.
72
+ buff.update_from_buffer(0, b"\xff" * 200)
73
+ buff.grow(300)
74
+ assert buff.to_bytearray(0, 200) == b"\xff" * 200
75
+ assert buff.to_bytearray(200, 300) == bytearray(300)
76
+
77
+
65
78
  @for_all_test_contexts
66
79
  def test_read_write(test_context):
67
80
  buff = test_context.new_buffer()
@@ -130,14 +143,35 @@ def test_free(test_context):
130
143
  @for_all_test_contexts
131
144
  def test_grow(test_context):
132
145
  ch = Check(test_context, 200)
146
+ alignment = ch.buffer.default_alignment
147
+
148
+ def aligned(offset):
149
+ return -(-offset // alignment) * alignment
150
+
151
+ def grown(capacity, size):
152
+ # Without grow_step, a full buffer grows by its own capacity, or by
153
+ # enough to fit an aligned allocation of `size`, whichever is larger.
154
+ return capacity + max(capacity, size + alignment - 1)
155
+
133
156
  st = ch.new_string(150)
157
+ assert st == 0
158
+
159
+ # The second string never fits after the first one in 200 bytes.
134
160
  st = ch.new_string(60)
135
161
  ch.check()
136
- assert ch.buffer.capacity == 400
162
+ capacity = grown(200, 60)
163
+ assert st == aligned(150)
164
+ assert ch.buffer.capacity == capacity
137
165
  assert ch.buffer.chunks[0].start == st + 60
138
- assert ch.buffer.chunks[0].end == 400
166
+ assert ch.buffer.chunks[0].end == capacity
167
+
168
+ # The third string is larger than the whole buffer.
169
+ free_start = st + 60
139
170
  st = ch.new_string(500)
140
- assert ch.buffer.capacity == 900 + ch.buffer.default_alignment - 1
171
+ assert aligned(free_start) + 500 > capacity
172
+ capacity = grown(capacity, 500)
173
+ assert st == aligned(free_start)
174
+ assert ch.buffer.capacity == capacity
141
175
  ch.check()
142
176
 
143
177
 
@@ -16,6 +16,30 @@ def test_type(test_context):
16
16
  assert isinstance(a, test_context.nplike_array_type)
17
17
 
18
18
 
19
+ @for_all_test_contexts
20
+ @pytest.mark.parametrize(
21
+ "layout",
22
+ ["column", "reversed_column", "strided_matrix", "C", "F", "scalar"],
23
+ )
24
+ def test_nparray_to_context_array_layout(test_context, layout):
25
+ base = np.arange(24, dtype=np.float64).reshape(6, 4)
26
+ values = {
27
+ "column": base[:, 0],
28
+ "reversed_column": base[::-1, 0],
29
+ "strided_matrix": base[::2, ::2],
30
+ "C": base,
31
+ "F": np.asfortranarray(base),
32
+ "scalar": np.array(3.0),
33
+ }[layout]
34
+
35
+ transferred = test_context.nparray_to_context_array(values)
36
+ restored = test_context.nparray_from_context_array(transferred)
37
+
38
+ assert restored.shape == values.shape
39
+ assert restored.dtype == values.dtype
40
+ np.testing.assert_array_equal(restored, values)
41
+
42
+
19
43
  @for_all_test_contexts
20
44
  def test_ffts(test_context):
21
45
  if "Pyopencl" in str(test_context):
@@ -0,0 +1 @@
1
+ __version__ = "0.8.0"
@@ -12,11 +12,11 @@ from .typeutils import (
12
12
  allocate_on_buffer,
13
13
  Info,
14
14
  is_integer,
15
- _to_slot_size,
16
15
  default_conf,
17
16
  )
18
17
  from .ref import is_ref, is_unionref
19
18
  from .scalar import Int64, is_scalar
19
+ from .context import _align
20
20
 
21
21
  log = logging.getLogger(__name__)
22
22
 
@@ -186,7 +186,8 @@ class MetaArray(type):
186
186
  data["_is_static_type"] = False
187
187
  else:
188
188
  data["_is_static_type"] = True
189
- static_size = _itemtype._size
189
+ static_size = _align(_itemtype._size, _itemtype._alignment)
190
+ data["_itemsize"] = static_size
190
191
  if "_shape" not in data:
191
192
  raise ValueError(f"No shape defined for {cls}")
192
193
  if "_order" not in data:
@@ -213,14 +214,18 @@ class MetaArray(type):
213
214
  )
214
215
 
215
216
  if data["_is_static_shape"] and data["_is_static_type"]:
216
- _size = _itemtype._size
217
+ alignment = _itemtype._alignment
218
+ _size = static_size
217
219
  for d in _shape:
218
220
  _size *= d
219
- _size = _to_slot_size(_size)
220
221
  else:
222
+ alignment = max(8, _itemtype._alignment)
221
223
  _size = None
222
224
  _data_offset += 8 # space for dynamic size
225
+ if data["_is_static_type"]:
226
+ _data_offset = _align(_data_offset, _itemtype._alignment)
223
227
 
228
+ data["_alignment"] = alignment
224
229
  data["_size"] = _size
225
230
  data["_data_offset"] = _data_offset
226
231
  # need to applied to derived classes as well
@@ -256,6 +261,7 @@ class MetaArray(type):
256
261
 
257
262
 
258
263
  class Array(metaclass=MetaArray):
264
+ _alignment: int
259
265
  _shape: tuple
260
266
  _order: tuple
261
267
  _strides: tuple
@@ -326,8 +332,8 @@ class Array(metaclass=MetaArray):
326
332
  offset = 0
327
333
  for idx in iter_index(shape, order):
328
334
  offsets[idx] = offset
329
- offset += cls._itemtype._size
330
- assert size == _to_slot_size(offset)
335
+ offset += cls._itemsize
336
+ assert size == offset
331
337
  else: # handling other cases
332
338
  offset = 8 # space for size data
333
339
  # determine shape and order
@@ -379,19 +385,15 @@ class Array(metaclass=MetaArray):
379
385
  offset += len(shape) * 8 # space for strides
380
386
  order = mk_order(cls._order, shape)
381
387
  if cls._is_static_type:
382
- strides = get_strides(shape, order, cls._itemtype._size)
388
+ strides = get_strides(shape, order, cls._itemsize)
383
389
  else:
384
390
  strides = get_strides(shape, order, 8)
385
391
  items = np.prod(shape)
386
392
 
387
393
  # needs items, order, shape, value
388
394
  if cls._is_static_type:
389
- # offsets = np.empty(shape, dtype="int64")
390
- # for idx in iter_index(shape, order):
391
- # offsets[idx] = offset
392
- # offset += cls._itemtype._size
393
- offset += cls._itemtype._size * items
394
- size = _to_slot_size(offset)
395
+ offset = cls._data_offset + cls._itemsize * items
396
+ size = _align(offset, cls._alignment)
395
397
 
396
398
  else:
397
399
  # args must be an array of correct dimensions
@@ -399,9 +401,10 @@ class Array(metaclass=MetaArray):
399
401
  offset += items * 8
400
402
  for idx in iter_index(shape, order):
401
403
  extra[idx] = cls._itemtype._inspect_args(value[idx])
404
+ offset = _align(offset, cls._itemtype._alignment)
402
405
  offsets[idx] = offset
403
406
  offset += extra[idx].size
404
- size = _to_slot_size(offset)
407
+ size = _align(offset, cls._alignment)
405
408
  info.offsets = offsets
406
409
  info.extra = extra
407
410
 
@@ -439,7 +442,7 @@ class Array(metaclass=MetaArray):
439
442
  coffset += 8
440
443
  else:
441
444
  if cls._is_static_type:
442
- strides = (cls._itemtype._size,)
445
+ strides = (cls._itemsize,)
443
446
  else:
444
447
  strides = (8,)
445
448
  self._strides = tuple(strides)
@@ -447,7 +450,11 @@ class Array(metaclass=MetaArray):
447
450
  shape = cls._shape
448
451
  if not cls._is_static_type:
449
452
  items = np.prod(shape)
450
- self._offsets = Int64._array_from_buffer(buffer, coffset, items)
453
+ # Offsets are host metadata, also when the payload lives on a GPU.
454
+ # Device scalars must not become offsets used to slice the byte buffer.
455
+ self._offsets = buffer.context.nparray_from_context_array(
456
+ Int64._array_from_buffer(buffer, coffset, items)
457
+ )
451
458
  return self
452
459
 
453
460
  @classmethod
@@ -473,6 +480,8 @@ class Array(metaclass=MetaArray):
473
480
  if not cls._is_static_type:
474
481
  Int64._array_to_buffer(buffer, coffset, info.offsets)
475
482
  coffset += 8 * len(info.offsets)
483
+ else:
484
+ coffset = offset + cls._data_offset
476
485
  if hasattr(cls._itemtype, "_dtype") and hasattr(
477
486
  value, "dtype"
478
487
  ): # is a scalar type:
@@ -495,7 +504,7 @@ class Array(metaclass=MetaArray):
495
504
  ioffset = offset + cls._data_offset
496
505
  for idx in range(info.items):
497
506
  cls._itemtype._to_buffer(buffer, ioffset, value, None)
498
- ioffset += cls._itemtype._size
507
+ ioffset += cls._itemsize
499
508
  else:
500
509
  for idx in iter_index(info.shape, cls._order):
501
510
  cls._itemtype._to_buffer(
@@ -513,7 +522,7 @@ class Array(metaclass=MetaArray):
513
522
  cls._itemtype._to_buffer(
514
523
  buffer, ioffset, value[idx], info=None
515
524
  )
516
- ioffset += cls._itemtype._size
525
+ ioffset += cls._itemsize
517
526
  else:
518
527
  for idx in iter_index(info.shape, cls._order):
519
528
  cls._itemtype._to_buffer(
@@ -529,7 +538,7 @@ class Array(metaclass=MetaArray):
529
538
  info = cls._inspect_args(*args)
530
539
 
531
540
  self._buffer, self._offset = allocate_on_buffer(
532
- info.size, _context, _buffer, _offset
541
+ info.size, _context, _buffer, _offset, alignment=cls._alignment
533
542
  )
534
543
 
535
544
  cls._to_buffer(self._buffer, self._offset, info.value, info)
@@ -143,7 +143,7 @@ def _concatenate_sources(sources, apply_to_source=()):
143
143
 
144
144
 
145
145
  def _align(offset, alignment):
146
- "round to nearest multiple of 8"
146
+ "Round up to a multiple of the power-of-two alignment."
147
147
  return (offset + alignment - 1) & (-alignment)
148
148
 
149
149
 
@@ -493,11 +493,11 @@ class XBuffer(ABC):
493
493
  def _make_context(self):
494
494
  "return a default context"
495
495
 
496
- def allocate(self, size, align=True):
496
+ def allocate(self, size, align=True, alignment=1):
497
497
  # find available free slot
498
498
  # and update free slot if exists
499
499
  if align:
500
- alignment = self.default_alignment
500
+ alignment = max(self.default_alignment, alignment)
501
501
  else:
502
502
  alignment = 1
503
503
  # sizepa = size + alignment - 1
@@ -520,7 +520,7 @@ class XBuffer(ABC):
520
520
  self.grow(self.capacity)
521
521
 
522
522
  # try again
523
- return self.allocate(size, align=align)
523
+ return self.allocate(size, align=align, alignment=alignment)
524
524
 
525
525
  def grow(self, capacity):
526
526
  """
@@ -375,7 +375,7 @@ typedef unsigned int uint32_t; //only_for_context cuda
375
375
  typedef unsigned short uint16_t; //only_for_context cuda
376
376
  typedef unsigned char uint8_t; //only_for_context cuda
377
377
 
378
- #if defined(__CUDACC_RTC__) || defined(__HIPCC_RTC__)
378
+ #if defined(__CUDACC_RTC__)
379
379
  typedef signed long long int64_t;
380
380
  typedef unsigned long long uint64_t;
381
381
  #endif
@@ -403,6 +403,11 @@ class ContextCupy(XContext):
403
403
  ``xobjects.settings.cuda_fast_compile = False``, or equivalently the
404
404
  environment variable ``XSUITE_CUDA_FAST_COMPILE=0``, to disable it.
405
405
 
406
+ On ROCm/HIP, ``xobjects.settings.rocm_fast_kernels`` (environment variable
407
+ ``XSUITE_ROCM_FAST_KERNELS=1``) force-inlines all device functions. This
408
+ makes tracking kernels significantly faster with unchanged results, at the
409
+ cost of much slower compilation. It is disabled by default.
410
+
406
411
  Args:
407
412
  default_block_size (int):
408
413
  CUDA thread size that is used by default
@@ -538,7 +543,12 @@ class ContextCupy(XContext):
538
543
  # NVRTC (default): add NVRTC-specific flags
539
544
  nvrtc_args = (*extra_compile_args,)
540
545
  fast_compile = settings.cuda_fast_compile
541
- if nvrtc and nvrtc.getVersion() >= (12, 9):
546
+ if cupy.cuda.runtime.is_hip:
547
+ # On ROCm, CuPy's nvrtc module is hiprtc and getVersion()
548
+ # returns the HIP version, so the NVRTC version check below
549
+ # does not apply (and hiprtc has no --Ofast-compile).
550
+ pass
551
+ elif nvrtc and nvrtc.getVersion() >= (12, 9):
542
552
  # If supported, skip prohibitively heavy optimisations (e.g.
543
553
  # involving cloning). This it at the expense of <20%
544
554
  # runtime performance, but gain of a lot of compile time and memory.
@@ -550,6 +560,43 @@ class ContextCupy(XContext):
550
560
  "Compilation time and memory usage might be high: if this is a problem, please update CUDA nvrtc."
551
561
  )
552
562
 
563
+ if cupy.cuda.runtime.is_hip:
564
+ # Without __launch_bounds__, HIP assumes kernels may be
565
+ # launched with up to 1024 threads per block, which
566
+ # caps each lane at 128 registers and makes large kernels
567
+ # spill heavily to scratch memory (~2x slower than
568
+ # OpenCL, which defaults to 256). All kernels here are
569
+ # launched with default_block_size, so we tell the compiler.
570
+ nvrtc_args += (
571
+ f"--gpu-max-threads-per-block={self.default_block_size}",
572
+ )
573
+
574
+ if settings.rocm_fast_kernels:
575
+ # Force inlining of every device function. Real calls on
576
+ # AMDGPU save/restore registers through scratch memory;
577
+ # removing them can make kernels significantly faster with
578
+ # bit-identical results, but compilation is much slower.
579
+ # This is done using internal llvm options.
580
+ warnings.warn(
581
+ "XSUITE_ROCM_FAST_KERNELS is enabled: all device "
582
+ "functions are force-inlined. Kernels run faster, but "
583
+ "compilation will be much slower (minutes instead of "
584
+ "seconds for large lines) and use more memory. "
585
+ "Compiled kernels are cached, so this cost is paid "
586
+ "once per kernel."
587
+ )
588
+ nvrtc_args += (
589
+ "-mllvm",
590
+ "-amdgpu-early-inline-all=true",
591
+ "-mllvm",
592
+ "-amdgpu-function-calls=false",
593
+ )
594
+ elif settings.rocm_fast_kernels:
595
+ warnings.warn(
596
+ "XSUITE_ROCM_FAST_KERNELS only applies to CuPy on "
597
+ "ROCm/HIP and is ignored on CUDA."
598
+ )
599
+
553
600
  if self.cuda_compute_capability is None:
554
601
  module = cupy.RawModule(
555
602
  code=specialized_source,
@@ -281,6 +281,10 @@ class ContextPyopencl(XContext):
281
281
  Returns:
282
282
  pyopencl.array.Array:The same array copied to the device.
283
283
  """
284
+ # PyOpenCL requires contiguous host input, including for column views
285
+ # and reversed slices. Preserve already contiguous C/F layouts.
286
+ if not (arr.flags.c_contiguous or arr.flags.f_contiguous):
287
+ arr = np.ascontiguousarray(arr)
284
288
  dev_arr = cla.to_device(self.queue, arr)
285
289
  return dev_arr
286
290
 
@@ -369,9 +373,16 @@ class BufferPyopencl(XBuffer):
369
373
  return ContextPyopencl()
370
374
 
371
375
  def _new_buffer(self, capacity):
372
- return cl.Buffer(
376
+ buffer = cl.Buffer(
373
377
  self.context.context, cl.mem_flags.READ_WRITE, capacity
374
378
  )
379
+ # OpenCL buffers are not initialised on allocation. Zero them, like
380
+ # the CPU and CUDA buffers, so that unused bytes (e.g. padding between
381
+ # struct fields) do not contain leftover data.
382
+ cl.enqueue_fill_buffer(
383
+ self.context.queue, buffer, np.uint8(0), 0, capacity
384
+ )
385
+ return buffer
375
386
 
376
387
  def copy_from(self, source, src_offset, dest_offset, byte_count):
377
388
  # Does not pass through cpu if it can
@@ -460,6 +471,9 @@ class BufferPyopencl(XBuffer):
460
471
  return self.to_nplike(offset, dtype, shape).get()
461
472
 
462
473
  def update_from_nplike(self, offset, dest_dtype, arr):
474
+ if arr.nbytes == 0:
475
+ # Empty pyopencl arrays have no backing buffer (base_data is None)
476
+ return
463
477
  if arr.dtype != dest_dtype:
464
478
  arr = arr.astype(dest_dtype)
465
479
  self.update_from_native(offset, arr.base_data, arr.offset, arr.nbytes)
@@ -115,9 +115,9 @@ GPUFUN double atomicAdd(GPUGLMEM double *addr, double val) { return atomic
115
115
  // -------------------------------------------
116
116
  #if defined(XO_CONTEXT_CUDA)
117
117
  // CUDA compiler may not have <stdint.h>, so define the types if needed.
118
- #if defined(__CUDACC_RTC__) || defined(__HIPCC_RTC__)
119
- // NVRTC and HIPRTC (CuPy RawModule default) can’t see <stdint.h>
120
- // We detect via __CUDACC_RTC__ (Nvidia) or __HIPCC_RTC__ (ROCm)
118
+ #if defined(__CUDACC_RTC__)
119
+ // NVRTC (CuPy RawModule default) can’t see <stdint.h>
120
+ // We detect via __CUDACC_RTC__. HIPRTC (AMD) appears to have the right defs
121
121
  typedef signed char int8_t;
122
122
  typedef short int16_t;
123
123
  typedef int int32_t;