from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import function
-from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import googletest
-@test_util.with_c_api
class FunctionTest(XLATestCase):
def testFunction(self):
from tensorflow.python.framework import op_def_registry
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
-from tensorflow.python.framework import test_util
from tensorflow.python.ops import gradients
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
self.assertEqual(b"jit_scope_0", func_attrs["_XlaScope"].s)
-@test_util.with_c_api
class CompilationEnabledInGradientTest(test.TestCase):
def testCompilationInGradient(self):
from tensorflow.contrib.distributions.python.ops.bijectors.reshape import Reshape
from tensorflow.python.framework import dtypes
-from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
-from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops.distributions.bijector_test_util import assert_bijective_and_finite
from tensorflow.python.platform import test
-@test_util.with_c_api
class _ReshapeBijectorTest(object):
"""Base class for testing the reshape transformation.
raise NotImplementedError("Subclass failed to implement `build_shapes`.")
-@test_util.with_c_api
class ReshapeBijectorTestStatic(test.TestCase, _ReshapeBijectorTest):
def build_shapes(self, shape_in, shape_out):
bijector, x, y, event_ndims=2, rtol=1e-6, atol=0)
def testInvalidDimensionsOpError(self):
- if ops._USE_C_API:
- error_message = "Invalid value in tensor used for shape: -2"
- else:
- error_message = "elements must be either positive integers or `-1`."
- self._testInvalidDimensionsOpError(error_message)
+ self._testInvalidDimensionsOpError(
+ "Invalid value in tensor used for shape: -2")
def testInputOutputMismatchOpError(self):
- if ops._USE_C_API:
- error_message = "Cannot reshape a tensor with"
- else:
- error_message = "Input to reshape is a tensor with"
- self._testInputOutputMismatchOpError(error_message)
+ self._testInputOutputMismatchOpError("Cannot reshape a tensor with")
-@test_util.with_c_api
class ReshapeBijectorTestDynamic(test.TestCase, _ReshapeBijectorTest):
def build_shapes(self, shape_in, shape_out):
self._testInputOutputMismatchOpError("Input to reshape is a tensor with")
-@test_util.with_c_api
class ReshapeBijectorTestDynamicNdims(test.TestCase, _ReshapeBijectorTest):
def build_shapes(self, shape_in, shape_out):
[3, 4], dtype=dtypes.int32))
-@test_util.with_c_api
class WithShapeTest(test.TestCase):
def _assert_with_shape(self, tensor, expected_value, expected_shape,
tensor_partial_shape.set_shape([None, 2])
for incompatible_shape in [[0], [1]]:
- if ops._USE_C_API:
- error_message = "Shapes must be equal rank, but are 2 and 1"
- else:
- error_message = r"Shapes \(\?, 2\) and \([01],\) are not compatible"
self.assertRaisesRegexp(
- ValueError, error_message,
+ ValueError, "Shapes must be equal rank, but are 2 and 1",
tensor_util.with_shape, incompatible_shape, tensor_partial_shape)
for incompatible_shape in [[1, 2, 1]]:
self.assertRaisesRegexp(ValueError, "Dimensions must be equal",
tensor_util.with_shape, incompatible_shape,
tensor_partial_shape)
for incompatible_shape in [[2, 1]]:
- if ops._USE_C_API:
- error_message = (r"Dimension 1 in both shapes must be equal, but are "
- r"2 and 1. Shapes are \[\?,2\] and \[2,1\].")
- else:
- error_message = r"Shapes \(\?, 2\) and \(2, 1\) are not compatible"
self.assertRaisesRegexp(
- ValueError, error_message,
+ ValueError,
+ r"Dimension 1 in both shapes must be equal, but are 2 and 1. "
+ r"Shapes are \[\?,2\] and \[2,1\].",
tensor_util.with_shape, incompatible_shape, tensor_partial_shape)
compatible_shape = [2, 2]
from tensorflow.contrib.losses.python.losses import loss_ops
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
-from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
-from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
self.assertAlmostEqual(np.average(weights) * 10.0, loss, 3)
-@test_util.with_c_api
class SparseSoftmaxCrossEntropyLossTest(test.TestCase):
def testNoneWeightRaisesValueError(self):
labels = constant_op.constant([[0, 1], [2, 3]])
weights = constant_op.constant([1.2, 3.4, 5.6, 7.8])
- if ops._USE_C_API:
- error_type = ValueError
- else:
- error_type = errors_impl.InvalidArgumentError
- with self.assertRaises(error_type):
+ with self.assertRaises(ValueError):
loss_ops.sparse_softmax_cross_entropy(
logits, labels, weights=weights).eval()
from tensorflow.python.platform import googletest
-@test_util.with_c_api
class IntegrationTest(test_util.TensorFlowTestCase):
"""Class to test Tensorflow-TensorRT integration."""
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
-from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
expected_seq4_batch2=expected_seq4_batch2)
-class BatchSequencesWithStatesTestWithCApi(BatchSequencesWithStatesTest):
-
- def setUp(self):
- self._prev_value = ops._USE_C_API
- ops._USE_C_API = True
- super(BatchSequencesWithStatesTestWithCApi, self).setUp()
-
- def tearDown(self):
- super(BatchSequencesWithStatesTestWithCApi, self).tearDown()
- ops._USE_C_API = self._prev_value
-
-
-@test_util.with_c_api
class PaddingTest(test.TestCase):
def testPaddingInvalidLengths(self):
from tensorflow.python.platform import test
from tensorflow.python.training import server_lib
-ops._USE_C_API = True
# NOTE(mrry): Dummy shape registration for ops used in the tests, since they
# don't have C++ op registrations on which to attach C++ shape fns.
config = config_pb2.ConfigProto(cluster_def=cluster_def)
with ops.Graph().as_default() as g, ops.device('/job:worker/task:1'):
- with ops.device('/cpu:0'):
+ with ops.device('/cpu:0'):
const = constant_op.constant(17)
sess = session.Session(server1.target, config=config, graph=g)
run_options = config_pb2.RunOptions(
with self.assertRaises(errors.FailedPreconditionError):
sess3.run(v)
- @test_util.disable_c_api # Partial runs don't work with C API
def testClusterSpecPropagationPartialRun(self):
"""Test successful partial run with ClusterSpec propagation."""
server1 = server_lib.Server.create_local_server()
from tensorflow.python.training import server_lib
-class SessionListDevicesTestMethods(object):
- """Mixin with test methods."""
+class SessionListDevicesTest(test_util.TensorFlowTestCase):
def testListDevices(self):
with session.Session() as sess:
'/job:worker/replica:0/task:1/device:CPU:0' in device_names)
-class SessionListDevicesTest(SessionListDevicesTestMethods,
- test_util.TensorFlowTestCase):
- """Test case that invokes test methods with _USE_C_API=False."""
-
- def setUp(self):
- self.prev_use_c_api = ops._USE_C_API
- ops._USE_C_API = False
- super(SessionListDevicesTest, self).setUp()
-
- def tearDown(self):
- ops._USE_C_API = self.prev_use_c_api
- super(SessionListDevicesTest, self).tearDown()
-
-
-class SessionListDevicesWithCApiTest(SessionListDevicesTestMethods,
- test_util.TensorFlowTestCase):
- """Test case that invokes test methods with _USE_C_API=True."""
-
- def setUp(self):
- self.prev_use_c_api = ops._USE_C_API
- ops._USE_C_API = True
- super(SessionListDevicesWithCApiTest, self).setUp()
-
- def tearDown(self):
- ops._USE_C_API = self.prev_use_c_api
- super(SessionListDevicesWithCApiTest, self).tearDown()
-
-
if __name__ == '__main__':
googletest.main()
ops.RegisterShape('ConstructionFails')(common_shapes.unknown_shape)
-class PartialRunTestMethods(object):
+class PartialRunTest(test_util.TensorFlowTestCase):
def RunTestPartialRun(self, sess):
a = array_ops.placeholder(dtypes.float32, shape=[])
self.RunTestPartialRunEmptyFetches(session.Session(server.target))
-class PartialRunTest(PartialRunTestMethods, test_util.TensorFlowTestCase):
- """Test case that invokes test methods with _USE_C_API=False."""
-
- def setUp(self):
- self.prev_use_c_api = ops._USE_C_API
- ops._USE_C_API = False
- super(PartialRunTest, self).setUp()
-
- def tearDown(self):
- ops._USE_C_API = self.prev_use_c_api
- super(PartialRunTest, self).tearDown()
-
-
-class PartialRunWithCApiTest(PartialRunTestMethods,
- test_util.TensorFlowTestCase):
- """Test case that invokes test methods with _USE_C_API=True."""
-
- def setUp(self):
- self.prev_use_c_api = ops._USE_C_API
- ops._USE_C_API = True
- super(PartialRunWithCApiTest, self).setUp()
-
- def tearDown(self):
- ops._USE_C_API = self.prev_use_c_api
- super(PartialRunWithCApiTest, self).tearDown()
-
-
if __name__ == '__main__':
googletest.main()
ops.RegisterShape('ConstructionFails')(common_shapes.unknown_shape)
-@test_util.with_c_api
class SessionTest(test_util.TensorFlowTestCase):
def setUp(self):
# Run with a bogus handle.
s.partial_run('foo', r1, feed_dict={a: 1, b: 2})
- def testOpConstructionErrorPayload(self):
- if ops._USE_C_API:
- return # No shape registration for 'ConstructionFails'
-
- with session.Session():
- failing_op = ops.get_default_graph().create_op(
- 'ConstructionFails', [], [], name='f')
-
- def exc_predicate(e):
- return (e.op == failing_op and
- e.error_code == error_codes_pb2.INVALID_ARGUMENT)
-
- with self.assertRaisesOpError(exc_predicate):
- failing_op.run()
-
def testErrorBasedOn(self):
with session.Session() as sess:
a = constant_op.constant(0.0, shape=[2, 3])
if gdef is None:
gdef = graph.as_graph_def()
else:
- # NOTE(skyewm): import_graph_def breaks the running threads without
- # the C API enabled. This is not a regression so I didn't fix it.
- if ops._USE_C_API:
- importer.import_graph_def(gdef, name='import')
+ importer.import_graph_def(gdef, name='import')
stop.set()
for t in threads:
return True
-@test_util.with_c_api
class VirtualGpuTest(test_util.TensorFlowTestCase):
def __init__(self, method_name):
return retval
-@test_util.with_c_api
class LinearModelTest(test.TestCase):
def test_raises_if_empty_feature_columns(self):
price = fc.numeric_column('price', shape=2)
with ops.Graph().as_default():
features = {'price': [[1.], [5.]]}
- if ops._USE_C_API:
- with self.assertRaisesRegexp(
- Exception,
- r'Cannot reshape a tensor with 2 elements to shape \[2,2\]'):
- predictions = fc.linear_model(features, [price])
- else:
- predictions = fc.linear_model(features, [price])
- with _initialized_session():
- with self.assertRaisesRegexp(Exception, 'requested shape has 4'):
- predictions.eval()
+ with self.assertRaisesRegexp(
+ Exception,
+ r'Cannot reshape a tensor with 2 elements to shape \[2,2\]'):
+ fc.linear_model(features, [price])
def test_dense_reshaping(self):
price = fc.numeric_column('price', shape=[1, 2])
sess.run(net, feed_dict={features['price']: np.array(1)})
-@test_util.with_c_api
class _LinearModelTest(test.TestCase):
def test_raises_if_empty_feature_columns(self):
price = fc.numeric_column('price', shape=2)
with ops.Graph().as_default():
features = {'price': [[1.], [5.]]}
- if ops._USE_C_API:
- with self.assertRaisesRegexp(
- Exception,
- r'Cannot reshape a tensor with 2 elements to shape \[2,2\]'):
- predictions = get_keras_linear_model_predictions(features, [price])
- else:
- predictions = get_keras_linear_model_predictions(features, [price])
- with _initialized_session():
- with self.assertRaisesRegexp(Exception, 'requested shape has 4'):
- predictions.eval()
+ with self.assertRaisesRegexp(
+ Exception,
+ r'Cannot reshape a tensor with 2 elements to shape \[2,2\]'):
+ get_keras_linear_model_predictions(features, [price])
def test_dense_reshaping(self):
price = fc.numeric_column('price', shape=[1, 2])
self.assertAllEqual([[2, 2], [2, 2], [2, 2]], gradient)
-@test_util.with_c_api
class FunctionalInputLayerTest(test.TestCase):
def test_raises_if_empty_feature_columns(self):
price = fc.numeric_column('price', shape=2)
with ops.Graph().as_default():
features = {'price': [[1.], [5.]]}
- if ops._USE_C_API:
- with self.assertRaisesRegexp(
- Exception,
- r'Cannot reshape a tensor with 2 elements to shape \[2,2\]'):
- net = fc.input_layer(features, [price])
- else:
- net = fc.input_layer(features, [price])
- with _initialized_session():
- with self.assertRaisesRegexp(Exception, 'requested shape has 4'):
- net.eval()
+ with self.assertRaisesRegexp(
+ Exception,
+ r'Cannot reshape a tensor with 2 elements to shape \[2,2\]'):
+ fc.input_layer(features, [price])
def test_reshaping(self):
price = fc.numeric_column('price', shape=[1, 2])
from tensorflow.python.framework import meta_graph
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
-from tensorflow.python.framework import test_util
from tensorflow.python.grappler import tf_optimizer
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
from tensorflow.python.training import training as train
-@test_util.with_c_api
class MemoryOptimizerSwapTest(test.TestCase):
"""Tests the Grappler memory optimizer."""
self.assertEqual('c', node.input[1])
-@test_util.with_c_api
class MemoryOptimizerRecomputeTest(test.TestCase):
"""Tests the Python interface to recomputation rewrites.
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
-from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradient_checker
from tensorflow.python.ops import gradients_impl
return np.log(x) - np.log1p(-x)
-@test_util.with_c_api
class AssertCloseTest(test.TestCase):
def testAssertCloseIntegerDtype(self):
self.assertEqual(None, du.maybe_get_static_value(x, dtype=np.float64))
-@test_util.with_c_api
class GetLogitsAndProbsTest(test.TestCase):
def testImproperArguments(self):
logit.eval(feed_dict={l: np.ones([int(2**11+1)])})
-@test_util.with_c_api
class EmbedCheckCategoricalEventShapeTest(test.TestCase):
def testTooSmall(self):
du.embed_check_categorical_event_shape(param)
-@test_util.with_c_api
class EmbedCheckIntegerCastingClosedTest(test.TestCase):
def testCorrectlyAssertsNonnegative(self):
x_checked.eval(feed_dict={x: np.array([1, -1], dtype=np.int32)})
-@test_util.with_c_api
class LogCombinationsTest(test.TestCase):
def testLogCombinationsBinomial(self):
self.assertEqual([2, 2], log_binom.get_shape())
-@test_util.with_c_api
class DynamicShapeTest(test.TestCase):
def testSameDynamicShape(self):
}))
-@test_util.with_c_api
class RotateTransposeTest(test.TestCase):
def _np_rotate_transpose(self, x, shift):
shift: shift_value}))
-@test_util.with_c_api
class PickVectorTest(test.TestCase):
def testCorrectlyPicksVector(self):
constant_op.constant(False), x, y)) # No eval.
-@test_util.with_c_api
class PreferStaticRankTest(test.TestCase):
def testNonEmptyConstantTensor(self):
self.assertAllEqual(0, rank.eval(feed_dict={x: 1}))
-@test_util.with_c_api
class PreferStaticShapeTest(test.TestCase):
def testNonEmptyConstantTensor(self):
self.assertAllEqual(np.array([]), shape.eval(feed_dict={x: 1}))
-@test_util.with_c_api
class PreferStaticValueTest(test.TestCase):
def testNonEmptyConstantTensor(self):
self.assertAllEqual(np.array(1), value.eval(feed_dict={x: 1}))
-@test_util.with_c_api
class FillTriangularTest(test.TestCase):
def setUp(self):
self._run_test(self._rng.randn(2, 3, int(7*8/2)), upper=True)
-@test_util.with_c_api
class ReduceWeightedLogSumExp(test.TestCase):
def _reduce_weighted_logsumexp(self, logx, w, axis, keep_dims=False):
du.reduce_weighted_logsumexp(x, w, axis=[0, 1]).eval())
-@test_util.with_c_api
class GenNewSeedTest(test.TestCase):
def testOnlyNoneReturnsNone(self):
# TODO(jvdillon): Merge this test back into:
# tensorflow/python/kernel_tests/softplus_op_test.py
# once TF core is accepting new ops.
-@test_util.with_c_api
class SoftplusTest(test.TestCase):
def _npSoftplus(self, np_features):
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
-from tensorflow.python.framework import test_util
from tensorflow.python.layers import convolutional as conv_layers
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.platform import test
-@test_util.with_c_api
class ConvTest(test.TestCase):
def testInvalidDataFormat(self):
conv_layers.conv3d(images, 32, 9, data_format='channels_first')
-@test_util.with_c_api
class SeparableConv1DTest(test.TestCase):
def testInvalidDataFormat(self):
self.assertEqual(layer.bias_constraint, b_constraint)
-@test_util.with_c_api
class SeparableConv2DTest(test.TestCase):
def testInvalidDataFormat(self):
self.assertEqual(layer.bias_constraint, b_constraint)
-@test_util.with_c_api
class Conv2DTransposeTest(test.TestCase):
def testInvalidDataFormat(self):
self.assertEqual(layer.bias_constraint, b_constraint)
-@test_util.with_c_api
class Conv3DTransposeTest(test.TestCase):
def testInvalidDataFormat(self):
SingletonTestTuple = collections.namedtuple("SingletonTestTuple", "a")
-@test_util.with_c_api
class GroupTestCase(test_util.TensorFlowTestCase):
def _StripNode(self, nd):
control_flow_ops.group(1, 2)
-@test_util.with_c_api
class ShapeTestCase(test_util.TensorFlowTestCase):
def testShape(self):
[constant_op.constant(1.0)], tensor).get_shape())
-@test_util.with_c_api
class WithDependenciesTestCase(test_util.TensorFlowTestCase):
def testTupleDependencies(self):
self.assertEquals(1, counter.eval())
-@test_util.with_c_api
class SwitchTestCase(test_util.TensorFlowTestCase):
def testIndexedSlicesWithDenseShape(self):
self.assertEquals(grad_x_false.eval(), 0.)
-@test_util.with_c_api
class CondTest(test_util.TensorFlowTestCase):
def testCondTrue(self):
- # Create new Graph and Session for each test so we pick up _USE_C_API
- # correctly.
with ops.Graph().as_default():
with session.Session():
x = constant_op.constant(2)
control_flow_ops.cond(True, lambda: x, lambda: x, fn2=lambda: x)
-@test_util.with_c_api
class ContextTest(test_util.TensorFlowTestCase):
def testCondContext(self):
# TODO(yori): Add tests for indexed slices.
-@test_util.with_c_api
class DataTypesTest(test_util.TensorFlowTestCase):
def assertAllEqualNested(self, a, b):
self.assertEqual(matrix.get_shape(), tensor_shape.TensorShape([2, 2]))
-@test_util.with_c_api
class CaseTest(test_util.TensorFlowTestCase):
def testCase_withDefault(self):
sess.run(output, feed_dict={x: 4})
-@test_util.with_c_api
class WhileLoopTestCase(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes()
self.assertEqual(10.0, grads[1].eval())
def testNoGradientForStringOutputs(self):
- # This test can't be run twice because the TestStringOutput gradient can
- # only be registered once. Just run with the C API enabled.
- if not ops._USE_C_API: return
-
with ops.Graph().as_default():
def _TestOpGrad(_, float_grad, string_grad):
np.testing.assert_allclose(a, b)
-@test_util.with_c_api
class FunctionGradientsTest(test_util.TensorFlowTestCase):
@classmethod
f.add_to_graph(ops.Graph())
-@test_util.with_c_api
class StopGradientTest(test_util.TensorFlowTestCase):
def testStopGradient(self):
assert igrad is None
-@test_util.with_c_api
class PreventGradientTest(test_util.TensorFlowTestCase):
def testPreventGradient(self):
_ = gradients.gradients(out, inp)
-@test_util.with_c_api
class HessianVectorProductTest(test_util.TensorFlowTestCase):
def testHessianVectorProduct(self):
self.assertAllClose(hess_v_value, hess_v_actual)
-@test_util.with_c_api
class HessianTest(test_util.TensorFlowTestCase):
def testHessian1D(self):
self.assertAllClose(hess_value, hess_actual.reshape((m * n, m * n)))
-@test_util.with_c_api
class IndexedSlicesToTensorTest(test_util.TensorFlowTestCase):
def testIndexedSlicesToTensor(self):
str(w[0].message))
-@test_util.with_c_api
class OnlyRealGradientsTest(test_util.TensorFlowTestCase):
def testRealOnly(self):
self.assertTrue(None not in grads)
-@test_util.with_c_api
class CustomGradientTest(test_util.TensorFlowTestCase):
def testCustomGradientTrivial(self):
log = np.log
-@test_util.with_c_api
class ReduceTest(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes()
math_ops.reduce_sum(x, axis)
-@test_util.with_c_api
class LogSumExpTest(test_util.TensorFlowTestCase):
def testReduceLogSumExp(self):
self.assertEqual(-np.inf, res)
-@test_util.with_c_api
class RoundTest(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes()
self.assertAllClose(y_tf_np, y_np, atol=1e-2)
-@test_util.with_c_api
class ModTest(test_util.TensorFlowTestCase):
def testFloat(self):
self.assertAllClose(y_tf_np, y_np)
-@test_util.with_c_api
class SquaredDifferenceTest(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes()
self.assertAllClose(z, z_tf)
-@test_util.with_c_api
class ApproximateEqualTest(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes()
self.assertAllEqual(z, z_tf)
-@test_util.with_c_api
class ScalarMulTest(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes()
self.assertAllEqual(self.evaluate(x.indices), [0, 2, 5])
-@test_util.with_c_api
class AccumulateNTest(test_util.TensorFlowTestCase):
def testFloat(self):
self.assertAllEqual(x[0] * 6, math_ops.accumulate_n([tf_x[0]] * 6).eval())
-@test_util.with_c_api
class AddNTest(test_util.TensorFlowTestCase):
def testPartials(self):
[g.eval() for g in add_n_grad])
-@test_util.with_c_api
class DivAndModTest(test_util.TensorFlowTestCase):
# TODO(aselle): Test more types before exposing new division operators.
from tensorflow.python.platform import test
-@test_util.with_c_api
class BatchNormalizationTest(test.TestCase):
def _npBatchNorm(self, x, m, v, beta, gamma, epsilon,
param_dtype=dtypes.float32, atol=0.001)
-@test_util.with_c_api
class SufficientStatisticsTest(test.TestCase):
def _npSuffStats(self, x, axes, shift, keep_dims):
self._testSuffStats([1, 2, 3], [0, 2], shift, keep_dims, has_shape)
-@test_util.with_c_api
class NormalizeMomentsTest(test.TestCase):
def _npNormalizeMoments(self, counts, mean_ss, variance_ss, shift):
self._testNormalizeMoments([2, 3], shift)
-@test_util.with_c_api
class MomentsTest(test.TestCase):
def _unweighted_moments(self, x, axes, keep_dims=False, extra_out_grads=None):
self._testGlobalGradient(from_y="var")
-@test_util.with_c_api
class WeightedMomentsTest(MomentsTest):
"""Tests for nn.weighted_moments.
file_io.delete_recursively(test.get_temp_dir())
-@test_util.with_c_api
class SavedModelTest(test.TestCase):
def _get_export_dir(self, label):
- if ops._USE_C_API:
- label += "_c_api"
return os.path.join(test.get_temp_dir(), label)
def _init_and_validate_variable(self, sess, variable_name, variable_value):
# does not have any attr values for the "TestAttr" node, and there is no
# default specified in the TestAttr OpDef.
sess = session.Session(graph=ops.Graph())
- if ops._USE_C_API:
- error_message = "NodeDef missing attr 'T' from Op<name=TestAttr"
- else:
- error_message = ("Expected one attr with name .*T(out)?.* in name: "
- "\"test_attr\".*")
- with self.assertRaisesRegexp(ValueError, error_message):
+ with self.assertRaisesRegexp(
+ ValueError, "NodeDef missing attr 'T' from Op<name=TestAttr"):
loader.load(sess, ["foo"], export_dir)
# Rewrite the SavedModel to change the type of the T attr in "test_attr"
from tensorflow.python.tools import optimize_for_inference_lib
-@test_util.with_c_api
class OptimizeForInferenceTest(test.TestCase):
def create_node_def(self, op, name, inputs):
from tensorflow.python.util import compat
-@test_util.with_c_api
class SaverTest(test.TestCase):
def basicSaveRestore(self, variable_op):
save.save(sess, save_path)
-@test_util.with_c_api
class SaveRestoreShardedTest(test.TestCase):
_WRITE_VERSION = saver_pb2.SaverDef.V1
self._testPartitionedVariables(use_resource=True)
-@test_util.with_c_api
class SaveRestoreShardedTestV2(SaveRestoreShardedTest):
_WRITE_VERSION = saver_pb2.SaverDef.V2
-@test_util.with_c_api
class MaxToKeepTest(test.TestCase):
def _get_test_dir(self, dirname):
self.assertFalse(gfile.Exists(save._MetaGraphFilename(s1)))
-@test_util.with_c_api
class KeepCheckpointEveryNHoursTest(test.TestCase):
def _get_test_dir(self, dirname):
self.assertTrue(saver_module.checkpoint_exists(s4))
-@test_util.with_c_api
class SaveRestoreWithVariableNameMap(test.TestCase):
def _testNonReshape(self, variable_op):
self._testNonReshape(variables.Variable)
-@test_util.with_c_api
class LatestCheckpointWithRelativePaths(test.TestCase):
@staticmethod
self.assertEqual(v0.eval(), 2.0)
-@test_util.with_c_api
class CheckpointStateTest(test.TestCase):
def _get_test_dir(self, dirname):
os.path.join(save_dir, "./model.ckpt-687529"))
-@test_util.with_c_api
class MetaGraphTest(test.TestCase):
def _get_test_dir(self, dirname):
sess.run("new_model/output:0")
-@test_util.with_c_api
class CheckpointReaderTest(test.TestCase):
_WRITE_VERSION = saver_pb2.SaverDef.V1
pywrap_tensorflow.NewCheckpointReader("non-existent")
-@test_util.with_c_api
class CheckpointReaderForV2Test(CheckpointReaderTest):
_WRITE_VERSION = saver_pb2.SaverDef.V2
-@test_util.with_c_api
class WriteGraphTest(test.TestCase):
def _get_test_dir(self, dirname):
self.assertTrue(os.path.exists(path))
-@test_util.with_c_api
class SaverUtilsTest(test.TestCase):
def setUp(self):
self.assertTrue(mtimes[1] >= mtimes[0])
-@test_util.with_c_api
class ScopedGraphTest(test.TestCase):
def _get_test_dir(self, dirname):
return ret
-@test_util.with_c_api
class CheckpointableCompatibilityTests(test.TestCase):
# TODO(allenl): Track down python3 reference cycles in these tests.
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
-from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.training import slot_creator
-@test_util.with_c_api
class SlotCreatorTest(test.TestCase):
def testCreateSlotFromVariable(self):