Skip to content

Commit c051841

Browse files
committed
Raise explicitly on Python methods that are incompatible with lazy variables
Notably changes the behavior of `__bool__` to always raise. Before there was a hack based on whether a variable had been compared to something before.
1 parent 438418e commit c051841

File tree

16 files changed

+108
-63
lines changed

16 files changed

+108
-63
lines changed

pytensor/compile/function/pfunc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -569,7 +569,7 @@ def construct_pfunc_ins_and_outs(
569569
if not fgraph:
570570
# Extend the outputs with the updates on input variables so they are
571571
# also cloned
572-
additional_outputs = [i.update for i in inputs if i.update]
572+
additional_outputs = [i.update for i in inputs if i.update is not None]
573573
if outputs is None:
574574
out_list = []
575575
else:
@@ -608,7 +608,7 @@ def construct_pfunc_ins_and_outs(
608608
new_i.variable = iv
609609

610610
# If needed, replace the input's update by its cloned equivalent
611-
if i.update:
611+
if i.update is not None:
612612
new_i.update = clone_d[i.update]
613613

614614
new_inputs.append(new_i)

pytensor/compile/function/types.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ def std_fgraph(
198198
update_mapping = {}
199199
out_idx = len(output_specs)
200200
for idx, input_spec in enumerate(input_specs):
201-
if input_spec.update:
201+
if input_spec.update is not None:
202202
updates.append(input_spec.update)
203203
update_mapping[out_idx] = idx
204204
out_idx += 1
@@ -1195,7 +1195,7 @@ def insert_deepcopy(fgraph, wrapped_inputs, wrapped_outputs):
11951195
updated_fgraph_inputs = {
11961196
fgraph_i
11971197
for i, fgraph_i in zip(wrapped_inputs, fgraph.inputs, strict=True)
1198-
if getattr(i, "update", False)
1198+
if getattr(i, "update", None) is not None
11991199
}
12001200

12011201
# We can't use fgraph.inputs as this don't include Constant Value.
@@ -1351,7 +1351,11 @@ def check_unused_inputs(inputs, outputs, on_unused_input):
13511351
ancestors(
13521352
(
13531353
[o.variable for o in outputs]
1354-
+ [i.update for i in inputs if getattr(i, "update", False)]
1354+
+ [
1355+
i.update
1356+
for i in inputs
1357+
if getattr(i, "update", None) is not None
1358+
]
13551359
),
13561360
blockers=[i.variable for i in inputs],
13571361
)

pytensor/compile/nanguardmode.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def _is_numeric_value(arr, var):
3636
return False
3737
elif isinstance(arr, np.random.mtrand.RandomState | np.random.Generator):
3838
return False
39-
elif var and isinstance(var.type, RandomType):
39+
elif var is not None and isinstance(var.type, RandomType):
4040
return False
4141
elif isinstance(arr, slice):
4242
return False

pytensor/scalar/basic.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -725,6 +725,37 @@ def get_scalar_type(dtype, cache: dict[str, ScalarType] = {}) -> ScalarType:
725725

726726

727727
class _scalar_py_operators:
728+
# These can't work because Python requires native output types
729+
def __bool__(self):
730+
raise TypeError(
731+
"ScalarVariable cannot be converted to Python boolean. "
732+
"Call `.astype(bool)` for the symbolic equivalent."
733+
)
734+
735+
def __index__(self):
736+
raise TypeError(
737+
"ScalarVariable cannot be converted to Python integer. "
738+
"Call `.astype(int)` for the symbolic equivalent."
739+
)
740+
741+
def __int__(self):
742+
raise TypeError(
743+
"ScalarVariable cannot be converted to Python integer. "
744+
"Call `.astype(int)` for the symbolic equivalent."
745+
)
746+
747+
def __float__(self):
748+
raise TypeError(
749+
"ScalarVariable cannot be converted to Python float. "
750+
"Call `.astype(float)` for the symbolic equivalent."
751+
)
752+
753+
def __complex__(self):
754+
raise TypeError(
755+
"ScalarVariable cannot be converted to Python complex number. "
756+
"Call `.astype(complex)` for the symbolic equivalent."
757+
)
758+
728759
# So that we can simplify checking code when we have a mixture of ScalarType
729760
# variables and Tensor variables
730761
ndim = 0

pytensor/scalar/loop.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,12 +60,12 @@ def __init__(
6060
constant = []
6161
if not len(init) == len(update):
6262
raise ValueError("An update must be given for each init variable")
63-
if until:
63+
if until is not None:
6464
inputs, outputs = clone([*init, *constant], [*update, until])
6565
else:
6666
inputs, outputs = clone([*init, *constant], update)
6767

68-
self.is_while = bool(until)
68+
self.is_while = until is not None
6969
self.inputs, self.outputs = self._cleanup_graph(inputs, outputs)
7070
self._validate_updates(self.inputs, self.outputs)
7171

pytensor/scalar/math.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -942,7 +942,7 @@ def inner_loop_a(sum_a, delta, xpow, k_minus_one_minus_n, fac, dfac, x):
942942
dfac = k_minus_one_minus_n * dfac + fac
943943
fac *= k_minus_one_minus_n
944944
delta = dfac / xpow
945-
return (sum_a, delta, xpow, k_minus_one_minus_n, fac, dfac), ()
945+
return (sum_a, delta, xpow, k_minus_one_minus_n, fac, dfac), None
946946

947947
init = [sum_a0, delta, xpow, k_minus_one_minus_n, fac, dfac]
948948
constant = [x]

pytensor/scan/basic.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -979,7 +979,7 @@ def wrap_into_list(x):
979979
# user-specified within the inner-function (e.g. by returning an update
980980
# `dict`) or the `SharedVariable.default_update`s of a shared variable
981981
# created in the inner-function.
982-
if input.update and (is_local or input.variable in updates):
982+
if input.update is not None and (is_local or input.variable in updates):
983983
# We need to remove the `default_update`s on the shared
984984
# variables created within the context of the loop function
985985
# (e.g. via use of `RandomStream`); otherwise, they'll get

pytensor/scan/op.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2582,7 +2582,7 @@ def compute_all_gradients(known_grads):
25822582

25832583
# mask inputs that get no gradients
25842584
for dx in range(len(dC_dinps_t)):
2585-
if not dC_dinps_t[dx]:
2585+
if dC_dinps_t[dx] is None:
25862586
dC_dinps_t[dx] = pt.zeros_like(diff_inputs[dx])
25872587
else:
25882588
disconnected_dC_dinps_t[dx] = False

pytensor/tensor/basic.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3386,7 +3386,14 @@ def __getitem__(self, *args):
33863386
raise NotImplementedError(
33873387
"Not implemented for slices whose step is complex"
33883388
)
3389-
ranges = [arange(sl.start or 0, sl.stop, sl.step or 1) for sl in args[0]]
3389+
ranges = [
3390+
arange(
3391+
sl.start if sl.start is not None else 0,
3392+
sl.stop,
3393+
sl.step if sl.step is not None else 1,
3394+
)
3395+
for sl in args[0]
3396+
]
33903397
shapes = [
33913398
tuple([1] * j + [r.shape[0]] + [1] * (ndim - 1 - j))
33923399
for j, r in enumerate(ranges)

pytensor/tensor/conv/abstract_conv.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2198,7 +2198,7 @@ def __init__(
21982198
):
21992199
border_mode = "valid"
22002200

2201-
self.imshp = tuple(imshp) if imshp else (None,) * (2 + convdim)
2201+
self.imshp = tuple(imshp) if imshp is not None else (None,) * (2 + convdim)
22022202
for imshp_i in self.imshp:
22032203
if imshp_i is not None:
22042204
# Components of imshp should be constant or ints
@@ -2208,7 +2208,7 @@ def __init__(
22082208
raise ValueError(
22092209
"imshp should be None or a tuple of constant int values"
22102210
).with_traceback(sys.exc_info()[2])
2211-
if kshp:
2211+
if kshp is not None:
22122212
self.kshp = tuple(kshp)
22132213
else:
22142214
self.kshp = (None,) * ((2 + 2 * convdim) if unshared else (2 + convdim))

0 commit comments

Comments
 (0)