Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 0 additions & 35 deletions python/paddle/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@

__all__ = []

int_type = int
long_type = int


# str and bytes related functions
def to_text(obj, encoding='utf-8', inplace=False):
Expand Down Expand Up @@ -227,35 +224,3 @@ def round(x, d=0):
else:
import __builtin__
return __builtin__.round(x, d)


def floor_division(x, y):
"""
Compatible division which act the same behaviour in Python3 and Python2,
whose result will be a int value of floor(x / y) in Python3 and value of
(x / y) in Python2.

Args:
x(int|float) : The number to divide.
y(int|float) : The number to be divided

Returns:
division result of x // y
"""
return x // y


# exception related functions
def get_exception_message(exc):
"""
Get the error message of a specific exception

Args:
exec(Exception) : The exception to get error message.

Returns:
the error message of exec
"""
assert exc is not None

return str(exc)
15 changes: 6 additions & 9 deletions python/paddle/fluid/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,17 @@
from .. import compat as cpt
if os.name == 'nt':
executable_path = os.path.abspath(os.path.dirname(sys.executable))
raise ImportError(
"""NOTE: You may need to run \"set PATH=%s;%%PATH%%\"
raise ImportError("""NOTE: You may need to run \"set PATH=%s;%%PATH%%\"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

测试覆盖率没过,不过与本 PR 无关

image

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已豁免

if you encounters \"DLL load failed\" errors. If you have python
installed in other directory, replace \"%s\" with your own
directory. The original error is: \n %s""" %
(executable_path, executable_path, cpt.get_exception_message(e)))
(executable_path, executable_path, str(e)))
else:
raise ImportError(
"""NOTE: You may need to run \"export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH\"
if you encounters \"libmkldnn.so not found\" errors. If you have python
installed in other directory, replace \"/usr/local/lib\" with your own
directory. The original error is: \n""" + cpt.get_exception_message(e))
directory. The original error is: \n""" + str(e))
except Exception as e:
raise e

Expand All @@ -75,8 +74,7 @@ def avx_supported():
has_avx = os.popen('cat /proc/cpuinfo | grep -i avx').read() != ''
except Exception as e:
sys.stderr.write('Can not get the AVX flag from /proc/cpuinfo.\n'
'The original error is: %s\n' %
cpt.get_exception_message(e))
'The original error is: %s\n' % str(e))
return has_avx
elif sysstr == 'darwin':
try:
Expand All @@ -85,7 +83,7 @@ def avx_supported():
except Exception as e:
sys.stderr.write(
'Can not get the AVX flag from machdep.cpu.features.\n'
'The original error is: %s\n' % cpt.get_exception_message(e))
'The original error is: %s\n' % str(e))
if not has_avx:
import subprocess
pipe = subprocess.Popen(
Expand Down Expand Up @@ -155,8 +153,7 @@ def asm_func(code_str, restype=ctypes.c_uint32, argtypes=()):
ctypes.c_size_t(0), ONE_PAGE)
except Exception as e:
sys.stderr.write('Failed getting the AVX flag on Windows.\n'
'The original error is: %s\n' %
cpt.get_exception_message(e))
'The original error is: %s\n' % str(e))
return (retval & (1 << avx_bit)) > 0
else:
sys.stderr.write('Do not get AVX flag on %s\n' % sysstr)
Expand Down
19 changes: 9 additions & 10 deletions python/paddle/fluid/tests/unittests/dist_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
from paddle.fluid import core
from test_dist_base import TestDistRunnerBase, runtime_main, RUN_STEP
import paddle.compat as cpt
from paddle.compat import long_type

import hashlib

Expand Down Expand Up @@ -183,10 +182,10 @@ def merge_cfg_from_list(cfg_list, g_cfgs):
input_descs = {
# The actual data shape of src_word is:
# [batch_size * max_src_len_in_batch, 1]
"src_word": [(batch_size, seq_len, long_type(1)), "int64", 2],
"src_word": [(batch_size, seq_len, 1), "int64", 2],
# The actual data shape of src_pos is:
# [batch_size * max_src_len_in_batch, 1]
"src_pos": [(batch_size, seq_len, long_type(1)), "int64"],
"src_pos": [(batch_size, seq_len, 1), "int64"],
# This input is used to remove attention weights on paddings in the
# encoder.
# The actual data shape of src_slf_attn_bias is:
Expand All @@ -195,11 +194,11 @@ def merge_cfg_from_list(cfg_list, g_cfgs):
[(batch_size, ModelHyperParams.n_head, seq_len, seq_len), "float32"],
# The actual data shape of trg_word is:
# [batch_size * max_trg_len_in_batch, 1]
"trg_word": [(batch_size, seq_len, long_type(1)), "int64",
"trg_word": [(batch_size, seq_len, 1), "int64",
2], # lod_level is only used in fast decoder.
# The actual data shape of trg_pos is:
# [batch_size * max_trg_len_in_batch, 1]
"trg_pos": [(batch_size, seq_len, long_type(1)), "int64"],
"trg_pos": [(batch_size, seq_len, 1), "int64"],
# This input is used to remove attention weights on paddings and
# subsequent words in the decoder.
# The actual data shape of trg_slf_attn_bias is:
Expand All @@ -218,15 +217,15 @@ def merge_cfg_from_list(cfg_list, g_cfgs):
"enc_output": [(batch_size, seq_len, ModelHyperParams.d_model), "float32"],
# The actual data shape of label_word is:
# [batch_size * max_trg_len_in_batch, 1]
"lbl_word": [(batch_size * seq_len, long_type(1)), "int64"],
"lbl_word": [(batch_size * seq_len, 1), "int64"],
# This input is used to mask out the loss of padding tokens.
# The actual data shape of label_weight is:
# [batch_size * max_trg_len_in_batch, 1]
"lbl_weight": [(batch_size * seq_len, long_type(1)), "float32"],
"lbl_weight": [(batch_size * seq_len, 1), "float32"],
# These inputs are used to change the shape tensor in beam-search decoder.
"trg_slf_attn_pre_softmax_shape_delta": [(long_type(2), ), "int32"],
"trg_slf_attn_post_softmax_shape_delta": [(long_type(4), ), "int32"],
"init_score": [(batch_size, long_type(1)), "float32"],
"trg_slf_attn_pre_softmax_shape_delta": [(2, ), "int32"],
"trg_slf_attn_post_softmax_shape_delta": [(4, ), "int32"],
"init_score": [(batch_size, 1), "float32"],
}

# Names of word embedding table which might be reused for weight sharing.
Expand Down
28 changes: 0 additions & 28 deletions python/paddle/fluid/tests/unittests/test_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@

class TestCompatible(unittest.TestCase):

def test_type(self):
self.assertEqual(cpt.int_type, int)
self.assertEqual(cpt.long_type, int)

def test_to_text(self):
self.assertIsNone(cpt.to_text(None))

Expand Down Expand Up @@ -252,30 +248,6 @@ def test_round(self):
self.assertEqual(5.0, cpt.round(5))
self.assertRaises(TypeError, cpt.round, None)

def test_floor_division(self):
self.assertEqual(0.0, cpt.floor_division(3, 4))
self.assertEqual(1.0, cpt.floor_division(4, 3))
self.assertEqual(2.0, cpt.floor_division(6, 3))
self.assertEqual(-2.0, cpt.floor_division(-4, 3))
self.assertEqual(-2.0, cpt.floor_division(-6, 3))
self.assertRaises(ZeroDivisionError, cpt.floor_division, 3, 0)
self.assertRaises(TypeError, cpt.floor_division, None, None)

def test_get_exception_message(self):
exception_message = "test_message"
self.assertRaises(AssertionError, cpt.get_exception_message, None)
try:
raise RuntimeError(exception_message)
except Exception as e:
self.assertEqual(exception_message, cpt.get_exception_message(e))
self.assertIsNotNone(e)

try:
raise Exception(exception_message)
except Exception as e:
self.assertEqual(exception_message, cpt.get_exception_message(e))
self.assertIsNotNone(e)


if __name__ == "__main__":
unittest.main()
4 changes: 2 additions & 2 deletions python/paddle/fluid/tests/unittests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -906,7 +906,7 @@ def test_dataset_none(self):
print("warning: we skip trainer_desc_pb2 import problem in windows")
except RuntimeError as e:
error_msg = "dataset is need and should be initialized"
self.assertEqual(error_msg, cpt.get_exception_message(e))
self.assertEqual(error_msg, str(e))
except Exception as e:
self.assertTrue(False)

Expand Down Expand Up @@ -950,7 +950,7 @@ def test_fetch_handler(self):
print("warning: we skip trainer_desc_pb2 import problem in windows")
except RuntimeError as e:
error_msg = "dataset is need and should be initialized"
self.assertEqual(error_msg, cpt.get_exception_message(e))
self.assertEqual(error_msg, str(e))
except Exception as e:
self.assertTrue(False)

Expand Down
3 changes: 1 addition & 2 deletions python/paddle/fluid/tests/unittests/test_exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ def test_exception(self):
try:
core.__unittest_throw_exception__()
except RuntimeError as ex:
self.assertIn("This is a test of exception",
cpt.get_exception_message(ex))
self.assertIn("This is a test of exception", str(ex))
exception = ex

self.assertIsNotNone(exception)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ def __reader__():
for _ in loader():
print("test_single_process_with_thread_expection")
except core.EnforceNotMet as ex:
self.assertIn("Blocking queue is killed",
cpt.get_exception_message(ex))
self.assertIn("Blocking queue is killed", str(ex))
exception = ex
self.assertIsNotNone(exception)

Expand Down Expand Up @@ -131,8 +130,7 @@ def __reader__():
for image, _ in loader():
fluid.layers.relu(image)
except core.EnforceNotMet as ex:
self.assertIn("Blocking queue is killed",
cpt.get_exception_message(ex))
self.assertIn("Blocking queue is killed", str(ex))
exception = ex
self.assertIsNotNone(exception)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def func_test_not_callable_func(self):
try:
CleanupFuncRegistrar.register(5)
except TypeError as ex:
self.assertIn("is not callable", cpt.get_exception_message(ex))
self.assertIn("is not callable", str(ex))
exception = ex
self.assertIsNotNone(exception)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def func_simple_example_eager_grad_not_allow_unused(self):
# allow_unused is false in default
dx = fluid.dygraph.grad(out, [x, z])
except ValueError as e:
error_msg = cpt.get_exception_message(e)
error_msg = str(e)
assert error_msg.find("allow_unused") > 0

def test_simple_example_eager_grad_not_allow_unused(self):
Expand All @@ -134,7 +134,7 @@ def func_simple_example_eager_grad_duplicate_input(self):
# duplicate input will arise RuntimeError errors
dx = fluid.dygraph.grad(out, [x, x])
except RuntimeError as e:
error_msg = cpt.get_exception_message(e)
error_msg = str(e)
assert error_msg.find("duplicate") > 0

def test_simple_example_eager_grad_duplicate_input(self):
Expand All @@ -158,7 +158,7 @@ def func_simple_example_eager_grad_duplicate_output(self):
# duplicate output will arise RuntimeError errors
dx = fluid.dygraph.grad([out, out], [x])
except RuntimeError as e:
error_msg = cpt.get_exception_message(e)
error_msg = str(e)
assert error_msg.find("duplicate") > 0

def test_simple_example_eager_grad_duplicate_output(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def try_except_exit():
set_child_signal_handler(id(self), test_process.pid)
time.sleep(5)
except SystemError as ex:
self.assertIn("Fatal", cpt.get_exception_message(ex))
self.assertIn("Fatal", str(ex))
exception = ex
return exception

Expand Down Expand Up @@ -88,8 +88,7 @@ def try_except_exit():
set_child_signal_handler(id(self), test_process.pid)
time.sleep(5)
except SystemError as ex:
self.assertIn("Segmentation fault",
cpt.get_exception_message(ex))
self.assertIn("Segmentation fault", str(ex))
exception = ex
return exception

Expand Down Expand Up @@ -122,7 +121,7 @@ def try_except_exit():
set_child_signal_handler(id(self), test_process.pid)
time.sleep(5)
except SystemError as ex:
self.assertIn("Bus error", cpt.get_exception_message(ex))
self.assertIn("Bus error", str(ex))
exception = ex
return exception

Expand Down
6 changes: 3 additions & 3 deletions python/paddle/fluid/tests/unittests/test_lookup_table_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def test_check_output(self):
flatten_idx = ids.flatten()
padding_idx = np.random.choice(flatten_idx, 1)[0]
self.outputs['Out'][np.squeeze(ids == padding_idx)] = np.zeros(31)
self.attrs = {'padding_idx': cpt.long_type(padding_idx)}
self.attrs = {'padding_idx': padding_idx}
self.check_output()


Expand Down Expand Up @@ -250,7 +250,7 @@ def test_check_output(self):
flatten_idx = ids.flatten()
padding_idx = np.random.choice(flatten_idx, 1)[0]
self.outputs['Out'][np.squeeze(ids == padding_idx)] = np.zeros(31)
self.attrs = {'padding_idx': cpt.long_type(padding_idx)}
self.attrs = {'padding_idx': padding_idx}
self.check_output()

def test_check_grad(self):
Expand Down Expand Up @@ -380,7 +380,7 @@ def test_check_output(self):
flatten_idx = ids.flatten()
padding_idx = np.random.choice(flatten_idx, 1)[0]
self.outputs['Out'][np.squeeze(ids == padding_idx)] = np.zeros(31)
self.attrs = {'padding_idx': cpt.long_type(padding_idx)}
self.attrs = {'padding_idx': padding_idx}
self.check_output()


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def test_check_output(self):
flatten_idx = ids.flatten()
padding_idx = np.random.choice(flatten_idx, 1)[0]
self.outputs['Out'][np.squeeze(ids == padding_idx)] = np.zeros(31)
self.attrs = {'padding_idx': cpt.long_type(padding_idx)}
self.attrs = {'padding_idx': padding_idx}
self.check_output()


Expand Down
5 changes: 2 additions & 3 deletions python/paddle/fluid/tests/unittests/test_operator_desc.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,14 @@ def test_error_type(self):
self.assertFail()
except ValueError as v_err:
self.assertEqual(
cpt.get_exception_message(v_err),
str(v_err),
"`type` to initialized an Operator can not be None.")
try:
block.append_op(type="no_such_op")
self.assertFail()
except ValueError as a_err:
self.assertEqual(
cpt.get_exception_message(a_err),
"Operator \"no_such_op\" has not been registered.")
str(a_err), "Operator \"no_such_op\" has not been registered.")

def test_op_desc_creation(self):
program = Program()
Expand Down
2 changes: 1 addition & 1 deletion python/paddle/fluid/tests/unittests/test_optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -990,7 +990,7 @@ def test_load(self):
except NotImplementedError as e:
self.assertEqual(
"load function is not supported by Recompute Optimizer for now",
cpt.get_exception_message(e))
str(e))

def test_dropout(self):
"""
Expand Down
2 changes: 1 addition & 1 deletion python/paddle/fluid/tests/unittests/test_prune.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def test_prune_target_none(self):
except ValueError as e:
self.assertIn(
"All targets of Program._prune_with_input() can only be Variable or Operator",
cpt.get_exception_message(e))
str(e))


def mock(self, program, feed, fetch, optimize_ops):
Expand Down
2 changes: 1 addition & 1 deletion python/paddle/fluid/tests/unittests/test_zeros_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def test_shape_errors(self):
shape = [-1, 5]
out = paddle.zeros(shape)
except Exception as e:
error_msg = cpt.get_exception_message(e)
error_msg = str(e)
assert error_msg.find("expected to be no less than 0") > 0

def test_eager(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def test_check_output(self):
flatten_idx = ids.flatten()
padding_idx = np.random.choice(flatten_idx, 1)[0]
self.outputs['Out'][np.squeeze(ids == padding_idx)] = np.zeros(31)
self.attrs = {'padding_idx': cpt.long_type(padding_idx)}
self.attrs = {'padding_idx': padding_idx}
self.check_output_with_place(place=paddle.XPUPlace(0))


Expand Down