-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathbase.py
More file actions
1216 lines (1089 loc) · 50.1 KB
/
Copy pathbase.py
File metadata and controls
1216 lines (1089 loc) · 50.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
from functools import lru_cache
from operator import getitem
from types import BuiltinFunctionType, ModuleType
import numpy as np
from ... import _STANDARD_OPERATOR_NAMES, backend, op
from ...dtypes import BOOL, INT8, UINT64, _supports_complex, lookup_dtype
from ...exceptions import UdfParseError, check_status_carg
from .. import _has_numba, _supports_udfs, ffi, lib
from ..dtypes import _sample_values
from ..expr import InfixExprBase
from ..utils import output_type
if _has_numba:
import numba
from numba import NumbaError
else:
NumbaError = TypeError
UNKNOWN_OPCLASS = "UnknownOpClass"
# These now live as e.g. `gb.unary.ss.positioni`
# Deprecations such as `gb.unary.positioni` will be removed in 2023.9.0 or later.
_SS_OPERATORS = {
# unary
"erf", # scipy.special.erf
"erfc", # scipy.special.erfc
"frexpe", # np.frexp[1]
"frexpx", # np.frexp[0]
"lgamma", # scipy.special.loggamma
"tgamma", # scipy.special.gamma
# Positional
# unary
"positioni",
"positioni1",
"positionj",
"positionj1",
# binary
"firsti",
"firsti1",
"firstj",
"firstj1",
"secondi",
"secondi1",
"secondj",
"secondj1",
# semiring
"any_firsti",
"any_firsti1",
"any_firstj",
"any_firstj1",
"any_secondi",
"any_secondi1",
"any_secondj",
"any_secondj1",
"max_firsti",
"max_firsti1",
"max_firstj",
"max_firstj1",
"max_secondi",
"max_secondi1",
"max_secondj",
"max_secondj1",
"min_firsti",
"min_firsti1",
"min_firstj",
"min_firstj1",
"min_secondi",
"min_secondi1",
"min_secondj",
"min_secondj1",
"plus_firsti",
"plus_firsti1",
"plus_firstj",
"plus_firstj1",
"plus_secondi",
"plus_secondi1",
"plus_secondj",
"plus_secondj1",
"times_firsti",
"times_firsti1",
"times_firstj",
"times_firstj1",
"times_secondi",
"times_secondi1",
"times_secondj",
"times_secondj1",
}
def _hasop(module, name):
return (
name in module.__dict__
or name in module._delayed
or name in getattr(module, "_deprecated", ())
)
def _bool_to_int8(dtype):
"""Return INT8 if ``dtype`` is BOOL, else the dtype unchanged.
Numba can't compile cfuncs that read or write ``CPointer(boolean)``
(errors like ``cannot store i1 to i8*`` / ``cond is not i1: i8``); see
numba/numba#5395. Routing BOOL through INT8 sidesteps that; GraphBLAS
coerces back at the cfunc boundary.
MAINT 2026-05-24: still hits on Numba 0.65. Re-test periodically and
drop the INT8 routing when upstream is fixed.
"""
return INT8 if dtype == BOOL else dtype
class OpPath:
def __init__(self, parent, name):
self._parent = parent
self._name = name
self._delayed = {}
self._delayed_commutes_to = {}
def __getattr__(self, key):
if key in self._delayed:
func, kwargs = self._delayed.pop(key)
return func(**kwargs)
self.__getattribute__(key) # raises
def _call_op(op, left, right=None, thunk=None, **kwargs):
if right is None and thunk is None:
if isinstance(left, InfixExprBase):
# op(A & B), op(A | B), op(A @ B)
return getattr(left.left, f"_{left.method_name}")(
left.right, op, is_infix=True, **kwargs
)
if find_opclass(op)[1] == "Semiring":
raise TypeError(
f"Bad type when calling {op!r}. Got type: {type(left)}.\n"
f"Expected an infix expression, such as: {op!r}(A @ B)"
)
raise TypeError(
f"Bad type when calling {op!r}. Got type: {type(left)}.\n"
"Expected an infix expression or an apply with a Vector or Matrix and a scalar:\n"
f" - {op!r}(A & B)\n"
f" - {op!r}(A, 1)\n"
f" - {op!r}(1, A)"
)
# op(A, 1) -> apply (or select if thunk provided)
from ..matrix import Matrix, TransposedMatrix
from ..vector import Vector
if (left_type := output_type(left)) in {Vector, Matrix, TransposedMatrix}:
if thunk is not None:
return left.select(op, thunk=thunk, **kwargs)
return left.apply(op, right=right, **kwargs)
if (right_type := output_type(right)) in {Vector, Matrix, TransposedMatrix}:
return right.apply(op, left=left, **kwargs)
from ..scalar import Scalar, _as_scalar
if left_type is Scalar:
if thunk is not None:
return left.select(op, thunk=thunk, **kwargs)
return left.apply(op, right=right, **kwargs)
if right_type is Scalar:
return right.apply(op, left=left, **kwargs)
try:
left_scalar = _as_scalar(left, is_cscalar=False)
except Exception:
pass
else:
if thunk is not None:
return left_scalar.select(op, thunk=thunk, **kwargs)
return left_scalar.apply(op, right=right, **kwargs)
raise TypeError(
f"Bad types when calling {op!r}. Got types: {type(left)}, {type(right)}.\n"
"Expected an infix expression or an apply with a Vector or Matrix and a scalar:\n"
f" - {op!r}(A & B)\n"
f" - {op!r}(A, 1)\n"
f" - {op!r}(1, A)"
)
if _has_numba:
def _finalize_udt_op(parent_op, dtype, dtype2, ret_type, wrapper, wrapper_sig, typed_user_cls):
"""Compile the cfunc, allocate the ``GrB`` op, wrap it, and cache it.
Shared tail for ``_compile_udt`` in UnaryOp / BinaryOp / IndexUnaryOp /
SelectOp. Looks up the SuiteSparse handle type and ``_new`` symbol
from ``typed_user_cls.opclass``. ``dtype2`` is ``None`` for unary
ops; the rest pass both. Returns the cached ``TypedUser*Op``.
"""
wrapper = numba.cfunc(wrapper_sig, nopython=True, error_model="numpy")(wrapper)
c_typename = _GB_OBJ_C_TYPENAME[typed_user_cls.opclass]
error_label = c_typename.removeprefix("GrB_").removeprefix("GxB_")
gb_obj = ffi.new(f"{c_typename}*")
new_func = getattr(lib, f"{c_typename}_new")
if dtype2 is None:
check_status_carg(
new_func(gb_obj, wrapper.cffi, ret_type._carg, dtype._carg),
error_label,
gb_obj[0],
)
op = typed_user_cls(parent_op, parent_op.name, dtype, ret_type, gb_obj[0])
key = dtype
else:
check_status_carg(
new_func(gb_obj, wrapper.cffi, ret_type._carg, dtype._carg, dtype2._carg),
error_label,
gb_obj[0],
)
op = typed_user_cls(
parent_op, parent_op.name, dtype, ret_type, gb_obj[0], dtype2=dtype2
)
key = (dtype, dtype2)
parent_op._udt_types[key] = ret_type
parent_op._udt_ops[key] = op
return op
def _compile_udf_for_udt(numba_func, sig, *, op_kind, op_name, dtypes):
"""Compile ``sig`` and re-raise Numba compilation errors as ``UdfParseError``.
Catches the full ``NumbaError`` hierarchy (TypingError, LoweringError,
UnsupportedError, ...) so any compilation failure produces a
single-line UDT diagnostic.
"""
try:
numba_func.compile(sig)
except NumbaError as exc:
dtypes_str = ", ".join(str(d) for d in dtypes)
snippet = _summarize_numba_typing_error(exc)
raise UdfParseError(
f"{op_kind}.{op_name} does not work with ({dtypes_str}): {snippet}"
) from exc
# Numba prefixes its actionable diagnostic line with one of these.
_NUMBA_DIAG_PREFIXES = (
"No implementation of function",
"No conversion from",
"Field ",
"Cannot infer",
"Operator Overload",
"Invalid use of",
"use of undeclared",
"Untyped global",
)
_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
def _summarize_numba_typing_error(exc):
"""Pull the most actionable lines out of a Numba TypingError.
Numba's "No implementation of function ... found for signature:"
diagnostic puts the signature on the line *below* the prefix; the
signature is the actionable part. When the matched line ends with a
``:``, append the next non-empty line so the user sees both.
"""
lines = [_ANSI_RE.sub("", line).strip() for line in str(exc).splitlines()]
for i, line in enumerate(lines):
if line.startswith(_NUMBA_DIAG_PREFIXES):
if line.endswith(":"):
for follow in lines[i + 1 :]:
if follow:
return f"{line} {follow}"
return line
for line in lines:
if line:
return line
return "Numba could not compile the function for these input types"
def _resolve_udt_return_type(numba_ret_type, *dtypes):
"""Resolve a Numba return type to a DataType, matching Tuple returns to an input UDT.
When a UDF returns a tuple, Numba infers ``Tuple(...)`` rather than a
Record type. Match by field count, preferring a candidate whose field
types align with the Tuple's element types.
"""
try:
return lookup_dtype(numba_ret_type)
except (ValueError, TypeError):
pass
if isinstance(numba_ret_type, numba.core.types.BaseTuple):
from .udt_utils import _iter_record_leaves
n = len(numba_ret_type.types)
def _leaves(d):
"""Yield ``(python_path, c_path, leaf_dtype)`` for a record UDT."""
return list(_iter_record_leaves(d.np_type))
# Match by total leaf count (flat for shallow records, total
# leaves across nesting for nested records).
same_arity = [
d
for d in dtypes
if d._is_udt and d.np_type.names is not None and len(_leaves(d)) == n
]
# Prefer a UDT whose leaf types match the tuple elements element-wise.
for d in same_arity:
leaf_dtypes = [leaf for _py, _c, leaf in _leaves(d)]
try:
expected = [lookup_dtype(t).numba_type for t in leaf_dtypes]
except (ValueError, TypeError):
continue
if all(et == tt for et, tt in zip(expected, numba_ret_type.types, strict=True)):
return d
# No perfect match; fall back to the first arity-compatible UDT.
if same_arity:
return same_arity[0]
# Tuple return whose arity matches no input UDT: most likely the
# user is returning the wrong number of fields. List the candidate
# arities so the fix is obvious.
record_arities = sorted(
{len(_leaves(d)) for d in dtypes if d._is_udt and d.np_type.names is not None}
)
if record_arities:
expected = " or ".join(str(a) for a in record_arities)
raise UdfParseError(
f"UDT UDF returned a tuple of length {n}; expected {expected} "
f"to match one of the input record UDTs."
)
# All UDT inputs are array UDTs. Tuples don't map to those: the
# function should return a numpy array of the right shape (or a
# scalar) instead.
array_inputs = [d for d in dtypes if d._is_udt and d.np_type.subdtype is not None]
if array_inputs:
shape = array_inputs[0].np_type.subdtype[1]
raise UdfParseError(
f"UDT UDF returned a tuple of length {n}, but inputs are array UDTs of "
f"shape {shape}. Return a numpy array (e.g., ``np.array(...)``) or a "
f"scalar; tuple returns are only matched to record UDTs."
)
elif isinstance(numba_ret_type, numba.core.types.Array):
# A UDF over an array UDT may build its result (``x + y``) instead
# of returning an operand. Numba types that as a plain Array, which
# ``lookup_dtype`` doesn't recognize, so match it back to an array
# UDT input by base element type and dimensionality.
candidates = [
d
for d in dtypes
if d._is_udt
and d.np_type.subdtype is not None
and d.numba_type.dtype == numba_ret_type.dtype
and len(d.numba_type.shape) == numba_ret_type.ndim
]
# An Array type carries ``ndim`` but not its extents, so operands
# that differ only in length are indistinguishable here. Guessing
# would hand SuiteSparse an element of the wrong size, so say so.
# Compare the UDTs rather than their shapes: a flat ``FP64[2, 3]``
# and a layered ``FP64[3][2]`` are separate DataTypes with separate
# GrB_Type handles, yet Numba collapses both to the same shape.
unique = []
for d in candidates:
if not any(d is seen for seen in unique):
unique.append(d)
if len(unique) > 1:
raise UdfParseError(
f"UDT UDF returned {numba_ret_type!r}, which matches more than one "
f"input array UDT ({', '.join(str(d) for d in unique)}). "
f"Return one of the operands, or make the operands the same type."
)
if unique:
return unique[0]
# An array UDT went in and an array came out, but not one that
# fits: name the mismatch rather than fall through to the generic
# "unsupported type", whose advice the user already followed.
array_inputs = [d for d in dtypes if d._is_udt and d.np_type.subdtype is not None]
if array_inputs:
d = array_inputs[0]
nested = d.numba_type
raise UdfParseError(
f"UDT UDF returned {numba_ret_type!r}, which matches no input array "
f"UDT: {d} elements are {nested.dtype} with shape {nested.shape}. "
f"Return an array of that dtype and rank, or one of the operands."
)
raise UdfParseError(
f"UDT UDF returned an unsupported type {numba_ret_type!r}. "
f"Return a scalar, a tuple matching a record UDT's fields, or a numpy array "
f"matching an array UDT's shape."
)
def _array_udt_view(dtype):
"""Return ``(base_element_numba_type, shape)`` for an array UDT.
Array UDTs are addressed as a ``carray`` over their base elements, in
the UDT's declared shape, rather than as Numba's ``NestedArray``. Numba
models a ``NestedArray`` *value* as an array descriptor (data pointer,
shape, strides, ...), so loading or storing one through a ``CPointer``
moves the descriptor rather than the element payload, corrupting
whatever follows it (and overrunning the element outright once the
descriptor is the wider of the two).
Read from ``numba_type`` rather than ``np_type.subdtype`` so this
agrees with the type the UDF was compiled against: numpy keeps nested
subarray dtypes layered, e.g. ``FP64[5]`` inside ``[6]`` stays
``(dtype(('<f8', (5,))), (6,))``, while Numba collapses the same dtype
to ``nestedarray(float64, (6, 5))``.
"""
nested = dtype.numba_type
return nested.dtype, nested.shape
def _input_operand(dtype, var):
"""Return ``(setup_line, deref_expr, ptr_arg_type)`` for one input operand.
- ``setup_line`` is the optional ``var = numba.carray(var_ptr, n)`` line
to add to the wrapper body (empty for non-UDT cases).
- ``deref_expr`` is the value to pass to ``numba_func`` for this operand.
- ``ptr_arg_type`` is the Numba ``CPointer(...)`` type for the wrapper signature.
"""
nt = numba.types
if dtype._is_udt:
if dtype.np_type.subdtype is None:
return (
f" {var} = numba.carray({var}_ptr, 1)\n",
f"{var}[0]",
nt.CPointer(dtype.numba_type),
)
base_numba, shape = _array_udt_view(dtype)
return (
f" {var} = numba.carray({var}_ptr, {shape})\n",
var,
nt.CPointer(base_numba),
)
if dtype == BOOL:
# Numba can't compile bool ptrs (numba/numba#5395); expose them
# as int8 and cast on deref.
# MAINT 2026-05-24: still hits on Numba 0.65; re-test periodically.
return "", f"bool({var}_ptr[0])", nt.CPointer(INT8.numba_type)
return "", f"{var}_ptr[0]", nt.CPointer(dtype.numba_type)
def _output_handler(return_type, numba_ret_type):
"""Return ``(setup_line, ret_ptr_type, write_kind, write_info)``.
``write_kind`` is ``"record_fields"`` when the UDF returns a Tuple to be
unpacked into a record output, ``"array_elements"`` for an array UDT
output, otherwise ``"direct"``. ``write_info`` is the tuple-unpack field
tuple for ``"record_fields"`` and a ``(BL, BR, zname)`` 3-tuple for
``"direct"``; ``"array_elements"`` needs none, since ``setup_line``
already binds ``z`` to the right shape.
"""
nt = numba.types
ztype = INT8 if return_type == BOOL else return_type
ret_ptr_type = nt.CPointer(ztype.numba_type)
if (
numba_ret_type is not None
and isinstance(numba_ret_type, numba.core.types.BaseTuple)
and return_type._is_udt
and return_type.np_type.names is not None
):
# ``write_info`` pairs each leaf field's Python access path
# (``"['a']"`` for flat, ``"['outer']['inner_a']"`` for nested)
# with whether that leaf is array-typed. The wrapper iterates
# these to write the flat tuple ``_result`` back leaf-by-leaf.
from .udt_utils import _iter_record_leaves
leaves = tuple(
(py, d.subdtype is not None)
for py, _c, d in _iter_record_leaves(return_type.np_type)
)
return (
" z = numba.carray(z_ptr, 1)\n",
ret_ptr_type,
"record_fields",
leaves,
)
if return_type._is_udt:
if return_type.np_type.subdtype is None:
return (
" z = numba.carray(z_ptr, 1)\n",
ret_ptr_type,
"direct",
("", "", "z[0]"),
)
base_numba, shape = _array_udt_view(return_type)
return (
f" z = numba.carray(z_ptr, {shape})\n",
nt.CPointer(base_numba),
"array_elements",
None,
)
if return_type == BOOL:
return "", ret_ptr_type, "direct", ("bool(", ")", "z_ptr[0]")
return "", ret_ptr_type, "direct", ("", "", "z_ptr[0]")
def _compose_wrapper_body(zkind, zinfo, signature_line, body_setup, call_expr):
"""Assemble the Python source for a UDT cfunc wrapper.
For record returns, the wrapper writes leaf-by-leaf; Numba does not
compile a nested-tuple assignment to an outer record field. Array
returns and array-typed record leaves slice-assign into the caller's
buffer, so a wrong-shape return cannot overrun it. It does not reach
the caller either: the resulting ``ValueError`` is raised inside a
cfunc, which Numba prints and swallows, so the write stops there and
every leaf from that point on keeps whatever SuiteSparse had in the
buffer. ``_check_array_udf_shape`` and
``_check_record_udf_leaf_shapes`` reject such a return up front, but
only when they can run the UDF, so this is the backstop that always
runs rather than dead code.
Slice-assign also broadcasts, which is why those checks accept any
return that broadcasts to the element rather than requiring an exact
shape: filling a ``(6,)`` element from a ``(1,)`` return works here
and must keep working.
"""
if zkind == "array_elements":
return (
f"{signature_line}\n"
f"{body_setup}"
f" _result = {call_expr}\n"
f" z[:] = _result\n"
)
if zkind == "record_fields":
# Array-typed leaves slice-assign. Numba's record-field setitem
# copies the destination's extent regardless of the source's, so a
# short source is read past its end and a long one is silently
# truncated; ``[:]`` makes both a shape error instead.
field_assigns = "".join(
f" z[0]{path}{'[:]' if is_array else ''} = _result[{i}]\n"
for i, (path, is_array) in enumerate(zinfo)
)
return (
f"{signature_line}\n"
f"{body_setup}"
f" _result = {call_expr}\n"
f"{field_assigns}"
)
BL, BR, zname = zinfo
return f"{signature_line}\n{body_setup} {zname} = {BL}{call_expr}{BR}\n"
def _udf_probe_value(dtype):
"""Build a stand-in operand of ``dtype`` for a UDF probe.
Ones rather than zeros, for the same reason ``dtypes._sample_values``
avoids zeros: a UDF that divides by an operand raises on a zero-filled
probe, and :func:`_run_udf_probe` treats a raising probe as "cannot
check", which would quietly skip the check the probe exists to perform.
"""
if dtype._is_udt:
np_type = dtype.np_type
if np_type.subdtype is None:
return np.ones(1, dtype=np_type)[0]
base_np_type, shape = np_type.subdtype
return np.ones(shape, dtype=base_np_type)
return _sample_values[dtype]
def _run_udf_probe(numba_func, operands):
"""Run the UDF on stand-in operands. Returns ``(result,)``, or ``None``.
Numba's ``Array`` type records ``ndim`` but not extents, so a UDF that
builds its result (``x + y``) rather than returning an operand can only
be shape-checked by running it. Doing that at registration turns a
wrong-shape return into an error the caller sees. Left to the wrapper
it raises inside a cfunc, where Numba prints the traceback (once per
element) and returns, handing back an uninitialized element and no
exception.
The cost is that the first ``op[udt]`` lookup now executes the user's
function once, on ones, where before it only compiled it. Registering
the op does not, since compilation stays lazy, but
``OpBase.__contains__`` is a typed lookup, so ``udt in some_op`` runs
the function as a side effect of a membership test. It costs no extra
compile: the probe passes an ``ndarray``, and the wrapper's
``numba.carray`` view needs that same specialization anyway.
The check is best-effort, not a guarantee. A UDF that raises on the
probe values returns ``None`` here and is not checked at all, so one
that also returns a wrong shape still reaches the wrapper and still
fails the way it always did: a ``ValueError`` inside the cfunc that
Numba prints and swallows, a caller that sees no exception, and an
element left as SuiteSparse found it. The wrapper's slice-assign
remains the only backstop that always runs. Only the call is guarded,
so mistakes in the probe itself still surface.
One probe cannot settle a UDF whose output shape depends on operand
*values* rather than their types: it reports the shape for the probe
values, which is why the callers say so in their message.
"""
args = [_udf_probe_value(d) for d in operands]
try:
return (numba_func(*args),)
except NumbaError as exc:
raise UdfParseError(_summarize_numba_typing_error(exc)) from exc
except Exception:
return None
# Shared tail for the shape diagnostics: the probed shape is one sample, so
# a value-dependent UDF can be rejected on a shape it returns only here.
_SHAPE_HINT = (
"A UDF whose output shape varies with its input values must still fit every element."
)
def _fits_by_broadcast(shape, expected):
"""Whether a return of ``shape`` fills an ``expected``-shaped destination.
The wrapper slice-assigns (``z[:] = ...``), and numpy broadcasts on
assignment, so an exact match is not the requirement: a ``(1,)`` return
legitimately fills a ``(6,)`` element, and a ``(1, 3)`` return fills
every row of a ``(2, 3)`` one. Rejecting those would refuse code that
works today.
numpy's assignment rule is broadcasting plus a leading-``1`` strip when
the source has the higher rank, so ``(1, 6)`` fits ``(6,)`` while
``(6, 1)`` does not. ``test_udt_broadcast_matches_numba_slice_assign``
pins this against Numba's own slice-assign for both.
"""
shape = tuple(shape)
expected = tuple(expected)
while len(shape) > len(expected) and shape[0] == 1:
shape = shape[1:]
try:
return np.broadcast_shapes(shape, expected) == expected
except ValueError:
return False
def _check_array_udf_shape(numba_func, return_type, operands):
"""Reject a UDF whose built array cannot fill the array UDT's element."""
probed = _run_udf_probe(numba_func, operands)
if probed is None:
return
expected = return_type.numba_type.shape
shape = getattr(probed[0], "shape", None)
if shape is not None and not _fits_by_broadcast(shape, expected):
raise UdfParseError(
f"UDT UDF returned an array of shape {tuple(shape)} when run on sample "
f"values, but {return_type} elements are {tuple(expected)}. Return an "
f"array whose shape matches or broadcasts to that, or one of the "
f"operands. {_SHAPE_HINT}"
)
def _check_record_udf_leaf_shapes(numba_func, return_type, operands):
"""Reject a record return whose array-typed leaf cannot fill its field.
The array-leaf half of :func:`_check_array_udf_shape`. The wrapper
slice-assigns those leaves, so a wrong extent raises inside the cfunc
and abandons the write part-way: every leaf after it keeps whatever
SuiteSparse had in the buffer, scalar leaves included.
Only records that actually have an array leaf are probed, so the
common record UDF still registers without running the user's code.
"""
from .udt_utils import _iter_record_leaves
leaves = [(py, d) for py, _c, d in _iter_record_leaves(return_type.np_type)]
if not any(d.subdtype is not None for _py, d in leaves):
return
probed = _run_udf_probe(numba_func, operands)
if probed is None:
return
result = probed[0]
if not isinstance(result, tuple) or len(result) != len(leaves):
return
for (path, leaf_dtype), value in zip(leaves, result, strict=True):
if leaf_dtype.subdtype is None:
continue
expected = leaf_dtype.subdtype[1]
shape = getattr(value, "shape", None)
if shape is not None and not _fits_by_broadcast(shape, expected):
raise UdfParseError(
f"UDT UDF returned an array of shape {tuple(shape)} for field "
f"{path} of {return_type} when run on sample values, which holds "
f"{tuple(expected)} there. Return an array whose shape matches or "
f"broadcasts to that. {_SHAPE_HINT}"
)
def _get_udt_wrapper(
numba_func, return_type, dtype, dtype2=None, *, include_indexes=False, numba_ret_type=None
):
"""Build a Numba cfunc wrapper for unary, binary, indexunary, or select UDFs on UDTs.
``include_indexes=True`` inserts ``(row, col)`` between ``x`` and
``y`` in both the wrapper signature and the call to ``numba_func``,
matching the IndexUnaryOp and SelectOp shape. The IndexBinaryOp path
(four indices plus a theta operand) uses
:func:`_get_udt_wrapper_indexbinary`.
"""
nt = numba.types
zsetup, zptr_type, zkind, zinfo = _output_handler(return_type, numba_ret_type)
xsetup, xderef, xptr_type = _input_operand(dtype, "x")
wrapper_args = [zptr_type, xptr_type]
probe_operands = [dtype]
if include_indexes:
wrapper_args.extend([UINT64.numba_type, UINT64.numba_type])
probe_operands.extend([UINT64, UINT64])
ysetup, yderef_expr, yarg = "", "", ""
if dtype2 is not None:
ysetup, yderef, yptr_type = _input_operand(dtype2, "y")
wrapper_args.append(yptr_type)
probe_operands.append(dtype2)
yarg = ", y_ptr"
yderef_expr = f", {yderef}"
wrapper_sig = nt.void(*wrapper_args)
if zkind == "array_elements":
_check_array_udf_shape(numba_func, return_type, probe_operands)
elif zkind == "record_fields":
_check_record_udf_leaf_shapes(numba_func, return_type, probe_operands)
rcidx = ", row, col" if include_indexes else ""
signature_line = f"def wrapper(z_ptr, x_ptr{rcidx}{yarg}):"
body_setup = f"{zsetup}{xsetup}{ysetup}"
call_expr = f"numba_func({xderef}{rcidx}{yderef_expr})"
text = _compose_wrapper_body(zkind, zinfo, signature_line, body_setup, call_expr)
from .udt_utils import _compile_codegen
kind = "indexunary" if include_indexes else ("binary" if dtype2 is not None else "unary")
wrapper = _compile_codegen(
text,
func_name="wrapper",
source_label=f"<gb-udt-wrapper {kind} dtype={dtype} ret={return_type}>",
extra_ns={"numba_func": numba_func},
)
return wrapper, wrapper_sig
def _get_udt_wrapper_indexbinary(
numba_func, return_type, dtype, dtype2, *, numba_ret_type=None
):
"""Build a Numba cfunc wrapper for IndexBinaryOp UDFs on UDTs.
Signature: ``f(x, ix, jx, y, iy, jy, theta) -> z``. ``dtype2`` is the
shared type of ``y`` and ``theta``.
"""
nt = numba.types
zsetup, zptr_type, zkind, zinfo = _output_handler(return_type, numba_ret_type)
xsetup, xderef, xptr_type = _input_operand(dtype, "x")
ysetup, yderef, yptr_type = _input_operand(dtype2, "y")
tsetup, tderef, tptr_type = _input_operand(dtype2, "t")
wrapper_sig = nt.void(
zptr_type,
xptr_type,
UINT64.numba_type,
UINT64.numba_type,
yptr_type,
UINT64.numba_type,
UINT64.numba_type,
tptr_type,
)
# Same registration-time guards as :func:`_get_udt_wrapper`. Without
# them a wrong-shape return is memory-safe but silent: the wrapper's
# ``z[:] =`` raises inside the cfunc, Numba prints and swallows it,
# and the element is left as SuiteSparse found it.
if zkind in ("array_elements", "record_fields"):
probe_operands = [dtype, UINT64, UINT64, dtype2, UINT64, UINT64, dtype2]
if zkind == "array_elements":
_check_array_udf_shape(numba_func, return_type, probe_operands)
else:
_check_record_udf_leaf_shapes(numba_func, return_type, probe_operands)
signature_line = "def wrapper(z_ptr, x_ptr, ix, jx, y_ptr, iy, jy, t_ptr):"
body_setup = f"{zsetup}{xsetup}{ysetup}{tsetup}"
call_expr = f"numba_func({xderef}, ix, jx, {yderef}, iy, jy, {tderef})"
text = _compose_wrapper_body(zkind, zinfo, signature_line, body_setup, call_expr)
from .udt_utils import _compile_codegen
wrapper = _compile_codegen(
text,
func_name="wrapper",
source_label=f"<gb-udt-wrapper indexbinary dtype={dtype} dtype2={dtype2}>",
extra_ns={"numba_func": numba_func},
)
return wrapper, wrapper_sig
# Maps ``opclass`` to the SuiteSparse C type name SS allocates for it.
# ``IndexBinaryOp`` is in the GxB_ namespace (SS-specific, added in 9.4);
# the rest are GrB_. ``SelectOp`` is implemented on top of
# ``GrB_IndexUnaryOp`` (BOOL-returning), so its handle frees through the
# same ``GrB_IndexUnaryOp_free``. Used by ``TypedOpBase.__del__`` to
# synthesize the pointer cell for ``<C type>_free``.
_GB_OBJ_C_TYPENAME = {
"UnaryOp": "GrB_UnaryOp",
"BinaryOp": "GrB_BinaryOp",
"IndexUnaryOp": "GrB_IndexUnaryOp",
"SelectOp": "GrB_IndexUnaryOp",
"IndexBinaryOp": "GxB_IndexBinaryOp",
"Monoid": "GrB_Monoid",
"Semiring": "GrB_Semiring",
}
class TypedOpBase:
__slots__ = (
"parent",
"name",
"type",
"return_type",
"gb_obj",
"gb_name",
"_type2",
"_jit_c_info",
"_gb_obj_owner",
"__weakref__",
)
# Subclasses whose ``gb_obj`` was allocated via ``GrB_<Type>_new`` /
# ``GxB_<Type>_new`` (TypedUser*Op, _BoundIndexBinaryOp) override this so
# ``__del__`` frees the SuiteSparse handle. Built-in typed ops point at
# SuiteSparse's permanent built-in singletons and must never free.
_owns_gb_obj = False
def __init__(self, parent, name, type_, return_type, gb_obj, gb_name, dtype2=None):
self.parent = parent
self.name = name
self.type = type_
self.return_type = return_type
self.gb_obj = gb_obj
self.gb_name = gb_name
self._type2 = dtype2
# ``(c_name, c_definition)`` when SuiteSparse JIT-compiled a kernel
# for this typed op; ``None`` for built-in ops and for UDT ops with
# no JIT path.
self._jit_c_info = None
# Set when ``gb_obj`` is borrowed from another typed op rather than
# allocated here (``SelectOp._from_indexunary``). Storing the owner
# both suppresses our free and keeps the handle alive as long as we
# point at it; disclaiming ownership without naming an owner would
# leave this op holding a dangling handle.
self._gb_obj_owner = None
@property
def jit_c_name(self):
"""The C symbol name SuiteSparse uses for this op's JIT kernel, or ``None``."""
return self._jit_c_info[0] if self._jit_c_info is not None else None
@property
def jit_c_source(self):
"""C source SuiteSparse JIT-compiles for this op, or ``None`` when no JIT kernel exists."""
return self._jit_c_info[1] if self._jit_c_info is not None else None
def __repr__(self):
classname = self.opclass.lower()
classname = classname.removesuffix("op")
dtype2 = "" if self._type2 is None else f", {self._type2.name}"
return f"{classname}.{self.name}[{self.type.name}{dtype2}]"
@property
def _carg(self):
return self.gb_obj
@property
def is_positional(self):
return self.parent.is_positional
def __reduce__(self):
if self._type2 is None or self.type == self._type2:
return (getitem, (self.parent, self.type))
return (getitem, (self.parent, (self.type, self._type2)))
def __del__(self):
# Free the SuiteSparse handle we allocated. Built-in typed ops alias
# SuiteSparse's permanent built-in singletons and must never free.
# Mirrors the ``Matrix.__del__`` / ``Vector.__del__`` pattern.
if not type(self)._owns_gb_obj:
return
# A borrowed handle belongs to ``_gb_obj_owner``, which we keep alive.
# ``getattr`` guards the case where ``__init__`` raised before the slot
# was set.
if getattr(self, "_gb_obj_owner", None) is not None:
return
gb_obj = getattr(self, "gb_obj", None)
if gb_obj is None or lib is None or ffi is None:
# Interpreter shutdown can clear ``lib`` / ``ffi`` before
# finalizers run; SS will clean up the handles at process exit.
return
c_type_name = _GB_OBJ_C_TYPENAME.get(self.opclass)
if c_type_name is None: # pragma: no cover (defensive)
return
free_fn = getattr(lib, f"{c_type_name}_free", None)
if free_fn is None:
# ``GxB_IndexBinaryOp_free`` is absent on SS < 9.4; that build
# also can't allocate one in the first place, so this path is
# unreachable in practice but guarded for safety.
return
# ``GrB_<Type>_free`` takes a pointer-to-pointer (sets ``*p = NULL``
# after free). Synthesize a cell pointing at our handle and call it.
free_fn(ffi.new(f"{c_type_name}*", gb_obj))
class _BinaryopJitDelegate:
"""Mixin for ops that don't own a JIT kernel; defer introspection to ``binaryop``.
Monoids and semirings reuse the binary op's JIT kernel. The setter
accepts ``None`` so ``TypedOpBase.__init__``'s slot init is a no-op.
"""
__slots__ = ()
@property
def _jit_c_info(self):
return self.binaryop._jit_c_info
@_jit_c_info.setter
def _jit_c_info(self, value):
# No-op so ``TypedOpBase.__init__``'s ``self._jit_c_info = None``
# slot-init succeeds. The kernel lives on ``binaryop``.
pass
def _deserialize_parameterized(parameterized_op, args, kwargs):
return parameterized_op(*args, **kwargs)
class ParameterizedUdf:
__slots__ = "name", "__call__", "_anonymous", "__weakref__"
is_positional = False
_custom_dtype = None
# Subclasses set this to the OpBase subclass they parameterize (e.g.,
# ``ParameterizedUnaryOp._op_class = UnaryOp``). Assigned after the
# OpBase subclass is defined to avoid an import-order cycle.
_op_class = None
def __init__(self, name, anonymous):
self.name = name
self._anonymous = anonymous
# lru_cache per instance
method = self._call.__get__(self, type(self))
self.__call__ = lru_cache(maxsize=1024)(method)
def _call(self, *args, **kwargs):
raise NotImplementedError
def __reduce__(self):
# The namespace prefix (``unary``, ``binary``, ...) comes from the
# OpBase subclass each parameterized op wraps. Standard ops pickle by
# name; user-registered ones pickle the reduce tuple and re-register
# on load via ``_deserialize`` (which dispatches through ``_op_class``).
name = f"{self._op_class._modname}.{self.name}"
if not self._anonymous and name in _STANDARD_OPERATOR_NAMES:
return name
return (self._deserialize, (self.name, self.func, self._anonymous, self._is_udt))
@classmethod
def _deserialize(cls, name, func, anonymous, is_udt=False):
"""Re-register a parameterized UDF on unpickle, or reuse if already present.
Shared by the five ``Parameterized*Op`` subclasses; each sets
``_op_class`` to the matching OpBase subclass for the dispatch below.
"""
op_cls = cls._op_class
if anonymous:
return op_cls.register_anonymous(func, name, parameterized=True, is_udt=is_udt)
if (rv := op_cls._find(name)) is not None:
return rv
return op_cls.register_new(name, func, parameterized=True, is_udt=is_udt)
_VARNAMES = tuple(x for x in dir(lib) if x[0] != "_")
class OpBase:
__slots__ = (
"name",
"_typed_ops",
"types",
"coercions",
"_anonymous",
"_udt_types",
"_udt_ops",
"__weakref__",
)
_parse_config = None
_initialized = False
_module = None
_positional = None
def __init__(self, name, *, anonymous=False):
self.name = name
self._typed_ops = {}
self.types = {}
self.coercions = {}
self._anonymous = anonymous
self._udt_types = None
self._udt_ops = None
def __repr__(self):
return f"{self._modname}.{self.name}"
def __getitem__(self, type_):
if type(type_) is tuple:
from .utils import get_typed_op
dtype1, dtype2 = type_
dtype1 = lookup_dtype(dtype1)
dtype2 = lookup_dtype(dtype2)
return get_typed_op(self, dtype1, dtype2)
if not self._is_udt:
type_ = lookup_dtype(type_)
if type_ not in self._typed_ops:
if self._udt_types is None:
if self.is_positional:
return self._typed_ops[UINT64]
raise KeyError(f"{self.name} does not work with {type_}")
else:
return self._typed_ops[type_]
# This is a UDT or is able to operate on UDTs such as `first` any `any`
dtype = lookup_dtype(type_)
return self._compile_udt(dtype, dtype)