diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6f5f765676..92c13924e9 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -9,7 +9,7 @@ exclude: | )$ repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v5.0.0 + rev: v6.0.0 hooks: - id: debug-statements exclude: | @@ -25,11 +25,11 @@ repos: rev: v1.0.0 hooks: - id: sphinx-lint - args: ["."] + args: ["-i", ".pixi", "."] - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.7.3 + rev: v0.14.0 hooks: - - id: ruff + - id: ruff-check types_or: [python, pyi, jupyter] args: ["--fix", "--output-format=full"] - id: ruff-format diff --git a/pytensor/bin/pytensor_cache.py b/pytensor/bin/pytensor_cache.py index b5d22876ec..3d5507ea7a 100644 --- a/pytensor/bin/pytensor_cache.py +++ b/pytensor/bin/pytensor_cache.py @@ -1,6 +1,7 @@ import logging import os import sys +from pathlib import Path if sys.platform == "win32": @@ -24,7 +25,7 @@ def print_help(exit_status): if exit_status: - print(f"command \"{' '.join(sys.argv)}\" not recognized") + print(f'command "{" ".join(sys.argv)}" not recognized') print('Type "pytensor-cache" to print the cache location') print('Type "pytensor-cache help" to print this help') print('Type "pytensor-cache clear" to erase the cache') @@ -65,11 +66,7 @@ def main(): # Print a warning if some cached modules were not removed, so that the # user knows he should manually delete them, or call # pytensor-cache purge, # to properly clear the cache. - items = [ - item - for item in sorted(os.listdir(cache.dirname)) - if item.startswith("tmp") - ] + items = list(Path(cache.dirname).glob("tmp*")) if items: _logger.warning( "There remain elements in the cache dir that you may " diff --git a/pytensor/compile/builders.py b/pytensor/compile/builders.py index eedefa430f..c76d7db33b 100644 --- a/pytensor/compile/builders.py +++ b/pytensor/compile/builders.py @@ -122,7 +122,7 @@ def construct_nominal_fgraph( ( local_inputs, local_outputs, - (clone_d, update_d, update_expr, new_shared_inputs), + (_clone_d, update_d, update_expr, new_shared_inputs), ) = new assert len(local_inputs) == len(inputs) + len(implicit_shared_inputs) diff --git a/pytensor/compile/function/__init__.py b/pytensor/compile/function/__init__.py index 61e4aa3cfe..ffce6db4fb 100644 --- a/pytensor/compile/function/__init__.py +++ b/pytensor/compile/function/__init__.py @@ -12,7 +12,7 @@ from pytensor.graph import Variable -__all__ = ["types", "pfunc"] +__all__ = ["pfunc", "types"] __docformat__ = "restructuredtext en" _logger = logging.getLogger("pytensor.compile.function") diff --git a/pytensor/compile/function/pfunc.py b/pytensor/compile/function/pfunc.py index 91d6e1a588..1c76e2e3a3 100644 --- a/pytensor/compile/function/pfunc.py +++ b/pytensor/compile/function/pfunc.py @@ -328,8 +328,7 @@ def clone_inputs(i): cloned_outputs = [] # TODO: get Function.__call__ to return None else: raise TypeError( - "output must be an PyTensor Variable or Out " - "instance (or list of them)", + "output must be an PyTensor Variable or Out instance (or list of them)", outputs, ) @@ -592,7 +591,7 @@ def construct_pfunc_ins_and_outs( clone_inner_graphs=True, ) input_variables, cloned_extended_outputs, other_stuff = output_vars - clone_d, update_d, update_expr, shared_inputs = other_stuff + clone_d, update_d, _update_expr, shared_inputs = other_stuff # Recover only the clones of the original outputs if outputs is None: diff --git a/pytensor/compile/function/types.py b/pytensor/compile/function/types.py index 635af25e47..d77f11d84d 100644 --- a/pytensor/compile/function/types.py +++ b/pytensor/compile/function/types.py @@ -215,7 +215,7 @@ def add_supervisor_to_fgraph( input for spec, input in zip(input_specs, fgraph.inputs, strict=True) if not ( - spec.mutable or has_destroy_handler and fgraph.has_destroyers([input]) + spec.mutable or (has_destroy_handler and fgraph.has_destroyers([input])) ) ) ) diff --git a/pytensor/compile/mode.py b/pytensor/compile/mode.py index 8bd0e2f901..acfd931a60 100644 --- a/pytensor/compile/mode.py +++ b/pytensor/compile/mode.py @@ -407,7 +407,7 @@ def register(self, *optimizations): optimizations. """ - link, opt = self.get_linker_optimizer( + _link, opt = self.get_linker_optimizer( self.provided_linker, self.provided_optimizer ) return self.clone(optimizer=opt.register(*optimizations)) diff --git a/pytensor/compile/monitormode.py b/pytensor/compile/monitormode.py index 40c8c41dfe..305c4cc4af 100644 --- a/pytensor/compile/monitormode.py +++ b/pytensor/compile/monitormode.py @@ -45,8 +45,7 @@ def __init__( optimizer = config.optimizer if linker is not None and not isinstance(linker.mode, MonitorMode): raise Exception( - "MonitorMode can only use its own linker! You " - "should not provide one.", + "MonitorMode can only use its own linker! You should not provide one.", linker, ) diff --git a/pytensor/compile/profiling.py b/pytensor/compile/profiling.py index a68365527f..e8f25ce372 100644 --- a/pytensor/compile/profiling.py +++ b/pytensor/compile/profiling.py @@ -514,14 +514,12 @@ def summary_class(self, file=sys.stderr, N=None): # While this carries over less information, it is arranged such # that it is way more readable than the previous output of the # profiler + nb_classes = max(0, len(otimes) - N) + percent_total = sum(f for f, t, a, ci, nb_call, nb_op in otimes[N:]) + time_total = sum(t for f, t, a, ci, nb_call, nb_op in otimes[N:]) print( - " ... (remaining %i Classes account for %6.2f%%(%.2fs) of " - "the runtime)" - % ( - max(0, len(otimes) - N), - sum(f for f, t, a, ci, nb_call, nb_op in otimes[N:]), - sum(t for f, t, a, ci, nb_call, nb_op in otimes[N:]), - ), + f" ... (remaining {nb_classes} Classes account for " + f"{percent_total:6.2f}%%({time_total:.2f}s) of the runtime)", file=file, ) print("", file=file) @@ -607,14 +605,12 @@ def summary_ops(self, file=sys.stderr, N=None): # While this carries over less information, it is arranged such # that it is way more readable than the previous output of the # profiler + nb_ops = max(0, len(otimes) - N) + percent_total = sum(f for f, t, a, ci, nb_call, nb_op in otimes[N:]) + time_total = sum(t for f, t, a, ci, nb_call, nb_op in otimes[N:]) print( - " ... (remaining %i Ops account for %6.2f%%(%.2fs) of " - "the runtime)" - % ( - max(0, len(otimes) - N), - sum(f for f, t, a, ci, nb_call, nb_op in otimes[N:]), - sum(t for f, t, a, ci, nb_call, nb_op in otimes[N:]), - ), + f" ... (remaining {nb_ops} Ops account for " + f"{percent_total:6.2f}%%({time_total:.2f}s) of the runtime)", file=file, ) print("", file=file) @@ -935,18 +931,14 @@ def count_running_memory(order, fgraph, nodes_mem, ignore_dmap=False): if dmap and idx2 in dmap: vidx = dmap[idx2] assert len(vidx) == 1, ( - "Here we only support the " - "possibility to destroy one " - "input" + "Here we only support the possibility to destroy one input" ) ins = node.inputs[vidx[0]] if vmap and idx2 in vmap: assert ins is None vidx = vmap[idx2] assert len(vidx) == 1, ( - "Here we only support the " - "possibility to view one " - "input" + "Here we only support the possibility to view one input" ) ins = node.inputs[vidx[0]] if ins is not None: @@ -1093,9 +1085,7 @@ def min_memory_generator(executable_nodes, viewed_by, view_of): assert ins is None vidx = vmap[idx] assert len(vidx) == 1, ( - "Here we only support " - "the possibility to " - "view one input" + "Here we only support the possibility to view one input" ) ins = node.inputs[vidx[0]] if ins is not None: @@ -1304,22 +1294,22 @@ def print_stats(stats1, stats2): print( ( - f" CPU: {int(round(new_max_running_max_memory_size[1] / 1024.0))}KB " - f"({int(round(max_running_max_memory_size[1] / 1024.0))}KB)" + f" CPU: {round(new_max_running_max_memory_size[1] / 1024.0)}KB " + f"({round(max_running_max_memory_size[1] / 1024.0)}KB)" ), file=file, ) print( ( - f" GPU: {int(round(new_max_running_max_memory_size[2] / 1024.0))}KB " - f"({int(round(max_running_max_memory_size[2] / 1024.0))}KB)" + f" GPU: {round(new_max_running_max_memory_size[2] / 1024.0)}KB " + f"({round(max_running_max_memory_size[2] / 1024.0)}KB)" ), file=file, ) print( ( - f" CPU + GPU: {int(round(new_max_running_max_memory_size[0] / 1024.0))}KB " - f"({int(round(max_running_max_memory_size[0] / 1024.0))}KB)" + f" CPU + GPU: {round(new_max_running_max_memory_size[0] / 1024.0)}KB " + f"({round(max_running_max_memory_size[0] / 1024.0)}KB)" ), file=file, ) @@ -1333,22 +1323,22 @@ def print_stats(stats1, stats2): ) print_stats(stats[1], stats[3]) - (max_node_memory_size, _, _, _) = stats[0] + (_max_node_memory_size, _, _, _) = stats[0] (new_max_node_memory_size, _, _, _) = stats[2] print( " Max peak memory if allow_gc=False (linker don't make a difference)", file=file, ) print( - f" CPU: {int(round(new_max_node_memory_size[1] / 1024.0))}KB", + f" CPU: {round(new_max_node_memory_size[1] / 1024.0)}KB", file=file, ) print( - f" GPU: {int(round(new_max_node_memory_size[2] / 1024.0))}KB", + f" GPU: {round(new_max_node_memory_size[2] / 1024.0)}KB", file=file, ) print( - f" CPU + GPU: {int(round(new_max_node_memory_size[0] / 1024.0))}KB", + f" CPU + GPU: {round(new_max_node_memory_size[0] / 1024.0)}KB", file=file, ) print("---", file=file) @@ -1356,7 +1346,7 @@ def print_stats(stats1, stats2): if min_max_peak: print( " Minimum peak from all valid apply node order is " - f"{int(round(min_max_peak / 1024.0))}KB(took {min_peak_time:3f}s to compute)", + f"{round(min_max_peak / 1024.0)}KB(took {min_peak_time:3f}s to compute)", file=file, ) @@ -1405,7 +1395,7 @@ def print_stats(stats1, stats2): print( ( f" ... (remaining {max(0, len(node_mem) - N)} Apply account for " - f"{sum_remaining:4d}B/{size_sum_dense :d}B ({p}) of the" + f"{sum_remaining:4d}B/{size_sum_dense:d}B ({p}) of the" " Apply with dense outputs sizes)" ), file=file, @@ -1545,8 +1535,7 @@ def amdlibm_speed_up(op): return True elif s_op.__class__ not in scalar_op_amdlibm_no_speed_up: print( - "We don't know if amdlibm will accelerate " - "this scalar op.", + "We don't know if amdlibm will accelerate this scalar op.", s_op, file=file, ) diff --git a/pytensor/configdefaults.py b/pytensor/configdefaults.py index 7698c5d441..f99b8240ca 100644 --- a/pytensor/configdefaults.py +++ b/pytensor/configdefaults.py @@ -67,8 +67,7 @@ def _warn_cxx(val): """We only support clang++ as otherwise we hit strange g++/OSX bugs.""" if sys.platform == "darwin" and val and "clang++" not in val: _logger.warning( - "Only clang++ is supported. With g++," - " we end up with strange g++/OSX bugs." + "Only clang++ is supported. With g++, we end up with strange g++/OSX bugs." ) return True diff --git a/pytensor/gradient.py b/pytensor/gradient.py index 5924fd7fcb..ecdf4fbd4c 100644 --- a/pytensor/gradient.py +++ b/pytensor/gradient.py @@ -624,8 +624,7 @@ def grad( if cost is not None and isinstance(cost.type, NullType): raise ValueError( - "Can't differentiate a NaN cost. " - f"Cost is NaN because {cost.type.why_null}" + f"Can't differentiate a NaN cost. Cost is NaN because {cost.type.why_null}" ) if cost is not None and cost.type.ndim != 0: @@ -2199,9 +2198,9 @@ def hessian(cost, wrt, consider_constant=None, disconnected_inputs="raise"): sequences=pytensor.tensor.arange(expr.shape[0]), non_sequences=[expr, input], ) - assert ( - not updates - ), "Scan has returned a list of updates; this should not happen." + assert not updates, ( + "Scan has returned a list of updates; this should not happen." + ) hessians.append(hess) return as_list_or_tuple(using_list, using_tuple, hessians) diff --git a/pytensor/graph/basic.py b/pytensor/graph/basic.py index 5d6667683b..1ee46f3449 100644 --- a/pytensor/graph/basic.py +++ b/pytensor/graph/basic.py @@ -427,19 +427,17 @@ class Variable(Node, Generic[_TypeType, OptionalApplyType]): c = a + b # create a simple expression - f = pytensor.function( - [b], [c] - ) # this works because a has a value associated with it already + # this works because a has a value associated with it already + f = pytensor.function([b], [c]) - assert 4.0 == f(2.5) # bind 2.5 to an internal copy of b and evaluate an internal c + # bind 2.5 to an internal copy of b and evaluate an internal c + assert 4.0 == f(2.5) - pytensor.function( - [a], [c] - ) # compilation error because b (required by c) is undefined + # compilation error because b (required by c) is undefined + pytensor.function([a], [c]) - pytensor.function( - [a, b], [c] - ) # compilation error because a is constant, it can't be an input + # compilation error because a is constant, it can't be an input + pytensor.function([a, b], [c]) The python variables ``a, b, c`` all refer to instances of type diff --git a/pytensor/graph/features.py b/pytensor/graph/features.py index a6e5b870c7..f03b58dfcb 100644 --- a/pytensor/graph/features.py +++ b/pytensor/graph/features.py @@ -391,8 +391,7 @@ def __init__(self): def on_attach(self, fgraph): if hasattr(fgraph, "checkpoint") or hasattr(fgraph, "revert"): raise AlreadyThere( - "History feature is already present or in" - " conflict with another plugin." + "History feature is already present or in conflict with another plugin." ) self.history[fgraph] = [] # Don't call unpickle here, as ReplaceValidate.on_attach() diff --git a/pytensor/graph/fg.py b/pytensor/graph/fg.py index b97068da0f..2728d50a50 100644 --- a/pytensor/graph/fg.py +++ b/pytensor/graph/fg.py @@ -559,7 +559,7 @@ def remove_node(self, node: Apply, reason: str | None = None): out_clients = clients.get(out, ()) while out_clients: - out_client, out_idx = out_clients.pop() + out_client, _out_idx = out_clients.pop() if isinstance(out_client.op, Output): self.remove_output(out_client.op.idx, remove_client=False) diff --git a/pytensor/graph/rewriting/basic.py b/pytensor/graph/rewriting/basic.py index 750250ea0d..0a36ceadb7 100644 --- a/pytensor/graph/rewriting/basic.py +++ b/pytensor/graph/rewriting/basic.py @@ -2827,7 +2827,7 @@ def local_recursive_function( else: out_index = 0 - final_outs, rewritten_nodes = local_recursive_function(rewrites, out, {}, 0) + final_outs, _rewritten_nodes = local_recursive_function(rewrites, out, {}, 0) return final_outs[out_index] @@ -2975,10 +2975,7 @@ def check_stack_trace(f_or_fgraph, ops_to_check="last", bug_print="raise"): raise ValueError("ops_to_check does not have the right type") if not apply_nodes_to_check: - msg = ( - "Provided op instances/classes are not in the graph or the " - "graph is empty" - ) + msg = "Provided op instances/classes are not in the graph or the graph is empty" if bug_print == "warn": warnings.warn(msg) elif bug_print == "raise": diff --git a/pytensor/graph/rewriting/db.py b/pytensor/graph/rewriting/db.py index fc18636a1a..b5f0de04aa 100644 --- a/pytensor/graph/rewriting/db.py +++ b/pytensor/graph/rewriting/db.py @@ -464,7 +464,7 @@ def query(self, *tags, position_cutoff: int | float | None = None, **kwtags): return ret def print_summary(self, stream=sys.stdout): - print(f"{self.__class__.__name__ } (id {id(self)})", file=stream) + print(f"{self.__class__.__name__} (id {id(self)})", file=stream) positions = list(self.__position__.items()) def c(a, b): diff --git a/pytensor/link/basic.py b/pytensor/link/basic.py index 9d9c8c2ae4..1c79d28289 100644 --- a/pytensor/link/basic.py +++ b/pytensor/link/basic.py @@ -509,7 +509,7 @@ def make_thunk(self, **kwargs): kwargs.pop("input_storage", None) make_all += [x.make_all(**kwargs) for x in self.linkers[1:]] - fns, input_lists, output_lists, thunk_lists, order_lists = zip( + _fns, input_lists, output_lists, thunk_lists, order_lists = zip( *make_all, strict=True ) diff --git a/pytensor/link/c/basic.py b/pytensor/link/c/basic.py index 0fe46c8a9f..5e4019a55c 100644 --- a/pytensor/link/c/basic.py +++ b/pytensor/link/c/basic.py @@ -108,12 +108,12 @@ def failure_code(sub, use_goto=True): be careful to avoid executing incorrect code. """ + id = sub["id"] + failure_var = sub["failure_var"] if use_goto: - goto_statement = "goto __label_%(id)i;" % sub + goto_statement = f"goto __label_{id};" else: goto_statement = "" - id = sub["id"] - failure_var = sub["failure_var"] return f"""{{ {failure_var} = {id}; if (!PyErr_Occurred()) {{ @@ -821,9 +821,9 @@ def code_gen(self): behavior = op.c_code(node, name, isyms, osyms, sub) - assert isinstance( - behavior, str - ), f"{node.op} didn't return a string for c_code" + assert isinstance(behavior, str), ( + f"{node.op} didn't return a string for c_code" + ) # To help understand what is following. It help read the c code. # This prevent different op that generate the same c code # to be merged, I suppose this won't happen... @@ -1738,7 +1738,7 @@ def find_task(self, failure_code): def __call__(self): failure = self.run_cthunk(self.cthunk) if failure: - task, taskname, id = self.find_task(failure) + task, _taskname, _id = self.find_task(failure) try: trace = task.trace except AttributeError: @@ -1753,8 +1753,7 @@ def __call__(self): except Exception: print( # noqa: T201 ( - "ERROR retrieving error_storage." - "Was the error set in the c code?" + "ERROR retrieving error_storage. Was the error set in the c code?" ), end=" ", file=sys.stderr, @@ -1981,7 +1980,7 @@ def make_thunk(self, **kwargs): .make_all(**kwargs) ) kwargs.pop("input_storage", None) - _f, i2, o2, thunks2, order2 = ( + _f, i2, _o2, thunks2, order2 = ( OpWiseCLinker(schedule=self.schedule) .accept(fgraph, no_recycling=no_recycling) .make_all(**kwargs) diff --git a/pytensor/link/c/cmodule.py b/pytensor/link/c/cmodule.py index da20c4b167..4e269f8be5 100644 --- a/pytensor/link/c/cmodule.py +++ b/pytensor/link/c/cmodule.py @@ -1496,7 +1496,7 @@ def clear_unversioned(self, min_age=None): # May happen for broken versioned keys. continue for key_idx, key in enumerate(key_data.keys): - version, rest = key + version, _rest = key if version: # Since the version is included in the module hash, # it should not be possible to mix versioned and @@ -2243,7 +2243,7 @@ def join_options(init_part): if "target-cpu" in p: opt = p.split() if len(opt) == 2: - opt_name, opt_val = opt + _opt_name, opt_val = opt new_flags[i] = f"-march={opt_val}" # Some versions of GCC report the native arch @@ -2474,7 +2474,7 @@ def linking_patch(lib_dirs: list[str], libs: list[str]) -> list[str]: else: # In explicit else because of https://github.com/python/mypy/issues/10773 def sort_key(lib): - name, *numbers, extension = lib.split(".") + _name, *numbers, extension = lib.split(".") return (extension == "dll", tuple(map(int, numbers))) patched_lib_ldflags = [] diff --git a/pytensor/link/c/op.py b/pytensor/link/c/op.py index 8ccfa2a9a3..2a0170f98d 100644 --- a/pytensor/link/c/op.py +++ b/pytensor/link/c/op.py @@ -84,7 +84,7 @@ def is_f16(t): outputs = cl.make_thunk( input_storage=node_input_storage, output_storage=node_output_storage ) - thunk, node_input_filters, node_output_filters = outputs + thunk, _node_input_filters, _node_output_filters = outputs if compute_map is None: rval = is_cthunk_wrapper_type(thunk) @@ -588,7 +588,7 @@ def c_code(self, node, name, inp, out, sub): {define_macros} {{ if ({self.func_name}({self.format_c_function_args(inp, out)}{params}) != 0) {{ - {sub['fail']} + {sub["fail"]} }} }} {undef_macros} diff --git a/pytensor/link/c/params_type.py b/pytensor/link/c/params_type.py index 457983ce03..dbb8cda8e3 100644 --- a/pytensor/link/c/params_type.py +++ b/pytensor/link/c/params_type.py @@ -116,7 +116,8 @@ def __init__(value_attr1, value_attr2): .. code-block:: python wrapper = ParamsType( - enum1=EnumList("A", ("B", "beta"), "C"), enum2=EnumList(("D", "delta"), "E", "F") + enum1=EnumList("A", ("B", "beta"), "C"), + enum2=EnumList(("D", "delta"), "E", "F"), ) b1 = wrapper.B b2 = wrapper.get_enum("B") @@ -540,7 +541,9 @@ def enum_from_alias(self, alias): wrapper = ParamsType( scalar=ScalarType("int32"), letters=EnumType(A=(1, "alpha"), B=(2, "beta"), C=3), - digits=EnumList(("ZERO", "nothing"), ("ONE", "unit"), ("TWO", "couple")), + digits=EnumList( + ("ZERO", "nothing"), ("ONE", "unit"), ("TWO", "couple") + ), ) print(wrapper.get_enum("C")) # 3 print(wrapper.get_enum("TWO")) # 2 @@ -593,7 +596,9 @@ def __init__(self): self.b = numpy.asarray([[1, 2, 3], [4, 5, 6]]) - params_type = ParamsType(a=ScalarType("int32"), b=dmatrix, c=ScalarType("bool")) + params_type = ParamsType( + a=ScalarType("int32"), b=dmatrix, c=ScalarType("bool") + ) o = MyObject() value_for_c = False @@ -852,20 +857,20 @@ def c_extract(self, name, sub, check_input=True, **kwargs): const char* fields[] = {{{fields_list}}}; if (py_{name} == Py_None) {{ PyErr_SetString(PyExc_ValueError, "ParamsType: expected an object, not None."); - {sub['fail']} + {sub["fail"]} }} for (int i = 0; i < {self.length}; ++i) {{ PyObject* o = PyDict_GetItemString(py_{name}, fields[i]); if (o == NULL) {{ PyErr_Format(PyExc_TypeError, "ParamsType: missing expected attribute \\"%s\\" in object.", fields[i]); - {sub['fail']} + {sub["fail"]} }} {name}->extract(o, i); if ({name}->errorOccurred()) {{ /* The extract code from attribute type should have already raised a Python exception, * so we just print the attribute name in stderr. */ fprintf(stderr, "\\nParamsType: error when extracting value for attribute \\"%s\\".\\n", fields[i]); - {sub['fail']} + {sub["fail"]} }} }} }} diff --git a/pytensor/link/c/type.py b/pytensor/link/c/type.py index 1c35c4897a..84715eebb6 100644 --- a/pytensor/link/c/type.py +++ b/pytensor/link/c/type.py @@ -350,7 +350,11 @@ class EnumType(CType, dict): .. code-block:: python enum = EnumType( - CONSTANT_1=0, CONSTANT_2=1, CONSTANT_3=2, ctype="size_t", cname="MyEnumName" + CONSTANT_1=0, + CONSTANT_2=1, + CONSTANT_3=2, + ctype="size_t", + cname="MyEnumName", ) **Example with aliases** @@ -477,7 +481,7 @@ def get_aliases(self): return tuple(sorted(self.aliases)) def __repr__(self): - names_to_aliases = {constant_name: "" for constant_name in self} + names_to_aliases = dict.fromkeys(self, "") for alias in self.aliases: names_to_aliases[self.aliases[alias]] = f"({alias})" args = ", ".join(f"{k}{names_to_aliases[k]}:{self[k]}" for k in sorted(self)) @@ -674,7 +678,9 @@ class EnumList(EnumType): .. code-block:: python - enum = EnumList(("A", "alpha"), ("B", "beta"), "C", "D", "E", "F", ("G", "gamma")) + enum = EnumList( + ("A", "alpha"), ("B", "beta"), "C", "D", "E", "F", ("G", "gamma") + ) See test class :class:`tests.graph.test_types.TestOpEnumList` for a working example. diff --git a/pytensor/link/jax/dispatch/random.py b/pytensor/link/jax/dispatch/random.py index b298492915..edd9fff8b5 100644 --- a/pytensor/link/jax/dispatch/random.py +++ b/pytensor/link/jax/dispatch/random.py @@ -288,7 +288,7 @@ def jax_funcify_choice(op: ptr.ChoiceWithoutReplacement, node): """JAX implementation of `ChoiceRV`.""" batch_ndim = op.batch_ndim(node) - a_core_ndim, *p_core_ndim, _ = op.ndims_params + a_core_ndim, *_p_core_ndim, _ = op.ndims_params if batch_ndim and a_core_ndim == 0: raise NotImplementedError( @@ -324,7 +324,7 @@ def sample_fn(rng_key, size, dtype, *parameters): batch_sampling_keys = jax.random.split(rng_key, np.prod(size)) # Ravel the batch dimensions because vmap only works along a single axis - raveled_batch_a = a.reshape((-1,) + a.shape[batch_ndim:]) + raveled_batch_a = a.reshape((-1, *a.shape[batch_ndim:])) if p is None: raveled_sample = jax.vmap( lambda key, a: jax.random.choice( @@ -332,7 +332,7 @@ def sample_fn(rng_key, size, dtype, *parameters): ) )(batch_sampling_keys, raveled_batch_a) else: - raveled_batch_p = p.reshape((-1,) + p.shape[batch_ndim:]) + raveled_batch_p = p.reshape((-1, *p.shape[batch_ndim:])) raveled_sample = jax.vmap( lambda key, a, p: jax.random.choice( key, a, shape=core_shape, replace=False, p=p @@ -363,7 +363,7 @@ def sample_fn(rng_key, size, dtype, *parameters): x = jax.numpy.broadcast_to(x, size + x.shape[batch_ndim:]) batch_sampling_keys = jax.random.split(rng_key, np.prod(size)) - raveled_batch_x = x.reshape((-1,) + x.shape[batch_ndim:]) + raveled_batch_x = x.reshape((-1, *x.shape[batch_ndim:])) raveled_sample = jax.vmap(lambda key, x: jax.random.permutation(key, x))( batch_sampling_keys, raveled_batch_x ) diff --git a/pytensor/link/jax/dispatch/scan.py b/pytensor/link/jax/dispatch/scan.py index 7ff939b43f..3c3080765c 100644 --- a/pytensor/link/jax/dispatch/scan.py +++ b/pytensor/link/jax/dispatch/scan.py @@ -90,7 +90,7 @@ def inner_func_outs_to_jax_outs( """ ( inner_mit_sot, - inner_sit_sot, + _inner_sit_sot, inner_shared, inner_non_seqs, ) = old_carry @@ -184,10 +184,10 @@ def get_shared_outs(final_carry): These outputs cannot be traced in PyTensor Scan """ ( - inner_out_mit_sot, - inner_out_sit_sot, + _inner_out_mit_sot, + _inner_out_sit_sot, inner_out_shared, - inner_in_non_seqs, + _inner_in_non_seqs, ) = final_carry shared_outs = inner_out_shared[: info.n_shared_outs] diff --git a/pytensor/link/numba/dispatch/linalg/_LAPACK.py b/pytensor/link/numba/dispatch/linalg/_LAPACK.py index 421d182c94..1381336fab 100644 --- a/pytensor/link/numba/dispatch/linalg/_LAPACK.py +++ b/pytensor/link/numba/dispatch/linalg/_LAPACK.py @@ -226,7 +226,7 @@ def numba_xlamch(cls, dtype): Determine machine precision for floating point arithmetic. """ - lapack_ptr, float_pointer = _get_lapack_ptr_and_ptr_type(dtype, "lamch") + lapack_ptr, _float_pointer = _get_lapack_ptr_and_ptr_type(dtype, "lamch") output_dtype = _get_output_ctype(dtype) functype = ctypes.CFUNCTYPE( output_dtype, # Output diff --git a/pytensor/link/numba/dispatch/linalg/decomposition/lu.py b/pytensor/link/numba/dispatch/linalg/decomposition/lu.py index 8a836cd76a..26b308d4ef 100644 --- a/pytensor/link/numba/dispatch/linalg/decomposition/lu.py +++ b/pytensor/link/numba/dispatch/linalg/decomposition/lu.py @@ -21,7 +21,7 @@ def _pivot_to_permutation(p, dtype): @numba_njit def _lu_factor_to_lu(a, dtype, overwrite_a): - A_copy, IPIV, INFO = _getrf(a, overwrite_a=overwrite_a) + A_copy, IPIV, _INFO = _getrf(a, overwrite_a=overwrite_a) L = np.eye(A_copy.shape[-1], dtype=dtype) L += np.tril(A_copy, k=-1) diff --git a/pytensor/link/numba/dispatch/scalar.py b/pytensor/link/numba/dispatch/scalar.py index ada4e8cc36..4e0019b74b 100644 --- a/pytensor/link/numba/dispatch/scalar.py +++ b/pytensor/link/numba/dispatch/scalar.py @@ -119,12 +119,12 @@ def {scalar_op_fn_name}({input_names}): ) if not has_pyx_skip_dispatch: scalar_op_src = f""" -def {scalar_op_fn_name}({', '.join(input_names)}): +def {scalar_op_fn_name}({", ".join(input_names)}): return direct_cast(scalar_func_numba({converted_call_args}), output_dtype) """ else: scalar_op_src = f""" -def {scalar_op_fn_name}({', '.join(input_names)}): +def {scalar_op_fn_name}({", ".join(input_names)}): return direct_cast(scalar_func_numba({converted_call_args}, np.intc(1)), output_dtype) """ diff --git a/pytensor/link/numba/dispatch/subtensor.py b/pytensor/link/numba/dispatch/subtensor.py index fe0eda153e..e877241977 100644 --- a/pytensor/link/numba/dispatch/subtensor.py +++ b/pytensor/link/numba/dispatch/subtensor.py @@ -107,9 +107,9 @@ def {function_name}({", ".join(input_names)}): @numba_funcify.register(AdvancedIncSubtensor) def numba_funcify_AdvancedSubtensor(op, node, **kwargs): if isinstance(op, AdvancedSubtensor): - x, y, idxs = node.inputs[0], None, node.inputs[1:] + _x, _y, idxs = node.inputs[0], None, node.inputs[1:] else: - x, y, *idxs = node.inputs + _x, _y, *idxs = node.inputs basic_idxs = [ idx @@ -286,7 +286,7 @@ def advanced_inc_subtensor_multiple_vector(x, y, *idxs): def numba_funcify_AdvancedIncSubtensor1(op, node, **kwargs): inplace = op.inplace set_instead_of_inc = op.set_instead_of_inc - x, vals, idxs = node.inputs + x, vals, _idxs = node.inputs broadcast_with_index = vals.type.ndim < x.type.ndim or vals.type.broadcastable[0] # TODO: Add runtime_broadcast check diff --git a/pytensor/link/pytorch/dispatch/basic.py b/pytensor/link/pytorch/dispatch/basic.py index 62fdd14bae..5e8d812a54 100644 --- a/pytensor/link/pytorch/dispatch/basic.py +++ b/pytensor/link/pytorch/dispatch/basic.py @@ -225,7 +225,7 @@ def tensorfromscalar(x): @pytorch_funcify.register(Split) def pytorch_funcify_Split(op, node, **kwargs): - x, dim, split_sizes = node.inputs + _x, dim, split_sizes = node.inputs if isinstance(dim, Constant) and isinstance(split_sizes, Constant): dim = int(dim.data) split_sizes = tuple(int(size) for size in split_sizes.data) diff --git a/pytensor/link/pytorch/dispatch/subtensor.py b/pytensor/link/pytorch/dispatch/subtensor.py index 5dfa7dfa36..26b4fd0f7f 100644 --- a/pytensor/link/pytorch/dispatch/subtensor.py +++ b/pytensor/link/pytorch/dispatch/subtensor.py @@ -24,7 +24,7 @@ def check_negative_steps(indices): @pytorch_funcify.register(Subtensor) def pytorch_funcify_Subtensor(op, node, **kwargs): idx_list = op.idx_list - x, *idxs = node.inputs + _x, *idxs = node.inputs if all(isinstance(idx, Constant) for idx in idxs): # Use constant indices to avoid graph break diff --git a/pytensor/link/vm.py b/pytensor/link/vm.py index c6e1283806..a2126855e4 100644 --- a/pytensor/link/vm.py +++ b/pytensor/link/vm.py @@ -83,16 +83,16 @@ def calculate_reallocate_info( ins = None if dmap and idx_o in dmap: idx_v = dmap[idx_o] - assert ( - len(idx_v) == 1 - ), "Here we only support the possibility to destroy one input" + assert len(idx_v) == 1, ( + "Here we only support the possibility to destroy one input" + ) ins = node.inputs[idx_v[0]] if vmap and idx_o in vmap: assert ins is None idx_v = vmap[idx_o] - assert ( - len(idx_v) == 1 - ), "Here we only support the possibility to view one input" + assert len(idx_v) == 1, ( + "Here we only support the possibility to view one input" + ) ins = node.inputs[idx_v[0]] if ins is not None: assert isinstance(ins, Variable) diff --git a/pytensor/misc/ordered_set.py b/pytensor/misc/ordered_set.py index c6b6566644..a33cc53c32 100644 --- a/pytensor/misc/ordered_set.py +++ b/pytensor/misc/ordered_set.py @@ -9,7 +9,7 @@ def __init__(self, iterable: Iterable | None = None) -> None: if iterable is None: self.values = {} else: - self.values = {value: None for value in iterable} + self.values = dict.fromkeys(iterable) def __contains__(self, value) -> bool: return value in self.values diff --git a/pytensor/printing.py b/pytensor/printing.py index c54a0a9b05..2600d15459 100644 --- a/pytensor/printing.py +++ b/pytensor/printing.py @@ -295,8 +295,10 @@ def debugprint( if hasattr(var.owner, "op"): if ( isinstance(var.owner.op, HasInnerGraph) - or hasattr(var.owner.op, "scalar_op") - and isinstance(var.owner.op.scalar_op, HasInnerGraph) + or ( + hasattr(var.owner.op, "scalar_op") + and isinstance(var.owner.op.scalar_op, HasInnerGraph) + ) ) and var not in inner_graph_vars: inner_graph_vars.append(var) if print_op_info: @@ -675,8 +677,10 @@ def get_id_str( if hasattr(in_var, "owner") and hasattr(in_var.owner, "op"): if ( isinstance(in_var.owner.op, HasInnerGraph) - or hasattr(in_var.owner.op, "scalar_op") - and isinstance(in_var.owner.op.scalar_op, HasInnerGraph) + or ( + hasattr(in_var.owner.op, "scalar_op") + and isinstance(in_var.owner.op.scalar_op, HasInnerGraph) + ) ) and in_var not in inner_graph_ops: inner_graph_ops.append(in_var) @@ -882,7 +886,9 @@ def process(self, output, pstate): max_i = len(node.inputs) - 1 for i, input in enumerate(node.inputs): new_precedence = self.precedence - if self.assoc == "left" and i != 0 or self.assoc == "right" and i != max_i: + if (self.assoc == "left" and i != 0) or ( + self.assoc == "right" and i != max_i + ): new_precedence += 1e-6 with set_precedence(pstate, new_precedence): diff --git a/pytensor/scalar/basic.py b/pytensor/scalar/basic.py index 769a5dfeeb..5102d5f609 100644 --- a/pytensor/scalar/basic.py +++ b/pytensor/scalar/basic.py @@ -1005,8 +1005,7 @@ def as_scalar(x: Any, name: str | None = None) -> ScalarVariable: # Also, if we do, why can't we support multiple outputs? if len(x.outputs) != 1: raise ValueError( - "It is ambiguous which output of a multi-output" - " Op has to be fetched.", + "It is ambiguous which output of a multi-output Op has to be fetched.", x, ) return as_scalar(x.outputs[0]) @@ -1692,7 +1691,7 @@ def get_grad(self, elem): def L_op(self, inputs, outputs, gout): (x, low, hi) = inputs - (gz,) = gout + (_gz,) = gout grads = [self.get_grad(elem) for elem in [x, low, hi]] return grads @@ -1731,7 +1730,7 @@ def L_op(self, inputs, outputs, gout): return (condition_grad, first_part, second_part) def output_types(self, types): - (cond_t, ift_t, iff_t) = types + (_cond_t, ift_t, iff_t) = types return upcast_out(ift_t, iff_t) @@ -2487,7 +2486,7 @@ def impl(self, x, y): return y def c_code(self, node, name, inputs, outputs, sub): - (x, y) = inputs + (_x, y) = inputs (z,) = outputs return f"{z} = {y};" @@ -2498,7 +2497,7 @@ def connection_pattern(self, node): return [[False], [True]] def grad(self, inputs, gout): - (x, y) = inputs + (_x, y) = inputs (gz,) = gout if y.type in continuous_types: # x is disconnected because the elements of x are not used @@ -2707,7 +2706,7 @@ def impl(self, x): def grad(self, inputs, gout): (x,) = inputs - (gz,) = gout + (_gz,) = gout rval = x.zeros_like() if rval.type in discrete_types: @@ -2748,7 +2747,7 @@ def impl(self, x): def grad(self, inputs, gout): (x,) = inputs - (gz,) = gout + (_gz,) = gout rval = x.zeros_like() if rval.type in discrete_types: @@ -2774,7 +2773,7 @@ def impl(self, x): def grad(self, inputs, gout): (x,) = inputs - (gz,) = gout + (_gz,) = gout rval = x.zeros_like() if rval.type in discrete_types: @@ -2800,7 +2799,7 @@ def impl(self, x): def grad(self, inputs, gout): (x,) = inputs - (gz,) = gout + (_gz,) = gout return [x.zeros_like(dtype=config.floatX)] def c_code(self, node, name, inputs, outputs, sub): @@ -2828,7 +2827,7 @@ def impl(self, x): def grad(self, inputs, gout): (x,) = inputs - (gz,) = gout + (_gz,) = gout rval = x.zeros_like() if rval.type in discrete_types: @@ -2914,7 +2913,7 @@ def impl(self, x): def grad(self, inputs, gout): (x,) = inputs - (gz,) = gout + (_gz,) = gout rval = x.zeros_like() if rval.type in discrete_types: @@ -3935,7 +3934,7 @@ def impl(self, x): return np.real(x) def grad(self, inputs, gout): - (x,) = inputs + (_x,) = inputs (gz,) = gout return [complex(gz, 0)] diff --git a/pytensor/scalar/loop.py b/pytensor/scalar/loop.py index 80168fd122..f23c4e1c42 100644 --- a/pytensor/scalar/loop.py +++ b/pytensor/scalar/loop.py @@ -219,7 +219,7 @@ def c_code_template(self): for i, c in enumerate(fgraph.inputs[n_update:], start=n_update + 1) } out_subd = {u: f"%(o{i})s" for i, u in enumerate(fgraph.outputs[:n_update])} - until_subd = {u: "until" for u in fgraph.outputs[n_update:]} + until_subd = dict.fromkeys(fgraph.outputs[n_update:], "until") subd = {**carry_subd, **constant_subd, **until_subd} for var in fgraph.variables: @@ -307,7 +307,7 @@ def c_code_template(self): # Output until flag if self.is_while: - _c_code += f"%(o{len(fgraph.outputs)-1})s = until;\n" + _c_code += f"%(o{len(fgraph.outputs) - 1})s = until;\n" _c_code += "}\n" diff --git a/pytensor/scalar/math.py b/pytensor/scalar/math.py index d08759a978..bbd6ec6064 100644 --- a/pytensor/scalar/math.py +++ b/pytensor/scalar/math.py @@ -1882,7 +1882,7 @@ def is_nonpositive_integer(x): # We have to pass the converges flag to interrupt the loop, as the switch is not lazy z_is_zero = eq(z, 0) converges = check_2f1_converges(a, b, c, z) - *grads, grad_converges = _grad_2f1_loop( + *grads, _grad_converges = _grad_2f1_loop( a, b, c, z, skip_loop=z_is_zero | (~converges), wrt=wrt, dtype=dtype ) diff --git a/pytensor/scan/op.py b/pytensor/scan/op.py index 05a860584e..80cfa0fcf3 100644 --- a/pytensor/scan/op.py +++ b/pytensor/scan/op.py @@ -2104,7 +2104,7 @@ def perform(self, node, inputs, output_storage): # are read and written. # This way, there will be no information overwritten # before it is read (as it used to happen). - shape = (pdx,) + output_storage[idx][0].shape[1:] + shape = (pdx, *output_storage[idx][0].shape[1:]) tmp = np.empty(shape, dtype=node.outputs[idx].type.dtype) tmp[:] = output_storage[idx][0][:pdx] output_storage[idx][0][: store_steps[idx] - pdx] = output_storage[ @@ -2113,7 +2113,7 @@ def perform(self, node, inputs, output_storage): output_storage[idx][0][store_steps[idx] - pdx :] = tmp del tmp else: - shape = (store_steps[idx] - pdx,) + output_storage[idx][0].shape[1:] + shape = (store_steps[idx] - pdx, *output_storage[idx][0].shape[1:]) tmp = np.empty(shape, dtype=node.outputs[idx].type.dtype) tmp[:] = output_storage[idx][0][pdx:] output_storage[idx][0][store_steps[idx] - pdx :] = output_storage[ @@ -2304,7 +2304,7 @@ def infer_shape(self, fgraph, node, input_shapes): if x is None: scan_outs.append(None) else: - scan_outs.append((Shape_i(0)(o),) + x[1:]) + scan_outs.append((Shape_i(0)(o), *x[1:])) return scan_outs def connection_pattern(self, node): @@ -2453,8 +2453,7 @@ def compute_all_gradients(known_grads): for g_y in g_y_s: if str(g_y.dtype) in integer_dtypes: raise TypeError( - "Gradients may never be integers but g_y " - f"has type {g_y.type}" + f"Gradients may never be integers but g_y has type {g_y.type}" ) out_indices = [get_out_idx(self_outputs.index(y)) for y in y_s] diff --git a/pytensor/scan/rewriting.py b/pytensor/scan/rewriting.py index 09793ab15a..0bc4f12143 100644 --- a/pytensor/scan/rewriting.py +++ b/pytensor/scan/rewriting.py @@ -846,8 +846,7 @@ def scan_push_out_add(fgraph, node): add_of_dot_nodes = [ n for n in op.fgraph.apply_nodes - if - ( + if ( # We have an Add isinstance(n.op, Elemwise) and isinstance(n.op.scalar_op, ps.Add) diff --git a/pytensor/sparse/basic.py b/pytensor/sparse/basic.py index 7f200b2a7c..6ad2a8336f 100644 --- a/pytensor/sparse/basic.py +++ b/pytensor/sparse/basic.py @@ -174,8 +174,7 @@ def as_sparse_variable(x, name=None, ndim=None, **kwargs): if isinstance(x, Apply): if len(x.outputs) != 1: raise ValueError( - "It is ambiguous which output of a " - "multi-output Op has to be fetched.", + "It is ambiguous which output of a multi-output Op has to be fetched.", x, ) else: @@ -617,7 +616,7 @@ def grad(self, inputs, g): if isinstance(g[0].type, DisconnectedType): return [csm.zeros_like()] - data, indices, indptr, _shape = csm_properties(csm) + _data, indices, indptr, _shape = csm_properties(csm) return [CSM(csm.format)(g[0], indices, indptr, _shape)] @@ -846,7 +845,7 @@ def perform(self, node, inputs, outputs): g_data, g_indices, g_indptr, - g_shape, + _g_shape, ) = inputs (g_out,) = outputs if len(x_indptr) - 1 == x_shape[0]: @@ -1333,8 +1332,7 @@ def make_node(self, x, index): # of dimension 1 and int/uint dtype. if scipy_ver < [0, 14] and ind.step is not None: raise ValueError( - "Slice with step is not support with current" - " version of Scipy." + "Slice with step is not support with current version of Scipy." ) if ind.step is None or ind.step == 1: step = generic_None @@ -1600,7 +1598,7 @@ def make_node(self, x, s): def perform(self, node, inputs, outputs): (x, s) = inputs (z,) = outputs - M, N = x.shape + _M, N = x.shape assert x.format == "csc" assert s.shape == (N,) @@ -1880,7 +1878,7 @@ def perform(self, node, inputs, outputs): z[0] = x.diagonal() def grad(self, inputs, gout): - (x,) = inputs + (_x,) = inputs (gz,) = gout return [square_diagonal(gz)] @@ -3021,7 +3019,7 @@ def perform(self, node, inputs, outputs): z[0] = c def grad(self, inputs, gout): - (x,) = inputs + (_x,) = inputs (gz,) = gout return [gz] @@ -4252,7 +4250,7 @@ def connection_pattern(self, node): def grad(self, inputs, grads): (g_output,) = grads - x, y = inputs[:2] + _x, _y = inputs[:2] idx_list = inputs[2:] gx = g_output diff --git a/pytensor/sparse/rewriting.py b/pytensor/sparse/rewriting.py index 72d5c1dbb3..041688fdc6 100644 --- a/pytensor/sparse/rewriting.py +++ b/pytensor/sparse/rewriting.py @@ -982,7 +982,7 @@ def make_node(self, a_val, a_ind, a_ptr, a_dim, b_val, b_ind, b_ptr, b_dim): def c_code(self, node, name, inputs, outputs, sub): # retrieve dtype number - (a_val, a_ind, a_ptr, a_dim, b_val, b_ind, b_ptr, b_dim) = inputs + (a_val, a_ind, a_ptr, a_dim, b_val, b_ind, b_ptr, _b_dim) = inputs (z,) = outputs typenum_z = node.outputs[0].type.dtype_specs()[2] if node.inputs[0].type.dtype in ("complex64", "complex128"): diff --git a/pytensor/sparse/sandbox/sp.py b/pytensor/sparse/sandbox/sp.py index 22cc8b6d62..f8aa211b84 100644 --- a/pytensor/sparse/sandbox/sp.py +++ b/pytensor/sparse/sandbox/sp.py @@ -258,7 +258,7 @@ def evaluate(inshp, kshp, strides=(1, 1), nkern=1, mode="valid", ws=True): def perform(self, node, inputs, outputs): (inshp, kshp) = inputs (out_indices, out_indptr, spmat_shape) = outputs - indices, indptr, spmatshp, outshp = self.evaluate(inshp, kshp) + indices, indptr, spmatshp, _outshp = self.evaluate(inshp, kshp) out_indices[0] = indices out_indptr[0] = indptr spmat_shape[0] = np.asarray(spmatshp) diff --git a/pytensor/sparse/sandbox/sp2.py b/pytensor/sparse/sandbox/sp2.py index a47fe72275..0e6f97b804 100644 --- a/pytensor/sparse/sandbox/sp2.py +++ b/pytensor/sparse/sandbox/sp2.py @@ -124,8 +124,8 @@ def connection_pattern(self, node): return [[True], [True], [False]] def grad(self, inputs, gout): - (n, p, shape) = inputs - (gz,) = gout + (n, p, _shape) = inputs + (_gz,) = gout comment_n = "No gradient exists for the number of samples in class\ Binomial of pytensor/sparse/sandbox/sp2.py" comment_p = "No gradient exists for the prob of success in class\ diff --git a/pytensor/tensor/_linalg/solve/rewriting.py b/pytensor/tensor/_linalg/solve/rewriting.py index ae97e6d61d..096acd6602 100644 --- a/pytensor/tensor/_linalg/solve/rewriting.py +++ b/pytensor/tensor/_linalg/solve/rewriting.py @@ -190,7 +190,7 @@ def _scan_split_non_sequence_decomposition_and_solve( and isinstance(inner_node.op.core_op, Solve) and inner_node.op.core_op.assume_a in allowed_assume_a ): - A, b = inner_node.inputs + A, _b = inner_node.inputs if all( (isinstance(root_inp, Constant) or (root_inp in non_sequences)) for root_inp in graph_inputs([A]) @@ -207,9 +207,9 @@ def _scan_split_non_sequence_decomposition_and_solve( eager=True, allowed_assume_a=allowed_assume_a, ) - assert ( - isinstance(replace_dict, dict) and len(replace_dict) > 0 - ), "Rewrite failed" + assert isinstance(replace_dict, dict) and len(replace_dict) > 0, ( + "Rewrite failed" + ) new_scan_fgraph.replace_all(replace_dict.items()) changed = True break # Break to start over with a fresh toposort diff --git a/pytensor/tensor/basic.py b/pytensor/tensor/basic.py index 2ecce07647..e789659474 100644 --- a/pytensor/tensor/basic.py +++ b/pytensor/tensor/basic.py @@ -367,7 +367,7 @@ def _get_underlying_scalar_constant_value( elif isinstance(op, ps.ScalarOp): if isinstance(v.owner.op, ps.Second): # We don't need both input to be constant for second - shp, val = v.owner.inputs + _shp, val = v.owner.inputs v = val continue if isinstance(v.owner.op, _scalar_constant_value_elemwise_ops): @@ -384,7 +384,7 @@ def _get_underlying_scalar_constant_value( elif isinstance(op, Elemwise): if isinstance(v.owner.op.scalar_op, ps.Second): # We don't need both input to be constant for second - shp, val = v.owner.inputs + _shp, val = v.owner.inputs v = val continue elif elemwise and isinstance( @@ -691,7 +691,7 @@ def infer_shape(self, fgraph, node, in_shapes): return [()] def grad(self, inp, grads): - (s,) = inp + (_s,) = inp (dt,) = grads return [tensor_from_scalar(dt)] @@ -2214,7 +2214,7 @@ def __init__(self, len_splits): self.view_map = {i: [0] for i in range(self.len_splits)} def __str__(self): - return f"{self.__class__.__name__ }{{{self.len_splits}}}" + return f"{self.__class__.__name__}{{{self.len_splits}}}" def make_node(self, x, axis, splits): """WRITEME""" @@ -2273,7 +2273,7 @@ def perform(self, node, inputs, outputs_storage): def infer_shape(self, fgraph, node, in_shapes): axis = node.inputs[1] splits = node.inputs[2] - shp_x, shp_axis, shp_splits = in_shapes + shp_x, _shp_axis, _shp_splits = in_shapes out_shapes = [] for i in range(self.len_splits): temp = as_tensor_variable(shp_x) @@ -2284,7 +2284,7 @@ def infer_shape(self, fgraph, node, in_shapes): def L_op(self, inputs, outputs, g_outputs): """Join the gradients along the axis that was used to split x.""" - x, axis, n = inputs + _x, axis, n = inputs # If all the output gradients are disconnected, then so are the inputs if builtins.all(isinstance(g.type, DisconnectedType) for g in g_outputs): @@ -2599,7 +2599,7 @@ def c_code(self, node, name, inputs, outputs, sub): code = f""" int axis = {axis_def} - PyArrayObject* arrays[{n}] = {{{','.join(arrays)}}}; + PyArrayObject* arrays[{n}] = {{{",".join(arrays)}}}; int out_is_valid = {out} != NULL; {axis_check} @@ -3354,7 +3354,7 @@ def connection_pattern(self, node): return [[True], [False], [True]] def L_op(self, inputs, outputs, grads): - start, stop, step = inputs + start, _stop, step = inputs (gz,) = grads # `start` and `step` affect the output values # but the outputs are integers so there's @@ -3874,7 +3874,7 @@ def c_code(self, node, nodename, input_names, output_names, sub): PyArrayObject *{out_name}_copy = (PyArrayObject*) PyArray_Copy({out_name}); Py_DECREF({out_name}); if (!{out_name}_copy) {{ - {sub['fail']}; // Error already set by Numpy + {sub["fail"]}; // Error already set by Numpy }} {out_name} = {out_name}_copy; }} @@ -4051,8 +4051,8 @@ def alloc_diag(diag, offset=0, axis1=0, axis2=1): # Re-order axes so they correspond to diagonals at axis1, axis2 axes = list(range(diag.type.ndim - 1)) last_idx = axes[-1] - axes = axes[:axis1] + [last_idx + 1] + axes[axis1:] - axes = axes[:axis2] + [last_idx + 2] + axes[axis2:] + axes = [*axes[:axis1], last_idx + 1, *axes[axis1:]] + axes = [*axes[:axis2], last_idx + 2, *axes[axis2:]] result = result.transpose(axes) return AllocDiag( @@ -4525,7 +4525,7 @@ def _make_along_axis_idx(arr_shape, indices, axis): if dim is None: fancy_index.append(indices) else: - ind_shape = shape_ones[:dim] + (-1,) + shape_ones[dim + 1 :] + ind_shape = (*shape_ones[:dim], -1, *shape_ones[dim + 1 :]) fancy_index.append(arange(n).reshape(ind_shape)) return tuple(fancy_index) @@ -4577,73 +4577,73 @@ def ix_(*args): __all__ = [ - "take_along_axis", - "expand_dims", - "atleast_Nd", + "alloc", + "arange", + "as_tensor", + "as_tensor_variable", "atleast_1d", "atleast_2d", "atleast_3d", + "atleast_Nd", + "cast", "choose", - "swapaxes", - "moveaxis", - "stacklists", + "concatenate", + "constant", + "default", "diag", "diagonal", - "inverse_permutation", - "permute_row_elements", - "mgrid", - "ogrid", - "arange", - "tile", + "empty", + "empty_like", + "expand_dims", + "extract_diag", + "eye", + "fill", + "flatnonzero", "flatten", - "is_flat", - "vertical_stack", - "horizontal_stack", + "full", + "full_like", + "get_scalar_constant_value", + "get_underlying_scalar_constant_value", "get_vector_length", - "concatenate", - "stack", - "roll", - "join", - "split", - "transpose", - "matrix_transpose", - "default", - "tensor_copy", + "horizontal_stack", "identity", - "transfer", - "alloc", "identity_like", - "eye", - "triu", - "tril", - "tri", - "nonzero_values", - "flatnonzero", + "inverse_permutation", + "is_flat", + "join", + "matrix_transpose", + "mgrid", + "moveaxis", "nonzero", + "nonzero_values", + "ogrid", "ones", - "zeros", - "zeros_like", "ones_like", - "fill", + "permute_row_elements", + "roll", + "scalar_from_tensor", "second", - "where", + "split", + "stack", + "stacklists", + "swapaxes", "switch", - "cast", - "scalar_from_tensor", + "take_along_axis", + "tensor_copy", "tensor_from_scalar", - "get_scalar_constant_value", - "get_underlying_scalar_constant_value", - "constant", - "as_tensor_variable", - "as_tensor", - "extract_diag", - "full", - "full_like", - "empty", - "empty_like", + "tile", "trace", + "transfer", + "transpose", + "tri", + "tril", "tril_indices", "tril_indices_from", + "triu", "triu_indices", "triu_indices_from", + "vertical_stack", + "where", + "zeros", + "zeros_like", ] diff --git a/pytensor/tensor/blas.py b/pytensor/tensor/blas.py index 1b1459e55e..b19a4475f5 100644 --- a/pytensor/tensor/blas.py +++ b/pytensor/tensor/blas.py @@ -77,7 +77,6 @@ import functools import logging -import os import shlex import warnings from pathlib import Path @@ -402,9 +401,9 @@ def _ldflags( include_dir=False, ) for d in dirs: - for f in os.listdir(d.strip('"')): - if f.endswith(".so") or f.endswith(".dylib") or f.endswith(".dll"): - if any(f.find(ll) >= 0 for ll in l): + for f in Path(d.strip('"')).iterdir(): + if f.suffix in {".so", ".dylib", ".dll"}: + if any(f.stem.find(ll) >= 0 for ll in l): found_dyn = True # Special treatment of clang framework. Specifically for MacOS Accelerate if "-framework" in l and "Accelerate" in l: @@ -1644,7 +1643,7 @@ def R_op(self, inputs, eval_points): iv1 = pytensor.graph.op.get_test_value(inputs[1]) except TestValueError: pytensor.graph.op.missing_test_message( - "second input passed to BatchedDot.R_op has no test value" + "second input passed to BatchedDot. R_op has no test value" ) test_values_enabled = False @@ -1653,8 +1652,7 @@ def R_op(self, inputs, eval_points): ev0 = pytensor.graph.op.get_test_value(eval_points[0]) except TestValueError: pytensor.graph.op.missing_test_message( - "first eval point passed to BatchedDot.R_op " - "has no test value" + "first eval point passed to BatchedDot. R_op has no test value" ) test_values_enabled = False if eval_points[1]: @@ -1662,8 +1660,7 @@ def R_op(self, inputs, eval_points): ev1 = pytensor.graph.op.get_test_value(eval_points[1]) except TestValueError: pytensor.graph.op.missing_test_message( - "second eval point passed to BatchedDot.R_op " - "has no test value" + "second eval point passed to BatchedDot.R_op has no test value" ) test_values_enabled = False diff --git a/pytensor/tensor/conv/abstract_conv.py b/pytensor/tensor/conv/abstract_conv.py index 5b0441ac57..9adb6354b2 100644 --- a/pytensor/tensor/conv/abstract_conv.py +++ b/pytensor/tensor/conv/abstract_conv.py @@ -244,7 +244,7 @@ def get_conv_gradweights_shape( for i in range(len(subsample)) ) if unshared: - return (nchan,) + top_shape[2:] + (nkern,) + out_shp + return (nchan, *top_shape[2:], nkern, *out_shp) else: return (nchan, nkern, *out_shp) @@ -2487,14 +2487,12 @@ def make_node(self, img, kern): img = assert_shape( img, self.imshp, - "AbstractConv shape mismatch: shape of " - "image does not match given imshp.", + "AbstractConv shape mismatch: shape of image does not match given imshp.", ) kern = assert_shape( kern, self.kshp, - "AbstractConv shape mismatch: shape of " - "filters does not match given kshp.", + "AbstractConv shape mismatch: shape of filters does not match given kshp.", ) out_shape = ( @@ -2908,9 +2906,9 @@ def perform(self, node, inp, out_): def correct_for_groups(mat): mshp0 = mat.shape[0] // self.num_groups mshp1 = mat.shape[1] * self.num_groups - mat = mat.reshape((self.num_groups, mshp0) + mat.shape[1:]) + mat = mat.reshape((self.num_groups, mshp0, *mat.shape[1:])) mat = mat.transpose((1, 0, 2, *range(3, 3 + self.convdim))) - mat = mat.reshape((mshp0, mshp1) + mat.shape[-self.convdim :]) + mat = mat.reshape((mshp0, mshp1, *mat.shape[-self.convdim :])) return mat if self.num_groups > 1: @@ -3285,7 +3283,7 @@ def perform(self, node, inp, out_): def correct_for_groups(mat): mshp0 = mat.shape[0] // self.num_groups mshp1 = mat.shape[-self.convdim - 1] * self.num_groups - mat = mat.reshape((self.num_groups, mshp0) + mat.shape[1:]) + mat = mat.reshape((self.num_groups, mshp0, *mat.shape[1:])) if self.unshared: # for 2D -> (1, 2, 3, 0, 4, 5, 6) mat = mat.transpose( @@ -3296,14 +3294,16 @@ def correct_for_groups(mat): ) ) mat = mat.reshape( - (mshp0,) - + mat.shape[1 : 1 + self.convdim] - + (mshp1,) - + mat.shape[-self.convdim :] + ( + mshp0, + *mat.shape[1 : 1 + self.convdim], + mshp1, + *mat.shape[-self.convdim :], + ) ) else: mat = mat.transpose((1, 0, 2, *range(3, 3 + self.convdim))) - mat = mat.reshape((mshp0, mshp1) + mat.shape[-self.convdim :]) + mat = mat.reshape((mshp0, mshp1, *mat.shape[-self.convdim :])) return mat kern = correct_for_groups(kern) diff --git a/pytensor/tensor/einsum.py b/pytensor/tensor/einsum.py index b1517ebb56..6add65b4da 100644 --- a/pytensor/tensor/einsum.py +++ b/pytensor/tensor/einsum.py @@ -388,7 +388,7 @@ def _contraction_list_from_path( ) contract_tuple = _find_contraction(contract_inds, input_sets, output_set) - out_inds, input_sets, idx_removed, idx_contract = contract_tuple + out_inds, input_sets, idx_removed, _idx_contract = contract_tuple tmp_inputs = [input_list.pop(x) for x in contract_inds] @@ -671,9 +671,9 @@ def filter_singleton_dims(operand, names, other_operand, other_names): einsum_operands = list(tensor_operands) # So we can pop for operand_indices, contracted_names, einstr, _, _ in contraction_list: contracted_names = sorted(contracted_names) - assert len(contracted_names) == len( - set(contracted_names) - ), "The set was needed!" + assert len(contracted_names) == len(set(contracted_names)), ( + "The set was needed!" + ) input_str, result_names = einstr.split("->") input_names = input_str.split(",") diff --git a/pytensor/tensor/elemwise.py b/pytensor/tensor/elemwise.py index 5c98a2e023..c7f29e7602 100644 --- a/pytensor/tensor/elemwise.py +++ b/pytensor/tensor/elemwise.py @@ -821,7 +821,7 @@ def _c_all(self, node, nodename, inames, onames, sub): # for each input: # same as range(ndim), but with 'x' at all broadcastable positions orders = [ - [s == 1 and "x" or i for i, s in enumerate(input.type.shape)] + [(s == 1 and "x") or i for i, s in enumerate(input.type.shape)] for input in inputs ] diff --git a/pytensor/tensor/elemwise_cgen.py b/pytensor/tensor/elemwise_cgen.py index 9f3fef7627..cc970b6f3e 100644 --- a/pytensor/tensor/elemwise_cgen.py +++ b/pytensor/tensor/elemwise_cgen.py @@ -691,10 +691,10 @@ def make_reordered_loop_careduce( counter = iter(range(inp_ndim)) unsorted_vars = dedent( f""" - npy_intp dim_lengths[{inp_ndim}] = {{{','.join(f'{inp_var}_n{i}' for i in range(inp_ndim))}}}; - npy_intp inp_strides[{inp_ndim}] = {{{','.join(f'{inp_var}_stride{i}' for i in range(inp_ndim))}}}; - npy_intp acc_strides[{inp_ndim}] = {{{','.join("0" if i in reduction_axes else f'{acc_var}_stride{next(counter)}'for i in range(inp_ndim))}}}; - bool reduction_axes[{inp_ndim}] = {{{', '.join("1" if i in reduction_axes else "0" for i in range(inp_ndim))}}};\n + npy_intp dim_lengths[{inp_ndim}] = {{{",".join(f"{inp_var}_n{i}" for i in range(inp_ndim))}}}; + npy_intp inp_strides[{inp_ndim}] = {{{",".join(f"{inp_var}_stride{i}" for i in range(inp_ndim))}}}; + npy_intp acc_strides[{inp_ndim}] = {{{",".join("0" if i in reduction_axes else f"{acc_var}_stride{next(counter)}" for i in range(inp_ndim))}}}; + bool reduction_axes[{inp_ndim}] = {{{", ".join("1" if i in reduction_axes else "0" for i in range(inp_ndim))}}};\n """ ) diff --git a/pytensor/tensor/extra_ops.py b/pytensor/tensor/extra_ops.py index 6dafe646e8..de8dd32226 100644 --- a/pytensor/tensor/extra_ops.py +++ b/pytensor/tensor/extra_ops.py @@ -212,7 +212,7 @@ def c_code_cache_version(self): def grad(self, inputs, output_gradients): num_ins = len(inputs) if num_ins == 3: - x, v, sorter = inputs + x, v, _sorter = inputs else: x, v = inputs @@ -994,7 +994,7 @@ def grad(self, inp, cost_grad): The gradient is currently implemented for matrices only. """ - a, val = inp + a, _val = inp grad = cost_grad[0] if a.dtype.startswith("complex"): return [None, None] @@ -1120,7 +1120,7 @@ def grad(self, inp, cost_grad): ----- The gradient is currently implemented for matrices only. """ - a, val, offset = inp + a, _val, offset = inp grad = cost_grad[0] height, width = grad.shape @@ -1558,7 +1558,7 @@ def broadcast_shape_iter( (one,) * (max_dims - len(a)) + tuple( one - if sh == 1 or isinstance(sh, Constant) and sh.value == 1 + if sh == 1 or (isinstance(sh, Constant) and sh.value == 1) else (ps.as_scalar(sh) if not isinstance(sh, Variable) else sh) for sh in a ) @@ -2067,25 +2067,25 @@ def concat_with_broadcast(tensor_list, axis=0): __all__ = [ - "searchsorted", - "cumsum", - "cumprod", - "diff", - "bincount", - "squeeze", - "compress", - "repeat", "bartlett", - "fill_diagonal", - "fill_diagonal_offset", - "unique", - "unravel_index", - "ravel_multi_index", + "bincount", + "broadcast_arrays", "broadcast_shape", "broadcast_to", + "compress", "concat_with_broadcast", + "cumprod", + "cumsum", + "diff", + "fill_diagonal", + "fill_diagonal_offset", "geomspace", - "logspace", "linspace", - "broadcast_arrays", + "logspace", + "ravel_multi_index", + "repeat", + "searchsorted", + "squeeze", + "unique", + "unravel_index", ] diff --git a/pytensor/tensor/math.py b/pytensor/tensor/math.py index 8119b8a80e..6c201b22c8 100644 --- a/pytensor/tensor/math.py +++ b/pytensor/tensor/math.py @@ -4162,154 +4162,154 @@ def nan_to_num(x, nan=0.0, posinf=None, neginf=None): not_equal = neq __all__ = [ - "max_and_argmax", - "max", - "matmul", - "vecdot", - "matvec", - "vecmat", - "argmax", - "min", - "argmin", - "smallest", - "largest", - "lt", - "less", - "gt", - "greater", - "le", - "less_equal", - "ge", - "greater_equal", - "eq", - "equal", - "neq", - "not_equal", - "isnan", - "isinf", - "isposinf", - "isneginf", + "abs", + "add", + "all", "allclose", - "isclose", "and_", + "angle", + "any", + "arccos", + "arccosh", + "arcsin", + "arcsinh", + "arctan", + "arctan2", + "arctanh", + "argmax", + "argmin", + "betainc", + "betaincinv", "bitwise_and", - "or_", + "bitwise_not", "bitwise_or", - "xor", "bitwise_xor", - "invert", - "bitwise_not", - "abs", - "exp", - "exp2", - "expm1", - "neg", - "reciprocal", - "log", - "log2", - "log10", - "log1p", - "sgn", - "sign", "ceil", - "floor", - "trunc", - "iround", - "round", - "round_half_to_even", - "round_half_away_from_zero", - "sqr", - "square", - "cov", - "sqrt", - "deg2rad", - "rad2deg", + "ceil_intdiv", + "chi2sf", + "clip", + "complex", + "complex_from_polar", + "conj", + "conjugate", "cos", - "arccos", - "sin", - "arcsin", - "tan", - "arctan", - "arctan2", "cosh", - "arccosh", - "sinh", - "arcsinh", - "tanh", - "arctanh", + "cov", + "deg2rad", + "dense_dot", + "digamma", + "divmod", + "dot", + "eq", + "equal", "erf", "erfc", + "erfcinv", "erfcx", "erfinv", - "erfcinv", - "owens_t", + "exp", + "exp2", + "expit", + "expm1", + "floor", + "floor_div", "gamma", - "gammaln", - "psi", - "digamma", - "tri_gamma", - "polygamma", - "chi2sf", "gammainc", "gammaincc", - "gammau", - "gammal", - "gammaincinv", "gammainccinv", - "j0", - "j1", - "jv", + "gammaincinv", + "gammal", + "gammaln", + "gammau", + "ge", + "greater", + "greater_equal", + "gt", + "hyp2f1", "i0", "i1", + "imag", + "int_div", + "invert", + "iround", + "isclose", + "isinf", + "isnan", + "isneginf", + "isposinf", "iv", "ive", + "j0", + "j1", + "jv", "kn", "kv", "kve", - "sigmoid", - "expit", - "softplus", - "log1pexp", + "largest", + "le", + "less", + "less_equal", + "log", "log1mexp", - "betainc", - "betaincinv", - "real", - "imag", - "angle", - "complex", - "conj", - "conjugate", - "complex_from_polar", - "sum", - "prod", + "log1p", + "log1pexp", + "log2", + "log10", + "logaddexp", + "logsumexp", + "lt", + "matmul", + "matvec", + "max", + "max_and_argmax", + "maximum", "mean", "median", - "var", - "std", - "std", - "maximum", + "min", "minimum", - "divmod", - "add", - "sub", - "mul", - "true_div", - "int_div", - "floor_div", - "ceil_intdiv", "mod", - "pow", - "clip", - "dot", - "dense_dot", - "tensordot", + "mul", + "nan_to_num", + "neg", + "neq", + "not_equal", + "or_", "outer", - "any", - "all", - "ptp", + "owens_t", + "polygamma", + "pow", "power", - "logaddexp", - "logsumexp", - "hyp2f1", - "nan_to_num", + "prod", + "psi", + "ptp", + "rad2deg", + "real", + "reciprocal", + "round", + "round_half_away_from_zero", + "round_half_to_even", + "sgn", + "sigmoid", + "sign", + "sin", + "sinh", + "smallest", + "softplus", + "sqr", + "sqrt", + "square", + "std", + "std", + "sub", + "sum", + "tan", + "tanh", + "tensordot", + "tri_gamma", + "true_div", + "trunc", + "var", + "vecdot", + "vecmat", + "xor", ] diff --git a/pytensor/tensor/nlinalg.py b/pytensor/tensor/nlinalg.py index 6c9e2f6708..8abd2a6889 100644 --- a/pytensor/tensor/nlinalg.py +++ b/pytensor/tensor/nlinalg.py @@ -1114,19 +1114,19 @@ def kron(a, b): __all__ = [ - "pinv", - "inv", - "trace", - "matrix_dot", "det", "eig", "eigh", - "svd", + "inv", + "kron", "lstsq", + "matrix_dot", "matrix_power", "norm", + "pinv", "slogdet", + "svd", "tensorinv", "tensorsolve", - "kron", + "trace", ] diff --git a/pytensor/tensor/optimize.py b/pytensor/tensor/optimize.py index 7d4bdade77..9e7e685721 100644 --- a/pytensor/tensor/optimize.py +++ b/pytensor/tensor/optimize.py @@ -224,9 +224,9 @@ def prepare_node( def make_node(self, *inputs): assert len(inputs) == len(self.inner_inputs) for input, inner_input in zip(inputs, self.inner_inputs): - assert ( - input.type == inner_input.type - ), f"Input {input} does not match expected type {inner_input.type}" + assert input.type == inner_input.type, ( + f"Input {input} does not match expected type {inner_input.type}" + ) return Apply(self, inputs, [self.inner_inputs[0].type(), ps.bool("success")]) @@ -559,7 +559,7 @@ def perform(self, node, inputs, outputs): def L_op(self, inputs, outputs, output_grads): x, *args = inputs - x_star, success = outputs + x_star, _success = outputs output_grad, _ = output_grads inner_x, *inner_args = self.fgraph.inputs @@ -999,4 +999,4 @@ def root( return solution, success -__all__ = ["minimize_scalar", "minimize", "root_scalar", "root"] +__all__ = ["minimize", "minimize_scalar", "root", "root_scalar"] diff --git a/pytensor/tensor/pad.py b/pytensor/tensor/pad.py index 2a3b8b4588..cce7bee619 100644 --- a/pytensor/tensor/pad.py +++ b/pytensor/tensor/pad.py @@ -117,7 +117,7 @@ def _get_padding_slices( def _constant_pad( x: TensorVariable, pad_width: TensorVariable, constant_values: TensorVariable ) -> TensorVariable: - padded, area_slice, pad_width = _symbolic_pad(x, pad_width) + padded, _area_slice, pad_width = _symbolic_pad(x, pad_width) values = broadcast_to(constant_values, as_tensor((padded.ndim, 2))) for axis in range(padded.ndim): @@ -133,7 +133,7 @@ def _constant_pad( def _edge_pad(x: TensorVariable, pad_width: TensorVariable) -> TensorVariable: - padded, area_slice, pad_width = _symbolic_pad(x, pad_width) + padded, _area_slice, pad_width = _symbolic_pad(x, pad_width) for axis in range(padded.ndim): width_pair = pad_width[axis] dim_shape = padded.shape[axis] @@ -219,7 +219,7 @@ def _stat_pad( stat_func: Callable, stat_length: TensorVariable | None, ): - padded, area_slice, pad_width = _symbolic_pad(x, pad_width) + padded, _area_slice, pad_width = _symbolic_pad(x, pad_width) if stat_length is None: stat_length = [[None, None]] * padded.ndim # type: ignore else: @@ -243,7 +243,7 @@ def _stat_pad( def _linear_ramp_pad( x: TensorVariable, pad_width: TensorVariable, end_values: TensorVariable | int = 0 ) -> TensorVariable: - padded, area_slice, pad_width = _symbolic_pad(x, pad_width) + padded, _area_slice, pad_width = _symbolic_pad(x, pad_width) end_values = as_tensor(end_values) end_values = broadcast_to(end_values, as_tensor((padded.ndim, 2))) @@ -689,4 +689,4 @@ def pad( return cast(TensorVariable, op) -__all__ = ["pad", "flip"] +__all__ = ["flip", "pad"] diff --git a/pytensor/tensor/random/basic.py b/pytensor/tensor/random/basic.py index 3aeba505a9..59e02ee3b4 100644 --- a/pytensor/tensor/random/basic.py +++ b/pytensor/tensor/random/basic.py @@ -2132,42 +2132,42 @@ def permutation(x, **kwargs): __all__ = [ - "permutation", - "choice", - "integers", - "categorical", - "multinomial", + "bernoulli", + "beta", "betabinom", - "nbinom", "binomial", - "laplace", - "bernoulli", - "truncexpon", - "wald", - "invgamma", - "halfcauchy", + "categorical", "cauchy", - "hypergeometric", - "geometric", - "poisson", + "chisquare", + "choice", "dirichlet", - "multivariate_normal", - "vonmises", - "logistic", - "weibull", "exponential", - "gumbel", - "pareto", - "chisquare", "gamma", - "lognormal", + "gengamma", + "geometric", + "gumbel", + "halfcauchy", "halfnormal", + "hypergeometric", + "integers", + "invgamma", + "laplace", + "logistic", + "lognormal", + "multinomial", + "multivariate_normal", + "nbinom", + "negative_binomial", "normal", - "beta", - "triangular", - "uniform", + "pareto", + "permutation", + "poisson", "standard_normal", - "negative_binomial", - "gengamma", "t", + "triangular", + "truncexpon", + "uniform", + "vonmises", + "wald", + "weibull", ] diff --git a/pytensor/tensor/random/rewriting/numba.py b/pytensor/tensor/random/rewriting/numba.py index 3ed6c12781..008de25947 100644 --- a/pytensor/tensor/random/rewriting/numba.py +++ b/pytensor/tensor/random/rewriting/numba.py @@ -55,7 +55,7 @@ def introduce_explicit_core_shape_rv(fgraph, node): """ op: RandomVariable = node.op - next_rng, rv = node.outputs + _next_rng, rv = node.outputs shape_feature: ShapeFeature | None = getattr(fgraph, "shape_feature", None) if shape_feature: core_shape = [ diff --git a/pytensor/tensor/rewriting/basic.py b/pytensor/tensor/rewriting/basic.py index 696d89a366..c9ade02a00 100644 --- a/pytensor/tensor/rewriting/basic.py +++ b/pytensor/tensor/rewriting/basic.py @@ -448,7 +448,7 @@ def local_useless_fill(fgraph, node): rewrite. """ - r, v = node.inputs + _r, v = node.inputs out_type = node.outputs[0].type if ( diff --git a/pytensor/tensor/rewriting/elemwise.py b/pytensor/tensor/rewriting/elemwise.py index 65d9cfafb5..1bcaa8624d 100644 --- a/pytensor/tensor/rewriting/elemwise.py +++ b/pytensor/tensor/rewriting/elemwise.py @@ -392,7 +392,7 @@ def local_dimshuffle_lift(fgraph, node): ret = inode.op(*new_inputs, return_list=True) return ret if inode and isinstance(inode.op, DimShuffle): - new_order = [x == "x" and "x" or inode.op.new_order[x] for x in new_order] + new_order = [(x == "x" and "x") or inode.op.new_order[x] for x in new_order] inp = inode.inputs[0] if is_dimshuffle_useless(new_order, inp): diff --git a/pytensor/tensor/rewriting/extra_ops.py b/pytensor/tensor/rewriting/extra_ops.py index 92d1f04e9a..1b95bfc6d3 100644 --- a/pytensor/tensor/rewriting/extra_ops.py +++ b/pytensor/tensor/rewriting/extra_ops.py @@ -51,7 +51,7 @@ def local_Unique_Alloc_lift(fgraph, node): if not (alloc_var.owner and isinstance(alloc_var.owner.op, Alloc)): return False - alloced_var, *alloc_shape = alloc_var.owner.inputs + alloced_var, *_alloc_shape = alloc_var.owner.inputs new_unique, *_ = node.op.make_node(alloced_var).outputs @@ -84,7 +84,7 @@ def local_Unique_Repeat_lift(fgraph, node): if not (repeat_var.owner and isinstance(repeat_var.owner.op, Repeat)): return False - repeated_var, *repeat_shape = repeat_var.owner.inputs + repeated_var, *_repeat_shape = repeat_var.owner.inputs new_unique, *_ = node.op.make_node(repeated_var).outputs @@ -121,7 +121,7 @@ def local_Unique_second(fgraph, node): ): return False - shape_var, seconded_var = second_var.owner.inputs + _shape_var, seconded_var = second_var.owner.inputs new_unique, *_ = node.op.make_node(seconded_var).outputs diff --git a/pytensor/tensor/rewriting/linalg.py b/pytensor/tensor/rewriting/linalg.py index 2883cdf629..17a3ce9165 100644 --- a/pytensor/tensor/rewriting/linalg.py +++ b/pytensor/tensor/rewriting/linalg.py @@ -350,8 +350,10 @@ def local_lift_through_linalg( outer_op = node.op if y.owner and ( - isinstance(y.owner.op, Blockwise) - and isinstance(y.owner.op.core_op, BlockDiagonal) + ( + isinstance(y.owner.op, Blockwise) + and isinstance(y.owner.op.core_op, BlockDiagonal) + ) or isinstance(y.owner.op, KroneckerProduct) ): input_matrices = y.owner.inputs diff --git a/pytensor/tensor/rewriting/math.py b/pytensor/tensor/rewriting/math.py index e313163b6e..307700ac70 100644 --- a/pytensor/tensor/rewriting/math.py +++ b/pytensor/tensor/rewriting/math.py @@ -2514,7 +2514,7 @@ def local_log1p(fgraph, node): # log(1-x) -> log1p(-x) (log_arg,) = node.inputs if log_arg.owner and log_arg.owner.op == add: - scalars, scalar_inputs, nonconsts = scalarconsts_rest( + scalars, _scalar_inputs, nonconsts = scalarconsts_rest( log_arg.owner.inputs, only_process_constants=True ) # scalar_inputs are potentially dimshuffled and fill'd scalars @@ -3195,7 +3195,7 @@ def is_1pexp(t, only_process_constants=True): """ if t.owner and t.owner.op == add: - scalars, scalar_inputs, nonconsts = scalarconsts_rest( + scalars, _scalar_inputs, nonconsts = scalarconsts_rest( t.owner.inputs, only_process_constants=only_process_constants ) # scalar_inputs are potentially dimshuffled and filled with scalars @@ -3709,7 +3709,7 @@ def local_reciprocal_1_plus_exp(fgraph, node): # so we don't care to check client counts reciprocal_arg = node.inputs[0] if reciprocal_arg.owner and reciprocal_arg.owner.op == add: - scalars_, scalar_inputs, nonconsts = scalarconsts_rest( + scalars_, _scalar_inputs, nonconsts = scalarconsts_rest( reciprocal_arg.owner.inputs, only_process_constants=True ) # scalar_inputs are potentially dimshuffled and fill'd scalars diff --git a/pytensor/tensor/rewriting/shape.py b/pytensor/tensor/rewriting/shape.py index f784954dc9..5dd2859147 100644 --- a/pytensor/tensor/rewriting/shape.py +++ b/pytensor/tensor/rewriting/shape.py @@ -448,8 +448,7 @@ def update_shape(self, r, other_r): assert all( ( not hasattr(r.type, "shape") - or r.type.shape[i] != 1 - and other_r.type.shape[i] != 1 + or (r.type.shape[i] != 1 and other_r.type.shape[i] != 1) ) or self.lscalar_one.equals(merged_shape[i]) or self.lscalar_one.equals( diff --git a/pytensor/tensor/shape.py b/pytensor/tensor/shape.py index 34b141d454..78ab8864c9 100644 --- a/pytensor/tensor/shape.py +++ b/pytensor/tensor/shape.py @@ -469,7 +469,7 @@ def connection_pattern(self, node): return [[True], *[[False]] * len(node.inputs[1:])] def grad(self, inp, grads): - x, *shape = inp + _x, *shape = inp (gz,) = grads return [specify_shape(gz, shape)] + [ pytensor.gradient.DisconnectedType()() for _ in range(len(shape)) @@ -706,7 +706,7 @@ def connection_pattern(self, node): return [[True], [False]] def grad(self, inp, grads): - x, shp = inp + x, _shp = inp (g_out,) = grads return [reshape(g_out, shape(x), ndim=x.ndim), DisconnectedType()()] diff --git a/pytensor/tensor/signal/conv.py b/pytensor/tensor/signal/conv.py index 5d5d0c8f40..9eb9a8abf7 100644 --- a/pytensor/tensor/signal/conv.py +++ b/pytensor/tensor/signal/conv.py @@ -104,7 +104,7 @@ def c_code(self, node, name, inputs, outputs, sub): if (PyArray_NDIM({in1}) != 1 || PyArray_NDIM({in2}) != 1) {{ PyErr_SetString(PyExc_ValueError, "Convolve1d C code expects 1D arrays."); - {sub['fail']}; + {sub["fail"]}; }} npy_intp n_in2 = PyArray_DIM({in2}, 0); @@ -112,7 +112,7 @@ def c_code(self, node, name, inputs, outputs, sub): // Create a reversed view of in2 if (n_in2 == 0) {{ PyErr_SetString(PyExc_ValueError, "Convolve1d: second input (kernel) cannot be empty."); - {sub['fail']}; + {sub["fail"]}; }} else {{ npy_intp view_dims[1]; view_dims[0] = n_in2; @@ -136,7 +136,7 @@ def c_code(self, node, name, inputs, outputs, sub): if (!in2_flipped_view) {{ PyErr_SetString(PyExc_RuntimeError, "Failed to create flipped kernel view for Convolve1d."); - {sub['fail']}; + {sub["fail"]}; }} Py_INCREF({in2}); @@ -145,7 +145,7 @@ def c_code(self, node, name, inputs, outputs, sub): Py_DECREF(in2_flipped_view); in2_flipped_view = NULL; PyErr_SetString(PyExc_RuntimeError, "Failed to set base object for flipped kernel view in Convolve1d."); - {sub['fail']}; + {sub["fail"]}; }} PyArray_UpdateFlags(in2_flipped_view, (NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS)); }} @@ -156,7 +156,7 @@ def c_code(self, node, name, inputs, outputs, sub): Py_XDECREF(in2_flipped_view); // Clean up the view if correlate fails if (!{out}) {{ // PyArray_Correlate already set an error - {sub['fail']}; + {sub["fail"]}; }} }} """ diff --git a/pytensor/tensor/slinalg.py b/pytensor/tensor/slinalg.py index 68d056fdc0..e9fab7aa5e 100644 --- a/pytensor/tensor/slinalg.py +++ b/pytensor/tensor/slinalg.py @@ -88,7 +88,7 @@ def perform(self, node, inputs, outputs): # Squareness check if x.shape[0] != x.shape[1]: raise ValueError( - "Input array is expected to be square but has " f"the shape: {x.shape}." + f"Input array is expected to be square but has the shape: {x.shape}." ) # Scipy cholesky only makes use of overwrite_a when it is F_CONTIGUOUS @@ -322,7 +322,7 @@ def L_op(self, inputs, outputs, output_gradients): http://eprints.maths.ox.ac.uk/1079/ """ - A, b = inputs + A, _b = inputs c = outputs[0] # C is a scalar representing the entire graph @@ -1850,7 +1850,7 @@ def inplace_on_inputs(self, allowed_inplace_inputs: list[int]) -> "Op": def _call_and_get_lwork(self, fn, *args, lwork, **kwargs): if lwork in [-1, None]: - *_, work, info = fn(*args, lwork=-1, **kwargs) + *_, work, _info = fn(*args, lwork=-1, **kwargs) lwork = work.item() return fn(*args, lwork=lwork, **kwargs) @@ -1861,13 +1861,13 @@ def perform(self, node, inputs, outputs): if self.pivoting: (geqp3,) = get_lapack_funcs(("geqp3",), (x,)) - qr, jpvt, tau, *work_info = self._call_and_get_lwork( + qr, jpvt, tau, *_work_info = self._call_and_get_lwork( geqp3, x, lwork=-1, overwrite_a=self.overwrite_a ) jpvt -= 1 # geqp3 returns a 1-based index array, so subtract 1 else: (geqrf,) = get_lapack_funcs(("geqrf",), (x,)) - qr, tau, *work_info = self._call_and_get_lwork( + qr, tau, *_work_info = self._call_and_get_lwork( geqrf, x, lwork=-1, overwrite_a=self.overwrite_a ) @@ -1901,11 +1901,11 @@ def perform(self, node, inputs, outputs): (gor_un_gqr,) = get_lapack_funcs(("orgqr",), (qr,)) if M < N: - Q, work, info = self._call_and_get_lwork( + Q, _work, _info = self._call_and_get_lwork( gor_un_gqr, qr[:, :M], tau, lwork=-1, overwrite_a=1 ) elif self.mode == "economic": - Q, work, info = self._call_and_get_lwork( + Q, _work, _info = self._call_and_get_lwork( gor_un_gqr, qr, tau, lwork=-1, overwrite_a=1 ) else: @@ -1914,7 +1914,7 @@ def perform(self, node, inputs, outputs): qqr[:, :N] = qr # Always overwite qqr -- it's a meaningless intermediate value - Q, work, info = self._call_and_get_lwork( + Q, _work, _info = self._call_and_get_lwork( gor_un_gqr, qqr, tau, lwork=-1, overwrite_a=1 ) @@ -2088,18 +2088,18 @@ def qr( __all__ = [ + "block_diag", + "cho_solve", "cholesky", - "solve", "eigvalsh", "expm", - "solve_discrete_lyapunov", - "solve_continuous_lyapunov", - "solve_discrete_are", - "solve_triangular", - "block_diag", - "cho_solve", "lu", "lu_factor", "lu_solve", "qr", + "solve", + "solve_continuous_lyapunov", + "solve_discrete_are", + "solve_discrete_lyapunov", + "solve_triangular", ] diff --git a/pytensor/tensor/special.py b/pytensor/tensor/special.py index 3464294a14..b845e69b37 100644 --- a/pytensor/tensor/special.py +++ b/pytensor/tensor/special.py @@ -274,7 +274,7 @@ def perform(self, node, input_storage, output_storage): z[0] = scipy.special.softmax(x, axis=self.axis) def L_op(self, inp, outputs, grads): - (x,) = inp + (_x,) = inp (g_sm,) = grads return [SoftmaxGrad(axis=self.axis)(g_sm, outputs[0])] @@ -812,11 +812,11 @@ def betaln(a, b): __all__ = [ - "softmax", - "log_softmax", - "poch", - "factorial", - "logit", "beta", "betaln", + "factorial", + "log_softmax", + "logit", + "poch", + "softmax", ] diff --git a/pytensor/tensor/subtensor.py b/pytensor/tensor/subtensor.py index ccc706c7f2..d7fc1bedbc 100644 --- a/pytensor/tensor/subtensor.py +++ b/pytensor/tensor/subtensor.py @@ -1154,7 +1154,7 @@ def init_entry(entry, depth=0): subtensor_init = "\n".join(init_cmds) (x,) = inputs[:1] - (z,) = outputs + (_z,) = outputs if view_ndim: rval = f""" @@ -2028,7 +2028,7 @@ def grad(self, inputs, grads): class IncSubtensorPrinter(SubtensorPrinter): def process(self, r, pstate): - x, y, *idx_args = r.owner.inputs + x, _y, *idx_args = r.owner.inputs res = self._process(r.owner.op.idx_list, [x, *idx_args], pstate) @@ -2487,7 +2487,7 @@ def perform(self, node, inputs, output_storage): output_storage[0][0] = x def infer_shape(self, fgraph, node, ishapes): - x, y, ilist = ishapes + x, _y, _ilist = ishapes return [x] def R_op(self, inputs, eval_points): diff --git a/pytensor/tensor/type_other.py b/pytensor/tensor/type_other.py index 1454b18cde..61545df370 100644 --- a/pytensor/tensor/type_other.py +++ b/pytensor/tensor/type_other.py @@ -140,4 +140,4 @@ def as_symbolic_None(x, **kwargs): return NoneConst -__all__ = ["make_slice", "slicetype", "none_type_t", "NoneConst", "NoneSliceConst"] +__all__ = ["NoneConst", "NoneSliceConst", "make_slice", "none_type_t", "slicetype"] diff --git a/pytensor/utils.py b/pytensor/utils.py index 46c53b0759..e013c12e5d 100644 --- a/pytensor/utils.py +++ b/pytensor/utils.py @@ -14,16 +14,16 @@ __all__ = [ - "get_unbound_function", - "maybe_add_to_os_environ_pathlist", - "subprocess_Popen", - "call_subprocess_Popen", - "output_subprocess_Popen", "LOCAL_BITWIDTH", - "PYTHON_INT_BITWIDTH", - "NPY_RAVEL_AXIS", "NDARRAY_C_VERSION", + "NPY_RAVEL_AXIS", + "PYTHON_INT_BITWIDTH", "NoDuplicateOptWarningFilter", + "call_subprocess_Popen", + "get_unbound_function", + "maybe_add_to_os_environ_pathlist", + "output_subprocess_Popen", + "subprocess_Popen", ] diff --git a/pytensor/xtensor/rewriting/shape.py b/pytensor/xtensor/rewriting/shape.py index 73ca1c8a72..20abf2f00a 100644 --- a/pytensor/xtensor/rewriting/shape.py +++ b/pytensor/xtensor/rewriting/shape.py @@ -167,9 +167,9 @@ def lower_broadcast(fgraph, node): if dim in broadcast_dims and broadcast_dims[dim] is None: # If the dimension is not excluded, set its shape broadcast_dims[dim] = dim_length - assert not any( - value is None for value in broadcast_dims.values() - ), "All dimensions must have a length" + assert not any(value is None for value in broadcast_dims.values()), ( + "All dimensions must have a length" + ) # Create zeros with the broadcast dimensions, to then broadcast each input against # PyTensor will rewrite into using only the shapes of the zeros tensor diff --git a/pytensor/xtensor/shape.py b/pytensor/xtensor/shape.py index 3e2116e56b..0a7960228f 100644 --- a/pytensor/xtensor/shape.py +++ b/pytensor/xtensor/shape.py @@ -491,7 +491,7 @@ def expand_dims(x, dim=None, create_index_for_new_dim=None, axis=None, **dim_kwa if isinstance(dim, str): dims_dict = {dim: 1} elif isinstance(dim, Sequence) and not isinstance(dim, dict): - dims_dict = {d: 1 for d in dim} + dims_dict = dict.fromkeys(dim, 1) elif isinstance(dim, dict): dims_dict = {} for name, val in dim.items(): diff --git a/pytensor/xtensor/type.py b/pytensor/xtensor/type.py index 3adf872fd1..e5882b1dba 100644 --- a/pytensor/xtensor/type.py +++ b/pytensor/xtensor/type.py @@ -651,10 +651,10 @@ def _head_tail_or_thin( ) else: # Default to 5 for head and tail - indexers = {dim: 5 for dim in self.type.dims} + indexers = dict.fromkeys(self.type.dims, 5) elif not isinstance(indexers, dict): - indexers = {dim: indexers for dim in self.type.dims} + indexers = dict.fromkeys(self.type.dims, indexers) if kind == "head": indices = {dim: slice(None, value) for dim, value in indexers.items()} diff --git a/tests/compile/function/test_types.py b/tests/compile/function/test_types.py index 90589db337..89eb7b2393 100644 --- a/tests/compile/function/test_types.py +++ b/tests/compile/function/test_types.py @@ -47,9 +47,9 @@ class TestFunction: def test_none(self): fn = function([], None) # ok rval = fn() - assert ( - rval != [] - ), "See #254: Using None as function output leads to [] return value" + assert rval != [], ( + "See #254: Using None as function output leads to [] return value" + ) assert rval is None def test_empty(self): @@ -57,14 +57,14 @@ def test_empty(self): assert fn() == [] def test_extra_inputs(self): - x, s = scalars("xs") + x, _s = scalars("xs") fn = function([x], [x]) with pytest.raises(TypeError): fn(1, 2) def test_missing_inputs(self): def fn(): - x, s = scalars("xs") + x, _s = scalars("xs") function([], [x]) with pytest.raises(MissingInputError): @@ -162,7 +162,7 @@ def test_naming_rule0(self): def test_naming_rule1(self): a = scalar() # the a is for 'anonymous' (un-named). - x, s = scalars("xs") + _x, s = scalars("xs") f = function([a, s], a / s) assert f(1, 2) == 0.5 assert f(2, 1) == 2.0 diff --git a/tests/compile/test_builders.py b/tests/compile/test_builders.py index ba0257cdda..6c6906b31f 100644 --- a/tests/compile/test_builders.py +++ b/tests/compile/test_builders.py @@ -43,9 +43,9 @@ class TestOpFromGraph(unittest_tools.InferShapeTester): def test_valid_input(self): - x, y, z = matrices("xyz") + x, _y, _z = matrices("xyz") - with pytest.raises(ValueError, match="Expected at least.*"): + with pytest.raises(ValueError, match=r"Expected at least.*"): OpFromGraph([x], [x])() with pytest.raises(ValueError, match=r"Expected 1 input\(s\)"): @@ -61,7 +61,7 @@ def test_valid_input(self): OpFromGraph([x], [x], updates={}) def test_clone(self): - x, y, z = matrices("xyz") + x, _y, _z = matrices("xyz") ofg = OpFromGraph([x], [2 * x]) @@ -227,12 +227,12 @@ def go(inps, gs): # list override case def go1(inps, gs): - x, w, b = inps + _x, w, _b = inps g = gs[0] return g * w * 2 def go2(inps, gs): - x, w, b = inps + x, _w, _b = inps g = gs[0] return g * x * 1.5 @@ -563,7 +563,7 @@ def test_make_node_shared(self): assert y_clone != y y_clone.name = "y_clone" - out_new = test_ofg.make_node(*(out.owner.inputs[:1] + [y_clone])).outputs[0] + out_new = test_ofg.make_node(*([*out.owner.inputs[:1], y_clone])).outputs[0] assert "on_unused_input" in out_new.owner.op.kwargs assert out_new.owner.op.shared_inputs == [y_clone] diff --git a/tests/compile/test_debugmode.py b/tests/compile/test_debugmode.py index fae76fab0d..95d0074fc3 100644 --- a/tests/compile/test_debugmode.py +++ b/tests/compile/test_debugmode.py @@ -312,7 +312,7 @@ def insert_bad_dtype(fgraph, node): with pytest.raises(TypeError): e = einfo.value new_e = e.__class__("TTT" + str(e)) - exc_type, exc_value, exc_trace = sys.exc_info() + _exc_type, exc_value, exc_trace = sys.exc_info() exc_value = new_e raise exc_value.with_traceback(exc_trace) @@ -395,7 +395,7 @@ def make_node(self, a, b): return Apply(self, [a, b], [c]) def perform(self, node, inp, out): - a, b = inp + _a, b = inp (c,) = out c[0] = b @@ -405,7 +405,7 @@ def make_node(self, a, b): return Apply(self, [a, b], [c]) def perform(self, node, inp, out): - a, b = inp + _a, b = inp (c,) = out c[0] = b[1:3] @@ -453,7 +453,7 @@ def make_node(self, a, b): return Apply(self, [a, b], [c, d]) def perform(self, node, inp, out): - a, b = inp + a, _b = inp c, d = out c[0] = a d[0] = a[1:] @@ -477,7 +477,7 @@ def make_node(self, a, b): return Apply(self, [a, b], [c, d]) def perform(self, node, inp, out): - a, b = inp + a, _b = inp c, d = out r = a * 2 c[0] = r @@ -503,7 +503,7 @@ def make_node(self, a, b): return Apply(self, [a, b], [c, d]) def perform(self, node, inp, out): - a, b = inp + a, _b = inp c, d = out r = a * 1 c[0] = r @@ -528,7 +528,7 @@ def make_node(self, a, b): return Apply(self, [a, b], [c, d]) def perform(self, node, inp, out): - a, b = inp + a, _b = inp c, d = out r = a * 1 c[0] = r[:-1] diff --git a/tests/compile/test_misc.py b/tests/compile/test_misc.py index dd5698fc38..9e6b179c6f 100644 --- a/tests/compile/test_misc.py +++ b/tests/compile/test_misc.py @@ -62,7 +62,7 @@ def test_nnet(): for x in data: input = x[0:3] target = x[3:] - output, cost = nnet.sgd_step(input, target) + _output, cost = nnet.sgd_step(input, target) mean_cost += cost mean_cost /= float(len(data)) # print(f"Mean cost at epoch {epoch}: {mean_cost}") diff --git a/tests/compile/test_ops.py b/tests/compile/test_ops.py index 6d81caae6c..d27ba83bd4 100644 --- a/tests/compile/test_ops.py +++ b/tests/compile/test_ops.py @@ -70,7 +70,7 @@ def test_infer_shape(self): y.tag.test_value = [0, 0, 0, 0] def infer_shape(fgraph, node, shapes): - x, y = shapes + _x, y = shapes return [y] @wrap_py([dmatrix, dvector], dvector, infer_shape) diff --git a/tests/graph/rewriting/test_utils.py b/tests/graph/rewriting/test_utils.py index a8099b6296..37e63e66e4 100644 --- a/tests/graph/rewriting/test_utils.py +++ b/tests/graph/rewriting/test_utils.py @@ -29,7 +29,7 @@ def check(self, expected): def test_single_var(self): # Test `is_same_graph` with some trivial graphs (one Variable). - x, y, z = vectors("x", "y", "z") + x, y, _z = vectors("x", "y", "z") self.check( [ (x, x, (({}, True),)), diff --git a/tests/graph/test_basic.py b/tests/graph/test_basic.py index 9a929155bd..455b36f757 100644 --- a/tests/graph/test_basic.py +++ b/tests/graph/test_basic.py @@ -205,9 +205,9 @@ def test_eval(self): assert self.w.eval({self.x: 1.0, self.y: 2.0}) == 6.0 assert self.w.eval({self.z: 3}) == 6.0 assert hasattr(self.w, "_fn_cache"), "variable must have cache after eval" - assert not hasattr( - pickle.loads(pickle.dumps(self.w)), "_fn_cache" - ), "temporary functions must not be serialized" + assert not hasattr(pickle.loads(pickle.dumps(self.w)), "_fn_cache"), ( + "temporary functions must not be serialized" + ) def test_eval_with_strings(self): assert self.w.eval({"x": 1.0, self.y: 2.0}) == 6.0 diff --git a/tests/graph/test_compute_test_value.py b/tests/graph/test_compute_test_value.py index ea59ff68f8..c535cc97cc 100644 --- a/tests/graph/test_compute_test_value.py +++ b/tests/graph/test_compute_test_value.py @@ -219,7 +219,7 @@ def fx(prior_result, A): return prior_result * A # Symbolic description of the result - result, updates = pytensor.scan( + result, _updates = pytensor.scan( fn=fx, outputs_info=pt.ones_like(A), non_sequences=A, n_steps=k ) @@ -264,7 +264,7 @@ def fx(prior_result, A): fn=fx, outputs_info=pt.ones_like(A.T), non_sequences=A, n_steps=k ) - with pytest.raises(ValueError, match="^could not broadcast input"): + with pytest.raises(ValueError, match=r"^could not broadcast input"): pytensor.scan( fn=fx, outputs_info=pt.ones_like(A.T), non_sequences=A, n_steps=k ) diff --git a/tests/graph/test_destroyhandler.py b/tests/graph/test_destroyhandler.py index 70333f369b..761787e54c 100644 --- a/tests/graph/test_destroyhandler.py +++ b/tests/graph/test_destroyhandler.py @@ -155,7 +155,7 @@ def test_misc(): @assertFailure_fast def test_aliased_inputs_replacement(): - x, y, z = inputs() + x, y, _z = inputs() tv = transpose_view(x) tvv = transpose_view(tv) sx = sigmoid(x) @@ -223,14 +223,14 @@ def test_destroyers_loop(): def test_aliased_inputs(): - x, y, z = inputs() + x, _y, _z = inputs() e = add_in_place(x, x) g = create_fgraph([x], [e], False) assert not g.consistent() def test_aliased_inputs2(): - x, y, z = inputs() + x, _y, _z = inputs() e = add_in_place(x, transpose_view(x)) g = create_fgraph([x], [e], False) assert not g.consistent() @@ -238,14 +238,14 @@ def test_aliased_inputs2(): @assertFailure_fast def test_aliased_inputs_tolerate(): - x, y, z = inputs() + x, _y, _z = inputs() e = add_in_place_2(x, x) g = create_fgraph([x], [e], False) assert g.consistent() def test_aliased_inputs_tolerate2(): - x, y, z = inputs() + x, _y, _z = inputs() e = add_in_place_2(x, transpose_view(x)) g = create_fgraph([x], [e], False) assert not g.consistent() @@ -253,7 +253,7 @@ def test_aliased_inputs_tolerate2(): @assertFailure_fast def test_same_aliased_inputs_ignored(): - x, y, z = inputs() + x, _y, _z = inputs() e = add_in_place_3(x, x) g = create_fgraph([x], [e], False) assert g.consistent() @@ -261,7 +261,7 @@ def test_same_aliased_inputs_ignored(): @assertFailure_fast def test_different_aliased_inputs_ignored(): - x, y, z = inputs() + x, _y, _z = inputs() e = add_in_place_3(x, transpose_view(x)) g = create_fgraph([x], [e], False) assert g.consistent() @@ -325,7 +325,7 @@ def test_long_destroyers_loop(): def test_misc_2(): - x, y, z = inputs() + x, y, _z = inputs() tv = transpose_view(x) e = add_in_place(x, tv) g = create_fgraph([x, y], [e], False) @@ -398,7 +398,7 @@ def test_usage_loop_insert_views(): def test_value_repl(): - x, y, z = inputs() + x, y, _z = inputs() sy = sigmoid(y) e = add_in_place(x, sy) g = create_fgraph([x, y], [e], False) @@ -409,7 +409,7 @@ def test_value_repl(): @config.change_flags(compute_test_value="off") def test_value_repl_2(): - x, y, z = inputs() + x, y, _z = inputs() sy = sigmoid(y) e = add_in_place(x, sy) g = create_fgraph([x, y], [e], False) @@ -423,7 +423,7 @@ def test_multiple_inplace(): # this tests issue #5223 # there were some problems with Ops that have more than # one in-place input. - x, y, z = inputs() + x, y, _z = inputs() # we will try to replace this op with an in-place version m = multiple(x, y) # this makes it impossible to run in-place on x diff --git a/tests/graph/test_fg.py b/tests/graph/test_fg.py index cd69e9022c..c14ad2dce8 100644 --- a/tests/graph/test_fg.py +++ b/tests/graph/test_fg.py @@ -62,8 +62,8 @@ def test_validate_inputs(self): with pytest.raises( ValueError, match=( - "One of the provided inputs is the output of an already existing node. " - "If that is okay, either discard that input's owner or use graph.clone." + "One of the provided inputs is the output of an already existing node\\. " + "If that is okay, either discard that input's owner or use graph\\.clone\\." ), ): var3 = op1(var1) @@ -208,7 +208,7 @@ def test_import_var(self): assert var5 in fg.variables assert var5.owner in fg.apply_nodes - with pytest.raises(TypeError, match="Computation graph contains.*"): + with pytest.raises(TypeError, match=r"Computation graph contains.*"): from pytensor.graph.null_type import NullType fg.import_var(NullType()(), "testing") @@ -265,7 +265,7 @@ def test_replace_test_value(self): assert var6.tag.test_value.shape != var4.tag.test_value.shape - with pytest.raises(AssertionError, match="The replacement.*"): + with pytest.raises(AssertionError, match=r"The replacement.*"): fg.replace(var4, var6) def test_replace(self): @@ -342,12 +342,12 @@ def test_check_integrity(self): var5 = op3(var4, var2, var2) fg = FunctionGraph([var1, var2], [var3, var5], clone=False) - with pytest.raises(Exception, match="The following nodes are .*"): + with pytest.raises(Exception, match=r"The following nodes are .*"): fg.apply_nodes.remove(var5.owner) fg.check_integrity() - with pytest.raises(Exception, match="Inconsistent clients.*"): + with pytest.raises(Exception, match=r"Inconsistent clients.*"): fg.apply_nodes.add(var5.owner) fg.remove_client(var2, (var5.owner, 1)) @@ -355,14 +355,14 @@ def test_check_integrity(self): fg.add_client(var2, (var5.owner, 1)) - with pytest.raises(Exception, match="The following variables are.*"): + with pytest.raises(Exception, match=r"The following variables are.*"): fg.variables.remove(var4) fg.check_integrity() fg.variables.add(var4) - with pytest.raises(Exception, match="Undeclared input.*"): + with pytest.raises(Exception, match=r"Undeclared input.*"): var6 = MyVariable2("var6") fg.clients[var6] = [(var5.owner, 3)] fg.variables.add(var6) @@ -376,26 +376,26 @@ def test_check_integrity(self): # TODO: What if the index value is greater than 1? It will throw an # `IndexError`, but that doesn't sound like anything we'd want. out_node = Output(idx=1).make_node(var4) - with pytest.raises(Exception, match="Inconsistent clients list.*"): + with pytest.raises(Exception, match=r"Inconsistent clients list.*"): fg.add_client(var4, (out_node, 0)) fg.check_integrity() fg.remove_client(var4, (out_node, 0)) - with pytest.raises(TypeError, match="The first entry of.*"): + with pytest.raises(TypeError, match=r"The first entry of.*"): fg.add_client(var4, (None, 0)) var7 = op1(var4) - with pytest.raises(Exception, match="Client not in FunctionGraph.*"): + with pytest.raises(Exception, match=r"Client not in FunctionGraph.*"): fg.add_client(var4, (var7.owner, 0)) fg.check_integrity() fg.remove_client(var4, (var7.owner, 0)) - with pytest.raises(Exception, match="Inconsistent clients list.*"): + with pytest.raises(Exception, match=r"Inconsistent clients list.*"): fg.add_client(var4, (var3.owner, 0)) fg.check_integrity() diff --git a/tests/link/c/test_basic.py b/tests/link/c/test_basic.py index 62a828858d..2e975509dd 100644 --- a/tests/link/c/test_basic.py +++ b/tests/link/c/test_basic.py @@ -200,7 +200,7 @@ def test_cthunk_str(): y = double("y") e = add(x, y) lnk = CLinker().accept(FunctionGraph([x, y], [e])) - cthunk, input_storage, output_storage = lnk.make_thunk() + cthunk, _input_storage, _output_storage = lnk.make_thunk() assert str(cthunk).startswith("_CThunk") assert "module" in str(cthunk) @@ -253,7 +253,7 @@ def test_clinker_literal_cache(): not config.cxx, reason="G++ not available, so we need to skip this test." ) def test_clinker_single_node(): - x, y, z = inputs() + x, y, _z = inputs() node = add.make_node(x, y) lnk = CLinker().accept(FunctionGraph(node.inputs, node.outputs)) fn = make_function(lnk) @@ -265,7 +265,7 @@ def test_clinker_single_node(): ) def test_clinker_dups(): # Testing that duplicate inputs are allowed. - x, y, z = inputs() + x, _y, _z = inputs() e = add(x, x) lnk = CLinker().accept(FunctionGraph([x, x], [e])) fn = make_function(lnk) diff --git a/tests/link/c/test_params_type.py b/tests/link/c/test_params_type.py index 8fb47077af..6d680c7d5b 100644 --- a/tests/link/c/test_params_type.py +++ b/tests/link/c/test_params_type.py @@ -77,18 +77,18 @@ def c_code(self, node, name, inputs, outputs, sub): Y = outputs[0] float_type = node.inputs[0].type.c_element_type() return f""" - {float_type} a = ({float_type}) (*(npy_float64*) PyArray_GETPTR1({sub['params']}->a, 0)); // 0-D TensorType. - {float_type} b = {sub['params']}->b; // ScalarType. - {float_type} c = ({float_type}) PyFloat_AsDouble({sub['params']}->c); // Generic. + {float_type} a = ({float_type}) (*(npy_float64*) PyArray_GETPTR1({sub["params"]}->a, 0)); // 0-D TensorType. + {float_type} b = {sub["params"]}->b; // ScalarType. + {float_type} c = ({float_type}) PyFloat_AsDouble({sub["params"]}->c); // Generic. Py_XDECREF({Y}); {Y} = (PyArrayObject*)PyArray_EMPTY(PyArray_NDIM({X}), PyArray_DIMS({X}), PyArray_TYPE({X}), PyArray_IS_F_CONTIGUOUS({X})); if (PyArray_CopyInto({Y}, {X}) != 0) {{ PyErr_SetString(PyExc_RuntimeError, "Unable to copy input into output."); - {sub['fail']} + {sub["fail"]} }}; if (quadratic_{name}({Y}, a, b, c) != 0) {{ PyErr_SetString(PyExc_RuntimeError, "Unable to compute quadratic function."); - {sub['fail']} + {sub["fail"]} }} """ diff --git a/tests/link/c/test_type.py b/tests/link/c/test_type.py index 0ebd249bf4..5aa5765a43 100644 --- a/tests/link/c/test_type.py +++ b/tests/link/c/test_type.py @@ -201,7 +201,7 @@ def c_code_cache_version(self): def c_code(self, node, name, inputs, outputs, sub): # params in C code will already contains expected C constant value. return f""" - {outputs[0]} = {sub['params']}; + {outputs[0]} = {sub["params"]}; """ diff --git a/tests/link/jax/test_random.py b/tests/link/jax/test_random.py index 5a26d1617b..9cf148412e 100644 --- a/tests/link/jax/test_random.py +++ b/tests/link/jax/test_random.py @@ -90,9 +90,9 @@ def test_replaced_shared_rng_storage_order(noise_first): # The bug was found when noise used to be the first input of the fgraph # If this changes, the test may need to be tweaked to keep the save coverage - assert isinstance( - f.input_storage[1 - noise_first].type, RandomType - ), "Test may need to be tweaked" + assert isinstance(f.input_storage[1 - noise_first].type, RandomType), ( + "Test may need to be tweaked" + ) # Confirm that input_storage type and fgraph input order are aligned for storage, fgrapn_input in zip( diff --git a/tests/link/numba/test_random.py b/tests/link/numba/test_random.py index c311e87657..c7da82b2db 100644 --- a/tests/link/numba/test_random.py +++ b/tests/link/numba/test_random.py @@ -662,7 +662,7 @@ def test_unaligned_RandomVariable(rv_op, dist_args, base_size, cdf_name, params_ (10, 4), pytest.raises( ValueError, - match="Vectorized input 0 has an incompatible shape in axis 1.", + match="Vectorized input 0 has an incompatible shape in axis 1\\.", ), ), ], diff --git a/tests/link/numba/test_scan.py b/tests/link/numba/test_scan.py index a43ed72770..2edeff934c 100644 --- a/tests/link/numba/test_scan.py +++ b/tests/link/numba/test_scan.py @@ -343,7 +343,7 @@ def power_step(prior_result, x): def test_grad_sitsot(): def get_sum_of_grad(inp): - scan_outputs, updates = scan( + scan_outputs, _updates = scan( fn=lambda x: x * 2, outputs_info=[inp], n_steps=5, mode="NUMBA" ) return grad(scan_outputs.sum(), inp).sum() diff --git a/tests/link/pytorch/test_elemwise.py b/tests/link/pytorch/test_elemwise.py index 152b235074..dacf6f8699 100644 --- a/tests/link/pytorch/test_elemwise.py +++ b/tests/link/pytorch/test_elemwise.py @@ -108,7 +108,7 @@ def test_softmax(axis, dtype): if dtype == "int64": with pytest.raises( NotImplementedError, - match="Pytorch Softmax is not currently implemented for non-float types.", + match="Pytorch Softmax is not currently implemented for non-float types\\.", ): compare_pytorch_and_py([x], [out], [test_input]) else: @@ -125,7 +125,7 @@ def test_logsoftmax(axis, dtype): if dtype == "int64": with pytest.raises( NotImplementedError, - match="Pytorch LogSoftmax is not currently implemented for non-float types.", + match="Pytorch LogSoftmax is not currently implemented for non-float types\\.", ): compare_pytorch_and_py([x], [out], [test_input]) else: diff --git a/tests/link/pytorch/test_extra_ops.py b/tests/link/pytorch/test_extra_ops.py index 2f72f7a908..19b718ba54 100644 --- a/tests/link/pytorch/test_extra_ops.py +++ b/tests/link/pytorch/test_extra_ops.py @@ -24,9 +24,9 @@ def test_pytorch_CumOp(axis, dtype): # Create the output variable if isinstance(axis, tuple): - with pytest.raises(TypeError, match="axis must be an integer or None."): + with pytest.raises(TypeError, match="axis must be an integer or None\\."): out = pt.cumsum(a, axis=axis) - with pytest.raises(TypeError, match="axis must be an integer or None."): + with pytest.raises(TypeError, match="axis must be an integer or None\\."): out = pt.cumprod(a, axis=axis) else: out = pt.cumsum(a, axis=axis) diff --git a/tests/link/test_link.py b/tests/link/test_link.py index 7d84c2a478..410329aa4c 100644 --- a/tests/link/test_link.py +++ b/tests/link/test_link.py @@ -147,26 +147,26 @@ def test_function(self): assert fn(1.0, 2.0, 3.0) == 1.5 def test_constant(self): - x, y, z = inputs() + x, y, _z = inputs() y = Constant(tdouble, 2.0) e = mul(add(x, y), div(x, y)) fn = make_function(perform_linker(FunctionGraph([x], [e]))) assert fn(1.0) == 1.5 def test_input_output_same(self): - x, y, z = inputs() + x, _y, _z = inputs() fn = make_function(perform_linker(FunctionGraph([x], [x]))) assert 1.0 == fn(1.0) def test_input_dependency0(self): - x, y, z = inputs() + x, y, _z = inputs() a, d = add(x, y), div(x, y) e = mul(a, d) fn = make_function(perform_linker(FunctionGraph(*clone([x, y, a], [e])))) assert fn(1.0, 2.0, 9.0) == 4.5 def test_skiphole(self): - x, y, z = inputs() + x, y, _z = inputs() a = add(x, y) r = raise_err(a) e = add(r, a) diff --git a/tests/link/test_vm.py b/tests/link/test_vm.py index dad7ed4fdd..26058ce429 100644 --- a/tests/link/test_vm.py +++ b/tests/link/test_vm.py @@ -421,7 +421,7 @@ def make_thunk(self, *args, **kwargs): z = BadOp()(a) - with pytest.raises(Exception, match=".*Apply node that caused the error.*"): + with pytest.raises(Exception, match=r".*Apply node that caused the error.*"): function([a], z, mode=Mode(optimizer=None, linker=linker)) @@ -433,7 +433,7 @@ def __call__(self): a = scalar() fg = FunctionGraph(outputs=[SomeOp()(a)]) - with pytest.raises(ValueError, match="`nodes` and `thunks`.*"): + with pytest.raises(ValueError, match=r"`nodes` and `thunks`.*"): SomeVM(fg, fg.apply_nodes, [], []) @@ -453,7 +453,7 @@ def test_Loop_exception(): thunks = [node.op.make_thunk(node, storage_map, compute_map, []) for node in nodes] - with pytest.raises(ValueError, match="`nodes`, `thunks` and `post_thunk_clear`.*"): + with pytest.raises(ValueError, match=r"`nodes`, `thunks` and `post_thunk_clear`.*"): Loop( fg, fg.apply_nodes, diff --git a/tests/scalar/test_basic.py b/tests/scalar/test_basic.py index 2ab5a68c4c..bd7efc54bb 100644 --- a/tests/scalar/test_basic.py +++ b/tests/scalar/test_basic.py @@ -63,7 +63,7 @@ def test_mul_add_true(): - x, y, z = floats("xyz") + x, y, _z = floats("xyz") e = mul(add(x, y), true_div(x, y)) g = FunctionGraph([x, y], [e]) fn = make_function(DualLinker().accept(g)) @@ -109,7 +109,7 @@ def has_f16(comp): assert not has_f16(nc) def test_straightforward(self): - x, y, z = floats("xyz") + x, y, _z = floats("xyz") e = mul(add(x, y), true_div(x, y)) C = Composite([x, y], [e]) c = C.make_node(x, y) @@ -132,7 +132,7 @@ def test_flatten(self): @pytest.mark.parametrize("literal_value", (70.0, -np.inf, np.float32("nan"))) def test_with_constants(self, literal_value): - x, y, z = floats("xyz") + x, y, _z = floats("xyz") e = mul(add(literal_value, y), true_div(x, y)) comp_op = Composite([x, y], [e]) comp_node = comp_op.make_node(x, y) @@ -249,71 +249,71 @@ def c_code(self, *args): class TestLogical: def test_gt(self): - x, y, z = floats("xyz") + x, y, _z = floats("xyz") fn = make_function(DualLinker().accept(FunctionGraph([x, y], [x > y]))) for a, b in ((3.0, 9), (3, 0.9), (3, 3)): assert fn(a, b) == (a > b) def test_lt(self): - x, y, z = floats("xyz") + x, y, _z = floats("xyz") fn = make_function(DualLinker().accept(FunctionGraph([x, y], [x < y]))) for a, b in ((3.0, 9), (3, 0.9), (3, 3)): assert fn(a, b) == (a < b) def test_le(self): - x, y, z = floats("xyz") + x, y, _z = floats("xyz") fn = make_function(DualLinker().accept(FunctionGraph([x, y], [x <= y]))) for a, b in ((3.0, 9), (3, 0.9), (3, 3)): assert fn(a, b) == (a <= b) def test_ge(self): - x, y, z = floats("xyz") + x, y, _z = floats("xyz") fn = make_function(DualLinker().accept(FunctionGraph([x, y], [x >= y]))) for a, b in ((3.0, 9), (3, 0.9), (3, 3)): assert fn(a, b) == (a >= b) def test_eq(self): - x, y, z = floats("xyz") + x, y, _z = floats("xyz") fn = make_function(DualLinker().accept(FunctionGraph([x, y], [eq(x, y)]))) for a, b in ((3.0, 9), (3, 0.9), (3, 3)): assert fn(a, b) == (a == b) def test_neq(self): - x, y, z = floats("xyz") + x, y, _z = floats("xyz") fn = make_function(DualLinker().accept(FunctionGraph([x, y], [neq(x, y)]))) for a, b in ((3.0, 9), (3, 0.9), (3, 3)): assert fn(a, b) == (a != b) def test_or(self): - x, y, z = ints("xyz") + x, y, _z = ints("xyz") fn = make_function(DualLinker().accept(FunctionGraph([x, y], [x | y]))) for a, b in ((0, 1), (0, 0), (1, 0), (1, 1)): assert fn(a, b) == (a | b), (a, b) def test_xor(self): - x, y, z = ints("xyz") + x, y, _z = ints("xyz") fn = make_function(DualLinker().accept(FunctionGraph([x, y], [x ^ y]))) for a, b in ((0, 1), (0, 0), (1, 0), (1, 1)): assert fn(a, b) == (a ^ b), (a, b) def test_and(self): - x, y, z = ints("xyz") + x, y, _z = ints("xyz") fn = make_function(DualLinker().accept(FunctionGraph([x, y], [and_(x, y)]))) for a, b in ((0, 1), (0, 0), (1, 0), (1, 1)): assert fn(a, b) == (a & b), (a, b) - x, y, z = ints("xyz") + x, y, _z = ints("xyz") fn = make_function(DualLinker().accept(FunctionGraph([x, y], [x & y]))) for a, b in ((0, 1), (0, 0), (1, 0), (1, 1)): assert fn(a, b) == (a & b), (a, b) def test_not(self): - x, y, z = ints("xyz") + x, y, _z = ints("xyz") fn = make_function(DualLinker().accept(FunctionGraph([x, y], [invert(x)]))) for a, b in ((0, 1), (0, 0), (1, 0), (1, 1)): assert fn(a, b) == ~a, (a,) - x, y, z = ints("xyz") + x, y, _z = ints("xyz") fn = make_function(DualLinker().accept(FunctionGraph([x, y], [~x]))) for a, b in ((0, 1), (0, 0), (1, 0), (1, 1)): assert fn(a, b) == ~a, (a,) diff --git a/tests/scalar/test_loop.py b/tests/scalar/test_loop.py index 6e46a56cdc..d4f0f5b021 100644 --- a/tests/scalar/test_loop.py +++ b/tests/scalar/test_loop.py @@ -89,7 +89,7 @@ def update(x_prev, y_prev): return [x, y] op = ScalarLoop(init=[x0, y0], constant=[const], update=update(x0, y0)) - x, y = op(n_steps, x0, y0, const) + _x, y = op(n_steps, x0, y0, const) fn = function([n_steps, x0, y0, const], y, mode=mode) np.testing.assert_allclose(fn(n_steps=1, x0=0, y0=0, const=1), 0.0) diff --git a/tests/scan/test_basic.py b/tests/scan/test_basic.py index 2d3daeec0e..98a249c154 100644 --- a/tests/scan/test_basic.py +++ b/tests/scan/test_basic.py @@ -144,12 +144,12 @@ def prod(inputs): t = t.flatten() t[pos] += _eps t = t.reshape(pt[i].shape) - f_eps = f(*(pt[:i] + [t] + pt[i + 1 :])) + f_eps = f(*([*pt[:i], t, *pt[i + 1 :]])) _g.append(np.asarray((f_eps - f_x) / _eps)) gx.append(np.asarray(_g).reshape(pt[i].shape)) else: t = np.array(pt[i] + _eps) - f_eps = f(*(pt[:i] + [t] + pt[i + 1 :])) + f_eps = f(*([*pt[:i], t, *pt[i + 1 :]])) gx.append(np.asarray((f_eps - f_x) / _eps)) self.gx = gx @@ -273,7 +273,7 @@ def inner_fn(x): r = normal(x, rng=inner_rng) return r + y + z, z - out, out_updates = scan( + out, _out_updates = scan( inner_fn, outputs_info=[pt.as_tensor(0.0, dtype=config.floatX), None], n_steps=4, @@ -784,7 +784,7 @@ def incr(s): return s + 1 x = vector("x") - sx, upx = scan(fn=incr, sequences=[{"input": x}]) + sx, _upx = scan(fn=incr, sequences=[{"input": x}]) scan_seqs = sx.owner.op.outer_seqs(sx.owner.inputs) @@ -794,8 +794,8 @@ def incr(s): def test_hash(self): x = vector() y = vector() - scan1, updates = scan(lambda _x: _x + 1, x) - scan2, updates = scan(lambda _x: _x + 1, y) + scan1, _updates = scan(lambda _x: _x + 1, x) + scan2, _updates = scan(lambda _x: _x + 1, y) assert scan1.owner.op == scan2.owner.op assert hash(scan1.owner.op) == hash(scan2.owner.op) @@ -967,7 +967,7 @@ def test_random_as_input_to_scan(self): def test_shared_updates(self): X = shared(np.array(1)) - out, updates = scan( + _out, updates = scan( lambda: {X: (X + 1)}, outputs_info=[], non_sequences=[], @@ -983,7 +983,7 @@ def test_shared_memory_aliasing_updates(self): x = shared(np.array(1)) y = shared(np.array(1)) - out, updates = scan( + _out, updates = scan( lambda: {x: x + 1, y: x}, outputs_info=[], non_sequences=[], @@ -1100,7 +1100,7 @@ def test_inner_grad(self): y.name = "y" gy = grad(y, x) gy.name = "gy" - hy, updates = scan( + hy, _updates = scan( lambda i, gy, x: grad(gy[i] * fc2, x), sequences=pt.arange(gy.shape[0]), non_sequences=[gy, x], @@ -1133,7 +1133,7 @@ def test_sequence_is_scan(self, mode): def test_grad_sitsot(self): def get_sum_of_grad(inp): - scan_outputs, updates = scan( + scan_outputs, _updates = scan( fn=lambda x: x * 2, outputs_info=[inp], n_steps=5 ) @@ -1157,7 +1157,7 @@ def inner_fct(mitsot_m2, sitsot): def get_sum_of_grad(input0, input1): outputs_info = [dict(initial=input0, taps=[-2]), input1] - scan_outputs, updates = scan( + scan_outputs, _updates = scan( fn=inner_fct, outputs_info=outputs_info, n_steps=3 ) @@ -1200,7 +1200,7 @@ def fn(a_m2, a_m1, b_m2, b_m1): a0 = shared(np.arange(2)) b0 = shared(np.arange(2)) - (a, b), _ = scan( + (a, _b), _ = scan( fn, outputs_info=[ {"initial": a0, "taps": [-2, -1]}, @@ -1274,7 +1274,9 @@ def inner_fct(mitsot_m2, mitsot_m1, sitsot): inputs = [matrix(), vector()] outputs_info = [dict(initial=inputs[0], taps=[-2, -1]), inputs[1]] - scan_outputs, updates = scan(fn=inner_fct, outputs_info=outputs_info, n_steps=5) + scan_outputs, _updates = scan( + fn=inner_fct, outputs_info=outputs_info, n_steps=5 + ) # Take the gradient of each output wrt its corresponding initial state gradients = [ @@ -1354,7 +1356,7 @@ def f_rnn(u_t, x_tm1, W_in, W): analytic_grad = grad_fn(v_u, v_x0, W_in, W) num_grad = multiple_outputs_numeric_grad(cost_fn, [v_u, v_x0, W_in, W]) - max_err, max_err_pos = num_grad.max_err(analytic_grad) + max_err, _max_err_pos = num_grad.max_err(analytic_grad) assert max_err <= 1e-2 def test_grad_multiple_outs(self): @@ -1415,7 +1417,7 @@ def f_rnn_cmpl(u1_t, u2_t, x_tm1, y_tm1, W_in1): cost_fn, [v_u1, v_u2, v_x0, v_y0, vW_in1] ) analytic_grad = grad_fn(v_u1, v_u2, v_x0, v_y0, vW_in1) - max_err, max_err_pos = num_grad.max_err(analytic_grad) + max_err, _max_err_pos = num_grad.max_err(analytic_grad) assert max_err <= 1e-2 def test_grad_multiple_outs_taps(self): @@ -1491,7 +1493,7 @@ def f_rnn_cmpl(u1_t, u2_tm1, u2_t, u2_tp1, x_tm1, y_tm1, y_tm3, W_in1): ) analytic_grad = grad_fn(v_u1, v_u2, v_x0, v_y0, vW_in1) - max_err, max_err_pos = num_grad.max_err(analytic_grad) + max_err, _max_err_pos = num_grad.max_err(analytic_grad) assert max_err <= 1e-2 @pytest.mark.slow @@ -1561,7 +1563,7 @@ def f_rnn_cmpl(u1_t, u2_tm1, u2_t, u2_tp1, x_tm1, y_tm1, y_tm3, W_in1): ) analytic_grad = grad_fn(v_u1, v_u2, v_x0, v_y0, vW_in1) - max_err, max_err_pos = num_grad.max_err(analytic_grad) + max_err, _max_err_pos = num_grad.max_err(analytic_grad) assert max_err <= 1e-2 def test_grad_multiple_outs_some_uncomputable(self): @@ -1633,7 +1635,7 @@ def reset_rng_grad_fn(*args): ndarray_mask=[True, False, True, True], ) analytic_grad = reset_rng_grad_fn(v_u, v_u2, v_x0, vW_in) - max_err, max_err_pos = num_grad.max_err(analytic_grad) + max_err, _max_err_pos = num_grad.max_err(analytic_grad) assert max_err <= 1e-2 # Also validate that the mappings outer_inp_from_outer_out and @@ -1720,7 +1722,7 @@ def test_grad_wrt_shared(self): x1 = shared(3.0) x1.name = "x1" x2 = vector("x2") - y, updates = scan(lambda v: pt.cast(v * x1, config.floatX), sequences=x2) + y, _updates = scan(lambda v: pt.cast(v * x1, config.floatX), sequences=x2) m = grad(y.sum(), x1) f = function([x2], m, allow_input_downcast=True) @@ -1731,7 +1733,7 @@ def test_inner_grad_wrt_shared(self): x2 = shared(np.array([1, 2, 3, 4, 5]), name="x2") K = x2 * x1 - out, updates = scan( + out, _updates = scan( lambda i, v: grad(K[i], v), sequences=pt.arange(K.shape[0]), non_sequences=x1, @@ -1852,7 +1854,7 @@ def test_grad_multiple_seqs_different_nsteps(self): x = scalar("x") _max_coefficients_supported = 1000 full_range = pt.arange(_max_coefficients_supported) - components, updates = scan( + components, _updates = scan( fn=lambda coeff, power, free_var: coeff * (free_var**power), outputs_info=None, sequences=[c, full_range], @@ -1872,7 +1874,7 @@ def test_grad_of_grad_of_state(self): x = scalar("x") _max_coefficients_supported = 1000 full_range = pt.arange(_max_coefficients_supported) - components, updates = scan( + components, _updates = scan( fn=lambda coeff, power, free_var: coeff * (free_var**power), outputs_info=None, sequences=[c, full_range], @@ -1891,7 +1893,7 @@ def onestep(xdl, xprev, w): xinit = tensor3("xinit") w = matrix("w") - (xseq, updates) = scan( + (xseq, _updates) = scan( n_steps=10, fn=onestep, outputs_info=[dict(initial=xinit, taps=[-4, -1])], @@ -1918,7 +1920,7 @@ def onestep(xdl, xprev, w): v_w[pos] = -1 * v_w[pos] analytic_grad = grad_fn(v_x, v_w) num_grad = multiple_outputs_numeric_grad(cost_fn, [v_x, v_w]) - max_err, max_err_pos = num_grad.max_err(analytic_grad) + max_err, _max_err_pos = num_grad.max_err(analytic_grad) assert max_err <= 1e-2 def test_grad_numeric_shared(self): @@ -2061,7 +2063,7 @@ def rnn_fn(_u, _y, _W): fn_rop = function( [u, h0, W, eu, eh0, eW], [nwo_u, nwo_h0, nwo_W, o], on_unused_input="ignore" ) - vnu, vnh0, vnW, vno = fn_rop(v_u, v_h0, v_W, v_eu, v_eh0, v_eW) + vnu, vnh0, vnW, _vno = fn_rop(v_u, v_h0, v_W, v_eu, v_eh0, v_eW) n2o_u, _ = scan( lambda i, o, u, h0, W, eu: (grad(o[i], u) * eu).sum(), @@ -2088,7 +2090,7 @@ def rnn_fn(_u, _y, _W): [u, h0, W, eu, eh0, eW], [n2o_u, n2o_h0, n2o_W, o], on_unused_input="ignore" ) - tnu, tnh0, tnW, tno = fn_test(v_u, v_h0, v_W, v_eu, v_eh0, v_eW) + tnu, tnh0, tnW, _tno = fn_test(v_u, v_h0, v_W, v_eu, v_eh0, v_eW) np.testing.assert_allclose(vnu, tnu, atol=1e-6) np.testing.assert_allclose(vnh0, tnh0, atol=1e-6) np.testing.assert_allclose(vnW, tnW, atol=2e-6) @@ -2473,7 +2475,7 @@ def f(x, y): def test_inconsistent_broadcast_error(): x = tensor3() initial_x = pt.constant(np.zeros((1, 10))) - y, updates = scan( + y, _updates = scan( fn=lambda x, prev_x: x + prev_x, sequences=x, outputs_info=[dict(initial=initial_x)], @@ -2491,7 +2493,7 @@ def count_up(): return pt.zeros(()), {c: c + inc} with pytest.raises(MissingInputError): - _, updates = scan(count_up, n_steps=20) + _, _updates = scan(count_up, n_steps=20) class TestGradUntil: @@ -2561,7 +2563,7 @@ def test_grad_until_and_truncate_sequence_taps(self): ) g = grad(r.sum(), self.x) f = function([self.x, self.threshold], [r, g]) - pytensor_output, pytensor_gradient = f(self.seq, 6) + _pytensor_output, pytensor_gradient = f(self.seq, 6) # Gradient computed by hand: numpy_grad = np.array([0, 0, 0, 5, 6, 10, 4, 5, 0, 0, 0, 0, 0, 0, 0]) @@ -2576,7 +2578,7 @@ def accum(seq_t, prev_sum): new_sum = prev_sum + seq_t return new_sum - rs, updates = scan( + rs, _updates = scan( fn=accum, sequences={"input": seq, "taps": [2]}, outputs_info=0, n_steps=1 ) @@ -2662,7 +2664,7 @@ def scan_body(size): def test_profile_info(): from pytensor.scan.utils import ScanProfileStats - z, updates = scan(fn=lambda u: u + 1, sequences=[pt.arange(10)], profile=True) + z, _updates = scan(fn=lambda u: u + 1, sequences=[pt.arange(10)], profile=True) assert isinstance(z.owner.op, Scan) fn = z.owner.op.fn @@ -2671,7 +2673,7 @@ def test_profile_info(): assert fn.profile.name == "scan_fn" # Set the `ScanProfileStats` name - z, updates = scan( + z, _updates = scan( fn=lambda u: u + 1, sequences=[pt.arange(10)], profile="profile_name" ) @@ -2683,7 +2685,7 @@ def test_profile_info(): # Use an existing profile object profile = fn.profile - z, updates = scan(fn=lambda u: u + 1, sequences=[pt.arange(10)], profile=profile) + z, _updates = scan(fn=lambda u: u + 1, sequences=[pt.arange(10)], profile=profile) assert isinstance(z.owner.op, Scan) fn = z.owner.op.fn @@ -2837,7 +2839,7 @@ def f_rnn_cmpl(u1_t, u2_t, x_tm1, y_tm1, y_tm3, W_in1): v_x[i] = np.dot(v_u1[i], vW_in1) + v_u2[i] * vW_in2 + np.dot(v_x[i - 1], vW) v_y[i] = np.dot(v_x[i - 1], vWout) + v_y[i - 1] - (pytensor_dump1, pytensor_dump2, pytensor_x, pytensor_y) = benchmark( + (_pytensor_dump1, _pytensor_dump2, pytensor_x, pytensor_y) = benchmark( f4, v_u1, v_u2, v_x0, v_y0, vW_in1 ) @@ -2912,7 +2914,7 @@ def test_use_scan_direct_output(self): x = scalar() seq = vector() outputs_info = [x, pt.zeros_like(x)] - (out1, out2), updates = scan( + (out1, out2), _updates = scan( lambda a, b, c: (a + b, b + c), sequences=seq, outputs_info=outputs_info, @@ -2951,7 +2953,7 @@ def test_use_scan_direct_output2(self): x = dcol() seq = dcol() outputs_info = [x, pt.zeros_like(x)] - (out1, out2), updates = scan( + (out1, out2), _updates = scan( lambda a, b, c: (a + b, a + c), sequences=seq, outputs_info=outputs_info ) @@ -2993,7 +2995,7 @@ def f(inp, mem): d = dot(i, W) return d, d - outs, updts = scan( + outs, _updts = scan( f, sequences=[x], non_sequences=[], outputs_info=[None, memory] ) @@ -3091,7 +3093,7 @@ def onestep(x, x_tm4): seq = matrix() initial_value = shared(np.zeros((4, 1), dtype=config.floatX)) outputs_info = [{"initial": initial_value, "taps": [-4]}, None] - results, updates = scan(fn=onestep, sequences=seq, outputs_info=outputs_info) + results, _updates = scan(fn=onestep, sequences=seq, outputs_info=outputs_info) f = function([seq], results[1]) assert np.all(exp_out == f(inp)) @@ -3242,7 +3244,7 @@ def test_disconnected_gradient(self): m = matrix("m") u0 = pt.zeros((7,)) - [u, m2], _ = scan(lambda _, u: [u, v], sequences=m, outputs_info=[u0, None]) + [_u, m2], _ = scan(lambda _, u: [u, v], sequences=m, outputs_info=[u0, None]) # This used to raise an exception with older versions because for a # disconnected gradient a non disconnected type was returned grad((m * m2).sum(), v) @@ -3252,7 +3254,7 @@ def test_disconnected_gradient2(self): m = matrix("m") u0 = pt.zeros((7,)) - [u, m2], _ = scan( + [_u, m2], _ = scan( lambda x, u: [x + u, u + v], sequences=m, outputs_info=[u0, None] ) # This used to raise an exception with older versions because @@ -3273,7 +3275,7 @@ def step(seq): out2 = out1 + 1 return out1, out2 - [out1, out2], _ = scan(step, sequences=v) + [_out1, out2], _ = scan(step, sequences=v) gv = grad(out2.sum(), [v]) f = function([v], gv) @@ -3441,7 +3443,7 @@ def _active(x, pre_h): pre_h = dot(x, W_x) return pre_h - value, scan_updates = scan( + value, _scan_updates = scan( _active, sequences=X, outputs_info=[pt.alloc(floatx(0.0), 1, out_size)], @@ -3462,11 +3464,11 @@ def accum(prev_value, step): condition = until(new_value > max_value) return [new_value, new_step], condition - rs, updates = scan(fn=accum, outputs_info=[0, 0], n_steps=n_steps) + rs, _updates = scan(fn=accum, outputs_info=[0, 0], n_steps=n_steps) f = function(inputs=[max_value, n_steps], outputs=rs) - _sum, total_steps = f(100, 100) + _sum, _total_steps = f(100, 100) @pytest.mark.skip( reason="This test fails because not typed outputs_info " @@ -3482,13 +3484,13 @@ def test_outputs_info_not_typed(self): # Generate the components of the polynomial full_range = pt.arange(max_coefficients_supported) - components, updates = scan( + components, _updates = scan( fn=lambda coeff, power, free_var: coeff * (free_var**power), sequences=[coefficients, full_range], non_sequences=x, ) polynomial1 = components.sum() - polynomial2, updates = scan( + polynomial2, _updates = scan( fn=lambda coeff, power, prev, free_var: prev + coeff * (free_var**power), outputs_info=pt.constant(0, dtype="floatX"), sequences=[coefficients, full_range], @@ -3496,7 +3498,7 @@ def test_outputs_info_not_typed(self): ) # python int - polynomial3, updates = scan( + polynomial3, _updates = scan( fn=lambda coeff, power, prev, free_var: prev + coeff * (free_var**power), outputs_info=0, sequences=[coefficients, full_range], @@ -3504,7 +3506,7 @@ def test_outputs_info_not_typed(self): ) # python float - polynomial4, updates = scan( + polynomial4, _updates = scan( fn=lambda coeff, power, prev, free_var: prev + coeff * (free_var**power), outputs_info=0.0, sequences=[coefficients, full_range], @@ -3553,7 +3555,7 @@ def stochastic_pooling(in_idx): rand_nums = rand_stream.binomial(1, 0.5, size=pooled.shape) return pooled + rand_nums, updates_inner - out, updates_outer = scan(unit_dropout, sequences=[pt.arange(inp.shape[0])]) + out, _updates_outer = scan(unit_dropout, sequences=[pt.arange(inp.shape[0])]) with pytest.raises(NullTypeGradError): grad(out.sum(), inp) @@ -3571,7 +3573,7 @@ def one_step(v, W): # o = v + 1 # <-- this line works return o - OS, updates = scan( + OS, _updates = scan( fn=one_step, sequences=V, outputs_info=[None], non_sequences=[W] ) @@ -3602,7 +3604,7 @@ def test_infershape_seq_shorter_nsteps(self): ValueError, match=r".*Sequence 0 has shape \(10,\) but the Scan's required number of steps is 20.*", ): - out1, out2 = f(vx) + _out1, _out2 = f(vx) # Even though the graph is nonsense, this could be correct somehow? out_shape1, out_shape2 = f_shape(vx) @@ -3626,7 +3628,7 @@ def lm(m): m + trng.uniform(size=[3]), ] - [o1, o2], updates = scan( + [o1, _o2], updates = scan( lm, sequences=x, n_steps=None, @@ -3704,7 +3706,7 @@ def f_rnn_cmpl(u1_t, u2_t, x_tm1, y_tm1, y_tm3, W_in1): v_x[i] = np.dot(v_u1[i], vW_in1) + v_u2[i] * vW_in2 + np.dot(v_x[i - 1], vW) v_y[i] = np.dot(v_x[i - 1], vWout) + v_y[i - 1] - (pytensor_dump, pytensor_x, pytensor_y) = f4(v_u1, v_u2, v_x0, v_y0, vW_in1) + (_pytensor_dump, pytensor_x, pytensor_y) = f4(v_u1, v_u2, v_x0, v_y0, vW_in1) utt.assert_allclose(pytensor_x, v_x[-2:]) utt.assert_allclose(pytensor_y, v_y[-4:]) @@ -3723,7 +3725,7 @@ def inner_fct(previous_val): condition = until(previous_val > 5) return new_val, condition - out, updates = scan(inner_fct, outputs_info=x, n_steps=10) + out, _updates = scan(inner_fct, outputs_info=x, n_steps=10) g_out = grad(out.sum(), x) fct = function([x], [out, g_out]) @@ -3758,7 +3760,7 @@ def step(seq1, sitsot_m1, mitsot_m2, mitsot_m1): ) return next_sitsot_val, next_mitsot_val, nitsot_out - out, updates = scan( + out, _updates = scan( fn=step, sequences=seq, outputs_info=[ @@ -3960,7 +3962,7 @@ def one_step(x_t, h_tm2, h_tm1, W_ih, W_hh, b_h, W_ho, b_o): return [h_t, y_t] # hidden and outputs of the entire sequence - [h, y], _ = scan( + [_h, y], _ = scan( fn=one_step, sequences=dict(input=x), # corresponds to the return type of one_step @@ -4152,7 +4154,7 @@ def fn(n): return s_in_y.sum() - s_y, updates = scan( + s_y, _updates = scan( fn=fn, outputs_info=[None], sequences=[pt.as_tensor([3, 2, 1], dtype=np.int64)], diff --git a/tests/scan/test_printing.py b/tests/scan/test_printing.py index f6f395a96d..5a7b45becc 100644 --- a/tests/scan/test_printing.py +++ b/tests/scan/test_printing.py @@ -15,7 +15,7 @@ def test_debugprint_sitsot(): A = dvector("A") # Symbolic description of the result - result, updates = pytensor.scan( + result, _updates = pytensor.scan( fn=lambda prior_result, A: prior_result * A, outputs_info=pt.ones_like(A), non_sequences=A, @@ -72,7 +72,7 @@ def test_debugprint_sitsot_no_extra_info(): A = dvector("A") # Symbolic description of the result - result, updates = pytensor.scan( + result, _updates = pytensor.scan( fn=lambda prior_result, A: prior_result * A, outputs_info=pt.ones_like(A), non_sequences=A, @@ -132,7 +132,7 @@ def test_debugprint_nitsot(): max_coefficients_supported = 10000 # Generate the components of the polynomial - components, updates = pytensor.scan( + components, _updates = pytensor.scan( fn=lambda coefficient, power, free_variable: coefficient * (free_variable**power), outputs_info=None, @@ -202,7 +202,7 @@ def test_debugprint_nested_scans(): A = dvector("A") def compute_A_k(A, k): - result, updates = pytensor.scan( + result, _updates = pytensor.scan( fn=lambda prior_result, A: prior_result * A, outputs_info=pt.ones_like(A), non_sequences=A, @@ -213,7 +213,7 @@ def compute_A_k(A, k): return A_k - components, updates = pytensor.scan( + components, _updates = pytensor.scan( fn=lambda c, power, some_A, some_k: c * (compute_A_k(some_A, some_k) ** power), outputs_info=None, sequences=[c, pt.arange(n)], @@ -487,7 +487,7 @@ def test_debugprint_mitmot(): A = dvector("A") # Symbolic description of the result - result, updates = pytensor.scan( + result, _updates = pytensor.scan( fn=lambda prior_result, A: prior_result * A, outputs_info=pt.ones_like(A), non_sequences=A, diff --git a/tests/scan/test_rewriting.py b/tests/scan/test_rewriting.py index 9871f2d8bf..ef3aebd971 100644 --- a/tests/scan/test_rewriting.py +++ b/tests/scan/test_rewriting.py @@ -321,13 +321,13 @@ def init_K(i, X, Y): K = XX + XX.T return K.sum() - beta, K_updts = scan( + beta, _K_updts = scan( init_K, sequences=pt.arange(E), non_sequences=[inputs, targets] ) # mean def predict_mean_i(i, x_star, s_star, X, beta, h): - n, D = shape(X) + _n, D = shape(X) # rescale every dimension by the corresponding inverse lengthscale iL = pt.diag(h[i, :D]) inp = (X - x_star).dot(iL) @@ -341,7 +341,7 @@ def predict_mean_i(i, x_star, s_star, X, beta, h): Mi = pt_sum(lb) * h[i, D] return Mi - (M), M_updts = scan( + (M), _M_updts = scan( predict_mean_i, sequences=pt.arange(E), non_sequences=[x_star, s_star, inputs, beta, hyp], @@ -377,7 +377,7 @@ def predict_mean_i(i, x_star, s_star, X, beta, h): expected_output = dfdm(X, Y, test_m, test_s) # equivalent code for the jacobian using scan - dMdm, dMdm_updts = scan( + dMdm, _dMdm_updts = scan( lambda i, M, x: grad(M[i], x), sequences=pt.arange(M.shape[0]), non_sequences=[M, x_star], @@ -475,7 +475,7 @@ def inner_fct(vect, mat): vect_squared = vect**2 return dot(vect_squared, mat), vect_squared - outputs, updates = pytensor.scan( + outputs, _updates = pytensor.scan( fn=inner_fct, outputs_info=[None] * 2, sequences=a, non_sequences=b ) @@ -523,7 +523,7 @@ def inner_fct(seq1, previous_output1, nonseq1): output2 = dot(output1, nonseq1) return output1, output2 - outputs, updates = pytensor.scan( + outputs, _updates = pytensor.scan( fn=inner_fct, outputs_info=[a[0], None], sequences=a, non_sequences=b ) @@ -822,38 +822,38 @@ def test_basic(self): def sum(s): return s + 1 - sx, upx = scan(sum, sequences=[x]) - sy, upy = scan(sum, sequences=[y]) + sx, _upx = scan(sum, sequences=[x]) + sy, _upy = scan(sum, sequences=[y]) f = function([x, y], [sx, sy], mode=self.mode) assert self.count_scans(f) == 2 - sx, upx = scan(sum, sequences=[x], n_steps=2) - sy, upy = scan(sum, sequences=[y], n_steps=3) + sx, _upx = scan(sum, sequences=[x], n_steps=2) + sy, _upy = scan(sum, sequences=[y], n_steps=3) f = function([x, y], [sx, sy], mode=self.mode) assert self.count_scans(f) == 2 - sx, upx = scan(sum, sequences=[x], n_steps=4) - sy, upy = scan(sum, sequences=[y], n_steps=4) + sx, _upx = scan(sum, sequences=[x], n_steps=4) + sy, _upy = scan(sum, sequences=[y], n_steps=4) f = function([x, y], [sx, sy], mode=self.mode) assert self.count_scans(f) == 1 - sx, upx = scan(sum, sequences=[x]) - sy, upy = scan(sum, sequences=[x]) + sx, _upx = scan(sum, sequences=[x]) + sy, _upy = scan(sum, sequences=[x]) f = function([x], [sx, sy], mode=self.mode) assert self.count_scans(f) == 1 - sx, upx = scan(sum, sequences=[x]) - sy, upy = scan(sum, sequences=[x], mode="FAST_COMPILE") + sx, _upx = scan(sum, sequences=[x]) + sy, _upy = scan(sum, sequences=[x], mode="FAST_COMPILE") f = function([x], [sx, sy], mode=self.mode) assert self.count_scans(f) == 1 - sx, upx = scan(sum, sequences=[x]) - sy, upy = scan(sum, sequences=[x], truncate_gradient=1) + sx, _upx = scan(sum, sequences=[x]) + sy, _upy = scan(sum, sequences=[x], truncate_gradient=1) f = function([x], [sx, sy], mode=self.mode) assert self.count_scans(f) == 2 @@ -870,11 +870,11 @@ def test_three_scans(self): def sum(s): return s + 1 - sx, upx = scan(sum, sequences=[x], n_steps=4, name="X") + sx, _upx = scan(sum, sequences=[x], n_steps=4, name="X") # We need to use an expression of y rather than y so the toposort # comes up with the 'Y' scan last. - sy, upy = scan(sum, sequences=[2 * y + 2], n_steps=4, name="Y") - sz, upz = scan(sum, sequences=[sx], n_steps=4, name="Z") + sy, _upy = scan(sum, sequences=[2 * y + 2], n_steps=4, name="Y") + sz, _upz = scan(sum, sequences=[sx], n_steps=4, name="Z") f = function([x, y], [sy, sz], mode=self.mode) assert self.count_scans(f) == 2 @@ -922,20 +922,20 @@ def sub(s): def sub_alt(s): return s - 1, until(s > 4) - sx, upx = scan(add, sequences=[x]) - sy, upy = scan(sub, sequences=[y]) + sx, _upx = scan(add, sequences=[x]) + sy, _upy = scan(sub, sequences=[y]) f = function([x, y], [sx, sy], mode=self.mode) assert self.count_scans(f) == 2 - sx, upx = scan(add, sequences=[x]) - sy, upy = scan(sub, sequences=[x]) + sx, _upx = scan(add, sequences=[x]) + sy, _upy = scan(sub, sequences=[x]) f = function([x], [sx, sy], mode=self.mode) assert self.count_scans(f) == 1 - sx, upx = scan(add, sequences=[x]) - sy, upy = scan(sub_alt, sequences=[x]) + sx, _upx = scan(add, sequences=[x]) + sy, _upy = scan(sub_alt, sequences=[x]) f = function([x], [sx, sy], mode=self.mode) assert self.count_scans(f) == 2 @@ -1277,7 +1277,7 @@ def f_rnn_cmpl(u1_t, u2_t, x_tm1, y_tm1, y_tm3, W_in1): v_x[i] = np.dot(v_u1[i], vW_in1) + v_u2[i] * vW_in2 + np.dot(v_x[i - 1], vW) v_y[i] = np.dot(v_x[i - 1], vWout) + v_y[i - 1] - (pytensor_dump, pytensor_x, pytensor_y) = f4(v_u1, v_u2, v_x0, v_y0, vW_in1) + (_pytensor_dump, pytensor_x, pytensor_y) = f4(v_u1, v_u2, v_x0, v_y0, vW_in1) utt.assert_allclose(pytensor_x, v_x[-1:]) utt.assert_allclose(pytensor_y, v_y[-1:]) @@ -1399,7 +1399,7 @@ def step(u_t, x1_tm1, x1_tm3, x2_tm1, x3tm2, x3_tm1, x4_tm1): x20 = scalar("x20") x30 = vector("x30") x40 = scalar("x40") - [x1, x2, x3, x4, x5, x6, x7], updates = scan( + [x1, x2, x3, x4, x5, _x6, _x7], updates = scan( step, u, [ @@ -1442,7 +1442,9 @@ def step(u_t, x1_tm1, x1_tm3, x2_tm1, x3tm2, x3_tm1, x4_tm1): node for node in f.maker.fgraph.apply_nodes if isinstance(node.op, Scan) ] # x6 and x7 are dropped because they are not used - [n_steps, seq, x4_buffer, x5_buffer, x1_len, x2_len, x3_len] = scan_node.inputs + [_n_steps, _seq, x4_buffer, x5_buffer, x1_len, x2_len, x3_len] = ( + scan_node.inputs + ) [x4_underlying_alloc] = [ var for var in ancestors([x4_buffer]) @@ -1491,7 +1493,7 @@ def test_savemem_does_not_duplicate_number_of_scan_nodes(self): def test_savemem_opt(self, benchmark): y0 = shared(np.ones((2, 10))) - [y1, y2], updates = scan( + [_y1, y2], _updates = scan( lambda y: [y, y], outputs_info=[dict(initial=y0, taps=[-2]), None], n_steps=5, @@ -1846,7 +1848,7 @@ def test_opt_order(): x = matrix("x") A = matrix("A") - z, updates = scan(dot, sequences=[], non_sequences=[x, A], n_steps=2) + z, _updates = scan(dot, sequences=[], non_sequences=[x, A], n_steps=2) f = function([x, A], z, mode="FAST_RUN") topo = f.maker.fgraph.toposort() diff --git a/tests/scan/test_utils.py b/tests/scan/test_utils.py index 3586101ada..d3e8697049 100644 --- a/tests/scan/test_utils.py +++ b/tests/scan/test_utils.py @@ -159,7 +159,7 @@ def scan_fn(mus_t, sigma_t, S_tm2, S_tm1, Gamma_t): Y_t = srng.normal(mus_t[S_tm1], sigma_t, name="Y_t") return S_t, Y_t - (S_rv, Y_rv), scan_updates = pytensor.scan( + (S_rv, Y_rv), _scan_updates = pytensor.scan( fn=scan_fn, sequences=[mus_pt, sigmas_pt], non_sequences=[Gamma_rv], diff --git a/tests/sparse/sandbox/test_sp.py b/tests/sparse/sandbox/test_sp.py index 869dac8fd0..2273f5dee3 100644 --- a/tests/sparse/sandbox/test_sp.py +++ b/tests/sparse/sandbox/test_sp.py @@ -41,7 +41,7 @@ def test_convolution(self): ttot, ntot = 0, 0 for conv_mode in convmodes: for ss in ssizes: - output, outshp = sp.convolve( + output, _outshp = sp.convolve( kerns, kshp, nkern, input, imshp, ss, bias=bias, mode=conv_mode ) f = function([kerns, bias, input], output, mode=mode) @@ -157,7 +157,7 @@ def test_multilayer_conv(self): l1hidval = l1propup(l1kernvals, img1d) # actual values - l2hid, l2shp = sp.convolve( + l2hid, _l2shp = sp.convolve( kerns[1], kshp[1], nkerns[1], @@ -222,7 +222,7 @@ def test_maxpool(self): assert np.all(output_val == my_output_val) def mp(input): - output, outshp = sp.max_pool(input, imval.shape[1:], maxpoolshp) + output, _outshp = sp.max_pool(input, imval.shape[1:], maxpoolshp) return output utt.verify_grad(mp, [imval.reshape(imval.shape[0], -1)]) diff --git a/tests/sparse/test_basic.py b/tests/sparse/test_basic.py index 4286660ccf..27376fa770 100644 --- a/tests/sparse/test_basic.py +++ b/tests/sparse/test_basic.py @@ -2115,7 +2115,7 @@ def test_grad(self): for format in sparse.sparse_formats: for axis in self.possible_axis: for struct in [True, False]: - variable, data = sparse_random_inputs(format, shape=(9, 10)) + _variable, data = sparse_random_inputs(format, shape=(9, 10)) verify_grad_sparse( self.op_class(axis=axis, sparse_grad=struct), data, @@ -2151,7 +2151,7 @@ def test_infer_shape(self): def test_grad(self): for format in sparse.sparse_formats: - variable, data = sparse_random_inputs(format, shape=(10, 10)) + _variable, data = sparse_random_inputs(format, shape=(10, 10)) verify_grad_sparse(self.op, data, structured=False) @@ -2221,7 +2221,7 @@ def test_infer_shape(self): def test_grad(self): for format in sparse.sparse_formats: for shape in zip(range(5, 9), range(3, 7)[::-1], strict=True): - variable, data = sparse_random_inputs(format, shape=shape) + _variable, data = sparse_random_inputs(format, shape=shape) verify_grad_sparse(self.op, data, structured=False) @@ -2252,7 +2252,7 @@ def test_op(self): def test_grad(self): for format in sparse.sparse_formats: for shape in zip(range(5, 9), range(3, 7)[::-1], strict=True): - variable, data = sparse_random_inputs(format, shape=shape) + _variable, data = sparse_random_inputs(format, shape=shape) verify_grad_sparse(self.op, data, structured=False) @@ -2377,7 +2377,7 @@ def test_get_item_list_grad(self): def op_with_fixed_index(x): return op(x, index=np.asarray([0, 1])) - x, x_val = sparse_random_inputs("csr", (4, 5)) + _x, x_val = sparse_random_inputs("csr", (4, 5)) try: verify_grad_sparse(op_with_fixed_index, x_val) @@ -2421,7 +2421,7 @@ def test_get_item_2lists_grad(self): def op_with_fixed_index(x): return op(x, ind1=np.asarray([0, 1]), ind2=np.asarray([2, 3])) - x, x_val = sparse_random_inputs("csr", (4, 5)) + _x, x_val = sparse_random_inputs("csr", (4, 5)) verify_grad_sparse(op_with_fixed_index, x_val) @@ -2978,7 +2978,7 @@ def test_op(self): def test_grad(self): for format in sparse.sparse_formats: for dtype in sparse.float_dtypes: - variable, data = sparse_random_inputs( + _variable, data = sparse_random_inputs( format, shape=(4, 7), out_dtype=dtype, gap=self.gap_grad ) @@ -3308,10 +3308,10 @@ def test_infer_shape(self): def test_grad(self): for format in sparse.sparse_formats: for dtype in sparse.float_dtypes: - (x,), (x_value,) = sparse_random_inputs( + (_x,), (x_value,) = sparse_random_inputs( format, shape=(9, 10), out_dtype=dtype, p=0.1 ) - (y,), (y_value,) = sparse_random_inputs( + (_y,), (y_value,) = sparse_random_inputs( format, shape=(10, 24), out_dtype=dtype, p=0.1 ) data = [x_value, y_value] diff --git a/tests/sparse/test_type.py b/tests/sparse/test_type.py index 28ea9d5304..d63dd00913 100644 --- a/tests/sparse/test_type.py +++ b/tests/sparse/test_type.py @@ -79,5 +79,5 @@ def test_SparseTensorType_filter(): x_res = z.type.filter(x.astype("float32"), allow_downcast=True) assert x_res.dtype == "float64" - with pytest.raises(TypeError, match=".*dtype but got.*"): + with pytest.raises(TypeError, match=r".*dtype but got.*"): w.type.filter(x) diff --git a/tests/tensor/conv/test_abstract_conv.py b/tests/tensor/conv/test_abstract_conv.py index 23ba23e1e9..277cb0e350 100644 --- a/tests/tensor/conv/test_abstract_conv.py +++ b/tests/tensor/conv/test_abstract_conv.py @@ -266,7 +266,7 @@ def test_get_shape(self): computed_image_shape = get_conv_gradinputs_shape( kernel_shape, output_shape, b, (2, 3), (d, d) ) - image_shape_with_None = image_shape[:2] + (None, None) + image_shape_with_None = (*image_shape[:2], None, None) assert computed_image_shape == image_shape_with_None # compute the kernel_shape given this output_shape @@ -276,7 +276,7 @@ def test_get_shape(self): # if border_mode == 'half', the shape should be None if b == "half": - kernel_shape_with_None = kernel_shape[:2] + (None, None) + kernel_shape_with_None = (*kernel_shape[:2], None, None) assert computed_kernel_shape == kernel_shape_with_None else: assert computed_kernel_shape == kernel_shape @@ -285,7 +285,7 @@ def test_get_shape(self): computed_kernel_shape = get_conv_gradweights_shape( kernel_shape, output_shape, b, (2, 3), (d, d) ) - kernel_shape_with_None = kernel_shape[:2] + (None, None) + kernel_shape_with_None = (*kernel_shape[:2], None, None) assert computed_kernel_shape == kernel_shape_with_None @@ -1531,7 +1531,7 @@ def get_upsampled_twobytwo_mat(self, two_by_two, ratio): The array upsampled by using bilinear interpolation. Array is of shape (batch size, num channels, 2*ratio, 2*ratio). """ - kern, shp = self.numerical_upsampling_multiplier(ratio) + kern, _shp = self.numerical_upsampling_multiplier(ratio) up_1D = two_by_two[:, :, :, :1] * kern[::-1] + two_by_two[:, :, :, 1:] * kern up_2D = ( up_1D[:, :, :1, :] * kern[::-1][:, np.newaxis] diff --git a/tests/tensor/random/rewriting/test_basic.py b/tests/tensor/random/rewriting/test_basic.py index 837b2c3b0c..f17f20ddbd 100644 --- a/tests/tensor/random/rewriting/test_basic.py +++ b/tests/tensor/random/rewriting/test_basic.py @@ -76,9 +76,9 @@ def apply_local_rewrite_to_rv( ).owner.outputs dist_st = op_fn(rv) - assert ( - count_rv_nodes_in_graph([dist_st, next_rng]) == 1 - ), "Function expects a single RV in the graph" + assert count_rv_nodes_in_graph([dist_st, next_rng]) == 1, ( + "Function expects a single RV in the graph" + ) f_inputs = [ p @@ -97,9 +97,9 @@ def apply_local_rewrite_to_rv( ) new_rv, new_next_rng = f_rewritten.maker.fgraph.outputs - assert ( - count_rv_nodes_in_graph([new_rv, new_next_rng]) == 1 - ), "Rewritten should have a single RV in the graph" + assert count_rv_nodes_in_graph([new_rv, new_next_rng]) == 1, ( + "Rewritten should have a single RV in the graph" + ) return new_rv, f_inputs, dist_st, f_rewritten @@ -133,7 +133,7 @@ def test_inplace_rewrites(rv_op): mode="FAST_RUN", ) - (new_out, new_rng) = f.maker.fgraph.outputs + (new_out, _new_rng) = f.maker.fgraph.outputs assert new_out.type == out.type new_node = new_out.owner new_op = new_node.op @@ -201,7 +201,7 @@ def test_inplace_rewrites(rv_op): def test_local_rv_size_lift(dist_op, dist_params, size): rng = shared(np.random.default_rng(1233532), borrow=False) - new_out, f_inputs, dist_st, f_rewritten = apply_local_rewrite_to_rv( + new_out, _f_inputs, _dist_st, _f_rewritten = apply_local_rewrite_to_rv( local_rv_size_lift, lambda rv: rv, dist_op, diff --git a/tests/tensor/random/test_op.py b/tests/tensor/random/test_op.py index edec9a4389..adf42e0550 100644 --- a/tests/tensor/random/test_op.py +++ b/tests/tensor/random/test_op.py @@ -32,7 +32,7 @@ def test_RandomVariable_basics(strict_test_value_flags): assert str_res == 'normal_rv{"(),()->()"}' # `ndims_params` should be a `Sequence` type - with pytest.raises(TypeError, match="^Parameter ndims_params*"): + with pytest.raises(TypeError, match=r"^Parameter ndims_params*"): RandomVariable( "normal", 0, @@ -42,7 +42,7 @@ def test_RandomVariable_basics(strict_test_value_flags): ) # `size` should be a `Sequence` type - with pytest.raises(TypeError, match="^Parameter size*"): + with pytest.raises(TypeError, match=r"^Parameter size*"): RandomVariable( "normal", 0, diff --git a/tests/tensor/random/test_utils.py b/tests/tensor/random/test_utils.py index f7d8731c1b..aa761d2922 100644 --- a/tests/tensor/random/test_utils.py +++ b/tests/tensor/random/test_utils.py @@ -284,7 +284,7 @@ def __init__(self, seed=123): def test_supp_shape_from_ref_param_shape(): - with pytest.raises(ValueError, match="^ndim_supp*"): + with pytest.raises(ValueError, match=r"^ndim_supp*"): supp_shape_from_ref_param_shape( ndim_supp=0, dist_params=(np.array([1, 2]), 0), @@ -306,7 +306,7 @@ def test_supp_shape_from_ref_param_shape(): ) assert res == (2,) - with pytest.raises(ValueError, match="^Reference parameter*"): + with pytest.raises(ValueError, match=r"^Reference parameter*"): supp_shape_from_ref_param_shape( ndim_supp=1, dist_params=(np.array(1),), diff --git a/tests/tensor/rewriting/test_basic.py b/tests/tensor/rewriting/test_basic.py index 4a78a1e9fe..d9eb2ad7ad 100644 --- a/tests/tensor/rewriting/test_basic.py +++ b/tests/tensor/rewriting/test_basic.py @@ -298,7 +298,7 @@ def test_inconsistent_shared(self, shape_unsafe): # Error raised by SpecifyShape that is introduced due to static shape inference with pytest.raises( AssertionError, - match="SpecifyShape: dim 0 of input has shape 3, expected 6.", + match="SpecifyShape: dim 0 of input has shape 3, expected 6\\.", ): f() else: diff --git a/tests/tensor/rewriting/test_blas.py b/tests/tensor/rewriting/test_blas.py index 10e040367c..6d31920386 100644 --- a/tests/tensor/rewriting/test_blas.py +++ b/tests/tensor/rewriting/test_blas.py @@ -164,7 +164,7 @@ def test_gemm_canonicalize(): def test_res_is_a(): - X, Y, Z, a, b = XYZab() + _X, _Y, _Z, a, _b = XYZab() assert not res_is_a(None, a, sqrt) assert not res_is_a(None, a + a, sqrt) diff --git a/tests/tensor/rewriting/test_blockwise.py b/tests/tensor/rewriting/test_blockwise.py index a17ad18a1f..e72b87ffe9 100644 --- a/tests/tensor/rewriting/test_blockwise.py +++ b/tests/tensor/rewriting/test_blockwise.py @@ -107,9 +107,8 @@ def test_blockwise_alloc(): y = tensor("y", shape=()) out = vector_add(alloc(x, 3, 1, 5), alloc(y, 7, 5)) expected_out = alloc(vector_add(alloc(x, 5), alloc(y, 5)), 3, 7, 5) - assert equal( - [rewrite(out)], [expected_out] - ), None # pytensor.dprint([expected_out, rewrite(out)], print_type=True) + # pytensor.dprint([expected_out, rewrite(out)], print_type=True) + assert equal([rewrite(out)], [expected_out]) x = tensor("x", shape=(5,)) y = tensor("y", shape=()) diff --git a/tests/tensor/rewriting/test_elemwise.py b/tests/tensor/rewriting/test_elemwise.py index 5982ee291d..197dd30f36 100644 --- a/tests/tensor/rewriting/test_elemwise.py +++ b/tests/tensor/rewriting/test_elemwise.py @@ -113,7 +113,7 @@ def test_merge2(self): assert check_stack_trace(g, ops_to_check="all") def test_elim3(self): - x, y, z = inputs() + x, _y, _z = inputs() e = ds(ds(ds(x, (0, "x", 1)), (2, 0, "x", 1)), (1, 0)) g = FunctionGraph([x], [e], clone=False) assert isinstance(g.outputs[0].owner.op, DimShuffle) @@ -1076,7 +1076,7 @@ def test_elemwise_fusion(self, case, nb_repeat=1, assert_len_topo=True): def test_fusion_35_inputs(self): r"""Make sure we don't fuse too many `Op`\s and go past the 31 function arguments limit.""" - inpts = vectors(["i%i" % i for i in range(35)]) + inpts = vectors([f"i{i}" for i in range(35)]) # Make an elemwise graph looking like: # sin(i34 + sin(i33 + sin(... i1 + sin(i0) ...))) diff --git a/tests/tensor/rewriting/test_linalg.py b/tests/tensor/rewriting/test_linalg.py index 38f7369bcc..515120e446 100644 --- a/tests/tensor/rewriting/test_linalg.py +++ b/tests/tensor/rewriting/test_linalg.py @@ -499,7 +499,7 @@ def test_svd_uv_merge(): s_1 = svd(a, full_matrices=False, compute_uv=False) _, s_2, _ = svd(a, full_matrices=False, compute_uv=True) _, s_3, _ = svd(a, full_matrices=True, compute_uv=True) - u_4, s_4, v_4 = svd(a, full_matrices=True, compute_uv=True) + u_4, _s_4, _v_4 = svd(a, full_matrices=True, compute_uv=True) # `grad` will introduces an SVD Op with compute_uv=True # full_matrices = True is not supported for grad of svd gs = pt.grad(pt.sum(s_1), a) diff --git a/tests/tensor/rewriting/test_math.py b/tests/tensor/rewriting/test_math.py index eda10cbd25..2d6e36c3ad 100644 --- a/tests/tensor/rewriting/test_math.py +++ b/tests/tensor/rewriting/test_math.py @@ -285,7 +285,7 @@ def test_elemwise_multiple_inputs_rewrites(self): # Test with and without DimShuffle shp = (5, 5) fx, fy, fz = fmatrices("xyz") - dx, dy, dz = dmatrices("xyz") + _dx, _dy, _dz = dmatrices("xyz") # fv = fvector('r').dimshuffle('x', 0) # dv = dvector('s').dimshuffle('x', 0) fxv = np.asarray(np.random.random(shp), dtype="float32") @@ -1272,7 +1272,7 @@ def test_local_useless_elemwise_comparison(self): # The following case is what made me discover those cases. X = matrix("X") Y = vector("Y") - X_sum, updates = pytensor.scan( + X_sum, _updates = pytensor.scan( fn=lambda x: x.sum(), outputs_info=None, sequences=[X], non_sequences=None ) Z = X_sum + Y @@ -1769,9 +1769,9 @@ def assert_func_pair_rewritten( assert len(topo) in acceptable_topo_lens assert delta_condition - assert ( - isinstance(topo[0].op, DeepCopyOp) == should_copy - ), "Inverse functions not removed!" + assert isinstance(topo[0].op, DeepCopyOp) == should_copy, ( + "Inverse functions not removed!" + ) def test(self): """Test rewrites for consecutive functional inverses.""" diff --git a/tests/tensor/test_basic.py b/tests/tensor/test_basic.py index 8e9e8d0ab1..4d429979f9 100644 --- a/tests/tensor/test_basic.py +++ b/tests/tensor/test_basic.py @@ -589,7 +589,7 @@ def test_ndim_all_broadcastable(self): def test_ndim_incompatible(self): x = TensorType(config.floatX, shape=(1, None))("x") - with pytest.raises(ValueError, match="^Tensor of type.*"): + with pytest.raises(ValueError, match=r"^Tensor of type.*"): as_tensor_variable(x, ndim=0) def test_bool(self): @@ -898,7 +898,7 @@ def test_runtime_broadcast(self, mode): def test_infer_static_shape(): - with pytest.raises(TypeError, match="^Shapes must be scalar integers.*"): + with pytest.raises(TypeError, match=r"^Shapes must be scalar integers.*"): infer_static_shape([constant(1.0)]) with ( @@ -907,16 +907,16 @@ def test_infer_static_shape(): ): infer_static_shape([dscalar("x")]) - with pytest.raises(ValueError, match=".*could not be cast to have 0 dimensions"): + with pytest.raises(ValueError, match=r".*could not be cast to have 0 dimensions"): infer_static_shape((as_tensor_variable([[1, 2]]),)) constant_size = constant([1]) specify_size = specify_shape(constant_size, [1]) - sh, static_shape = infer_static_shape(specify_size) + _sh, static_shape = infer_static_shape(specify_size) assert static_shape == (1,) x = scalar("x") - sh, static_shape = infer_static_shape([x.size]) + _sh, static_shape = infer_static_shape([x.size]) assert static_shape == (1,) @@ -1269,7 +1269,7 @@ def test_get_vector_length(): as_tensor_variable([1, 2], ndim=1), as_tensor_variable([3, 4], ndim=1), ) - with pytest.raises(ValueError, match="^Length of .*"): + with pytest.raises(ValueError, match=r"^Length of .*"): get_vector_length(z) # Test `MakeVector`s @@ -1329,13 +1329,13 @@ def eval_outputs_and_check_vector(self, outputs, make_vector_op=None): return variables def test_input_validation(self): - with pytest.raises(TypeError, match=".*integer.*"): + with pytest.raises(TypeError, match=r".*integer.*"): Split(2)(matrix(), dscalar(), [1, 1]) - with pytest.raises(TypeError, match=".*integer.*"): + with pytest.raises(TypeError, match=r".*integer.*"): Split(2)(matrix(), ivector(), [1, 1]) - with pytest.raises(TypeError, match=".*integer.*"): + with pytest.raises(TypeError, match=r".*integer.*"): join(dscalar(), matrix(), matrix()) def test_join_scalar(self): @@ -3131,7 +3131,7 @@ def test_default(): assert f(None, 2) == 2 assert f(1, None) == 1 - with pytest.raises(TypeError, match=".*compatible types.*"): + with pytest.raises(TypeError, match=r".*compatible types.*"): default(x, vector()) @@ -3622,7 +3622,7 @@ def test_diag(self): @pytest.mark.parametrize("inp", (scalar, tensor3)) def test_diag_invalid_input_ndim(self, inp): x = inp() - with pytest.raises(ValueError, match="Input must be 1- or 2-d."): + with pytest.raises(ValueError, match="Input must be 1- or 2-d\\."): diag(x) diff --git a/tests/tensor/test_blas.py b/tests/tensor/test_blas.py index 0052bbba4b..6d1e843a9e 100644 --- a/tests/tensor/test_blas.py +++ b/tests/tensor/test_blas.py @@ -584,9 +584,9 @@ def just_gemm(i, o, ishapes=None, max_graphlen=0, expected_nb_gemm=1): ) nb_gemm = 0 for node in f.maker.fgraph.apply_nodes: - assert not isinstance( - node.op, Dot - ), "_dot22 not changed to gemm_inplace in graph" + assert not isinstance(node.op, Dot), ( + "_dot22 not changed to gemm_inplace in graph" + ) assert node.op != _dot22 if node.op == gemm_inplace: nb_gemm += 1 @@ -602,9 +602,9 @@ def just_gemm(i, o, ishapes=None, max_graphlen=0, expected_nb_gemm=1): assert node.op != gemm_inplace, "gemm_inplace in original graph" graphlen = len(f.maker.fgraph.toposort()) - assert not ( - max_graphlen and (graphlen <= max_graphlen) - ), f"graphlen={graphlen}>{max_graphlen}" + assert not (max_graphlen and (graphlen <= max_graphlen)), ( + f"graphlen={graphlen}>{max_graphlen}" + ) rng = np.random.default_rng(unittest_tools.fetch_seed(234)) r0 = f(*[np.asarray(rng.standard_normal(sh), config.floatX) for sh in ishapes]) @@ -896,7 +896,7 @@ def test_inplace0(): def test_inplace1(): - X, Y, Z, a, b = XYZab() + X, Y, Z, _a, _b = XYZab() # with > 2 terms in the overall addition f = inplace_func([X, Y, Z], [Z + Z + dot(X, Y)], mode="FAST_RUN") # pytensor.printing.debugprint(f) @@ -1438,7 +1438,7 @@ def test_simple(self): def test_default_beta_y(self): vs = self.get_data() - alpha_v, beta_v, a_v, x_v, y_v = vs + _alpha_v, _beta_v, a_v, x_v, _y_v = vs a = shared(a_v) x = shared(x_v) @@ -1582,7 +1582,7 @@ def test_upcasting_scalar_nogemv(self): # an incorrect dtype, and forces upcasting of the result # We put this test in this class to test it on the gpu too. vs = self.get_data() - alpha_v, beta_v, a_v, x_v, y_v = vs + alpha_v, _beta_v, a_v, x_v, y_v = vs alpha_v = alpha_v.astype("float64") a_v = a_v.astype("float32") x_v = x_v.astype("float32") diff --git a/tests/tensor/test_elemwise.py b/tests/tensor/test_elemwise.py index d01dba4b4c..2224145f9f 100644 --- a/tests/tensor/test_elemwise.py +++ b/tests/tensor/test_elemwise.py @@ -255,7 +255,7 @@ class TestBroadcast: cop = Elemwise openmp_minsize = 2 * config.openmp_elemwise_minsize - openmp_minsize_sqrt = int(math.ceil(math.sqrt(openmp_minsize))) + openmp_minsize_sqrt = math.ceil(math.sqrt(openmp_minsize)) # The order is important if you change them. linkers = [PerformLinker, CLinker] @@ -792,7 +792,7 @@ def test_elemwise_grad_bool(self): x = scalar(dtype="bool") y = bscalar() z = x * y - dx, dy = pytensor.grad(z, [x, y]) + _dx, _dy = pytensor.grad(z, [x, y]) def test_infer_shape(self): for s_left, s_right in [ @@ -881,7 +881,7 @@ def make_node(self, *args): custom_elemwise = CustomElemwise(ps.add) - z_1, z_2 = custom_elemwise( + z_1, _z_2 = custom_elemwise( as_tensor_variable(np.eye(1)), as_tensor_variable(np.eye(1)), ) @@ -891,7 +891,7 @@ def make_node(self, *args): assert out[0].eval() == 1 assert out[1].eval() == 1 - z_1, z_2 = custom_elemwise( + z_1, _z_2 = custom_elemwise( as_tensor_variable(np.eye(1)), as_tensor_variable(np.eye(3)) ) in_2_shape = (ps.constant(3), ps.constant(3)) @@ -977,7 +977,7 @@ def impl(self, n, x): return x * n def grad(self, inputs, gout): - (n, x) = inputs + (n, _x) = inputs (gz,) = gout dy_dx = n return [pytensor.gradient.grad_not_implemented(self, 0, n), gz * dy_dx] diff --git a/tests/tensor/test_extra_ops.py b/tests/tensor/test_extra_ops.py index 352238adec..4942f81964 100644 --- a/tests/tensor/test_extra_ops.py +++ b/tests/tensor/test_extra_ops.py @@ -1019,7 +1019,7 @@ def check(shape, index_ndim, mode, order): ) # create some invalid indices to test the mode if mode in ("wrap", "clip"): - multi_index = (multi_index[0] - 1,) + multi_index[1:] + multi_index = (multi_index[0] - 1, *multi_index[1:]) # test with scalars and higher-dimensional indices if index_ndim == 0: multi_index = tuple(i[-1] for i in multi_index) @@ -1374,7 +1374,7 @@ def test_concat_with_broadcast(): with pytest.raises( TypeError, - match="Only tensors with the same number of dimensions can be concatenated.", + match="Only tensors with the same number of dimensions can be concatenated\\.", ): a = pt.tensor("a", shape=(1, 3, 5)) b = pt.tensor("b", shape=(3, 5)) diff --git a/tests/tensor/test_math.py b/tests/tensor/test_math.py index 9215693f79..fc7f5cdd17 100644 --- a/tests/tensor/test_math.py +++ b/tests/tensor/test_math.py @@ -1462,7 +1462,7 @@ def test_bool(self): def test_MaxAndArgmax_deprecated(): with pytest.raises( AttributeError, - match="The class `MaxandArgmax` has been deprecated. Call `Max` and `Argmax` seperately as an alternative.", + match="The class `MaxandArgmax` has been deprecated\\. Call `Max` and `Argmax` seperately as an alternative\\.", ): pytensor.tensor.math.MaxAndArgmax @@ -2651,9 +2651,8 @@ def numpy_i_scalar(dtype): # behavior. return - if ( - {a_type, b_type} == {"complex128", "float32"} - or {a_type, b_type} == {"complex128", "float16"} + if {a_type, b_type} == {"complex128", "float32"} or ( + {a_type, b_type} == {"complex128", "float16"} and set(combo) == {"scalar", "array"} and pytensor_dtype == "complex128" and numpy_dtype == "complex64" diff --git a/tests/tensor/test_math_scipy.py b/tests/tensor/test_math_scipy.py index 5d69ff1f09..fbfa5fb77e 100644 --- a/tests/tensor/test_math_scipy.py +++ b/tests/tensor/test_math_scipy.py @@ -1151,7 +1151,7 @@ def test_unused_grad_loop_opt(self, wrt): test_b1, test_z, *expected_dds, - expected_ddz, + _expected_ddz, ) = self.few_iters_case a1, a2, b1, z = pt.scalars("a1", "a2", "b1", "z") diff --git a/tests/tensor/test_merge.py b/tests/tensor/test_merge.py index 6d5a884b88..561b5d7c89 100644 --- a/tests/tensor/test_merge.py +++ b/tests/tensor/test_merge.py @@ -48,11 +48,8 @@ def __repr__(self): return self.name def __eq__(self, other): - return ( - self is other - or isinstance(other, MyOp) - and self.x is not None - and self.x == other.x + return self is other or ( + isinstance(other, MyOp) and self.x is not None and self.x == other.x ) def __hash__(self): diff --git a/tests/tensor/test_nlinalg.py b/tests/tensor/test_nlinalg.py index cc4ed99a93..69b5722240 100644 --- a/tests/tensor/test_nlinalg.py +++ b/tests/tensor/test_nlinalg.py @@ -218,7 +218,7 @@ def test_grad(self, compute_uv, full_matrices, gradient_test_case, shape, batche NotImplementedError, match="Gradient of svd not implemented for full_matrices=True", ): - U, s, V = svd( + _U, s, _V = svd( self.A, compute_uv=compute_uv, full_matrices=full_matrices ) pytensor.grad(s.sum(), self.A) diff --git a/tests/tensor/test_shape.py b/tests/tensor/test_shape.py index 2b37eada72..a0a6f82459 100644 --- a/tests/tensor/test_shape.py +++ b/tests/tensor/test_shape.py @@ -495,14 +495,14 @@ def test_python_perform(self): f = pytensor.function([x, shape], y, mode=Mode("py")) assert f([1], (1,)) == [1] - with pytest.raises(AssertionError, match="SpecifyShape:.*"): + with pytest.raises(AssertionError, match=r"SpecifyShape:.*"): assert f([1], (2,)) == [1] x = matrix() y = specify_shape(x, (None, 2)) f = pytensor.function([x], y, mode=Mode("py")) assert f(np.zeros((3, 2), dtype=config.floatX)).shape == (3, 2) - with pytest.raises(AssertionError, match="SpecifyShape:.*"): + with pytest.raises(AssertionError, match=r"SpecifyShape:.*"): assert f(np.zeros((3, 3), dtype=config.floatX)) def test_bad_shape(self): @@ -516,7 +516,7 @@ def test_bad_shape(self): assert np.array_equal(f(xval), xval) xval = np.random.random(3).astype(config.floatX) - with pytest.raises(AssertionError, match="SpecifyShape:.*"): + with pytest.raises(AssertionError, match=r"SpecifyShape:.*"): f(xval) assert isinstance( @@ -540,14 +540,14 @@ def test_bad_shape(self): for shape_ in [(4, 3), (2, 8)]: xval = np.random.random(shape_).astype(config.floatX) - with pytest.raises(AssertionError, match="SpecifyShape:.*"): + with pytest.raises(AssertionError, match=r"SpecifyShape:.*"): f(xval) s = iscalar("s") f = pytensor.function([x, s], specify_shape(x, None, s), mode=self.mode) x_val = np.zeros((3, 2), dtype=config.floatX) assert f(x_val, 2).shape == (3, 2) - with pytest.raises(AssertionError, match="SpecifyShape:.*"): + with pytest.raises(AssertionError, match=r"SpecifyShape:.*"): f(xval, 3) def test_infer_shape(self): diff --git a/tests/tensor/test_slinalg.py b/tests/tensor/test_slinalg.py index a82307a612..94aa771cf9 100644 --- a/tests/tensor/test_slinalg.py +++ b/tests/tensor/test_slinalg.py @@ -240,7 +240,7 @@ def test__repr__(self): def test_solve_raises_on_invalid_assume_a(): - with pytest.raises(ValueError, match="Invalid assume_a: test. It must be one of"): + with pytest.raises(ValueError, match="Invalid assume_a: test\\. It must be one of"): Solve(assume_a="test", b_ndim=2) @@ -259,7 +259,7 @@ def test_solve_raises_on_invalid_assume_a(): ("tridiagonal", False, True), ] solve_test_ids = [ - f'{assume_a}_{"lower" if lower else "upper"}_{"A^T" if transposed else "A"}' + f"{assume_a}_{'lower' if lower else 'upper'}_{'A^T' if transposed else 'A'}" for assume_a, lower, transposed in solve_test_cases ] diff --git a/tests/tensor/test_subtensor.py b/tests/tensor/test_subtensor.py index 9333b4c32e..d8dadf0009 100644 --- a/tests/tensor/test_subtensor.py +++ b/tests/tensor/test_subtensor.py @@ -841,7 +841,7 @@ def test_grad_2d_inc_set_subtensor(self): mv = np.asarray(random(*m_shape), dtype=self.dtype) t = op(n[:z, :z], m) - gn, gm = pytensor.grad(pt_sum(t), [n, m]) + _gn, _gm = pytensor.grad(pt_sum(t), [n, m]) utt.verify_grad(lambda m: op(n[:z, :z], m), [mv], mode=self.mode) utt.verify_grad(lambda nn: op(nn[:z, :z], mv), [data], mode=self.mode) @@ -1272,7 +1272,7 @@ def test_advanced1_inc_and_set(self): if len(inc_shape) == len(data_shape) and ( len(inc_shapes) == 0 or inc_shape[0] != 1 ): - inc_shape = (n_to_inc,) + inc_shape[1:] + inc_shape = (n_to_inc, *inc_shape[1:]) # Symbolic variable with increment value. inc_var_static_shape = tuple( @@ -1364,12 +1364,12 @@ def test_advanced1_inc_runtime_broadcast(self, func): f(np.ones((20, 5))) # Fine with pytest.raises( ValueError, - match="Runtime broadcasting not allowed. AdvancedIncSubtensor1 was asked", + match="Runtime broadcasting not allowed\\. AdvancedIncSubtensor1 was asked", ): f(np.ones((1, 5))) with pytest.raises( ValueError, - match="Runtime broadcasting not allowed. AdvancedIncSubtensor1 was asked", + match="Runtime broadcasting not allowed\\. AdvancedIncSubtensor1 was asked", ): f(np.ones((20, 1))) @@ -2822,15 +2822,15 @@ def bcast_shape_tuple(x): (np.arange(np.prod((5, 6, 7, 8))).reshape((5, 6, 7, 8)), test_idx[:2]), ( np.arange(np.prod((5, 6, 7, 8))).reshape((5, 6, 7, 8)), - test_idx[:2] + (slice(None, None),), + (*test_idx[:2], slice(None, None)), ), ( np.arange(np.prod((5, 6, 7, 8))).reshape((5, 6, 7, 8)), - (slice(None, None),) + test_idx[:1], + (slice(None, None), *test_idx[:1]), ), ( np.arange(np.prod((5, 6, 7, 8))).reshape((5, 6, 7, 8)), - (slice(None, None), None) + test_idx[1:2], + (slice(None, None), None, *test_idx[1:2]), ), ( np.arange(np.prod((5, 6, 7, 8))).reshape((5, 6, 7, 8)), @@ -2842,15 +2842,15 @@ def bcast_shape_tuple(x): ), ( np.arange(np.prod((5, 6, 7, 8))).reshape((5, 6, 7, 8)), - test_idx[:1] + (slice(None, None),) + test_idx[1:2], + (*test_idx[:1], slice(None, None), *test_idx[1:2]), ), ( np.arange(np.prod((5, 6, 7, 8))).reshape((5, 6, 7, 8)), - test_idx[:1] + (slice(None, None),) + test_idx[1:2] + (slice(None, None),), + (*test_idx[:1], slice(None, None), *test_idx[1:2], slice(None, None)), ), ( np.arange(np.prod((5, 6, 7, 8))).reshape((5, 6, 7, 8)), - test_idx[:1] + (None,) + test_idx[1:2], + (*test_idx[:1], None, *test_idx[1:2]), ), (np.arange(np.prod((5, 4))).reshape((5, 4)), ([1, 3, 2], slice(1, 3))), (np.arange(np.prod((5, 4))).reshape((5, 4)), (slice(1, 3), [1, 3, 2])), @@ -2880,7 +2880,7 @@ def test_indexed_result_shape(test_array, test_idx): def test_symbolic_slice(): x = tensor4("x") - a, b = x.shape[:2] + a, _b = x.shape[:2] output = a.eval({x: np.zeros((5, 4, 3, 2), dtype=config.floatX)}) assert output == np.array(5) @@ -2903,7 +2903,7 @@ def test_get_vector_length(): assert get_vector_length(lvector()[1:1]) == 0 assert get_vector_length(lvector()[-1:-1:3]) == 0 - with pytest.raises(ValueError, match="^Length of .*"): + with pytest.raises(ValueError, match=r"^Length of .*"): get_vector_length(x[lscalar() :]) diff --git a/tests/tensor/test_type.py b/tests/tensor/test_type.py index e9a1914067..ebfe15bb6a 100644 --- a/tests/tensor/test_type.py +++ b/tests/tensor/test_type.py @@ -115,7 +115,7 @@ def test_filter_variable(): with pytest.raises(TypeError): test_type.filter(np.empty((0, 1), dtype=config.floatX)) - with pytest.raises(TypeError, match=".*not aligned.*"): + with pytest.raises(TypeError, match=r".*not aligned.*"): test_val = np.empty((1, 2), dtype=config.floatX) test_val.flags.aligned = False test_type.filter(test_val) diff --git a/tests/test_config.py b/tests/test_config.py index 2dd3c32180..ab34037c67 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -150,7 +150,9 @@ def test_deviceparam(self): cp._apply("cuda123") with pytest.raises(ValueError, match="It was removed from PyTensor"): cp._apply("gpu123") - with pytest.raises(ValueError, match='Valid options start with one of "cpu".'): + with pytest.raises( + ValueError, match='Valid options start with one of "cpu"\\.' + ): cp._apply("notadevice") assert str(cp) == "unnamed (cpu)" @@ -233,9 +235,9 @@ def test_config_pickling(): for name in root._config_var_dict: v_original = getattr(root, name) v_restored = getattr(restored, name) - assert ( - v_restored == v_original - ), f"{name} did not survive pickling ({v_restored} != {v_original})" + assert v_restored == v_original, ( + f"{name} did not survive pickling ({v_restored} != {v_original})" + ) # and validate that the test would catch typical problems root = _create_test_config() @@ -247,7 +249,7 @@ def test_config_pickling(): ) with pytest.raises( AttributeError, - match="Can't (pickle|get) local object 'test_config_pickling..'", + match=r"Can't (pickle|get) local object 'test_config_pickling\.\.'", ): pickle.dump(root, io.BytesIO()) diff --git a/tests/test_gradient.py b/tests/test_gradient.py index ed1b596691..a79746da6d 100644 --- a/tests/test_gradient.py +++ b/tests/test_gradient.py @@ -88,8 +88,8 @@ def make_node(self): return Apply(self, inputs, outputs) def grad(self, inp, grads): - (x,) = inp - (gz,) = grads + (_x,) = inp + (_gz,) = grads def perform(self, *args, **kwargs): raise NotImplementedError() @@ -157,8 +157,8 @@ def make_node(self): return Apply(self, inputs, outputs) def grad(self, inp, grads): - (x,) = inp - gz1, gz2 = grads + (_x,) = inp + _gz1, _gz2 = grads return (gval,) def perform(self, *args, **kwargs): @@ -182,8 +182,8 @@ def make_node(self): return Apply(self, inputs, outputs) def grad(self, inp, grads): - x0, x1 = inp - (gz,) = grads + _x0, _x1 = inp + (_gz,) = grads return (gval0, gval1) def perform(self, *args, **kwargs): @@ -231,8 +231,8 @@ def make_node(self): return Apply(self, inputs, outputs) def grad(self, inp, grads): - x0, x1 = inp - gz0, gz1 = grads + _x0, _x1 = inp + _gz0, _gz1 = grads return self.gval0, self.gval1 def perform(self, *args, **kwargs): diff --git a/tests/test_ifelse.py b/tests/test_ifelse.py index 5ca7de6e63..7beae3af07 100644 --- a/tests/test_ifelse.py +++ b/tests/test_ifelse.py @@ -335,9 +335,9 @@ def test_sparse_conversions(self): z = matrix("csr", dtype=self.dtype, name="z") cond = iscalar("cond") - with pytest.raises(TypeError, match=".*do not match."): + with pytest.raises(TypeError, match=r".*do not match."): ifelse(cond, x, y) - with pytest.raises(TypeError, match=".*do not match."): + with pytest.raises(TypeError, match=r".*do not match."): ifelse(cond, y, x) with pytest.raises(TypeError): ifelse(cond, x, z) diff --git a/tests/test_printing.py b/tests/test_printing.py index dbad8c063b..53bd0a1391 100644 --- a/tests/test_printing.py +++ b/tests/test_printing.py @@ -486,7 +486,7 @@ def test_Print(capsys): fn() - stdout, stderr = capsys.readouterr() + stdout, _stderr = capsys.readouterr() assert "hello" in stdout diff --git a/tests/unittest_tools.py b/tests/unittest_tools.py index fee2fea3b4..0d82dbf63a 100644 --- a/tests/unittest_tools.py +++ b/tests/unittest_tools.py @@ -43,8 +43,7 @@ def fetch_seed(pseed=None): seed = None except ValueError: warnings.warn( - "Error: config.unittests__rseed contains " - "invalid seed, using None instead" + "Error: config.unittests__rseed contains invalid seed, using None instead" ) seed = None diff --git a/tests/xtensor/test_indexing.py b/tests/xtensor/test_indexing.py index b36873683b..c582be3481 100644 --- a/tests/xtensor/test_indexing.py +++ b/tests/xtensor/test_indexing.py @@ -1,4 +1,3 @@ -# ruff: noqa: E402 import pytest @@ -412,7 +411,7 @@ def test_adv_index_update(mode, idx_dtype): else: with pytest.raises( IndexError, - match="Boolean indexer should be unlabeled or on the same dimension to the indexed array.", + match="Boolean indexer should be unlabeled or on the same dimension to the indexed array\\.", ): getattr(x[idx.rename(a="b"), :3], mode)(y) vectorized_update = x diff --git a/tests/xtensor/test_linalg.py b/tests/xtensor/test_linalg.py index 9db4b3dcee..8311272df1 100644 --- a/tests/xtensor/test_linalg.py +++ b/tests/xtensor/test_linalg.py @@ -1,4 +1,3 @@ -# ruff: noqa: E402 import pytest diff --git a/tests/xtensor/test_math.py b/tests/xtensor/test_math.py index 48d91771be..479c8d457a 100644 --- a/tests/xtensor/test_math.py +++ b/tests/xtensor/test_math.py @@ -1,4 +1,3 @@ -# ruff: noqa: E402 import pytest diff --git a/tests/xtensor/test_reduction.py b/tests/xtensor/test_reduction.py index 689ef3925a..85850d6a41 100644 --- a/tests/xtensor/test_reduction.py +++ b/tests/xtensor/test_reduction.py @@ -1,4 +1,3 @@ -# ruff: noqa: E402 import pytest diff --git a/tests/xtensor/test_shape.py b/tests/xtensor/test_shape.py index 571f7a8d5b..5313d7bde9 100644 --- a/tests/xtensor/test_shape.py +++ b/tests/xtensor/test_shape.py @@ -1,4 +1,3 @@ -# ruff: noqa: E402 import pytest @@ -350,11 +349,11 @@ def test_squeeze_errors(): # Non-existent dimension x1 = xtensor("x1", dims=("city", "country"), shape=(3, 1)) - with pytest.raises(ValueError, match="Dimension .* not found"): + with pytest.raises(ValueError, match=r"Dimension .* not found"): x1.squeeze("time") # Dimension size > 1 - with pytest.raises(ValueError, match="has static size .* not 1"): + with pytest.raises(ValueError, match=r"has static size .* not 1"): x1.squeeze("city") # Symbolic shape: dim is not 1 at runtime → should raise @@ -580,7 +579,7 @@ def test_broadcast_errors(self): y = xtensor("y", dims=("c", "d"), shape=(5, 6)) z = xtensor("z", dims=("b", "d"), shape=(4, 7)) - with pytest.raises(ValueError, match="Dimension .* has conflicting shapes"): + with pytest.raises(ValueError, match=r"Dimension .* has conflicting shapes"): broadcast(x, y, z) def test_broadcast_no_input(self): diff --git a/tests/xtensor/test_type.py b/tests/xtensor/test_type.py index 0ad86796d3..cbe7595302 100644 --- a/tests/xtensor/test_type.py +++ b/tests/xtensor/test_type.py @@ -1,4 +1,3 @@ -# ruff: noqa: E402 import pytest diff --git a/tests/xtensor/util.py b/tests/xtensor/util.py index 1d76afe0ea..82d1f071c8 100644 --- a/tests/xtensor/util.py +++ b/tests/xtensor/util.py @@ -1,4 +1,3 @@ -# ruff: noqa: E402 import pytest @@ -16,9 +15,9 @@ def xr_function(*args, **kwargs): """Compile and wrap a PyTensor function to return xarray DataArrays.""" fn = function(*args, **kwargs) symbolic_outputs = fn.maker.fgraph.outputs - assert all( - isinstance(out.type, XTensorType) for out in symbolic_outputs - ), "All outputs must be xtensor" + assert all(isinstance(out.type, XTensorType) for out in symbolic_outputs), ( + "All outputs must be xtensor" + ) def xfn(*xr_inputs): np_inputs = [