From 17748b7d3419e78e7dfad3dc768908ac240aa6df Mon Sep 17 00:00:00 2001 From: Ricardo Vieira Date: Wed, 5 Feb 2025 10:39:59 +0100 Subject: [PATCH] Remove accidental print statements --- pyproject.toml | 11 ++++- pytensor/breakpoint.py | 16 +++---- pytensor/compile/compiledir.py | 46 +++++++++---------- pytensor/compile/debugmode.py | 8 ++-- pytensor/compile/mode.py | 2 +- pytensor/compile/monitormode.py | 6 +-- pytensor/compile/nanguardmode.py | 2 +- pytensor/compile/profiling.py | 4 +- pytensor/graph/features.py | 22 ++++----- pytensor/graph/fg.py | 2 +- pytensor/graph/rewriting/basic.py | 20 ++++---- pytensor/graph/utils.py | 4 +- pytensor/link/c/basic.py | 12 ++--- pytensor/link/c/op.py | 2 +- pytensor/printing.py | 7 ++- pytensor/tensor/basic.py | 1 - pytensor/tensor/nlinalg.py | 10 ++-- pytensor/tensor/rewriting/blas.py | 2 +- pytensor/tensor/rewriting/elemwise.py | 8 ++-- pytensor/tensor/rewriting/math.py | 16 +++---- scripts/slowest_tests/extract-slow-tests.py | 2 +- tests/d3viz/test_d3viz.py | 2 +- tests/link/c/test_cmodule.py | 1 - tests/link/numba/test_basic.py | 1 - tests/link/test_vm.py | 51 +++++++++++---------- tests/scan/test_basic.py | 3 +- tests/tensor/rewriting/test_math.py | 36 ++++++++------- tests/tensor/test_complex.py | 12 ++--- tests/tensor/test_fft.py | 1 - tests/tensor/test_shape.py | 1 - tests/test_config.py | 2 +- tests/test_printing.py | 6 +-- tests/unittest_tools.py | 10 ++-- 33 files changed, 161 insertions(+), 168 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 4e2a1fdb05..e82c42753a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -129,7 +129,7 @@ exclude = ["doc/", "pytensor/_version.py"] docstring-code-format = true [tool.ruff.lint] -select = ["B905", "C", "E", "F", "I", "UP", "W", "RUF", "PERF", "PTH", "ISC"] +select = ["B905", "C", "E", "F", "I", "UP", "W", "RUF", "PERF", "PTH", "ISC", "T20"] ignore = ["C408", "C901", "E501", "E741", "RUF012", "PERF203", "ISC001"] unfixable = [ # zip-strict: the auto-fix adds `strict=False` but we might want `strict=True` instead @@ -144,7 +144,12 @@ lines-after-imports = 2 # TODO: Get rid of these: "**/__init__.py" = ["F401", "E402", "F403"] "pytensor/tensor/linalg.py" = ["F403"] -"pytensor/link/c/cmodule.py" = ["PTH"] +"pytensor/link/c/cmodule.py" = ["PTH", "T201"] +"pytensor/misc/elemwise_time_test.py" = ["T201"] +"pytensor/misc/elemwise_openmp_speedup.py" = ["T201"] +"pytensor/misc/check_duplicate_key.py" = ["T201"] +"pytensor/misc/check_blas.py" = ["T201"] +"pytensor/bin/pytensor_cache.py" = ["T201"] # For the tests we skip because `pytest.importorskip` is used: "tests/link/jax/test_scalar.py" = ["E402"] "tests/link/jax/test_tensor_basic.py" = ["E402"] @@ -158,6 +163,8 @@ lines-after-imports = 2 "tests/sparse/test_sp2.py" = ["E402"] "tests/sparse/test_utils.py" = ["E402"] "tests/sparse/sandbox/test_sp.py" = ["E402", "F401"] +"tests/compile/test_monitormode.py" = ["T201"] +"scripts/run_mypy.py" = ["T201"] [tool.mypy] diff --git a/pytensor/breakpoint.py b/pytensor/breakpoint.py index 314f2a7325..3d59b5c24c 100644 --- a/pytensor/breakpoint.py +++ b/pytensor/breakpoint.py @@ -108,14 +108,14 @@ def perform(self, node, inputs, output_storage): f"'{self.name}' could not be casted to NumPy arrays" ) - print("\n") - print("-------------------------------------------------") - print(f"Conditional breakpoint '{self.name}' activated\n") - print("The monitored variables are stored, in order,") - print("in the list variable 'monitored' as NumPy arrays.\n") - print("Their contents can be altered and, when execution") - print("resumes, the updated values will be used.") - print("-------------------------------------------------") + print("\n") # noqa: T201 + print("-------------------------------------------------") # noqa: T201 + print(f"Conditional breakpoint '{self.name}' activated\n") # noqa: T201 + print("The monitored variables are stored, in order,") # noqa: T201 + print("in the list variable 'monitored' as NumPy arrays.\n") # noqa: T201 + print("Their contents can be altered and, when execution") # noqa: T201 + print("resumes, the updated values will be used.") # noqa: T201 + print("-------------------------------------------------") # noqa: T201 try: import pudb diff --git a/pytensor/compile/compiledir.py b/pytensor/compile/compiledir.py index 0482ed6cd8..127b971b2e 100644 --- a/pytensor/compile/compiledir.py +++ b/pytensor/compile/compiledir.py @@ -95,10 +95,10 @@ def cleanup(): def print_title(title, overline="", underline=""): len_title = len(title) if overline: - print(str(overline) * len_title) - print(title) + print(str(overline) * len_title) # noqa: T201 + print(title) # noqa: T201 if underline: - print(str(underline) * len_title) + print(str(underline) * len_title) # noqa: T201 def print_compiledir_content(): @@ -159,7 +159,7 @@ def print_compiledir_content(): _logger.error(f"Could not read key file '{filename}'.") print_title(f"PyTensor cache: {compiledir}", overline="=", underline="=") - print() + print() # noqa: T201 print_title(f"List of {len(table)} compiled individual ops", underline="+") print_title( @@ -168,9 +168,9 @@ def print_compiledir_content(): ) table = sorted(table, key=lambda t: str(t[1])) for dir, op, types, compile_time in table: - print(dir, f"{compile_time:.3f}s", op, types) + print(dir, f"{compile_time:.3f}s", op, types) # noqa: T201 - print() + print() # noqa: T201 print_title( f"List of {len(table_multiple_ops)} compiled sets of ops", underline="+" ) @@ -180,9 +180,9 @@ def print_compiledir_content(): ) table_multiple_ops = sorted(table_multiple_ops, key=lambda t: (t[1], t[2])) for dir, ops_to_str, types_to_str, compile_time in table_multiple_ops: - print(dir, f"{compile_time:.3f}s", ops_to_str, types_to_str) + print(dir, f"{compile_time:.3f}s", ops_to_str, types_to_str) # noqa: T201 - print() + print() # noqa: T201 print_title( ( f"List of {len(table_op_class)} compiled Op classes and " @@ -191,33 +191,33 @@ def print_compiledir_content(): underline="+", ) for op_class, nb in reversed(table_op_class.most_common()): - print(op_class, nb) + print(op_class, nb) # noqa: T201 if big_key_files: big_key_files = sorted(big_key_files, key=lambda t: str(t[1])) big_total_size = sum(sz for _, sz, _ in big_key_files) - print( + print( # noqa: T201 f"There are directories with key files bigger than {int(max_key_file_size)} bytes " "(they probably contain big tensor constants)" ) - print( + print( # noqa: T201 f"They use {int(big_total_size)} bytes out of {int(total_key_sizes)} (total size " "used by all key files)" ) for dir, size, ops in big_key_files: - print(dir, size, ops) + print(dir, size, ops) # noqa: T201 nb_keys = sorted(nb_keys.items()) - print() + print() # noqa: T201 print_title("Number of keys for a compiled module", underline="+") print_title( "number of keys/number of modules with that number of keys", underline="-" ) for n_k, n_m in nb_keys: - print(n_k, n_m) - print() - print( + print(n_k, n_m) # noqa: T201 + print() # noqa: T201 + print( # noqa: T201 f"Skipped {int(zeros_op)} files that contained 0 op " "(are they always pytensor.scalar ops?)" ) @@ -242,18 +242,18 @@ def basecompiledir_ls(): subdirs = sorted(subdirs) others = sorted(others) - print(f"Base compile dir is {config.base_compiledir}") - print("Sub-directories (possible compile caches):") + print(f"Base compile dir is {config.base_compiledir}") # noqa: T201 + print("Sub-directories (possible compile caches):") # noqa: T201 for d in subdirs: - print(f" {d}") + print(f" {d}") # noqa: T201 if not subdirs: - print(" (None)") + print(" (None)") # noqa: T201 if others: - print() - print("Other files in base_compiledir:") + print() # noqa: T201 + print("Other files in base_compiledir:") # noqa: T201 for f in others: - print(f" {f}") + print(f" {f}") # noqa: T201 def basecompiledir_purge(): diff --git a/pytensor/compile/debugmode.py b/pytensor/compile/debugmode.py index cc1a5b225a..5c51222a1b 100644 --- a/pytensor/compile/debugmode.py +++ b/pytensor/compile/debugmode.py @@ -1315,9 +1315,9 @@ def on_change_input(self, fgraph, node, i, r, new_r, reason=None): def printstuff(self): for key in self.equiv: - print(key) + print(key) # noqa: T201 for e in self.equiv[key]: - print(" ", e) + print(" ", e) # noqa: T201 # List of default version of make thunk. @@ -1569,7 +1569,7 @@ def f(): ##### for r, s in storage_map.items(): if s[0] is not None: - print(r, s) + print(r, s) # noqa: T201 assert s[0] is None # try: @@ -2079,7 +2079,7 @@ def __init__( raise StochasticOrder(infolog.getvalue()) else: if self.verbose: - print( + print( # noqa: T201 "OPTCHECK: optimization", i, "of", diff --git a/pytensor/compile/mode.py b/pytensor/compile/mode.py index ae905089b5..43a5e131cb 100644 --- a/pytensor/compile/mode.py +++ b/pytensor/compile/mode.py @@ -178,7 +178,7 @@ def __init__(self, header): def apply(self, fgraph): import pytensor.printing - print("PrintCurrentFunctionGraph:", self.header) + print("PrintCurrentFunctionGraph:", self.header) # noqa: T201 pytensor.printing.debugprint(fgraph.outputs) diff --git a/pytensor/compile/monitormode.py b/pytensor/compile/monitormode.py index 770d4e2f7e..8663bc8832 100644 --- a/pytensor/compile/monitormode.py +++ b/pytensor/compile/monitormode.py @@ -108,8 +108,8 @@ def detect_nan(fgraph, i, node, fn): not isinstance(output[0], np.random.RandomState | np.random.Generator) and np.isnan(output[0]).any() ): - print("*** NaN detected ***") + print("*** NaN detected ***") # noqa: T201 debugprint(node) - print(f"Inputs : {[input[0] for input in fn.inputs]}") - print(f"Outputs: {[output[0] for output in fn.outputs]}") + print(f"Inputs : {[input[0] for input in fn.inputs]}") # noqa: T201 + print(f"Outputs: {[output[0] for output in fn.outputs]}") # noqa: T201 break diff --git a/pytensor/compile/nanguardmode.py b/pytensor/compile/nanguardmode.py index 7f90825953..e2fd44cda3 100644 --- a/pytensor/compile/nanguardmode.py +++ b/pytensor/compile/nanguardmode.py @@ -236,7 +236,7 @@ def do_check_on(value, nd, var=None): if config.NanGuardMode__action == "raise": raise AssertionError(msg) elif config.NanGuardMode__action == "pdb": - print(msg) + print(msg) # noqa: T201 import pdb pdb.set_trace() diff --git a/pytensor/compile/profiling.py b/pytensor/compile/profiling.py index 3dfe5283bb..a68365527f 100644 --- a/pytensor/compile/profiling.py +++ b/pytensor/compile/profiling.py @@ -82,7 +82,7 @@ def _atexit_print_fn(): to_sum.append(ps) else: # TODO print the name if there is one! - print("Skipping empty Profile") + print("Skipping empty Profile") # noqa: T201 if len(to_sum) > 1: # Make a global profile cum = copy.copy(to_sum[0]) @@ -125,7 +125,7 @@ def _atexit_print_fn(): assert len(merge) == len(cum.rewriter_profile[1]) cum.rewriter_profile = (cum.rewriter_profile[0], merge) except Exception as e: - print(e) + print(e) # noqa: T201 cum.rewriter_profile = None else: cum.rewriter_profile = None diff --git a/pytensor/graph/features.py b/pytensor/graph/features.py index 93321fa61f..06be6d013a 100644 --- a/pytensor/graph/features.py +++ b/pytensor/graph/features.py @@ -491,7 +491,7 @@ def validate_(self, fgraph): if verbose: r = uf.f_locals.get("r", "") reason = uf_info.function - print(f"validate failed on node {r}.\n Reason: {reason}, {e}") + print(f"validate failed on node {r}.\n Reason: {reason}, {e}") # noqa: T201 raise t1 = time.perf_counter() if fgraph.profile: @@ -603,13 +603,13 @@ def replace_all_validate( except Exception as e: fgraph.revert(chk) if verbose: - print( + print( # noqa: T201 f"rewriting: validate failed on node {r}.\n Reason: {reason}, {e}" ) raise if verbose: - print( + print( # noqa: T201 f"rewriting: rewrite {reason} replaces {r} of {r.owner} with {new_r} of {new_r.owner}" ) @@ -692,11 +692,11 @@ def on_import(self, fgraph, node, reason): except TypeError: # node.op is unhashable return except Exception as e: - print("OFFENDING node", type(node), type(node.op), file=sys.stderr) + print("OFFENDING node", type(node), type(node.op), file=sys.stderr) # noqa: T201 try: - print("OFFENDING node hash", hash(node.op), file=sys.stderr) + print("OFFENDING node hash", hash(node.op), file=sys.stderr) # noqa: T201 except Exception: - print("OFFENDING node not hashable", file=sys.stderr) + print("OFFENDING node not hashable", file=sys.stderr) # noqa: T201 raise e def on_prune(self, fgraph, node, reason): @@ -725,7 +725,7 @@ def __init__(self, active=True): def on_attach(self, fgraph): if self.active: - print("-- attaching to: ", fgraph) + print("-- attaching to: ", fgraph) # noqa: T201 def on_detach(self, fgraph): """ @@ -733,19 +733,19 @@ def on_detach(self, fgraph): that it installed into the function_graph """ if self.active: - print("-- detaching from: ", fgraph) + print("-- detaching from: ", fgraph) # noqa: T201 def on_import(self, fgraph, node, reason): if self.active: - print(f"-- importing: {node}, reason: {reason}") + print(f"-- importing: {node}, reason: {reason}") # noqa: T201 def on_prune(self, fgraph, node, reason): if self.active: - print(f"-- pruning: {node}, reason: {reason}") + print(f"-- pruning: {node}, reason: {reason}") # noqa: T201 def on_change_input(self, fgraph, node, i, r, new_r, reason=None): if self.active: - print(f"-- changing ({node}.inputs[{i}]) from {r} to {new_r}") + print(f"-- changing ({node}.inputs[{i}]) from {r} to {new_r}") # noqa: T201 class PreserveVariableAttributes(Feature): diff --git a/pytensor/graph/fg.py b/pytensor/graph/fg.py index 1d845e2eb3..e9b676f51a 100644 --- a/pytensor/graph/fg.py +++ b/pytensor/graph/fg.py @@ -491,7 +491,7 @@ def replace( if verbose is None: verbose = config.optimizer_verbose if verbose: - print( + print( # noqa: T201 f"rewriting: rewrite {reason} replaces {var} of {var.owner} with {new_var} of {new_var.owner}" ) diff --git a/pytensor/graph/rewriting/basic.py b/pytensor/graph/rewriting/basic.py index 344d6a1940..16b5b65a0e 100644 --- a/pytensor/graph/rewriting/basic.py +++ b/pytensor/graph/rewriting/basic.py @@ -1002,7 +1002,7 @@ def transform(self, fgraph, node, *args, **kwargs): # ensure we have data for all input variables that need it if missing: if self.verbose > 0: - print( + print( # noqa: T201 f"{self.__class__.__name__} cannot meta-rewrite {node}, " f"{len(missing)} of {int(node.nin)} input shapes unknown" ) @@ -1010,7 +1010,7 @@ def transform(self, fgraph, node, *args, **kwargs): # now we can apply the different rewrites in turn, # compile the resulting subgraphs and time their execution if self.verbose > 1: - print( + print( # noqa: T201 f"{self.__class__.__name__} meta-rewriting {node} ({len(self.get_rewrites(node))} choices):" ) timings = [] @@ -1027,20 +1027,20 @@ def transform(self, fgraph, node, *args, **kwargs): continue except Exception as e: if self.verbose > 0: - print(f"* {node_rewriter}: exception", e) + print(f"* {node_rewriter}: exception", e) # noqa: T201 continue else: if self.verbose > 1: - print(f"* {node_rewriter}: {timing:.5g} sec") + print(f"* {node_rewriter}: {timing:.5g} sec") # noqa: T201 timings.append((timing, outputs, node_rewriter)) else: if self.verbose > 0: - print(f"* {node_rewriter}: not applicable") + print(f"* {node_rewriter}: not applicable") # noqa: T201 # finally, we choose the fastest one if timings: timings.sort() if self.verbose > 1: - print(f"= {timings[0][2]}") + print(f"= {timings[0][2]}") # noqa: T201 return timings[0][1] return @@ -1305,7 +1305,7 @@ def transform(self, fgraph, node): new_vars = list(new_repl.values()) if config.optimizer_verbose: - print( + print( # noqa: T201 f"rewriting: rewrite {rewrite} replaces node {node} with {new_repl}" ) @@ -2641,21 +2641,21 @@ def print_profile(cls, stream, prof, level=0): try: o.print_profile(stream, prof, level + 2) except NotImplementedError: - print(blanc, "merge not implemented for ", o) + print(blanc, "merge not implemented for ", o) # noqa: T201 for o, prof in zip( rewrite.final_rewriters, final_sub_profs[i], strict=True ): try: o.print_profile(stream, prof, level + 2) except NotImplementedError: - print(blanc, "merge not implemented for ", o) + print(blanc, "merge not implemented for ", o) # noqa: T201 for o, prof in zip( rewrite.cleanup_rewriters, cleanup_sub_profs[i], strict=True ): try: o.print_profile(stream, prof, level + 2) except NotImplementedError: - print(blanc, "merge not implemented for ", o) + print(blanc, "merge not implemented for ", o) # noqa: T201 @staticmethod def merge_profile(prof1, prof2): diff --git a/pytensor/graph/utils.py b/pytensor/graph/utils.py index 9c2eef5049..42ebbcd216 100644 --- a/pytensor/graph/utils.py +++ b/pytensor/graph/utils.py @@ -274,9 +274,9 @@ def __repr__(self): return "scratchpad" + str(self.__dict__) def info(self): - print(f"") + print(f"") # noqa: T201 for k, v in self.__dict__.items(): - print(f" {k}: {v}") + print(f" {k}: {v}") # noqa: T201 # These two methods have been added to help Mypy def __getattribute__(self, name): diff --git a/pytensor/link/c/basic.py b/pytensor/link/c/basic.py index 0b717c74a6..d7f43e7377 100644 --- a/pytensor/link/c/basic.py +++ b/pytensor/link/c/basic.py @@ -875,10 +875,10 @@ def code_gen(self): self.c_init_code_apply = c_init_code_apply if (self.init_tasks, self.tasks) != self.get_init_tasks(): - print("init_tasks\n", self.init_tasks, file=sys.stderr) - print(self.get_init_tasks()[0], file=sys.stderr) - print("tasks\n", self.tasks, file=sys.stderr) - print(self.get_init_tasks()[1], file=sys.stderr) + print("init_tasks\n", self.init_tasks, file=sys.stderr) # noqa: T201 + print(self.get_init_tasks()[0], file=sys.stderr) # noqa: T201 + print("tasks\n", self.tasks, file=sys.stderr) # noqa: T201 + print(self.get_init_tasks()[1], file=sys.stderr) # noqa: T201 assert (self.init_tasks, self.tasks) == self.get_init_tasks() # List of indices that should be ignored when passing the arguments @@ -1756,7 +1756,7 @@ def __call__(self): exc_value = exc_type(_exc_value) exc_value.__thunk_trace__ = trace except Exception: - print( + print( # noqa: T201 ( "ERROR retrieving error_storage." "Was the error set in the c code?" @@ -1764,7 +1764,7 @@ def __call__(self): end=" ", file=sys.stderr, ) - print(self.error_storage, file=sys.stderr) + print(self.error_storage, file=sys.stderr) # noqa: T201 raise raise exc_value.with_traceback(exc_trace) diff --git a/pytensor/link/c/op.py b/pytensor/link/c/op.py index 74905d686f..b668f242e1 100644 --- a/pytensor/link/c/op.py +++ b/pytensor/link/c/op.py @@ -79,7 +79,7 @@ def is_f16(t): # that don't implement c code. In those cases, we # don't want to print a warning. cl.get_dynamic_module() - print(f"Disabling C code for {self} due to unsupported float16") + warnings.warn(f"Disabling C code for {self} due to unsupported float16") raise NotImplementedError("float16") outputs = cl.make_thunk( input_storage=node_input_storage, output_storage=node_output_storage diff --git a/pytensor/printing.py b/pytensor/printing.py index 6a18f6e8e5..bc42029c11 100644 --- a/pytensor/printing.py +++ b/pytensor/printing.py @@ -726,7 +726,7 @@ def _print_fn(op, xin): pmsg = temp() else: pmsg = temp - print(op.message, attr, "=", pmsg) + print(op.message, attr, "=", pmsg) # noqa: T201 class Print(Op): @@ -1657,7 +1657,7 @@ def apply_name(node): raise if print_output_file: - print("The output file is available at", outfile) + print("The output file is available at", outfile) # noqa: T201 class _TagGenerator: @@ -1824,8 +1824,7 @@ def var_descriptor(obj, _prev_obs: dict | None = None, _tag_generator=None) -> s # The __str__ method is encoding the object's id in its str name = position_independent_str(obj) if " at 0x" in name: - print(name) - raise AssertionError() + raise AssertionError(name) prefix = cur_tag + "=" diff --git a/pytensor/tensor/basic.py b/pytensor/tensor/basic.py index 8ee9894c9d..26bd34692b 100644 --- a/pytensor/tensor/basic.py +++ b/pytensor/tensor/basic.py @@ -613,7 +613,6 @@ def get_scalar_constant_value( """ if isinstance(v, TensorVariable | np.ndarray): if v.ndim != 0: - print(v, v.ndim) raise NotScalarConstantError("Input ndim != 0") return get_underlying_scalar_constant_value( v, diff --git a/pytensor/tensor/nlinalg.py b/pytensor/tensor/nlinalg.py index 1f589e1789..a9d7016099 100644 --- a/pytensor/tensor/nlinalg.py +++ b/pytensor/tensor/nlinalg.py @@ -216,9 +216,8 @@ def perform(self, node, inputs, outputs): (z,) = outputs try: z[0] = np.asarray(np.linalg.det(x), dtype=x.dtype) - except Exception: - print("Failed to compute determinant", x) - raise + except Exception as e: + raise ValueError("Failed to compute determinant", x) from e def grad(self, inputs, g_outputs): (gz,) = g_outputs @@ -256,9 +255,8 @@ def perform(self, node, inputs, outputs): (sign, det) = outputs try: sign[0], det[0] = (np.array(z, dtype=x.dtype) for z in np.linalg.slogdet(x)) - except Exception: - print("Failed to compute determinant", x) - raise + except Exception as e: + raise ValueError("Failed to compute determinant", x) from e def infer_shape(self, fgraph, node, shapes): return [(), ()] diff --git a/pytensor/tensor/rewriting/blas.py b/pytensor/tensor/rewriting/blas.py index d3fc0398c4..31264f74d4 100644 --- a/pytensor/tensor/rewriting/blas.py +++ b/pytensor/tensor/rewriting/blas.py @@ -573,7 +573,7 @@ def print_profile(cls, stream, prof, level=0): print(blanc, " callbacks_time", file=stream) for i in sorted(prof[12].items(), key=lambda a: a[1]): if i[1] > 0: - print(i) + print(i) # noqa: T201 @node_rewriter([Dot]) diff --git a/pytensor/tensor/rewriting/elemwise.py b/pytensor/tensor/rewriting/elemwise.py index 3226f9b5a7..eaba64c275 100644 --- a/pytensor/tensor/rewriting/elemwise.py +++ b/pytensor/tensor/rewriting/elemwise.py @@ -314,14 +314,14 @@ def apply(self, fgraph): except (ValueError, InconsistencyError) as e: prof["nb_inconsistent"] += 1 if check_each_change != 1 and not raised_warning: - print( + print( # noqa: T201 ( "Some inplace rewriting was not " "performed due to an unexpected error:" ), file=sys.stderr, ) - print(e, file=sys.stderr) + print(e, file=sys.stderr) # noqa: T201 raised_warning = True fgraph.revert(chk) continue @@ -335,7 +335,7 @@ def apply(self, fgraph): fgraph.validate() except Exception: if not raised_warning: - print( + print( # noqa: T201 ( "Some inplace rewriting was not " "performed due to an unexpected error" @@ -1080,7 +1080,7 @@ def print_profile(stream, prof, level=0): print(blanc, " callbacks_time", file=stream) for i in sorted(prof[6].items(), key=lambda a: a[1])[::-1]: if i[1] > 0: - print(blanc, " ", i) + print(blanc, " ", i) # noqa: T201 print(blanc, " time_toposort", prof[7], file=stream) diff --git a/pytensor/tensor/rewriting/math.py b/pytensor/tensor/rewriting/math.py index 065ecfc0b1..0af1d40bf6 100644 --- a/pytensor/tensor/rewriting/math.py +++ b/pytensor/tensor/rewriting/math.py @@ -3434,14 +3434,14 @@ def perform_sigm_times_exp( sigm_minus_x = [] if full_tree is None: full_tree = tree - if False: # Debug code. - print("") - print(f" full_tree = {full_tree}") - print(f" tree = {tree}") - print(f" exp_x = {exp_x}") - print(f" exp_minus_x = {exp_minus_x}") - print(f" sigm_x = {sigm_x}") - print(f" sigm_minus_x= {sigm_minus_x}") + # if False: # Debug code. + # print("") + # print(f" full_tree = {full_tree}") + # print(f" tree = {tree}") + # print(f" exp_x = {exp_x}") + # print(f" exp_minus_x = {exp_minus_x}") + # print(f" sigm_x = {sigm_x}") + # print(f" sigm_minus_x= {sigm_minus_x}") neg, inputs = tree if isinstance(inputs, list): # Recurse through inputs of the multiplication. diff --git a/scripts/slowest_tests/extract-slow-tests.py b/scripts/slowest_tests/extract-slow-tests.py index 3a06e4a68b..14df837a7b 100644 --- a/scripts/slowest_tests/extract-slow-tests.py +++ b/scripts/slowest_tests/extract-slow-tests.py @@ -72,7 +72,7 @@ def main(read_lines): lines = read_lines() times = extract_lines(lines) parsed_times = format_times(times) - print("\n".join(parsed_times)) + print("\n".join(parsed_times)) # noqa: T201 if __name__ == "__main__": diff --git a/tests/d3viz/test_d3viz.py b/tests/d3viz/test_d3viz.py index 7e4b0426a0..38809a5faa 100644 --- a/tests/d3viz/test_d3viz.py +++ b/tests/d3viz/test_d3viz.py @@ -28,7 +28,7 @@ def check(self, f, reference=None, verbose=False): tmp_dir = Path(tempfile.mkdtemp()) html_file = tmp_dir / "index.html" if verbose: - print(html_file) + print(html_file) # noqa: T201 d3v.d3viz(f, html_file) assert html_file.stat().st_size > 0 if reference: diff --git a/tests/link/c/test_cmodule.py b/tests/link/c/test_cmodule.py index 2242bc12e9..46533fef35 100644 --- a/tests/link/c/test_cmodule.py +++ b/tests/link/c/test_cmodule.py @@ -258,7 +258,6 @@ def test_default_blas_ldflags( def patched_compile_tmp(*args, **kwargs): def wrapped(test_code, tmp_prefix, flags, try_run, output): if len(flags) >= 2 and flags[:2] == ["-framework", "Accelerate"]: - print(enabled_accelerate_framework) if enabled_accelerate_framework: return (True, True) else: diff --git a/tests/link/numba/test_basic.py b/tests/link/numba/test_basic.py index 1b0fa8fd52..f0f73ca74d 100644 --- a/tests/link/numba/test_basic.py +++ b/tests/link/numba/test_basic.py @@ -836,7 +836,6 @@ def test_config_options_fastmath(): with config.change_flags(numba__fastmath=True): pytensor_numba_fn = function([x], pt.sum(x), mode=numba_mode) - print(list(pytensor_numba_fn.vm.jit_fn.py_func.__globals__)) numba_mul_fn = pytensor_numba_fn.vm.jit_fn.py_func.__globals__["impl_sum"] assert numba_mul_fn.targetoptions["fastmath"] == { "afn", diff --git a/tests/link/test_vm.py b/tests/link/test_vm.py index 69a922e731..dad7ed4fdd 100644 --- a/tests/link/test_vm.py +++ b/tests/link/test_vm.py @@ -1,4 +1,3 @@ -import time from collections import Counter import numpy as np @@ -108,23 +107,25 @@ def numpy_version(x, depth): return z def time_numpy(): + # TODO: Make this a benchmark test steps_a = 5 steps_b = 100 x = np.asarray([2.0, 3.0], dtype=config.floatX) numpy_version(x, steps_a) - t0 = time.perf_counter() - # print numpy_version(x, steps_a) - t1 = time.perf_counter() - t2 = time.perf_counter() - # print numpy_version(x, steps_b) - t3 = time.perf_counter() - t_a = t1 - t0 - t_b = t3 - t2 + # t0 = time.perf_counter() + numpy_version(x, steps_a) + # t1 = time.perf_counter() + # t2 = time.perf_counter() + numpy_version(x, steps_b) + # t3 = time.perf_counter() + # t_a = t1 - t0 + # t_b = t3 - t2 - print(f"numpy takes {1000 * (t_b - t_a) / (steps_b - steps_a):f} s/Kop") + # print(f"numpy takes {1000 * (t_b - t_a) / (steps_b - steps_a):f} s/Kop") def time_linker(name, linker): + # TODO: Make this a benchmark test steps_a = 5 steps_b = 100 x = vector() @@ -135,20 +136,20 @@ def time_linker(name, linker): f_b = function([x], b, mode=Mode(optimizer=None, linker=linker())) f_a([2.0, 3.0]) - t0 = time.perf_counter() + # t0 = time.perf_counter() f_a([2.0, 3.0]) - t1 = time.perf_counter() + # t1 = time.perf_counter() f_b([2.0, 3.0]) - t2 = time.perf_counter() + # t2 = time.perf_counter() f_b([2.0, 3.0]) - t3 = time.perf_counter() + # t3 = time.perf_counter() - t_a = t1 - t0 - t_b = t3 - t2 + # t_a = t1 - t0 + # t_b = t3 - t2 - print(f"{name} takes {1000 * (t_b - t_a) / (steps_b - steps_a):f} s/Kop") + # print(f"{name} takes {1000 * (t_b - t_a) / (steps_b - steps_a):f} s/Kop") time_linker("c|py", OpWiseCLinker) time_linker("vmLinker", VMLinker) @@ -167,7 +168,7 @@ def time_linker(name, linker): ], ) def test_speed_lazy(linker): - # TODO FIXME: This isn't a real test. + # TODO FIXME: This isn't a real test. Make this a benchmark test def build_graph(x, depth=5): z = x @@ -185,20 +186,20 @@ def build_graph(x, depth=5): f_b = function([x], b, mode=Mode(optimizer=None, linker=linker)) f_a([2.0]) - t0 = time.perf_counter() + # t0 = time.perf_counter() f_a([2.0]) - t1 = time.perf_counter() + # t1 = time.perf_counter() f_b([2.0]) - t2 = time.perf_counter() + # t2 = time.perf_counter() f_b([2.0]) - t3 = time.perf_counter() + # t3 = time.perf_counter() - t_a = t1 - t0 - t_b = t3 - t2 + # t_a = t1 - t0 + # t_b = t3 - t2 - print(f"{linker} takes {1000 * (t_b - t_a) / (steps_b - steps_a):f} s/Kop") + # print(f"{linker} takes {1000 * (t_b - t_a) / (steps_b - steps_a):f} s/Kop") @pytest.mark.parametrize( diff --git a/tests/scan/test_basic.py b/tests/scan/test_basic.py index b75e9ca852..9fa893ab27 100644 --- a/tests/scan/test_basic.py +++ b/tests/scan/test_basic.py @@ -12,7 +12,6 @@ import os import pickle import shutil -import sys from pathlib import Path from tempfile import mkdtemp @@ -3076,7 +3075,7 @@ def loss_inner(sum_inner, W): cost = result_outer[0][-1] H = hessian(cost, W) - print(".", file=sys.stderr) + # print(".", file=sys.stderr) f = function([W, n_steps], H) benchmark(f, np.ones((8,), dtype="float32"), 1) diff --git a/tests/tensor/rewriting/test_math.py b/tests/tensor/rewriting/test_math.py index a1759ef81b..9a092663a9 100644 --- a/tests/tensor/rewriting/test_math.py +++ b/tests/tensor/rewriting/test_math.py @@ -1628,6 +1628,7 @@ def test_local_mul_specialize(): def speed_local_pow_specialize_range(): + # TODO: This should be a benchmark test val = np.random.random(1e7) v = vector() mode = get_default_mode() @@ -1641,9 +1642,9 @@ def speed_local_pow_specialize_range(): t2 = time.perf_counter() f2(val) t3 = time.perf_counter() - print(i, t2 - t1, t3 - t2, t2 - t1 < t3 - t2) + # print(i, t2 - t1, t3 - t2, t2 - t1 < t3 - t2) if not t2 - t1 < t3 - t2: - print("WARNING WE ARE SLOWER") + raise ValueError("WARNING WE ARE SLOWER") for i in range(-3, -1500, -1): f1 = function([v], v**i, mode=mode) f2 = function([v], v**i, mode=mode_without_pow_rewrite) @@ -1653,9 +1654,9 @@ def speed_local_pow_specialize_range(): t2 = time.perf_counter() f2(val) t3 = time.perf_counter() - print(i, t2 - t1, t3 - t2, t2 - t1 < t3 - t2) + # print(i, t2 - t1, t3 - t2, t2 - t1 < t3 - t2) if not t2 - t1 < t3 - t2: - print("WARNING WE ARE SLOWER") + raise ValueError("WARNING WE ARE SLOWER") def test_local_pow_specialize(): @@ -2483,19 +2484,20 @@ def test_local_grad_log_erfc_neg(self): assert f.maker.fgraph.outputs[0].dtype == config.floatX def speed_local_log_erfc(self): + # TODO: Make this a benchmark test! val = np.random.random(1e6) x = vector() mode = get_mode("FAST_RUN") f1 = function([x], log(erfc(x)), mode=mode.excluding("local_log_erfc")) f2 = function([x], log(erfc(x)), mode=mode) - print(f1.maker.fgraph.toposort()) - print(f2.maker.fgraph.toposort()) - t0 = time.perf_counter() + # print(f1.maker.fgraph.toposort()) + # print(f2.maker.fgraph.toposort()) + # t0 = time.perf_counter() f1(val) - t1 = time.perf_counter() + # t1 = time.perf_counter() f2(val) - t2 = time.perf_counter() - print(t1 - t0, t2 - t1) + # t2 = time.perf_counter() + # print(t1 - t0, t2 - t1) class TestLocalMergeSwitchSameCond: @@ -4144,13 +4146,13 @@ def check(expr1, expr2): perform_sigm_times_exp(trees[0]) trees[0] = simplify_mul(trees[0]) good = is_same_graph(compute_mul(trees[0]), compute_mul(trees[1])) - if not good: - print(trees[0]) - print(trees[1]) - print("***") - pytensor.printing.debugprint(compute_mul(trees[0])) - print("***") - pytensor.printing.debugprint(compute_mul(trees[1])) + # if not good: + # print(trees[0]) + # print(trees[1]) + # print("***") + # pytensor.printing.debugprint(compute_mul(trees[0])) + # print("***") + # pytensor.printing.debugprint(compute_mul(trees[1])) assert good check(sigmoid(x) * exp_op(-x), sigmoid(-x)) diff --git a/tests/tensor/test_complex.py b/tests/tensor/test_complex.py index f0f7333f9c..a1b99751ed 100644 --- a/tests/tensor/test_complex.py +++ b/tests/tensor/test_complex.py @@ -73,9 +73,7 @@ def f(a): try: utt.verify_grad(f, [aval]) except GradientError as e: - print(e.num_grad.gf) - print(e.analytic_grad) - raise + raise ValueError(f"Failed: {e.num_grad.gf=} {e.analytic_grad=}") from e @pytest.mark.skip(reason="Complex grads not enabled, see #178") def test_mul_mixed1(self): @@ -88,9 +86,7 @@ def f(a): try: utt.verify_grad(f, [aval]) except GradientError as e: - print(e.num_grad.gf) - print(e.analytic_grad) - raise + raise ValueError(f"Failed: {e.num_grad.gf=} {e.analytic_grad=}") from e @pytest.mark.skip(reason="Complex grads not enabled, see #178") def test_mul_mixed(self): @@ -104,9 +100,7 @@ def f(a, b): try: utt.verify_grad(f, [aval, bval]) except GradientError as e: - print(e.num_grad.gf) - print(e.analytic_grad) - raise + raise ValueError(f"Failed: {e.num_grad.gf=} {e.analytic_grad=}") from e @pytest.mark.skip(reason="Complex grads not enabled, see #178") def test_polar_grads(self): diff --git a/tests/tensor/test_fft.py b/tests/tensor/test_fft.py index 94c49662bc..3976c67622 100644 --- a/tests/tensor/test_fft.py +++ b/tests/tensor/test_fft.py @@ -43,7 +43,6 @@ def test_1Drfft(self): utt.assert_allclose(rfft_ref, res_rfft_comp) m = rfft.type() - print(m.ndim) irfft = fft.irfft(m) f_irfft = pytensor.function([m], irfft) res_irfft = f_irfft(res_rfft) diff --git a/tests/tensor/test_shape.py b/tests/tensor/test_shape.py index 2ffcb25fe5..e85b8cfd46 100644 --- a/tests/tensor/test_shape.py +++ b/tests/tensor/test_shape.py @@ -797,7 +797,6 @@ def test_reshape(self): assert equal_computations([vect_out], [reshape(mat, new_shape)]) new_shape = stack([[-1, x], [x - 1, -1]], axis=0) - print(new_shape.type) [vect_out] = vectorize_node(node, vec, new_shape).outputs vec_test_value = np.arange(6) np.testing.assert_allclose( diff --git a/tests/test_config.py b/tests/test_config.py index 4370309f39..2dd3c32180 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -192,7 +192,7 @@ def test_invalid_configvar_access(): # But we can make sure that nothing crazy happens when we access it: with pytest.raises(configparser.ConfigAccessViolation, match="different instance"): - print(root.test__on_test_instance) + assert root.test__on_test_instance is not None def test_no_more_dotting(): diff --git a/tests/test_printing.py b/tests/test_printing.py index be5dbbc5a1..4dd4f3866d 100644 --- a/tests/test_printing.py +++ b/tests/test_printing.py @@ -138,9 +138,9 @@ def test_min_informative_str(): D. D E. E""" - if mis != reference: - print("--" + mis + "--") - print("--" + reference + "--") + # if mis != reference: + # print("--" + mis + "--") + # print("--" + reference + "--") assert mis == reference diff --git a/tests/unittest_tools.py b/tests/unittest_tools.py index a5b0a21a49..adb83fe7c0 100644 --- a/tests/unittest_tools.py +++ b/tests/unittest_tools.py @@ -1,5 +1,6 @@ import logging import sys +import warnings from copy import copy, deepcopy from functools import wraps @@ -41,12 +42,9 @@ def fetch_seed(pseed=None): else: seed = None except ValueError: - print( - ( - "Error: config.unittests__rseed contains " - "invalid seed, using None instead" - ), - file=sys.stderr, + warnings.warn( + "Error: config.unittests__rseed contains " + "invalid seed, using None instead" ) seed = None