提交 8e24e782 authored 作者: Brandon T. Willard's avatar Brandon T. Willard

Update print warnings to use warnings.warn

This commit also removes redundant "WARNING" and "DEPRECATION" strings and, for the latter, sets the category (or raises) a `DeprecationWarning`.
上级 0d34af2e
import sys
from warnings import warn
import numpy as np
import pytest
......@@ -197,7 +197,7 @@ class TestCGemv(OptimizationTestMixin):
def test_force_gemv_init(self):
if check_force_gemv_init():
sys.stderr.write(
warn(
"WARNING: The current BLAS requires Theano to initialize"
+ " memory for some GEMV calls which will result in a minor"
+ " degradation in performance for such calls."
......
......@@ -13,6 +13,7 @@ import sys
from io import StringIO
from itertools import chain
from itertools import product as itertools_product
from warnings import warn
import numpy as np
......@@ -934,7 +935,7 @@ def _check_strides_match(a, b, warn_err, op):
if warn_err == 2:
raise e
else:
print("WARNING:", e, file=sys.stderr)
warn(str(e))
def _lessbroken_deepcopy(a):
......@@ -2459,7 +2460,7 @@ class _Maker(FunctionMaker): # inheritance buys a few helper functions
l0 = fgraph0.equivalence_tracker.event_list
if li != l0:
infolog = StringIO()
print("WARNING: Optimization process is unstable...", file=infolog)
print("Optimization process is unstable...", file=infolog)
print(
" (HINT: Ops that the nodes point to must compare " "equal)",
file=infolog,
......
......@@ -123,7 +123,7 @@ class AddDestroyHandler(gof.GlobalOptimizer):
break
if not supervisor_added:
warnings.warn(
"WARNING: Supervisor is not added. Please build a FunctionGraph"
"Supervisor is not added. Please build a FunctionGraph"
"via theano.compile.function.types.std_graph()"
"or add the Supervisor class manually.",
stacklevel=3,
......
......@@ -2014,7 +2014,7 @@ class GCC_compiler(Compiler):
and "icpc" not in theano.config.cxx
):
_logger.warning(
"OPTIMIZATION WARNING: your Theano flag `cxx` seems not to be"
"Your Theano flag `cxx` seems not to be"
" the g++ compiler. So we disable the compiler optimization"
" specific to g++ that tell to compile for a specific CPU."
" At worst, this could cause slow down.\n"
......@@ -2083,7 +2083,7 @@ class GCC_compiler(Compiler):
else:
reported_lines = native_lines
_logger.warning(
"OPTIMIZATION WARNING: Theano was not able to find the"
"Theano was not able to find the"
" g++ parameters that tune the compilation to your "
" specific CPU. This can slow down the execution of Theano"
" functions. Please submit the following lines to"
......@@ -2095,7 +2095,7 @@ class GCC_compiler(Compiler):
_logger.info(f"g++ default lines: {default_lines}")
if len(default_lines) < 1:
_logger.warning(
"OPTIMIZATION WARNING: Theano was not able to find the"
"Theano was not able to find the"
" default g++ parameters. This is needed to tune"
" the compilation to your specific"
" CPU. This can slow down the execution of Theano"
......
......@@ -3,6 +3,7 @@ import traceback
from copy import copy, deepcopy
from io import StringIO
from sys import getsizeof
from warnings import warn
import numpy as np
......@@ -334,7 +335,7 @@ def raise_with_op(fgraph, node, thunk=None, exc_info=None, storage_map=None):
str(exc_value) + detailed_err_msg + "\n" + "\n".join(hints)
)
except TypeError:
print(f"WARNING: {exc_type} error does not allow us to add extra error message")
warn(f"{exc_type} error does not allow us to add extra error message")
# Some exception need extra parameter in inputs. So forget the
# extra long error message in that case.
raise exc_value.with_traceback(exc_trace)
......
......@@ -610,17 +610,15 @@ class ReplaceValidate(History, Validator):
if rm in fgraph.apply_nodes or rm in fgraph.variables:
fgraph.revert(chk)
if warn:
out = sys.stderr
print(
"WARNING: An optimization wanted to replace a Variable"
warn(
"An optimization wanted to replace a Variable"
" in the graph, but the replacement for it doesn't"
" remove it. We disabled the optimization."
" Your function runs correctly, but it would be"
" appreciated if you submit this problem to the"
" mailing list theano-users so that we can fix it.",
file=out,
" mailing list theano-users so that we can fix it."
f"{reason}: {replacements}",
)
print(reason, replacements, file=out)
raise ReplacementDidNotRemoveError()
def __getstate__(self):
......
......@@ -3,6 +3,7 @@ import linecache
import sys
import traceback
from io import StringIO
from warnings import warn
from theano import config
......@@ -397,7 +398,10 @@ def deprecated(filename, msg=""):
def g(*args, **kwargs):
if printme[0]:
print(f"WARNING: {filename}.{f.__name__} deprecated. {msg}")
warn(
f"{filename}.{f.__name__} deprecated. {msg}",
category=DeprecationWarning,
)
printme[0] = False
return f(*args, **kwargs)
......
......@@ -24,11 +24,21 @@ try:
except ImportError:
pygpu = None
from . import ctc, dnn, extra_ops, fft, multinomial, opt, reduction, rng_mrg, sort
from .basic_ops import as_gpuarray_variable
from theano.gpuarray import (
ctc,
dnn,
extra_ops,
fft,
multinomial,
opt,
reduction,
rng_mrg,
sort,
)
from theano.gpuarray.basic_ops import as_gpuarray_variable
# This is for documentation not to depend on the availability of pygpu
from .type import (
from theano.gpuarray.type import (
ContextNotDefined,
GpuArrayConstant,
GpuArraySharedVariable,
......@@ -160,8 +170,8 @@ def init_dev(dev, name=None, preallocate=None):
f" {int(context.free_gmem / MB)} MB are available."
)
elif gmem > context.free_gmem - 50 * MB:
print(
"WARNING: Preallocating too much memory can prevent cudnn and cublas from working properly"
warnings.warn(
"Preallocating too much memory can prevent cudnn and cublas from working properly"
)
# This will allocate and immediately free an object of size gmem
......
......@@ -2157,6 +2157,7 @@ def consider_constant(x):
"consider_constant() is deprecated, use zero_grad() or "
"disconnected_grad() instead."
),
category=DeprecationWarning,
stacklevel=3,
)
......
......@@ -22,7 +22,7 @@ __all__ = [
]
warnings.warn(
"DEPRECATION: theano.sandbox.blocksparse does not exist anymore,"
"theano.sandbox.blocksparse does not exist anymore,"
"it has been moved to theano.tensor.nnet.blocksparse.",
category=DeprecationWarning,
)
import sys
from warnings import warn
print(
"DEPRECATION: theano.sandbox.conv no longer provides conv. "
warn(
"theano.sandbox.conv no longer provides conv. "
"They have been moved to theano.tensor.nnet.conv",
file=sys.stderr,
category=DeprecationWarning,
)
from theano.tensor.nnet.nnet import softsign # noqa
import sys
from warnings import warn
print(
"DEPRECATION WARNING: softsign was moved from theano.sandbox.softsign to "
"theano.tensor.nnet.nnet ",
file=sys.stderr,
warn(
"softsign was moved from theano.sandbox.softsign to theano.tensor.nnet.nnet ",
category=DeprecationWarning,
)
......@@ -377,9 +377,8 @@ def scan(
for i in range(n_outs):
if outs_info[i] is not None:
if isinstance(outs_info[i], dict):
# DEPRECATED :
if outs_info[i].get("return_steps", None) is not None:
raise ValueError(
raise DeprecationWarning(
"Using `return_steps` has been deprecated. "
"Simply select the entries you need using a "
"subtensor. Scan will optimize memory "
......@@ -396,12 +395,9 @@ def scan(
):
# ^ no initial state but taps provided
raise ValueError(
(
"If you are using slices of an output "
"you need to provide a initial state "
"for it"
),
outs_info[i],
"If you are using slices of an output "
"you need to provide a initial state "
f"for it: {outs_info[i]}"
)
elif (
outs_info[i].get("initial", None) is not None
......
......@@ -101,14 +101,6 @@ list_opt_slice = [
]
def warning(*msg):
_logger.warning("WARNING theano.scan: " + " ".join(msg))
def info(*msg):
_logger.info("INFO theano.scan: " + " ".join(msg))
@gof.local_optimizer([Scan])
def remove_constants_and_unused_inputs_scan(fgraph, node):
"""
......
......@@ -202,7 +202,8 @@ def clone(
"""
if copy_inputs is not DEPRECATED_ARG:
warnings.warn(
"In `clone()` function, the argument `copy_inputs` has been deprecated and renamed into `share_inputs`"
"In `clone()` function, the argument `copy_inputs` has been deprecated and renamed into `share_inputs`",
category=DeprecationWarning,
)
assert share_inputs # since we used `copy_inputs` we should have default value for `share_inputs`
share_inputs = copy_inputs
......
import sys
from warnings import warn
try:
......@@ -7,16 +7,10 @@ try:
scipy_ver = [int(n) for n in scipy.__version__.split(".")[:2]]
enable_sparse = bool(scipy_ver >= [0, 7])
if not enable_sparse:
sys.stderr.write(
f"WARNING: scipy version = {scipy.__version__}."
" We request version >=0.7.0 for the sparse code as it has"
" bugs fixed in the sparse matrix code.\n"
)
warn(f"SciPy version is {scipy.__version__}. We recommend a version >= 0.7.0")
except ImportError:
enable_sparse = False
sys.stderr.write(
"WARNING: scipy can't be imported." " We disable the sparse matrix code."
)
warn("scipy can't be imported." " We disable the sparse matrix code.")
from theano.sparse.type import *
......
......@@ -3,13 +3,11 @@ Classes for handling sparse matrices.
To read about different sparse formats, see
http://www-users.cs.umn.edu/~saad/software/SPARSKIT/paper.ps
"""
# TODO
# Automatic methods for determining best sparse format?
TODO: Automatic methods for determining best sparse format?
import sys
"""
from warnings import warn
import numpy as np
import scipy.sparse
......@@ -907,9 +905,8 @@ class DenseFromSparse(gof.op.Op):
(x,) = inputs
(out,) = outputs
if _is_dense(x):
print(
("WARNING: You just called DenseFromSparse on a dense matrix."),
file=sys.stderr,
warn(
"You just called DenseFromSparse on a dense matrix.",
)
out[0] = x
else:
......@@ -2398,10 +2395,8 @@ class MulSD(gof.op.Op):
z_data[j_idx] *= y[i, j]
out[0] = z
else:
print(
("WARNING: crappy implementation of MulSD"),
x.format,
file=sys.stderr,
warn(
"This implementation of MulSD is deficient: {x.format}",
)
out[0] = type(x)(x.toarray() * y)
......
......@@ -5455,7 +5455,10 @@ def flatten(x, ndim=None, outdim=None):
elif outdim is not None and ndim is not None:
raise ValueError("You should only specify ndim")
elif outdim is not None:
warnings.warn("flatten outdim parameter is deprecated, use ndim instead.")
warnings.warn(
"flatten outdim parameter is deprecated, use ndim instead.",
category=DeprecationWarning,
)
ndim = outdim
# Any input variable can be flattened to have ndim of 1,
......
......@@ -554,12 +554,12 @@ class ConvOp(OpenMPOp):
new -= 1
warnstr = (
"OPTIMISATION WARNING: in ConvOp.__init__() "
"unroll_batch(%i) must be 0 or a divisor of"
" bsize(%i). We revert it to %i. This"
"In ConvOp.__init__(): "
f"unroll_batch({self.unroll_batch}) must be 0 or a divisor of"
f" bsize({self.bsize}). We revert it to {new}. This"
" won't change the result, but may make it slower."
)
_logger.warning(warnstr, self.unroll_batch, self.bsize, new)
_logger.warning(warnstr)
self.unroll_batch = new
......@@ -580,12 +580,12 @@ class ConvOp(OpenMPOp):
new -= 1
warnstr = (
"OPTIMISATION WARNING: in ConvOp.__init__()"
" unroll_kern(%i) should be 0 or a divisor of"
" nkern(%i). We revert it to %i. This"
"In ConvOp.__init__(): "
f"unroll_kern({self.unroll_kern}) must be 0 or a divisor of"
f" nkern({self.nkern}). We revert it to {new}. This"
" won't change the result, but may make it slower."
)
_logger.warning(warnstr, self.unroll_kern, self.nkern, new)
_logger.warning(warnstr)
self.unroll_kern = new
self.outshp = get_conv_output_shape(
......
......@@ -440,9 +440,10 @@ class Softmax(Op):
raise ValueError(f"x must be 1-d or 2-d tensor of floats. Got {x.type}")
if x.ndim == 1:
warnings.warn(
"DEPRECATION: If x is a vector, Softmax will not automatically pad x "
"If x is a vector, Softmax will not automatically pad x "
"anymore in next releases. If you need it, please do it manually. The "
"vector case is gonna be supported soon and the output will be a vector.",
category=PendingDeprecationWarning,
stacklevel=4,
)
x = tt.shape_padleft(x, n_ones=1)
......@@ -638,9 +639,10 @@ class LogSoftmax(Op):
raise ValueError(f"x must be 1-d or 2-d tensor of floats. Got {x.type}")
if x.ndim == 1:
warnings.warn(
"DEPRECATION: If x is a vector, LogSoftmax will not automatically pad x "
"If x is a vector, LogSoftmax will not automatically pad x "
"anymore in next releases. If you need it, please do it manually. The "
"vector case is gonna be supported soon and the output will be a vector.",
category=PendingDeprecationWarning,
stacklevel=4,
)
x = tt.shape_padleft(x, n_ones=1)
......@@ -1661,8 +1663,7 @@ def local_argmax_pushdown(fgraph, node):
):
if theano.config.warn.argmax_pushdown_bug:
logging.getLogger("theano.tensor.nnet.nnet").warn(
"WARNING: there "
"was a bug in Theano fixed on May 27th, 2010 in this case."
"There was a bug in Theano fixed on May 27th, 2010 in this case."
" I.E. when we take the max of a softplus, softmax, exp, "
"log, tanh, sigmoid, softmax_with_bias op, we were doing "
"the max of the parent of the input. To remove this "
......
......@@ -5821,7 +5821,7 @@ def local_sum_prod_div_dimshuffle(fgraph, node):
if compatible_dims:
_logger.warning(
"WARNING: Your current code is fine, but"
"Your current code is fine, but"
" Theano versions between "
"rev. 3bd9b789f5e8 (2010-06-16) and"
" cfc6322e5ad4 (2010-08-03) would "
......@@ -5876,7 +5876,7 @@ def local_sum_prod_div_dimshuffle(fgraph, node):
node.op, Sum
):
_logger.warning(
"WARNING: Your current code is fine,"
"Your current code is fine,"
" but Theano versions between "
"rev. 3bd9b789f5e8 (2010-06-16) and"
" cfc6322e5ad4 (2010-08-03) would "
......@@ -5986,7 +5986,7 @@ def local_op_of_op(fgraph, node):
and len(newaxis) == len(newaxis_old)
):
_logger.warning(
"WARNING (YOUR CURRENT CODE IS FINE): Theano "
"(YOUR CURRENT CODE IS FINE): Theano "
"versions between version 9923a40c7b7a and August "
"2nd, 2010 generated bugged code in this case. "
"This happens when there are two consecutive sums "
......
"""Define random number Type (`RandomStateType`) and Op (`RandomFunction`)."""
import sys
from copy import copy
from functools import reduce
from warnings import warn
import numpy as np
......@@ -200,10 +199,8 @@ class RandomFunction(gof.Op):
assert shape.type.ndim == 1
assert (shape.type.dtype == "int64") or (shape.type.dtype == "int32")
if not isinstance(r.type, RandomStateType):
print(
"WARNING: RandomState instances should be in RandomStateType",
file=sys.stderr,
)
warn("RandomState instances should be in RandomStateType")
# the following doesn't work because we want to ignore the
# broadcastable flags in shape.type
# assert shape.type == tensor.lvector
......@@ -532,9 +529,9 @@ def binomial(random_state, size=None, n=1, p=0.5, ndim=None, dtype="int64", prob
"""
if prob is not None:
p = prob
print(
"DEPRECATION WARNING: the parameter prob to the binomal fct have been renamed to p to have the same name as np.",
file=sys.stderr,
warn(
"The parameter prob to the binomal fct have been renamed to p to have the same name as np.",
category=DeprecationWarning,
)
n = tensor.as_tensor_variable(n)
p = tensor.as_tensor_variable(p)
......@@ -964,9 +961,9 @@ class RandomStreamsBase:
"""
if prob is not None:
p = prob
print(
"DEPRECATION WARNING: the parameter prob to the binomal fct have been renamed to p to have the same name as numpy.",
file=sys.stderr,
warn(
"The parameter prob to the binomal fct have been renamed to p to have the same name as numpy.",
category=DeprecationWarning,
)
return self.gen(binomial, size, n, p, ndim=ndim, dtype=dtype)
......
......@@ -93,9 +93,10 @@ def pool_2d(
)
else:
warnings.warn(
"DEPRECATION: the 'ds' parameter is not going to exist"
"The 'ds' parameter is not going to exist"
" anymore as it is going to be replaced by the parameter"
" 'ws'.",
category=DeprecationWarning,
stacklevel=2,
)
ws = ds
......@@ -110,9 +111,10 @@ def pool_2d(
)
else:
warnings.warn(
"DEPRECATION: the 'st' parameter is not going to exist"
"The 'st' parameter is not going to exist"
" anymore as it is going to be replaced by the parameter"
" 'stride'.",
category=DeprecationWarning,
stacklevel=2,
)
stride = st
......@@ -125,9 +127,10 @@ def pool_2d(
)
else:
warnings.warn(
"DEPRECATION: the 'padding' parameter is not going to exist"
"The 'padding' parameter is not going to exist"
" anymore as it is going to be replaced by the parameter"
" 'pad'.",
category=DeprecationWarning,
stacklevel=2,
)
pad = padding
......@@ -145,6 +148,7 @@ def pool_2d(
" GPU combination supported is when"
" `ws == stride and pad == (0, 0) and mode == 'max'`."
" Otherwise, the convolution will be executed on CPU.",
category=DeprecationWarning,
stacklevel=2,
)
ignore_border = False
......@@ -210,9 +214,10 @@ def pool_3d(
)
else:
warnings.warn(
"DEPRECATION: the 'ds' parameter is not going to exist"
"The 'ds' parameter is not going to exist"
" anymore as it is going to be replaced by the parameter"
" 'ws'.",
category=DeprecationWarning,
stacklevel=2,
)
ws = ds
......@@ -227,9 +232,10 @@ def pool_3d(
)
else:
warnings.warn(
"DEPRECATION: the 'st' parameter is not going to exist"
"The 'st' parameter is not going to exist"
" anymore as it is going to be replaced by the parameter"
" 'stride'.",
category=DeprecationWarning,
stacklevel=2,
)
stride = st
......@@ -242,9 +248,10 @@ def pool_3d(
)
else:
warnings.warn(
"DEPRECATION: the 'padding' parameter is not going to exist"
"The 'padding' parameter is not going to exist"
" anymore as it is going to be replaced by the parameter"
" 'pad'.",
category=DeprecationWarning,
stacklevel=2,
)
pad = padding
......@@ -262,6 +269,7 @@ def pool_3d(
" GPU combination supported is when"
" `ws == stride and pad == (0, 0, 0) and mode == 'max'`."
" Otherwise, the convolution will be executed on CPU.",
category=DeprecationWarning,
stacklevel=2,
)
ignore_border = False
......@@ -387,9 +395,10 @@ class Pool(OpenMPOp):
)
else:
warnings.warn(
"DEPRECATION: the 'ds' parameter is not going to exist"
"The 'ds' parameter is not going to exist"
" anymore as it is going to be replaced by the parameter"
" 'ws'.",
category=DeprecationWarning,
stacklevel=2,
)
ws = ds
......@@ -404,9 +413,10 @@ class Pool(OpenMPOp):
)
else:
warnings.warn(
"DEPRECATION: the 'st' parameter is not going to exist"
"The 'st' parameter is not going to exist"
" anymore as it is going to be replaced by the parameter"
" 'stride'.",
category=DeprecationWarning,
stacklevel=2,
)
stride = st
......@@ -420,9 +430,10 @@ class Pool(OpenMPOp):
)
else:
warnings.warn(
"DEPRECATION: the 'padding' parameter is not going to"
"The 'padding' parameter is not going to"
" exist anymore as it is going to be replaced by the"
" parameter 'pad'.",
category=DeprecationWarning,
stacklevel=2,
)
pad = padding
......@@ -1032,9 +1043,10 @@ class PoolGrad(OpenMPOp):
)
else:
warnings.warn(
"DEPRECATION: the 'ds' parameter in PoolGrad is not going"
"The 'ds' parameter in PoolGrad is not going"
" to exist anymore as it is going to be replaced by the"
" parameter 'ws'.",
category=DeprecationWarning,
stacklevel=2,
)
ws = ds
......@@ -1049,9 +1061,10 @@ class PoolGrad(OpenMPOp):
)
else:
warnings.warn(
"DEPRECATION: the 'st' parameter in PoolGrad is not going"
"The 'st' parameter in PoolGrad is not going"
" to exist anymore as it is going to be replaced by the"
" parameter 'stride'.",
category=DeprecationWarning,
stacklevel=2,
)
stride = st
......@@ -1064,9 +1077,10 @@ class PoolGrad(OpenMPOp):
)
else:
warnings.warn(
"DEPRECATION: the 'padding' parameter in PoolGrad is not"
"The 'padding' parameter in PoolGrad is not"
" going to exist anymore as it is going to be replaced"
" by the parameter 'pad'.",
category=DeprecationWarning,
stacklevel=2,
)
pad = padding
......
......@@ -55,9 +55,10 @@ class TensorType(Type):
self.sparse_grad = sparse_grad
if sparse_grad:
warnings.warn(
"DEPRECATION WARNING: You use an old interface to"
"You use an old interface to"
" AdvancedSubtensor1 sparse_grad. Now use"
" theano.sparse_grad(a_tensor[an_int_vector])."
" theano.sparse_grad(a_tensor[an_int_vector]).",
category=DeprecationWarning,
)
def clone(self, dtype=None, broadcastable=None):
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论