python_code
stringlengths
0
258k
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np import functools import itertools as it class TestReduceOps(hu.HypothesisTestCase): @given( d0=st.integers(1, 5), d1=st.integers(1, 5), d2=st.integers(1, 5), d3=st.integers(1, 5), keepdims=st.integers(0, 1), seed=st.integers(0, 2**32 - 1), **hu.gcs_cpu_only) def test_reduce_sum_mean(self, d0, d1, d2, d3, keepdims, seed, gc, dc): def reduce_mean_ref(data, axis, keepdims): return [np.mean(data, axis=axis, keepdims=keepdims)] def reduce_sum_ref(data, axis, keepdims): return [np.sum(data, axis=axis, keepdims=keepdims)] def reduce_op_test(op_name, op_ref, data, axes, keepdims, device): op = core.CreateOperator( op_name, ["data"], ["Y"], axes=axes, keepdims=keepdims, ) self.assertReferenceChecks(device, op, [data], functools.partial( op_ref, axis=axes, keepdims=keepdims)) np.random.seed(seed) for axes in it.combinations(range(4), 2): data = np.random.randn(d0, d1, d2, d3).astype(np.float32) reduce_op_test("ReduceMean", reduce_mean_ref, data, axes, keepdims, gc) reduce_op_test("ReduceSum", reduce_sum_ref, data, axes, keepdims, gc) for axes in it.combinations(range(3), 2): data = np.random.randn(d0, d1, d2).astype(np.float32) reduce_op_test("ReduceMean", reduce_mean_ref, data, axes, keepdims, gc) reduce_op_test("ReduceSum", reduce_sum_ref, data, axes, keepdims, gc) for axes in it.combinations(range(2), 2): data = np.random.randn(d0, d1).astype(np.float32) reduce_op_test("ReduceMean", reduce_mean_ref, data, axes, keepdims, gc) reduce_op_test("ReduceSum", reduce_sum_ref, data, axes, keepdims, gc) for axes in it.combinations(range(1), 1): data = np.random.randn(d0).astype(np.float32) reduce_op_test("ReduceMean", reduce_mean_ref, data, axes, keepdims, gc) reduce_op_test("ReduceSum", reduce_sum_ref, data, axes, keepdims, gc) class TestReduceFrontReductions(hu.HypothesisTestCase): def grad_variant_input_test(self, grad_op_name, X, ref, num_reduce_dim): workspace.ResetWorkspace() Y = np.array(ref(X)[0]).astype(np.float32) dY = np.array(np.random.rand(*Y.shape)).astype(np.float32) shape = np.array(X.shape).astype(np.int64) workspace.FeedBlob("X", X) workspace.FeedBlob("dY", dY) workspace.FeedBlob("shape", shape) grad_op = core.CreateOperator( grad_op_name, ["dY", "X"], ["dX"], num_reduce_dim=num_reduce_dim) grad_op1 = core.CreateOperator( grad_op_name, ["dY", "shape"], ["dX1"], num_reduce_dim=num_reduce_dim) workspace.RunOperatorOnce(grad_op) workspace.RunOperatorOnce(grad_op1) dX = workspace.FetchBlob("dX") dX1 = workspace.FetchBlob("dX1") np.testing.assert_array_equal(dX, dX1) def max_op_test(self, op_name, num_reduce_dim, gc, dc, in_data, in_names, ref_max): op = core.CreateOperator( op_name, in_names, ["outputs"], num_reduce_dim=num_reduce_dim ) self.assertReferenceChecks( device_option=gc, op=op, inputs=in_data, reference=ref_max, ) # Skip gradient check because it is too unreliable with max. # Just check CPU and CUDA have same results Y = np.array(ref_max(*in_data)[0]).astype(np.float32) dY = np.array(np.random.rand(*Y.shape)).astype(np.float32) if len(in_data) == 2: grad_in_names = ["dY", in_names[0], "Y", in_names[1]] grad_in_data = [dY, in_data[0], Y, in_data[1]] else: grad_in_names = ["dY", in_names[0], "Y"] grad_in_data = [dY, in_data[0], Y] grad_op = core.CreateOperator( op_name + "Gradient", grad_in_names, ["dX"], num_reduce_dim=num_reduce_dim ) self.assertDeviceChecks(dc, grad_op, grad_in_data, [0]) def reduce_op_test(self, op_name, op_ref, in_data, in_names, num_reduce_dims, device): op = core.CreateOperator( op_name, in_names, ["outputs"], num_reduce_dim=num_reduce_dims ) self.assertReferenceChecks( device_option=device, op=op, inputs=in_data, reference=op_ref ) self.assertGradientChecks( device, op, in_data, 0, [0], stepsize=1e-2, threshold=1e-2) @given(num_reduce_dim=st.integers(0, 4), **hu.gcs) def test_reduce_front_sum(self, num_reduce_dim, gc, dc): X = np.random.rand(7, 4, 3, 5).astype(np.float32) def ref_sum(X): return [np.sum(X, axis=(tuple(range(num_reduce_dim))))] self.reduce_op_test( "ReduceFrontSum", ref_sum, [X], ["input"], num_reduce_dim, gc) self.grad_variant_input_test( "ReduceFrontSumGradient", X, ref_sum, num_reduce_dim) @given(**hu.gcs) def test_reduce_front_sum_with_length(self, dc, gc): num_reduce_dim = 1 X = np.random.rand(2, 3, 4, 5).astype(np.float32) batch_size = int(np.prod([2, 3, 4, 5][num_reduce_dim:])) d = 120 // batch_size lengths = np.random.randint(1, d, size=batch_size).astype(np.int32) def ref_sum(X, lengths): Y = X.reshape(d, lengths.size) rv = np.zeros((lengths.size, 1)).astype(np.float32) for ii in range(lengths.size): rv[ii] = np.sum(Y[:lengths[ii], ii]) return [rv.reshape((2, 3, 4, 5)[num_reduce_dim:])] self.reduce_op_test( "ReduceFrontSum", ref_sum, [X, lengths], ["input", "lengths"], num_reduce_dim, gc) @given(num_reduce_dim=st.integers(0, 4), **hu.gcs) def test_reduce_front_mean(self, num_reduce_dim, gc, dc): X = np.random.rand(6, 7, 8, 2).astype(np.float32) def ref_mean(X): return [np.mean(X, axis=(tuple(range(num_reduce_dim))))] self.reduce_op_test( "ReduceFrontMean", ref_mean, [X], ["input"], num_reduce_dim, gc) self.grad_variant_input_test( "ReduceFrontMeanGradient", X, ref_mean, num_reduce_dim) @given(**hu.gcs) def test_reduce_front_mean_with_length(self, dc, gc): num_reduce_dim = 1 X = np.random.rand(2, 3, 4, 5).astype(np.float32) batch_size = int(np.prod([2, 3, 4, 5][num_reduce_dim:])) d = 120 // batch_size lengths = np.random.randint(1, d, size=batch_size).astype(np.int32) def ref_mean(X, lengths): Y = X.reshape(d, lengths.size) rv = np.zeros((lengths.size, 1)).astype(np.float32) for ii in range(lengths.size): rv[ii] = np.mean(Y[:lengths[ii], ii]) return [rv.reshape((2, 3, 4, 5)[num_reduce_dim:])] self.reduce_op_test( "ReduceFrontMean", ref_mean, [X, lengths], ["input", "lengths"], num_reduce_dim, gc) @given(num_reduce_dim=st.integers(0, 4), **hu.gcs) def test_reduce_front_max(self, num_reduce_dim, gc, dc): X = np.random.rand(6, 7, 8, 2).astype(np.float32) def ref_frontmax(X): return [np.max(X, axis=(tuple(range(num_reduce_dim))))] self.max_op_test( "ReduceFrontMax", num_reduce_dim, gc, dc, [X], ["X"], ref_frontmax) @given(**hu.gcs) def test_reduce_front_max_with_length(self, dc, gc): num_reduce_dim = 1 X = np.random.rand(2, 3, 4, 5).astype(np.float32) batch_size = int(np.prod([2, 3, 4, 5][num_reduce_dim:])) d = 120 // batch_size lengths = np.random.randint(1, d, size=batch_size).astype(np.int32) def ref_max(X, lengths): Y = X.reshape(d, lengths.size) rv = np.zeros((lengths.size, 1)).astype(np.float32) for ii in range(lengths.size): rv[ii] = np.max(Y[:lengths[ii], ii]) return [rv.reshape((2, 3, 4, 5)[num_reduce_dim:])] self.max_op_test( "ReduceFrontMax", num_reduce_dim, gc, dc, [X, lengths], ["X", "lengths"], ref_max) @given(num_reduce_dim=st.integers(0, 4), **hu.gcs) def test_reduce_back_max(self, num_reduce_dim, gc, dc): X = np.random.rand(6, 7, 8, 2).astype(np.float32) def ref_backmax(X): return [np.max(X, axis=(0, 1, 2, 3)[4 - num_reduce_dim:])] self.max_op_test( "ReduceBackMax", num_reduce_dim, gc, dc, [X], ["X"], ref_backmax) @given(**hu.gcs) def test_reduce_back_max_with_length(self, gc, dc): num_reduce_dim = 1 X = np.random.rand(2, 3, 4, 5).astype(np.float32) batch_size = int(np.prod([2, 3, 4, 5][:4 - num_reduce_dim])) d = 120 // batch_size lengths = np.random.randint(1, d, size=batch_size).astype(np.int32) def ref_max(X, lengths): Y = X.reshape(lengths.size, d) rv = np.zeros((lengths.size, 1)).astype(np.float32) for ii in range(lengths.size): rv[ii] = np.max(Y[ii, :lengths[ii]]) return [rv.reshape((2, 3, 4, 5)[:4 - num_reduce_dim])] self.max_op_test( "ReduceBackMax", num_reduce_dim, gc, dc, [X, lengths], ["X", "lengths"], ref_max) @given(**hu.gcs) def test_reduce_back_sum(self, dc, gc): num_reduce_dim = 1 X = np.random.rand(6, 7, 8, 2).astype(np.float32) def ref_sum(X): return [np.sum(X, axis=(0, 1, 2, 3)[4 - num_reduce_dim:])] self.reduce_op_test( "ReduceBackSum", ref_sum, [X], ["input"], num_reduce_dim, gc) self.grad_variant_input_test( "ReduceBackSumGradient", X, ref_sum, num_reduce_dim) @given(**hu.gcs) def test_reduce_back_sum_with_length(self, dc, gc): num_reduce_dim = 1 X = np.random.rand(2, 3, 4, 5).astype(np.float32) batch_size = int(np.prod([2, 3, 4, 5][:4 - num_reduce_dim])) d = 120 // batch_size lengths = np.random.randint(1, d, size=batch_size).astype(np.int32) def ref_sum(X, lengths): Y = X.reshape(lengths.size, d) rv = np.zeros((lengths.size, 1)).astype(np.float32) for ii in range(lengths.size): rv[ii] = np.sum(Y[ii, :lengths[ii]]) return [rv.reshape((2, 3, 4, 5)[:4 - num_reduce_dim])] self.reduce_op_test( "ReduceBackSum", ref_sum, [X, lengths], ["input", "lengths"], num_reduce_dim, gc) @given(num_reduce_dim=st.integers(0, 4), **hu.gcs) def test_reduce_back_mean(self, num_reduce_dim, dc, gc): X = np.random.rand(6, 7, 8, 2).astype(np.float32) def ref_mean(X): return [np.mean(X, axis=(0, 1, 2, 3)[4 - num_reduce_dim:])] self.reduce_op_test( "ReduceBackMean", ref_mean, [X], ["input"], num_reduce_dim, gc) self.grad_variant_input_test( "ReduceBackMeanGradient", X, ref_mean, num_reduce_dim) @given(**hu.gcs) def test_reduce_back_mean_with_length(self, dc, gc): num_reduce_dim = 1 X = np.random.rand(2, 3, 4, 5).astype(np.float32) batch_size = int(np.prod([2, 3, 4, 5][:4 - num_reduce_dim])) d = 120 // batch_size lengths = np.random.randint(1, d, size=batch_size).astype(np.int32) def ref_mean(X, lengths): Y = X.reshape(lengths.size, d) rv = np.zeros((lengths.size, 1)).astype(np.float32) for ii in range(lengths.size): rv[ii] = np.mean(Y[ii, :lengths[ii]]) return [rv.reshape((2, 3, 4, 5)[:4 - num_reduce_dim])] self.reduce_op_test( "ReduceBackMean", ref_mean, [X, lengths], ["input", "lengths"], num_reduce_dim, gc)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace import caffe2.python.hypothesis_test_util as hu import hypothesis from hypothesis import given import hypothesis.strategies as st import numpy as np import unittest class TestMomentumSGD(hu.HypothesisTestCase): @given(n=st.integers(4, 8), nesterov=st.booleans(), **hu.gcs) def test_momentum_sgd(self, n, nesterov, gc, dc): param = np.random.rand(n).astype(np.float32) grad = np.random.rand(n).astype(np.float32) lr = np.random.rand(1).astype(np.float32) param_momentum = np.random.rand(n).astype(np.float32) momentum = 0.9 def momentum_sgd(grad, param_momentum, lr, param=None): if not nesterov: adjusted_gradient = lr * grad + momentum * param_momentum if param is None: return [adjusted_gradient, adjusted_gradient] else: paramup = param - adjusted_gradient return [adjusted_gradient, adjusted_gradient, paramup] else: m_new = momentum * param_momentum + lr * grad grad_new = (1 + momentum) * m_new - momentum * param_momentum if param is None: return [grad_new, m_new] else: paramup = param - grad_new return [grad_new, m_new, paramup] op = core.CreateOperator( "MomentumSGDUpdate", ["grad", "param_momentum", "lr", "param"], ["grad", "param_momentum", "param"], momentum=momentum, nesterov=int(nesterov), ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[grad, param_momentum, lr, param], reference=momentum_sgd ) op_noparam = core.CreateOperator( "MomentumSGD", ["grad", "param_momentum", "lr"], ["grad", "param_momentum"], momentum=momentum, nesterov=int(nesterov), ) self.assertReferenceChecks( device_option=gc, op=op_noparam, inputs=[grad, param_momentum, lr], reference=momentum_sgd ) @given( inputs=hu.tensors(n=3), momentum=st.floats(min_value=0.1, max_value=0.9), nesterov=st.booleans(), lr=st.floats(min_value=0.1, max_value=0.9), data_strategy=st.data(), **hu.gcs ) def test_sparse_momentum_sgd( self, inputs, momentum, nesterov, lr, data_strategy, gc, dc ): w, grad, m = inputs # Create an indexing array containing values which index into grad indices = data_strategy.draw( hu.tensor( max_dim=1, min_value=1, max_value=grad.shape[0], dtype=np.int64, elements=st.sampled_from(np.arange(grad.shape[0])), ), ) # Verify that the generated indices are unique hypothesis.assume( np.array_equal( np.unique(indices.flatten()), np.sort(indices.flatten()))) # Sparsify grad grad = grad[indices] # Make momentum >= 0 m = np.abs(m) # Convert lr to a numpy array lr = np.asarray([lr], dtype=np.float32) op = core.CreateOperator( "SparseMomentumSGDUpdate", ["grad", "m", "lr", "param", "indices"], ["adjusted_grad", "m", "param"], momentum=momentum, nesterov=int(nesterov), device_option=gc ) # Reference def momentum_sgd(grad, m, lr): lr = lr[0] if not nesterov: adjusted_gradient = lr * grad + momentum * m return (adjusted_gradient, adjusted_gradient) else: m_new = momentum * m + lr * grad return ((1 + momentum) * m_new - momentum * m, m_new) def sparse(grad, m, lr, param, i): grad_new, m_new = momentum_sgd(grad, m[i], lr) m[i] = m_new param[i] -= grad_new return (grad_new, m, param) self.assertReferenceChecks( gc, op, [grad, m, lr, w, indices], sparse) @given(n=st.integers(4, 8), nesterov=st.booleans(), **hu.gcs_gpu_only) @unittest.skipIf(not workspace.has_gpu_support, "No gpu support.") def test_fp16momentum_sgd(self, n, nesterov, gc, dc): gpuvers = workspace.GetDeviceProperties(0)["major"] if gpuvers < 6: print("No FP16 support because major version {} < 6".format(gpuvers)) return param = np.random.rand(n).astype(np.float16) grad = np.random.rand(n).astype(np.float16) lr = np.random.rand(1).astype(np.float32) param_momentum = np.random.rand(n).astype(np.float16) momentum = 0.9 nesterov = True def momentum_sgd(grad, param_momentum, lr, param=None): if not nesterov: adjusted_gradient = lr * grad + momentum * param_momentum paramup = param - adjusted_gradient return [adjusted_gradient, adjusted_gradient, paramup] else: m_new = momentum * param_momentum + lr * grad grad_new = (1 + momentum) * m_new - momentum * param_momentum paramup = param - grad_new return [grad_new, m_new, paramup] op = core.CreateOperator( "FP16MomentumSGDUpdate", ["grad", "param_momentum", "lr", "param"], ["grad", "param_momentum", "param"], momentum=momentum, nesterov=int(nesterov), weight_decay=0.0, ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[grad, param_momentum, lr, param], reference=momentum_sgd ) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace, dyndep import caffe2.python.hypothesis_test_util as hu import numpy as np class TestPercentileOp(hu.HypothesisTestCase): def _test_percentile_op( self, original_inp, value_to_pct_map, dist_lengths, expected_values ): op = core.CreateOperator( 'Percentile', ['original_values', 'value_to_pct_map', 'dist_lengths'], ['percentile_values'] ) workspace.FeedBlob('original_values', np.array(original_inp, dtype=np.float32)) workspace.FeedBlob( 'value_to_pct_map', np.array(value_to_pct_map, dtype=np.float32)) workspace.FeedBlob('dist_lengths', np.array(dist_lengths, dtype=np.int32)) workspace.RunOperatorOnce(op) np.testing.assert_array_almost_equal( workspace.FetchBlob('percentile_values'), np.array(expected_values), decimal=5 ) def test_percentile_op_with_only_one_dist(self): self._test_percentile_op( original_inp=[[5]], value_to_pct_map=[[5, 0.4]], dist_lengths=[1], expected_values=[[0.4]] ) def test_percentile_op_with_all_elements_in_map(self): self._test_percentile_op( original_inp=[[3, 4], [10, 4]], value_to_pct_map=[[3, 0.3], [4, 0.6], [10, 0.8], [4, 0.5], [5, 0.6]], dist_lengths=[3, 2], expected_values=[[0.3, 0.5], [0.8, 0.5]], ) def test_percentile_op_with_same_value(self): self._test_percentile_op( original_inp=[[1, 1], [1, 2]], value_to_pct_map=[[1, 0.1], [4, 0.4], [2, 0.5]], dist_lengths=[2, 1], expected_values=[[0.1, 0.0], [0.1, 0.5]] ) def test_percentile_op_with_elements_bigger_than_map_range(self): self._test_percentile_op( original_inp=[[1, 5], [3, 4]], value_to_pct_map=[[1, 0.1], [4, 0.4], [2, 0.1], [3, 0.3]], dist_lengths=[2, 2], expected_values=[[0.1, 1.], [0.3, 1.0]] ) def test_percentile_op_with_elements_smaller_than_map_range(self): self._test_percentile_op( original_inp=[[1], [5], [6]], value_to_pct_map=[[2, 0.2], [5, 0.5], [7, 0.5]], dist_lengths=[3], expected_values=[[0.0], [0.5], [0.5]] ) def test_percentile_op_with_interpolation(self): self._test_percentile_op( original_inp=[[3, 2, 5], [6, 7, 8]], value_to_pct_map=[[1, 0.1], [4, 0.7], [4.5, 0.8], [6, 0.5], [8, 0.9], [8, 0.6]], dist_lengths=[3, 2, 1], expected_values=[[0.5, 0.0, 0.0], [1.0, 0.7, 0.6]] ) def test_percentile_op_with_large_sample_size_per_dist(self): self._test_percentile_op( original_inp=[[3, 1], [5, 7]], value_to_pct_map=[[3, 0.5], [4, 0.6], [5, 0.7], [1, 0.2], [2, 0.3], [5, 0.8]], dist_lengths=[3, 3], expected_values=[[0.5, 0.2], [0.7, 1.0]] ) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from hypothesis import given import hypothesis.strategies as st from caffe2.python import core import caffe2.python.hypothesis_test_util as hu class TestConditionalOp(hu.HypothesisTestCase): @given(rows_num=st.integers(1, 10000), **hu.gcs_cpu_only) def test_conditional(self, rows_num, gc, dc): op = core.CreateOperator( "Conditional", ["condition", "data_t", "data_f"], "output" ) data_t = np.random.random((rows_num, 10, 20)).astype(np.float32) data_f = np.random.random((rows_num, 10, 20)).astype(np.float32) condition = np.random.choice(a=[True, False], size=rows_num) def ref(condition, data_t, data_f): output = [ data_t[i] if condition[i] else data_f[i] for i in range(rows_num) ] return (output,) self.assertReferenceChecks(gc, op, [condition, data_t, data_f], ref)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from caffe2.python.core import CreatePythonOperator import caffe2.python.hypothesis_test_util as hu from hypothesis import given import hypothesis.strategies as st import numpy as np import unittest if workspace.is_asan: # Numba seems to be not compatible with ASAN (at least at Facebook) # so if we are in asan mode, we disable Numba which further disables # the numba python op test. HAS_NUMBA = False else: try: import numba HAS_NUMBA = True except ImportError: HAS_NUMBA = False class PythonOpTest(hu.HypothesisTestCase): @unittest.skipIf(not HAS_NUMBA, "") @given(x=hu.tensor(), n=st.integers(min_value=1, max_value=20), w=st.integers(min_value=1, max_value=20)) def test_multithreaded_evaluation_numba_nogil(self, x, n, w): @numba.jit(nopython=True, nogil=True) def g(input_, output): output[...] = input_ def f(inputs, outputs): outputs[0].reshape(inputs[0].shape) g(inputs[0].data, outputs[0].data) ops = [CreatePythonOperator(f, ["x"], [str(i)]) for i in range(n)] net = core.Net("net") net.Proto().op.extend(ops) net.Proto().type = "dag" net.Proto().num_workers = w iters = 100 plan = core.Plan("plan") plan.AddStep(core.ExecutionStep("test-step", net, iters)) workspace.FeedBlob("x", x) workspace.RunPlan(plan.Proto().SerializeToString()) for i in range(n): y = workspace.FetchBlob(str(i)) np.testing.assert_almost_equal(x, y) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import itertools import numpy as np import tempfile import unittest import os from caffe2.python import core, workspace import caffe2.python.hypothesis_test_util as hu class TestMap(hu.HypothesisTestCase): def test_create_map(self): dtypes = [core.DataType.INT32, core.DataType.INT64] for key_dtype, value_dtype in itertools.product(dtypes, dtypes): op = core.CreateOperator( 'CreateMap', [], ['map'], key_dtype=key_dtype, value_dtype=value_dtype, ) workspace.RunOperatorOnce(op) self.assertTrue(workspace.HasBlob('map')) def test_map(self): def test_map_func(KEY_T, VALUE_T): model_file = os.path.join(tempfile.mkdtemp(), 'db') key_data = np.asarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=KEY_T) value_data = np.asarray([2, 3, 3, 3, 3, 2, 3, 3, 3, 3], dtype=VALUE_T) workspace.FeedBlob("key_data", key_data) workspace.FeedBlob("value_data", value_data) save_net = core.Net("save_net") save_net.KeyValueToMap(["key_data", "value_data"], "map_data") save_net.Save( ["map_data"], [], db=model_file, db_type="minidb", absolute_path=True ) workspace.RunNetOnce(save_net) workspace.ResetWorkspace() load_net = core.Net("load_net") load_net.Load( [], ["map_data"], db=model_file, db_type="minidb", load_all=True, absolute_path=True ) load_net.MapToKeyValue("map_data", ["key_data", "value_data"]) workspace.RunNetOnce(load_net) key_data2 = workspace.FetchBlob("key_data") value_data2 = workspace.FetchBlob("value_data") assert(set(zip(key_data, value_data)) == set(zip(key_data2, value_data2))) test_map_func(np.int64, np.int64) test_map_func(np.int64, np.int32) test_map_func(np.int32, np.int32) test_map_func(np.int32, np.int64) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from caffe2.proto import caffe2_pb2 from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np def _one_hots(): index_size = st.integers(min_value=1, max_value=5) lengths = st.lists( elements=st.integers(min_value=0, max_value=5)) return st.tuples(index_size, lengths).flatmap( lambda x: st.tuples( st.just(x[0]), st.just(x[1]), st.lists( elements=st.integers(min_value=0, max_value=x[0] - 1), min_size=sum(x[1]), max_size=sum(x[1])))) class TestOneHotOps(hu.HypothesisTestCase): @given( x=hu.tensor( min_dim=2, max_dim=2, dtype=np.int32, elements=st.integers(min_value=0, max_value=10)), **hu.gcs_cpu_only) def test_batch_one_hot(self, x, gc, dc): d = x.shape[1] lens = [] vals = [] for i in range(0, d): val = np.unique(x[:, i]) vals.extend(val) lens.append(len(val)) lens = np.array(lens, dtype=np.int32) vals = np.array(vals, dtype=np.int32) def ref(x, lens, vals): output_dim = vals.size ret = np.zeros((x.shape[0], output_dim)).astype(x.dtype) p = 0 for i, l in enumerate(lens): for j in range(0, l): v = vals[p + j] ret[x[:, i] == v, p + j] = 1 p += lens[i] return (ret, ) op = core.CreateOperator('BatchOneHot', ["X", "LENS", "VALS"], ["Y"]) self.assertReferenceChecks(gc, op, [x, lens, vals], ref) @given( x=hu.tensor( min_dim=2, max_dim=2, dtype=np.float32, elements=st.floats(min_value=-5, max_value=5)), **hu.gcs_cpu_only) def test_batch_bucketized_one_hot(self, x, gc, dc): d = x.shape[1] lens = np.random.randint(low=1, high=5, size=d) boundaries = [] for i in range(d): cur_boundary = np.random.randn(lens[i]) * 5 cur_boundary.sort() boundaries += cur_boundary.tolist() lens = np.array(lens, dtype=np.int32) boundaries = np.array(boundaries, dtype=np.float32) def ref(x, lens, boundaries): output_dim = lens.size + boundaries.size ret = np.zeros((x.shape[0], output_dim)).astype(x.dtype) boundary_offset = 0 output_offset = 0 for i, l in enumerate(lens): bucket_idx = np.digitize( x[:, i], boundaries[boundary_offset:boundary_offset + l], right=True ) for j in range(x.shape[0]): ret[j, output_offset + bucket_idx[j]] = 1.0 boundary_offset += lens[i] output_offset += (lens[i] + 1) return (ret, ) op = core.CreateOperator('BatchBucketOneHot', ["X", "LENS", "BOUNDARIES"], ["Y"]) self.assertReferenceChecks(gc, op, [x, lens, boundaries], ref) @given( hot_indices=hu.tensor( min_dim=1, max_dim=1, dtype=np.int64, elements=st.integers(min_value=0, max_value=42)), end_padding=st.integers(min_value=0, max_value=2), **hu.gcs) def test_one_hot(self, hot_indices, end_padding, gc, dc): def one_hot_ref(hot_indices, size): out = np.zeros([len(hot_indices), size], dtype=float) x = enumerate(hot_indices) for i, x in enumerate(hot_indices): out[i, x] = 1. return (out, ) size = np.array(max(hot_indices) + end_padding + 1, dtype=np.int64) if size == 0: size = 1 op = core.CreateOperator('OneHot', ['hot_indices', 'size'], ['output']) self.assertReferenceChecks( gc, op, [hot_indices, size], one_hot_ref, input_device_options={'size': core.DeviceOption(caffe2_pb2.CPU)}) @given(hot_indices=_one_hots()) def test_segment_one_hot(self, hot_indices): index_size, lengths, indices = hot_indices index_size = np.array(index_size, dtype=np.int64) lengths = np.array(lengths, dtype=np.int32) indices = np.array(indices, dtype=np.int64) def segment_one_hot_ref(lengths, hot_indices, size): offset = 0 out = np.zeros([len(lengths), size], dtype=float) for i, length in enumerate(lengths): for idx in hot_indices[offset:offset + length]: out[i, idx] = 1. offset += length return (out, ) op = core.CreateOperator( 'SegmentOneHot', ['lengths', 'hot_indices', 'size'], ['output']) self.assertReferenceChecks( hu.cpu_do, op, [lengths, indices, index_size], segment_one_hot_ref) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np import math MAX_TEST_EMBEDDING_SIZE = 20 MAX_TEST_SEQUENCE_LENGTH = 10 MAX_TEST_BATCH_SIZE = 5 MIN_TEST_ALPHA = 5000.0 MAX_TEST_ALPHA = 20000.0 MIN_TEST_AMPLITUDE = 0.1 MAX_TEST_AMPLITUDE = 10.0 class TestSinusoidPositionEncodingOp(hu.HypothesisTestCase): @given( positions_vec=hu.arrays( dims=[MAX_TEST_SEQUENCE_LENGTH], dtype=np.int32, elements=st.integers(1, MAX_TEST_SEQUENCE_LENGTH) ), embedding_size=st.integers(1, MAX_TEST_EMBEDDING_SIZE), batch_size=st.integers(1, MAX_TEST_BATCH_SIZE), alpha=st.floats(MIN_TEST_ALPHA, MAX_TEST_ALPHA), amplitude=st.floats(MIN_TEST_AMPLITUDE, MAX_TEST_AMPLITUDE), **hu.gcs_cpu_only ) def test_sinusoid_embedding( self, positions_vec, embedding_size, batch_size, alpha, amplitude, gc, dc ): positions = np.tile(positions_vec, [batch_size, 1]).transpose() op = core.CreateOperator( "SinusoidPositionEncoding", ["positions"], ["output"], embedding_size=embedding_size, alpha=alpha, amplitude=amplitude, ) def sinusoid_encoding(dim, position): x = 1. * position / math.pow(alpha, 1. * dim / embedding_size) if dim % 2 == 0: return amplitude * math.sin(x) else: return amplitude * math.cos(x) def sinusoid_embedding_op(positions): output_shape = (len(positions), len(positions[0]), embedding_size) ar = np.zeros(output_shape) for i, position_vector in enumerate(positions): for j, position in enumerate(position_vector): for k in range(embedding_size): ar[i, j, k] = sinusoid_encoding(k, position) return [ar] self.assertReferenceChecks( device_option=gc, op=op, inputs=[positions], reference=sinusoid_embedding_op, )
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace import caffe2.python.hypothesis_test_util as hu from hypothesis import given from hypothesis import strategies as st import numpy as np import time class TestTensorPackOps(hu.HypothesisTestCase): def pack_segments_ref(self, return_presence_mask=False): def pack_segments_ref(lengths, data): arr = [] constant_values = 0 if data.dtype.char == 'S': constant_values = '' for idx in range(np.size(lengths)): chunk = data[np.sum(lengths[:idx]):np.sum(lengths[:idx + 1])] pad_length = np.max(lengths) - lengths[idx] # ((0, pad_length), (0, 0)) says add pad_length rows of padding # below chunk and 0 rows of padding elsewhere arr.append( np.pad( chunk, ((0, pad_length), (0, 0)), mode=str("constant"), constant_values=constant_values ) ) result = [arr] if return_presence_mask: presence_arr = [] for length in lengths: pad_length = np.max(lengths) - length presence_arr.append( np.pad( np.ones((length), dtype=np.bool), ((0, pad_length)), mode=str("constant") ) ) result.append(presence_arr) return result return pack_segments_ref @given( num_seq=st.integers(10, 500), cell_size=st.integers(1, 10), **hu.gcs ) def test_pack_ops(self, num_seq, cell_size, gc, dc): # create data lengths = np.arange(num_seq, dtype=np.int32) + 1 num_cell = np.sum(lengths) data = np.zeros(num_cell * cell_size, dtype=np.float32) left = np.cumsum(np.arange(num_seq) * cell_size) right = np.cumsum(lengths * cell_size) for i in range(num_seq): data[left[i]:right[i]] = i + 1.0 data.resize(num_cell, cell_size) print("\nnum seq:{}, num cell: {}, cell size:{}\n".format( num_seq, num_cell, cell_size) + "=" * 60 ) # run test op = core.CreateOperator( 'PackSegments', ['l', 'd'], ['t']) workspace.FeedBlob('l', lengths) workspace.FeedBlob('d', data) start = time.time() self.assertReferenceChecks( device_option=gc, op=op, inputs=[lengths, data], reference=self.pack_segments_ref(), ) end = time.time() print("{} used time: {}".format(gc, end - start).replace('\n', ' ')) with core.DeviceScope(gc): workspace.FeedBlob('l', lengths) workspace.FeedBlob('d', data) workspace.RunOperatorOnce(core.CreateOperator( 'PackSegments', ['l', 'd'], ['t'], device_option=gc)) workspace.RunOperatorOnce(core.CreateOperator( 'UnpackSegments', ['l', 't'], ['newd'], device_option=gc)) assert((workspace.FetchBlob('newd') == workspace.FetchBlob('d')).all()) @given( **hu.gcs_cpu_only ) def test_pack_ops_str(self, gc, dc): # GPU does not support string. Test CPU implementation only. workspace.FeedBlob('l', np.array([1, 2, 3], dtype=np.int64)) strs = np.array([ ["a", "a"], ["b", "b"], ["bb", "bb"], ["c", "c"], ["cc", "cc"], ["ccc", "ccc"]], dtype='|S') workspace.FeedBlob('d', strs) workspace.RunOperatorOnce(core.CreateOperator( 'PackSegments', ['l', 'd'], ['t'], device_option=gc)) workspace.RunOperatorOnce(core.CreateOperator( 'UnpackSegments', ['l', 't'], ['newd'], device_option=gc)) assert((workspace.FetchBlob('newd') == workspace.FetchBlob('d')).all()) def test_pad_minf(self): workspace.FeedBlob('l', np.array([1, 2, 3], dtype=np.int32)) workspace.FeedBlob( 'd', np.array([ [1.0, 1.1], [2.0, 2.1], [2.2, 2.2], [3.0, 3.1], [3.2, 3.3], [3.4, 3.5]], dtype=np.float32)) workspace.RunOperatorOnce(core.CreateOperator( 'PackSegments', ['l', 'd'], ['t'], pad_minf=True)) workspace.RunOperatorOnce(core.CreateOperator( 'Exp', ['t'], ['r'] )) result = workspace.FetchBlob('t') assert(result[0, -1, 0] < -1000.0) # The whole point of padding with -inf is that when we exponentiate it # then it should be zero. exponentiated = workspace.FetchBlob('r') assert(exponentiated[0, -1, 0] == 0.0) @given(**hu.gcs_cpu_only) def test_presence_mask(self, gc, dc): lengths = np.array([1, 2, 3], dtype=np.int32) data = np.array( [ [1.0, 1.0], [2.0, 2.0], [2.0, 2.0], [3.0, 3.0], [3.0, 3.0], [3.0, 3.0] ], dtype=np.float32 ) op = core.CreateOperator( 'PackSegments', ['l', 'd'], ['t', 'p'], return_presence_mask=True ) workspace.FeedBlob('l', lengths) workspace.FeedBlob('d', data) inputs = [lengths, data] self.assertReferenceChecks( device_option=gc, op=op, inputs=inputs, reference=self.pack_segments_ref(return_presence_mask=True), ) op = core.CreateOperator( 'PackSegments', ['l', 'd'], ['t', 'p'], return_presence_mask=True ) workspace.RunOperatorOnce(op) output = workspace.FetchBlob('t') expected_output_shape = (3, 3, 2) self.assertEquals(output.shape, expected_output_shape) presence_mask = workspace.FetchBlob('p') expected_presence_mask = np.array( [[True, False, False], [True, True, False], [True, True, True]], dtype=np.bool ) self.assertEqual(presence_mask.shape, expected_presence_mask.shape) np.testing.assert_array_equal(presence_mask, expected_presence_mask) def test_presence_mask_empty(self): lengths = np.array([], dtype=np.int32) data = np.array([], dtype=np.float32) op = core.CreateOperator( 'PackSegments', ['l', 'd'], ['t', 'p'], return_presence_mask=True ) workspace.FeedBlob('l', lengths) workspace.FeedBlob('d', data) workspace.RunOperatorOnce(op) output = workspace.FetchBlob('p') expected_output_shape = (0, 0) self.assertEquals(output.shape, expected_output_shape) @given(**hu.gcs_cpu_only) def test_out_of_bounds(self, gc, dc): # Copy pasted from test_pack_ops but with 3 changed to 4 lengths = np.array([1, 2, 4], dtype=np.int32) data = np.array([ [1.0, 1.0], [2.0, 2.0], [2.0, 2.0], [3.0, 3.0], [3.0, 3.0], [3.0, 3.0]], dtype=np.float32) op = core.CreateOperator( 'PackSegments', ['l', 'd'], ['t']) inputs = [lengths, data] self.assertRunOpRaises( device_option=gc, op=op, inputs=inputs, exception=RuntimeError ) @given(**hu.gcs_cpu_only) def test_under_bounds(self, gc, dc): # Copy pasted from test_pack_ops but with 3 changed to 2 lengths = np.array([1, 2, 2], dtype=np.int32) data = np.array([ [1.0, 1.0], [2.0, 2.0], [2.0, 2.0], [3.0, 3.0], [3.0, 3.0], [3.0, 3.0]], dtype=np.float32) op = core.CreateOperator( 'PackSegments', ['l', 'd'], ['t']) inputs = [lengths, data] self.assertRunOpRaises( device_option=gc, op=op, inputs=inputs, exception=RuntimeError ) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.proto import caffe2_pb2 from caffe2.python import core from hypothesis import assume, given, settings import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class TestFcOperator(hu.HypothesisTestCase): def _run_test(self, n, m, k, transposed, multi_dim, dtype, engine, gc, dc): if dtype == np.float16: # fp16 only supported with CUDA assume(gc.device_type == caffe2_pb2.CUDA) dc = [d for d in dc if d.device_type == caffe2_pb2.CUDA] if engine == 'TENSORCORE': # TensorCore only makes sense with CUDA assume(gc.device_type == caffe2_pb2.CUDA) # ensures TensorCore kernels can be called m *= 8 k *= 8 n *= 8 X = np.random.rand(m, k).astype(dtype) - 0.5 if multi_dim: if transposed: W = np.random.rand(k, n, 1, 1).astype(dtype) - 0.5 else: W = np.random.rand(n, k, 1, 1).astype(dtype) - 0.5 else: if transposed: W = np.random.rand(k, n).astype(dtype) - 0.5 else: W = np.random.rand(n, k).astype(dtype) - 0.5 b = np.random.rand(n).astype(dtype) - 0.5 def fc_op(X, W, b): return [np.dot(X, W.reshape(n, k).transpose()) + b.reshape(n)] def fc_tranposed_op(X, W, b): return [np.dot(X, W.reshape(k, n)) + b.reshape(n)] op = core.CreateOperator( 'FCTransposed' if transposed else 'FC', ['X', 'W', 'b'], 'out', engine=engine, ) if dtype == np.float16 and gc.device_type == caffe2_pb2.CUDA: a = caffe2_pb2.Argument() a.i = 1 a.name = "float16_compute" op.arg.extend([a]) # Check against numpy reference self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, W, b], reference=fc_tranposed_op if transposed else fc_op, ) # Check over multiple devices self.assertDeviceChecks(dc, op, [X, W, b], [0]) # Gradient checks threshold = 0.5 if dtype == np.float16 else 0.005 stepsize = 0.5 if dtype == np.float16 else 0.05 for i in range(3): self.assertGradientChecks(gc, op, [X, W, b], i, [0], threshold=threshold, stepsize=stepsize) @settings(max_examples=50) @given(n=st.integers(1, 5), m=st.integers(0, 5), k=st.integers(1, 5), multi_dim=st.sampled_from([True, False]), dtype=st.sampled_from([np.float32, np.float16]), engine=st.sampled_from(['', 'TENSORCORE']), **hu.gcs) def test_fc(self, **kwargs): self._run_test(transposed=False, **kwargs) @settings(max_examples=50) @given(n=st.integers(1, 5), m=st.integers(0, 5), k=st.integers(1, 5), multi_dim=st.sampled_from([True, False]), dtype=st.sampled_from([np.float32, np.float16]), engine=st.sampled_from(['', 'TENSORCORE']), **hu.gcs) def test_fc_transposed(self, **kwargs): self._run_test(transposed=True, **kwargs) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from hypothesis import assume, given import hypothesis.strategies as st import numpy as np from caffe2.proto import caffe2_pb2 from caffe2.python import core import caffe2.python.hypothesis_test_util as hu class TestDropout(hu.HypothesisTestCase): @given(X=hu.tensor(), in_place=st.booleans(), ratio=st.floats(0, 0.999), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_dropout_is_test(self, X, in_place, ratio, engine, gc, dc): """Test with is_test=True for a deterministic reference impl.""" # TODO(lukeyeager): enable this path when the GPU path is fixed if in_place: # Skip if trying in-place on GPU assume(not (gc.device_type == caffe2_pb2.CUDA and engine == '')) # If in-place on CPU, don't compare with GPU dc = dc[:1] op = core.CreateOperator("Dropout", ["X"], ["X" if in_place else "Y"], ratio=ratio, engine=engine, is_test=True) self.assertDeviceChecks(dc, op, [X], [0]) # No sense in checking gradients for test phase def reference_dropout_test(x): return x, np.ones(x.shape, dtype=np.bool) self.assertReferenceChecks( gc, op, [X], reference_dropout_test, # The 'mask' output may be uninitialized outputs_to_check=[0]) @given(X=hu.tensor(), in_place=st.booleans(), output_mask=st.booleans(), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_dropout_ratio0(self, X, in_place, output_mask, engine, gc, dc): """Test with ratio=0 for a deterministic reference impl.""" # TODO(lukeyeager): enable this path when the op is fixed if in_place: # Skip if trying in-place on GPU assume(gc.device_type != caffe2_pb2.CUDA) # If in-place on CPU, don't compare with GPU dc = dc[:1] is_test = not output_mask op = core.CreateOperator("Dropout", ["X"], ["X" if in_place else "Y"] + (["mask"] if output_mask else []), ratio=0.0, engine=engine, is_test=is_test) self.assertDeviceChecks(dc, op, [X], [0]) if not is_test: self.assertGradientChecks(gc, op, [X], 0, [0]) def reference_dropout_ratio0(x): return (x,) if is_test else (x, np.ones(x.shape, dtype=np.bool)) self.assertReferenceChecks( gc, op, [X], reference_dropout_ratio0, # Don't check the mask with cuDNN because it's packed data outputs_to_check=None if engine != 'CUDNN' else [0])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import hypothesis.strategies as st import numpy as np import random from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu class TestTopK(hu.HypothesisTestCase): def top_k_ref(self, X, k, flatten_indices, axis=-1): in_dims = X.shape out_dims = list(in_dims) out_dims[axis] = k out_dims = tuple(out_dims) if axis == -1: axis = len(in_dims) - 1 prev_dims = 1 next_dims = 1 for i in range(axis): prev_dims *= in_dims[i] for i in range(axis + 1, len(in_dims)): next_dims *= in_dims[i] n = in_dims[axis] X_flat = X.reshape((prev_dims, n, next_dims)) values_ref = np.ndarray( shape=(prev_dims, k, next_dims), dtype=np.float32) indices_ref = np.ndarray( shape=(prev_dims, k, next_dims), dtype=np.int64) flatten_indices_ref = np.ndarray( shape=(prev_dims, k, next_dims), dtype=np.int64) for i in range(prev_dims): for j in range(next_dims): kv = [] for x in range(n): val = X_flat[i, x, j] y = x * next_dims + i * in_dims[axis] * next_dims + j kv.append((val, x, y)) cnt = 0 for val, x, y in sorted( kv, key=lambda x: (x[0], -x[1]), reverse=True): values_ref[i, cnt, j] = val indices_ref[i, cnt, j] = x flatten_indices_ref[i, cnt, j] = y cnt += 1 if cnt >= k: break values_ref = values_ref.reshape(out_dims) indices_ref = indices_ref.reshape(out_dims) flatten_indices_ref = flatten_indices_ref.flatten() if flatten_indices: return (values_ref, indices_ref, flatten_indices_ref) else: return (values_ref, indices_ref) @given(X=hu.tensor(), flatten_indices=st.booleans(), **hu.gcs) def test_top_k(self, X, flatten_indices, gc, dc): X = X.astype(dtype=np.float32) k = random.randint(1, X.shape[-1]) output_list = ["Values", "Indices"] if flatten_indices: output_list.append("FlattenIndices") op = core.CreateOperator("TopK", ["X"], output_list, k=k, device_option=gc) def bind_ref(X_loc): return self.top_k_ref(X_loc, k, flatten_indices) self.assertReferenceChecks(gc, op, [X], bind_ref) self.assertDeviceChecks(dc, op, [X], [0]) @given(bs=st.integers(1, 3), n=st.integers(1, 1), k=st.integers(1, 1), flatten_indices=st.booleans(), **hu.gcs) def test_top_k_1(self, bs, n, k, flatten_indices, gc, dc): X = np.random.rand(bs, n).astype(dtype=np.float32) output_list = ["Values", "Indices"] if flatten_indices: output_list.append("FlattenIndices") op = core.CreateOperator("TopK", ["X"], output_list, k=k, device_option=gc) def bind_ref(X_loc): return self.top_k_ref(X_loc, k, flatten_indices) self.assertReferenceChecks(gc, op, [X], bind_ref) self.assertDeviceChecks(dc, op, [X], [0]) @given(bs=st.integers(1, 3), n=st.integers(1, 10000), k=st.integers(1, 1), flatten_indices=st.booleans(), **hu.gcs) def test_top_k_2(self, bs, n, k, flatten_indices, gc, dc): X = np.random.rand(bs, n).astype(dtype=np.float32) output_list = ["Values", "Indices"] if flatten_indices: output_list.append("FlattenIndices") op = core.CreateOperator("TopK", ["X"], output_list, k=k, device_option=gc) def bind_ref(X_loc): return self.top_k_ref(X_loc, k, flatten_indices) self.assertReferenceChecks(gc, op, [X], bind_ref) self.assertDeviceChecks(dc, op, [X], [0]) @given(bs=st.integers(1, 3), n=st.integers(1, 10000), k=st.integers(1, 1024), flatten_indices=st.booleans(), **hu.gcs) def test_top_k_3(self, bs, n, k, flatten_indices, gc, dc): X = np.random.rand(bs, n).astype(dtype=np.float32) k = min(k, n) output_list = ["Values", "Indices"] if flatten_indices: output_list.append("FlattenIndices") op = core.CreateOperator("TopK", ["X"], output_list, k=k, device_option=gc) def bind_ref(X_loc): return self.top_k_ref(X_loc, k, flatten_indices) self.assertReferenceChecks(gc, op, [X], bind_ref) self.assertDeviceChecks(dc, op, [X], [0]) @given(bs=st.integers(1, 3), n=st.integers(100, 10000), flatten_indices=st.booleans(), **hu.gcs) def test_top_k_4(self, bs, n, flatten_indices, gc, dc): k = np.random.randint(n // 3, 3 * n // 4) X = np.random.rand(bs, n).astype(dtype=np.float32) output_list = ["Values", "Indices"] if flatten_indices: output_list.append("FlattenIndices") op = core.CreateOperator("TopK", ["X"], output_list, k=k, device_option=gc) def bind_ref(X_loc): return self.top_k_ref(X_loc, k, flatten_indices) self.assertReferenceChecks(gc, op, [X], bind_ref) self.assertDeviceChecks(dc, op, [X], [0]) @given(bs=st.integers(1, 3), n=st.integers(1, 1024), flatten_indices=st.booleans(), **hu.gcs) def test_top_k_5(self, bs, n, flatten_indices, gc, dc): k = n X = np.random.rand(bs, n).astype(dtype=np.float32) output_list = ["Values", "Indices"] if flatten_indices: output_list.append("FlattenIndices") op = core.CreateOperator("TopK", ["X"], output_list, k=k, device_option=gc) def bind_ref(X_loc): return self.top_k_ref(X_loc, k, flatten_indices) self.assertReferenceChecks(gc, op, [X], bind_ref) self.assertDeviceChecks(dc, op, [X], [0]) @given(bs=st.integers(1, 3), n=st.integers(1, 5000), flatten_indices=st.booleans(), **hu.gcs) def test_top_k_6(self, bs, n, flatten_indices, gc, dc): k = n X = np.random.rand(bs, n).astype(dtype=np.float32) output_list = ["Values", "Indices"] if flatten_indices: output_list.append("FlattenIndices") op = core.CreateOperator("TopK", ["X"], output_list, k=k, device_option=gc) def bind_ref(X_loc): return self.top_k_ref(X_loc, k, flatten_indices) self.assertReferenceChecks(gc, op, [X], bind_ref) self.assertDeviceChecks(dc, op, [X], [0]) @given(X=hu.tensor(dtype=np.float32), k=st.integers(1, 5), axis=st.integers(-1, 5), flatten_indices=st.booleans(), **hu.gcs) def test_top_k_axis(self, X, k, axis, flatten_indices, gc, dc): dims = X.shape if axis >= len(dims): axis %= len(dims) if k > dims[axis]: k = (k - 1) % dims[axis] + 1 output_list = ["Values", "Indices"] if flatten_indices: output_list.append("FlattenIndices") op = core.CreateOperator( "TopK", ["X"], output_list, k=k, axis=axis, device_option=gc) def bind_ref(X_loc): return self.top_k_ref(X_loc, k, flatten_indices, axis) self.assertReferenceChecks(gc, op, [X], bind_ref) self.assertDeviceChecks(dc, op, [X], [0]) @given(X=hu.tensor(dtype=np.float32), k=st.integers(1, 5), axis=st.integers(-1, 5), **hu.gcs) def test_top_k_grad(self, X, k, axis, gc, dc): dims = X.shape if axis >= len(dims): axis %= len(dims) if k > dims[axis]: k = (k - 1) % dims[axis] + 1 # this try to make sure adding stepsize (0.05) # will not change TopK selections at all # since dims max_value = 5 as defined in # caffe2/caffe2/python/hypothesis_test_util.py input_axis = len(dims) - 1 if axis == -1 else axis prev_dims = 1 next_dims = 1 for i in range(input_axis): prev_dims *= dims[i] for i in range(input_axis + 1, len(dims)): next_dims *= dims[i] X_flat = X.reshape((prev_dims, dims[input_axis], next_dims)) for i in range(prev_dims): for j in range(next_dims): X_flat[i, :, j] = np.arange( dims[axis], dtype=np.float32) / np.float32(dims[axis]) np.random.shuffle(X_flat[i, :, j]) X = X_flat.reshape(dims) op = core.CreateOperator( "TopK", ["X"], ["Values", "Indices"], k=k, axis=axis, device_option=gc) self.assertGradientChecks(gc, op, [X], 0, [0])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from caffe2.python.text_file_reader import TextFileReader from caffe2.python.test_util import TestCase from caffe2.python.schema import Struct, Scalar, FetchRecord import tempfile import numpy as np class TestTextFileReader(TestCase): def test_text_file_reader(self): schema = Struct( ('field1', Scalar(dtype=str)), ('field2', Scalar(dtype=str)), ('field3', Scalar(dtype=np.float32))) num_fields = 3 col_data = [ ['l1f1', 'l2f1', 'l3f1', 'l4f1'], ['l1f2', 'l2f2', 'l3f2', 'l4f2'], [0.456, 0.789, 0.10101, -24342.64], ] row_data = list(zip(*col_data)) with tempfile.NamedTemporaryFile(mode='w+', delete=False) as txt_file: txt_file.write( '\n'.join( '\t'.join(str(x) for x in f) for f in row_data ) + '\n' ) txt_file.flush() for num_passes in range(1, 3): for batch_size in range(1, len(row_data) + 2): init_net = core.Net('init_net') reader = TextFileReader( init_net, filename=txt_file.name, schema=schema, batch_size=batch_size, num_passes=num_passes) workspace.RunNetOnce(init_net) net = core.Net('read_net') should_stop, record = reader.read_record(net) results = [np.array([])] * num_fields while True: workspace.RunNetOnce(net) arrays = FetchRecord(record).field_blobs() for i in range(num_fields): results[i] = np.append(results[i], arrays[i]) if workspace.FetchBlob(should_stop): break for i in range(num_fields): col_batch = np.tile(col_data[i], num_passes) if col_batch.dtype in (np.float32, np.float64): np.testing.assert_array_almost_equal( col_batch, results[i], decimal=3) else: np.testing.assert_array_equal(col_batch, results[i]) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import hypothesis.strategies as st import caffe2.python.hypothesis_test_util as hu import numpy as np import unittest class TestFloor(hu.HypothesisTestCase): @given(X=hu.tensor(), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_floor(self, X, gc, dc, engine): op = core.CreateOperator("Floor", ["X"], ["Y"], engine=engine) def floor_ref(X): return (np.floor(X),) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X], reference=floor_ref) # Check over multiple devices self.assertDeviceChecks(dc, op, [X], [0]) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import assume, given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class TestReduceFrontSum(hu.HypothesisTestCase): @given(batch_size=st.integers(1, 3), stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), dilation=st.integers(1, 3), size=st.integers(7, 10), channels=st.integers(1, 8), **hu.gcs) def test_im2col_layout(self, batch_size, stride, pad, kernel, dilation, size, channels, gc, dc): dkernel = (dilation * (kernel - 1) + 1) assume(size >= dkernel) NCHW_TO_NHWC = (0, 2, 3, 1) NHWC_TO_NCHW = (0, 3, 1, 2) COL_NHWC_TO_NCHW = (4, 2, 3, 0, 1) N = batch_size C = channels H = size W = size out_h = int((H + (2 * pad) - dkernel) / stride + 1) out_w = int((W + (2 * pad) - dkernel) / stride + 1) im_nchw = np.random.rand(N, C, H, W).astype(np.float32) - 0.5 im_nhwc = im_nchw.transpose(NCHW_TO_NHWC) op_im2col_nchw = core.CreateOperator( "Im2Col", ["im_nchw"], ["col_nchw"], stride=stride, kernel=kernel, dilation=dilation, pad=pad, order="NCHW", device_option=gc) op_im2col_nhwc = core.CreateOperator( "Im2Col", ["im_nhwc"], ["col_nhwc"], stride=stride, kernel=kernel, dilation=dilation, pad=pad, order="NHWC", device_option=gc) self.ws.create_blob("im_nchw").feed(im_nchw, device_option=gc) self.ws.create_blob("im_nhwc").feed(im_nhwc, device_option=gc) self.ws.run(op_im2col_nchw) self.ws.run(op_im2col_nhwc) # there is probably a clever way to spell this in np col_nchw = self.ws.blobs["col_nchw"].fetch() col_nhwc = self.ws.blobs["col_nhwc"].fetch() col_nchw_ = col_nchw.reshape(N, C, kernel, kernel, out_h, out_w) col_nhwc_ = col_nhwc.reshape(N, out_h, out_w, kernel, kernel, C) for i in range(0, N): np.testing.assert_allclose( col_nchw_[i], col_nhwc_[i].transpose(COL_NHWC_TO_NCHW), atol=1e-4, rtol=1e-4) op_col2im_nchw = core.CreateOperator( "Col2Im", ["col_nchw", "im_nchw"], ["out_nchw"], stride=stride, kernel=kernel, dilation=dilation, pad=pad, order="NCHW", device_option=gc) op_col2im_nhwc = core.CreateOperator( "Col2Im", ["col_nhwc", "im_nhwc"], ["out_nhwc"], stride=stride, kernel=kernel, dilation=dilation, pad=pad, order="NHWC", device_option=gc) self.ws.run(op_col2im_nchw) self.ws.run(op_col2im_nhwc) out_nchw = self.ws.blobs["out_nchw"].fetch() out_nhwc = self.ws.blobs["out_nhwc"].fetch() np.testing.assert_allclose( out_nchw, out_nhwc.transpose(NHWC_TO_NCHW), atol=1e-4, rtol=1e-4) @given(batch_size=st.integers(1, 3), stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), dilation=st.integers(1, 3), size=st.integers(7, 10), channels=st.integers(1, 8), order=st.sampled_from(["NCHW"]), **hu.gcs) def test_col2im_gradients(self, batch_size, stride, pad, kernel, dilation, size, channels, order, gc, dc): assume(size >= dilation * (kernel - 1) + 1) op = core.CreateOperator( "Im2Col", ["X"], ["Y"], stride=stride, kernel=kernel, dilation=dilation, pad=pad, order=order, device_option=gc) X = np.random.rand(batch_size, channels, size, size).astype(np.float32) self.assertGradientChecks(gc, op, [X], 0, [0]) return
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from caffe2.python.test_util import TestCase import numpy as np class TestCounterOps(TestCase): def test_stats_ops(self): # The global StatRegistry isn't reset when the workspace is reset, # so there may be existing stats from a previous test workspace.RunOperatorOnce(core.CreateOperator( 'StatRegistryExport', [], ['prev_k', 'prev_v', 'prev_ts'])) previous_keys = workspace.FetchBlob('prev_k') existing = len(previous_keys) prefix = '/'.join([__name__, 'TestCounterOps', 'test_stats_ops']) keys = [ (prefix + '/key1').encode('ascii'), (prefix + '/key2').encode('ascii') ] values = [34, 45] workspace.FeedBlob('k', np.array(keys, dtype=str)) workspace.FeedBlob('v', np.array(values, dtype=np.int64)) for _ in range(2): workspace.RunOperatorOnce(core.CreateOperator( 'StatRegistryUpdate', ['k', 'v'], [])) workspace.RunOperatorOnce(core.CreateOperator( 'StatRegistryExport', [], ['k2', 'v2', 't2'])) workspace.RunOperatorOnce(core.CreateOperator( 'StatRegistryCreate', [], ['reg'])) workspace.RunOperatorOnce(core.CreateOperator( 'StatRegistryUpdate', ['k2', 'v2', 'reg'], [])) workspace.RunOperatorOnce(core.CreateOperator( 'StatRegistryExport', ['reg'], ['k3', 'v3', 't3'])) k3 = workspace.FetchBlob('k3') v3 = workspace.FetchBlob('v3') t3 = workspace.FetchBlob('t3') self.assertEqual(len(k3) - existing, 2) self.assertEqual(len(v3), len(k3)) self.assertEqual(len(t3), len(k3)) for key in keys: self.assertIn(key, k3)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import numpy as np import caffe2.proto.caffe2_pb2 as caffe2_pb2 from caffe2.python import core, workspace, timeout_guard class BlobsQueueDBTest(unittest.TestCase): def test_create_blobs_queue_db_string(self): def add_blobs(queue, num_samples): blob = core.BlobReference("blob") status = core.BlobReference("blob_status") for i in range(num_samples): self._add_blob_to_queue( queue, self._create_test_tensor_protos(i), blob, status ) self._test_create_blobs_queue_db(add_blobs) def test_create_blobs_queue_db_tensor(self): def add_blobs(queue, num_samples): blob = core.BlobReference("blob") status = core.BlobReference("blob_status") for i in range(num_samples): data = self._create_test_tensor_protos(i) data = np.array([data], dtype=str) self._add_blob_to_queue( queue, data, blob, status ) self._test_create_blobs_queue_db(add_blobs) def _test_create_blobs_queue_db(self, add_blobs_fun): num_samples = 10000 batch_size = 10 init_net = core.Net('init_net') net = core.Net('test_create_blobs_queue_db') queue = init_net.CreateBlobsQueue([], 'queue', capacity=num_samples) reader = init_net.CreateBlobsQueueDB( [queue], 'blobs_queue_db_reader', value_blob_index=0, timeout_secs=0.1, ) workspace.RunNetOnce(init_net) add_blobs_fun(queue, num_samples) net.TensorProtosDBInput( [reader], ['image', 'label'], batch_size=batch_size) workspace.CreateNet(net) close_net = core.Net('close_net') close_net.CloseBlobsQueue([queue], []) for i in range(int(num_samples / batch_size)): print("Running net, iteration {}".format(i)) with timeout_guard.CompleteInTimeOrDie(2.0): workspace.RunNet(net) images = workspace.FetchBlob('image') labels = workspace.FetchBlob('label') self.assertEqual(batch_size, len(images)) self.assertEqual(batch_size, len(labels)) for idx, item in enumerate(images): self.assertEqual( "foo{}".format(i * batch_size + idx).encode('utf-8'), item ) for item in labels: self.assertEqual(1, item) workspace.RunNetOnce(close_net) def _add_blob_to_queue(self, queue, data, blob, status): workspace.FeedBlob(blob, data) op = core.CreateOperator( "SafeEnqueueBlobs", [queue, blob], [blob, status], ) workspace.RunOperatorOnce(op) def _create_test_tensor_protos(self, idx): item = caffe2_pb2.TensorProtos() data = item.protos.add() data.data_type = core.DataType.STRING data.string_data.append("foo{}".format(idx).encode('utf-8')) label = item.protos.add() label.data_type = core.DataType.INT32 label.int32_data.append(1) return item.SerializeToString()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import errno import hypothesis.strategies as st from hypothesis import given import numpy as np import os import shutil import tempfile import unittest from caffe2.proto import caffe2_pb2 from caffe2.python import core, test_util, workspace if workspace.has_gpu_support: DEVICES = [caffe2_pb2.CPU, caffe2_pb2.CUDA] max_gpuid = workspace.NumCudaDevices() - 1 else: DEVICES = [caffe2_pb2.CPU] max_gpuid = 0 # Utility class for other loading tests, don't add test functions here # Inherit from this test instead. If you add a test here, # each derived class will inherit it as well and cause test duplication class TestLoadSaveBase(test_util.TestCase): def __init__(self, methodName, db_type='minidb'): super(TestLoadSaveBase, self).__init__(methodName) self._db_type = db_type @given(src_device_type=st.sampled_from(DEVICES), src_gpu_id=st.integers(min_value=0, max_value=max_gpuid), dst_device_type=st.sampled_from(DEVICES), dst_gpu_id=st.integers(min_value=0, max_value=max_gpuid)) def load_save(self, src_device_type, src_gpu_id, dst_device_type, dst_gpu_id): workspace.ResetWorkspace() dtypes = [np.float16, np.float32, np.float64, np.bool, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16] arrays = [np.random.permutation(6).reshape(2, 3).astype(T) for T in dtypes] src_device_option = core.DeviceOption( src_device_type, src_gpu_id) dst_device_option = core.DeviceOption( dst_device_type, dst_gpu_id) for i, arr in enumerate(arrays): self.assertTrue(workspace.FeedBlob(str(i), arr, src_device_option)) self.assertTrue(workspace.HasBlob(str(i))) try: # Saves the blobs to a local db. tmp_folder = tempfile.mkdtemp() op = core.CreateOperator( "Save", [str(i) for i in range(len(arrays))], [], absolute_path=1, db=os.path.join(tmp_folder, "db"), db_type=self._db_type) self.assertTrue(workspace.RunOperatorOnce(op)) # Reset the workspace so that anything we load is surely loaded # from the serialized proto. workspace.ResetWorkspace() self.assertEqual(len(workspace.Blobs()), 0) def _LoadTest(keep_device, device_type, gpu_id, blobs, loadAll): """A helper subfunction to test keep and not keep.""" op = core.CreateOperator( "Load", [], blobs, absolute_path=1, db=os.path.join(tmp_folder, "db"), db_type=self._db_type, device_option=dst_device_option, keep_device=keep_device, load_all=loadAll) self.assertTrue(workspace.RunOperatorOnce(op)) for i, arr in enumerate(arrays): self.assertTrue(workspace.HasBlob(str(i))) fetched = workspace.FetchBlob(str(i)) self.assertEqual(fetched.dtype, arr.dtype) np.testing.assert_array_equal( workspace.FetchBlob(str(i)), arr) proto = caffe2_pb2.BlobProto() proto.ParseFromString(workspace.SerializeBlob(str(i))) self.assertTrue(proto.HasField('tensor')) self.assertEqual(proto.tensor.device_detail.device_type, device_type) if device_type == caffe2_pb2.CUDA: self.assertEqual(proto.tensor.device_detail.cuda_gpu_id, gpu_id) blobs = [str(i) for i in range(len(arrays))] # Load using device option stored in the proto, i.e. # src_device_option _LoadTest(1, src_device_type, src_gpu_id, blobs, 0) # Load again, but this time load into dst_device_option. _LoadTest(0, dst_device_type, dst_gpu_id, blobs, 0) # Load back to the src_device_option to see if both paths are able # to reallocate memory. _LoadTest(1, src_device_type, src_gpu_id, blobs, 0) # Reset the workspace, and load directly into the dst_device_option. workspace.ResetWorkspace() _LoadTest(0, dst_device_type, dst_gpu_id, blobs, 0) # Test load all which loads all blobs in the db into the workspace. workspace.ResetWorkspace() _LoadTest(1, src_device_type, src_gpu_id, [], 1) # Load again making sure that overwrite functionality works. _LoadTest(1, src_device_type, src_gpu_id, [], 1) # Load again with different device. _LoadTest(0, dst_device_type, dst_gpu_id, [], 1) workspace.ResetWorkspace() _LoadTest(0, dst_device_type, dst_gpu_id, [], 1) finally: # clean up temp folder. try: shutil.rmtree(tmp_folder) except OSError as e: if e.errno != errno.ENOENT: raise def saveFile(self, tmp_folder, db_name, db_type, start_blob_id): dtypes = [np.float16, np.float32, np.float64, np.bool, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16] arrays = [np.random.permutation(6).reshape(2, 3).astype(T) for T in dtypes] for i, arr in enumerate(arrays): self.assertTrue(workspace.FeedBlob(str(i + start_blob_id), arr)) self.assertTrue(workspace.HasBlob(str(i + start_blob_id))) # Saves the blobs to a local db. tmp_file = os.path.join(tmp_folder, db_name) op = core.CreateOperator( "Save", [str(i + start_blob_id) for i in range(len(arrays))], [], absolute_path=1, db=tmp_file, db_type=db_type) workspace.RunOperatorOnce(op) return tmp_file, arrays class TestLoadSave(TestLoadSaveBase): def testLoadSave(self): self.load_save() def testRepeatedArgs(self): dtypes = [np.float16, np.float32, np.float64, np.bool, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16] arrays = [np.random.permutation(6).reshape(2, 3).astype(T) for T in dtypes] for i, arr in enumerate(arrays): self.assertTrue(workspace.FeedBlob(str(i), arr)) self.assertTrue(workspace.HasBlob(str(i))) # Saves the blobs to a local db. tmp_folder = tempfile.mkdtemp() op = core.CreateOperator( "Save", [str(i) for i in range(len(arrays))] * 2, [], absolute_path=1, db=os.path.join(tmp_folder, "db"), db_type=self._db_type) with self.assertRaises(RuntimeError): workspace.RunOperatorOnce(op) try: shutil.rmtree(tmp_folder) except OSError as e: if e.errno != errno.ENOENT: raise def testLoadExcessblobs(self): tmp_folder = tempfile.mkdtemp() tmp_file, arrays = self.saveFile(tmp_folder, "db", self._db_type, 0) op = core.CreateOperator( "Load", [], [str(i) for i in range(len(arrays))] * 2, absolute_path=1, db=tmp_file, db_type=self._db_type, load_all=False) with self.assertRaises(RuntimeError): workspace.RunOperatorOnce(op) try: shutil.rmtree(tmp_folder) except OSError as e: if e.errno != errno.ENOENT: raise def testTruncatedFile(self): tmp_folder = tempfile.mkdtemp() tmp_file, arrays = self.saveFile(tmp_folder, "db", self._db_type, 0) with open(tmp_file, 'wb+') as fdest: fdest.seek(20, os.SEEK_END) fdest.truncate() op = core.CreateOperator( "Load", [], [str(i) for i in range(len(arrays))], absolute_path=1, db=tmp_file, db_type=self._db_type, load_all=False) with self.assertRaises(RuntimeError): workspace.RunOperatorOnce(op) op = core.CreateOperator( "Load", [], [], absolute_path=1, db=tmp_file, db_type=self._db_type, load_all=True) with self.assertRaises(RuntimeError): workspace.RunOperatorOnce(op) try: shutil.rmtree(tmp_folder) except OSError as e: if e.errno != errno.ENOENT: raise def testBlobNameOverrides(self): original_names = ['blob_a', 'blob_b', 'blob_c'] new_names = ['x', 'y', 'z'] blobs = [np.random.permutation(6) for i in range(3)] for i, blob in enumerate(blobs): self.assertTrue(workspace.FeedBlob(original_names[i], blob)) self.assertTrue(workspace.HasBlob(original_names[i])) self.assertEqual(len(workspace.Blobs()), 3) try: # Saves the blobs to a local db. tmp_folder = tempfile.mkdtemp() with self.assertRaises(RuntimeError): workspace.RunOperatorOnce( core.CreateOperator( "Save", original_names, [], absolute_path=1, strip_prefix='.temp', blob_name_overrides=new_names, db=os.path.join(tmp_folder, "db"), db_type=self._db_type ) ) self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "Save", original_names, [], absolute_path=1, blob_name_overrides=new_names, db=os.path.join(tmp_folder, "db"), db_type=self._db_type ) ) ) self.assertTrue(workspace.ResetWorkspace()) self.assertEqual(len(workspace.Blobs()), 0) self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "Load", [], [], absolute_path=1, db=os.path.join(tmp_folder, "db"), db_type=self._db_type, load_all=1 ) ) ) self.assertEqual(len(workspace.Blobs()), 3) for i, name in enumerate(new_names): self.assertTrue(workspace.HasBlob(name)) self.assertTrue((workspace.FetchBlob(name) == blobs[i]).all()) # moved here per @cxj's suggestion load_new_names = ['blob_x', 'blob_y', 'blob_z'] # load 'x' into 'blob_x' self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "Load", [], load_new_names[0:1], absolute_path=1, db=os.path.join(tmp_folder, "db"), db_type=self._db_type, source_blob_names=new_names[0:1] ) ) ) # we should have 'blob_a/b/c/' and 'blob_x' now self.assertEqual(len(workspace.Blobs()), 4) for i, name in enumerate(load_new_names[0:1]): self.assertTrue(workspace.HasBlob(name)) self.assertTrue((workspace.FetchBlob(name) == blobs[i]).all()) self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "Load", [], load_new_names[0:3], absolute_path=1, db=os.path.join(tmp_folder, "db"), db_type=self._db_type, source_blob_names=new_names[0:3] ) ) ) # we should have 'blob_a/b/c/' and 'blob_x/y/z' now self.assertEqual(len(workspace.Blobs()), 6) for i, name in enumerate(load_new_names[0:3]): self.assertTrue(workspace.HasBlob(name)) self.assertTrue((workspace.FetchBlob(name) == blobs[i]).all()) finally: # clean up temp folder. try: shutil.rmtree(tmp_folder) except OSError as e: if e.errno != errno.ENOENT: raise def testMissingFile(self): tmp_folder = tempfile.mkdtemp() tmp_file = os.path.join(tmp_folder, "missing_db") op = core.CreateOperator( "Load", [], [], absolute_path=1, db=tmp_file, db_type=self._db_type, load_all=True) with self.assertRaises(RuntimeError): try: workspace.RunOperatorOnce(op) except RuntimeError as e: print(e) raise try: shutil.rmtree(tmp_folder) except OSError as e: if e.errno != errno.ENOENT: raise def testLoadMultipleFilesGivenSourceBlobNames(self): tmp_folder = tempfile.mkdtemp() db_file_1, arrays_1 = self.saveFile(tmp_folder, "db1", self._db_type, 0) db_file_2, arrays_2 = self.saveFile( tmp_folder, "db2", self._db_type, len(arrays_1) ) db_files = [db_file_1, db_file_2] blobs_names = [str(i) for i in range(len(arrays_1) + len(arrays_2))] workspace.ResetWorkspace() self.assertEqual(len(workspace.Blobs()), 0) self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "Load", [], blobs_names, absolute_path=1, dbs=db_files, db_type=self._db_type, source_blob_names=blobs_names ) ) ) self.assertEqual(len(workspace.Blobs()), len(blobs_names)) for i in range(len(arrays_1)): np.testing.assert_array_equal( workspace.FetchBlob(str(i)), arrays_1[i] ) for i in range(len(arrays_2)): np.testing.assert_array_equal( workspace.FetchBlob(str(i + len(arrays_1))), arrays_2[i] ) try: shutil.rmtree(tmp_folder) except OSError as e: if e.errno != errno.ENOENT: raise def testLoadAllMultipleFiles(self): tmp_folder = tempfile.mkdtemp() db_file_1, arrays_1 = self.saveFile(tmp_folder, "db1", self._db_type, 0) db_file_2, arrays_2 = self.saveFile( tmp_folder, "db2", self._db_type, len(arrays_1) ) db_files = [db_file_1, db_file_2] workspace.ResetWorkspace() self.assertEqual(len(workspace.Blobs()), 0) self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "Load", [], [], absolute_path=1, dbs=db_files, db_type=self._db_type, load_all=True ) ) ) self.assertEqual(len(workspace.Blobs()), len(arrays_1) + len(arrays_2)) for i in range(len(arrays_1)): np.testing.assert_array_equal( workspace.FetchBlob(str(i)), arrays_1[i] ) for i in range(len(arrays_2)): np.testing.assert_array_equal( workspace.FetchBlob(str(i + len(arrays_1))), arrays_2[i] ) try: shutil.rmtree(tmp_folder) except OSError as e: if e.errno != errno.ENOENT: raise def testLoadAllMultipleFilesWithSameKey(self): tmp_folder = tempfile.mkdtemp() db_file_1, arrays_1 = self.saveFile(tmp_folder, "db1", self._db_type, 0) db_file_2, arrays_2 = self.saveFile(tmp_folder, "db2", self._db_type, 0) db_files = [db_file_1, db_file_2] workspace.ResetWorkspace() self.assertEqual(len(workspace.Blobs()), 0) op = core.CreateOperator( "Load", [], [], absolute_path=1, dbs=db_files, db_type=self._db_type, load_all=True) with self.assertRaises(RuntimeError): workspace.RunOperatorOnce(op) try: shutil.rmtree(tmp_folder) except OSError as e: if e.errno != errno.ENOENT: raise def testLoadRepeatedFiles(self): tmp_folder = tempfile.mkdtemp() tmp_file, arrays = self.saveFile(tmp_folder, "db", self._db_type, 0) db_files = [tmp_file, tmp_file] workspace.ResetWorkspace() self.assertEqual(len(workspace.Blobs()), 0) op = core.CreateOperator( "Load", [], [str(i) for i in range(len(arrays))], absolute_path=1, dbs=db_files, db_type=self._db_type, load_all=False) with self.assertRaises(RuntimeError): workspace.RunOperatorOnce(op) try: shutil.rmtree(tmp_folder) except OSError as e: if e.errno != errno.ENOENT: raise if __name__ == '__main__': unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core import caffe2.python.hypothesis_test_util as hu from hypothesis import given import numpy as np import math class TestLearningRate(hu.HypothesisTestCase): @given(**hu.gcs_cpu_only) def test_alter_learning_rate_op(self, gc, dc): iter = np.random.randint(low=1, high=1e5, size=1) active_period = int(np.random.randint(low=1, high=1e3, size=1)) inactive_period = int(np.random.randint(low=1, high=1e3, size=1)) base_lr = float(np.random.random(1)) def ref(iter): iter = float(iter) reminder = iter % (active_period + inactive_period) if reminder < active_period: return (np.array(base_lr), ) else: return (np.array(0.), ) op = core.CreateOperator( 'LearningRate', 'iter', 'lr', policy="alter", active_first=True, base_lr=base_lr, active_period=active_period, inactive_period=inactive_period ) self.assertReferenceChecks(gc, op, [iter], ref) @given(**hu.gcs_cpu_only) def test_hill_learning_rate_op(self, gc, dc): iter = np.random.randint(low=1, high=1e5, size=1) num_iter = int(np.random.randint(low=1e2, high=1e3, size=1)) start_multiplier = 1e-4 gamma = 1.0 power = 0.5 end_multiplier = 1e-2 base_lr = float(np.random.random(1)) def ref(iter): iter = float(iter) if iter < num_iter: lr = start_multiplier + ( 1.0 - start_multiplier ) * iter / num_iter else: iter -= num_iter lr = math.pow(1.0 + gamma * iter, -power) lr = max(lr, end_multiplier) return (np.array(base_lr * lr), ) op = core.CreateOperator( 'LearningRate', 'data', 'out', policy="hill", base_lr=base_lr, num_iter=num_iter, start_multiplier=start_multiplier, gamma=gamma, power=power, end_multiplier=end_multiplier, ) self.assertReferenceChecks(gc, op, [iter], ref) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest from hypothesis import given import numpy as np from caffe2.proto import caffe2_pb2 from caffe2.python import core, workspace import caffe2.python.hypothesis_test_util as hu # TODO(jiayq): make them hypothesis tests for better coverage. class TestElementwiseBroadcast(hu.HypothesisTestCase): @given(**hu.gcs) def test_broadcast_Add(self, gc, dc): # Set broadcast and no axis, i.e. broadcasting last dimensions. X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(4, 5).astype(np.float32) op = core.CreateOperator("Add", ["X", "Y"], "out", broadcast=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal(out, X + Y) self.assertDeviceChecks(dc, op, [X, Y], [0]) self.assertGradientChecks(gc, op, [X, Y], 1, [0]) # broadcasting intermediate dimensions X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(3, 4).astype(np.float32) op = core.CreateOperator("Add", ["X", "Y"], "out", broadcast=1, axis=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal(out, X + Y[:, :, np.newaxis]) self.assertDeviceChecks(dc, op, [X, Y], [0]) self.assertGradientChecks(gc, op, [X, Y], 1, [0]) # broadcasting the first dimension X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(2).astype(np.float32) op = core.CreateOperator("Add", ["X", "Y"], "out", broadcast=1, axis=0) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal( out, X + Y[:, np.newaxis, np.newaxis, np.newaxis]) self.assertDeviceChecks(dc, op, [X, Y], [0]) self.assertGradientChecks(gc, op, [X, Y], 1, [0]) # broadcasting with single elem dimensions at both ends X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(1, 4, 1).astype(np.float32) op = core.CreateOperator("Add", ["X", "Y"], "out", broadcast=1, axis=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal(out, X + Y) self.assertDeviceChecks(dc, op, [X, Y], [0]) self.assertGradientChecks(gc, op, [X, Y], 1, [0]) @given(**hu.gcs) def test_broadcast_Mul(self, gc, dc): # Set broadcast and no axis, i.e. broadcasting last dimensions. X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(4, 5).astype(np.float32) op = core.CreateOperator("Mul", ["X", "Y"], "out", broadcast=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal(out, X * Y) self.assertDeviceChecks(dc, op, [X, Y], [0]) self.assertGradientChecks(gc, op, [X, Y], 1, [0]) # broadcasting intermediate dimensions X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(3, 4).astype(np.float32) op = core.CreateOperator("Mul", ["X", "Y"], "out", broadcast=1, axis=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal(out, X * Y[:, :, np.newaxis]) self.assertGradientChecks(gc, op, [X, Y], 1, [0]) self.assertDeviceChecks(dc, op, [X, Y], [0]) # broadcasting the first dimension X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(2).astype(np.float32) op = core.CreateOperator("Mul", ["X", "Y"], "out", broadcast=1, axis=0) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal( out, X * Y[:, np.newaxis, np.newaxis, np.newaxis]) self.assertGradientChecks(gc, op, [X, Y], 1, [0]) self.assertDeviceChecks(dc, op, [X, Y], [0]) # broadcasting with single elem dimensions at both ends X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(1, 4, 1).astype(np.float32) op = core.CreateOperator("Mul", ["X", "Y"], "out", broadcast=1, axis=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal(out, X * Y) self.assertDeviceChecks(dc, op, [X, Y], [0]) self.assertGradientChecks(gc, op, [X, Y], 1, [0]) @given(**hu.gcs) def test_broadcast_Sub(self, gc, dc): # Set broadcast and no axis, i.e. broadcasting last dimensions. X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(4, 5).astype(np.float32) op = core.CreateOperator("Sub", ["X", "Y"], "out", broadcast=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal(out, X - Y) self.assertDeviceChecks(dc, op, [X, Y], [0]) self.assertGradientChecks(gc, op, [X, Y], 1, [0]) # broadcasting intermediate dimensions X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(3, 4).astype(np.float32) op = core.CreateOperator("Sub", ["X", "Y"], "out", broadcast=1, axis=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal(out, X - Y[:, :, np.newaxis]) self.assertGradientChecks(gc, op, [X, Y], 1, [0]) self.assertDeviceChecks(dc, op, [X, Y], [0]) # broadcasting the first dimension X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(2).astype(np.float32) op = core.CreateOperator("Sub", ["X", "Y"], "out", broadcast=1, axis=0) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal( out, X - Y[:, np.newaxis, np.newaxis, np.newaxis]) self.assertGradientChecks(gc, op, [X, Y], 1, [0]) self.assertDeviceChecks(dc, op, [X, Y], [0]) # broadcasting with single elem dimensions at both ends X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(1, 4, 1).astype(np.float32) op = core.CreateOperator("Sub", ["X", "Y"], "out", broadcast=1, axis=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal(out, X - Y) self.assertDeviceChecks(dc, op, [X, Y], [0]) self.assertGradientChecks(gc, op, [X, Y], 1, [0]) @given(**hu.gcs) def test_broadcast_powt(self, gc, dc): np.random.seed(101) #operator def powt_op(X, Y): return [np.power(X, Y)] #two gradients Y*X^(Y-1) and X^Y * ln(X) def powt_grad(g_out, outputs, fwd_inputs): [X, Y] = fwd_inputs Z = outputs[0] return ([Y * np.power(X, Y - 1), Z * np.log(X)] * g_out) #1. Set broadcast and no axis, i.e. broadcasting last dimensions. X = np.random.rand(2, 3, 4, 5).astype(np.float32) + 1.0 Y = np.random.rand(4, 5).astype(np.float32) + 2.0 #two gradients Y*X^(Y-1) and X^Y * ln(X) #latter gradient is sumed over 1 and 0 dims to account for broadcast def powt_grad_broadcast(g_out, outputs, fwd_inputs): [GX, GY] = powt_grad(g_out, outputs, fwd_inputs) return ([GX, np.sum(np.sum(GY, 1), 0)]) op = core.CreateOperator("Pow", ["X", "Y"], "Z", broadcast=1) self.assertReferenceChecks(device_option=gc, op=op, inputs=[X, Y], reference=powt_op, output_to_grad="Z", grad_reference=powt_grad_broadcast) #2. broadcasting intermediate dimensions X = np.random.rand(2, 3, 4, 5).astype(np.float32) + 1.0 Y = np.random.rand(3, 4).astype(np.float32) + 2.0 #pow op with the latter array increased by one dim def powt_op_axis1(X, Y): return powt_op(X, Y[:, :, np.newaxis]) #two gradients Y*X^(Y-1) and X^Y * ln(X) #latter gradient is sumed over 3 and 0 dims to account for broadcast def powt_grad_axis1(g_out, outputs, fwd_inputs): [X, Y] = fwd_inputs [GX, GY] = powt_grad(g_out, outputs, [X, Y[:, :, np.newaxis]]) return ([GX, np.sum(np.sum(GY, 3), 0)]) op = core.CreateOperator("Pow", ["X", "Y"], "Z", broadcast=1, axis=1) self.assertReferenceChecks(device_option=gc, op=op, inputs=[X, Y], reference=powt_op_axis1, output_to_grad="Z", grad_reference=powt_grad_axis1) #3. broadcasting the first dimension X = np.random.rand(2, 3, 4, 5).astype(np.float32) + 1.0 Y = np.random.rand(2).astype(np.float32) + 2.0 #pow op with the latter array increased by one dim def powt_op_axis0(X, Y): return powt_op(X, Y[:, np.newaxis, np.newaxis, np.newaxis]) #two gradients Y*X^(Y-1) and X^Y * ln(X) #latter gradient is sumed over 3, 2 and 1 dims to account for broadcast def powt_grad_axis0(g_out, outputs, fwd_inputs): [X, Y] = fwd_inputs [GX, GY] = powt_grad(g_out, outputs, [X, Y[:, np.newaxis, np.newaxis, np.newaxis]]) return ([GX, np.sum(np.sum(np.sum(GY, 3), 2), 1)]) op = core.CreateOperator("Pow", ["X", "Y"], "Z", broadcast=1, axis=0) self.assertReferenceChecks(device_option=gc, op=op, inputs=[X, Y], reference=powt_op_axis0, output_to_grad="Z", grad_reference=powt_grad_axis0) #4. broadcasting with single elem dimensions at both ends X = np.random.rand(2, 3, 4, 5).astype(np.float32) + 1.0 Y = np.random.rand(1, 4, 1).astype(np.float32) + 2.0 #pow op with the latter array increased by one dim def powt_op_mixed(X, Y): return powt_op(X, Y[np.newaxis, :, :, :]) #two gradients Y*X^(Y-1) and X^Y * ln(X) #latter gradient is sumed over 0 and 1 dims to account for broadcast def powt_grad_mixed(g_out, outputs, fwd_inputs): [X, Y] = fwd_inputs [GX, GY] = powt_grad(g_out, outputs, [X, Y[np.newaxis, :, :, :]]) return ([GX, np.reshape(np.sum(np.sum(np.sum(GY, 3), 1), 0), (1, 4, 1))]) op = core.CreateOperator("Pow", ["X", "Y"], "Z", broadcast=1, axis=1) self.assertReferenceChecks(device_option=gc, op=op, inputs=[X, Y], reference=powt_op_mixed, output_to_grad="Z", grad_reference=powt_grad_mixed) @given(**hu.gcs) def test_broadcast_scalar(self, gc, dc): # broadcasting constant X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(1).astype(np.float32) op = core.CreateOperator("Add", ["X", "Y"], "out", broadcast=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal( out, X + Y) self.assertDeviceChecks(dc, op, [X, Y], [0]) # broadcasting scalar X = np.random.rand(1).astype(np.float32) Y = np.random.rand(1).astype(np.float32).reshape([]) op = core.CreateOperator("Add", ["X", "Y"], "out", broadcast=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal( out, X + Y) self.assertDeviceChecks(dc, op, [X, Y], [0]) @given(**hu.gcs) def test_semantic_broadcast(self, gc, dc): # NCHW as default X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(3).astype(np.float32) op = core.CreateOperator( "Add", ["X", "Y"], "out", broadcast=1, axis_str="C") workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal( out, X + Y[:, np.newaxis, np.newaxis]) self.assertDeviceChecks(dc, op, [X, Y], [0]) # NHWC X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(5).astype(np.float32) op = core.CreateOperator( "Add", ["X", "Y"], "out", broadcast=1, axis_str="C", order="NHWC") workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") np.testing.assert_array_almost_equal(out, X + Y) self.assertDeviceChecks(dc, op, [X, Y], [0]) @given(**hu.gcs) def test_sum_reduce(self, gc, dc): # Set broadcast and no axis, i.e. broadcasting last dimensions. X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(4, 5).astype(np.float32) op = core.CreateOperator( "SumReduceLike", ["X", "Y"], "out", broadcast=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") res = np.sum(X, axis=0) res = np.sum(res, axis=0) np.testing.assert_array_almost_equal(out, res) self.assertDeviceChecks(dc, op, [X, Y], [0]) # Set broadcast and no axis, i.e. broadcasting last dimensions. X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(2, 3).astype(np.float32) op = core.CreateOperator( "SumReduceLike", ["X", "Y"], "out", broadcast=1, axis=0) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") res = np.sum(X, axis=3) res = np.sum(res, axis=2) np.testing.assert_array_almost_equal(out, res, decimal=3) self.assertDeviceChecks(dc, op, [X, Y], [0]) # broadcasting intermediate dimensions X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(3, 4).astype(np.float32) op = core.CreateOperator( "SumReduceLike", ["X", "Y"], "out", broadcast=1, axis=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") res = np.sum(X, axis=0) res = np.sum(res, axis=2) np.testing.assert_array_almost_equal(out, res) self.assertDeviceChecks(dc, op, [X, Y], [0]) # broadcasting intermediate dimensions X = np.random.rand(2, 3, 4, 500).astype(np.float64) Y = np.random.rand(1).astype(np.float64) op = core.CreateOperator( "SumReduceLike", ["X", "Y"], "out", broadcast=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") res = np.array(np.sum(X)) np.testing.assert_array_almost_equal(out, res, decimal=0) # broadcasting with single elem dimensions at both ends X = np.random.rand(2, 3, 4, 5).astype(np.float32) Y = np.random.rand(1, 3, 4, 1).astype(np.float32) op = core.CreateOperator( "SumReduceLike", ["X", "Y"], "out", broadcast=1) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) workspace.RunOperatorOnce(op) out = workspace.FetchBlob("out") res = np.sum(X, axis=0) res = np.sum(res, axis=2).reshape(Y.shape) np.testing.assert_array_almost_equal(out, res) self.assertDeviceChecks(dc, op, [X, Y], [0]) # fp64 is not supported with the CUDA op dc_cpu_only = [d for d in dc if d.device_type != caffe2_pb2.CUDA] self.assertDeviceChecks(dc_cpu_only, op, [X, Y], [0]) @unittest.skipIf(not workspace.has_gpu_support, "No gpu support") @given(**hu.gcs_gpu_only) def test_sum_reduce_fp16(self, gc, dc): # Set broadcast and no axis, i.e. broadcasting last dimensions. X = np.random.rand(2, 3, 4, 5).astype(np.float16) Y = np.random.rand(4, 5).astype(np.float16) op = core.CreateOperator( "SumReduceLike", ["X", "Y"], "out", broadcast=1, device_option=gc) def ref_op(X, Y): res = np.sum(X, axis=0) res = np.sum(res, axis=0) return [res] self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, Y], reference=ref_op, threshold=1e-3) # Set broadcast and no axis, i.e. broadcasting last dimensions. X = np.random.rand(2, 3, 4, 5).astype(np.float16) Y = np.random.rand(2, 3).astype(np.float16) op = core.CreateOperator( "SumReduceLike", ["X", "Y"], "out", broadcast=1, axis=0) def ref_op(X, Y): res = np.sum(X, axis=3) res = np.sum(res, axis=2) return [res] self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, Y], reference=ref_op, threshold=1e-3) # broadcasting intermediate dimensions X = np.random.rand(2, 3, 4, 5).astype(np.float16) Y = np.random.rand(3, 4).astype(np.float16) op = core.CreateOperator( "SumReduceLike", ["X", "Y"], "out", broadcast=1, axis=1) def ref_op(X, Y): res = np.sum(X, axis=0) res = np.sum(res, axis=2) return [res] self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, Y], reference=ref_op, threshold=1e-3) # broadcasting with single elem dimensions at both ends X = np.random.rand(2, 3, 4, 5).astype(np.float16) Y = np.random.rand(1, 3, 4, 1).astype(np.float16) op = core.CreateOperator( "SumReduceLike", ["X", "Y"], "out", broadcast=1) def ref_op(X, Y): res = np.sum(X, axis=0) res = np.sum(res, axis=2) return [res.reshape(Y.shape)] self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, Y], reference=ref_op, threshold=1e-3) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import recurrent, workspace from caffe2.python.model_helper import ModelHelper from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class RecurrentNetworkTest(hu.HypothesisTestCase): @given(T=st.integers(1, 4), n=st.integers(1, 5), d=st.integers(1, 5)) def test_sum_mul(self, T, n, d): model = ModelHelper(name='external') input_blob, initial_input_blob = model.net.AddExternalInputs( 'input', 'initial_input') step = ModelHelper(name='step', param_model=model) input_t, output_t_prev = step.net.AddExternalInput( 'input_t', 'output_t_prev') output_t_internal = step.net.Sum([input_t, output_t_prev]) output_t = step.net.Mul([input_t, output_t_internal]) step.net.AddExternalOutput(output_t) self.simple_rnn(T, n, d, model, step, input_t, output_t, output_t_prev, input_blob, initial_input_blob) @given(T=st.integers(1, 4), n=st.integers(1, 5), d=st.integers(1, 5)) def test_mul(self, T, n, d): model = ModelHelper(name='external') input_blob, initial_input_blob = model.net.AddExternalInputs( 'input', 'initial_input') step = ModelHelper(name='step', param_model=model) input_t, output_t_prev = step.net.AddExternalInput( 'input_t', 'output_t_prev') output_t = step.net.Mul([input_t, output_t_prev]) step.net.AddExternalOutput(output_t) self.simple_rnn(T, n, d, model, step, input_t, output_t, output_t_prev, input_blob, initial_input_blob) @given(T=st.integers(1, 4), n=st.integers(1, 5), d=st.integers(1, 5)) def test_extract(self, T, n, d): model = ModelHelper(name='external') workspace.ResetWorkspace() input_blob, initial_input_blob = model.net.AddExternalInputs( 'input', 'initial_input') step = ModelHelper(name='step', param_model=model) input_t, output_t_prev = step.net.AddExternalInput( 'input_t', 'output_t_prev') output_t = step.net.Mul([input_t, output_t_prev]) step.net.AddExternalOutput(output_t) inputs = np.random.randn(T, n, d).astype(np.float32) initial_input = np.random.randn(1, n, d).astype(np.float32) recurrent.recurrent_net( net=model.net, cell_net=step.net, inputs=[(input_t, input_blob)], initial_cell_inputs=[(output_t_prev, initial_input_blob)], links={output_t_prev: output_t}, scope="test_rnn_sum_mull", ) workspace.blobs[input_blob] = inputs workspace.blobs[initial_input_blob] = initial_input workspace.RunNetOnce(model.param_init_net) workspace.CreateNet(model.net) prefix = "extractTest" workspace.RunNet(model.net.Proto().name, T) retrieved_blobs = recurrent.retrieve_step_blobs( model.net, prefix ) # needed for python3.6, which returns bytearrays instead of str retrieved_blobs = [x.decode() for x in retrieved_blobs] for i in range(T): blob_name = prefix + "_" + "input_t" + str(i) self.assertTrue( blob_name in retrieved_blobs, "blob extraction failed on timestep {}\ . \n\n Extracted Blobs: {} \n\n Looking for {}\ .".format(i, retrieved_blobs, blob_name) ) def simple_rnn(self, T, n, d, model, step, input_t, output_t, output_t_prev, input_blob, initial_input_blob): input = np.random.randn(T, n, d).astype(np.float32) initial_input = np.random.randn(1, n, d).astype(np.float32) print(locals()) recurrent.recurrent_net( net=model.net, cell_net=step.net, inputs=[(input_t, input_blob)], initial_cell_inputs=[(output_t_prev, initial_input_blob)], links={output_t_prev: output_t}, scope="test_rnn_sum_mull", ) workspace.blobs[input_blob] = input workspace.blobs[initial_input_blob] = initial_input op = model.net._net.op[-1] # Just conviniently store all inputs in an array in the same # order as op.input inputs = [workspace.blobs[name] for name in op.input] def reference(input, initial_input): global_ws_name = workspace.CurrentWorkspace() input_all = workspace.blobs[input_blob] workspace.SwitchWorkspace("ref", create_if_missing=True) workspace.blobs[input_blob] = input workspace.blobs[output_t_prev] = initial_input.reshape(n, d) res_all = np.zeros(shape=input.shape, dtype=np.float32) for t_cur in range(T): workspace.blobs[input_t] = input_all[t_cur] workspace.RunNetOnce(step.net) result_t = workspace.blobs[output_t] workspace.blobs[output_t_prev] = result_t res_all[t_cur] = result_t workspace.SwitchWorkspace(global_ws_name) shape = list(input.shape) shape[0] = 1 return (res_all, res_all[-1].reshape(shape)) self.assertReferenceChecks( device_option=hu.cpu_do, op=op, inputs=inputs, reference=reference, output_to_grad=op.output[0], outputs_to_check=[0, 1], ) self.assertGradientChecks( device_option=hu.cpu_do, op=op, inputs=inputs, outputs_to_check=0, outputs_with_grads=[0], threshold=0.01, stepsize=0.005, ) # Hacky version of 1-D convolution def _convolution_1d( self, model, inputs, conv_window, conv_filter, conv_bias, output_name, left_pad, ): if left_pad: padding_width = conv_window - 1 else: padding_width = 0 # [batch_size, inputs_length, state_size] inputs_transposed = model.net.Transpose( inputs, 'inputs_transposed', axes=[1, 0, 2], ) # [batch_size, 1, inputs_length, state_size] inputs_transposed_4d = model.net.ExpandDims( inputs_transposed, 'inputs_transposed_4d', dims=[1], ) # [batch_size, 1, inputs_length - conv_window + 1, state_size] output_transposed_4d = model.net.Conv( [inputs_transposed_4d, conv_filter, conv_bias], output_name + '_transposed_4d', kernel_h=1, kernel_w=conv_window, order='NHWC', pad_t=0, pad_l=padding_width, pad_b=0, pad_r=0, ) # [batch_size, inputs_length - conv_window + 1, state_size] output_transposed = model.net.Squeeze( output_transposed_4d, output_name + '_transposed', dims=[1], ) # [inputs_length - conv_window + 1, batch_size, state_size] output = model.net.Transpose( output_transposed, output_name, axes=[1, 0, 2], ) return output @given(sequence_length=st.integers(3, 7), conv_window=st.integers(1, 3), batch_size=st.integers(1, 5), state_size=st.integers(1, 5)) def test_stateful_convolution_forward_only( self, sequence_length, conv_window, batch_size, state_size, ): ''' This unit test demonstrates another ways of using RecurrentNetwork. Imagine, that you want to compute convolution over a sequence, but sequence elements are not given to you from the beginning, so you have to loop over the sequence and compute convolution for each element separately. This situation can occur, during inference/generation step of the neural networks. First of all, you have to provide actual input via recurrent states, since the input of RecurrentNetwork should be known in advance. Here, we use `fake_inputs` as the input, and it's used by the op to extract batch size and sequence length. The actual input sequence is stored in the recurrent state `input_state`. At every step we generate a new element via input_state_t (in this example, input_state_t is generated at random, but in a real situation it can be created using convolution output from the previous step). A few important differences from regular RecurrentNetwork usecase: 1. input_state_t_prev is not only a single previous element of input_state sequence. It is last conv_window elements including (!) the current one - input_state_t. We specify that using `link_window` argument of RecurrentNetwork. We need that many elements to compute a single convolution step. Also, note that `link_window` specifies how many elements to link starting at `timestep` + `link_offset` position. 2. First few steps might require additional zero padding from the left, since there is no enough element of input_state sequence are available. So the initial_state for input_state contains several elements (exactly how many pads we need for the first step). Also, because of that all offseting over input_state sequnece is being shifted by length of initial_input_state: see `link_offset` and `alias_offset` arguments of RecurrentNetwork. In this test, we assert that we get the same result if we apply convolution over all elements simultaneously, since the whole input_state sequence was generated at the end. ''' model = ModelHelper(name='model') fake_inputs = model.param_init_net.UniformFill( [], 'fake_inputs', min=-1.0, max=1.0, shape=[sequence_length, batch_size, state_size], ) initial_input_state = model.param_init_net.ConstantFill( [], 'initial_input_state', value=0.0, shape=[conv_window - 1, batch_size, state_size], ) initial_output_state = model.param_init_net.ConstantFill( [], 'initial_output_state', value=0.0, shape=[1, batch_size, state_size], ) step_model = ModelHelper(name='step_model', param_model=model) ( fake_input_t, timestep, input_state_t_prev, ) = step_model.net.AddExternalInputs( 'fake_input_t', 'timestep', 'input_state_t_prev', ) conv_filter = step_model.param_init_net.XavierFill( [], 'conv_filter', shape=[state_size, 1, conv_window, state_size], ) conv_bias = step_model.param_init_net.ConstantFill( [], 'conv_bias', shape=[state_size], value=0.0, ) step_model.params.extend([conv_filter, conv_bias]) input_state_t = step_model.net.UniformFill( [], 'input_state_t', min=-1.0, max=1.0, shape=[1, batch_size, state_size], ) output_state_t = self._convolution_1d( model=step_model, inputs=input_state_t_prev, conv_window=conv_window, conv_filter=conv_filter, conv_bias=conv_bias, output_name='output_state_t', left_pad=False, ) initial_recurrent_states = [initial_input_state, initial_output_state] all_inputs = ( [fake_inputs] + step_model.params + initial_recurrent_states ) all_outputs = ['input_state_all', 'output_state_all'] recurrent_states = ['input_state', 'output_state'] input_state_all, output_state_all, _ = model.net.RecurrentNetwork( all_inputs, all_outputs + ['step_workspaces'], param=[all_inputs.index(p) for p in step_model.params], alias_src=recurrent_states, alias_dst=all_outputs, alias_offset=[conv_window - 1, 1], recurrent_states=recurrent_states, initial_recurrent_state_ids=[ all_inputs.index(s) for s in initial_recurrent_states ], link_internal=[ str(input_state_t_prev), str(input_state_t), str(output_state_t), ], link_external=['input_state', 'input_state', 'output_state'], link_offset=[0, conv_window - 1, 1], link_window=[conv_window, 1, 1], backward_link_internal=[], backward_link_external=[], backward_link_offset=[], step_net=step_model.net.Proto(), timestep='timestep' if timestep is None else str(timestep), outputs_with_grads=[], ) output_states_2 = self._convolution_1d( model=model, inputs=input_state_all, conv_window=conv_window, conv_filter=conv_filter, conv_bias=conv_bias, output_name='output_states_2', left_pad=True, ) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) np.testing.assert_almost_equal( workspace.FetchBlob(output_state_all), workspace.FetchBlob(output_states_2), decimal=3, )
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from caffe2.python.test_util import TestCase class TestAtomicOps(TestCase): def test_atomic_ops(self): """ Test that both countdown and checksum are update atomically by having cowntdown count from 20k to 0 from parallel the workers and updating the checksum to the value fetched. If operations are trully atomic, each value from 1 to 20k should be fetched exactly once from the countdown, and fed exactly once to the checksum, such that at the end checksum must contain the exact value of sum[i=0..20000](i). """ init_net = core.Net('init') mutex_countdown = init_net.CreateMutex([]) mutex_checksum = init_net.CreateMutex([]) countdown = init_net.ConstantFill([], shape=[], value=20000, dtype=core.DataType.INT32) checksum = init_net.ConstantFill( [], shape=[], value=0, dtype=core.DataType.INT32) minus_one = init_net.ConstantFill( [], shape=[], value=-1, dtype=core.DataType.INT32) steps = [] for i in range(0, 100): net = core.Net('net:%d' % i) _, fetched_count = net.AtomicFetchAdd( [mutex_countdown, countdown, minus_one], [countdown, 'fetched_count:%d' % i]) net.AtomicFetchAdd( [mutex_checksum, checksum, fetched_count], [checksum, 'not_used']) steps.append( core.execution_step('worker:%d' % i, net, num_iter=200)) super_step = core.execution_step( 'parent', steps, concurrent_substeps=True) plan = core.Plan('plan') plan.AddStep(core.execution_step('init', init_net)) plan.AddStep(super_step) workspace.RunPlan(plan) # checksum = sum[i=1..20000](i) = 20000 * 20001 / 2 = 200010000 self.assertEquals(workspace.FetchBlob(checksum), 200010000) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class RMACRegionsOpTest(hu.HypothesisTestCase): @given( n=st.integers(500, 500), h=st.integers(1, 10), w=st.integers(1, 10), scales=st.integers(1, 3), **hu.gcs ) def test(self, n, h, w, scales, gc, dc): X = np.random.rand(n, 64, h, w).astype(np.float32) overlap = 0.4 def ref_op(X): N, H, W = X.shape[0], X.shape[2], X.shape[3] # Possible regions for the long dimension steps = np.array((2, 3, 4, 5, 6, 7), dtype=np.float32) minW = np.minimum(H, W) # steps(idx) regions for long dimension b = (np.maximum(H, W) - minW) / (steps - 1) idx = np.argmin( np.abs(((minW**2 - minW * b) / minW**2) - overlap)) + 1 # Region overplus per dimension Wd = 0 Hd = 0 if H < W: Wd = idx elif H > W: Hd = idx regions_xywh = [] for l in range(1, scales + 1): wl = np.floor(2 * minW / (l + 1)) # Center coordinates if l + Wd - 1 > 0: b = (W - wl) / (l + Wd - 1) else: b = 0 cenW = np.floor(b * np.arange(l - 1 + Wd + 1)) # Center coordinates if l + Hd - 1 > 0: b = (H - wl) / (l + Hd - 1) else: b = 0 cenH = np.floor(b * np.arange(l - 1 + Hd + 1)) for i_ in cenW: for j_ in cenH: regions_xywh.append([i_, j_, wl, wl]) # Round the regions. Careful with the borders! for i in range(len(regions_xywh)): for j in range(4): regions_xywh[i][j] = int(round(regions_xywh[i][j])) if regions_xywh[i][0] + regions_xywh[i][2] > W: regions_xywh[i][0] -= ( (regions_xywh[i][0] + regions_xywh[i][2]) - W ) if regions_xywh[i][1] + regions_xywh[i][3] > H: regions_xywh[i][1] -= ( (regions_xywh[i][1] + regions_xywh[i][3]) - H ) # Filter out 0-sized regions regions_xywh = [r for r in regions_xywh if r[2] * r[3] > 0] # Convert to ROIPoolOp format: (batch_index x1 y1 x2 y2) regions = [ [i, x, y, x + w - 1, y + h - 1] for i in np.arange(N) for x, y, w, h in regions_xywh ] return (np.array(regions).astype(np.float32), ) op = core.CreateOperator( 'RMACRegions', ['X'], ['RMAC_REGIONS'], scales=scales, overlap=overlap, ) # Check against numpy reference self.assertReferenceChecks(gc, op, [X], ref_op)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class TestPackRNNSequenceOperator(hu.HypothesisTestCase): @given(n=st.integers(0, 10), k=st.integers(1, 5), dim=st.integers(1, 5), **hu.gcs_cpu_only) def test_pack_rnn_seqence(self, n, k, dim, gc, dc): lengths = np.random.randint(k, size=n).astype(np.int32) + 1 values = np.random.rand(sum(lengths), dim).astype(np.float32) def pack_op(values, lengths): T = max(lengths) if any(lengths) else 0 N = lengths.size output = np.zeros((T, N) + values.shape[1:]).astype(np.float32) offset = 0 for c in range(N): for r in range(lengths[c]): output[r][c] = values[offset + r] offset += lengths[c] return [output] op = core.CreateOperator( 'PackRNNSequence', ['values', 'lengths'], 'out' ) # Check against numpy reference self.assertReferenceChecks( device_option=gc, op=op, inputs=[values, lengths], reference=pack_op, ) # Check over multiple devices self.assertDeviceChecks(dc, op, [values, lengths], [0]) # Gradient check self.assertGradientChecks(gc, op, [values, lengths], 0, [0]) @given(n=st.integers(0, 10), k=st.integers(2, 5), dim=st.integers(1, 5), **hu.gcs_cpu_only) def test_unpack_rnn_seqence(self, n, k, dim, gc, dc): lengths = np.random.randint(k, size=n).astype(np.int32) + 1 T = max(lengths) if any(lengths) else 0 N = lengths.size values = np.random.rand(T, N, dim).astype(np.float32) def unpack_op(values, lengths): M = sum(lengths) output = np.zeros((M,) + values.shape[2:]).astype(np.float32) N = lengths.size offset = 0 for c in range(N): for r in range(lengths[c]): output[offset + r] = values[r][c] offset += lengths[c] return [output] op = core.CreateOperator( 'UnpackRNNSequence', ['values', 'lengths'], 'out' ) # Check against numpy reference self.assertReferenceChecks( device_option=gc, op=op, inputs=[values, lengths], reference=unpack_op, ) # Check over multiple devices self.assertDeviceChecks(dc, op, [values, lengths], [0]) # Gradient check self.assertGradientChecks(gc, op, [values, lengths], 0, [0]) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class TestLengthsTopKOps(hu.HypothesisTestCase): @given(N=st.integers(min_value=0, max_value=10), K=st.integers(min_value=1, max_value=10), **hu.gcs_cpu_only) def test_lengths_top_k_op(self, N, K, gc, dc): lens = np.random.randint(low=1, high=2 * K + 1, size=N).astype(np.int32) X = [] for i in lens: X.extend(map(lambda x: x / 100.0, range(0, 6 * i, 6))) X = np.array(X, dtype=np.float32) op = core.CreateOperator("LengthsTopK", ["X", "Y"], ["values", "indices"], k=K) def lengths_top_k(X, lens): N, si = lens.shape[0], 0 values, indices = [], [] for i in range(N): cur_indices = X[si:si + lens[i]].argsort()[-K:][::-1] cur_values = X[si:si + lens[i]][cur_indices] values.extend(cur_values) indices.extend(cur_indices) si += lens[i] if lens[i] < K: values.extend([0] * (K - lens[i])) indices.extend([-1] * (K - lens[i])) return (np.array(values, dtype=np.float32).reshape(-1, K), np.array(indices, dtype=np.int32).reshape(-1, K)) self.assertDeviceChecks(dc, op, [X, lens], [0, 1]) self.assertReferenceChecks(gc, op, [X, lens], lengths_top_k) self.assertGradientChecks(gc, op, [X, lens], 0, [0]) @given(N=st.integers(min_value=0, max_value=10), K=st.integers(min_value=1, max_value=10), **hu.gcs_cpu_only) def test_lengths_top_k_empty_op(self, N, K, gc, dc): lens = np.zeros((N, ), dtype=np.int32) X = np.array([], dtype=np.float32) op = core.CreateOperator("LengthsTopK", ["X", "Y"], ["values", "indices"], k=K) def lengths_top_k(X, lens): return (np.zeros((N, K), dtype=np.float32), -1 * np.ones((N, K), dtype=np.int32)) self.assertDeviceChecks(dc, op, [X, lens], [0, 1]) self.assertReferenceChecks(gc, op, [X, lens], lengths_top_k) self.assertGradientChecks(gc, op, [X, lens], 0, [0])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import hypothesis.strategies as st import caffe2.python.hypothesis_test_util as hu import numpy as np import unittest class TestSelu(hu.HypothesisTestCase): @given(X=hu.tensor(), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_selu_1(self, X, gc, dc, engine): alpha = 1.0 scale = 2.0 op = core.CreateOperator("Selu", ["X"], ["Y"], alpha=alpha, scale=scale, engine=engine) X = TestSelu.fix0(X) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) self.assertReferenceChecks( gc, op, [X], lambda x: TestSelu.selu_ref(x, alpha=alpha, scale=scale) ) @given(X=hu.tensor(), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_selu_2(self, X, gc, dc, engine): alpha = 1.6732 scale = 1.0507 op = core.CreateOperator("Selu", ["X"], ["Y"], alpha=alpha, scale=scale, engine=engine) X = TestSelu.fix0(X) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=1e-2, threshold=1e-2) self.assertReferenceChecks( gc, op, [X], lambda x: TestSelu.selu_ref(x, alpha=alpha, scale=scale) ) @given(X=hu.tensor(), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_selu_3(self, X, gc, dc, engine): alpha = 1.3 scale = 1.1 op = core.CreateOperator("Selu", ["X"], ["Y"], alpha=alpha, scale=scale, engine=engine) X = TestSelu.fix0(X) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) self.assertReferenceChecks( gc, op, [X], lambda x: TestSelu.selu_ref(x, alpha=alpha, scale=scale) ) @given(X=hu.tensor(), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_selu_inplace(self, X, gc, dc, engine): alpha = 1.3 scale = 1.1 op = core.CreateOperator("Selu", ["X"], ["X"], alpha=alpha, scale=scale, engine=engine) X = TestSelu.fix0(X) self.assertDeviceChecks(dc, op, [X], [0]) # inplace gradient Y = TestSelu.selu_ref(X, alpha=alpha, scale=scale) dX = np.ones_like(X) op2 = core.CreateOperator("SeluGradient", ["Y", "dX"], ["dX"], alpha=alpha, scale=scale, engine=engine) self.assertDeviceChecks(dc, op2, [Y, dX], [0]) @staticmethod def fix0(X): # go away from the origin point to avoid kink problems X += 0.02 * np.sign(X) X[X == 0.0] += 0.02 return X @staticmethod def selu_ref(x, scale, alpha): ret = scale * ((x > 0) * x + (x <= 0) * (alpha * (np.exp(x) - 1))) return [ret] if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class TestIndexHashOps(hu.HypothesisTestCase): @given( indices=st.sampled_from([ np.int32, np.int64 ]).flatmap(lambda dtype: hu.tensor(min_dim=1, max_dim=1, dtype=dtype)), seed=st.integers(min_value=0, max_value=10), modulo=st.integers(min_value=100000, max_value=200000), **hu.gcs_cpu_only ) def test_index_hash_ops(self, indices, seed, modulo, gc, dc): op = core.CreateOperator("IndexHash", ["indices"], ["hashed_indices"], seed=seed, modulo=modulo) def index_hash(indices): dtype = np.array(indices).dtype assert dtype == np.int32 or dtype == np.int64 hashed_indices = [] for index in indices: hashed = dtype.type(0xDEADBEEF * seed) indices_bytes = np.array([index], dtype).view(np.int8) for b in indices_bytes: hashed = dtype.type(hashed * 65537 + b) hashed = (modulo + hashed % modulo) % modulo hashed_indices.append(hashed) return [hashed_indices] self.assertDeviceChecks(dc, op, [indices], [0]) self.assertReferenceChecks(gc, op, [indices], index_hash) def test_shape_and_type_inference(self): with hu.temp_workspace("shape_type_inf_int64"): net = core.Net('test_net') net.ConstantFill( [], "values", shape=[64], dtype=core.DataType.INT64, ) net.IndexHash(['values'], ['values_output']) (shapes, types) = workspace.InferShapesAndTypes([net], {}) self.assertEqual(shapes["values_output"], [64]) self.assertEqual(types["values_output"], core.DataType.INT64) with hu.temp_workspace("shape_type_inf_int32"): net = core.Net('test_net') net.ConstantFill( [], "values", shape=[2, 32], dtype=core.DataType.INT32, ) net.IndexHash(['values'], ['values_output']) (shapes, types) = workspace.InferShapesAndTypes([net], {}) self.assertEqual(shapes["values_output"], [2, 32]) self.assertEqual(types["values_output"], core.DataType.INT32)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace import caffe2.python.hypothesis_test_util as hu import numpy as np class TestArgMaxOp(hu.HypothesisTestCase): def _test_op( self, op_name, original_inp, expected_values, ): op = core.CreateOperator( op_name, ['input'], ['output'], ) workspace.FeedBlob('input', np.array(original_inp, dtype=np.float32)) workspace.RunOperatorOnce(op) np.testing.assert_array_equal( workspace.FetchBlob('output'), np.array(expected_values), ) def test_rowwise_argmax_op_with_large_input(self): X = [[1, 2, 3, 100, 3, 2, 1, 1.5, 1, 1, 1, 1, 1, 1.0], [1, 2, 3, 1, 3, 2, 1, 1.5, 1, 100, 1, 1, 1, 1.0], [1, 2, 3, 1, 3, 2, 1, 1.5, 1, 1, 100, 1, 1, 1.0], [1, 2, 3, 1, 3, 2, 1, 1.5, 1, 1, 1, 100, 1, 1.0], [1, 2, 3, 1, 3, 2, 1, 1.5, 1, 1, 1, 1, 100, 1.0], [100, 2, 3, 1, 3, 2, 1, 1.5, 1, 1, 1, 1, 1, 1.0], [1, 2, 3, 100, 3, 2, 1, 1.5, 1, 1, 1, 1, 1, 1.0], [1, 2, 3, 1, 3, 2, 100, 1.5, 1, 1, 1, 1, 1, 1.0]] self._test_op( op_name='RowWiseArgMax', original_inp=X, expected_values=[[3], [9], [10], [11], [12], [0], [3], [6]], ) def test_rowwise_argmax_op_with_small_input(self): X = [[4.2, 6, 3.1], [10, 20, 40.4], [100.01, 25, 3]] self._test_op( op_name='RowWiseArgMax', original_inp=X, expected_values=[[1], [2], [0]], ) def test_rowwise_argmax_with_duplicate_values(self): X = [[2, 2], [3, 3]] self._test_op( op_name='RowWiseArgMax', original_inp=X, expected_values=[[0], [0]], ) def test_rowwise_argmax_with_1x1_tensor(self): X = [[1]] self._test_op( op_name='RowWiseArgMax', original_inp=X, expected_values=[[0]], ) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import numpy as np import datetime from caffe2.python import core, workspace DTYPES = { 'uint8': np.uint8, 'uint8_fused': np.uint8, 'float': np.float32, 'float16': np.float16, } def benchmark_sparse_lengths_sum( dtype_str, categorical_limit, embedding_size, average_len, batch_size, iterations): print('Preparing lookup table. ' + str(datetime.datetime.now())) # We will use a constant, but non-trivial value so we save initialization # time. data = np.ones([categorical_limit, embedding_size], dtype=np.float32) data *= 17.01 if dtype_str == 'uint8': scale_bias = np.random.rand(categorical_limit, 2).astype(np.float32) workspace.FeedBlob("scale_bias", scale_bias.astype(np.float32)) elif dtype_str == 'uint8_fused': scale_bias = np.random.randint(255, size=(categorical_limit, 8)) data = np.concatenate([data, scale_bias], axis=1) print('Data has shape {} {}'.format(data.shape, datetime.datetime.now())) workspace.FeedBlob("X", data.astype(DTYPES[dtype_str])) # In order to produce truly random lengths and indices, we will embed a # Python operator in the net to generate them. def f(_, outputs): lengths = np.random.randint( int(average_len * 0.75), int(average_len * 1.25), batch_size).astype(np.int32) indices = np.random.randint( 0, categorical_limit, np.sum(lengths)).astype(np.int64) outputs[0].feed(indices) outputs[1].feed(lengths) net = core.Net("mynet") net.Python(f)([], ["indices", "lengths", ]) if dtype_str == "uint8": net.SparseLengthsSum8BitsRowwise(["X", "indices", "lengths", "scale_bias"], "Y") elif dtype_str == "uint8_fused": net.SparseLengthsSumFused8BitRowwise(["X", "indices", "lengths"], "Y") else: net.SparseLengthsSum(["X", "indices", "lengths"], "Y") workspace.CreateNet(net) # Set random seed, so that repeated runs will keep the same sequence of # random indices. np.random.seed(1701) print('Preparation finished. ' + str(datetime.datetime.now())) workspace.BenchmarkNet(net.Name(), 1, iterations, True) if __name__ == "__main__": parser = argparse.ArgumentParser( description="minimal benchmark for sparse lengths sum.") parser.add_argument( '-d', "--dtype", choices=list(DTYPES.keys()), default="float", help="The data type for the input lookup table.") parser.add_argument( '-e', "--embedding-size", type=int, default=6000000, help="Lookup table size.") parser.add_argument( "--embedding-dim", type=int, default=128, help="Embedding dimension.") parser.add_argument( "--average_len", type=int, default=27, help="Sparse feature average lengths, default is 27") parser.add_argument( "--batch_size", type=int, default=100, help="The batch size.") parser.add_argument( '-i', "--iteration", type=int, default=100000, help="The number of iterations.") args, extra_args = parser.parse_known_args() core.GlobalInit(['python'] + extra_args) benchmark_sparse_lengths_sum( args.dtype, args.embedding_size, args.embedding_dim, args.average_len, args.batch_size, args.iteration)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import functools import hypothesis from hypothesis import given, settings, HealthCheck import hypothesis.strategies as st import numpy as np from caffe2.python import core import caffe2.python.hypothesis_test_util as hu class TestAdagrad(hu.HypothesisTestCase): @staticmethod def ref_adagrad(param_in, mom_in, grad, lr, epsilon, using_fp16=False): mom_in_f32 = mom_in param_in_f32 = param_in if(using_fp16): mom_in_f32 = mom_in.astype(np.float32) param_in_f32 = param_in.astype(np.float32) mom_out = mom_in_f32 + np.square(grad) grad_adj = lr * grad / (np.sqrt(mom_out) + epsilon) param_out = param_in_f32 + grad_adj if(using_fp16): return (param_out.astype(np.float16), mom_out.astype(np.float16)) else: return (param_out.astype(np.float32), mom_out.astype(np.float32)) @staticmethod def ref_row_wise_adagrad(param_in, mom_in, grad, lr, epsilon): mom_out = mom_in + np.mean(np.square(grad)) grad_adj = lr * grad / (np.sqrt(mom_out) + epsilon) param_out = param_in + grad_adj return (param_out, mom_out) @given(inputs=hu.tensors(n=3), lr=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), epsilon=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), **hu.gcs) def test_adagrad(self, inputs, lr, epsilon, gc, dc): param, momentum, grad = inputs lr = np.array([lr], dtype=np.float32) op = core.CreateOperator( "Adagrad", ["param", "momentum", "grad", "lr"], ["param", "momentum"], epsilon=epsilon, device_option=gc, ) self.assertReferenceChecks( gc, op, [param, momentum, grad, lr], functools.partial(self.ref_adagrad, epsilon=epsilon)) # Suppress filter_too_much health check. # Likely caused by `assume` call falling through too often. @settings(suppress_health_check=[HealthCheck.filter_too_much]) @given(inputs=hu.tensors(n=3), lr=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), epsilon=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), data_strategy=st.data(), **hu.gcs) def test_sparse_adagrad(self, inputs, lr, epsilon, data_strategy, gc, dc): param, momentum, grad = inputs momentum = np.abs(momentum) lr = np.array([lr], dtype=np.float32) # Create an indexing array containing values that are lists of indices, # which index into grad indices = data_strategy.draw( hu.tensor(dtype=np.int64, elements=st.sampled_from(np.arange(grad.shape[0]))), ) hypothesis.note('indices.shape: %s' % str(indices.shape)) # For now, the indices must be unique hypothesis.assume(np.array_equal(np.unique(indices.flatten()), np.sort(indices.flatten()))) # Sparsify grad grad = grad[indices] op = core.CreateOperator( "SparseAdagrad", ["param", "momentum", "indices", "grad", "lr"], ["param", "momentum"], epsilon=epsilon, device_option=gc) def ref_sparse(param, momentum, indices, grad, lr, ref_using_fp16=False): param_out = np.copy(param) momentum_out = np.copy(momentum) for i, index in enumerate(indices): param_out[index], momentum_out[index] = self.ref_adagrad( param[index], momentum[index], grad[i], lr, epsilon, using_fp16=ref_using_fp16 ) return (param_out, momentum_out) ref_using_fp16_values = [False] if dc == hu.gpu_do: ref_using_fp16_values.append(True) for ref_using_fp16 in ref_using_fp16_values: if(ref_using_fp16): print('test_sparse_adagrad with half precision embedding') momentum_i = momentum.astype(np.float16) param_i = param.astype(np.float16) else: print('test_sparse_adagrad with full precision embedding') momentum_i = momentum.astype(np.float32) param_i = param.astype(np.float32) self.assertReferenceChecks( gc, op, [param_i, momentum_i, indices, grad, lr, ref_using_fp16], ref_sparse ) @given(inputs=hu.tensors(n=2), lr=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), epsilon=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), data_strategy=st.data(), **hu.gcs) def test_sparse_adagrad_empty(self, inputs, lr, epsilon, data_strategy, gc, dc): param, momentum = inputs momentum = np.abs(momentum) lr = np.array([lr], dtype=np.float32) grad = np.empty(shape=(0,) + param.shape[1:], dtype=np.float32) indices = np.empty(shape=(0,), dtype=np.int64) hypothesis.note('indices.shape: %s' % str(indices.shape)) op = core.CreateOperator( "SparseAdagrad", ["param", "momentum", "indices", "grad", "lr"], ["param", "momentum"], epsilon=epsilon, device_option=gc) def ref_sparse(param, momentum, indices, grad, lr): param_out = np.copy(param) momentum_out = np.copy(momentum) return (param_out, momentum_out) ref_using_fp16_values = [False] if dc == hu.gpu_do: ref_using_fp16_values.append(True) for ref_using_fp16 in ref_using_fp16_values: if(ref_using_fp16): print('test_sparse_adagrad_empty with half precision embedding') momentum_i = momentum.astype(np.float16) param_i = param.astype(np.float16) else: print('test_sparse_adagrad_empty with full precision embedding') momentum_i = momentum.astype(np.float32) param_i = param.astype(np.float32) self.assertReferenceChecks( gc, op, [param_i, momentum_i, indices, grad, lr], ref_sparse ) # Suppress filter_too_much health check. # Likely caused by `assume` call falling through too often. @settings(suppress_health_check=[HealthCheck.filter_too_much]) @given(inputs=hu.tensors(n=2), lr=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), epsilon=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), data_strategy=st.data(), **hu.gcs) def test_row_wise_sparse_adagrad(self, inputs, lr, epsilon, data_strategy, gc, dc): param, grad = inputs lr = np.array([lr], dtype=np.float32) # Create a 1D row-wise average sum of squared gradients tensor. momentum = data_strategy.draw( hu.tensor1d(min_len=param.shape[0], max_len=param.shape[0], elements=hu.elements_of_type(dtype=np.float32)) ) momentum = np.abs(momentum) # Create an indexing array containing values which index into grad indices = data_strategy.draw( hu.tensor(dtype=np.int64, elements=st.sampled_from(np.arange(grad.shape[0]))), ) # Note that unlike SparseAdagrad, RowWiseSparseAdagrad uses a moment # tensor that is strictly 1-dimensional and equal in length to the # first dimension of the parameters, so indices must also be # 1-dimensional. indices = indices.flatten() hypothesis.note('indices.shape: %s' % str(indices.shape)) # The indices must be unique hypothesis.assume(np.array_equal(np.unique(indices), np.sort(indices))) # Sparsify grad grad = grad[indices] op = core.CreateOperator( "RowWiseSparseAdagrad", ["param", "momentum", "indices", "grad", "lr"], ["param", "momentum"], epsilon=epsilon, device_option=gc) def ref_row_wise_sparse(param, momentum, indices, grad, lr): param_out = np.copy(param) momentum_out = np.copy(momentum) for i, index in enumerate(indices): param_out[index], momentum_out[index] = self.ref_row_wise_adagrad( param[index], momentum[index], grad[i], lr, epsilon) return (param_out, momentum_out) self.assertReferenceChecks( gc, op, [param, momentum, indices, grad, lr], ref_row_wise_sparse) @given(inputs=hu.tensors(n=1), lr=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), epsilon=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), data_strategy=st.data(), **hu.gcs) def test_row_wise_sparse_adagrad_empty(self, inputs, lr, epsilon, data_strategy, gc, dc): param = inputs[0] lr = np.array([lr], dtype=np.float32) momentum = data_strategy.draw( hu.tensor1d(min_len=param.shape[0], max_len=param.shape[0], elements=hu.elements_of_type(dtype=np.float32)) ) momentum = np.abs(momentum) grad = np.empty(shape=(0,) + param.shape[1:], dtype=np.float32) indices = np.empty(shape=(0,), dtype=np.int64) hypothesis.note('indices.shape: %s' % str(indices.shape)) op = core.CreateOperator( "RowWiseSparseAdagrad", ["param", "momentum", "indices", "grad", "lr"], ["param", "momentum"], epsilon=epsilon, device_option=gc) def ref_row_wise_sparse(param, momentum, indices, grad, lr): param_out = np.copy(param) momentum_out = np.copy(momentum) return (param_out, momentum_out) self.assertReferenceChecks( gc, op, [param, momentum, indices, grad, lr], ref_row_wise_sparse)
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import hypothesis.strategies as st import unittest import caffe2.python.hypothesis_test_util as hu from caffe2.python import core from hypothesis import given class TestPad(hu.HypothesisTestCase): @given(pad_t=st.integers(-5, 0), pad_l=st.integers(-5, 0), pad_b=st.integers(-5, 0), pad_r=st.integers(-5, 0), mode=st.sampled_from(["constant", "reflect", "edge"]), size_w=st.integers(16, 128), size_h=st.integers(16, 128), size_c=st.integers(1, 4), size_n=st.integers(1, 4), **hu.gcs) def test_crop(self, pad_t, pad_l, pad_b, pad_r, mode, size_w, size_h, size_c, size_n, gc, dc): op = core.CreateOperator( "PadImage", ["X"], ["Y"], pad_t=pad_t, pad_l=pad_l, pad_b=pad_b, pad_r=pad_r, ) X = np.random.rand( size_n, size_c, size_h, size_w).astype(np.float32) def ref(X): return (X[:, :, -pad_t:pad_b or None, -pad_l:pad_r or None],) self.assertReferenceChecks(gc, op, [X], ref) self.assertDeviceChecks(dc, op, [X], [0]) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import workspace, core, scope, gru_cell from caffe2.python.model_helper import ModelHelper from caffe2.python.rnn.rnn_cell_test_util import sigmoid, tanh, _prepare_rnn import caffe2.python.hypothesis_test_util as hu from caffe2.proto import caffe2_pb2 from functools import partial from hypothesis import given from hypothesis import settings as ht_settings import hypothesis.strategies as st import numpy as np import unittest def gru_unit(*args, **kwargs): ''' Implements one GRU unit, for one time step Shapes: hidden_t_prev.shape = (1, N, D) gates_out_t.shape = (1, N, G) seq_lenths.shape = (N,) ''' drop_states = kwargs.get('drop_states', False) sequence_lengths = kwargs.get('sequence_lengths', True) if sequence_lengths: hidden_t_prev, gates_out_t, seq_lengths, timestep = args else: hidden_t_prev, gates_out_t, timestep = args N = hidden_t_prev.shape[1] D = hidden_t_prev.shape[2] G = gates_out_t.shape[2] t = (timestep * np.ones(shape=(N, D))).astype(np.int32) assert t.shape == (N, D) assert G == 3 * D # Calculate reset, update, and output gates separately # because output gate depends on reset gate. gates_out_t = gates_out_t.reshape(N, 3, D) reset_gate_t = gates_out_t[:, 0, :].reshape(N, D) update_gate_t = gates_out_t[:, 1, :].reshape(N, D) output_gate_t = gates_out_t[:, 2, :].reshape(N, D) # Calculate gate outputs. reset_gate_t = sigmoid(reset_gate_t) update_gate_t = sigmoid(update_gate_t) output_gate_t = tanh(output_gate_t) if sequence_lengths: seq_lengths = (np.ones(shape=(N, D)) * seq_lengths.reshape(N, 1)).astype(np.int32) assert seq_lengths.shape == (N, D) valid = (t < seq_lengths).astype(np.int32) else: valid = np.ones(shape=(N, D)) assert valid.shape == (N, D) hidden_t = update_gate_t * hidden_t_prev + (1 - update_gate_t) * output_gate_t hidden_t = hidden_t * valid + hidden_t_prev * (1 - valid) * (1 - drop_states) hidden_t = hidden_t.reshape(1, N, D) return (hidden_t, ) def gru_reference(input, hidden_input, reset_gate_w, reset_gate_b, update_gate_w, update_gate_b, output_gate_w, output_gate_b, seq_lengths, drop_states=False, linear_before_reset=False): D = hidden_input.shape[hidden_input.ndim - 1] T = input.shape[0] N = input.shape[1] G = input.shape[2] print("Dimensions: T= ", T, " N= ", N, " G= ", G, " D= ", D) hidden = np.zeros(shape=(T + 1, N, D)) hidden[0, :, :] = hidden_input for t in range(T): input_t = input[t].reshape(1, N, G) hidden_t_prev = hidden[t].reshape(1, N, D) # Split input contributions for three gates. input_t = input_t.reshape(N, 3, D) input_reset = input_t[:, 0, :].reshape(N, D) input_update = input_t[:, 1, :].reshape(N, D) input_output = input_t[:, 2, :].reshape(N, D) reset_gate = np.dot(hidden_t_prev, reset_gate_w.T) + reset_gate_b reset_gate = reset_gate + input_reset update_gate = np.dot(hidden_t_prev, update_gate_w.T) + update_gate_b update_gate = update_gate + input_update if linear_before_reset: with_linear = np.dot(hidden_t_prev, output_gate_w.T) + output_gate_b output_gate = sigmoid(reset_gate) * with_linear else: with_reset = hidden_t_prev * sigmoid(reset_gate) output_gate = np.dot(with_reset, output_gate_w.T) + output_gate_b output_gate = output_gate + input_output gates_out_t = np.concatenate( (reset_gate, update_gate, output_gate), axis=2, ) print(reset_gate, update_gate, output_gate, gates_out_t, sep="\n") (hidden_t, ) = gru_unit( hidden_t_prev, gates_out_t, seq_lengths, t, drop_states=drop_states ) hidden[t + 1] = hidden_t return ( hidden[1:], hidden[-1].reshape(1, N, D), ) def gru_unit_op_input(): ''' Create input tensor where each dimension is from 1 to 4, ndim=3 and last dimension size is a factor of 3 hidden_t_prev.shape = (1, N, D) ''' dims_ = st.tuples( st.integers(min_value=1, max_value=1), # 1, one timestep st.integers(min_value=1, max_value=4), # n st.integers(min_value=1, max_value=4), # d ) def create_input(dims): dims = list(dims) dims[2] *= 3 return hu.arrays(dims) return dims_.flatmap(create_input) def gru_input(): ''' Create input tensor where each dimension is from 1 to 4, ndim=3 and last dimension size is a factor of 3 ''' dims_ = st.tuples( st.integers(min_value=1, max_value=4), # t st.integers(min_value=1, max_value=4), # n st.integers(min_value=1, max_value=4), # d ) def create_input(dims): dims = list(dims) dims[2] *= 3 return hu.arrays(dims) return dims_.flatmap(create_input) def _prepare_gru_unit_op(gc, n, d, outputs_with_grads, forward_only=False, drop_states=False, sequence_lengths=False, two_d_initial_states=None): print("Dims: (n,d) = ({},{})".format(n, d)) def generate_input_state(n, d): if two_d_initial_states: return np.random.randn(n, d).astype(np.float32) else: return np.random.randn(1, n, d).astype(np.float32) model = ModelHelper(name='external') with scope.NameScope("test_name_scope"): if sequence_lengths: hidden_t_prev, gates_t, seq_lengths, timestep = \ model.net.AddScopedExternalInputs( "hidden_t_prev", "gates_t", 'seq_lengths', "timestep", ) else: hidden_t_prev, gates_t, timestep = \ model.net.AddScopedExternalInputs( "hidden_t_prev", "gates_t", "timestep", ) workspace.FeedBlob( hidden_t_prev, generate_input_state(n, d).astype(np.float32), device_option=gc ) workspace.FeedBlob( gates_t, generate_input_state(n, 3 * d).astype(np.float32), device_option=gc ) if sequence_lengths: inputs = [hidden_t_prev, gates_t, seq_lengths, timestep] else: inputs = [hidden_t_prev, gates_t, timestep] hidden_t = model.net.GRUUnit( inputs, ['hidden_t'], forget_bias=0.0, drop_states=drop_states, sequence_lengths=sequence_lengths, ) model.net.AddExternalOutputs(hidden_t) workspace.RunNetOnce(model.param_init_net) if sequence_lengths: # 10 is used as a magic number to simulate some reasonable timestep # and generate some reasonable seq. lengths workspace.FeedBlob( seq_lengths, np.random.randint(1, 10, size=(n,)).astype(np.int32), device_option=gc ) workspace.FeedBlob( timestep, np.random.randint(1, 10, size=(1,)).astype(np.int32), device_option=core.DeviceOption(caffe2_pb2.CPU), ) print("Feed {}".format(timestep)) return hidden_t, model.net class GRUCellTest(hu.HypothesisTestCase): # Test just for GRUUnitOp @given( seed=st.integers(0, 2**32 - 1), input_tensor=gru_unit_op_input(), fwd_only=st.booleans(), drop_states=st.booleans(), sequence_lengths=st.booleans(), **hu.gcs ) @ht_settings(max_examples=15) def test_gru_unit_op(self, seed, input_tensor, fwd_only, drop_states, sequence_lengths, gc, dc): np.random.seed(seed) outputs_with_grads = [0] ref = gru_unit ref = partial(ref) t, n, d = input_tensor.shape assert d % 3 == 0 d = d // 3 ref = partial(ref, drop_states=drop_states, sequence_lengths=sequence_lengths) with core.DeviceScope(gc): net = _prepare_gru_unit_op(gc, n, d, outputs_with_grads=outputs_with_grads, forward_only=fwd_only, drop_states=drop_states, sequence_lengths=sequence_lengths)[1] # here we don't provide a real input for the net but just for one of # its ops (RecurrentNetworkOp). So have to hardcode this name workspace.FeedBlob("test_name_scope/external/recurrent/i2h", input_tensor, device_option=gc) print(str(net.Proto())) op = net._net.op[-1] inputs = [workspace.FetchBlob(name) for name in op.input] self.assertReferenceChecks( gc, op, inputs, ref, input_device_options={op.input[-1]: hu.cpu_do}, outputs_to_check=[0], ) # Checking for hidden_prev and gates gradients if not fwd_only: for param in range(2): print("Check param {}".format(param)) self.assertGradientChecks( device_option=gc, op=op, inputs=inputs, outputs_to_check=param, outputs_with_grads=outputs_with_grads, threshold=0.0001, stepsize=0.005, input_device_options={op.input[-1]: hu.cpu_do}, ) @given( seed=st.integers(0, 2**32 - 1), input_tensor=gru_input(), fwd_only=st.booleans(), drop_states=st.booleans(), linear_before_reset=st.booleans(), **hu.gcs ) @ht_settings(max_examples=20) def test_gru_main(self, seed, **kwargs): np.random.seed(seed) for outputs_with_grads in [[0], [1], [0, 1]]: self.gru_base(gru_cell.GRU, gru_reference, outputs_with_grads=outputs_with_grads, **kwargs) def gru_base(self, create_rnn, ref, outputs_with_grads, input_tensor, fwd_only, drop_states, linear_before_reset, gc, dc): print("GRU test parameters: ", locals()) t, n, d = input_tensor.shape assert d % 3 == 0 d = d // 3 ref = partial(ref, drop_states=drop_states, linear_before_reset=linear_before_reset) with core.DeviceScope(gc): net = _prepare_rnn( t, n, d, create_rnn, outputs_with_grads=outputs_with_grads, memory_optim=False, forget_bias=0.0, forward_only=fwd_only, drop_states=drop_states, linear_before_reset=linear_before_reset, num_states=1, )[1] # here we don't provide a real input for the net but just for one of # its ops (RecurrentNetworkOp). So have to hardcode this name workspace.FeedBlob("test_name_scope/external/recurrent/i2h", input_tensor, device_option=gc) op = net._net.op[-1] inputs = [workspace.FetchBlob(name) for name in op.input] self.assertReferenceChecks( gc, op, inputs, ref, input_device_options={"timestep": hu.cpu_do}, outputs_to_check=list(range(2)), ) # Checking for input, gates_t_w and gates_t_b gradients if not fwd_only: for param in range(2): print("Check param {}".format(param)) self.assertGradientChecks( device_option=gc, op=op, inputs=inputs, outputs_to_check=param, outputs_with_grads=outputs_with_grads, threshold=0.001, stepsize=0.005, input_device_options={"timestep": hu.cpu_do}, ) if __name__ == "__main__": workspace.GlobalInit([ 'caffe2', '--caffe2_log_level=0', ]) unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import hypothesis from hypothesis import given, settings, HealthCheck import hypothesis.strategies as st import numpy as np from caffe2.python import core import caffe2.python.hypothesis_test_util as hu class TestSparseNormalize(hu.HypothesisTestCase): @staticmethod def ref_normalize(param_in, use_max_norm, norm): param_norm = np.linalg.norm(param_in) + 1e-12 if (use_max_norm and param_norm > norm) or not use_max_norm: param_in = param_in * norm / param_norm return param_in # Suppress filter_too_much health check. # Likely caused by `assume` call falling through too often. @settings(suppress_health_check=[HealthCheck.filter_too_much]) @given(inputs=hu.tensors(n=2, min_dim=2, max_dim=2), use_max_norm=st.booleans(), norm=st.floats(min_value=1.0, max_value=4.0), data_strategy=st.data(), **hu.gcs_cpu_only) def test_sparse_normalize(self, inputs, use_max_norm, norm, data_strategy, gc, dc): param, grad = inputs param += 0.02 * np.sign(param) param[param == 0.0] += 0.02 # Create an indexing array containing values that are lists of indices, # which index into grad indices = data_strategy.draw( hu.tensor(dtype=np.int64, min_dim=1, max_dim=1, elements=st.sampled_from(np.arange(grad.shape[0]))), ) hypothesis.note('indices.shape: %s' % str(indices.shape)) # For now, the indices must be unique hypothesis.assume(np.array_equal(np.unique(indices.flatten()), np.sort(indices.flatten()))) # Sparsify grad grad = grad[indices] op = core.CreateOperator( "SparseNormalize", ["param", "indices", "grad"], ["param"], use_max_norm=use_max_norm, norm=norm, ) def ref_sparse_normalize(param, indices, grad): param_out = np.copy(param) for _, index in enumerate(indices): param_out[index] = self.ref_normalize( param[index], use_max_norm, norm, ) return (param_out,) # self.assertDeviceChecks(dc, op, [param, indices, grad], [0]) self.assertReferenceChecks( gc, op, [param, indices, grad], ref_sparse_normalize )
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import hypothesis.strategies as st import numpy as np from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu class TestArgOps(hu.HypothesisTestCase): def argmax_ref(self, X, axis, keepdims): indices = np.argmax(X, axis=axis) if keepdims: out_dims = list(X.shape) out_dims[axis] = 1 indices = indices.reshape(tuple(out_dims)) return [indices] @given(X=hu.tensor(dtype=np.float32), axis=st.integers(-1, 5), keepdims=st.booleans(), **hu.gcs) def test_argmax(self, X, axis, keepdims, gc, dc): if axis >= len(X.shape): axis %= len(X.shape) op = core.CreateOperator( "ArgMax", ["X"], ["Indices"], axis=axis, keepdims=keepdims, device_option=gc) def argmax_ref(X): indices = np.argmax(X, axis=axis) if keepdims: out_dims = list(X.shape) out_dims[axis] = 1 indices = indices.reshape(tuple(out_dims)) return [indices] self.assertReferenceChecks(gc, op, [X], argmax_ref) self.assertDeviceChecks(dc, op, [X], [0]) @given(X=hu.tensor(dtype=np.float32), axis=st.integers(-1, 5), keepdims=st.booleans(), **hu.gcs) def test_argmin(self, X, axis, keepdims, gc, dc): if axis >= len(X.shape): axis %= len(X.shape) op = core.CreateOperator( "ArgMin", ["X"], ["Indices"], axis=axis, keepdims=keepdims, device_option=gc) def argmin_ref(X): indices = np.argmin(X, axis=axis) if keepdims: out_dims = list(X.shape) out_dims[axis] = 1 indices = indices.reshape(tuple(out_dims)) return [indices] self.assertReferenceChecks(gc, op, [X], argmin_ref) self.assertDeviceChecks(dc, op, [X], [0]) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import core, workspace from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import hypothesis.extra.numpy as hnp class TestGatherOps(hu.HypothesisTestCase): @given(rows_num=st.integers(1, 10000), index_num=st.integers(0, 5000), **hu.gcs) def test_gather_ops(self, rows_num, index_num, gc, dc): data = np.random.random((rows_num, 10, 20)).astype(np.float32) ind = np.random.randint(rows_num, size=(index_num, )).astype('int32') op = core.CreateOperator( 'Gather', ['data', 'ind'], ['output']) def ref_gather(data, ind): if ind.size == 0: return [np.zeros((0, 10, 20)).astype(np.float32)] output = [r for r in [data[i] for i in ind]] return [output] self.assertReferenceChecks(gc, op, [data, ind], ref_gather) @st.composite def _inputs(draw): rows_num = draw(st.integers(1, 100)) index_num = draw(st.integers(1, 10)) batch_size = draw(st.integers(2, 10)) return ( draw(hnp.arrays( np.float32, (batch_size, rows_num, 2), elements=st.floats(-10.0, 10.0), )), draw(hnp.arrays( np.int32, (index_num, 1), elements=st.integers(0, rows_num - 1), )), ) class TestBatchGatherOps(hu.HypothesisTestCase): @given(inputs=_inputs(), **hu.gcs) def test_batch_gather_ops(self, inputs, gc, dc): data, ind = inputs op = core.CreateOperator( 'BatchGather', ['data', 'ind'], ['output']) def ref_batch_gather(data, ind): output = [] for b in range(data.shape[0]): output.append([r for r in [data[b][i] for i in ind]]) return [output] self.assertReferenceChecks(gc, op, [data, ind], ref_batch_gather) self.assertGradientChecks(gc, op, [data, ind], 0, [0]) class TestGatherFused8BitRowwise(hu.HypothesisTestCase): @given(rows_num=st.integers(1, 10000), cols_num=st.integers(1, 128), index_num=st.integers(0, 5000), **hu.gcs) def test_batch_gather_ops(self, rows_num, cols_num, index_num, gc, dc): data = np.random.random((rows_num, cols_num)).astype(np.float32) ind = np.random.randint(rows_num, size=(index_num, )).astype('int32') net = core.Net("bench") quantized_data = net.FloatToFused8BitRowwiseQuantized( 'data', 'quantized_data') dequantized_data = net.Fused8BitRowwiseQuantizedToFloat( quantized_data, 'dequantized_data') net.Gather( [dequantized_data, 'ind'], 'gather_reference') net.GatherFused8BitRowwise( [quantized_data, 'ind'], 'gather_quantized') workspace.FeedBlob('data', data) workspace.FeedBlob('ind', ind) workspace.CreateNet(net) workspace.RunNetOnce(net) gather_reference = workspace.FetchBlob('gather_reference') gather_quantized = workspace.FetchBlob('gather_quantized') np.testing.assert_array_almost_equal(gather_reference, gather_quantized) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import functools import numpy as np from hypothesis import assume, given import hypothesis.strategies as st from caffe2.proto import caffe2_pb2 from caffe2.python import brew, core, workspace import caffe2.python.hypothesis_test_util as hu from caffe2.python.model_helper import ModelHelper def _cudnn_supports( dilation=False, nhwc=False, backward=False, ): """Return True if cuDNN supports this configuration.""" v = workspace.GetCuDNNVersion() if backward: if nhwc: # nhwc isn't supported in backward ops. return False else: # Forward mode. if dilation and v < 6000: # Dilation not supported until v6 return False if dilation and nhwc: # Dilation and NHWC not supported together return False return True class TestConvolution(hu.HypothesisTestCase): # CUDNN does NOT support different padding values and we skip it @given(op_type=st.sampled_from(["Conv", "Conv2D"]), stride_h=st.integers(1, 3), stride_w=st.integers(1, 3), pad_t=st.integers(0, 3), pad_l=st.integers(0, 3), pad_b=st.integers(0, 3), pad_r=st.integers(0, 3), kernel=st.integers(3, 5), size=st.integers(1, 8), input_channels=st.integers(1, 3), output_channels=st.integers(1, 3), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), engine=st.sampled_from(["", "EIGEN"]), shared_buffer=st.booleans(), use_bias=st.booleans(), **hu.gcs) def test_convolution_separate_stride_pad_gradients(self, op_type, stride_h, stride_w, pad_t, pad_l, pad_b, pad_r, kernel, size, input_channels, output_channels, batch_size, order, engine, shared_buffer, use_bias, gc, dc): op = core.CreateOperator( op_type, ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], stride_h=stride_h, stride_w=stride_w, pad_t=pad_t, pad_l=pad_l, pad_b=pad_b, pad_r=pad_r, kernel=kernel, order=order, engine=engine, shared_buffer=int(shared_buffer), ) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( output_channels, kernel, kernel, input_channels).astype(np.float32)\ - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 if order == "NCHW": X = X.transpose((0, 3, 1, 2)) w = w.transpose((0, 3, 1, 2)) inputs = [X, w, b] if use_bias else [X, w] # Error handling path. if size + pad_r + pad_l < kernel or size + pad_t + pad_b < kernel: with self.assertRaises(RuntimeError): self.assertDeviceChecks(dc, op, inputs, [0]) return self.assertDeviceChecks(dc, op, inputs, [0]) for i in range(len(inputs)): self.assertGradientChecks(gc, op, inputs, i, [0]) # CUDNN does NOT support different padding values and we skip it @given(op_type=st.sampled_from(["Conv", "Conv2D"]), stride_h=st.integers(1, 3), stride_w=st.integers(1, 3), pad_t=st.integers(0, 3), pad_l=st.integers(0, 3), pad_b=st.integers(0, 3), pad_r=st.integers(0, 3), kernel=st.integers(1, 5), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), engine=st.sampled_from(["", "EIGEN"]), use_bias=st.booleans(), **hu.gcs) def test_convolution_separate_stride_pad_layout(self, op_type, stride_h, stride_w, pad_t, pad_l, pad_b, pad_r, kernel, size, input_channels, output_channels, batch_size, engine, use_bias, gc, dc): X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( output_channels, kernel, kernel, input_channels).astype(np.float32)\ - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 outputs = {} for order in ["NCHW", "NHWC"]: op = core.CreateOperator( op_type, ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], stride_h=stride_h, stride_w=stride_w, kernel=kernel, pad_t=pad_t, pad_l=pad_l, pad_b=pad_b, pad_r=pad_r, order=order, engine=engine, device_option=gc, ) if order == "NCHW": X_f = X.transpose((0, 3, 1, 2)) w_f = w.transpose((0, 3, 1, 2)) else: X_f = X w_f = w self.ws.create_blob("X").feed(X_f, device_option=gc) self.ws.create_blob("w").feed(w_f, device_option=gc) self.ws.create_blob("b").feed(b, device_option=gc) self.ws.run(op) outputs[order] = self.ws.blobs["Y"].fetch() np.testing.assert_allclose( outputs["NCHW"], outputs["NHWC"].transpose((0, 3, 1, 2)), atol=1e-4, rtol=1e-4) @given(op_type=st.sampled_from(["Conv", "Conv2D"]), stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), dilation=st.integers(1, 3), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), engine=st.sampled_from(["", "CUDNN", "MKLDNN"]), use_bias=st.booleans(), **hu.gcs) def test_convolution_gradients(self, op_type, stride, pad, kernel, dilation, size, input_channels, output_channels, batch_size, order, engine, use_bias, gc, dc): dkernel = dilation * (kernel - 1) + 1 if engine == 'CUDNN': assume(_cudnn_supports(dilation=(dilation > 1), nhwc=(order == 'NHWC'), backward=True)) assume(engine != "MKLDNN" or use_bias is True) op = core.CreateOperator( op_type, ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], stride=stride, kernel=kernel, dilation=dilation, pad=pad, order=order, engine=engine, ) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( output_channels, kernel, kernel, input_channels).astype(np.float32)\ - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 if order == "NCHW": X = X.transpose((0, 3, 1, 2)) w = w.transpose((0, 3, 1, 2)) inputs = [X, w, b] if use_bias else [X, w] # Error handling path. if size + pad + pad < dkernel or size + pad + pad < dkernel: with self.assertRaises(RuntimeError): self.assertDeviceChecks(dc, op, inputs, [0]) return self.assertDeviceChecks(dc, op, inputs, [0]) for i in range(len(inputs)): self.assertGradientChecks(gc, op, inputs, i, [0]) def _nd_convolution_nchw(self, n, input_channels, output_channels, batch_size, stride, size, kernel, dilation, pad, use_bias, gc, dc): dkernel = dilation * (kernel - 1) + 1 for op_type in ["Conv", "Conv" + str(n) + "D"]: op = core.CreateOperator( op_type, ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], strides=[stride] * n, kernels=[kernel] * n, dilations=[dilation] * n, pads=[pad] * n * 2, order="NCHW", engine="", ) input_dims = [batch_size, input_channels] input_dims.extend([size] * n) filter_dims = [output_channels, input_channels] filter_dims.extend([kernel] * n) X = np.random.rand(*input_dims).astype(np.float32) - 0.5 w = np.random.rand(*filter_dims).astype(np.float32) - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 inputs = [X, w, b] if use_bias else [X, w] if size + pad + pad < dkernel or size + pad + pad < dkernel: with self.assertRaises(RuntimeError): self.assertDeviceChecks(dc, op, inputs, [0]) return self.assertDeviceChecks(dc, op, inputs, [0]) for i in range(len(inputs)): self.assertGradientChecks(gc, op, inputs, i, [0]) @given(input_channels=st.integers(1, 3), output_channels=st.integers(1, 2), batch_size=st.integers(1, 3), stride=st.integers(1, 3), size=st.integers(7, 10), kernel=st.integers(1, 2), dilation=st.integers(1, 3), pad=st.integers(0, 3), use_bias=st.booleans(), **hu.gcs) def test_1d_convolution_nchw(self, input_channels, output_channels, batch_size, stride, size, kernel, dilation, pad, use_bias, gc, dc): self._nd_convolution_nchw( 1, input_channels, output_channels, batch_size, stride, size, kernel, dilation, pad, use_bias, gc, dc ) @given(input_channels=st.integers(1, 2), output_channels=st.integers(1, 2), batch_size=st.integers(1, 2), stride=st.integers(1, 2), size=st.integers(4, 5), kernel=st.integers(1, 2), dilation=st.integers(1, 2), pad=st.integers(0, 2), use_bias=st.booleans(), **hu.gcs) def test_3d_convolution_nchw(self, input_channels, output_channels, batch_size, stride, size, kernel, dilation, pad, use_bias, gc, dc): self._nd_convolution_nchw( 3, input_channels, output_channels, batch_size, stride, size, kernel, dilation, pad, use_bias, gc, dc ) @given(op_type=st.sampled_from(["Conv", "Conv3D"]), batch_size=st.integers(1, 2), stride=st.integers(1, 2), size=st.integers(3, 5), kernel=st.integers(1, 2), dilation=st.integers(1, 2), pad=st.integers(0, 2), use_bias=st.booleans(), **hu.gcs) def test_3d_convolution_cudnn_nchw(self, op_type, batch_size, stride, size, kernel, dilation, pad, use_bias, gc, dc): input_channels = 1 output_channels = 1 n = 3 dkernel = dilation * (kernel - 1) + 1 order = "NCHW" op = core.CreateOperator( op_type, ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], strides=[stride] * n, kernels=[kernel] * n, dilations=[dilation] * n, pads=[pad] * n * 2, order=order, engine="CUDNN", ) input_dims = [batch_size, input_channels] input_dims.extend([size] * n) filter_dims = [output_channels, input_channels] filter_dims.extend([kernel] * n) X = np.random.rand(*input_dims).astype(np.float32) - 0.5 w = np.random.rand(*filter_dims).astype(np.float32) - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 inputs = [X, w, b] if use_bias else [X, w] if size + pad + pad < dkernel or size + pad + pad < dkernel: with self.assertRaises(RuntimeError): self.assertDeviceChecks(dc, op, inputs, [0]) return self.assertDeviceChecks(dc, op, inputs, [0]) for i in range(len(inputs)): self.assertGradientChecks(gc, op, inputs, i, [0]) @given(op_type=st.sampled_from(["Conv", "Conv2D"]), stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), dilation=st.integers(1, 3), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), use_bias=st.booleans(), **hu.gcs) def test_convolution_layout(self, op_type, stride, pad, kernel, dilation, size, input_channels, output_channels, batch_size, use_bias, gc, dc): assume(size >= dilation * (kernel - 1) + 1) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( output_channels, kernel, kernel, input_channels).astype(np.float32)\ - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 Output = collections.namedtuple("Output", ["Y", "engine", "order"]) outputs = [] for order in ["NCHW", "NHWC"]: engine_list = [''] if _cudnn_supports(dilation=(dilation > 1), nhwc=(order == 'NHWC')): engine_list.append('CUDNN') for engine in engine_list: op = core.CreateOperator( op_type, ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], stride=stride, kernel=kernel, dilation=dilation, pad=pad, order=order, engine=engine, device_option=gc, ) if order == "NCHW": X_f = X.transpose((0, 3, 1, 2)) w_f = w.transpose((0, 3, 1, 2)) else: X_f = X w_f = w self.assertDeviceChecks( dc, op, [X_f, w_f, b] if use_bias else [X_f, w_f], [0]) self.ws.create_blob("X").feed(X_f, device_option=gc) self.ws.create_blob("w").feed(w_f, device_option=gc) self.ws.create_blob("b").feed(b, device_option=gc) self.ws.run(op) outputs.append(Output( Y=self.ws.blobs["Y"].fetch(), engine=engine, order=order)) def canonical(o): if o.order == "NHWC": return o.Y.transpose((0, 3, 1, 2)) else: return o.Y for o in outputs: np.testing.assert_allclose( canonical(outputs[0]), canonical(o), atol=1e-4, rtol=1e-4) @given(num_workers=st.integers(1, 4), net_type=st.sampled_from( ["simple", "dag"] + (["async_dag"] if workspace.has_gpu_support else [])), do=st.sampled_from(hu.device_options), engine=st.sampled_from(["CUDNN", ""])) def test_convolution_sync(self, net_type, num_workers, do, engine): m = ModelHelper(name="test_model") n = 1 d = 2 depth = 3 iters = 5 h = 5 w = 5 workspace.ResetWorkspace() use_cudnn = (engine == 'CUDNN') np.random.seed(1701) # Build a binary tree of conv layers, summing at each node. for i in reversed(range(depth)): for j in range(2 ** i): bottom_1 = "{}_{}".format(i + 1, 2 * j) bottom_2 = "{}_{}".format(i + 1, 2 * j + 1) mid_1 = "{}_{}_m".format(i + 1, 2 * j) mid_2 = "{}_{}_m".format(i + 1, 2 * j + 1) top = "{}_{}".format(i, j) w1, b1, w2, b2 = np.random.randn(4).tolist() brew.conv( m, bottom_1, mid_1, dim_in=d, dim_out=d, kernel=3, weight_init=('ConstantFill', dict(value=w1)), bias_init=('ConstantFill', dict(value=b1)), cudnn_state=np.random.randint(0, 3), stride=1, pad=1, deterministic=1, use_cudnn=use_cudnn, engine=engine) brew.conv( m, bottom_2, mid_2, dim_in=d, dim_out=d, kernel=3, stride=1, pad=1, weight_init=('ConstantFill', dict(value=w2)), bias_init=('ConstantFill', dict(value=b2)), deterministic=1, cudnn_state=np.random.randint(0, 3), use_cudnn=use_cudnn, engine=engine) m.net.Sum([mid_1, mid_2], top) m.net.Flatten(["0_0"], ["0_0_flat"]) m.net.SquaredL2Distance(["0_0_flat", "label"], "xent") m.net.AveragedLoss("xent", "loss") input_to_grad = m.AddGradientOperators(["loss"]) m.Proto().device_option.CopyFrom(do) m.param_init_net.Proto().device_option.CopyFrom(do) m.Proto().type = net_type m.Proto().num_workers = num_workers self.ws.run(m.param_init_net) def run(): import numpy as np np.random.seed(1701) input_blobs = ["{}_{}".format(depth, j) for j in range(2 ** depth)] for input_blob in input_blobs: self.ws.create_blob(input_blob).feed( np.random.randn(n, d, h, w).astype(np.float32), device_option=do) self.ws.create_blob("label").feed( np.random.randn(n, d * h * w).astype(np.float32), device_option=do) self.ws.run(m.net) gradients = [ self.ws.blobs[str(input_to_grad[input_blob])].fetch() for input_blob in input_blobs] return gradients outputs = [run() for _ in range(iters)] for output in outputs[1:]: np.testing.assert_array_equal(outputs[0], output) np.testing.assert_allclose( np.sum(np.square(output)), 1763719461732352.0, rtol=1e-5) def test_use_cudnn_engine_interactions(self): """Make sure the use_cudnn and engine kwargs work as expected.""" for model_default in [None, True, False]: arg_scope = {} if model_default is not None: arg_scope['use_cudnn'] = model_default else: model_default = True # the default model = ModelHelper(arg_scope=arg_scope) self.assertEqual(model.arg_scope['use_cudnn'], model_default) f = functools.partial(brew.conv, model, 'conv_in', 'conv_out', 10, 10, 5) for op_cudnn in [None, True, False]: for op_engine in [None, '', 'CUDNN']: kwargs = {} if op_cudnn is not None: kwargs['use_cudnn'] = op_cudnn else: op_cudnn = False # the default if op_engine is not None: kwargs['engine'] = op_engine calculated_cudnn = kwargs.get('use_cudnn', model_default) expected_engine = kwargs.get( 'engine', 'CUDNN' if calculated_cudnn else '') if ((calculated_cudnn is True and op_engine == '') or (calculated_cudnn is False and op_engine == 'CUDNN')): with self.assertRaises(ValueError): f(**kwargs) else: f(**kwargs) self.assertEqual(model.Proto().op[-1].engine, expected_engine) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import hypothesis.strategies as st import caffe2.python.hypothesis_test_util as hu import numpy as np import unittest def mux(select, left, right): return [np.vectorize(lambda c, x, y: x if c else y)(select, left, right)] def rowmux(select_vec, left, right): select = [[s] * len(left) for s in select_vec] return mux(select, left, right) class TestWhere(hu.HypothesisTestCase): def test_reference(self): self.assertTrue(( np.array([1, 4]) == mux([True, False], [1, 2], [3, 4])[0] ).all()) self.assertTrue(( np.array([[1], [4]]) == mux([[True], [False]], [[1], [2]], [[3], [4]])[0] ).all()) @given(N=st.integers(min_value=1, max_value=10), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs_cpu_only) def test_where(self, N, gc, dc, engine): C = np.random.rand(N).astype(bool) X = np.random.rand(N).astype(np.float32) Y = np.random.rand(N).astype(np.float32) op = core.CreateOperator("Where", ["C", "X", "Y"], ["Z"], engine=engine) self.assertDeviceChecks(dc, op, [C, X, Y], [0]) self.assertReferenceChecks(gc, op, [C, X, Y], mux) @given(N=st.integers(min_value=1, max_value=10), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs_cpu_only) def test_where_dim2(self, N, gc, dc, engine): C = np.random.rand(N, N).astype(bool) X = np.random.rand(N, N).astype(np.float32) Y = np.random.rand(N, N).astype(np.float32) op = core.CreateOperator("Where", ["C", "X", "Y"], ["Z"], engine=engine) self.assertDeviceChecks(dc, op, [C, X, Y], [0]) self.assertReferenceChecks(gc, op, [C, X, Y], mux) class TestRowWhere(hu.HypothesisTestCase): def test_reference(self): self.assertTrue(( np.array([1, 2]) == rowmux([True], [1, 2], [3, 4])[0] ).all()) self.assertTrue(( np.array([[1, 2], [7, 8]]) == rowmux([True, False], [[1, 2], [3, 4]], [[5, 6], [7, 8]])[0] ).all()) @given(N=st.integers(min_value=1, max_value=10), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs_cpu_only) def test_rowwhere(self, N, gc, dc, engine): C = np.random.rand(N).astype(bool) X = np.random.rand(N).astype(np.float32) Y = np.random.rand(N).astype(np.float32) op = core.CreateOperator( "Where", ["C", "X", "Y"], ["Z"], broadcast_on_rows=True, engine=engine, ) self.assertDeviceChecks(dc, op, [C, X, Y], [0]) self.assertReferenceChecks(gc, op, [C, X, Y], mux) @given(N=st.integers(min_value=1, max_value=10), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs_cpu_only) def test_rowwhere_dim2(self, N, gc, dc, engine): C = np.random.rand(N).astype(bool) X = np.random.rand(N, N).astype(np.float32) Y = np.random.rand(N, N).astype(np.float32) op = core.CreateOperator( "Where", ["C", "X", "Y"], ["Z"], broadcast_on_rows=True, engine=engine, ) self.assertDeviceChecks(dc, op, [C, X, Y], [0]) self.assertReferenceChecks(gc, op, [C, X, Y], rowmux) class TestIsMemberOf(hu.HypothesisTestCase): @given(N=st.integers(min_value=1, max_value=10), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs_cpu_only) def test_is_member_of(self, N, gc, dc, engine): X = np.random.randint(10, size=N).astype(np.int64) values = [0, 3, 4, 6, 8] op = core.CreateOperator( "IsMemberOf", ["X"], ["Y"], value=np.array(values), engine=engine, ) self.assertDeviceChecks(dc, op, [X], [0]) values = set(values) def test(x): return [np.vectorize(lambda x: x in values)(x)] self.assertReferenceChecks(gc, op, [X], test) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from functools import partial from hypothesis import given import numpy as np import unittest import hypothesis.strategies as st from caffe2.python import core, workspace import caffe2.python.hypothesis_test_util as hu class TesterBase: def segment_reduce_op(self, data, segment_ids, reducer, indices=None): segments = self.split(data, segment_ids, indices) output = np.zeros((len(segments), ) + data.shape[1:]) for i, segment in enumerate(segments): if len(segment) > 0: output[i] = reducer(segment) else: output[i] = 0.0 return output def segment_reduce_grad_op( self, data, segment_ids, reducer_grad, grad_out, output, indices=None ): segments = self.split(data, segment_ids, indices) segment_grads = [ reducer_grad(grad_out[i], [output[i]], [segment]) for i, segment in enumerate(segments) ] return self.unsplit(data.shape[1:], segment_grads, segment_ids) def _test(self, prefix, input_strategy, refs, gpu=False, **kwargs): tester = self operator_args = kwargs.pop('operator_args', {}) threshold = kwargs.pop('threshold', 1e-4) grad_check = kwargs.pop('grad_check', True) @given(X=input_strategy, **hu.gcs) def test_segment_ops(self, X, gc, dc): if not gpu and gc.device_type > 0: return for op_name, ref, grad_ref in refs: inputs = ['input%d' % i for i in range(0, len(X))] op = core.CreateOperator( prefix + op_name, inputs, ['output'], **operator_args ) print('Operator %s, ' % op.type, gc.device_type) def seg_reduce(data, *args): indices, segments = ( args if len(args) == 2 else (None, args[0]) ) out = tester.segment_reduce_op( data=data, segment_ids=segments, indices=indices, reducer=ref ) return (out, ) def seg_reduce_grad(grad_out, outputs, inputs): data = inputs[0] args = inputs[1:] indices, segments = ( args if len(args) == 2 else (None, args[0]) ) # grad r.t. data grad_val = tester.segment_reduce_grad_op( data, segments, grad_ref, grad_out, outputs[0], indices ) # if sparse, include indices along with data gradient data_grad_slice = ( (grad_val, indices) if indices is not None else grad_val ) # other inputs don't have gradient return (data_grad_slice, ) + (None, ) * (len(inputs) - 1) kwargs = {} if grad_check: kwargs['output_to_grad'] = 'output' kwargs['grad_reference'] = seg_reduce_grad self.assertReferenceChecks( device_option=gc, op=op, inputs=X, reference=seg_reduce, threshold=threshold, **kwargs ) return test_segment_ops class SegmentsTester(TesterBase): def split(self, data, segment_ids, indices=None): """ Given: data[M1 x M2 x ... x Md] the input data indices[N] the index of each entry of segment_ids into data, where 0 <= index[i] < M1, with default indices=[0,1,...N] segment_ids[N] the segment_id for each entry of indices, returns K outputs, each one containing data entries corresponding to one of the segments present in `segment_ids`. """ if segment_ids.size == 0: return [] K = max(segment_ids) + 1 outputs = [ np.zeros( (np.count_nonzero(segment_ids == seg_id), ) + data.shape[1:], dtype=data.dtype ) for seg_id in range(0, K) ] counts = np.zeros(K, dtype=int) for i, seg_id in enumerate(segment_ids): data_idx = i if indices is None else indices[i] outputs[seg_id][counts[seg_id]] = data[data_idx] counts[seg_id] += 1 return outputs def unsplit(self, extra_shape, inputs, segment_ids): """ Inverse operation to `split`, with indices=None """ output = np.zeros((len(segment_ids), ) + extra_shape) if len(segment_ids) == 0: return output K = max(segment_ids) + 1 counts = np.zeros(K, dtype=int) for i, seg_id in enumerate(segment_ids): output[i] = inputs[seg_id][counts[seg_id]] counts[seg_id] += 1 return output class LengthsTester(TesterBase): def split(self, data, lengths, indices=None): K = len(lengths) outputs = [ np.zeros((lengths[seg_id], ) + data.shape[1:], dtype=data.dtype) for seg_id in range(0, K) ] start = 0 for i in range(0, K): for j in range(0, lengths[i]): data_index = start + j if indices is not None: data_index = indices[data_index] outputs[i][j] = data[data_index] start += lengths[i] return outputs def unsplit(self, extra_shape, inputs, lengths): N = sum(lengths) output = np.zeros((N, ) + extra_shape) K = len(lengths) assert len(inputs) == K current = 0 for i in range(0, K): for j in range(0, lengths[i]): output[current] = inputs[i][j] current += 1 return output def sum_grad(grad_out, outputs, inputs): return np.repeat( np.expand_dims(grad_out, axis=0), inputs[0].shape[0], axis=0 ) def logsumexp(x): return np.log(np.sum(np.exp(x), axis=0)) def logsumexp_grad(grad_out, outputs, inputs): sum_exps = np.sum(np.exp(inputs[0]), axis=0) return np.repeat( np.expand_dims(grad_out / sum_exps, 0), inputs[0].shape[0], axis=0 ) * np.exp(inputs[0]) def logmeanexp(x): return np.log(np.mean(np.exp(x), axis=0)) def mean(x): return np.mean(x, axis=0) def mean_grad(grad_out, outputs, inputs): return np.repeat( np.expand_dims(grad_out / inputs[0].shape[0], 0), inputs[0].shape[0], axis=0 ) def max_fwd(x): return np.amax(x, axis=0) def max_grad(grad_out, outputs, inputs): flat_inputs = inputs[0].flatten() flat_outputs = np.array(outputs[0]).flatten() flat_grad_in = np.zeros(flat_inputs.shape) flat_grad_out = np.array(grad_out).flatten() blocks = inputs[0].shape[0] if blocks == 0: return np.zeros(inputs[0].shape) block_size = flat_inputs.shape[0] // blocks for i in range(block_size): out_grad = flat_grad_out[i] out = flat_outputs[i] for j in range(blocks): idx = j * block_size + i # we can produce multiple outputs for max if out == flat_inputs[idx]: flat_grad_in[idx] = out_grad return np.resize(flat_grad_in, inputs[0].shape) REFERENCES_ALL = [ ('Sum', partial(np.sum, axis=0), sum_grad), ('Mean', partial(np.mean, axis=0), mean_grad), ] REFERENCES_SORTED = [ ('RangeSum', partial(np.sum, axis=0), sum_grad), ('RangeLogSumExp', logsumexp, logsumexp_grad), # gradient is the same as sum ('RangeLogMeanExp', logmeanexp, logsumexp_grad), ('RangeMean', mean, mean_grad), ('RangeMax', max_fwd, max_grad), ] REFERENCES_LENGTHS_ONLY = [ ('Max', partial(np.amax, axis=0), max_grad), ] def sparse_lengths_weighted_sum_ref(D, W, I, L): R = np.zeros(shape=(len(L), ) + D.shape[1:], dtype=D.dtype) line = 0 for g in range(len(L)): for _ in range(L[g]): if len(D.shape) > 1: R[g, :] += W[line] * D[I[line], :] else: R[g] += W[line] * D[I[line]] line += 1 return [R] def sparse_lengths_weighted_sum_grad_ref( GO, fwd_out, fwd_in, grad_on_weights=False): D, W, I, L = fwd_in GI = np.zeros(shape=(len(I), ) + D.shape[1:], dtype=D.dtype) GW = np.zeros(shape=W.shape, dtype=W.dtype) if grad_on_weights else None line = 0 for g in range(len(L)): for _ in range(L[g]): if len(GO.shape) > 1: GI[line, :] = W[line] * GO[g, :] else: GI[line] = W[line] * GO[g] if GW is not None: if len(GO.shape) > 1: GW[line] = np.dot(GO[g].flatten(), D[I[line], :].flatten()) else: GW[line] = np.dot(GO[g].flatten(), D[I[line]].flatten()) line += 1 print(GW) return [(GI, I), GW, None, None] class TestSegmentOps(hu.HypothesisTestCase): def test_sorted_segment_ops(self): SegmentsTester()._test( 'SortedSegment', hu.segmented_tensor( dtype=np.float32, is_sorted=True, allow_empty=True ), REFERENCES_ALL + REFERENCES_SORTED )(self) def test_unsorted_segment_ops(self): SegmentsTester()._test( 'UnsortedSegment', hu.segmented_tensor( dtype=np.float32, is_sorted=False, allow_empty=True ), REFERENCES_ALL, )(self) def test_unsorted_segment_ops_gpu(self): SegmentsTester()._test( 'UnsortedSegment', hu.segmented_tensor( dtype=np.float32, is_sorted=False, allow_empty=True, ), REFERENCES_ALL, gpu=workspace.has_gpu_support, grad_check=False, )(self) def test_sparse_sorted_segment_ops(self): SegmentsTester()._test( 'SparseSortedSegment', hu.sparse_segmented_tensor( dtype=np.float32, is_sorted=True, allow_empty=True ), REFERENCES_ALL )(self) def test_sparse_unsorted_segment_ops(self): SegmentsTester()._test( 'SparseUnsortedSegment', hu.sparse_segmented_tensor( dtype=np.float32, is_sorted=False, allow_empty=True ), REFERENCES_ALL )(self) def test_lengths_ops(self): LengthsTester()._test( 'Lengths', hu.lengths_tensor( dtype=np.float32, min_value=1, max_value=5, allow_empty=True ), REFERENCES_ALL + REFERENCES_LENGTHS_ONLY, )(self) def test_sparse_lengths_ops(self): for itype in [np.int32, np.int64]: LengthsTester()._test( 'SparseLengths', hu.sparse_lengths_tensor( dtype=np.float32, min_value=1, max_value=5, allow_empty=True, itype=itype, ), REFERENCES_ALL, )(self) @unittest.skipIf(not workspace.has_gpu_support, "No gpu support") @given(**hu.gcs) def test_unsorted_sums_large(self, gc, dc): X = np.random.rand(10000, 32, 12).astype(np.float32) segments = np.random.randint(0, 10000, size=10000).astype(np.int32) op = core.CreateOperator("UnsortedSegmentSum", ["X", "segments"], "out") self.assertDeviceChecks(dc, op, [X, segments], [0]) @unittest.skipIf(not workspace.has_gpu_support, "No gpu support") @given(**hu.gcs) def test_sorted_segment_range_mean(self, gc, dc): X = np.random.rand(6, 32, 12).astype(np.float32) segments = np.array([0, 0, 1, 1, 2, 3]).astype(np.int32) op = core.CreateOperator( "SortedSegmentRangeMean", ["X", "segments"], "out" ) self.assertDeviceChecks(dc, op, [X, segments], [0]) self.assertGradientChecks(gc, op, [X, segments], 0, [0]) @unittest.skipIf(not workspace.has_gpu_support, "No gpu support") @given(**hu.gcs) def test_sorted_segment_range_log_mean_exp(self, gc, dc): X = np.random.rand(7, 32, 12).astype(np.float32) segments = np.array([0, 0, 1, 1, 2, 2, 3]).astype(np.int32) op = core.CreateOperator( "SortedSegmentRangeLogMeanExp", ["X", "segments"], "out" ) self.assertDeviceChecks(dc, op, [X, segments], [0]) self.assertGradientChecks(gc, op, [X, segments], 0, [0]) @unittest.skipIf(not workspace.has_gpu_support, "No gpu support") @given(**hu.gcs) def test_unsorted_means_large(self, gc, dc): X = np.random.rand(10000, 31, 19).astype(np.float32) segments = np.random.randint(0, 10000, size=10000).astype(np.int32) op = core.CreateOperator("UnsortedSegmentMean", ["X", "segments"], "out") self.assertDeviceChecks(dc, op, [X, segments], [0]) @given( inputs=hu.lengths_tensor( dtype=np.float32, min_value=1, max_value=5, allow_empty=True, ), **hu.gcs ) def test_lengths_sum(self, inputs, gc, dc): X, Y = inputs op = core.CreateOperator("LengthsSum", ["X", "Y"], "out") self.assertDeviceChecks(dc, op, [X, Y], [0]) self.assertGradientChecks(gc, op, [X, Y], 0, [0]) @given( inputs=hu.sparse_lengths_tensor( dtype=np.float32, min_value=1, max_value=5, allow_empty=True ), **hu.gcs ) def test_sparse_lengths_sum(self, inputs, gc, dc): X, Y, Z = inputs op = core.CreateOperator("SparseLengthsSum", ["X", "Y", "Z"], "out") self.assertDeviceChecks(dc, op, [X, Y, Z], [0]) self.assertGradientChecks(gc, op, [X, Y, Z], 0, [0]) @given( grad_on_weights=st.booleans(), inputs=hu.sparse_lengths_tensor( dtype=np.float32, min_value=1, max_value=5, allow_empty=True ), **hu.gcs ) def test_sparse_lengths_weighted_sum( self, grad_on_weights, inputs, gc, dc): D, I, L = inputs W = np.random.rand(I.size).astype(np.float32) op = core.CreateOperator( "SparseLengthsWeightedSum", ["D", "W", "I", "L"], "out", grad_on_weights=grad_on_weights) self.assertDeviceChecks(dc, op, [D, W, I, L], [0]) self.assertReferenceChecks( device_option=gc, op=op, inputs=[D, W, I, L], reference=sparse_lengths_weighted_sum_ref, threshold=1e-4, output_to_grad='out', grad_reference=partial( sparse_lengths_weighted_sum_grad_ref, grad_on_weights=grad_on_weights), ) self.assertGradientChecks(gc, op, [D, W, I, L], 0, [0]) if grad_on_weights: self.assertGradientChecks(gc, op, [D, W, I, L], 1, [0]) @given(**hu.gcs) def test_sparse_lengths_indices_in_gradient_sum_gpu(self, gc, dc): X = np.random.rand(3, 3, 4, 5).astype(np.float32) Y = np.asarray([3, 3, 2]).astype(np.int32) Z = np.random.randint(0, 50, size=8).astype(np.int64) op = core.CreateOperator( "SparseLengthsIndicesInGradientSumGradient", ["X", "Y", "Z"], "out" ) self.assertDeviceChecks(dc, op, [X, Y, Z], [0]) @given(**hu.gcs_cpu_only) def test_legacy_sparse_and_lengths_sum_gradient(self, gc, dc): X = np.random.rand(3, 64).astype(np.float32) Y = np.asarray([20, 20, 10]).astype(np.int32) workspace.FeedBlob("X", X) workspace.FeedBlob("Y", Y) test_net = core.Net("test_net") test_net.SparseLengthsSumGradient(["X", "Y"], "out1") test_net.LengthsSumGradient(["X", "Y"], "out2") workspace.RunNetOnce(test_net) out1 = workspace.FetchBlob("out1") out2 = workspace.FetchBlob("out2") self.assertTrue((out1 == out2).all()) @given(**hu.gcs) def test_sparse_lengths_sum_invalid_index(self, gc, dc): D = np.random.rand(50, 3, 4, 5).astype(np.float32) I = (np.random.randint(0, 10000, size=10) + 10000).astype(np.int64) L = np.asarray([4, 4, 2]).astype(np.int32) op = core.CreateOperator( "SparseLengthsSum", ["D", "I", "L"], "out") workspace.FeedBlob('D', D) workspace.FeedBlob('I', I) workspace.FeedBlob('L', L) with self.assertRaises(RuntimeError): workspace.RunOperatorOnce(op) @given(**hu.gcs_cpu_only) def test_sparse_lengths_positional_weighted_sum( self, gc, dc): D = np.random.rand(50, 3, 4, 5).astype(np.float32) W = np.random.rand(50).astype(np.float32) indices = np.random.randint(0, 50, size=10).astype(np.int64) L = np.asarray([4, 4, 2]).astype(np.int32) op = core.CreateOperator( "SparseLengthsPositionalWeightedSum", ["D", "W", "indices", "L"], "out") def ref_sparse(D, W, indices, L): workspace.FeedBlob("L", L) lengths_range_fill_op = core.CreateOperator( "LengthsRangeFill", ["L"], ["L_pos_seq"]) workspace.RunOperatorOnce(lengths_range_fill_op) workspace.FeedBlob("W", W) gather_op = core.CreateOperator( "Gather", ["W", "L_pos_seq"], ["W_gathered"]) workspace.RunOperatorOnce(gather_op) workspace.FeedBlob("D", D) workspace.FeedBlob("indices", indices) sparse_op = core.CreateOperator( "SparseLengthsWeightedSum", ["D", "W_gathered", "indices", "L"], "out_ref") workspace.RunOperatorOnce(sparse_op) return (workspace.FetchBlob("out_ref"),) self.assertReferenceChecks( gc, op, [D, W, indices, L], ref_sparse) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import hypothesis.strategies as st from hypothesis import given import numpy as np from caffe2.python import core import caffe2.python.hypothesis_test_util as hu @unittest.skipIf(not core.IsOperator("PackedFC"), "PackedFC is not supported in this caffe2 build.") class PackedFCTest(hu.HypothesisTestCase): @given(seed=st.integers(0, 65536), M=st.integers(16, 32), K=st.integers(128, 1024), N=st.integers(128, 1024), **hu.gcs_cpu_only) @unittest.skipIf(not core.C.builtin_cpu_supports_avx2(), "Intel MKL sgemm_pack has a known numerical issue with " "non-avx2 machines that will be fixed in a later build.") def test_packed_fc(self, seed, M, K, N, gc, dc): np.random.seed(seed) X = np.random.rand(M, K).astype(np.float32) - 0.5 W = np.random.rand(N, K).astype(np.float32) - 0.5 b = np.random.rand(N).astype(np.float32) - 0.5 # If you are debugging, the following hard-coded ones might help. # X = np.ones((24, 256)).astype(np.float32) # W = np.ones((128, 256)).astype(np.float32) # b = np.zeros(128).astype(np.float32) def ref(X, W, b): return (np.dot(X, W.T) + b,) for name in ["FC", "PackedFC"]: op = core.CreateOperator( name, ["X", "W", "b"], ["Y"], ) self.assertReferenceChecks(gc, op, [X, W, b], ref) @unittest.skipIf(not core.C.builtin_cpu_supports_avx2(), "Intel MKL sgemm_pack has a known numerical issue with " "non-avx2 machines that will be fixed in a later build.") @given(axis=st.integers(min_value=1, max_value=4), num_output=st.integers(min_value=4, max_value=8), **hu.gcs_cpu_only) def test_packed_fc_axis(self, axis, num_output, gc, dc): np.random.seed(1701) X = np.random.randn(1, 2, 3, 2, 1).astype(np.float32) K = np.prod(X.shape[axis:]) N = num_output W = np.random.randn(N, K).astype(np.float32) b = np.random.randn(N).astype(np.float32) op = core.CreateOperator( "PackedFC", ["X", "W", "b"], ["Y"], axis=axis) def ref(X, W, b): output_axes = list(X.shape[:axis]) + [N] return ( np.dot(X.reshape(int(X.size / K), K), W.T).reshape(output_axes) + b,) self.assertReferenceChecks(gc, op, [X, W, b], ref) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import workspace, crf, brew from caffe2.python.model_helper import ModelHelper import numpy as np from scipy.misc import logsumexp import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st from hypothesis import given class TestCRFOp(hu.HypothesisTestCase): @given(num_tags=st.integers(2, 4), num_words=st.integers(2, 15)) def test_crf_with_loss_op(self, num_tags, num_words): model = ModelHelper(name='external') embeddings_dim = 200 embeddings = np.random.randn(num_words, embeddings_dim).astype(np.float32) transitions = np.random.uniform( low=-1, high=1, size=(num_tags + 2, num_tags + 2) ).astype(np.float32) labels = np.random.randint(num_tags, size=(num_words)).astype(np.int64) embeddings_blob, labels_blob, transitions_blob = ( model.net.AddExternalInputs( 'embeddings_blob', 'labels_blob', 'crf_transitions') ) workspace.FeedBlob(str(embeddings_blob), embeddings) workspace.FeedBlob(str(labels_blob), labels) workspace.FeedBlob(str(transitions_blob), transitions) predictions_blob = brew.fc( model, embeddings_blob, "fc_0", embeddings_dim, num_tags, ('UniformFill', {'min': -1.0}, {'max': 1.0}), ('UniformFill', {'min': -1.0}, {'max': 1.0}) ) crf_layer = crf.CRFWithLoss(model, num_tags, transitions_blob) crf_loss = crf_layer.crf_loss(predictions_blob, labels_blob) model.net.AddGradientOperators([crf_loss]) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) loss = workspace.FetchBlob(str(crf_loss)) predictions = workspace.FetchBlob(str(predictions_blob)) np.testing.assert_allclose( loss, self._compute_loss_manual( predictions, num_tags, labels, transitions ), atol=0.001, rtol=0.001, err_msg='CRF LOSS is not matching the reference' ) @given(num_tags=st.integers(1, 4), num_words=st.integers(2, 4)) def test_crf_gradient(self, num_tags, num_words): base_model = ModelHelper(name='base_model') transitions = np.random.randn( num_tags + 2, num_tags + 2 ).astype(np.float32) predictions = np.random.randn(num_words, 1, num_tags + 2).astype(np.float32) initial = np.random.randn(1, num_tags + 2).astype(np.float32) predictions_blob, transitions_blob, initial_blob = ( base_model.net.AddExternalInputs( 'predictions_blob', 'crf_transitions', 'inital_blob' ) ) workspace.FeedBlob(str(predictions_blob), predictions) workspace.FeedBlob(str(transitions_blob), transitions) workspace.FeedBlob(str(initial_blob), initial) crf_layer = crf.CRFWithLoss(base_model, num_tags, transitions_blob) crf_layer.build_crf_net( predictions_blob, initial_blob, transitions_blob ) op = base_model.net._net.op[-1] workspace.RunNetOnce(base_model.param_init_net) gradients_to_check = ( index for (index, input_name) in enumerate(op.input) if input_name != "crf_net/zero_segment_id" ) inputs = [workspace.FetchBlob(name) for name in op.input] for param in gradients_to_check: self.assertGradientChecks( device_option=hu.cpu_do, op=op, inputs=inputs, outputs_to_check=param, outputs_with_grads=[1], threshold=0.05, stepsize=0.001, ) def _compute_loss_manual(self, predictions, num_tags, labels, transitions): low_score = -1000 b_s = np.array( [[low_score] * num_tags + [0, low_score]] ).astype(np.float32) e_s = np.array( [[low_score] * num_tags + [low_score, 0]] ).astype(np.float32) predictions = np.concatenate( [predictions, low_score * np.ones((predictions.shape[0], 2))], axis=1 ) predictions = np.concatenate( [b_s, predictions, e_s], axis=0 ) b_id = np.array([num_tags], dtype=np.int32) e_id = np.array([num_tags + 1], dtype=np.int32) labels = np.concatenate( [b_id, labels, e_id], axis=0 ) curr_state = predictions[0] input_states = predictions[1:] for input_state in input_states: prev = np.expand_dims(curr_state, axis=1) curr_input = np.expand_dims(input_state, axis=0) curr_state = logsumexp(prev + curr_input + transitions, axis=0) total_score = logsumexp(curr_state, axis=0) # Compute best path score unary_scores = sum(w[labels[i]] for i, w in enumerate(predictions)) binary_scores = sum( transitions[a][b] for a, b in zip(labels[:-1], labels[1:]) ) loss = total_score - (binary_scores + unary_scores) return loss
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import functools import hypothesis from hypothesis import given import hypothesis.strategies as st import numpy as np from caffe2.python import core import caffe2.python.hypothesis_test_util as hu class TestAdam(hu.HypothesisTestCase): @staticmethod def ref_adam(param, mom1, mom2, grad, LR, ITER, beta1, beta2, epsilon): t = ITER + 1 corrected_local_rate = LR * np.sqrt(1 - np.power(beta2, t)) / \ (1 - np.power(beta1, t)) mom1_out = (beta1 * mom1) + (1 - beta1) * grad mom2_out = (beta2 * mom2) + (1 - beta2) * np.square(grad) param_out = param + corrected_local_rate * mom1_out / \ (np.sqrt(mom2_out) + epsilon) return param_out, mom1_out, mom2_out @staticmethod def ref_row_wise_adam(param, mom1, mom2, grad, LR, ITER, beta1, beta2, epsilon): t = ITER + 1 corrected_local_rate = LR * np.sqrt(1 - np.power(beta2, t)) / \ (1 - np.power(beta1, t)) mom1_out = (beta1 * mom1) + (1 - beta1) * grad mom2_out = (beta2 * mom2) + (1 - beta2) * np.mean(np.square(grad)) param_out = param + corrected_local_rate * mom1_out / \ (np.sqrt(mom2_out) + epsilon) return (param_out, mom1_out, mom2_out) @given(inputs=hu.tensors(n=4), ITER=st.integers(min_value=0, max_value=10000), LR=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), beta1=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), beta2=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), epsilon=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), **hu.gcs) def test_adam(self, inputs, ITER, LR, beta1, beta2, epsilon, gc, dc): param, mom1, mom2, grad = inputs ITER = np.array([ITER], dtype=np.int64) LR = np.array([LR], dtype=np.float32) op = core.CreateOperator( "Adam", ["param", "mom1", "mom2", "grad", "lr", "iter"], ["output_param", "output_mom1", "output_mom2"], beta1=beta1, beta2=beta2, epsilon=epsilon) # Iter lives on the CPU input_device_options = {'iter': hu.cpu_do} self.assertReferenceChecks( gc, op, [param, mom1, mom2, grad, LR, ITER], functools.partial( self.ref_adam, beta1=beta1, beta2=beta2, epsilon=epsilon), input_device_options=input_device_options) @given(inputs=hu.tensors(n=4), ITER=st.integers(min_value=0, max_value=10000), LR=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), beta1=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), beta2=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), epsilon=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), data_strategy=st.data(), **hu.gcs) def test_sparse_adam(self, inputs, ITER, LR, beta1, beta2, epsilon, data_strategy, gc, dc): param, mom1, mom2, grad = inputs mom2 = np.absolute(mom2) ITER = np.array([ITER], dtype=np.int64) LR = np.array([LR], dtype=np.float32) # Create an indexing array containing values which index into grad indices = data_strategy.draw( hu.tensor( max_dim=1, min_value=1, max_value=grad.shape[0], dtype=np.int64, elements=st.sampled_from(np.arange(grad.shape[0])), ), ) # Verify that the generated indices are unique hypothesis.assume( np.array_equal( np.unique(indices.flatten()), np.sort(indices.flatten()))) # Sparsify grad grad = grad[indices] op = core.CreateOperator( "SparseAdam", ["param", "mom1", "mom2", "indices", "grad", "lr", "iter"], ["param", "mom1", "mom2"], beta1=beta1, beta2=beta2, epsilon=epsilon) def ref_sparse(param, mom1, mom2, indices, grad, LR, ITER): param_out = np.copy(param) mom1_out = np.copy(mom1) mom2_out = np.copy(mom2) for i, index in enumerate(indices): param_out[index], mom1_out[index], mom2_out[index] = \ self.ref_adam(param[index], mom1[index], mom2[index], grad[i], LR, ITER, beta1, beta2, epsilon) return (param_out, mom1_out, mom2_out) # Iter lives on the CPU input_device_options = {'iter': hu.cpu_do} self.assertReferenceChecks( gc, op, [param, mom1, mom2, indices, grad, LR, ITER], ref_sparse, input_device_options=input_device_options) @given(inputs=hu.tensors(n=3), ITER=st.integers(min_value=0, max_value=10000), LR=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), beta1=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), beta2=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), epsilon=st.floats(min_value=0.01, max_value=0.99, allow_nan=False, allow_infinity=False), data_strategy=st.data(), **hu.gcs_cpu_only) def test_row_wise_sparse_adam(self, inputs, ITER, LR, beta1, beta2, epsilon, data_strategy, gc, dc): param, mom1, grad = inputs ITER = np.array([ITER], dtype=np.int64) LR = np.array([LR], dtype=np.float32) # Create a 1D row-wise average 2nd moment tensor. mom2 = data_strategy.draw( hu.tensor1d(min_len=param.shape[0], max_len=param.shape[0], elements=hu.elements_of_type(dtype=np.float32)) ) mom2 = np.absolute(mom2) # Create an indexing array containing values which index into grad indices = data_strategy.draw( hu.tensor( max_dim=1, min_value=1, max_value=grad.shape[0], dtype=np.int64, elements=st.sampled_from(np.arange(grad.shape[0])), ), ) # Note that unlike SparseAdam, RowWiseSparseAdam uses a moment # tensor that is strictly 1-dimensional and equal in length to the # first dimension of the parameters, so indices must also be # 1-dimensional. indices = indices.flatten() hypothesis.note('indices.shape: %s' % str(indices.shape)) # Verify that the generated indices are unique hypothesis.assume(np.array_equal(np.unique(indices), np.sort(indices))) # Sparsify grad grad = grad[indices] op = core.CreateOperator( "RowWiseSparseAdam", ["param", "mom1", "mom2", "indices", "grad", "lr", "iter"], ["param", "mom1", "mom2"], beta1=beta1, beta2=beta2, epsilon=epsilon) def ref_row_wise_sparse(param, mom1, mom2, indices, grad, LR, ITER): param_out = np.copy(param) mom1_out = np.copy(mom1) mom2_out = np.copy(mom2) for i, index in enumerate(indices): param_out[index], mom1_out[index], mom2_out[index] = \ self.ref_row_wise_adam(param[index], mom1[index], mom2[index], grad[i], LR, ITER, beta1, beta2, epsilon) return (param_out, mom1_out, mom2_out) # Iter lives on the CPU input_device_options = {'iter': hu.cpu_do} self.assertReferenceChecks( gc, op, [param, mom1, mom2, indices, grad, LR, ITER], ref_row_wise_sparse, input_device_options=input_device_options) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import ( core, gradient_checker, rnn_cell, workspace, scope, utils ) from caffe2.python.attention import AttentionType from caffe2.python.model_helper import ModelHelper, ExtractPredictorNet from caffe2.python.rnn.rnn_cell_test_util import sigmoid, tanh, _prepare_rnn from caffe2.proto import caffe2_pb2 import caffe2.python.hypothesis_test_util as hu from functools import partial from hypothesis import assume, given from hypothesis import settings as ht_settings import hypothesis.strategies as st import numpy as np import unittest def lstm_unit(*args, **kwargs): forget_bias = kwargs.get('forget_bias', 0.0) drop_states = kwargs.get('drop_states', False) sequence_lengths = kwargs.get('sequence_lengths', True) if sequence_lengths: hidden_t_prev, cell_t_prev, gates, seq_lengths, timestep = args else: hidden_t_prev, cell_t_prev, gates, timestep = args D = cell_t_prev.shape[2] G = gates.shape[2] N = gates.shape[1] t = (timestep * np.ones(shape=(N, D))).astype(np.int32) assert t.shape == (N, D) assert G == 4 * D # Resize to avoid broadcasting inconsistencies with NumPy gates = gates.reshape(N, 4, D) cell_t_prev = cell_t_prev.reshape(N, D) i_t = gates[:, 0, :].reshape(N, D) f_t = gates[:, 1, :].reshape(N, D) o_t = gates[:, 2, :].reshape(N, D) g_t = gates[:, 3, :].reshape(N, D) i_t = sigmoid(i_t) f_t = sigmoid(f_t + forget_bias) o_t = sigmoid(o_t) g_t = tanh(g_t) if sequence_lengths: seq_lengths = (np.ones(shape=(N, D)) * seq_lengths.reshape(N, 1)).astype(np.int32) assert seq_lengths.shape == (N, D) valid = (t < seq_lengths).astype(np.int32) else: valid = np.ones(shape=(N, D)) assert valid.shape == (N, D) cell_t = ((f_t * cell_t_prev) + (i_t * g_t)) * (valid) + \ (1 - valid) * cell_t_prev * (1 - drop_states) assert cell_t.shape == (N, D) hidden_t = (o_t * tanh(cell_t)) * valid + hidden_t_prev * ( 1 - valid) * (1 - drop_states) hidden_t = hidden_t.reshape(1, N, D) cell_t = cell_t.reshape(1, N, D) return hidden_t, cell_t def layer_norm_with_scale_and_bias_ref(X, scale, bias, axis=-1, epsilon=1e-4): left = np.prod(X.shape[:axis]) reshaped = np.reshape(X, [left, -1]) mean = np.mean(reshaped, axis=1).reshape([left, 1]) stdev = np.sqrt( np.mean(np.square(reshaped), axis=1).reshape([left, 1]) - np.square(mean) + epsilon ) norm = (reshaped - mean) / stdev norm = np.reshape(norm, X.shape) adjusted = scale * norm + bias return adjusted def layer_norm_lstm_reference( input, hidden_input, cell_input, gates_w, gates_b, gates_t_norm_scale, gates_t_norm_bias, seq_lengths, forget_bias, drop_states=False ): T = input.shape[0] N = input.shape[1] G = input.shape[2] D = hidden_input.shape[hidden_input.ndim - 1] hidden = np.zeros(shape=(T + 1, N, D)) cell = np.zeros(shape=(T + 1, N, D)) assert hidden.shape[0] == T + 1 assert cell.shape[0] == T + 1 assert hidden.shape[1] == N assert cell.shape[1] == N cell[0, :, :] = cell_input hidden[0, :, :] = hidden_input for t in range(T): input_t = input[t].reshape(1, N, G) print(input_t.shape) hidden_t_prev = hidden[t].reshape(1, N, D) cell_t_prev = cell[t].reshape(1, N, D) gates = np.dot(hidden_t_prev, gates_w.T) + gates_b gates = gates + input_t gates = layer_norm_with_scale_and_bias_ref( gates, gates_t_norm_scale, gates_t_norm_bias ) hidden_t, cell_t = lstm_unit( hidden_t_prev, cell_t_prev, gates, seq_lengths, t, forget_bias=forget_bias, drop_states=drop_states, ) hidden[t + 1] = hidden_t cell[t + 1] = cell_t return ( hidden[1:], hidden[-1].reshape(1, N, D), cell[1:], cell[-1].reshape(1, N, D) ) def lstm_reference(input, hidden_input, cell_input, gates_w, gates_b, seq_lengths, forget_bias, drop_states=False): T = input.shape[0] N = input.shape[1] G = input.shape[2] D = hidden_input.shape[hidden_input.ndim - 1] hidden = np.zeros(shape=(T + 1, N, D)) cell = np.zeros(shape=(T + 1, N, D)) assert hidden.shape[0] == T + 1 assert cell.shape[0] == T + 1 assert hidden.shape[1] == N assert cell.shape[1] == N cell[0, :, :] = cell_input hidden[0, :, :] = hidden_input for t in range(T): input_t = input[t].reshape(1, N, G) hidden_t_prev = hidden[t].reshape(1, N, D) cell_t_prev = cell[t].reshape(1, N, D) gates = np.dot(hidden_t_prev, gates_w.T) + gates_b gates = gates + input_t hidden_t, cell_t = lstm_unit( hidden_t_prev, cell_t_prev, gates, seq_lengths, t, forget_bias=forget_bias, drop_states=drop_states, ) hidden[t + 1] = hidden_t cell[t + 1] = cell_t return ( hidden[1:], hidden[-1].reshape(1, N, D), cell[1:], cell[-1].reshape(1, N, D) ) def multi_lstm_reference(input, hidden_input_list, cell_input_list, i2h_w_list, i2h_b_list, gates_w_list, gates_b_list, seq_lengths, forget_bias, drop_states=False): num_layers = len(hidden_input_list) assert len(cell_input_list) == num_layers assert len(i2h_w_list) == num_layers assert len(i2h_b_list) == num_layers assert len(gates_w_list) == num_layers assert len(gates_b_list) == num_layers for i in range(num_layers): layer_input = np.dot(input, i2h_w_list[i].T) + i2h_b_list[i] h_all, h_last, c_all, c_last = lstm_reference( layer_input, hidden_input_list[i], cell_input_list[i], gates_w_list[i], gates_b_list[i], seq_lengths, forget_bias, drop_states=drop_states, ) input = h_all return h_all, h_last, c_all, c_last def compute_regular_attention_logits( hidden_t, weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b, attention_weighted_encoder_context_t_prev, weighted_prev_attention_context_w, weighted_prev_attention_context_b, attention_v, weighted_encoder_outputs, encoder_outputs_for_dot_product, coverage_prev, coverage_weights, ): weighted_hidden_t = np.dot( hidden_t, weighted_decoder_hidden_state_t_w.T, ) + weighted_decoder_hidden_state_t_b attention_v = attention_v.reshape([-1]) return np.sum( attention_v * np.tanh(weighted_encoder_outputs + weighted_hidden_t), axis=2, ) def compute_recurrent_attention_logits( hidden_t, weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b, attention_weighted_encoder_context_t_prev, weighted_prev_attention_context_w, weighted_prev_attention_context_b, attention_v, weighted_encoder_outputs, encoder_outputs_for_dot_product, coverage_prev, coverage_weights, ): weighted_hidden_t = np.dot( hidden_t, weighted_decoder_hidden_state_t_w.T, ) + weighted_decoder_hidden_state_t_b weighted_prev_attention_context = np.dot( attention_weighted_encoder_context_t_prev, weighted_prev_attention_context_w.T ) + weighted_prev_attention_context_b attention_v = attention_v.reshape([-1]) return np.sum( attention_v * np.tanh( weighted_encoder_outputs + weighted_hidden_t + weighted_prev_attention_context ), axis=2, ) def compute_dot_attention_logits( hidden_t, weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b, attention_weighted_encoder_context_t_prev, weighted_prev_attention_context_w, weighted_prev_attention_context_b, attention_v, weighted_encoder_outputs, encoder_outputs_for_dot_product, coverage_prev, coverage_weights, ): hidden_t_for_dot_product = np.transpose(hidden_t, axes=[1, 2, 0]) if ( weighted_decoder_hidden_state_t_w is not None and weighted_decoder_hidden_state_t_b is not None ): hidden_t_for_dot_product = np.matmul( weighted_decoder_hidden_state_t_w, hidden_t_for_dot_product, ) + np.expand_dims(weighted_decoder_hidden_state_t_b, axis=1) attention_logits_t = np.sum( np.matmul( encoder_outputs_for_dot_product, hidden_t_for_dot_product, ), axis=2, ) return np.transpose(attention_logits_t) def compute_coverage_attention_logits( hidden_t, weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b, attention_weighted_encoder_context_t_prev, weighted_prev_attention_context_w, weighted_prev_attention_context_b, attention_v, weighted_encoder_outputs, encoder_outputs_for_dot_product, coverage_prev, coverage_weights, ): weighted_hidden_t = np.dot( hidden_t, weighted_decoder_hidden_state_t_w.T, ) + weighted_decoder_hidden_state_t_b coverage_part = coverage_prev.T * coverage_weights encoder_part = weighted_encoder_outputs + coverage_part attention_v = attention_v.reshape([-1]) return np.sum( attention_v * np.tanh(encoder_part + weighted_hidden_t), axis=2, ) def lstm_with_attention_reference( input, initial_hidden_state, initial_cell_state, initial_attention_weighted_encoder_context, gates_w, gates_b, decoder_input_lengths, encoder_outputs_transposed, weighted_prev_attention_context_w, weighted_prev_attention_context_b, weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b, weighted_encoder_outputs, coverage_weights, attention_v, attention_zeros, compute_attention_logits, ): encoder_outputs = np.transpose(encoder_outputs_transposed, axes=[2, 0, 1]) encoder_outputs_for_dot_product = np.transpose( encoder_outputs_transposed, [0, 2, 1], ) decoder_input_length = input.shape[0] batch_size = input.shape[1] decoder_input_dim = input.shape[2] decoder_state_dim = initial_hidden_state.shape[2] encoder_output_dim = encoder_outputs.shape[2] hidden = np.zeros( shape=(decoder_input_length + 1, batch_size, decoder_state_dim)) cell = np.zeros( shape=(decoder_input_length + 1, batch_size, decoder_state_dim)) attention_weighted_encoder_context = np.zeros( shape=(decoder_input_length + 1, batch_size, encoder_output_dim)) cell[0, :, :] = initial_cell_state hidden[0, :, :] = initial_hidden_state attention_weighted_encoder_context[0, :, :] = ( initial_attention_weighted_encoder_context ) encoder_length = encoder_outputs.shape[0] coverage = np.zeros( shape=(decoder_input_length + 1, batch_size, encoder_length)) for t in range(decoder_input_length): input_t = input[t].reshape(1, batch_size, decoder_input_dim) hidden_t_prev = hidden[t].reshape(1, batch_size, decoder_state_dim) cell_t_prev = cell[t].reshape(1, batch_size, decoder_state_dim) attention_weighted_encoder_context_t_prev = ( attention_weighted_encoder_context[t].reshape( 1, batch_size, encoder_output_dim) ) gates_input = np.concatenate( (hidden_t_prev, attention_weighted_encoder_context_t_prev), axis=2, ) gates = np.dot(gates_input, gates_w.T) + gates_b gates = gates + input_t hidden_t, cell_t = lstm_unit(hidden_t_prev, cell_t_prev, gates, decoder_input_lengths, t) hidden[t + 1] = hidden_t cell[t + 1] = cell_t coverage_prev = coverage[t].reshape(1, batch_size, encoder_length) attention_logits_t = compute_attention_logits( hidden_t, weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b, attention_weighted_encoder_context_t_prev, weighted_prev_attention_context_w, weighted_prev_attention_context_b, attention_v, weighted_encoder_outputs, encoder_outputs_for_dot_product, coverage_prev, coverage_weights, ) attention_logits_t_exp = np.exp(attention_logits_t) attention_weights_t = ( attention_logits_t_exp / np.sum(attention_logits_t_exp, axis=0).reshape([1, -1]) ) coverage[t + 1, :, :] = coverage[t, :, :] + attention_weights_t.T attention_weighted_encoder_context[t + 1] = np.sum( ( encoder_outputs * attention_weights_t.reshape([-1, batch_size, 1]) ), axis=0, ) return ( hidden[1:], hidden[-1].reshape(1, batch_size, decoder_state_dim), cell[1:], cell[-1].reshape(1, batch_size, decoder_state_dim), attention_weighted_encoder_context[1:], attention_weighted_encoder_context[-1].reshape( 1, batch_size, encoder_output_dim, ) ) def lstm_with_regular_attention_reference( input, initial_hidden_state, initial_cell_state, initial_attention_weighted_encoder_context, gates_w, gates_b, decoder_input_lengths, weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b, weighted_encoder_outputs, attention_v, attention_zeros, encoder_outputs_transposed, ): return lstm_with_attention_reference( input=input, initial_hidden_state=initial_hidden_state, initial_cell_state=initial_cell_state, initial_attention_weighted_encoder_context=( initial_attention_weighted_encoder_context ), gates_w=gates_w, gates_b=gates_b, decoder_input_lengths=decoder_input_lengths, encoder_outputs_transposed=encoder_outputs_transposed, weighted_prev_attention_context_w=None, weighted_prev_attention_context_b=None, weighted_decoder_hidden_state_t_w=weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b=weighted_decoder_hidden_state_t_b, weighted_encoder_outputs=weighted_encoder_outputs, coverage_weights=None, attention_v=attention_v, attention_zeros=attention_zeros, compute_attention_logits=compute_regular_attention_logits, ) def lstm_with_recurrent_attention_reference( input, initial_hidden_state, initial_cell_state, initial_attention_weighted_encoder_context, gates_w, gates_b, decoder_input_lengths, weighted_prev_attention_context_w, weighted_prev_attention_context_b, weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b, weighted_encoder_outputs, attention_v, attention_zeros, encoder_outputs_transposed, ): return lstm_with_attention_reference( input=input, initial_hidden_state=initial_hidden_state, initial_cell_state=initial_cell_state, initial_attention_weighted_encoder_context=( initial_attention_weighted_encoder_context ), gates_w=gates_w, gates_b=gates_b, decoder_input_lengths=decoder_input_lengths, encoder_outputs_transposed=encoder_outputs_transposed, weighted_prev_attention_context_w=weighted_prev_attention_context_w, weighted_prev_attention_context_b=weighted_prev_attention_context_b, weighted_decoder_hidden_state_t_w=weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b=weighted_decoder_hidden_state_t_b, weighted_encoder_outputs=weighted_encoder_outputs, coverage_weights=None, attention_v=attention_v, attention_zeros=attention_zeros, compute_attention_logits=compute_recurrent_attention_logits, ) def lstm_with_dot_attention_reference( input, initial_hidden_state, initial_cell_state, initial_attention_weighted_encoder_context, gates_w, gates_b, decoder_input_lengths, encoder_outputs_transposed, weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b, ): return lstm_with_attention_reference( input=input, initial_hidden_state=initial_hidden_state, initial_cell_state=initial_cell_state, initial_attention_weighted_encoder_context=( initial_attention_weighted_encoder_context ), gates_w=gates_w, gates_b=gates_b, decoder_input_lengths=decoder_input_lengths, encoder_outputs_transposed=encoder_outputs_transposed, weighted_prev_attention_context_w=None, weighted_prev_attention_context_b=None, weighted_decoder_hidden_state_t_w=weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b=weighted_decoder_hidden_state_t_b, weighted_encoder_outputs=None, coverage_weights=None, attention_v=None, attention_zeros=None, compute_attention_logits=compute_dot_attention_logits, ) def lstm_with_dot_attention_reference_same_dim( input, initial_hidden_state, initial_cell_state, initial_attention_weighted_encoder_context, gates_w, gates_b, decoder_input_lengths, encoder_outputs_transposed, ): return lstm_with_dot_attention_reference( input=input, initial_hidden_state=initial_hidden_state, initial_cell_state=initial_cell_state, initial_attention_weighted_encoder_context=( initial_attention_weighted_encoder_context ), gates_w=gates_w, gates_b=gates_b, decoder_input_lengths=decoder_input_lengths, encoder_outputs_transposed=encoder_outputs_transposed, weighted_decoder_hidden_state_t_w=None, weighted_decoder_hidden_state_t_b=None, ) def lstm_with_dot_attention_reference_different_dim( input, initial_hidden_state, initial_cell_state, initial_attention_weighted_encoder_context, gates_w, gates_b, decoder_input_lengths, weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b, encoder_outputs_transposed, ): return lstm_with_dot_attention_reference( input=input, initial_hidden_state=initial_hidden_state, initial_cell_state=initial_cell_state, initial_attention_weighted_encoder_context=( initial_attention_weighted_encoder_context ), gates_w=gates_w, gates_b=gates_b, decoder_input_lengths=decoder_input_lengths, encoder_outputs_transposed=encoder_outputs_transposed, weighted_decoder_hidden_state_t_w=weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b=weighted_decoder_hidden_state_t_b, ) def lstm_with_coverage_attention_reference( input, initial_hidden_state, initial_cell_state, initial_attention_weighted_encoder_context, initial_coverage, gates_w, gates_b, decoder_input_lengths, weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b, weighted_encoder_outputs, coverage_weights, attention_v, attention_zeros, encoder_outputs_transposed, ): return lstm_with_attention_reference( input=input, initial_hidden_state=initial_hidden_state, initial_cell_state=initial_cell_state, initial_attention_weighted_encoder_context=( initial_attention_weighted_encoder_context ), gates_w=gates_w, gates_b=gates_b, decoder_input_lengths=decoder_input_lengths, encoder_outputs_transposed=encoder_outputs_transposed, weighted_prev_attention_context_w=None, weighted_prev_attention_context_b=None, weighted_decoder_hidden_state_t_w=weighted_decoder_hidden_state_t_w, weighted_decoder_hidden_state_t_b=weighted_decoder_hidden_state_t_b, weighted_encoder_outputs=weighted_encoder_outputs, coverage_weights=coverage_weights, attention_v=attention_v, attention_zeros=attention_zeros, compute_attention_logits=compute_coverage_attention_logits, ) def milstm_reference( input, hidden_input, cell_input, gates_w, gates_b, alpha, beta1, beta2, b, seq_lengths, forget_bias, drop_states=False): T = input.shape[0] N = input.shape[1] G = input.shape[2] D = hidden_input.shape[hidden_input.ndim - 1] hidden = np.zeros(shape=(T + 1, N, D)) cell = np.zeros(shape=(T + 1, N, D)) assert hidden.shape[0] == T + 1 assert cell.shape[0] == T + 1 assert hidden.shape[1] == N assert cell.shape[1] == N cell[0, :, :] = cell_input hidden[0, :, :] = hidden_input for t in range(T): input_t = input[t].reshape(1, N, G) hidden_t_prev = hidden[t].reshape(1, N, D) cell_t_prev = cell[t].reshape(1, N, D) gates = np.dot(hidden_t_prev, gates_w.T) + gates_b gates = (alpha * gates * input_t) + \ (beta1 * gates) + \ (beta2 * input_t) + \ b hidden_t, cell_t = lstm_unit( hidden_t_prev, cell_t_prev, gates, seq_lengths, t, forget_bias=forget_bias, drop_states=drop_states, ) hidden[t + 1] = hidden_t cell[t + 1] = cell_t return ( hidden[1:], hidden[-1].reshape(1, N, D), cell[1:], cell[-1].reshape(1, N, D) ) def layer_norm_milstm_reference( input, hidden_input, cell_input, gates_w, gates_b, alpha, beta1, beta2, b, gates_t_norm_scale, gates_t_norm_bias, seq_lengths, forget_bias, drop_states=False): T = input.shape[0] N = input.shape[1] G = input.shape[2] D = hidden_input.shape[hidden_input.ndim - 1] hidden = np.zeros(shape=(T + 1, N, D)) cell = np.zeros(shape=(T + 1, N, D)) assert hidden.shape[0] == T + 1 assert cell.shape[0] == T + 1 assert hidden.shape[1] == N assert cell.shape[1] == N cell[0, :, :] = cell_input hidden[0, :, :] = hidden_input for t in range(T): input_t = input[t].reshape(1, N, G) hidden_t_prev = hidden[t].reshape(1, N, D) cell_t_prev = cell[t].reshape(1, N, D) gates = np.dot(hidden_t_prev, gates_w.T) + gates_b gates = (alpha * gates * input_t) + \ (beta1 * gates) + \ (beta2 * input_t) + \ b gates = layer_norm_with_scale_and_bias_ref( gates, gates_t_norm_scale, gates_t_norm_bias ) hidden_t, cell_t = lstm_unit( hidden_t_prev, cell_t_prev, gates, seq_lengths, t, forget_bias=forget_bias, drop_states=drop_states, ) hidden[t + 1] = hidden_t cell[t + 1] = cell_t return ( hidden[1:], hidden[-1].reshape(1, N, D), cell[1:], cell[-1].reshape(1, N, D) ) def lstm_input(): ''' Create input tensor where each dimension is from 1 to 4, ndim=3 and last dimension size is a factor of 4 ''' dims_ = st.tuples( st.integers(min_value=1, max_value=4), # t st.integers(min_value=1, max_value=4), # n st.integers(min_value=1, max_value=4), # d ) def create_input(dims): dims = list(dims) dims[2] *= 4 return hu.arrays(dims) return dims_.flatmap(create_input) def _prepare_attention(t, n, dim_in, encoder_dim, forward_only=False, T=None, dim_out=None, residual=False, final_dropout=False): if dim_out is None: dim_out = [dim_in] print("Dims: t={} n={} dim_in={} dim_out={}".format(t, n, dim_in, dim_out)) model = ModelHelper(name='external') def generate_input_state(shape): return np.random.random(shape).astype(np.float32) initial_states = [] for layer_id, d in enumerate(dim_out): h, c = model.net.AddExternalInputs( "hidden_init_{}".format(layer_id), "cell_init_{}".format(layer_id), ) initial_states.extend([h, c]) workspace.FeedBlob(h, generate_input_state((1, n, d))) workspace.FeedBlob(c, generate_input_state((1, n, d))) awec_init = model.net.AddExternalInputs([ 'initial_attention_weighted_encoder_context', ]) initial_states.append(awec_init) workspace.FeedBlob( awec_init, generate_input_state((1, n, encoder_dim)), ) # Due to convoluted RNN scoping logic we make sure that things # work from a namescope with scope.NameScope("test_name_scope"): ( input_blob, seq_lengths, encoder_outputs, weighted_encoder_outputs, ) = model.net.AddScopedExternalInputs( 'input_blob', 'seq_lengths', 'encoder_outputs', 'weighted_encoder_outputs', ) layer_input_dim = dim_in cells = [] for layer_id, d in enumerate(dim_out): cell = rnn_cell.MILSTMCell( name='decoder_{}'.format(layer_id), forward_only=forward_only, input_size=layer_input_dim, hidden_size=d, forget_bias=0.0, memory_optimization=False, ) cells.append(cell) layer_input_dim = d decoder_cell = rnn_cell.MultiRNNCell( cells, name='decoder', residual_output_layers=range(1, len(cells)) if residual else None, ) attention_cell = rnn_cell.AttentionCell( encoder_output_dim=encoder_dim, encoder_outputs=encoder_outputs, encoder_lengths=None, decoder_cell=decoder_cell, decoder_state_dim=dim_out[-1], name='attention_decoder', attention_type=AttentionType.Recurrent, weighted_encoder_outputs=weighted_encoder_outputs, attention_memory_optimization=True, ) if final_dropout: # dropout ratio of 0.0 used to test mechanism but not interfere # with numerical tests attention_cell = rnn_cell.DropoutCell( internal_cell=attention_cell, dropout_ratio=0.0, name='dropout', forward_only=forward_only, is_test=False, ) attention_cell = ( attention_cell if T is None else rnn_cell.UnrolledCell(attention_cell, T) ) output_indices = decoder_cell.output_indices output_indices.append(2 * len(cells)) outputs_with_grads = [2 * i for i in output_indices] final_output, state_outputs = attention_cell.apply_over_sequence( model=model, inputs=input_blob, seq_lengths=seq_lengths, initial_states=initial_states, outputs_with_grads=outputs_with_grads, ) workspace.RunNetOnce(model.param_init_net) workspace.FeedBlob( seq_lengths, np.random.randint(1, t + 1, size=(n,)).astype(np.int32) ) return { 'final_output': final_output, 'net': model.net, 'initial_states': initial_states, 'input_blob': input_blob, 'encoder_outputs': encoder_outputs, 'weighted_encoder_outputs': weighted_encoder_outputs, 'outputs_with_grads': outputs_with_grads, } class MulCell(rnn_cell.RNNCell): def _apply(self, model, input_t, seq_lengths, states, timestep, extra_inputs): assert len(states) == 1 result = model.net.Mul([input_t, states[0]]) model.net.AddExternalOutput(result) return [result] def get_state_names(self): return [self.scope("state")] def prepare_mul_rnn(model, input_blob, shape, T, outputs_with_grad, num_layers): print("Shape: ", shape) t, n, d = shape cells = [MulCell(name="layer_{}".format(i)) for i in range(num_layers)] cell = rnn_cell.MultiRNNCell(name="multi_mul_rnn", cells=cells) if T is not None: cell = rnn_cell.UnrolledCell(cell, T=T) states = [ model.param_init_net.ConstantFill( [], "initial_state_{}".format(i), value=1.0, shape=[1, n, d]) for i in range(num_layers)] _, results = cell.apply_over_sequence( model=model, inputs=input_blob, initial_states=states, outputs_with_grads=[ x + 2 * (num_layers - 1) for x in outputs_with_grad ], seq_lengths=None, ) return results[-2:] class RNNCellTest(hu.HypothesisTestCase): @given( input_tensor=hu.tensor(min_dim=3, max_dim=3, max_value=3), num_layers=st.integers(1, 4), outputs_with_grad=st.sampled_from( [[0], [1], [0, 1]] ), ) @ht_settings(max_examples=10) def test_unroll_mul(self, input_tensor, num_layers, outputs_with_grad): outputs = [] nets = [] input_blob = None for T in [input_tensor.shape[0], None]: model = ModelHelper("rnn_mul_{}".format( "unroll" if T else "dynamic")) input_blob = model.net.AddExternalInputs("input_blob") outputs.append( prepare_mul_rnn(model, input_blob, input_tensor.shape, T, outputs_with_grad, num_layers)) workspace.RunNetOnce(model.param_init_net) nets.append(model.net) workspace.blobs[input_blob] = input_tensor gradient_checker.NetGradientChecker.CompareNets( nets, outputs, outputs_with_grad_ids=outputs_with_grad, inputs_with_grads=[input_blob], ) @given( input_tensor=hu.tensor(min_dim=3, max_dim=3, max_value=3), forget_bias=st.floats(-10.0, 10.0), drop_states=st.booleans(), dim_out=st.lists( elements=st.integers(min_value=1, max_value=3), min_size=1, max_size=3, ), outputs_with_grads=st.sampled_from( [[0], [1], [0, 1], [0, 2], [0, 1, 2, 3]] ) ) @ht_settings(max_examples=10) @utils.debug def test_unroll_lstm(self, input_tensor, dim_out, outputs_with_grads, **kwargs): lstms = [ _prepare_rnn( *input_tensor.shape, create_rnn=rnn_cell.LSTM, outputs_with_grads=outputs_with_grads, T=T, two_d_initial_states=False, dim_out=dim_out, **kwargs ) for T in [input_tensor.shape[0], None] ] outputs, nets, inputs = zip(*lstms) workspace.FeedBlob(inputs[0][-1], input_tensor) assert inputs[0] == inputs[1] gradient_checker.NetGradientChecker.CompareNets( nets, outputs, outputs_with_grads, inputs_with_grads=inputs[0], ) @given( input_tensor=hu.tensor(min_dim=3, max_dim=3, max_value=3), encoder_length=st.integers(min_value=1, max_value=3), encoder_dim=st.integers(min_value=1, max_value=3), hidden_units=st.integers(min_value=1, max_value=3), num_layers=st.integers(min_value=1, max_value=3), residual=st.booleans(), final_dropout=st.booleans(), ) @ht_settings(max_examples=10) @utils.debug def test_unroll_attention(self, input_tensor, encoder_length, encoder_dim, hidden_units, num_layers, residual, final_dropout): dim_out = [hidden_units] * num_layers encoder_tensor = np.random.random( (encoder_length, input_tensor.shape[1], encoder_dim), ).astype('float32') print('Decoder input shape: {}'.format(input_tensor.shape)) print('Encoder output shape: {}'.format(encoder_tensor.shape)) # Necessary because otherwise test fails for networks with fewer # layers than previous test. TODO: investigate why. workspace.ResetWorkspace() net, unrolled = [ _prepare_attention( t=input_tensor.shape[0], n=input_tensor.shape[1], dim_in=input_tensor.shape[2], encoder_dim=encoder_dim, T=T, dim_out=dim_out, residual=residual, final_dropout=final_dropout, ) for T in [input_tensor.shape[0], None] ] workspace.FeedBlob(net['input_blob'], input_tensor) workspace.FeedBlob(net['encoder_outputs'], encoder_tensor) workspace.FeedBlob( net['weighted_encoder_outputs'], np.random.random(encoder_tensor.shape).astype('float32'), ) for input_name in [ 'input_blob', 'encoder_outputs', 'weighted_encoder_outputs', ]: assert net[input_name] == unrolled[input_name] for state_name, unrolled_state_name in zip( net['initial_states'], unrolled['initial_states'], ): assert state_name == unrolled_state_name inputs_with_grads = net['initial_states'] + [ net['input_blob'], net['encoder_outputs'], net['weighted_encoder_outputs'], ] gradient_checker.NetGradientChecker.CompareNets( [net['net'], unrolled['net']], [[net['final_output']], [unrolled['final_output']]], [0], inputs_with_grads=inputs_with_grads, threshold=0.000001, ) @given( input_tensor=hu.tensor(min_dim=3, max_dim=3), forget_bias=st.floats(-10.0, 10.0), forward_only=st.booleans(), drop_states=st.booleans(), ) @ht_settings(max_examples=10) def test_layered_lstm(self, input_tensor, **kwargs): for outputs_with_grads in [[0], [1], [0, 1, 2, 3]]: for memory_optim in [False, True]: _, net, inputs = _prepare_rnn( *input_tensor.shape, create_rnn=rnn_cell.LSTM, outputs_with_grads=outputs_with_grads, memory_optim=memory_optim, **kwargs ) workspace.FeedBlob(inputs[-1], input_tensor) workspace.RunNetOnce(net) workspace.ResetWorkspace() def test_lstm(self): self.lstm_base(lstm_type=(rnn_cell.LSTM, lstm_reference)) def test_milstm(self): self.lstm_base(lstm_type=(rnn_cell.MILSTM, milstm_reference)) @unittest.skip("This is currently numerically unstable") def test_norm_lstm(self): self.lstm_base( lstm_type=(rnn_cell.LayerNormLSTM, layer_norm_lstm_reference), ) @unittest.skip("This is currently numerically unstable") def test_norm_milstm(self): self.lstm_base( lstm_type=(rnn_cell.LayerNormMILSTM, layer_norm_milstm_reference) ) @given( seed=st.integers(0, 2**32 - 1), input_tensor=lstm_input(), forget_bias=st.floats(-10.0, 10.0), fwd_only=st.booleans(), drop_states=st.booleans(), memory_optim=st.booleans(), outputs_with_grads=st.sampled_from([[0], [1], [0, 1, 2, 3]]), ) def lstm_base(self, seed, lstm_type, outputs_with_grads, memory_optim, input_tensor, forget_bias, fwd_only, drop_states): np.random.seed(seed) create_lstm, ref = lstm_type ref = partial(ref, forget_bias=forget_bias) t, n, d = input_tensor.shape assert d % 4 == 0 d = d // 4 ref = partial(ref, forget_bias=forget_bias, drop_states=drop_states) net = _prepare_rnn(t, n, d, create_lstm, outputs_with_grads=outputs_with_grads, memory_optim=memory_optim, forget_bias=forget_bias, forward_only=fwd_only, drop_states=drop_states)[1] # here we don't provide a real input for the net but just for one of # its ops (RecurrentNetworkOp). So have to hardcode this name workspace.FeedBlob("test_name_scope/external/recurrent/i2h", input_tensor) op = net._net.op[-1] inputs = [workspace.FetchBlob(name) for name in op.input] # Validate forward only mode is in effect if fwd_only: for arg in op.arg: self.assertFalse(arg.name == 'backward_step_net') self.assertReferenceChecks( hu.cpu_do, op, inputs, ref, outputs_to_check=list(range(4)), ) # Checking for input, gates_t_w and gates_t_b gradients if not fwd_only: for param in range(5): self.assertGradientChecks( device_option=hu.cpu_do, op=op, inputs=inputs, outputs_to_check=param, outputs_with_grads=outputs_with_grads, threshold=0.01, stepsize=0.005, ) def test_lstm_extract_predictor_net(self): model = ModelHelper(name="lstm_extract_test") with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU, 0)): output, _, _, _ = rnn_cell.LSTM( model=model, input_blob="input", seq_lengths="seqlengths", initial_states=("hidden_init", "cell_init"), dim_in=20, dim_out=40, scope="test", drop_states=True, return_last_layer_only=True, ) # Run param init net to get the shapes for all inputs shapes = {} workspace.RunNetOnce(model.param_init_net) for b in workspace.Blobs(): shapes[b] = workspace.FetchBlob(b).shape # But export in CPU (predict_net, export_blobs) = ExtractPredictorNet( net_proto=model.net.Proto(), input_blobs=["input"], output_blobs=[output], device=core.DeviceOption(caffe2_pb2.CPU, 1), ) # Create the net and run once to see it is valid # Populate external inputs with correctly shaped random input # and also ensure that the export_blobs was constructed correctly. workspace.ResetWorkspace() shapes['input'] = [10, 4, 20] shapes['cell_init'] = [1, 4, 40] shapes['hidden_init'] = [1, 4, 40] print(predict_net.Proto().external_input) self.assertTrue('seqlengths' in predict_net.Proto().external_input) for einp in predict_net.Proto().external_input: if einp == 'seqlengths': workspace.FeedBlob( "seqlengths", np.array([10] * 4, dtype=np.int32) ) else: workspace.FeedBlob( einp, np.zeros(shapes[einp]).astype(np.float32), ) if einp != 'input': self.assertTrue(einp in export_blobs) print(str(predict_net.Proto())) self.assertTrue(workspace.CreateNet(predict_net.Proto())) self.assertTrue(workspace.RunNet(predict_net.Proto().name)) # Validate device options set correctly for the RNNs for op in predict_net.Proto().op: if op.type == 'RecurrentNetwork': for arg in op.arg: if arg.name == "step_net": for step_op in arg.n.op: self.assertEqual(0, step_op.device_option.device_type) self.assertEqual(1, step_op.device_option.cuda_gpu_id) elif arg.name == 'backward_step_net': self.assertEqual(caffe2_pb2.NetDef(), arg.n) def test_lstm_params(self): model = ModelHelper(name="lstm_params_test") with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU, 0)): output, _, _, _ = rnn_cell.LSTM( model=model, input_blob="input", seq_lengths="seqlengths", initial_states=None, dim_in=20, dim_out=40, scope="test", drop_states=True, return_last_layer_only=True, ) for param in model.GetParams(): self.assertNotEqual(model.get_param_info(param), None) def test_milstm_params(self): model = ModelHelper(name="milstm_params_test") with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU, 0)): output, _, _, _ = rnn_cell.MILSTM( model=model, input_blob="input", seq_lengths="seqlengths", initial_states=None, dim_in=20, dim_out=[40, 20], scope="test", drop_states=True, return_last_layer_only=True, ) for param in model.GetParams(): self.assertNotEqual(model.get_param_info(param), None) def test_layer_norm_lstm_params(self): model = ModelHelper(name="layer_norm_lstm_params_test") with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU, 0)): output, _, _, _ = rnn_cell.LayerNormLSTM( model=model, input_blob="input", seq_lengths="seqlengths", initial_states=None, dim_in=20, dim_out=40, scope="test", drop_states=True, return_last_layer_only=True, ) for param in model.GetParams(): self.assertNotEqual(model.get_param_info(param), None) @given(encoder_output_length=st.integers(1, 3), encoder_output_dim=st.integers(1, 3), decoder_input_length=st.integers(1, 3), decoder_state_dim=st.integers(1, 3), batch_size=st.integers(1, 3), **hu.gcs) def test_lstm_with_regular_attention( self, encoder_output_length, encoder_output_dim, decoder_input_length, decoder_state_dim, batch_size, gc, dc, ): self.lstm_with_attention( partial( rnn_cell.LSTMWithAttention, attention_type=AttentionType.Regular, ), encoder_output_length, encoder_output_dim, decoder_input_length, decoder_state_dim, batch_size, lstm_with_regular_attention_reference, gc, ) @given(encoder_output_length=st.integers(1, 3), encoder_output_dim=st.integers(1, 3), decoder_input_length=st.integers(1, 3), decoder_state_dim=st.integers(1, 3), batch_size=st.integers(1, 3), **hu.gcs) def test_lstm_with_recurrent_attention( self, encoder_output_length, encoder_output_dim, decoder_input_length, decoder_state_dim, batch_size, gc, dc, ): self.lstm_with_attention( partial( rnn_cell.LSTMWithAttention, attention_type=AttentionType.Recurrent, ), encoder_output_length, encoder_output_dim, decoder_input_length, decoder_state_dim, batch_size, lstm_with_recurrent_attention_reference, gc, ) @given(encoder_output_length=st.integers(2, 2), encoder_output_dim=st.integers(4, 4), decoder_input_length=st.integers(3, 3), decoder_state_dim=st.integers(4, 4), batch_size=st.integers(5, 5), **hu.gcs) def test_lstm_with_dot_attention_same_dim( self, encoder_output_length, encoder_output_dim, decoder_input_length, decoder_state_dim, batch_size, gc, dc, ): self.lstm_with_attention( partial( rnn_cell.LSTMWithAttention, attention_type=AttentionType.Dot, ), encoder_output_length, encoder_output_dim, decoder_input_length, decoder_state_dim, batch_size, lstm_with_dot_attention_reference_same_dim, gc, ) @given(encoder_output_length=st.integers(1, 3), encoder_output_dim=st.integers(4, 4), decoder_input_length=st.integers(1, 3), decoder_state_dim=st.integers(5, 5), batch_size=st.integers(1, 3), **hu.gcs) def test_lstm_with_dot_attention_different_dim( self, encoder_output_length, encoder_output_dim, decoder_input_length, decoder_state_dim, batch_size, gc, dc, ): self.lstm_with_attention( partial( rnn_cell.LSTMWithAttention, attention_type=AttentionType.Dot, ), encoder_output_length, encoder_output_dim, decoder_input_length, decoder_state_dim, batch_size, lstm_with_dot_attention_reference_different_dim, gc, ) @given(encoder_output_length=st.integers(2, 3), encoder_output_dim=st.integers(1, 3), decoder_input_length=st.integers(1, 3), decoder_state_dim=st.integers(1, 3), batch_size=st.integers(1, 3), **hu.gcs) def test_lstm_with_coverage_attention( self, encoder_output_length, encoder_output_dim, decoder_input_length, decoder_state_dim, batch_size, gc, dc, ): self.lstm_with_attention( partial( rnn_cell.LSTMWithAttention, attention_type=AttentionType.SoftCoverage, ), encoder_output_length, encoder_output_dim, decoder_input_length, decoder_state_dim, batch_size, lstm_with_coverage_attention_reference, gc, ) def lstm_with_attention( self, create_lstm_with_attention, encoder_output_length, encoder_output_dim, decoder_input_length, decoder_state_dim, batch_size, ref, gc, ): model = ModelHelper(name='external') with core.DeviceScope(gc): ( encoder_outputs, decoder_inputs, decoder_input_lengths, initial_decoder_hidden_state, initial_decoder_cell_state, initial_attention_weighted_encoder_context, ) = model.net.AddExternalInputs( 'encoder_outputs', 'decoder_inputs', 'decoder_input_lengths', 'initial_decoder_hidden_state', 'initial_decoder_cell_state', 'initial_attention_weighted_encoder_context', ) create_lstm_with_attention( model=model, decoder_inputs=decoder_inputs, decoder_input_lengths=decoder_input_lengths, initial_decoder_hidden_state=initial_decoder_hidden_state, initial_decoder_cell_state=initial_decoder_cell_state, initial_attention_weighted_encoder_context=( initial_attention_weighted_encoder_context ), encoder_output_dim=encoder_output_dim, encoder_outputs=encoder_outputs, encoder_lengths=None, decoder_input_dim=decoder_state_dim, decoder_state_dim=decoder_state_dim, scope='external/LSTMWithAttention', ) op = model.net._net.op[-2] workspace.RunNetOnce(model.param_init_net) # This is original decoder_inputs after linear layer decoder_input_blob = op.input[0] workspace.FeedBlob( decoder_input_blob, np.random.randn( decoder_input_length, batch_size, decoder_state_dim * 4, ).astype(np.float32)) workspace.FeedBlob( 'external/LSTMWithAttention/encoder_outputs_transposed', np.random.randn( batch_size, encoder_output_dim, encoder_output_length, ).astype(np.float32), ) workspace.FeedBlob( 'external/LSTMWithAttention/weighted_encoder_outputs', np.random.randn( encoder_output_length, batch_size, encoder_output_dim, ).astype(np.float32), ) workspace.FeedBlob( 'external/LSTMWithAttention/coverage_weights', np.random.randn( encoder_output_length, batch_size, encoder_output_dim, ).astype(np.float32), ) workspace.FeedBlob( decoder_input_lengths, np.random.randint( 0, decoder_input_length + 1, size=(batch_size,) ).astype(np.int32)) workspace.FeedBlob( initial_decoder_hidden_state, np.random.randn(1, batch_size, decoder_state_dim).astype(np.float32) ) workspace.FeedBlob( initial_decoder_cell_state, np.random.randn(1, batch_size, decoder_state_dim).astype(np.float32) ) workspace.FeedBlob( initial_attention_weighted_encoder_context, np.random.randn( 1, batch_size, encoder_output_dim).astype(np.float32) ) workspace.FeedBlob( 'external/LSTMWithAttention/initial_coverage', np.zeros((1, batch_size, encoder_output_length)).astype(np.float32), ) inputs = [workspace.FetchBlob(name) for name in op.input] self.assertReferenceChecks( device_option=gc, op=op, inputs=inputs, reference=ref, grad_reference=None, output_to_grad=None, outputs_to_check=list(range(6)), ) gradients_to_check = [ index for (index, input_name) in enumerate(op.input) if input_name != 'decoder_input_lengths' ] for param in gradients_to_check: self.assertGradientChecks( device_option=gc, op=op, inputs=inputs, outputs_to_check=param, outputs_with_grads=[0, 4], threshold=0.01, stepsize=0.001, ) @given(seed=st.integers(0, 2**32 - 1), n=st.integers(1, 10), d=st.integers(1, 10), t=st.integers(1, 10), dtype=st.sampled_from([np.float32, np.float16]), use_sequence_lengths=st.booleans(), **hu.gcs) def test_lstm_unit_recurrent_network( self, seed, n, d, t, dtype, dc, use_sequence_lengths, gc): np.random.seed(seed) if dtype == np.float16: # only supported with CUDA assume(gc.device_type == caffe2_pb2.CUDA) dc = [do for do in dc if do.device_type == caffe2_pb2.CUDA] if use_sequence_lengths: op_inputs = ['hidden_t_prev', 'cell_t_prev', 'gates_t', 'seq_lengths', 'timestep'] else: op_inputs = ['hidden_t_prev', 'cell_t_prev', 'gates_t', 'timestep'] op = core.CreateOperator( 'LSTMUnit', op_inputs, ['hidden_t', 'cell_t'], sequence_lengths=use_sequence_lengths, ) cell_t_prev = np.random.randn(1, n, d).astype(dtype) hidden_t_prev = np.random.randn(1, n, d).astype(dtype) gates = np.random.randn(1, n, 4 * d).astype(dtype) seq_lengths = np.random.randint(1, t + 1, size=(n,)).astype(np.int32) timestep = np.random.randint(0, t, size=(1,)).astype(np.int32) if use_sequence_lengths: inputs = [hidden_t_prev, cell_t_prev, gates, seq_lengths, timestep] else: inputs = [hidden_t_prev, cell_t_prev, gates, timestep] input_device_options = {'timestep': hu.cpu_do} self.assertDeviceChecks( dc, op, inputs, [0], input_device_options=input_device_options) kwargs = {} if dtype == np.float16: kwargs['threshold'] = 1e-1 # default is 1e-4 def lstm_unit_reference(*args, **kwargs): return lstm_unit(*args, sequence_lengths=use_sequence_lengths, **kwargs) self.assertReferenceChecks( gc, op, inputs, lstm_unit_reference, input_device_options=input_device_options, **kwargs) kwargs = {} if dtype == np.float16: kwargs['threshold'] = 0.5 # default is 0.005 for i in range(2): self.assertGradientChecks( gc, op, inputs, i, [0, 1], input_device_options=input_device_options, **kwargs) @given(input_length=st.integers(2, 5), dim_in=st.integers(1, 3), max_num_units=st.integers(1, 3), num_layers=st.integers(2, 3), batch_size=st.integers(1, 3)) def test_multi_lstm( self, input_length, dim_in, max_num_units, num_layers, batch_size, ): model = ModelHelper(name='external') ( input_sequence, seq_lengths, ) = model.net.AddExternalInputs( 'input_sequence', 'seq_lengths', ) dim_out = [ np.random.randint(1, max_num_units + 1) for _ in range(num_layers) ] h_all, h_last, c_all, c_last = rnn_cell.LSTM( model=model, input_blob=input_sequence, seq_lengths=seq_lengths, initial_states=None, dim_in=dim_in, dim_out=dim_out, # scope='test', outputs_with_grads=(0,), return_params=False, memory_optimization=False, forget_bias=0.0, forward_only=False, return_last_layer_only=True, ) workspace.RunNetOnce(model.param_init_net) seq_lengths_val = np.random.randint( 1, input_length + 1, size=(batch_size), ).astype(np.int32) input_sequence_val = np.random.randn( input_length, batch_size, dim_in, ).astype(np.float32) workspace.FeedBlob(seq_lengths, seq_lengths_val) workspace.FeedBlob(input_sequence, input_sequence_val) hidden_input_list = [] cell_input_list = [] i2h_w_list = [] i2h_b_list = [] gates_w_list = [] gates_b_list = [] for i in range(num_layers): hidden_input_list.append( workspace.FetchBlob( 'layer_{}/initial_hidden_state'.format(i)), ) cell_input_list.append( workspace.FetchBlob( 'layer_{}/initial_cell_state'.format(i)), ) # Input projection for the first layer is produced outside # of the cell ans thus not scoped prefix = 'layer_{}/'.format(i) if i > 0 else '' i2h_w_list.append( workspace.FetchBlob('{}i2h_w'.format(prefix)), ) i2h_b_list.append( workspace.FetchBlob('{}i2h_b'.format(prefix)), ) gates_w_list.append( workspace.FetchBlob('layer_{}/gates_t_w'.format(i)), ) gates_b_list.append( workspace.FetchBlob('layer_{}/gates_t_b'.format(i)), ) workspace.RunNetOnce(model.net) h_all_calc = workspace.FetchBlob(h_all) h_last_calc = workspace.FetchBlob(h_last) c_all_calc = workspace.FetchBlob(c_all) c_last_calc = workspace.FetchBlob(c_last) h_all_ref, h_last_ref, c_all_ref, c_last_ref = multi_lstm_reference( input_sequence_val, hidden_input_list, cell_input_list, i2h_w_list, i2h_b_list, gates_w_list, gates_b_list, seq_lengths_val, forget_bias=0.0, ) h_all_delta = np.abs(h_all_ref - h_all_calc).sum() h_last_delta = np.abs(h_last_ref - h_last_calc).sum() c_all_delta = np.abs(c_all_ref - c_all_calc).sum() c_last_delta = np.abs(c_last_ref - c_last_calc).sum() self.assertAlmostEqual(h_all_delta, 0.0, places=5) self.assertAlmostEqual(h_last_delta, 0.0, places=5) self.assertAlmostEqual(c_all_delta, 0.0, places=5) self.assertAlmostEqual(c_last_delta, 0.0, places=5) input_values = { 'input_sequence': input_sequence_val, 'seq_lengths': seq_lengths_val, } for param in model.GetParams(): value = workspace.FetchBlob(param) input_values[str(param)] = value output_sum = model.net.SumElements( [h_all], 'output_sum', average=True, ) fake_loss = model.net.Tanh( output_sum, ) for param in model.GetParams(): gradient_checker.NetGradientChecker.Check( model.net, outputs_with_grad=[fake_loss], input_values=input_values, input_to_check=str(param), print_net=False, step_size=0.0001, threshold=0.05, ) if __name__ == "__main__": workspace.GlobalInit([ 'caffe2', '--caffe2_log_level=0', ]) unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import model_helper, workspace, core, rnn_cell from caffe2.python.attention import AttentionType import numpy as np import unittest import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st from hypothesis import given class TestRNNExecutor(unittest.TestCase): def setUp(self): self.batch_size = 8 self.input_dim = 20 self.hidden_dim = 30 self.encoder_dim = 40 @given( T=st.integers(10, 100), forward_only=st.booleans(), **hu.gcs) def test_lstm_with_attention_equal_simplenet(self, T, forward_only, gc, dc): self.Tseq = [T, T // 2, T // 2 + T // 4, T, T // 2 + 1] workspace.ResetWorkspace() with core.DeviceScope(gc): print("Run with device: {}, forward only: {}".format( gc, forward_only)) workspace.FeedBlob( "seq_lengths", np.array([T] * self.batch_size, dtype=np.int32) ) workspace.FeedBlob("target", np.random.rand( T, self.batch_size, self.hidden_dim).astype(np.float32)) workspace.FeedBlob("hidden_init", np.zeros( [1, self.batch_size, self.hidden_dim], dtype=np.float32 )) workspace.FeedBlob("cell_init", np.zeros( [1, self.batch_size, self.hidden_dim], dtype=np.float32 )) model = model_helper.ModelHelper(name="lstm") model.net.AddExternalInputs(["input"]) init_blobs = [] hidden_init, cell_init, encoder_outputs = model.net.AddExternalInputs( "hidden_init", "cell_init", "encoder_outputs" ) awec_init = model.net.AddExternalInputs([ 'initial_attention_weighted_encoder_context', ]) init_blobs.extend([hidden_init, cell_init]) workspace.FeedBlob( awec_init, np.random.rand(1, self.batch_size, self.encoder_dim).astype( np.float32), ) workspace.FeedBlob( encoder_outputs, np.random.rand(1, self.batch_size, self.encoder_dim).astype( np.float32), ) outputs = rnn_cell.LSTMWithAttention( model=model, decoder_inputs="input", decoder_input_lengths="seq_lengths", initial_decoder_hidden_state=hidden_init, initial_decoder_cell_state=cell_init, initial_attention_weighted_encoder_context=awec_init, encoder_output_dim=self.encoder_dim, encoder_outputs=encoder_outputs, encoder_lengths=None, decoder_input_dim=self.input_dim, decoder_state_dim=self.hidden_dim, scope="", attention_type=AttentionType.Recurrent, forward_only=forward_only, outputs_with_grads=[0], ) output = outputs[0] print(outputs) loss = model.AveragedLoss( model.SquaredL2Distance([output, "target"], "dist"), "loss" ) # Add gradient ops if not forward_only: model.AddGradientOperators([loss]) # init for init_blob in init_blobs: workspace.FeedBlob(init_blob, np.zeros( [1, self.batch_size, self.hidden_dim], dtype=np.float32 )) self._compare(model, forward_only) @given( num_layers=st.integers(1, 8), T=st.integers(4, 100), forward_only=st.booleans(), **hu.gcs) def test_lstm_equal_simplenet(self, num_layers, T, forward_only, gc, dc): ''' Test that the RNN executor produces same results as the non-executor (i.e running step nets as sequence of simple nets). ''' self.Tseq = [T, T // 2, T // 2 + T // 4, T, T // 2 + 1] workspace.ResetWorkspace() with core.DeviceScope(gc): print("Run with device: {}, forward only: {}".format( gc, forward_only)) workspace.FeedBlob( "seq_lengths", np.array([T] * self.batch_size, dtype=np.int32) ) workspace.FeedBlob("target", np.random.rand( T, self.batch_size, self.hidden_dim).astype(np.float32)) workspace.FeedBlob("hidden_init", np.zeros( [1, self.batch_size, self.hidden_dim], dtype=np.float32 )) workspace.FeedBlob("cell_init", np.zeros( [1, self.batch_size, self.hidden_dim], dtype=np.float32 )) model = model_helper.ModelHelper(name="lstm") model.net.AddExternalInputs(["input"]) init_blobs = [] for i in range(num_layers): hidden_init, cell_init = model.net.AddExternalInputs( "hidden_init_{}".format(i), "cell_init_{}".format(i) ) init_blobs.extend([hidden_init, cell_init]) output, last_hidden, _, last_state = rnn_cell.LSTM( model=model, input_blob="input", seq_lengths="seq_lengths", initial_states=init_blobs, dim_in=self.input_dim, dim_out=[self.hidden_dim] * num_layers, scope="", drop_states=True, forward_only=forward_only, return_last_layer_only=True, ) loss = model.AveragedLoss( model.SquaredL2Distance([output, "target"], "dist"), "loss" ) # Add gradient ops if not forward_only: model.AddGradientOperators([loss]) # init for init_blob in init_blobs: workspace.FeedBlob(init_blob, np.zeros( [1, self.batch_size, self.hidden_dim], dtype=np.float32 )) self._compare(model, forward_only) def _compare(self, model, forward_only): # Store list of blobs that exist in the beginning workspace.RunNetOnce(model.param_init_net) init_ws = {k: workspace.FetchBlob(k) for k in workspace.Blobs()} # Run with executor for enable_executor in [0, 1]: self.enable_rnn_executor(model.net, enable_executor, forward_only) workspace.ResetWorkspace() # Reset original state for k, v in init_ws.items(): workspace.FeedBlob(k, v) np.random.seed(10022015) ws = {} for j in range(len(self.Tseq)): input_shape = [self.Tseq[j], self.batch_size, self.input_dim] workspace.FeedBlob( "input", np.random.rand(*input_shape).astype(np.float32)) workspace.FeedBlob( "target", np.random.rand( self.Tseq[j], self.batch_size, self.hidden_dim ).astype(np.float32)) if j == 0: workspace.CreateNet(model.net, overwrite=True) workspace.RunNet(model.net.Proto().name) # Store results for each iteration for k in workspace.Blobs(): ws[k + "." + str(j)] = workspace.FetchBlob(k) if enable_executor: rnn_exec_ws = ws else: non_exec_ws = ws # Test that all blobs are equal after running with executor # or without. self.assertEqual(list(non_exec_ws.keys()), list(rnn_exec_ws.keys())) mismatch = False for k in rnn_exec_ws.keys(): non_exec_v = non_exec_ws[k] rnn_exec_v = rnn_exec_ws[k] if type(non_exec_v) is np.ndarray: if not np.array_equal(non_exec_v, rnn_exec_v): print("Mismatch: {}".format(k)) nv = non_exec_v.flatten() rv = rnn_exec_v.flatten() c = 0 for j in range(len(nv)): if rv[j] != nv[j]: print(j, rv[j], nv[j]) c += 1 if c == 10: break mismatch = True self.assertFalse(mismatch) def enable_rnn_executor(self, net, value, forward_only): num_found = 0 for op in net.Proto().op: if op.type.startswith("RecurrentNetwork"): for arg in op.arg: if arg.name == 'enable_rnn_executor': arg.i = value num_found += 1 # This sanity check is so that if someone changes the # enable_rnn_executor parameter name, the test will # start failing as this function will become defective. self.assertEqual(1 if forward_only else 2, num_found) if __name__ == "__main__": import unittest import random random.seed(2603) workspace.GlobalInit([ 'caffe2', '--caffe2_log_level=0', '--caffe2_rnn_executor=1']) unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import unittest from caffe2.proto import caffe2_pb2 from caffe2.python import workspace, core, model_helper, brew class CopyOpsTest(unittest.TestCase): def tearDown(self): # Reset workspace after each test # Otherwise, the multi-GPU test will use previously created tensors, # which may have been placed on the wrong device workspace.ResetWorkspace() def run_test_copy_gradient(self, device_opt): model = model_helper.ModelHelper(name="copy_test") with core.DeviceScope(device_opt): x = model.net.AddExternalInputs("x") y = model.Copy(x, "y") loss = model.AveragedLoss(y, "loss") gradient_map = model.AddGradientOperators([loss]) workspace.FeedBlob(x, np.random.rand(32).astype(np.float32)) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) self.assertTrue(np.array_equal( workspace.FetchBlob(x), workspace.FetchBlob(y), )) self.assertTrue(np.array_equal( workspace.FetchBlob(gradient_map[x]), workspace.FetchBlob(gradient_map[y]), )) def test_copy_gradient_cpu(self): self.run_test_copy_gradient(core.DeviceOption(caffe2_pb2.CPU, 0)) @unittest.skipIf(workspace.NumCudaDevices() < 1, "Need at least 1 GPU.") def test_copy_gradient_gpu(self): self.run_test_copy_gradient(core.DeviceOption(caffe2_pb2.CUDA, 0)) @unittest.skipIf(workspace.NumCudaDevices() < 2, "Need at least 2 GPU.") def test_copy_gradient_multiple_gpus(self): model = model_helper.ModelHelper(name="copy_test") with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU, 0)): x_cpu = model.net.AddExternalInputs("x_cpu") with core.DeviceScope(core.DeviceOption(caffe2_pb2.CUDA, 0)): x_gpu_1 = model.CopyCPUToGPU(x_cpu, "x_gpu_1") with core.DeviceScope(core.DeviceOption(caffe2_pb2.CUDA, 1)): x_gpu_2 = model.Copy(x_gpu_1, "x_gpu_2") loss = model.AveragedLoss(x_gpu_2, "loss") gradient_map = model.AddGradientOperators([loss]) workspace.FeedBlob("x_cpu", np.random.rand(32).astype(np.float32)) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) self.assertTrue(np.array_equal( workspace.FetchBlob("x_gpu_1"), workspace.FetchBlob("x_gpu_2"), )) self.assertTrue(np.array_equal( workspace.FetchBlob(gradient_map["x_gpu_1"]), workspace.FetchBlob(gradient_map["x_gpu_2"]), )) def get_op_with_output(model, output_blob_name): for op in model.net.Proto().op: if len(op.output) == 1 and op.output[0] == output_blob_name: return op return None self.assertEqual( get_op_with_output(model, "x_gpu_2_grad").device_option, core.DeviceOption(caffe2_pb2.CUDA, 1), ) self.assertEqual( get_op_with_output(model, "x_cpu_grad").device_option, core.DeviceOption(caffe2_pb2.CUDA, 0), ) @unittest.skipIf(workspace.NumCudaDevices() < 1, "Need at least 1 GPU.") def test_cpu2gpu_gpu2cpu_sparse_gradients(self): model = model_helper.ModelHelper(name="copy_test") v = model.param_init_net.UniformFill([], ["v"], shape=[16, 4]) indices = model.param_init_net.UniformFill([], ["v"], shape=[16, 4]) cpu_opt = core.DeviceOption(caffe2_pb2.CPU, 0) gpu_opt = core.DeviceOption(caffe2_pb2.CUDA, 0) with core.DeviceScope(gpu_opt): vcpu = model.CopyGPUToCPU(v, "vcpu") with core.DeviceScope(cpu_opt): g = model.Gather([vcpu, indices], "g") with core.DeviceScope(gpu_opt): ggpu = model.CopyCPUToGPU(g, "ggpu") f = brew.fc(model, ggpu, "out", dim_in=4, dim_out=6) (softmax, loss) = model.SoftmaxWithLoss( [f, "label"], ["softmax", "loss"], ) gradient_map = model.AddGradientOperators([loss]) self.assertTrue("v" in gradient_map) self.assertTrue(isinstance(gradient_map['v'], core.GradientSlice)) @unittest.skipIf(workspace.NumCudaDevices() < 1, "Need at least 1 GPU.") def test_cpu2gpu_gpu2cpu_gradients(self): model = model_helper.ModelHelper(name="copy_test") batch = 32 cpu_opt = core.DeviceOption(caffe2_pb2.CPU, 0) gpu_opt = core.DeviceOption(caffe2_pb2.CUDA, 0) with core.NameScope("cpu"): with core.DeviceScope(cpu_opt): x_cpu = brew.fc(model, 'data', 'x_cpu', 16, 8) with core.NameScope("gpu_0"): with core.DeviceScope(gpu_opt): x_gpu = model.CopyCPUToGPU(x_cpu, "x_gpu") pred_gpu = brew.fc(model, x_gpu, "pred_gpu", 8, 4) pred_cpu = model.CopyGPUToCPU(pred_gpu, "pred_cpu") with core.DeviceScope(cpu_opt): with core.NameScope("cpu"): (softmax, loss) = model.SoftmaxWithLoss( [pred_cpu, "label"], ["softmax", "loss"], ) gradient_map = model.AddGradientOperators([loss]) # Add param updates (for cpu and gpu) init_net = model.param_init_net with core.DeviceScope(cpu_opt): with core.NameScope("cpu"): ONE = init_net.ConstantFill([], "ONE", shape=[1], value=1.) LR = init_net.ConstantFill([], "LR", shape=[1], value=-2.0) for param in model.GetParams(): model.WeightedSum( [param, ONE, gradient_map[param], LR], param, ) with core.NameScope("gpu_0"): with core.DeviceScope(gpu_opt): ONE = init_net.ConstantFill([], "ONE", shape=[1], value=1.) LR = init_net.ConstantFill([], "LR", shape=[1], value=-2.0) for param in model.GetParams(): model.WeightedSum( [param, ONE, gradient_map[param], LR], param, ) with core.DeviceScope(cpu_opt): workspace.FeedBlob( 'cpu/data', np.random.rand(batch, 16).astype(np.float32), ) workspace.FeedBlob( 'cpu/label', np.random.randint(4, size=batch).astype(np.int32), ) workspace.RunNetOnce(model.param_init_net) workspace.CreateNet(model.net) initial_params = {p: workspace.FetchBlob(p) for p in model.GetParams()} workspace.RunNet(model.net.Proto().name) updated_params = {p: workspace.FetchBlob(p) for p in model.GetParams()} for p in model.GetParams(): g = gradient_map[p] expected = initial_params[p] - 2.0 * workspace.FetchBlob(g) actual = updated_params[p] self.assertTrue( np.array_equal(expected, updated_params[p]), "Mismatch: {}: {}, {}".format(p, expected, actual), )
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from caffe2.python.dataset import Dataset from caffe2.python.schema import ( Struct, Map, Scalar, from_blob_list, NewRecord, FeedRecord) from caffe2.python.record_queue import RecordQueue from caffe2.python.test_util import TestCase import numpy as np class TestRecordQueue(TestCase): def test_record_queue(self): num_prod = 8 num_consume = 3 schema = Struct( ('floats', Map( Scalar(np.int32), Scalar(np.float32))), ) contents_raw = [ [1, 2, 3], # len [11, 21, 22, 31, 32, 33], # key [1.1, 2.1, 2.2, 3.1, 3.2, 3.3], # value ] contents = from_blob_list(schema, contents_raw) ds = Dataset(schema) net = core.Net('init') ds.init_empty(net) content_blobs = NewRecord(net, contents) FeedRecord(content_blobs, contents) writer = ds.writer(init_net=net) writer.write_record(net, content_blobs) reader = ds.reader(init_net=net) # prepare receiving dataset rec_dataset = Dataset(contents, name='rec') rec_dataset.init_empty(init_net=net) rec_dataset_writer = rec_dataset.writer(init_net=net) workspace.RunNetOnce(net) queue = RecordQueue(contents, num_threads=num_prod) def process(net, fields): new_fields = [] for f in fields.field_blobs(): new_f = net.Copy(f) new_fields.append(new_f) new_fields = from_blob_list(fields, new_fields) return new_fields q_reader, q_step, q_exit, fields = queue.build(reader, process) producer_step = core.execution_step('producer', [q_step, q_exit]) consumer_steps = [] for i in range(num_consume): name = 'queue_reader_' + str(i) net_consume = core.Net(name) should_stop, fields = q_reader.read_record(net_consume) step_consume = core.execution_step(name, net_consume) name = 'dataset_writer_' + str(i) net_dataset = core.Net(name) rec_dataset_writer.write(net_dataset, fields.field_blobs()) step_dataset = core.execution_step(name, net_dataset) step = core.execution_step( 'consumer_' + str(i), [step_consume, step_dataset], should_stop_blob=should_stop) consumer_steps.append(step) consumer_step = core.execution_step( 'consumers', consumer_steps, concurrent_substeps=True) work_steps = core.execution_step( 'work', [producer_step, consumer_step], concurrent_substeps=True) plan = core.Plan('test') plan.AddStep(work_steps) core.workspace.RunPlan(plan) data = workspace.FetchBlobs(rec_dataset.get_blobs()) self.assertEqual(6, sum(data[0])) self.assertEqual(150, sum(data[1])) self.assertAlmostEqual(15, sum(data[2]), places=5) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from caffe2.python.test_util import TestCase import numpy as np import tempfile class TestIndexOps(TestCase): def _test_index_ops(self, entries, dtype, index_create_op): workspace.RunOperatorOnce(core.CreateOperator( index_create_op, [], ['index'], max_elements=10)) my_entries = np.array( [entries[0], entries[1], entries[2]], dtype=dtype) workspace.FeedBlob('entries', my_entries) workspace.RunOperatorOnce(core.CreateOperator( 'IndexLoad', ['index', 'entries'], ['index'])) query1 = np.array( [entries[0], entries[3], entries[0], entries[4]], dtype=dtype) workspace.FeedBlob('query1', query1) workspace.RunOperatorOnce(core.CreateOperator( 'IndexGet', ['index', 'query1'], ['result1'])) result1 = workspace.FetchBlob('result1') np.testing.assert_array_equal([1, 4, 1, 5], result1) workspace.RunOperatorOnce(core.CreateOperator( 'IndexFreeze', ['index'], ['index'])) query2 = np.array( [entries[5], entries[4], entries[0], entries[6], entries[7]], dtype=dtype) workspace.FeedBlob('query2', query2) workspace.RunOperatorOnce(core.CreateOperator( 'IndexGet', ['index', 'query2'], ['result2'])) result2 = workspace.FetchBlob('result2') np.testing.assert_array_equal([0, 5, 1, 0, 0], result2) workspace.RunOperatorOnce(core.CreateOperator( 'IndexSize', ['index'], ['index_size'])) size = workspace.FetchBlob('index_size') self.assertEquals(size, 6) workspace.RunOperatorOnce(core.CreateOperator( 'IndexStore', ['index'], ['stored_entries'])) stored_actual = workspace.FetchBlob('stored_entries') new_entries = np.array([entries[3], entries[4]], dtype=dtype) expected = np.concatenate((my_entries, new_entries)) if dtype is str: # we'll always get bytes back from Caffe2 expected = np.array([ x.item().encode('utf-8') if isinstance(x, np.str_) else x for x in expected ], dtype=object) np.testing.assert_array_equal(expected, stored_actual) workspace.RunOperatorOnce(core.CreateOperator( index_create_op, [], ['index2'])) workspace.RunOperatorOnce(core.CreateOperator( 'IndexLoad', ['index2', 'stored_entries'], ['index2'], skip_first_entry=1)) workspace.RunOperatorOnce(core.CreateOperator( 'IndexSize', ['index2'], ['index2_size'])) index2_size = workspace.FetchBlob('index2_size') self.assertEquals(index2_size, 5) # test serde with tempfile.NamedTemporaryFile() as tmp: workspace.RunOperatorOnce(core.CreateOperator( 'Save', ['index'], [], absolute_path=1, db_type='minidb', db=tmp.name)) # frees up the blob workspace.FeedBlob('index', np.array([])) # reloads the index workspace.RunOperatorOnce(core.CreateOperator( 'Load', [], ['index'], absolute_path=1, db_type='minidb', db=tmp.name)) query3 = np.array( [entries[0], entries[3], entries[0], entries[4], entries[4]], dtype=dtype) workspace.FeedBlob('query3', query3) workspace.RunOperatorOnce(core.CreateOperator( 'IndexGet', ['index', 'query3'], ['result3'])) result3 = workspace.FetchBlob('result3') np.testing.assert_array_equal([1, 4, 1, 5, 5], result3) def test_string_index_ops(self): self._test_index_ops([ 'entry1', 'entry2', 'entry3', 'new_entry1', 'new_entry2', 'miss1', 'miss2', 'miss3', ], str, 'StringIndexCreate') def test_int_index_ops(self): self._test_index_ops(list(range(8)), np.int32, 'IntIndexCreate') def test_long_index_ops(self): self._test_index_ops(list(range(8)), np.int64, 'LongIndexCreate') if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class TestElementwiseLinearOp(hu.HypothesisTestCase): @given(n=st.integers(2, 100), d=st.integers(2, 10), **hu.gcs) # @given(n=st.integers(2, 50), d=st.integers(2, 50), **hu.gcs_cpu_only) def test(self, n, d, gc, dc): X = np.random.rand(n, d).astype(np.float32) a = np.random.rand(d).astype(np.float32) b = np.random.rand(d).astype(np.float32) def ref_op(X, a, b): d = a.shape[0] return [np.multiply(X, a.reshape(1, d)) + b.reshape(1, d)] op = core.CreateOperator( "ElementwiseLinear", ["X", "a", "b"], ["Y"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, a, b], reference=ref_op, ) # Check over multiple devices self.assertDeviceChecks(dc, op, [X, a, b], [0]) # Gradient check wrt X self.assertGradientChecks(gc, op, [X, a, b], 0, [0]) # Gradient check wrt a self.assertGradientChecks(gc, op, [X, a, b], 1, [0]) # # Gradient check wrt b self.assertGradientChecks(gc, op, [X, a, b], 2, [0])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import hypothesis.strategies as st import caffe2.python.hypothesis_test_util as hu import numpy as np import unittest class TestMean(hu.HypothesisTestCase): @given( k=st.integers(1, 5), n=st.integers(1, 10), m=st.integers(1, 10), in_place=st.booleans(), seed=st.integers(0, 2**32 - 1), **hu.gcs ) def test_mean(self, k, n, m, in_place, seed, gc, dc): np.random.seed(seed) input_names = [] input_vars = [] for i in range(k): X_name = 'X' + str(i) input_names.append(X_name) var = np.random.randn(n, m).astype(np.float32) input_vars.append(var) def mean_ref(*args): return [np.mean(args, axis=0)] op = core.CreateOperator( "Mean", input_names, ['Y' if not in_place else 'X0'], ) self.assertReferenceChecks( device_option=gc, op=op, inputs=input_vars, reference=mean_ref, ) self.assertGradientChecks( device_option=gc, op=op, inputs=input_vars, outputs_to_check=0, outputs_with_grads=[0], ) self.assertDeviceChecks(dc, op, input_vars, [0]) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np import unittest class TestSpecializedSegmentOps(hu.HypothesisTestCase): @given(batchsize=st.integers(1, 20), fptype=st.sampled_from([np.float16, np.float32]), fp16asint=st.booleans(), blocksize=st.sampled_from([8, 17, 32, 64, 85, 96, 128, 163]), normalize_by_lengths=st.booleans(), **hu.gcs) def test_sparse_lengths_sum_cpu( self, batchsize, fptype, fp16asint, blocksize, normalize_by_lengths, gc, dc): if normalize_by_lengths == False: print("<test_sparse_lengths_sum_cpu>") else: print("<test_sparse_lengths_sum_mean_cpu>") tblsize = 300 if fptype == np.float32: Tbl = np.random.rand(tblsize, blocksize).astype(np.float32) atol = 1e-5 else: if fp16asint: Tbl = (10.0 * np.random.rand(tblsize, blocksize) ).round().astype(np.float16) atol = 1e-3 else: Tbl = np.random.rand(tblsize, blocksize).astype(np.float16) atol = 1e-1 # array of each row length Lengths = np.random.randint(1, 30, size=batchsize).astype(np.int32) # flat indices Indices = np.random.randint( 0, tblsize, size=sum(Lengths)).astype(np.int64) if normalize_by_lengths == False: op = core.CreateOperator("SparseLengthsSum", [ "Tbl", "Indices", "Lengths"], "out") else: op = core.CreateOperator("SparseLengthsMean", [ "Tbl", "Indices", "Lengths"], "out") self.ws.create_blob("Tbl").feed(Tbl) self.ws.create_blob("Indices").feed(Indices) self.ws.create_blob("Lengths").feed(Lengths) self.ws.run(op) def sparse_lengths_sum_ref(Tbl, Indices, Lengths): rptr = np.cumsum(np.insert(Lengths, [0], [0])) out = np.zeros((len(Lengths), blocksize)) if normalize_by_lengths == False: for i in range(0, len(rptr[0:-1])): out[i] = Tbl[Indices[rptr[i]:rptr[i + 1]]].sum(axis=0) else: for i in range(0, len(rptr[0:-1])): out[i] = Tbl[Indices[rptr[i]:rptr[i + 1]] ].sum(axis=0) * 1.0 / float(Lengths[i]) return out np.testing.assert_allclose(self.ws.blobs[("out")].fetch(), sparse_lengths_sum_ref(Tbl, Indices, Lengths), rtol=1e-3, atol=atol) @given(batchsize=st.integers(1, 20), fptype=st.sampled_from([np.float16, np.float32]), fp16asint=st.booleans(), blocksize=st.sampled_from([8, 17, 32, 64, 85, 96, 128, 163]), **hu.gcs) def test_sparse_lengths_weightedsum_cpu( self, batchsize, fptype, fp16asint, blocksize, gc, dc): print("<test_sparse_lengths_weightedsum_cpu>") tblsize = 300 if fptype == np.float32: Tbl = np.random.rand(tblsize, blocksize).astype(np.float32) atol = 1e-5 else: if fp16asint: Tbl = (10.0 * np.random.rand(tblsize, blocksize) ).round().astype(np.float16) atol = 1e-3 else: Tbl = np.random.rand(tblsize, blocksize).astype(np.float16) atol = 1e-1 # array of each row length Lengths = np.random.randint(1, 30, size=batchsize).astype(np.int32) # flat indices Indices = np.random.randint( 0, tblsize, size=sum(Lengths)).astype(np.int64) Weights = np.random.rand(sum(Lengths)).astype(np.float32) op = core.CreateOperator("SparseLengthsWeightedSum", [ "Tbl", "Weights", "Indices", "Lengths"], "out") self.ws.create_blob("Tbl").feed(Tbl) self.ws.create_blob("Indices").feed(Indices) self.ws.create_blob("Lengths").feed(Lengths) self.ws.create_blob("Weights").feed(Weights) self.ws.run(op) def sparse_lengths_weightedsum_ref(Tbl, Weights, Indices, Lengths): rptr = np.cumsum(np.insert(Lengths, [0], [0])) out = np.zeros((len(Lengths), blocksize)) for i in range(0, len(rptr[0:-1])): w = Weights[rptr[i]:rptr[i + 1]] out[i] = (Tbl[Indices[rptr[i]:rptr[i + 1]]] * w[:, np.newaxis]).sum(axis=0) return out np.testing.assert_allclose(self.ws.blobs[("out")].fetch(), sparse_lengths_weightedsum_ref(Tbl, Weights, Indices, Lengths), rtol=1e-3, atol=atol) @given(batchsize=st.integers(1, 20), blocksize=st.sampled_from([8, 16, 17, 26, 32, 64, 85, 96, 128, 148, 163]), normalize_by_lengths=st.booleans(), **hu.gcs) def test_sparse_lengths_weightedsum_8BitsRowwiseOp_cpu( self, batchsize, blocksize, normalize_by_lengths, gc, dc): if normalize_by_lengths == False: print("<test_sparse_lengths_weightedsum_SparseLengthsWeightedSum8BitsRowwise_cpu>") else: print("<test_sparse_lengths_weightedsum_SparseLengthsWeightedMean8BitsRowwise_cpu>") tblsize = 300 Tbl = np.random.randint(7, size = (tblsize, blocksize)).astype(np.uint8) atol = 1e-5 # array of each row length Lengths = np.random.randint(1, 30, size=batchsize).astype(np.int32) # flat indices Indices = np.random.randint( 0, tblsize, size=sum(Lengths)).astype(np.int64) Weights = np.random.rand(sum(Lengths)).astype(np.float32) Scale_Bias = np.random.rand(tblsize, 2).astype(np.float32) if normalize_by_lengths == False: op = core.CreateOperator("SparseLengthsWeightedSum8BitsRowwise", [ "Tbl", "Weights", "Indices", "Lengths", "Scale_Bias"], "out") else: op = core.CreateOperator("SparseLengthsWeightedMean8BitsRowwise", [ "Tbl", "Weights", "Indices", "Lengths", "Scale_Bias"], "out") self.ws.create_blob("Tbl").feed(Tbl) self.ws.create_blob("Weights").feed(Weights) self.ws.create_blob("Indices").feed(Indices) self.ws.create_blob("Lengths").feed(Lengths) self.ws.create_blob("Scale_Bias").feed(Scale_Bias) self.ws.run(op) def sparse_lengths_weightedsum_8BitsRowwiseOp_cpu_ref(Tbl, Weights, Indices, Lengths, Scale_Bias): rptr = np.cumsum(np.insert(Lengths, [0], [0])) out = np.zeros((len(Lengths), blocksize)) for i in range(0, len(rptr[0:-1])): w = Weights[rptr[i]:rptr[i + 1]] s = Scale_Bias[Indices[rptr[i]:rptr[i + 1]], 0][:, np.newaxis] b = Scale_Bias[Indices[rptr[i]:rptr[i + 1]], 1][:, np.newaxis] f = 1.0 if normalize_by_lengths == True: f = 1.0 / float(Lengths[i]) out[i] = (w[:, np.newaxis] * (s * Tbl[Indices[rptr[i]:rptr[i + 1]]] + b)).sum(axis=0) * f return out np.testing.assert_allclose(self.ws.blobs[("out")].fetch(), sparse_lengths_weightedsum_8BitsRowwiseOp_cpu_ref(Tbl, Weights, Indices, Lengths, Scale_Bias), rtol=1e-3, atol=atol) @given(batchsize=st.integers(1, 20), blocksize=st.sampled_from([8, 16, 17, 26, 32, 64, 85, 96, 128, 148, 163]), normalize_by_lengths=st.booleans(), **hu.gcs) def test_sparse_lengths_sum_8BitsRowwiseOp_cpu( self, batchsize, blocksize, normalize_by_lengths, gc, dc): if normalize_by_lengths == False: print("<test_sparse_lengths_sum_SparseLengthsSum8BitsRowwise_cpu>") else: print("<test_sparse_lengths_sum_SparseLengthsMean8BitsRowwise_cpu>") tblsize = 300 Tbl = np.random.randint(7, size = (tblsize, blocksize)).astype(np.uint8) atol = 1e-5 # array of each row length Lengths = np.random.randint(1, 30, size=batchsize).astype(np.int32) # flat indices Indices = np.random.randint( 0, tblsize, size=sum(Lengths)).astype(np.int64) Scale_Bias = np.random.rand(tblsize, 2).astype(np.float32) if normalize_by_lengths == False: op = core.CreateOperator("SparseLengthsSum8BitsRowwise", [ "Tbl", "Indices", "Lengths", "Scale_Bias"], "out") else: op = core.CreateOperator("SparseLengthsMean8BitsRowwise", [ "Tbl", "Indices", "Lengths", "Scale_Bias"], "out") self.ws.create_blob("Tbl").feed(Tbl) self.ws.create_blob("Indices").feed(Indices) self.ws.create_blob("Lengths").feed(Lengths) self.ws.create_blob("Scale_Bias").feed(Scale_Bias) self.ws.run(op) def sparse_lengths_sum_8BitsRowwiseOp_cpu_reg(Tbl, Indices, Lengths, Scale_Bias): rptr = np.cumsum(np.insert(Lengths, [0], [0])) out = np.zeros((len(Lengths), blocksize)) for i in range(0, len(rptr[0:-1])): s = Scale_Bias[Indices[rptr[i]:rptr[i + 1]], 0][:, np.newaxis] b = Scale_Bias[Indices[rptr[i]:rptr[i + 1]], 1][:, np.newaxis] f = 1.0 if normalize_by_lengths == True: f = 1.0 / float(Lengths[i]) out[i] = (s * Tbl[Indices[rptr[i]:rptr[i + 1]]] + b).sum(axis=0) * f return out np.testing.assert_allclose(self.ws.blobs[("out")].fetch(), sparse_lengths_sum_8BitsRowwiseOp_cpu_reg(Tbl, Indices, Lengths, Scale_Bias), rtol=1e-3, atol=atol) @given(batchsize=st.integers(1, 20), blocksize=st.sampled_from([8, 16, 17, 26, 32, 64, 85, 96, 128, 148, 163]), normalize_by_lengths=st.booleans(), **hu.gcs) def test_sparse_lengths_sum_8BitsRowwiseOp_cpu_invalid_index( self, batchsize, blocksize, normalize_by_lengths, gc, dc): tblsize = 300 Tbl = np.random.randint(7, size = (tblsize, blocksize)).astype(np.uint8) # array of each row length Lengths = np.random.randint(1, 30, size=batchsize).astype(np.int32) # flat indices Indices = np.random.randint( 0, tblsize, size=sum(Lengths)).astype(np.int64) Indices[0] += 1000 Scale_Bias = np.random.rand(tblsize, 2).astype(np.float32) if normalize_by_lengths == False: op = core.CreateOperator("SparseLengthsSum8BitsRowwise", [ "Tbl", "Indices", "Lengths", "Scale_Bias"], "out") else: op = core.CreateOperator("SparseLengthsMean8BitsRowwise", [ "Tbl", "Indices", "Lengths", "Scale_Bias"], "out") self.ws.create_blob("Tbl").feed(Tbl) self.ws.create_blob("Indices").feed(Indices) self.ws.create_blob("Lengths").feed(Lengths) self.ws.create_blob("Scale_Bias").feed(Scale_Bias) with self.assertRaises(RuntimeError): self.ws.run(op) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from hypothesis import given import hypothesis.strategies as st from caffe2.python import core from caffe2.python import workspace import caffe2.python.hypothesis_test_util as hu class TestWeightedMultiSample(hu.HypothesisTestCase): @given( num_samples=st.integers(min_value=0, max_value=128), data_len=st.integers(min_value=0, max_value=10000), **hu.gcs_cpu_only ) def test_weighted_multi_sample(self, num_samples, data_len, gc, dc): weights = np.zeros((data_len)) expected_indices = [] if data_len > 0: weights[-1] = 1.5 expected_indices = np.repeat(data_len - 1, num_samples) workspace.FeedBlob("weights", weights.astype(np.float32)) op = core.CreateOperator( "WeightedMultiSampling", ["weights"], ["sample_indices"], num_samples=num_samples, ) workspace.RunOperatorOnce(op) result_indices = workspace.FetchBlob("sample_indices") np.testing.assert_allclose(expected_indices, result_indices) self.assertDeviceChecks( dc, op, [weights.astype(np.float32)], [0] ) # test shape input shape = np.zeros((num_samples)) workspace.FeedBlob("shape", shape) op2 = core.CreateOperator( "WeightedMultiSampling", ["weights", "shape"], ["sample_indices_2"] ) workspace.RunOperatorOnce(op2) result_indices_2 = workspace.FetchBlob("sample_indices_2") if data_len > 0: assert len(result_indices_2) == num_samples for i in range(num_samples): assert 0 <= result_indices_2[i] < data_len else: assert len(result_indices_2) == 0 self.assertDeviceChecks(dc, op2, [weights.astype(np.float32), shape], [0]) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import hypothesis.strategies as st import caffe2.python.hypothesis_test_util as hu import numpy as np import unittest class TestGivenTensorFillOps(hu.HypothesisTestCase): @given(X=hu.tensor(min_dim=1, max_dim=4, dtype=np.int32), t=st.sampled_from([ (core.DataType.BOOL, np.bool_, "GivenTensorFill"), (core.DataType.INT32, np.int32, "GivenTensorFill"), (core.DataType.FLOAT, np.float32, "GivenTensorFill"), (core.DataType.INT32, np.int32, "GivenTensorIntFill"), (core.DataType.INT64, np.int64, "GivenTensorInt64Fill"), (core.DataType.BOOL, np.bool_, "GivenTensorBoolFill"), (core.DataType.DOUBLE, np.double, "GivenTensorDoubleFill"), (core.DataType.INT32, np.double, "GivenTensorDoubleFill"), ]), **hu.gcs) def test_given_tensor_fill(self, X, t, gc, dc): X = X.astype(t[1]) print('X: ', str(X)) op = core.CreateOperator( t[2], [], ["Y"], shape=X.shape, dtype=t[0], values=X.reshape((1, X.size)), ) def constant_fill(*args, **kw): return [X] self.assertReferenceChecks(gc, op, [], constant_fill) self.assertDeviceChecks(dc, op, [], [0]) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace import os import shutil import tempfile import unittest class CheckpointTest(unittest.TestCase): """A simple test case to make sure that the checkpoint behavior is correct. """ def testCheckpoint(self): temp_root = tempfile.mkdtemp() net = core.Net("test_checkpoint") # Note(jiayq): I am being a bit lazy here and am using the old iter # convention that does not have an input. Optionally change it to the # new style if needed. net.Iter([], "iter") net.ConstantFill([], "value", shape=[1, 2, 3]) net.Checkpoint(["iter", "value"], [], db=os.path.join(temp_root, "test_checkpoint_at_%05d"), db_type="leveldb", every=10, absolute_path=True) self.assertTrue(workspace.CreateNet(net)) for i in range(100): self.assertTrue(workspace.RunNet("test_checkpoint")) for i in range(1, 10): # Print statements are only for debugging purposes. # print("Asserting %d" % i) # print(os.path.join(temp_root, "test_checkpoint_at_%05d" % (i * 10))) self.assertTrue(os.path.exists( os.path.join(temp_root, "test_checkpoint_at_%05d" % (i * 10)))) # Finally, clean up. shutil.rmtree(temp_root) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class TestFcOperator(hu.HypothesisTestCase): @given(n=st.integers(1, 10), k=st.integers(1, 5), use_length=st.booleans(), **hu.gcs_cpu_only) def test_sparse_to_dense_mask(self, n, k, use_length, gc, dc): lengths = np.random.randint(k, size=n).astype(np.int32) + 1 N = sum(lengths) indices = np.random.randint(5, size=N) values = np.random.rand(N, 2).astype(np.float32) default = np.random.rand(2).astype(np.float32) mask = np.arange(3) np.random.shuffle(mask) input_str = ['indices', 'values', 'default'] input_data = [indices, values, default] if use_length and n > 1: input_str.append('lengths') input_data.append(lengths) output_str = ['output'] op = core.CreateOperator( 'SparseToDenseMask', input_str, output_str, mask=mask, ) # Check over multiple devices self.assertDeviceChecks( dc, op, input_data, [0]) # Gradient check for values self.assertGradientChecks( gc, op, input_data, 1, [0]) @given(n=st.integers(1, 10), k=st.integers(1, 5), use_length=st.booleans(), **hu.gcs_cpu_only) def test_sparse_to_dense_mask_with_int64(self, n, k, use_length, gc, dc): lengths = np.random.randint(k, size=n).astype(np.int32) + 1 N = sum(lengths) int64_mask = 10000000000 indices = np.random.randint(5, size=N) + int64_mask values = np.random.rand(N, 2).astype(np.float32) default = np.random.rand(2).astype(np.float32) mask = np.arange(3) + int64_mask np.random.shuffle(mask) input_str = ['indices', 'values', 'default'] input_data = [indices, values, default] if use_length and n > 1: input_str.append('lengths') input_data.append(lengths) output_str = ['output'] op = core.CreateOperator( 'SparseToDenseMask', input_str, output_str, mask=mask, ) # Check over multiple devices self.assertDeviceChecks( dc, op, input_data, [0]) # Gradient check for values self.assertGradientChecks( gc, op, input_data, 1, [0]) @given(n=st.integers(1, 10), k=st.integers(1, 5), dim=st.integers(1, 3), **hu.gcs_cpu_only) def test_sparse_to_dense_mask_high_dim(self, n, k, dim, gc, dc): lengths = np.random.randint(k, size=n).astype(np.int32) + 1 N = sum(lengths) indices = np.random.randint(5, size=N) shape = np.random.randint(5, size=dim).astype(np.int32) + 1 values = np.random.rand(*((N,) + tuple(shape))).astype(np.float32) default = np.random.rand(*shape).astype(np.float32) mask = np.arange(3) np.random.shuffle(mask) op = core.CreateOperator( 'SparseToDenseMask', ['indices', 'values', 'default', 'lengths'], ['output'], mask=mask, ) # Check over multiple devices self.assertDeviceChecks( dc, op, [indices, values, default, lengths], [0]) # Gradient check for values self.assertGradientChecks( gc, op, [indices, values, default, lengths], 1, [0]) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import hypothesis.strategies as st from hypothesis import given, settings import numpy as np from caffe2.python import core, workspace import caffe2.python.hypothesis_test_util as hu import caffe2.python.mkl_test_util as mu @unittest.skipIf(not workspace.C.has_mkldnn, "Skipping as we do not have mkldnn.") class MKLConvTest(hu.HypothesisTestCase): @given(stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(3, 5), size=st.integers(8, 8), input_channels=st.integers(1, 3), output_channels=st.integers(1, 3), batch_size=st.integers(1, 3), **mu.gcs) @settings(max_examples=2, timeout=100) def test_mkl_convolution(self, stride, pad, kernel, size, input_channels, output_channels, batch_size, gc, dc): op = core.CreateOperator( "Conv", ["X", "w", "b"], ["Y"], stride=stride, pad=pad, kernel=kernel, ) X = np.random.rand( batch_size, input_channels, size, size).astype(np.float32) - 0.5 w = np.random.rand( output_channels, input_channels, kernel, kernel) \ .astype(np.float32) - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 inputs = [X, w, b] self.assertDeviceChecks(dc, op, inputs, [0]) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from hypothesis import assume, given, settings import hypothesis.strategies as st import os import unittest from caffe2.python import core, workspace import caffe2.python.hypothesis_test_util as hu class TestPooling(hu.HypothesisTestCase): # CUDNN does NOT support different padding values and we skip it @given(stride_h=st.integers(1, 3), stride_w=st.integers(1, 3), pad_t=st.integers(0, 3), pad_l=st.integers(0, 3), pad_b=st.integers(0, 3), pad_r=st.integers(0, 3), kernel=st.integers(3, 5), size=st.integers(7, 9), input_channels=st.integers(1, 3), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), op_type=st.sampled_from(["MaxPool", "AveragePool", "LpPool", "MaxPool2D", "AveragePool2D"]), **hu.gcs) def test_pooling_separate_stride_pad(self, stride_h, stride_w, pad_t, pad_l, pad_b, pad_r, kernel, size, input_channels, batch_size, order, op_type, gc, dc): assume(np.max([pad_t, pad_l, pad_b, pad_r]) < kernel) op = core.CreateOperator( op_type, ["X"], ["Y"], stride_h=stride_h, stride_w=stride_w, pad_t=pad_t, pad_l=pad_l, pad_b=pad_b, pad_r=pad_r, kernel=kernel, order=order, ) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) if order == "NCHW": X = X.transpose((0, 3, 1, 2)) self.assertDeviceChecks(dc, op, [X], [0]) if 'MaxPool' not in op_type: self.assertGradientChecks(gc, op, [X], 0, [0]) # This test is to check if CUDNN works for bigger batch size or not @unittest.skipIf(not os.getenv('CAFFE2_DEBUG'), "This is a test that reproduces a cudnn error. If you " "want to run it, set env variable CAFFE2_DEBUG=1.") @given(**hu.gcs_gpu_only) def test_pooling_big_batch(self, gc, dc): op = core.CreateOperator( "AveragePool", ["X"], ["Y"], stride=1, kernel=7, pad=0, order="NHWC", engine="CUDNN", ) X = np.random.rand(70000, 7, 7, 81).astype(np.float32) self.assertDeviceChecks(dc, op, [X], [0]) @given(stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), size=st.integers(7, 9), input_channels=st.integers(1, 3), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), op_type=st.sampled_from(["MaxPool", "AveragePool", "MaxPool1D", "AveragePool1D"]), **hu.gcs) def test_pooling_1d(self, stride, pad, kernel, size, input_channels, batch_size, order, op_type, gc, dc): assume(pad < kernel) op = core.CreateOperator( op_type, ["X"], ["Y"], strides=[stride], kernels=[kernel], pads=[pad, pad], order=order, engine="", ) X = np.random.rand( batch_size, size, input_channels).astype(np.float32) if order == "NCHW": X = X.transpose((0, 2, 1)) self.assertDeviceChecks(dc, op, [X], [0]) if 'MaxPool' not in op_type: self.assertGradientChecks(gc, op, [X], 0, [0]) @given(stride=st.integers(1, 3), pad=st.integers(0, 2), kernel=st.integers(1, 6), size=st.integers(3, 5), input_channels=st.integers(1, 3), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), op_type=st.sampled_from(["MaxPool", "AveragePool", "MaxPool3D", "AveragePool3D"]), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_pooling_3d(self, stride, pad, kernel, size, input_channels, batch_size, order, op_type, engine, gc, dc): assume(pad < kernel) assume(size + pad + pad >= kernel) # some case here could be calculated with global pooling, but instead # calculated with general implementation, slower but should still # be corect. op = core.CreateOperator( op_type, ["X"], ["Y"], strides=[stride] * 3, kernels=[kernel] * 3, pads=[pad] * 6, order=order, engine=engine, ) X = np.random.rand( batch_size, size, size, size, input_channels).astype(np.float32) if order == "NCHW": X = X.transpose((0, 4, 1, 2, 3)) self.assertDeviceChecks(dc, op, [X], [0], threshold=0.001) if 'MaxPool' not in op_type: self.assertGradientChecks(gc, op, [X], 0, [0], threshold=0.001) @given(kernel=st.integers(3, 6), size=st.integers(3, 5), input_channels=st.integers(1, 3), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), op_type=st.sampled_from(["MaxPool", "AveragePool", "MaxPool3D", "AveragePool3D"]), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_global_pooling_3d(self, kernel, size, input_channels, batch_size, order, op_type, engine, gc, dc): # pad and stride ignored because they will be infered in global_pooling op = core.CreateOperator( op_type, ["X"], ["Y"], kernels=[kernel] * 3, order=order, global_pooling=True, engine=engine, ) X = np.random.rand( batch_size, size, size, size, input_channels).astype(np.float32) if order == "NCHW": X = X.transpose((0, 4, 1, 2, 3)) self.assertDeviceChecks(dc, op, [X], [0], threshold=0.001) if 'MaxPool' not in op_type: self.assertGradientChecks(gc, op, [X], 0, [0], threshold=0.001) @unittest.skipIf(not workspace.has_gpu_support, "No GPU support") @given(stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), size=st.integers(7, 9), input_channels=st.integers(1, 3), batch_size=st.integers(1, 3), **hu.gcs_gpu_only) def test_pooling_with_index(self, stride, pad, kernel, size, input_channels, batch_size, gc, dc): assume(pad < kernel) op = core.CreateOperator( "MaxPoolWithIndex", ["X"], ["Y", "Y_index"], stride=stride, kernel=kernel, pad=pad, order="NCHW", deterministic=1, ) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) # transpose due to order = NCHW X = X.transpose((0, 3, 1, 2)) self.assertDeviceChecks(dc, op, [X], [0]) @given(sz=st.integers(1, 20), batch_size=st.integers(1, 4), engine=st.sampled_from(["", "CUDNN"]), op_type=st.sampled_from(["AveragePool", "AveragePool2D"]), **hu.gcs) @settings(max_examples=3, timeout=10) def test_global_avg_pool_nchw(self, op_type, sz, batch_size, engine, gc, dc): ''' Special test to stress the fast path of NCHW average pool ''' op = core.CreateOperator( op_type, ["X"], ["Y"], stride=1, kernel=sz, pad=0, order="NCHW", engine=engine, ) X = np.random.rand( batch_size, 3, sz, sz).astype(np.float32) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) @given(sz=st.integers(1, 20), batch_size=st.integers(1, 4), engine=st.sampled_from(["", "CUDNN"]), op_type=st.sampled_from(["MaxPool", "MaxPool2D"]), **hu.gcs) @settings(max_examples=3, timeout=10) def test_global_max_pool_nchw(self, op_type, sz, batch_size, engine, gc, dc): ''' Special test to stress the fast path of NCHW max pool ''' # CuDNN 5 does not support deterministic max pooling. assume(workspace.GetCuDNNVersion() >= 6000 or engine != "CUDNN") op = core.CreateOperator( op_type, ["X"], ["Y"], stride=1, kernel=sz, pad=0, order="NCHW", engine=engine, deterministic=1, ) np.random.seed(1234) X = np.random.rand( batch_size, 3, sz, sz).astype(np.float32) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=1e-4) @given(stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), size=st.integers(7, 9), input_channels=st.integers(1, 3), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), op_type=st.sampled_from(["MaxPool", "AveragePool", "LpPool", "MaxPool2D", "AveragePool2D"]), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_pooling(self, stride, pad, kernel, size, input_channels, batch_size, order, op_type, engine, gc, dc): assume(pad < kernel) op = core.CreateOperator( op_type, ["X"], ["Y"], stride=stride, kernel=kernel, pad=pad, order=order, engine=engine, ) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) if order == "NCHW": X = X.transpose((0, 3, 1, 2)) self.assertDeviceChecks(dc, op, [X], [0]) if 'MaxPool' not in op_type: self.assertGradientChecks(gc, op, [X], 0, [0]) @given(size=st.integers(7, 9), input_channels=st.integers(1, 3), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), op_type=st.sampled_from(["MaxPool", "AveragePool", "LpPool"]), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_global_pooling(self, size, input_channels, batch_size, order, op_type, engine, gc, dc): # CuDNN 5 does not support deterministic max pooling. assume(workspace.GetCuDNNVersion() >= 6000 or op_type != "MaxPool") op = core.CreateOperator( op_type, ["X"], ["Y"], order=order, engine=engine, global_pooling=True, ) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) if order == "NCHW": X = X.transpose((0, 3, 1, 2)) self.assertDeviceChecks(dc, op, [X], [0]) if 'MaxPool' not in op_type: self.assertGradientChecks(gc, op, [X], 0, [0]) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import hypothesis.strategies as st import caffe2.python.hypothesis_test_util as hu import numpy as np import unittest class TestPiecewiseLinearTransform(hu.HypothesisTestCase): def constrain(self, v, min_val, max_val): def constrain_internal(x): return min(max(x, min_val), max_val) return np.array([constrain_internal(x) for x in v]) def transform(self, x, bounds, slopes, intercepts): n = len(slopes) x_ = self.constrain(x, bounds[0], bounds[-1]) index = np.minimum( np.maximum( np.searchsorted(bounds, x_) - 1, 0 ), n - 1 ) y = slopes[index] * x_ + intercepts[index] return y @given(n=st.integers(1, 100), **hu.gcs) def test_multi_predictions_params_from_arg(self, n, gc, dc): slopes = np.random.uniform(-1, 1, (2, n)).astype(np.float32) intercepts = np.random.uniform(-1, 1, (2, n)).astype(np.float32) bounds = np.random.uniform(0.1, 0.9, (2, n + 1)).astype(np.float32) bounds.sort() X = np.random.uniform(0, 1, (n, 2)).astype(np.float32) op = core.CreateOperator( "PiecewiseLinearTransform", ["X"], ["Y"], bounds=bounds.flatten().tolist(), slopes=slopes.flatten().tolist(), intercepts=intercepts.flatten().tolist(), ) def piecewise(x, *args, **kw): x_0 = self.transform( x[:, 0], bounds[0, :], slopes[0, :], intercepts[0, :]) x_1 = self.transform( x[:, 1], bounds[1, :], slopes[1, :], intercepts[1, :]) return [np.vstack((x_0, x_1)).transpose()] self.assertReferenceChecks(gc, op, [X], piecewise) self.assertDeviceChecks(dc, op, [X], [0]) @given(n=st.integers(1, 100), **hu.gcs) def test_binary_predictions_params_from_arg(self, n, gc, dc): slopes = np.random.uniform(-1, 1, size=n).astype(np.float32) intercepts = np.random.uniform(-1, 1, size=n).astype(np.float32) bounds = np.random.uniform(0.1, 0.9, n + 1).astype(np.float32) bounds.sort() X = np.random.uniform(0, 1, (n, 2)).astype(np.float32) X[:, 0] = 1 - X[:, 1] op = core.CreateOperator( "PiecewiseLinearTransform", ["X"], ["Y"], bounds=bounds.flatten().tolist(), slopes=slopes.flatten().tolist(), intercepts=intercepts.flatten().tolist(), pieces=n, binary=True, ) def piecewise(x): x_ = self.transform(x[:, 1], bounds, slopes, intercepts) return [np.vstack((1 - x_, x_)).transpose()] self.assertReferenceChecks(gc, op, [X], piecewise) self.assertDeviceChecks(dc, op, [X], [0]) @given(n=st.integers(1, 100), **hu.gcs) def test_multi_predictions_params_from_input(self, n, gc, dc): slopes = np.random.uniform(-1, 1, (2, n)).astype(np.float32) intercepts = np.random.uniform(-1, 1, (2, n)).astype(np.float32) bounds = np.random.uniform(0.1, 0.9, (2, n + 1)).astype(np.float32) bounds.sort() X = np.random.uniform(0, 1, (n, 2)).astype(np.float32) op = core.CreateOperator( "PiecewiseLinearTransform", ["X", "bounds", "slopes", "intercepts"], ["Y"], ) def piecewise(x, bounds, slopes, intercepts): x_0 = self.transform( x[:, 0], bounds[0, :], slopes[0, :], intercepts[0, :]) x_1 = self.transform( x[:, 1], bounds[1, :], slopes[1, :], intercepts[1, :]) return [np.vstack((x_0, x_1)).transpose()] self.assertReferenceChecks( gc, op, [X, bounds, slopes, intercepts], piecewise) self.assertDeviceChecks(dc, op, [X, bounds, slopes, intercepts], [0]) @given(n=st.integers(1, 100), **hu.gcs) def test_binary_predictions_params_from_input(self, n, gc, dc): slopes = np.random.uniform(-1, 1, size=n).astype(np.float32) intercepts = np.random.uniform(-1, 1, size=n).astype(np.float32) bounds = np.random.uniform(0.1, 0.9, n + 1).astype(np.float32) bounds.sort() X = np.random.uniform(0, 1, (n, 2)).astype(np.float32) X[:, 0] = 1 - X[:, 1] op = core.CreateOperator( "PiecewiseLinearTransform", ["X", "bounds", "slopes", "intercepts"], ["Y"], binary=True, ) def piecewise(x, bounds, slopes, intercepts): x_ = self.transform(x[:, 1], bounds, slopes, intercepts) return [np.vstack((1 - x_, x_)).transpose()] self.assertReferenceChecks( gc, op, [X, bounds, slopes, intercepts], piecewise) self.assertDeviceChecks(dc, op, [X, bounds, slopes, intercepts], [0]) @given(n=st.integers(1, 100), **hu.gcs) def test_1D_predictions_params_from_input(self, n, gc, dc): slopes = np.random.uniform(-1, 1, size=n).astype(np.float32) intercepts = np.random.uniform(-1, 1, size=n).astype(np.float32) bounds = np.random.uniform(0.1, 0.9, n + 1).astype(np.float32) bounds.sort() X = np.random.uniform(0, 1, size=n).astype(np.float32) op = core.CreateOperator( "PiecewiseLinearTransform", ["X", "bounds", "slopes", "intercepts"], ["Y"], binary=True, ) def piecewise(x, bounds, slopes, intercepts): x_ = self.transform(x, bounds, slopes, intercepts) return [x_] self.assertReferenceChecks( gc, op, [X, bounds, slopes, intercepts], piecewise) self.assertDeviceChecks(dc, op, [X, bounds, slopes, intercepts], [0]) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np import unittest class TestUniqueUniformFillOp(hu.HypothesisTestCase): @given( r=st.integers(1000, 10000), avoid=st.lists( st.integers(1, 1000), min_size=1, max_size=100, unique=True ), dtypes=st.sampled_from( [ (np.int32, core.DataType.INT32), (np.int64, core.DataType.INT64) ] ), s=st.integers(10, 500), **hu.gcs_cpu_only ) def test_unique_uniform_int_fill(self, r, avoid, dtypes, s, gc, dc): net = core.Net("net") workspace.FeedBlob("X", np.array([s], dtype=np.int64)) workspace.FeedBlob("AVOID", np.array(avoid, dtype=dtypes[0])) net.UniqueUniformFill( ["X", "AVOID"], ["Y"], min=1, max=r, input_as_shape=True, dtype=dtypes[1] ) workspace.RunNetOnce(net) y = workspace.FetchBlob("Y") self.assertEqual(s, len(y)) self.assertEqual(s, len(set(y))) self.assertEqual(s, len(set(y) - set(avoid))) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import OrderedDict import numpy as np from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu class TestFlexibleTopK(hu.HypothesisTestCase): def flexible_top_k_ref(self, X, k): X_flat = X.reshape((-1, X.shape[-1])) indices_ref = np.ndarray(shape=sum(k), dtype=np.int32) values_ref = np.ndarray(shape=sum(k), dtype=np.float32) offset = 0 for i in range(X_flat.shape[0]): od = OrderedDict() for j in range(X_flat.shape[1]): val = X_flat[i, j] if val not in od: od[val] = [] od[val].append(j) k_ = 0 for val, idxs in sorted(od.items(), reverse=True): for idx in idxs: indices_ref[offset + k_] = idx values_ref[offset + k_] = val k_ += 1 if k_ >= k[i]: break if k_ >= k[i]: break offset += k[i] return (values_ref, indices_ref) @given(X=hu.tensor(min_dim=2), **hu.gcs_cpu_only) def test_flexible_top_k(self, X, gc, dc): X = X.astype(dtype=np.float32) k_shape = (int(X.size / X.shape[-1]), ) k = np.random.randint(1, high=X.shape[-1] + 1, size=k_shape) output_list = ["Values", "Indices"] op = core.CreateOperator("FlexibleTopK", ["X", "k"], output_list, device_option=gc) def bind_ref(X_loc, k): ret = self.flexible_top_k_ref(X_loc, k) return ret self.assertReferenceChecks(gc, op, [X, k], bind_ref) @given(X=hu.tensor(min_dim=2), **hu.gcs_cpu_only) def test_flexible_top_k_grad(self, X, gc, dc): X = X.astype(np.float32) k_shape = (int(X.size / X.shape[-1]), ) k = np.random.randint(1, high=X.shape[-1] + 1, size=k_shape) # this try to make sure adding stepsize (0.05) # will not change TopK selections at all # since dims max_value = 5 as defined in # caffe2/caffe2/python/hypothesis_test_util.py for i in range(X.shape[-1]): X[..., i] = i * 1.0 / X.shape[-1] op = core.CreateOperator( "FlexibleTopK", ["X", "k"], ["Values", "Indices"], device_option=gc ) self.assertGradientChecks(gc, op, [X, k], 0, [0])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from hypothesis import given import hypothesis.strategies as st import numpy as np import unittest from caffe2.python import core, workspace, dyndep import caffe2.python.hypothesis_test_util as hu dyndep.InitOpsLibrary("@/caffe2/caffe2/mpi:mpi_ops") _has_mpi =False COMM = None RANK = 0 SIZE = 0 def SetupMPI(): try: from mpi4py import MPI global _has_mpi, COMM, RANK, SIZE _has_mpi = core.IsOperatorWithEngine("CreateCommonWorld", "MPI") COMM = MPI.COMM_WORLD RANK = COMM.Get_rank() SIZE = COMM.Get_size() except ImportError: _has_mpi = False @unittest.skipIf(not _has_mpi, "MPI is not available. Skipping.") class TestMPI(hu.HypothesisTestCase): @given(X=hu.tensor(), root=st.integers(min_value=0, max_value=SIZE - 1), device_option=st.sampled_from(hu.device_options), **hu.gcs) def test_broadcast(self, X, root, device_option, gc, dc): # Use mpi4py's broadcast to make sure that all nodes inherit the # same hypothesis test. X = COMM.bcast(X) root = COMM.bcast(root) device_option = COMM.bcast(device_option) X[:] = RANK self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "CreateCommonWorld", [], "comm", engine="MPI", device_option=device_option))) self.assertTrue(workspace.FeedBlob("X", X, device_option)) mpi_op = core.CreateOperator( "Broadcast", ["comm", "X"], "X", engine="MPI", root=root, device_option=device_option) self.assertTrue(workspace.RunOperatorOnce(mpi_op)) new_X = workspace.FetchBlob("X") np.testing.assert_array_equal(new_X, root) workspace.ResetWorkspace() @given(X=hu.tensor(), root=st.integers(min_value=0, max_value=SIZE - 1), device_option=st.sampled_from(hu.device_options), **hu.gcs) def test_reduce(self, X, root, device_option, gc, dc): # Use mpi4py's broadcast to make sure that all nodes inherit the # same hypothesis test. X = COMM.bcast(X) root = COMM.bcast(root) device_option = COMM.bcast(device_option) X[:] = RANK self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "CreateCommonWorld", [], "comm", engine="MPI", device_option=device_option))) self.assertTrue(workspace.FeedBlob("X", X, device_option)) mpi_op = core.CreateOperator( "Reduce", ["comm", "X"], "X_reduced", engine="MPI", root=root, device_option=device_option) self.assertTrue(workspace.RunOperatorOnce(mpi_op)) if (RANK == root): new_X = workspace.FetchBlob("X") np.testing.assert_array_equal(new_X, root) workspace.ResetWorkspace() @given(X=hu.tensor(), root=st.integers(min_value=0, max_value=SIZE - 1), device_option=st.sampled_from(hu.device_options), inplace=st.booleans(), **hu.gcs) def test_allreduce(self, X, root, device_option, inplace, gc, dc): # Use mpi4py's broadcast to make sure that all nodes inherit the # same hypothesis test. X = COMM.bcast(X) root = COMM.bcast(root) device_option = COMM.bcast(device_option) inplace = COMM.bcast(inplace) X[:] = RANK self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "CreateCommonWorld", [], "comm", engine="MPI", device_option=device_option))) # Use mpi4py's broadcast to make sure that all copies have the same # tensor size. X = COMM.bcast(X) X[:] = RANK self.assertTrue(workspace.FeedBlob("X", X, device_option)) mpi_op = core.CreateOperator( "Allreduce", ["comm", "X"], "X" if inplace else "X_reduced", engine="MPI", root=root, device_option=device_option) self.assertTrue(workspace.RunOperatorOnce(mpi_op)) new_X = workspace.FetchBlob("X" if inplace else "X_reduced") np.testing.assert_array_equal(new_X, SIZE * (SIZE - 1) / 2) workspace.ResetWorkspace() @given(X=hu.tensor(), device_option=st.sampled_from(hu.device_options), specify_send_blob=st.booleans(), specify_recv_blob=st.booleans(), **hu.gcs) def test_sendrecv( self, X, device_option, specify_send_blob, specify_recv_blob, gc, dc): # Use mpi4py's broadcast to make sure that all nodes inherit the # same hypothesis test. X = COMM.bcast(X) device_option = COMM.bcast(device_option) specify_send_blob = COMM.bcast(specify_send_blob) specify_recv_blob = COMM.bcast(specify_recv_blob) X[:] = RANK self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "CreateCommonWorld", [], "comm", engine="MPI", device_option=device_option))) self.assertTrue(workspace.FeedBlob("X", X, device_option)) for src in range(SIZE): for dst in range(SIZE): tag = src * SIZE + dst if src == dst: continue elif RANK == src: X[:] = RANK self.assertTrue(workspace.FeedBlob("X", X, device_option)) if specify_send_blob: self.assertTrue(workspace.FeedBlob( "dst", np.array(dst, dtype=np.int32))) self.assertTrue(workspace.FeedBlob( "tag", np.array(tag, dtype=np.int32))) mpi_op = core.CreateOperator( "SendTensor", ["comm", "X", "dst", "tag"], [], engine="MPI", raw_buffer=True, device_option=device_option) else: mpi_op = core.CreateOperator( "SendTensor", ["comm", "X"], [], engine="MPI", dst=dst, tag=tag, raw_buffer=True, device_option=device_option) self.assertTrue(workspace.RunOperatorOnce(mpi_op)) elif RANK == dst: if specify_recv_blob: self.assertTrue(workspace.FeedBlob( "src", np.array(src, dtype=np.int32))) self.assertTrue(workspace.FeedBlob( "tag", np.array(tag, dtype=np.int32))) mpi_op = core.CreateOperator( "ReceiveTensor", ["comm", "X", "src", "tag"], ["X", "src", "tag"], engine="MPI", src=src, tag=tag, raw_buffer=True, device_option=device_option) else: mpi_op = core.CreateOperator( "ReceiveTensor", ["comm", "X"], ["X", "src", "tag"], engine="MPI", src=src, tag=tag, raw_buffer=True, device_option=device_option) self.assertTrue(workspace.RunOperatorOnce(mpi_op)) received = workspace.FetchBlob("X") np.testing.assert_array_equal(received, src) src_blob = workspace.FetchBlob("src") np.testing.assert_array_equal(src_blob, src) tag_blob = workspace.FetchBlob("tag") np.testing.assert_array_equal(tag_blob, tag) # simply wait for the guys to finish COMM.barrier() workspace.ResetWorkspace() if __name__ == "__main__": SetupMPI() import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import core from caffe2.python.test_util import rand_array import caffe2.python.hypothesis_test_util as hu from hypothesis import given import hypothesis.strategies as st class TestScatterOps(hu.HypothesisTestCase): # TODO(dzhulgakov): add test cases for failure scenarios @given(num_args=st.integers(1, 5), first_dim=st.integers(1, 20), index_dim=st.integers(1, 10), extra_dims=st.lists(st.integers(1, 4), min_size=0, max_size=3), ind_type=st.sampled_from([np.int32, np.int64]), **hu.gcs) def testScatterWeightedSum( self, num_args, first_dim, index_dim, extra_dims, ind_type, gc, dc): ins = ['data', 'w0', 'indices'] for i in range(1, num_args + 1): ins.extend(['x' + str(i), 'w' + str(i)]) op = core.CreateOperator( 'ScatterWeightedSum', ins, ['data'], device_option=gc) def ref(d, w0, ind, *args): r = d.copy() for i in ind: r[i] *= w0 for i in range(0, len(args), 2): x = args[i] w = args[i+1] for i, j in enumerate(ind): r[j] += w * x[i] return [r] d = rand_array(first_dim, *extra_dims) ind = np.random.randint(0, first_dim, index_dim).astype(ind_type) # ScatterWeightedSumOp only supports w0=1.0 in CUDAContext if(gc == hu.gpu_do): w0 = np.array(1.0).astype(np.float32) else: w0 = rand_array() inputs = [d, w0, ind] for _ in range(1, num_args + 1): x = rand_array(index_dim, *extra_dims) w = rand_array() inputs.extend([x,w]) self.assertReferenceChecks(gc, op, inputs, ref, threshold=1e-3) @given(first_dim=st.integers(1, 20), index_dim=st.integers(1, 10), extra_dims=st.lists(st.integers(1, 4), min_size=0, max_size=3), data_type=st.sampled_from([np.float16, np.float32, np.int32, np.int64]), ind_type=st.sampled_from([np.int32, np.int64]), **hu.gcs) def testScatterAssign( self, first_dim, index_dim, extra_dims, data_type, ind_type, gc, dc): op = core.CreateOperator('ScatterAssign', ['data', 'indices', 'slices'], ['data']) def ref(d, ind, x): r = d.copy() r[ind] = x return [r] # let's have indices unique if first_dim < index_dim: first_dim, index_dim = index_dim, first_dim d = (rand_array(first_dim, *extra_dims) * 10).astype(data_type) ind = np.random.choice(first_dim, index_dim, replace=False).astype(ind_type) x = (rand_array(index_dim, *extra_dims) * 10).astype(data_type) self.assertReferenceChecks(gc, op, [d, ind, x], ref, threshold=1e-3) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import numpy as np from caffe2.proto import caffe2_pb2 from caffe2.python import core, workspace, test_util @unittest.skipIf(not workspace.C.has_mkldnn, "Skipping as we do not have mkldnn.") class TestMKLBasic(test_util.TestCase): def testReLUSpeed(self): X = np.random.randn(128, 4096).astype(np.float32) mkl_do = core.DeviceOption(caffe2_pb2.MKLDNN) # Makes sure that feed works. workspace.FeedBlob("X", X) workspace.FeedBlob("X_mkl", X, device_option=mkl_do) net = core.Net("test") # Makes sure that we can run relu. net.Relu("X", "Y") net.Relu("X_mkl", "Y_mkl", device_option=mkl_do) workspace.CreateNet(net) workspace.RunNet(net) # makes sure that the results are good. np.testing.assert_allclose( workspace.FetchBlob("Y"), workspace.FetchBlob("Y_mkl"), atol=1e-10, rtol=1e-10) runtime = workspace.BenchmarkNet(net.Proto().name, 1, 100, True) # The returned runtime is the time of # [whole_net, cpu_op, mkl_op] # so we will assume that the MKL one runs faster than the CPU one. # Note(Yangqing): in fact, it seems that in optimized mode, this is # not always guaranteed - MKL runs slower than the Eigen vectorized # version, so I am turning this assertion off. #self.assertTrue(runtime[1] >= runtime[2]) print("Relu CPU runtime {}, MKL runtime {}.".format(runtime[1], runtime[2])) # Note(Zhicheng): Disable the test below we implement to use # RegisterTensorInfoFunction to register for Tensor<MKLContext> # def testConvSpeed(self): # # We randomly select a shape to test the speed. Intentionally we # # test a batch size of 1 since this may be the most frequent use # # case for MKL during deployment time. # X = np.random.rand(1, 256, 27, 27).astype(np.float32) - 0.5 # W = np.random.rand(192, 256, 3, 3).astype(np.float32) - 0.5 # b = np.random.rand(192).astype(np.float32) - 0.5 # mkl_do = core.DeviceOption(caffe2_pb2.MKLDNN) # # Makes sure that feed works. # workspace.FeedBlob("X", X) # workspace.FeedBlob("W", W) # workspace.FeedBlob("b", b) # workspace.FeedBlob("X_mkl", X, device_option=mkl_do) # workspace.FeedBlob("W_mkl", W, device_option=mkl_do) # workspace.FeedBlob("b_mkl", b, device_option=mkl_do) # net = core.Net("test") # # Makes sure that we can run relu. # net.Conv(["X", "W", "b"], "Y", pad=1, stride=1, kernel=3) # net.Conv(["X_mkl", "W_mkl", "b_mkl"], "Y_mkl", # pad=1, stride=1, kernel=3, device_option=mkl_do) # workspace.CreateNet(net) # workspace.RunNet(net) # # makes sure that the results are good. # np.testing.assert_allclose( # workspace.FetchBlob("Y"), # workspace.FetchBlob("Y_mkl"), # atol=1e-2, # rtol=1e-2) # runtime = workspace.BenchmarkNet(net.Proto().name, 1, 100, True) # # print("Conv CPU runtime {}, MKL runtime {}.".format(runtime[1], runtime[2])) if __name__ == '__main__': unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class TestWeightedSumOp(hu.HypothesisTestCase): @given(n=st.integers(5, 8), m=st.integers(1, 1), d=st.integers(2, 4), grad_on_w=st.booleans(), **hu.gcs_cpu_only) def test_weighted_sum(self, n, m, d, grad_on_w, gc, dc): input_names = [] input_vars = [] for i in range(m): X_name = 'X' + str(i) w_name = 'w' + str(i) input_names.extend([X_name, w_name]) var = np.random.rand(n, d).astype(np.float32) vars()[X_name] = var input_vars.append(var) var = np.random.rand(1).astype(np.float32) vars()[w_name] = var input_vars.append(var) def weighted_sum_op_ref(*args): res = np.zeros((n, d)) for i in range(m): res = res + args[2 * i + 1] * args[2 * i] return (res, ) op = core.CreateOperator( "WeightedSum", input_names, ['Y'], grad_on_w=grad_on_w, ) self.assertReferenceChecks( device_option=gc, op=op, inputs=input_vars, reference=weighted_sum_op_ref, ) output_to_check_grad = range(2 * m) if grad_on_w else range(0, 2 * m, 2) for i in output_to_check_grad: self.assertGradientChecks( device_option=gc, op=op, inputs=input_vars, outputs_to_check=i, outputs_with_grads=[0], )
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import hypothesis.strategies as st import unittest import caffe2.python.hypothesis_test_util as hu from caffe2.python import core from hypothesis import given class TestResize(hu.HypothesisTestCase): @given(height_scale=st.floats(0.25, 4.0) | st.just(2.0), width_scale=st.floats(0.25, 4.0) | st.just(2.0), height=st.integers(4, 32), width=st.integers(4, 32), num_channels=st.integers(1, 4), batch_size=st.integers(1, 4), seed=st.integers(0, 65535), **hu.gcs) def test_nearest(self, height_scale, width_scale, height, width, num_channels, batch_size, seed, gc, dc): np.random.seed(seed) op = core.CreateOperator( "ResizeNearest", ["X"], ["Y"], width_scale=width_scale, height_scale=height_scale, ) X = np.random.rand( batch_size, num_channels, height, width).astype(np.float32) def ref(X): output_height = np.int32(height * height_scale) output_width = np.int32(width * width_scale) output_h_idxs, output_w_idxs = np.meshgrid(np.arange(output_height), np.arange(output_width), indexing='ij') input_h_idxs = np.minimum( output_h_idxs / height_scale, height - 1).astype(np.int32) input_w_idxs = np.minimum( output_w_idxs / width_scale, width - 1).astype(np.int32) Y = X[:, :, input_h_idxs, input_w_idxs] return Y, self.assertReferenceChecks(gc, op, [X], ref) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=0.1, threshold=1e-2) @given(height_scale=st.floats(0.25, 4.0) | st.just(2.0), width_scale=st.floats(0.25, 4.0) | st.just(2.0), height=st.integers(4, 32), width=st.integers(4, 32), num_channels=st.integers(1, 4), batch_size=st.integers(1, 4), seed=st.integers(0, 65535), **hu.gcs) def test_nearest_grad(self, height_scale, width_scale, height, width, num_channels, batch_size, seed, gc, dc): np.random.seed(seed) output_height = np.int32(height * height_scale) output_width = np.int32(width * width_scale) X = np.random.rand(batch_size, num_channels, height, width).astype(np.float32) dY = np.random.rand(batch_size, num_channels, output_height, output_width).astype(np.float32) op = core.CreateOperator( "ResizeNearestGradient", ["dY", "X"], ["dX"], width_scale=width_scale, height_scale=height_scale, ) def ref(dY, X): dX = np.zeros_like(X) for i in range(output_height): for j in range(output_width): input_i = np.minimum(i / height_scale, height - 1).astype(np.int32) input_j = np.minimum(j / width_scale, width - 1).astype(np.int32) dX[:, :, input_i, input_j] += dY[:, :, i, j] return dX, self.assertDeviceChecks(dc, op, [dY, X], [0]) self.assertReferenceChecks(gc, op, [dY, X], ref) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from hypothesis import given import hypothesis.strategies as st import caffe2.python.hypothesis_test_util as hu from caffe2.python import workspace, core class TestNegateGradient(hu.HypothesisTestCase): @given(X=hu.tensor(), inplace=st.booleans(), **hu.gcs) def test_forward(self, X, inplace, gc, dc): def neg_grad_ref(X): return (X,) op = core.CreateOperator("NegateGradient", ["X"], ["Y" if not inplace else "X"]) self.assertReferenceChecks(gc, op, [X], neg_grad_ref) self.assertDeviceChecks(dc, op, [X], [0]) @given(size=st.lists(st.integers(min_value=1, max_value=20), min_size=1, max_size=5)) def test_grad(self, size): X = np.random.random_sample(size) workspace.ResetWorkspace() workspace.FeedBlob("X", X.astype(np.float32)) net = core.Net("negate_grad_test") Y = net.NegateGradient(["X"], ["Y"]) grad_map = net.AddGradientOperators([Y]) workspace.RunNetOnce(net) # check X_grad == negate of Y_grad x_val, y_val = workspace.FetchBlobs(['X', 'Y']) x_grad_val, y_grad_val = workspace.FetchBlobs([grad_map['X'], grad_map['Y']]) np.testing.assert_array_equal(x_val, y_val) np.testing.assert_array_equal(x_grad_val, y_grad_val * (-1))
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np def entropy(p): q = 1. - p return -p * np.log(p) - q * np.log(q) def jsd(p, q): return [entropy(p / 2. + q / 2.) - entropy(p) / 2. - entropy(q) / 2.] def jsd_grad(go, o, pq_list): p, q = pq_list m = (p + q) / 2. return [np.log(p * (1 - m) / (1 - p) / m) / 2. * go, None] class TestJSDOps(hu.HypothesisTestCase): @given(n=st.integers(10, 100), **hu.gcs_cpu_only) def test_bernoulli_jsd(self, n, gc, dc): p = np.random.rand(n).astype(np.float32) q = np.random.rand(n).astype(np.float32) op = core.CreateOperator("BernoulliJSD", ["p", "q"], ["l"]) self.assertReferenceChecks( device_option=gc, op=op, inputs=[p, q], reference=jsd, output_to_grad='l', grad_reference=jsd_grad, )
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from hypothesis import given from hypothesis import strategies as st import caffe2.python.hypothesis_test_util as hu import numpy as np def batched_boarders_and_data( data_min_size=5, data_max_size=10, examples_min_number=1, examples_max_number=4, example_min_size=1, example_max_size=3, dtype=np.float32, elements=None): dims_ = st.tuples( st.integers(min_value=data_min_size, max_value=data_max_size), st.integers(min_value=examples_min_number, max_value=examples_max_number), st.integers(min_value=example_min_size, max_value=example_max_size), ) return dims_.flatmap( lambda dims: st.tuples( hu.arrays( [dims[1], dims[2], 2], dtype=np.int32, elements=st.integers(min_value=0, max_value=dims[0]) ), hu.arrays([dims[0]], dtype, elements) )) @st.composite def _tensor_splits(draw): lengths = draw(st.lists(st.integers(1, 5), min_size=1, max_size=10)) batch_size = draw(st.integers(1, 5)) element_pairs = [ (batch, r) for batch in range(batch_size) for r in range(len(lengths)) ] perm = draw(st.permutations(element_pairs)) perm = perm[:-1] # skip one range ranges = [[(0, 0)] * len(lengths) for _ in range(batch_size)] offset = 0 for pair in perm: ranges[pair[0]][pair[1]] = (offset, lengths[pair[1]]) offset += lengths[pair[1]] data = draw(st.lists( st.floats(min_value=-1.0, max_value=1.0), min_size=offset, max_size=offset )) key = draw(st.permutations(range(offset))) return ( np.array(data).astype(np.float32), np.array(ranges), np.array(lengths), np.array(key).astype(np.int64) ) def gather_ranges(data, ranges): lengths = [] output = [] for example_ranges in ranges: length = 0 for range in example_ranges: assert len(range) == 2 output.extend(data[range[0]:range[0] + range[1]]) length += range[1] lengths.append(length) return output, lengths def gather_ranges_to_dense(data, ranges, lengths): outputs = [] assert len(ranges) batch_size = len(ranges) assert len(ranges[0]) num_ranges = len(ranges[0]) assert ranges.shape[2] == 2 for i in range(num_ranges): out = [] for j in range(batch_size): start, length = ranges[j][i] if not length: out.append([0] * lengths[i]) else: assert length == lengths[i] out.append(data[start:start + length]) outputs.append(np.array(out)) return outputs def gather_ranges_to_dense_with_key(data, ranges, key, lengths): outputs = [] assert len(ranges) batch_size = len(ranges) assert len(ranges[0]) num_ranges = len(ranges[0]) assert ranges.shape[2] == 2 for i in range(num_ranges): out = [] for j in range(batch_size): start, length = ranges[j][i] if not length: out.append([0] * lengths[i]) else: assert length == lengths[i] key_data_list = zip( key[start:start + length], data[start:start + length]) sorted_key_data_list = sorted(key_data_list, key=lambda x: x[0]) sorted_data = [d for (k, d) in sorted_key_data_list] out.append(sorted_data) outputs.append(np.array(out)) return outputs class TestGatherRanges(hu.HypothesisTestCase): @given(boarders_and_data=batched_boarders_and_data(), **hu.gcs_cpu_only) def test_gather_ranges(self, boarders_and_data, gc, dc): boarders, data = boarders_and_data def boarders_to_range(boarders): assert len(boarders) == 2 boarders = sorted(boarders) return [boarders[0], boarders[1] - boarders[0]] ranges = np.apply_along_axis(boarders_to_range, 2, boarders) self.assertReferenceChecks( device_option=gc, op=core.CreateOperator("GatherRanges", ["data", "ranges"], ["output", "lengths"]), inputs=[data, ranges], reference=gather_ranges, ) @given(tensor_splits=_tensor_splits(), **hu.gcs_cpu_only) def test_gather_ranges_split(self, tensor_splits, gc, dc): data, ranges, lengths, _ = tensor_splits self.assertReferenceChecks( device_option=gc, op=core.CreateOperator( "GatherRangesToDense", ['data', 'ranges'], ['X_{}'.format(i) for i in range(len(lengths))], lengths=lengths ), inputs=[data, ranges, lengths], reference=gather_ranges_to_dense ) @given(tensor_splits=_tensor_splits(), **hu.gcs_cpu_only) def test_gather_ranges_with_key_split(self, tensor_splits, gc, dc): data, ranges, lengths, key = tensor_splits self.assertReferenceChecks( device_option=gc, op=core.CreateOperator( "GatherRangesToDense", ['data', 'ranges', 'key'], ['X_{}'.format(i) for i in range(len(lengths))], lengths=lengths ), inputs=[data, ranges, key, lengths], reference=gather_ranges_to_dense_with_key ) def test_shape_and_type_inference(self): with hu.temp_workspace("shape_type_inf_int32"): net = core.Net('test_net') net.ConstantFill( [], "ranges", shape=[3, 5, 2], dtype=core.DataType.INT32, ) net.ConstantFill( [], "values", shape=[64], dtype=core.DataType.INT64, ) net.GatherRanges(['values', 'ranges'], ['values_output', 'lengths_output']) (shapes, types) = workspace.InferShapesAndTypes([net], {}) self.assertEqual(shapes["values_output"], [64]) self.assertEqual(types["values_output"], core.DataType.INT64) self.assertEqual(shapes["lengths_output"], [3]) self.assertEqual(types["lengths_output"], core.DataType.INT32) if __name__ == "__main__": import unittest unittest.main()
from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import hypothesis.strategies as st import unittest import caffe2.python.hypothesis_test_util as hu from caffe2.python import core from hypothesis import given @st.composite def _tensor_splits(draw, add_axis=False): """Generates (axis, split_info, tensor_splits) tuples.""" tensor = draw(hu.tensor(min_value=4)) # Each dim has at least 4 elements. axis = draw(st.integers(-len(tensor.shape), len(tensor.shape) - 1)) if add_axis: # Simple case: get individual slices along one axis, where each of them # is (N-1)-dimensional. The axis will be added back upon concatenation. return ( axis, np.ones(tensor.shape[axis], dtype=np.int32), [ np.array(tensor.take(i, axis=axis)) for i in range(tensor.shape[axis]) ] ) else: # General case: pick some (possibly consecutive, even non-unique) # indices at which we will split the tensor, along the given axis. splits = sorted(draw( st.lists(elements=st.integers(0, tensor.shape[axis]), max_size=4) ) + [0, tensor.shape[axis]]) return ( axis, np.array(np.diff(splits), dtype=np.int32), [ tensor.take(range(splits[i], splits[i + 1]), axis=axis) for i in range(len(splits) - 1) ], ) class TestConcatSplitOps(hu.HypothesisTestCase): @given(tensor_splits=_tensor_splits(), **hu.gcs) def test_concat(self, tensor_splits, gc, dc): axis, _, splits = tensor_splits op = core.CreateOperator( "Concat", ['X_{}'.format(i) for i in range(len(splits))], ['concat_result', 'split_info'], axis=axis ) self.assertReferenceChecks( gc, op, splits, lambda *splits: ( np.concatenate(splits, axis=axis), np.array([a.shape[axis] for a in splits]) ) ) self.assertDeviceChecks(dc, op, splits, [0, 1]) self.assertGradientChecks(gc, op, splits, 0, [0]) @given(tensor_splits=_tensor_splits(add_axis=True), **hu.gcs) def test_concat_add_axis(self, tensor_splits, gc, dc): axis, _, splits = tensor_splits op = core.CreateOperator( "Concat", ['X_{}'.format(i) for i in range(len(splits))], ['concat_result', 'split_info'], axis=axis, add_axis=1 ) self.assertReferenceChecks( gc, op, splits, lambda *splits: ( np.concatenate( [np.expand_dims(a, axis) for a in splits], axis=axis ), np.array([1] * len(splits)) ) ) self.assertDeviceChecks(dc, op, splits, [0, 1]) for i in range(len(splits)): self.assertGradientChecks(gc, op, splits, i, [0]) @given(tensor_splits=_tensor_splits(), split_as_arg=st.booleans(), **hu.gcs) def test_split(self, tensor_splits, split_as_arg, gc, dc): axis, split_info, splits = tensor_splits split_as_arg = True if split_as_arg: input_names = ['input'] input_tensors = [np.concatenate(splits, axis=axis)] kwargs = dict(axis=axis, split=split_info) else: input_names = ['input', 'split'] input_tensors = [np.concatenate(splits, axis=axis), split_info] kwargs = dict(axis=axis) op = core.CreateOperator( "Split", input_names, ['X_{}'.format(i) for i in range(len(split_info))], **kwargs ) def split_ref(input, split=split_info): s = np.cumsum([0] + list(split)) return [ np.array(input.take(np.arange(s[i], s[i + 1]), axis=axis)) for i in range(len(split)) ] outputs_with_grad = range(len(split_info)) self.assertReferenceChecks(gc, op, input_tensors, split_ref) self.assertDeviceChecks(dc, op, input_tensors, outputs_with_grad) self.assertGradientChecks(gc, op, input_tensors, 0, outputs_with_grad) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from hypothesis import given import hypothesis.strategies as st from caffe2.python import core from caffe2.python import workspace import caffe2.python.hypothesis_test_util as hu class TestWeightedSample(hu.HypothesisTestCase): @given( batch=st.integers(min_value=0, max_value=128), weights_len=st.integers(min_value=0, max_value=128), **hu.gcs ) def test_weighted_sample(self, batch, weights_len, gc, dc): weights = np.zeros((batch, weights_len)) values = np.zeros((batch, weights_len)) rand_indices = [] rand_values = [] if batch > 0 and weights_len > 0: for i in range(batch): rand_tmp = np.random.randint(0, weights_len) rand_val = np.random.rand() rand_indices.append(rand_tmp) rand_values.append(rand_val) weights[i, rand_tmp] = 1.0 values[i, rand_tmp] = rand_val rand_indices = np.array(rand_indices, dtype=np.float32) rand_values = np.array(rand_values, dtype=np.float32) workspace.FeedBlob("weights", weights.astype(np.float32)) workspace.FeedBlob("values", values.astype(np.float32)) # output both indices and values op = core.CreateOperator( "WeightedSample", ["weights", "values"], ["sample_indices", "sample_values"] ) workspace.RunOperatorOnce(op) result_indices = workspace.FetchBlob("sample_indices") result_values = workspace.FetchBlob("sample_values") if batch > 0 and weights_len > 0: for i in range(batch): np.testing.assert_allclose(rand_indices[i], result_indices[i]) np.testing.assert_allclose(rand_values[i], result_values[i]) else: np.testing.assert_allclose(rand_indices, result_indices) np.testing.assert_allclose(rand_values, result_values) self.assertDeviceChecks( dc, op, [weights.astype(np.float32), values.astype(np.float32)], [0, 1] ) # output indices only op2 = core.CreateOperator( "WeightedSample", ["weights"], ["sample_indices_2"] ) workspace.RunOperatorOnce(op2) result = workspace.FetchBlob("sample_indices_2") if batch > 0 and weights_len > 0: for i in range(batch): np.testing.assert_allclose(rand_indices[i], result[i]) else: np.testing.assert_allclose(rand_indices, result) self.assertDeviceChecks(dc, op2, [weights.astype(np.float32)], [0]) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import hypothesis.strategies as st from caffe2.python import core, workspace from caffe2.proto import caffe2_pb2 from hypothesis import given import caffe2.python.hypothesis_test_util as hu import numpy as np def _fill_diagonal(shape, value): result = np.zeros(shape) np.fill_diagonal(result, value) return (result,) class TestFillerOperator(hu.HypothesisTestCase): @given(**hu.gcs) def test_shape_error(self, gc, dc): op = core.CreateOperator( 'GaussianFill', [], 'out', shape=32, # illegal parameter mean=0.0, std=1.0, ) exception = False try: workspace.RunOperatorOnce(op) except Exception: exception = True self.assertTrue(exception, "Did not throw exception on illegal shape") op = core.CreateOperator( 'ConstantFill', [], 'out', shape=[], # scalar value=2.0, ) exception = False self.assertTrue(workspace.RunOperatorOnce(op)) self.assertEqual(workspace.FetchBlob('out'), [2.0]) @given( shape=hu.dims().flatmap( lambda dims: hu.arrays( [dims], dtype=np.int64, elements=st.integers(min_value=0, max_value=20) ) ), a=st.integers(min_value=0, max_value=100), b=st.integers(min_value=0, max_value=100), **hu.gcs ) def test_uniform_int_fill_op_blob_input(self, shape, a, b, gc, dc): net = core.Net('test_net') with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)): shape_blob = net.Const(shape, dtype=np.int64) a_blob = net.Const(a, dtype=np.int32) b_blob = net.Const(b, dtype=np.int32) uniform_fill = net.UniformIntFill([shape_blob, a_blob, b_blob], 1, input_as_shape=1) workspace.RunNetOnce(net) blob_out = workspace.FetchBlob(uniform_fill) if b < a: new_shape = shape[:] new_shape[0] = 0 np.testing.assert_array_equal(new_shape, blob_out.shape) else: np.testing.assert_array_equal(shape, blob_out.shape) self.assertTrue((blob_out >= a).all()) self.assertTrue((blob_out <= b).all()) @given( **hu.gcs ) def test_uniform_fill_using_arg(self, gc, dc): net = core.Net('test_net') shape = [2**3, 5] # uncomment this to test filling large blob # shape = [2**30, 5] min_v = -100 max_v = 100 output_blob = net.UniformIntFill( [], ['output_blob'], shape=shape, min=min_v, max=max_v, ) workspace.RunNetOnce(net) output_data = workspace.FetchBlob(output_blob) np.testing.assert_array_equal(shape, output_data.shape) min_data = np.min(output_data) max_data = np.max(output_data) self.assertGreaterEqual(min_data, min_v) self.assertLessEqual(max_data, max_v) self.assertNotEqual(min_data, max_data) @given( shape=st.sampled_from( [ [3, 3], [5, 5, 5], [7, 7, 7, 7], ] ), **hu.gcs ) def test_diagonal_fill_op_float(self, shape, gc, dc): value = 2.5 op = core.CreateOperator( 'DiagonalFill', [], 'out', shape=shape, # scalar value=value, ) for device_option in dc: op.device_option.CopyFrom(device_option) # Check against numpy reference self.assertReferenceChecks(gc, op, [shape, value], _fill_diagonal) @given(**hu.gcs) def test_diagonal_fill_op_int(self, gc, dc): value = 2 shape = [3, 3] op = core.CreateOperator( 'DiagonalFill', [], 'out', shape=shape, dtype=core.DataType.INT32, value=value, ) # Check against numpy reference self.assertReferenceChecks(gc, op, [shape, value], _fill_diagonal) @given(lengths=st.lists(st.integers(min_value=0, max_value=10), min_size=0, max_size=10), **hu.gcs) def test_lengths_range_fill(self, lengths, gc, dc): op = core.CreateOperator( "LengthsRangeFill", ["lengths"], ["increasing_seq"]) def _len_range_fill(lengths): sids = [] for _, l in enumerate(lengths): sids.extend(list(range(l))) return (np.array(sids, dtype=np.int32), ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[np.array(lengths, dtype=np.int32)], reference=_len_range_fill) @given(**hu.gcs) def test_gaussian_fill_op(self, gc, dc): op = core.CreateOperator( 'GaussianFill', [], 'out', shape=[17, 3, 3], # sample odd dimensions mean=0.0, std=1.0, ) for device_option in dc: op.device_option.CopyFrom(device_option) assert workspace.RunOperatorOnce(op), "GaussianFill op did not run " "successfully" blob_out = workspace.FetchBlob('out') assert np.count_nonzero(blob_out) > 0, "All generated elements are " "zeros. Is the random generator functioning correctly?" @given(**hu.gcs) def test_msra_fill_op(self, gc, dc): op = core.CreateOperator( 'MSRAFill', [], 'out', shape=[15, 5, 3], # sample odd dimensions ) for device_option in dc: op.device_option.CopyFrom(device_option) assert workspace.RunOperatorOnce(op), "MSRAFill op did not run " "successfully" blob_out = workspace.FetchBlob('out') assert np.count_nonzero(blob_out) > 0, "All generated elements are " "zeros. Is the random generator functioning correctly?" if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core import hypothesis.strategies as st from hypothesis import given import caffe2.python.hypothesis_test_util as hu import numpy as np class TestFindOperator(hu.HypothesisTestCase): @given(n=st.sampled_from([1, 4, 8, 31, 79, 150]), idxsize=st.sampled_from([2, 4, 8, 1000, 5000]), **hu.gcs) def test_find(self, n, idxsize, gc, dc): maxval = 10 def findop(idx, X): res = [] for j in list(X.flatten()): i = np.where(idx == j)[0] if len(i) == 0: res.append(-1) else: res.append(i[-1]) print("Idx: {} X: {}".format(idx, X)) print("Res: {}".format(res)) return [np.array(res).astype(np.int32)] X = (np.random.rand(n) * maxval).astype(np.int32) idx = (np.random.rand(idxsize) * maxval).astype(np.int32) op = core.CreateOperator( "Find", ["idx", "X"], ["y"], ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[idx, X], reference=findop, )
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from caffe2.python.test_util import TestCase import numpy as np class TestExtendTensorOp(TestCase): def test_extend_tensor(self): # Tensor of size 6 holding info about elements 0 to 5 old_tensor = np.array([1, 2, 3, 4, 5, 6], dtype=np.int32) workspace.FeedBlob('old_tensor', old_tensor) indices = np.array([0, 5, 8, 2, 3, 7], dtype=np.int32) workspace.FeedBlob('indices', indices) new_tensor_expected = np.array([1, 2, 3, 4, 5, 6, 0, 0, 0], dtype=np.int32) extend_tensor_op = core.CreateOperator( 'ExtendTensor', ['old_tensor', 'indices'], ['old_tensor']) workspace.RunOperatorOnce(extend_tensor_op) new_tensor_observed = workspace.FetchBlob('old_tensor') np.testing.assert_array_equal(new_tensor_expected, new_tensor_observed) def test_counting(self): # Tensor of size 6 holding counts of elements with indices 0 to 5 counts = np.array([1, 2, 3, 4, 5, 6], dtype=np.float32) workspace.FeedBlob('counts', counts) # Indices of new words to be counted indices = np.array([0, 5, 8, 2, 3, 7, 7], dtype=np.int32) workspace.FeedBlob('indices', indices) # Extend the 'counts' tensor if necessary (if new words are seen) extend_tensor_op = core.CreateOperator( 'ExtendTensor', ['counts', 'indices'], ['counts']) workspace.RunOperatorOnce(extend_tensor_op) ones_counts = np.array([1], dtype=np.float32) ones_indices = np.array( [1 for i in range(len(indices))], dtype=np.float32) one = np.array([1], dtype=np.float32) workspace.FeedBlob('ones_counts', ones_counts) workspace.FeedBlob('ones_indices', ones_indices) workspace.FeedBlob('one', one) ins = ['counts', 'ones_counts', 'indices', 'ones_indices', 'one'] op = core.CreateOperator('ScatterWeightedSum', ins, ['counts']) workspace.RunOperatorOnce(op) new_tensor_expected = np.array([2, 2, 4, 5, 5, 7, 0, 2, 1], dtype=np.float32) new_tensor_observed = workspace.FetchBlob('counts') np.testing.assert_array_equal(new_tensor_expected, new_tensor_observed) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import core import caffe2.python.hypothesis_test_util as hu from hypothesis import given import hypothesis.strategies as st class DistanceTest(hu.HypothesisTestCase): @given(n=st.integers(1, 3), dim=st.integers(4, 16), **hu.gcs) def test_cosine_similarity(self, n, dim, gc, dc): X = np.random.uniform(-1, 1, (n, dim)).astype(np.float32) Y = np.random.uniform(-1, 1, (n, dim)).astype(np.float32) self.ws.create_blob("X").feed(X) self.ws.create_blob("Y").feed(Y) kEps = 1e-12 cos_op = core.CreateOperator("CosineSimilarity", ["X", "Y"], ["cos"]) self.ws.run(cos_op) cos = np.divide(np.multiply(X, Y).sum(axis=1), np.multiply(np.linalg.norm(X, axis=1) + kEps, np.linalg.norm(Y, axis=1) + kEps)) np.testing.assert_allclose(self.ws.blobs[("cos")].fetch(), cos, rtol=1e-4, atol=1e-4) self.assertGradientChecks(gc, cos_op, [X, Y], 0, [0], stepsize=1e-2, threshold=1e-2) self.assertGradientChecks(gc, cos_op, [X, Y], 1, [0], stepsize=1e-2, threshold=1e-2) @given(inputs=hu.tensors(n=2, min_dim=1, max_dim=2, dtype=np.float32), **hu.gcs) def test_dot_product(self, inputs, gc, dc): X, Y = inputs op = core.CreateOperator( 'DotProduct', ['X', 'Y'], ['DOT'], ) def dot_ref(X, Y): return ([np.dot(x, y) for x, y in zip(X, Y)],) # Check against numpy dot reference self.assertReferenceChecks(gc, op, [X, Y], dot_ref) # Check over multiple devices self.assertDeviceChecks(dc, op, [X, Y], [0]) # Gradient check wrt X self.assertGradientChecks(gc, op, [X, Y], 0, [0]) # Gradient check wrt Y self.assertGradientChecks(gc, op, [X, Y], 1, [0]) @given(n=st.integers(1, 3), dim=st.integers(4, 16), **hu.gcs) def test_L1_distance(self, n, dim, gc, dc): X = np.random.uniform(-1, 1, (n, dim)).astype(np.float32) Y = np.random.uniform(-1, 1, (n, dim)).astype(np.float32) # avoid kinks by moving away from 0 X += 0.02 * np.sign(X - Y) X[(X - Y) == 0.0] += 0.02 self.ws.create_blob("X").feed(X) self.ws.create_blob("Y").feed(Y) op = core.CreateOperator( 'L1Distance', ['X', 'Y'], ['l1_dist'], ) self.ws.run(op) np.testing.assert_allclose(self.ws.blobs[("l1_dist")].fetch(), [np.linalg.norm(x - y, ord=1) for x, y in zip(X, Y)], rtol=1e-4, atol=1e-4) self.assertDeviceChecks(dc, op, [X, Y], [0]) # Gradient check wrt X self.assertGradientChecks(gc, op, [X, Y], 0, [0], stepsize=1e-2, threshold=1e-2) # Gradient check wrt Y self.assertGradientChecks(gc, op, [X, Y], 1, [0], stepsize=1e-2, threshold=1e-2) @given(n=st.integers(1, 3), dim=st.integers(4, 16), **hu.gcs) def test_L2_distance(self, n, dim, gc, dc): X = np.random.uniform(-1, 1, (n, dim)).astype(np.float32) Y = np.random.uniform(-1, 1, (n, dim)).astype(np.float32) self.ws.create_blob("X").feed(X) self.ws.create_blob("Y").feed(Y) l2_op = core.CreateOperator("SquaredL2Distance", ["X", "Y"], ["l2_dist"]) self.ws.run(l2_op) np.testing.assert_allclose(self.ws.blobs[("l2_dist")].fetch(), np.square(X - Y).sum(axis=1) * 0.5, rtol=1e-4, atol=1e-4) self.assertGradientChecks(gc, l2_op, [X, Y], 0, [0], stepsize=1e-2, threshold=1e-2) self.assertGradientChecks(gc, l2_op, [X, Y], 1, [0], stepsize=1e-2, threshold=1e-2)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np # The reference implementation is susceptible to numerical cancellation when # *lambda1* is small and *data* is near one. We leave it up to the caller to # truncate lambda to zero or bound data away from one. Unfortunately, the C++ # implementation may be using higher precision than the python version, which # could cause this test to fail. We bound inputs away from the critical values. # (Note that a tolerance of 1e-6 on _either_ parameter is typically sufficient # to avoid catastrophic cancellation when the other is far from zero/one.) TOLERANCE = 1e-3 @st.composite def _inputs(draw): N = draw(st.integers(min_value=0, max_value=5)) D = draw(st.integers(min_value=1, max_value=5)) # N, D, data, lambda1, lambda2 return ( N, D, draw(st.lists( min_size=N * D, max_size=N * D, elements=st.one_of( st.floats(min_value=-10, max_value=1 - TOLERANCE), st.floats(min_value=1 + TOLERANCE, max_value=10)) )), draw(st.lists( elements=st.one_of( st.floats(min_value=-2, max_value=-TOLERANCE), st.floats(min_value=TOLERANCE, max_value=2)), min_size=D, max_size=D, )), draw(st.lists( elements=st.floats(min_value=-2, max_value=2), min_size=D, max_size=D, )), ) class TestBatchBoxCox(hu.HypothesisTestCase): @given( inputs=_inputs(), **hu.gcs_cpu_only ) def test_batch_box_cox(self, inputs, gc, dc): self.batch_box_cox(inputs, gc, dc) @given(**hu.gcs_cpu_only) def test_lambda1_is_all_zero(self, gc, dc): inputs = (1, 1, [[2]], [0], [0]) self.batch_box_cox(inputs, gc, dc) inputs = (2, 1, [[2], [4]], [0], [0]) self.batch_box_cox(inputs, gc, dc) inputs = (1, 3, [[1, 2, 3]], [0, 0, 0], [0, 0, 0]) self.batch_box_cox(inputs, gc, dc) inputs = (2, 3, [[1, 2, 3], [4, 5, 6]], [0, 0, 0], [0, 0, 0]) self.batch_box_cox(inputs, gc, dc) @given(**hu.gcs_cpu_only) def test_lambda1_is_partially_zero(self, gc, dc): inputs = (1, 5, [[1, 2, 3, 4, 5]], [0, -.5, 0, .5, 0], [0.1, 0.2, 0.3, 0.4, 0.5]) self.batch_box_cox(inputs, gc, dc) inputs = (3, 5, [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [1, 2, 3, 4, 5]], [0, -.5, 0, .5, 0], [0.1, 0.2, 0.3, 0.4, 0.5]) self.batch_box_cox(inputs, gc, dc) inputs = (2, 6, [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]], [0, -.5, 0, .5, 0, 1], [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]) self.batch_box_cox(inputs, gc, dc) inputs = (2, 7, [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]], [0, -.5, 0, .5, 0, 1, 0], [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]) self.batch_box_cox(inputs, gc, dc) @given(**hu.gcs_cpu_only) def test_bound_base_away_from_zero(self, gc, dc): inputs = (2, 3, [[1e-5, 1e-6, 1e-7], [1e-7, -1e-6, 1e-5]], [0, 0, 0], [0, 0, 1e-6]) self.batch_box_cox(inputs, gc, dc) def batch_box_cox(self, inputs, gc, dc): N, D, data, lambda1, lambda2 = inputs data = np.array(data, dtype=np.float32).reshape(N, D) lambda1 = np.array(lambda1, dtype=np.float32) lambda2 = np.array(lambda2, dtype=np.float32) # Bound data away from one. See comment in _inputs() above. base = data + lambda2 data[(base > 1 - TOLERANCE) & (base < 1 + TOLERANCE)] += 2 * TOLERANCE def ref(data, lambda1, lambda2): dim_1 = data.shape[1] output = np.copy(data) if data.size <= 0: return [output] for i in range(dim_1): output[:, i] = data[:, i] + lambda2[i] output[:, i] = np.maximum(output[:, i], 1e-6) if lambda1[i] == 0: output[:, i] = np.log(output[:, i]) else: output[:, i] =\ (np.power(output[:, i], lambda1[i]) - 1) / lambda1[i] return [output] for naive in [False, True]: op = core.CreateOperator( 'BatchBoxCox', ['data', 'lambda1', 'lambda2'], ['output'], naive=naive, # Note examples above with D=5, 6, 7. # A zero value falls back to the naive implementation. min_block_size=0 if naive else 6 ) self.assertReferenceChecks(gc, op, [data, lambda1, lambda2], ref) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from hypothesis import given import hypothesis.strategies as st from caffe2.python import core import caffe2.python.hypothesis_test_util as hu class TestActivations(hu.HypothesisTestCase): @given(X=hu.tensor(), alpha=st.floats(min_value=0.1, max_value=2.0), inplace=st.booleans(), **hu.gcs) def test_elu(self, X, alpha, inplace, gc, dc): # go away from the origin point to avoid kink problems X += 0.04 * np.sign(X) X[X == 0.0] += 0.04 def elu_ref(X): Y = X.copy() neg_indices = X <= 0 Y[neg_indices] = alpha * (np.exp(Y[neg_indices]) - 1) return (Y,) op = core.CreateOperator( "Elu", ["X"], ["Y" if not inplace else "X"], alpha=alpha) self.assertReferenceChecks(gc, op, [X], elu_ref) # Check over multiple devices self.assertDeviceChecks(dc, op, [X], [0]) # Gradient check wrt X self.assertGradientChecks(gc, op, [X], 0, [0]) @given(X=hu.tensor(min_dim=4, max_dim=4), alpha=st.floats(min_value=0.1, max_value=2.0), inplace=st.booleans(), shared=st.booleans(), order=st.sampled_from(["NCHW", "NHWC"]), seed=st.sampled_from([20, 100]), **hu.gcs) def test_prelu(self, X, alpha, inplace, shared, order, seed, gc, dc): np.random.seed(seed) W = np.random.randn( X.shape[1] if order == "NCHW" else X.shape[3]).astype(np.float32) if shared: W = np.random.randn(1).astype(np.float32) # go away from the origin point to avoid kink problems X += 0.04 * np.sign(X) X[X == 0.0] += 0.04 def prelu_ref(X, W): Y = X.copy() W = W.reshape(1, -1, 1, 1) if order == "NCHW" \ else W.reshape(1, 1, 1, -1) assert len(X.shape) == 4 neg_indices = X <= 0 assert len(neg_indices.shape) == 4 assert X.shape == neg_indices.shape Y[neg_indices] = (Y * W)[neg_indices] return (Y,) op = core.CreateOperator( "PRelu", ["X", "W"], ["Y" if not inplace else "X"], alpha=alpha, order=order) self.assertReferenceChecks(gc, op, [X, W], prelu_ref) # Check over multiple devices self.assertDeviceChecks(dc, op, [X, W], [0]) if not inplace: # Gradient check wrt X self.assertGradientChecks(gc, op, [X, W], 0, [0], stepsize=1e-2) # Gradient check wrt W self.assertGradientChecks(gc, op, [X, W], 1, [0], stepsize=1e-2) @given(X=hu.tensor(), alpha=st.floats(min_value=0.1, max_value=2.0), inplace=st.booleans(), **hu.gcs) def test_leaky_relu(self, X, alpha, inplace, gc, dc): # go away from the origin point to avoid kink problems X += 0.04 * np.sign(X) X[X == 0.0] += 0.04 def leaky_relu_ref(X): Y = X.copy() neg_indices = X <= 0 Y[neg_indices] = Y[neg_indices] * alpha return (Y,) op = core.CreateOperator( "LeakyRelu", ["X"], ["Y" if not inplace else "X"], alpha=alpha) self.assertReferenceChecks(gc, op, [X], leaky_relu_ref) # Check over multiple devices self.assertDeviceChecks(dc, op, [X], [0]) @given(X=hu.tensor(), inplace=st.booleans(), **hu.gcs) def test_leaky_relu_default(self, X, inplace, gc, dc): # go away from the origin point to avoid kink problems X += 0.04 * np.sign(X) X[X == 0.0] += 0.04 def leaky_relu_ref(X): Y = X.copy() neg_indices = X <= 0 Y[neg_indices] = Y[neg_indices] * 0.01 return (Y,) op = core.CreateOperator( "LeakyRelu", ["X"], ["Y" if not inplace else "X"]) self.assertReferenceChecks(gc, op, [X], leaky_relu_ref) # Check over multiple devices self.assertDeviceChecks(dc, op, [X], [0]) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np import unittest from functools import partial def _gen_test_add_padding(with_pad_data=True, is_remove=False): def gen_with_size(args): lengths, inner_shape = args data_dim = [sum(lengths)] + inner_shape lengths = np.array(lengths, dtype=np.int32) if with_pad_data: return st.tuples( st.just(lengths), hu.arrays(data_dim), hu.arrays(inner_shape), hu.arrays(inner_shape)) else: return st.tuples(st.just(lengths), hu.arrays(data_dim)) min_len = 4 if is_remove else 0 lengths = st.lists( st.integers(min_value=min_len, max_value=10), min_size=0, max_size=5) inner_shape = st.lists( st.integers(min_value=1, max_value=3), min_size=0, max_size=2) return st.tuples(lengths, inner_shape).flatmap(gen_with_size) def _add_padding_ref( start_pad_width, end_pad_width, ret_lengths, data, lengths, start_padding=None, end_padding=None): if start_padding is None: start_padding = np.zeros(data.shape[1:], dtype=data.dtype) end_padding = ( end_padding if end_padding is not None else start_padding) out_size = data.shape[0] + ( start_pad_width + end_pad_width) * len(lengths) out = np.ndarray((out_size,) + data.shape[1:]) in_ptr = 0 out_ptr = 0 for length in lengths: out[out_ptr:(out_ptr + start_pad_width)] = start_padding out_ptr += start_pad_width out[out_ptr:(out_ptr + length)] = data[in_ptr:(in_ptr + length)] in_ptr += length out_ptr += length out[out_ptr:(out_ptr + end_pad_width)] = end_padding out_ptr += end_pad_width lengths_out = lengths + (start_pad_width + end_pad_width) if ret_lengths: return (out, lengths_out) else: return (out, ) def _remove_padding_ref(start_pad_width, end_pad_width, data, lengths): pad_width = start_pad_width + end_pad_width out_size = data.shape[0] - ( start_pad_width + end_pad_width) * len(lengths) out = np.ndarray((out_size,) + data.shape[1:]) in_ptr = 0 out_ptr = 0 for length in lengths: out_length = length - pad_width out[out_ptr:(out_ptr + out_length)] = data[ (in_ptr + start_pad_width):(in_ptr + length - end_pad_width)] in_ptr += length out_ptr += out_length lengths_out = lengths - (start_pad_width + end_pad_width) return (out, lengths_out) def _gather_padding_ref(start_pad_width, end_pad_width, data, lengths): start_padding = np.zeros(data.shape[1:], dtype=data.dtype) end_padding = np.zeros(data.shape[1:], dtype=data.dtype) pad_width = start_pad_width + end_pad_width ptr = 0 for length in lengths: for _ in range(start_pad_width): start_padding += data[ptr] ptr += 1 ptr += length - pad_width for _ in range(end_pad_width): end_padding += data[ptr] ptr += 1 return (start_padding, end_padding) class TestSequenceOps(hu.HypothesisTestCase): @given(start_pad_width=st.integers(min_value=1, max_value=2), end_pad_width=st.integers(min_value=0, max_value=2), args=_gen_test_add_padding(with_pad_data=True), ret_lengths=st.booleans(), **hu.gcs) def test_add_padding( self, start_pad_width, end_pad_width, args, ret_lengths, gc, dc ): lengths, data, start_padding, end_padding = args start_padding = np.array(start_padding, dtype=np.float32) end_padding = np.array(end_padding, dtype=np.float32) outputs = ['output', 'lengths_out'] if ret_lengths else ['output'] op = core.CreateOperator( 'AddPadding', ['data', 'lengths', 'start_padding', 'end_padding'], outputs, padding_width=start_pad_width, end_padding_width=end_pad_width ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[data, lengths, start_padding, end_padding], reference=partial( _add_padding_ref, start_pad_width, end_pad_width, ret_lengths ) ) @given(start_pad_width=st.integers(min_value=1, max_value=2), end_pad_width=st.integers(min_value=0, max_value=2), args=_gen_test_add_padding(with_pad_data=False), **hu.gcs) def test_add_zero_padding(self, start_pad_width, end_pad_width, args, gc, dc): lengths, data = args op = core.CreateOperator( 'AddPadding', ['data', 'lengths'], ['output', 'lengths_out'], padding_width=start_pad_width, end_padding_width=end_pad_width) self.assertReferenceChecks( gc, op, [data, lengths], partial(_add_padding_ref, start_pad_width, end_pad_width, True)) @given(start_pad_width=st.integers(min_value=1, max_value=2), end_pad_width=st.integers(min_value=0, max_value=2), data=hu.tensor(min_dim=1, max_dim=3), **hu.gcs) def test_add_padding_no_length(self, start_pad_width, end_pad_width, data, gc, dc): op = core.CreateOperator( 'AddPadding', ['data'], ['output', 'output_lens'], padding_width=start_pad_width, end_padding_width=end_pad_width) self.assertReferenceChecks( gc, op, [data], partial( _add_padding_ref, start_pad_width, end_pad_width, True, lengths=np.array([data.shape[0]]))) # Uncomment the following seed to make this fail. # @seed(302934307671667531413257853548643485645) # See https://github.com/caffe2/caffe2/issues/1547 @unittest.skip("flaky test") @given(start_pad_width=st.integers(min_value=1, max_value=2), end_pad_width=st.integers(min_value=0, max_value=2), args=_gen_test_add_padding(with_pad_data=False, is_remove=True), **hu.gcs) def test_remove_padding(self, start_pad_width, end_pad_width, args, gc, dc): lengths, data = args op = core.CreateOperator( 'RemovePadding', ['data', 'lengths'], ['output', 'lengths_out'], padding_width=start_pad_width, end_padding_width=end_pad_width) self.assertReferenceChecks( device_option=gc, op=op, inputs=[data, lengths], reference=partial(_remove_padding_ref, start_pad_width, end_pad_width)) @given(start_pad_width=st.integers(min_value=0, max_value=2), end_pad_width=st.integers(min_value=0, max_value=2), args=_gen_test_add_padding(with_pad_data=True), **hu.gcs) def test_gather_padding(self, start_pad_width, end_pad_width, args, gc, dc): lengths, data, start_padding, end_padding = args padded_data, padded_lengths = _add_padding_ref( start_pad_width, end_pad_width, True, data, lengths, start_padding, end_padding) op = core.CreateOperator( 'GatherPadding', ['data', 'lengths'], ['start_padding', 'end_padding'], padding_width=start_pad_width, end_padding_width=end_pad_width) self.assertReferenceChecks( device_option=gc, op=op, inputs=[padded_data, padded_lengths], reference=partial(_gather_padding_ref, start_pad_width, end_pad_width)) @given(data=hu.tensor(min_dim=3, max_dim=3, dtype=np.float32, elements=st.floats(min_value=-np.inf, max_value=np.inf), min_value=1, max_value=10), **hu.gcs) def test_reverse_packed_segs(self, data, gc, dc): max_length = data.shape[0] batch_size = data.shape[1] lengths = np.random.randint(max_length + 1, size=batch_size) op = core.CreateOperator( "ReversePackedSegs", ["data", "lengths"], ["reversed_data"]) def op_ref(data, lengths): rev_data = np.array(data, copy=True) for i in range(batch_size): seg_length = lengths[i] for j in range(seg_length): rev_data[j][i] = data[seg_length - 1 - j][i] return (rev_data,) def op_grad_ref(grad_out, outputs, inputs): return op_ref(grad_out, inputs[1]) + (None,) self.assertReferenceChecks( device_option=gc, op=op, inputs=[data, lengths], reference=op_ref, output_to_grad='reversed_data', grad_reference=op_grad_ref) @given(data=hu.tensor(min_dim=1, max_dim=3, dtype=np.float32, elements=st.floats(min_value=-np.inf, max_value=np.inf), min_value=10, max_value=10), indices=st.lists(st.integers(min_value=0, max_value=9), min_size=0, max_size=10), **hu.gcs_cpu_only) def test_remove_data_blocks(self, data, indices, gc, dc): indices = np.array(indices) op = core.CreateOperator( "RemoveDataBlocks", ["data", "indices"], ["shrunk_data"]) def op_ref(data, indices): unique_indices = np.unique(indices) sorted_indices = np.sort(unique_indices) shrunk_data = np.delete(data, sorted_indices, axis=0) return (shrunk_data,) self.assertReferenceChecks( device_option=gc, op=op, inputs=[data, indices], reference=op_ref) @given(elements=st.lists(st.integers(min_value=0, max_value=9), min_size=0, max_size=10), **hu.gcs_cpu_only) def test_find_duplicate_elements(self, elements, gc, dc): mapping = { 0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g", 7: "h", 8: "i", 9: "j"} data = np.array([mapping[e] for e in elements], dtype='|S') op = core.CreateOperator( "FindDuplicateElements", ["data"], ["indices"]) def op_ref(data): unique_data = [] indices = [] for i, e in enumerate(data): if e in unique_data: indices.append(i) else: unique_data.append(e) return (np.array(indices, dtype=np.int64),) self.assertReferenceChecks( device_option=gc, op=op, inputs=[data], reference=op_ref) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from functools import partial from hypothesis import given from hypothesis import strategies as st import caffe2.python.hypothesis_test_util as hu import math import numpy as np def _data_and_scale( data_min_size=4, data_max_size=10, examples_min_number=1, examples_max_number=4, dtype=np.float32, elements=None): params_ = st.tuples( st.integers(min_value=examples_min_number, max_value=examples_max_number), st.integers(min_value=data_min_size, max_value=data_max_size), st.sampled_from([np.float32, np.int32, np.int64]) ) return params_.flatmap( lambda param_: st.tuples( hu.arrays([param_[0], param_[1]], dtype=dtype), hu.arrays( [param_[0]], dtype=param_[2], elements=(st.floats(0.0, 10000.0) if param_[2] in [np.float32] else st.integers(0, 10000)), ), ) ) def divide_by_square_root(data, scale): output = np.copy(data) num_examples = len(scale) assert num_examples == data.shape[0] assert len(data.shape) == 2 for i in range(0, num_examples): if scale[i] > 0: output[i] = np.multiply(data[i], 1 / math.sqrt(scale[i])) return (output, ) def grad(output_grad, ref_outputs, inputs): return (divide_by_square_root(output_grad, inputs[1])[0], None) class TestSquareRootDivide(hu.HypothesisTestCase): @given(data_and_scale=_data_and_scale(), **hu.gcs_cpu_only) def test_square_root_divide(self, data_and_scale, gc, dc): self.assertReferenceChecks( device_option=gc, op=core.CreateOperator("SquareRootDivide", ["data", "scale"], ["output"]), inputs=list(data_and_scale), reference=partial(divide_by_square_root), output_to_grad="output", grad_reference=grad, ) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np def _string_lists(alphabet=None): return st.lists( elements=st.text(alphabet=alphabet, average_size=3), min_size=0, max_size=3) class TestStringOps(hu.HypothesisTestCase): @given(strings=_string_lists()) def test_string_prefix(self, strings): length = 3 # although we are utf-8 encoding below to avoid python exceptions, # StringPrefix op deals with byte-length prefixes, which may produce # an invalid utf-8 string. The goal here is just to avoid python # complaining about the unicode -> str conversion. strings = np.array( [a.encode('utf-8') for a in strings], dtype=np.object ) def string_prefix_ref(strings): return ( np.array([a[:length] for a in strings], dtype=object), ) op = core.CreateOperator( 'StringPrefix', ['strings'], ['stripped'], length=length) self.assertReferenceChecks( hu.cpu_do, op, [strings], string_prefix_ref) @given(strings=_string_lists()) def test_string_suffix(self, strings): length = 3 strings = np.array( [a.encode('utf-8') for a in strings], dtype=np.object ) def string_suffix_ref(strings): return ( np.array([a[-length:] for a in strings], dtype=object), ) op = core.CreateOperator( 'StringSuffix', ['strings'], ['stripped'], length=length) self.assertReferenceChecks( hu.cpu_do, op, [strings], string_suffix_ref) @given(strings=st.text(alphabet=['a', 'b'], average_size=3)) def test_string_starts_with(self, strings): prefix = 'a' strings = np.array( [str(a) for a in strings], dtype=np.object ) def string_starts_with_ref(strings): return ( np.array([a.startswith(prefix) for a in strings], dtype=bool), ) op = core.CreateOperator( 'StringStartsWith', ['strings'], ['bools'], prefix=prefix) self.assertReferenceChecks( hu.cpu_do, op, [strings], string_starts_with_ref) @given(strings=st.text(alphabet=['a', 'b'], average_size=3)) def test_string_ends_with(self, strings): suffix = 'a' strings = np.array( [str(a) for a in strings], dtype=np.object ) def string_ends_with_ref(strings): return ( np.array([a.endswith(suffix) for a in strings], dtype=bool), ) op = core.CreateOperator( 'StringEndsWith', ['strings'], ['bools'], suffix=suffix) self.assertReferenceChecks( hu.cpu_do, op, [strings], string_ends_with_ref) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np def sigmoid(x): return 1.0 / (1.0 + np.exp(-x)) def sigmoid_cross_entropy_with_logits(x, z): return np.maximum(x, 0) - x * z + np.log(1 + np.exp(-np.abs(x))) def sigmoid_cross_entropy_with_logits_grad(x, z): return z - sigmoid(x) class TestCrossEntropyOps(hu.HypothesisTestCase): @given( inputs=st.lists( elements=st.integers(min_value=1, max_value=5), min_size=1, max_size=2, average_size=2, ).flatmap( lambda shape: st.tuples( hu.arrays( dims=shape, elements=st.one_of( st.floats(min_value=-1.0, max_value=-0.1), st.floats(min_value=0.1, max_value=1.0), )), hu.arrays( dims=shape, elements=st.sampled_from([0.0, 1.0]), ), ) ), **hu.gcs ) def test_sigmoid_cross_entropy_with_logits(self, inputs, gc, dc): logits, targets = inputs def sigmoid_xentr_logit_ref(logits, targets): s = sigmoid_cross_entropy_with_logits(logits, targets) m = np.mean(s, axis=len(logits.shape) - 1) return (m, ) def sigmoid_xentr_logit_grad_ref(g_out, outputs, fwd_inputs): fwd_logits, fwd_targets = fwd_inputs inner_size = fwd_logits.shape[-1] m = fwd_targets - sigmoid(fwd_logits) g_in = -np.expand_dims(g_out, axis=-1) * m / inner_size return (g_in, None) op = core.CreateOperator( 'SigmoidCrossEntropyWithLogits', ['logits', 'targets'], ['xentropy']) self.assertReferenceChecks( device_option=gc, op=op, inputs=[logits, targets], reference=sigmoid_xentr_logit_ref, output_to_grad='xentropy', grad_reference=sigmoid_xentr_logit_grad_ref) @given( inputs=st.lists( elements=st.integers(min_value=1, max_value=5), min_size=1, max_size=2, average_size=2, ).flatmap( lambda shape: st.tuples( hu.arrays( dims=shape, elements=st.one_of( st.floats(min_value=-1.0, max_value=-0.1), st.floats(min_value=0.1, max_value=1.0), )), hu.arrays( dims=shape, elements=st.sampled_from([0.0, 1.0]), ), hu.arrays( dims=shape, elements=st.floats(min_value=0.1, max_value=1.0), ), ) ), **hu.gcs ) def test_weighted_sigmoid_cross_entropy_with_logits(self, inputs, gc, dc): logits, targets, weights = inputs def weighted_sigmoid_xentr_logit_ref(logits, targets, weights): s = sigmoid_cross_entropy_with_logits(logits, targets) s = np.multiply(s, weights) m = np.mean(s, axis=len(logits.shape) - 1) return (m, ) def weighted_sigmoid_xentr_logit_grad_ref(g_out, outputs, fwd_inputs): fwd_logits, fwd_targets, fwd_weights = fwd_inputs inner_size = fwd_logits.shape[-1] m = fwd_targets - sigmoid(fwd_logits) m = np.multiply(m, weights) g_in = -np.expand_dims(g_out, axis=-1) * m / inner_size return (g_in, None, None) op = core.CreateOperator( 'WeightedSigmoidCrossEntropyWithLogits', ['logits', 'targets', 'weights'], ['xentropy']) self.assertReferenceChecks( device_option=gc, op=op, inputs=[logits, targets, weights], reference=weighted_sigmoid_xentr_logit_ref, output_to_grad='xentropy', grad_reference=weighted_sigmoid_xentr_logit_grad_ref) @given(n=st.integers(2, 10), b=st.integers(1, 5), **hu.gcs_cpu_only) def test_soft_label_cross_entropy(self, n, b, gc, dc): # Initialize X and add 1e-2 for numerical stability X = np.random.rand(b, n).astype(np.float32) X = X + 1e-2 for i in range(b): X[i] = X[i] / np.sum(X[i]) # Initialize label label = np.random.rand(b, n).astype(np.float32) for i in range(b): label[i] = label[i] / np.sum(label[i]) # Reference implementation of cross entropy with soft labels def soft_label_xentr_ref(X, label): xent = [np.sum((-label[j][i] * np.log(max(X[j][i], 1e-20)) for i in range(len(X[0])))) for j in range(b)] return (xent,) op = core.CreateOperator("CrossEntropy", ["X", "label"], ["Y"]) # TODO(surya) Once CrossEntropyOp is ported to GPU, add the respective # tests to this unit test. self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, label], reference=soft_label_xentr_ref, ) self.assertGradientChecks( gc, op, [X, label], 0, [0], stepsize=1e-4, threshold=1e-2) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from hypothesis import given import hypothesis.strategies as st from caffe2.python import core import caffe2.python.hypothesis_test_util as hu class TestUnmaskOp(hu.HypothesisTestCase): @given(N=st.integers(min_value=2, max_value=20), dtype=st.sampled_from([ np.bool_, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.float16, np.float32, np.float64]), **hu.gcs) def test(self, N, dtype, gc, dc): if dtype is np.bool_: all_value = np.random.choice(a=[True, False], size=N) else: all_value = (np.random.rand(N) * N).astype(dtype) M = np.random.randint(1, N) split = sorted(np.random.randint(1, N, size=M)) indices = np.random.permutation(N) pieces = np.split(indices, split) def ref(*args, **kwargs): return (all_value,) inputs = [] inputs_names = [] for i, piece in enumerate(pieces): piece.sort() mask = np.zeros(N, dtype=np.bool_) mask[piece] = True values = all_value[piece] inputs.extend([mask, values]) inputs_names.extend(["mask%d" % i, "value%d" % i]) op = core.CreateOperator( 'BooleanUnmask', inputs_names, 'output') self.assertReferenceChecks(gc, op, inputs, ref) self.assertDeviceChecks(dc, op, inputs, [0]) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import core, workspace from caffe2.python.test_util import TestCase from caffe2.proto import caffe2_pb2 class TestPrependDim(TestCase): def _test_fwd_bwd(self): old_shape = (128, 2, 4) new_shape = (8, 16, 2, 4) X = np.random.rand(*old_shape).astype(np.float32) Y = np.random.rand(*new_shape).astype(np.float32) net = core.Net('net') net.GivenTensorFill([], 'X', shape=old_shape, values=X.flatten()) net.GivenTensorFill([], 'Y', shape=new_shape, values=Y.flatten()) net.PrependDim(['X'], ['X_out'], dim_size=8) net.DotProduct(['X_out', 'Y'], 'Z') net.AddGradientOperators(['Z']) workspace.RunNetOnce(net) X_out = workspace.FetchBlob('X_out') X_grad = workspace.FetchBlob('X_grad') Y_grad = workspace.FetchBlob('Y_grad') # Check the shape of the gradient np.testing.assert_array_equal(X_out.shape, Y.shape) np.testing.assert_array_equal(X_grad.shape, X.shape) np.testing.assert_array_equal(Y_grad.shape, Y.shape) def test_prepend_dim(self): devices = [core.DeviceOption(caffe2_pb2.CPU, 0)] if workspace.NumCudaDevices() > 0: devices.append(core.DeviceOption(caffe2_pb2.CUDA, 0)) for device_opt in devices: with core.DeviceScope(device_opt): self._test_fwd_bwd() if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import hypothesis.strategies as st import caffe2.python.hypothesis_test_util as hu import numpy as np import unittest class TestThresholdedRelu(hu.HypothesisTestCase): # test case 1 - default alpha - we do reference and dc checks. # test case 2 does dc and reference checks over range of alphas. # test case 3 does gc over range of alphas. @given(input=hu.tensor(), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_thresholded_relu_1(self, input, gc, dc, engine): X = input op = core.CreateOperator("ThresholdedRelu", ["X"], ["Y"], engine=engine) def defaultRef(X): Y = np.copy(X) Y[Y <= 1.0] = 0.0 return (Y,) self.assertDeviceChecks(dc, op, [X], [0]) self.assertReferenceChecks(gc, op, [X], defaultRef) @given(input=hu.tensor(), alpha=st.floats(min_value=1.0, max_value=5.0), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_thresholded_relu_2(self, input, alpha, gc, dc, engine): X = input op = core.CreateOperator("ThresholdedRelu", ["X"], ["Y"], alpha=alpha, engine=engine) def ref(X): Y = np.copy(X) Y[Y <= alpha] = 0.0 return (Y,) self.assertDeviceChecks(dc, op, [X], [0]) self.assertReferenceChecks(gc, op, [X], ref) @given(input=hu.tensor(), alpha=st.floats(min_value=1.1, max_value=5.0), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_thresholded_relu_3(self, input, alpha, gc, dc, engine): X = TestThresholdedRelu.fix_input(input) op = core.CreateOperator("ThresholdedRelu", ["X"], ["Y"], alpha=float(alpha), engine=engine) self.assertGradientChecks(gc, op, [X], 0, [0]) @staticmethod def fix_input(input): # go away from alpha to avoid derivative discontinuities input += 0.02 * np.sign(input) return input if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import hypothesis.strategies as st import caffe2.python.hypothesis_test_util as hu import caffe2.python.mkl_test_util as mu import numpy as np import unittest class TestRelu(hu.HypothesisTestCase): @given(X=hu.tensor(), engine=st.sampled_from(["", "CUDNN"]), **mu.gcs) def test_relu(self, X, gc, dc, engine): op = core.CreateOperator("Relu", ["X"], ["Y"], engine=engine) # go away from the origin point to avoid kink problems X += 0.02 * np.sign(X) X[X == 0.0] += 0.02 self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class TestLars(hu.HypothesisTestCase): @given(offset=st.floats(min_value=0, max_value=100), **hu.gcs) def test_lars(self, offset, dc, gc): X = np.random.rand(6, 7, 8, 9).astype(np.float32) dX = np.random.rand(6, 7, 8, 9).astype(np.float32) def ref_lars(X, dX): return [1. / (np.linalg.norm(dX) / np.linalg.norm(X) + offset)] op = core.CreateOperator( "Lars", ["X", "dX"], ["rescale_factor"], offset=offset ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, dX], reference=ref_lars )
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from hypothesis import assume, given import hypothesis.strategies as st import numpy as np from caffe2.python import core import caffe2.python.hypothesis_test_util as hu from caffe2.proto import caffe2_pb2 import unittest class TestChannelBackpropStats(hu.HypothesisTestCase): @given( size=st.integers(7, 10), inputChannels=st.integers(1, 10), batchSize=st.integers(1, 3), **hu.gcs ) def testChannelBackpropStats(self, size, inputChannels, batchSize, gc, dc): op = core.CreateOperator( "ChannelBackpropStats", ["X", "mean", "invStdDev", "outputGrad"], ["scaleGrad", "biasGrad"], ) def referenceChannelBackpropStatsTest(X, mean, invStdDev, outputGrad): scaleGrad = np.zeros(inputChannels) biasGrad = np.zeros(inputChannels) for n in range(batchSize): for c in range(inputChannels): for h in range(size): for w in range(size): biasGrad[c] += outputGrad[n, c, h, w] scaleGrad[c] += ( X[n, c, h, w] - mean[c] ) * invStdDev[c] * outputGrad[n, c, h, w] return scaleGrad, biasGrad X = np.random.rand(batchSize, inputChannels, size, size)\ .astype(np.float32) - 0.5 sums = np.sum(X, axis=(0, 2, 3), keepdims=False) numPixels = size * size * batchSize mean = sums / numPixels sumsq = np.sum(X**2, axis=(0, 2, 3), keepdims=False) var = ((sumsq - (sums * sums) / numPixels) / numPixels).astype(np.float32) invStdDev = 1 / np.sqrt(var) outputGrad = np.random.rand(batchSize, inputChannels, size, size)\ .astype(np.float32) - 0.5 self.assertReferenceChecks( gc, op, [X, mean, invStdDev, outputGrad], referenceChannelBackpropStatsTest ) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from hypothesis import assume, given, settings import hypothesis.strategies as st from caffe2.python import core import caffe2.python.hypothesis_test_util as hu class TestConvolutionTranspose(hu.HypothesisTestCase): @given(stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), adj=st.integers(0, 2), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), engine=st.sampled_from(["", "CUDNN", "BLOCK"]), shared_buffer=st.booleans(), use_bias=st.booleans(), **hu.gcs) def test_convolution_transpose_layout_legacy_args( self, stride, pad, kernel, adj, size, input_channels, output_channels, batch_size, engine, shared_buffer, use_bias, gc, dc): assume(adj < stride) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( input_channels, kernel, kernel, output_channels)\ .astype(np.float32) - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 outputs = {} for order in ["NCHW", "NHWC"]: op = core.CreateOperator( "ConvTranspose", ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], stride=stride, kernel=kernel, pad=pad, adj=adj, order=order, engine=engine, shared_buffer=int(shared_buffer), device_option=gc, ) if order == "NCHW": X_f = X.transpose((0, 3, 1, 2)) w_f = w.transpose((0, 3, 1, 2)) else: X_f = X w_f = w self.assertDeviceChecks( dc, op, [X_f, w_f, b] if use_bias else [X_f, w_f], [0]) self.ws.create_blob("X").feed(X_f, device_option=gc) self.ws.create_blob("w").feed(w_f, device_option=gc) self.ws.create_blob("b").feed(b, device_option=gc) self.ws.run(op) outputs[order] = self.ws.blobs["Y"].fetch() output_size = (size - 1) * stride + kernel + adj - 2 * pad self.assertEqual( outputs["NCHW"].shape, (batch_size, output_channels, output_size, output_size)) np.testing.assert_allclose( outputs["NCHW"], outputs["NHWC"].transpose((0, 3, 1, 2)), atol=1e-4, rtol=1e-4) @given(stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), adj=st.integers(0, 2), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), engine=st.sampled_from(["", "CUDNN", "BLOCK"]), shared_buffer=st.booleans(), use_bias=st.booleans(), **hu.gcs) def test_convolution_transpose_layout( self, stride, pad, kernel, adj, size, input_channels, output_channels, batch_size, engine, shared_buffer, use_bias, gc, dc): assume(adj < stride) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( input_channels, kernel, kernel, output_channels)\ .astype(np.float32) - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 outputs = {} for order in ["NCHW", "NHWC"]: op = core.CreateOperator( "ConvTranspose", ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], strides=[stride] * 2, kernels=[kernel] * 2, pads=[pad] * 4, adjs=[adj] * 2, order=order, engine=engine, shared_buffer=int(shared_buffer), device_option=gc, ) if order == "NCHW": X_f = X.transpose((0, 3, 1, 2)) w_f = w.transpose((0, 3, 1, 2)) else: X_f = X w_f = w self.assertDeviceChecks( dc, op, [X_f, w_f, b] if use_bias else [X_f, w_f], [0]) self.ws.create_blob("X").feed(X_f, device_option=gc) self.ws.create_blob("w").feed(w_f, device_option=gc) self.ws.create_blob("b").feed(b, device_option=gc) self.ws.run(op) outputs[order] = self.ws.blobs["Y"].fetch() output_size = (size - 1) * stride + kernel + adj - 2 * pad self.assertEqual( outputs["NCHW"].shape, (batch_size, output_channels, output_size, output_size)) np.testing.assert_allclose( outputs["NCHW"], outputs["NHWC"].transpose((0, 3, 1, 2)), atol=1e-4, rtol=1e-4) # CUDNN does not support separate stride and pad so we skip it. @given(stride_h=st.integers(1, 3), stride_w=st.integers(1, 3), pad_t=st.integers(0, 3), pad_l=st.integers(0, 3), pad_b=st.integers(0, 3), pad_r=st.integers(0, 3), kernel=st.integers(1, 5), adj_h=st.integers(0, 2), adj_w=st.integers(0, 2), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), engine=st.sampled_from(["", "BLOCK"]), use_bias=st.booleans(), **hu.gcs) def test_convolution_transpose_separate_stride_pad_adj_layout( self, stride_h, stride_w, pad_t, pad_l, pad_b, pad_r, kernel, adj_h, adj_w, size, input_channels, output_channels, batch_size, engine, use_bias, gc, dc): assume(adj_h < stride_h) assume(adj_w < stride_w) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( input_channels, kernel, kernel, output_channels)\ .astype(np.float32) - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 outputs = {} for order in ["NCHW", "NHWC"]: op = core.CreateOperator( "ConvTranspose", ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], stride_h=stride_h, stride_w=stride_w, kernel=kernel, pad_t=pad_t, pad_l=pad_l, pad_b=pad_b, pad_r=pad_r, adj_h=adj_h, adj_w=adj_w, order=order, engine=engine, device_option=gc, ) if order == "NCHW": X_f = X.transpose((0, 3, 1, 2)) w_f = w.transpose((0, 3, 1, 2)) else: X_f = X w_f = w self.assertDeviceChecks( dc, op, [X_f, w_f, b] if use_bias else [X_f, w_f], [0]) self.ws.create_blob("X").feed(X_f, device_option=gc) self.ws.create_blob("w").feed(w_f, device_option=gc) self.ws.create_blob("b").feed(b, device_option=gc) self.ws.run(op) outputs[order] = self.ws.blobs["Y"].fetch() output_h = (size - 1) * stride_h + kernel + adj_h - pad_t - pad_b output_w = (size - 1) * stride_w + kernel + adj_w - pad_l - pad_r self.assertEqual( outputs["NCHW"].shape, (batch_size, output_channels, output_h, output_w)) np.testing.assert_allclose( outputs["NCHW"], outputs["NHWC"].transpose((0, 3, 1, 2)), atol=1e-4, rtol=1e-4) @given(stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), adj=st.integers(0, 2), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), engine=st.sampled_from(["", "CUDNN", "BLOCK"]), use_bias=st.booleans(), compute_dX=st.booleans(), **hu.gcs) @settings(max_examples=2, timeout=100) def test_convolution_transpose_gradients(self, stride, pad, kernel, adj, size, input_channels, output_channels, batch_size, order, engine, use_bias, compute_dX, gc, dc): assume(adj < stride) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( input_channels, kernel, kernel, output_channels)\ .astype(np.float32) - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 op = core.CreateOperator( "ConvTranspose", ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], stride=stride, kernel=kernel, pad=pad, adj=adj, order=order, engine=engine, no_gradient_to_input=not compute_dX, ) if order == "NCHW": X = X.transpose((0, 3, 1, 2)) w = w.transpose((0, 3, 1, 2)) inputs = [X, w, b] if use_bias else [X, w] self.assertDeviceChecks(dc, op, inputs, [0]) if use_bias and compute_dX: # w, b, X outputs_to_check = [1, 2, 0] elif use_bias: # w, b outputs_to_check = [1, 2] elif compute_dX: # w, X outputs_to_check = [1, 0] else: # w outputs_to_check = [1] for i in outputs_to_check: self.assertGradientChecks(gc, op, inputs, i, [0]) # CUDNN does not support separate stride and pad so we skip it. @given(stride_h=st.integers(1, 3), stride_w=st.integers(1, 3), pad_t=st.integers(0, 3), pad_l=st.integers(0, 3), pad_b=st.integers(0, 3), pad_r=st.integers(0, 3), kernel=st.integers(1, 5), adj_h=st.integers(0, 2), adj_w=st.integers(0, 2), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), engine=st.sampled_from(["", "BLOCK"]), use_bias=st.booleans(), compute_dX=st.booleans(), **hu.gcs) @settings(max_examples=2, timeout=100) def test_convolution_transpose_separate_stride_pad_adj_gradient( self, stride_h, stride_w, pad_t, pad_l, pad_b, pad_r, kernel, adj_h, adj_w, size, input_channels, output_channels, batch_size, order, engine, use_bias, compute_dX, gc, dc): assume(adj_h < stride_h) assume(adj_w < stride_w) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( input_channels, kernel, kernel, output_channels)\ .astype(np.float32) - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 op = core.CreateOperator( "ConvTranspose", ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], stride_h=stride_h, stride_w=stride_w, kernel=kernel, pad_t=pad_t, pad_l=pad_l, pad_b=pad_b, pad_r=pad_r, adj_h=adj_h, adj_w=adj_w, order=order, engine=engine, no_gradient_to_input=not compute_dX, ) if order == "NCHW": X = X.transpose((0, 3, 1, 2)) w = w.transpose((0, 3, 1, 2)) inputs = [X, w, b] if use_bias else [X, w] self.assertDeviceChecks(dc, op, inputs, [0]) if use_bias and compute_dX: # w, b, X outputs_to_check = [1, 2, 0] elif use_bias: # w, b outputs_to_check = [1, 2] elif compute_dX: # w, X outputs_to_check = [1, 0] else: # w outputs_to_check = [1] for i in outputs_to_check: self.assertGradientChecks(gc, op, inputs, i, [0]) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import core, workspace from caffe2.python.test_util import TestCase from caffe2.proto import caffe2_pb2 class TestLengthsToShapeOps(TestCase): def test_lengths_to_shape_ops(self): workspace.FeedBlob('l', np.array([200, 200, 200], dtype=np.int32)) workspace.RunOperatorOnce(core.CreateOperator( 'LengthsToShape', ['l'], ['s'])) workspace.FeedBlob('res', np.array([3, 200], dtype=np.int32)) assert ((workspace.FetchBlob('s') == workspace.FetchBlob('res')).all()) def test_reshape_ops(self): workspace.FeedBlob('res', np.array([[0, 0, 0, 0]], dtype=np.float32)) workspace.FeedBlob('shape', np.array([1, 4], dtype=np.int32)) workspace.FeedBlob('input', np.zeros((2, 2), dtype=np.float32)) workspace.RunOperatorOnce(core.CreateOperator( 'Reshape', ['input', 'shape'], ['output', 'old_shape'])) assert ((workspace.FetchBlob('output') == workspace.FetchBlob('res')).all()) def test_basic_reshape(self): _test_reshape(old_shape=(4, 2, 1), new_shape=(2, 4)) _test_reshape(old_shape=(4, 2, 1), new_shape=(2, 4), arg_shape=False) def test_missing_dim(self): _test_reshape(old_shape=(4, 2, 1), new_shape=(-1, 8)) _test_reshape(old_shape=(4, 2, 1), new_shape=(-1, 8), arg_shape=False) def test_in_place(self): _test_reshape(old_shape=(4, 2, 1), new_shape=(-1, 8), in_place=True) _test_reshape(old_shape=(4, 2, 1), new_shape=(-1, 8), in_place=True, arg_shape=False) def test_zero_dim(self): _test_reshape(old_shape=(4, 2, 1), new_shape=(0, 0, 0), expected_shape=(4, 2, 1)) _test_reshape(old_shape=(4, 2, 1), new_shape=(0, 0, 0), expected_shape=(4, 2, 1), arg_shape=False) _test_reshape(old_shape=(4, 2, 1), new_shape=(0, 2, 1), expected_shape=(4, 2, 1)) _test_reshape(old_shape=(4, 2, 1), new_shape=(0, 2, 1), expected_shape=(4, 2, 1), arg_shape=False) def test_zero_dim_and_missing_dim(self): _test_reshape(old_shape=(4, 2, 1), new_shape=(0, -1, 0), expected_shape=(4, 2, 1)) _test_reshape(old_shape=(4, 2, 1), new_shape=(0, -1, 0), expected_shape=(4, 2, 1), arg_shape=False) _test_reshape(old_shape=(4, 3, 2), new_shape=(-1, 0), expected_shape=(8, 3)) _test_reshape(old_shape=(4, 3, 2), new_shape=(-1, 0), expected_shape=(8, 3), arg_shape=False) def test_backprop(self): old_shape = (4, 2, 1) new_shape = (1, 8) X = np.random.rand(*old_shape).astype(np.float32) Y = np.random.rand(*new_shape).astype(np.float32) net = core.Net('net') net.GivenTensorFill([], 'X', shape=old_shape, values=X.flatten()) net.GivenTensorFill([], 'Y', shape=new_shape, values=Y.flatten()) net.Reshape(['X'], ['X_out', 'old_shape'], shape=new_shape) net.DotProduct(['X_out', 'Y'], 'Z') net.AddGradientOperators(['Z']) workspace.RunNetOnce(net) Z = workspace.FetchBlob('Z') X_grad = workspace.FetchBlob('X_grad') # Check forward computation np.testing.assert_allclose( Z.squeeze(), X.reshape(new_shape).dot(Y.T).squeeze(), rtol=1e-5) # Check the shape of the gradient np.testing.assert_array_equal(X_grad.shape, X.shape) # Check the gradient np.testing.assert_allclose(X_grad, Y.reshape(old_shape), rtol=1e-5) def test_input_shape_changes(self): workspace.FeedBlob( 'input_blob', np.array(np.random.rand(10, 20, 10), dtype=np.float32)) net = core.Net('mynet') z, _ = net.Reshape('input_blob', ['z_reshape', 'dummy_size'], shape=(-1, 10)) workspace.CreateNet(net) workspace.RunNet(net) workspace.FeedBlob( 'input_blob', np.array(np.random.rand(10, 40, 10), dtype=np.float32)) workspace.RunNet(net) def _test_reshape(old_shape, new_shape, expected_shape=None, arg_shape=True, in_place=False): devices = [core.DeviceOption(caffe2_pb2.CPU, 0)] if workspace.NumCudaDevices() > 0: devices.append(core.DeviceOption(caffe2_pb2.CUDA, 0)) for device_opt in devices: with core.DeviceScope(device_opt): if expected_shape is None: expected_shape = new_shape X = np.random.rand(*old_shape).astype(np.float32) blob_in = 'X' blob_out = blob_in if in_place else blob_in + '_out' if arg_shape: op = core.CreateOperator('Reshape', [blob_in], [blob_out, 'old_shape'], shape=new_shape) else: op = core.CreateOperator('Reshape', [blob_in, 'new_shape'], [blob_out, 'old_shape']) workspace.FeedBlob('new_shape', np.asarray(new_shape)) workspace.FeedBlob(blob_in, X) workspace.RunOperatorOnce(op) Y = workspace.FetchBlob(blob_out) np.testing.assert_allclose(Y, X.reshape(expected_shape)) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest try: import lmdb except ImportError: raise unittest.SkipTest('python-lmdb is not installed') import sys import os import shutil import tempfile from caffe2.proto import caffe2_pb2 from caffe2.python import workspace, model_helper import numpy as np class VideoInputOpTest(unittest.TestCase): def create_a_list(self, output_file, line, n): # create a list that repeat a line n times # used for creating a list file for simple test input with open(output_file, 'w') as file: for _i in range(n): file.write(line) def create_video_db(self, list_file, output_file, use_list=False): # Write to lmdb database... LMDB_MAP_SIZE = 1 << 40 # MODIFY env = lmdb.open(output_file, map_size=LMDB_MAP_SIZE) total_size = 0 file_name = [] start_frame = [] label = [] index = 0 with env.begin(write=True) as txn: with open(list_file, 'r') as data: for line in data: p = line.split() file_name = p[0] start_frame = int(p[1]) label = int(p[2]) if not use_list: with open(file_name, mode='rb') as file: video_data = file.read() else: video_data = file_name tensor_protos = caffe2_pb2.TensorProtos() video_tensor = tensor_protos.protos.add() video_tensor.data_type = 4 # string data video_tensor.string_data.append(video_data) label_tensor = tensor_protos.protos.add() label_tensor.data_type = 2 label_tensor.int32_data.append(label) start_frame_tensor = tensor_protos.protos.add() start_frame_tensor.data_type = 2 start_frame_tensor.int32_data.append(start_frame) txn.put( '{}'.format(index).encode('ascii'), tensor_protos.SerializeToString() ) index = index + 1 total_size = total_size + len(video_data) + sys.getsizeof(int) return total_size # sample one clip randomly from the video def test_rgb_with_temporal_jittering(self): random_label = np.random.randint(0, 100) VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi" if not os.path.exists(VIDEO): raise unittest.SkipTest('Missing data') temp_list = tempfile.NamedTemporaryFile(delete=False).name line_str = '{} 0 {}\n'.format(VIDEO, random_label) self.create_a_list(temp_list, line_str, 16) video_db_dir = tempfile.mkdtemp() self.create_video_db(temp_list, video_db_dir) model = model_helper.ModelHelper(name="Video Loader from LMDB") reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb") # build the model model.net.VideoInput( reader, ["data", "label"], name="data", batch_size=16, clip_per_video=1, crop_size=112, scale_w=171, scale_h=128, length_rgb=8, sampling_rate_rgb=1, decode_type=0, video_res_type=0) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) data = workspace.FetchBlob("data") label = workspace.FetchBlob("label") np.testing.assert_equal(label, random_label) np.testing.assert_equal(data.shape, [16, 3, 8, 112, 112]) os.remove(temp_list) shutil.rmtree(video_db_dir) # sample multiple clips uniformly from the video def test_rgb_with_uniform_sampling(self): random_label = np.random.randint(0, 100) clip_per_video = np.random.randint(2, 11) VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi" if not os.path.exists(VIDEO): raise unittest.SkipTest('Missing data') temp_list = tempfile.NamedTemporaryFile(delete=False).name line_str = '{} 0 {}\n'.format(VIDEO, random_label) self.create_a_list(temp_list, line_str, 16) video_db_dir = tempfile.mkdtemp() self.create_video_db(temp_list, video_db_dir) model = model_helper.ModelHelper(name="Video Loader from LMDB") reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb") # build the model model.net.VideoInput( reader, ["data", "label"], name="data", batch_size=3, clip_per_video=clip_per_video, crop_size=112, scale_w=171, scale_h=128, length_rgb=8, sampling_rate_rgb=1, decode_type=1, video_res_type=0) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) data = workspace.FetchBlob("data") label = workspace.FetchBlob("label") np.testing.assert_equal(label, random_label) np.testing.assert_equal(data.shape, [3 * clip_per_video, 3, 8, 112, 112]) os.remove(temp_list) shutil.rmtree(video_db_dir) # sample multiple clips uniformly from the video, rectangle cropping. # VideoResType is USE_WIDTH_HEIGHT def test_rgb_with_uniform_sampling_rectangle_cropping_use_width_height(self): batch_size = 3 crop_height, crop_width = 112, 144 random_label = np.random.randint(0, 100) clip_per_video = np.random.randint(2, 11) VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi" if not os.path.exists(VIDEO): raise unittest.SkipTest('Missing data') temp_list = tempfile.NamedTemporaryFile(delete=False).name line_str = '{} 0 {}\n'.format(VIDEO, random_label) self.create_a_list(temp_list, line_str, 16) video_db_dir = tempfile.mkdtemp() self.create_video_db(temp_list, video_db_dir) model = model_helper.ModelHelper(name="Video Loader from LMDB") reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb") # build the model model.net.VideoInput( reader, ["data", "label"], name="data", batch_size=batch_size, clip_per_video=clip_per_video, crop_height=crop_height, crop_width=crop_width, scale_w=171, scale_h=128, length_rgb=8, sampling_rate_rgb=1, color_jitter=True, color_lighting=True, decode_type=1, video_res_type=0) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) data = workspace.FetchBlob("data") label = workspace.FetchBlob("label") np.testing.assert_equal( label.shape, [batch_size * clip_per_video]) for i in range(batch_size * clip_per_video): np.testing.assert_equal(label[i], random_label) np.testing.assert_equal( data.shape, [batch_size * clip_per_video, 3, 8, crop_height, crop_width]) os.remove(temp_list) shutil.rmtree(video_db_dir) # sample multiple clips uniformly from the video, rectangle cropping. # VideoResType is USE_MINIMAL_WIDTH_HEIGHT def test_rgb_with_uniform_sampling_rectangle_cropping_use_minimal_width_height( self ): batch_size = 3 height_min, width_min = 128, 166 crop_height, crop_width = 112, 144 random_label = np.random.randint(0, 100) clip_per_video = np.random.randint(2, 11) VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi" if not os.path.exists(VIDEO): raise unittest.SkipTest('Missing data') temp_list = tempfile.NamedTemporaryFile(delete=False).name line_str = '{} 0 {}\n'.format(VIDEO, random_label) self.create_a_list(temp_list, line_str, 16) video_db_dir = tempfile.mkdtemp() self.create_video_db(temp_list, video_db_dir) model = model_helper.ModelHelper(name="Video Loader from LMDB") reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb") # build the model model.net.VideoInput( reader, ["data", "label"], name="data", batch_size=batch_size, clip_per_video=clip_per_video, height_min=height_min, width_min=width_min, crop_height=crop_height, crop_width=crop_width, length_rgb=8, sampling_rate_rgb=1, color_jitter=True, color_lighting=True, decode_type=1, video_res_type=1) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) data = workspace.FetchBlob("data") label = workspace.FetchBlob("label") np.testing.assert_equal( label.shape, [batch_size * clip_per_video]) for i in range(batch_size * clip_per_video): np.testing.assert_equal(label[i], random_label) np.testing.assert_equal( data.shape, [batch_size * clip_per_video, 3, 8, crop_height, crop_width]) os.remove(temp_list) shutil.rmtree(video_db_dir) # sample multiple clips uniformly from the video, while color jitterring # and lighting are enabled def test_rgb_with_uniform_sampling_color_jittering_lighting(self): batch_size = 3 random_label = np.random.randint(0, 100) clip_per_video = np.random.randint(2, 11) VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi" if not os.path.exists(VIDEO): raise unittest.SkipTest('Missing data') temp_list = tempfile.NamedTemporaryFile(delete=False).name line_str = '{} 0 {}\n'.format(VIDEO, random_label) self.create_a_list(temp_list, line_str, 16) video_db_dir = tempfile.mkdtemp() self.create_video_db(temp_list, video_db_dir) model = model_helper.ModelHelper(name="Video Loader from LMDB") reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb") # build the model model.net.VideoInput( reader, ["data", "label"], name="data", batch_size=batch_size, clip_per_video=clip_per_video, crop_size=112, scale_w=171, scale_h=128, length_rgb=8, sampling_rate_rgb=1, color_jitter=True, color_lighting=True, decode_type=1, video_res_type=0) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) data = workspace.FetchBlob("data") label = workspace.FetchBlob("label") np.testing.assert_equal( label.shape, [batch_size * clip_per_video]) for i in range(batch_size * clip_per_video): np.testing.assert_equal(label[i], random_label) np.testing.assert_equal( data.shape, [batch_size * clip_per_video, 3, 8, 112, 112]) os.remove(temp_list) shutil.rmtree(video_db_dir) # sample multiple clips uniformly from the video def test_rgb_with_uniform_sampling_and_multi_cropping(self): # we take left-top, central-top, right-top, left-bottom, central-bottom, # right-bottom and central-central croppings as well as their mirrorings # In total, 14 croppings multi_crop_count = 14 batch_size = 3 random_label = np.random.randint(0, 100) clip_per_video = np.random.randint(2, 11) VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi" if not os.path.exists(VIDEO): raise unittest.SkipTest('Missing data') temp_list = tempfile.NamedTemporaryFile(delete=False).name line_str = '{} 0 {}\n'.format(VIDEO, random_label) self.create_a_list(temp_list, line_str, 16) video_db_dir = tempfile.mkdtemp() self.create_video_db(temp_list, video_db_dir) model = model_helper.ModelHelper(name="Video Loader from LMDB") reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb") # build the model model.net.VideoInput( reader, ["data", "label"], name="data", batch_size=batch_size, clip_per_video=clip_per_video, crop_size=112, scale_w=171, scale_h=128, length_rgb=8, sampling_rate_rgb=1, decode_type=1, multi_crop=True, video_res_type=0) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) data = workspace.FetchBlob("data") label = workspace.FetchBlob("label") np.testing.assert_equal( label.shape, [batch_size * clip_per_video * multi_crop_count]) for i in range(batch_size * clip_per_video * multi_crop_count): np.testing.assert_equal(label[i], random_label) np.testing.assert_equal( data.shape, [batch_size * clip_per_video * multi_crop_count, 3, 8, 112, 112]) os.remove(temp_list) shutil.rmtree(video_db_dir) # test optical flow def test_optical_flow_with_temporal_jittering(self): random_label = np.random.randint(0, 100) VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi" if not os.path.exists(VIDEO): raise unittest.SkipTest('Missing data') temp_list = tempfile.NamedTemporaryFile(delete=False).name line_str = '{} 0 {}\n'.format(VIDEO, random_label) self.create_a_list(temp_list, line_str, 16) video_db_dir = tempfile.mkdtemp() self.create_video_db(temp_list, video_db_dir) model = model_helper.ModelHelper(name="Video Loader from LMDB") reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb") model.net.VideoInput( reader, ["data", "label"], name="data", batch_size=16, clip_per_video=1, crop_size=112, scale_w=171, scale_h=128, length_of=8, sampling_rate_of=1, frame_gap_of=1, decode_type=0, video_res_type=0, get_rgb=False, get_optical_flow=True) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) data = workspace.FetchBlob("data") label = workspace.FetchBlob("label") np.testing.assert_equal(label, random_label) np.testing.assert_equal(data.shape, [16, 2, 8, 112, 112]) os.remove(temp_list) shutil.rmtree(video_db_dir) # test optical flow, rectangle cropping, VideoResType is # USE_WIDTH_HEIGHT def test_optical_flow_with_rectangle_cropping_use_width_height(self): batch_size = 16 scale_h, scale_w = 128, 166 crop_height, crop_width = 112, 144 random_label = np.random.randint(0, 100) VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi" if not os.path.exists(VIDEO): raise unittest.SkipTest('Missing data') temp_list = tempfile.NamedTemporaryFile(delete=False).name line_str = '{} 0 {}\n'.format(VIDEO, random_label) self.create_a_list(temp_list, line_str, batch_size) video_db_dir = tempfile.mkdtemp() self.create_video_db(temp_list, video_db_dir) model = model_helper.ModelHelper(name="Video Loader from LMDB") reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb") model.net.VideoInput( reader, ["data", "label"], name="data", batch_size=batch_size, clip_per_video=1, scale_h=scale_h, scale_w=scale_w, crop_height=crop_height, crop_width=crop_width, length_of=8, sampling_rate_of=1, frame_gap_of=1, decode_type=0, video_res_type=0, get_rgb=False, get_optical_flow=True) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) data = workspace.FetchBlob("data") label = workspace.FetchBlob("label") np.testing.assert_equal(label.shape, [batch_size]) for i in range(batch_size): np.testing.assert_equal(label[i], random_label) np.testing.assert_equal( data.shape, [batch_size, 2, 8, crop_height, crop_width]) os.remove(temp_list) shutil.rmtree(video_db_dir) # test optical flow, rectangle cropping, VideoResType is # USE_MINIMAL_WIDTH_HEIGHT def test_optical_flow_with_rectangle_cropping_use_minimal_width_height(self): batch_size = 16 height_min, width_min = 128, 166 crop_height, crop_width = 112, 144 random_label = np.random.randint(0, 100) VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi" if not os.path.exists(VIDEO): raise unittest.SkipTest('Missing data') temp_list = tempfile.NamedTemporaryFile(delete=False).name line_str = '{} 0 {}\n'.format(VIDEO, random_label) self.create_a_list(temp_list, line_str, batch_size) video_db_dir = tempfile.mkdtemp() self.create_video_db(temp_list, video_db_dir) model = model_helper.ModelHelper(name="Video Loader from LMDB") reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb") model.net.VideoInput( reader, ["data", "label"], name="data", batch_size=batch_size, clip_per_video=1, height_min=height_min, width_min=width_min, crop_height=crop_height, crop_width=crop_width, length_of=8, sampling_rate_of=1, frame_gap_of=1, decode_type=0, video_res_type=1, get_rgb=False, get_optical_flow=True) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) data = workspace.FetchBlob("data") label = workspace.FetchBlob("label") np.testing.assert_equal(label.shape, [batch_size]) for i in range(batch_size): np.testing.assert_equal(label[i], random_label) np.testing.assert_equal( data.shape, [batch_size, 2, 8, crop_height, crop_width]) os.remove(temp_list) shutil.rmtree(video_db_dir) # test optical flow, multi-cropping def test_optical_flow_with_multi_cropping(self): multi_crop_count = 14 batch_size = 16 height_min, width_min = 128, 166 crop_height, crop_width = 112, 144 random_label = np.random.randint(0, 100) VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi" if not os.path.exists(VIDEO): raise unittest.SkipTest('Missing data') temp_list = tempfile.NamedTemporaryFile(delete=False).name line_str = '{} 0 {}\n'.format(VIDEO, random_label) self.create_a_list(temp_list, line_str, batch_size) video_db_dir = tempfile.mkdtemp() self.create_video_db(temp_list, video_db_dir) model = model_helper.ModelHelper(name="Video Loader from LMDB") reader = model.CreateDB("sample", db=video_db_dir, db_type="lmdb") model.net.VideoInput( reader, ["data", "label"], name="data", batch_size=batch_size, clip_per_video=1, height_min=height_min, width_min=width_min, crop_height=crop_height, crop_width=crop_width, length_of=8, sampling_rate_of=1, frame_gap_of=1, decode_type=0, multi_crop=True, video_res_type=1, get_rgb=False, get_optical_flow=True) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) data = workspace.FetchBlob("data") label = workspace.FetchBlob("label") np.testing.assert_equal(label.shape, [batch_size * multi_crop_count]) for i in range(batch_size * multi_crop_count): np.testing.assert_equal(label[i], random_label) np.testing.assert_equal( data.shape, [batch_size * multi_crop_count, 2, 8, crop_height, crop_width]) os.remove(temp_list) shutil.rmtree(video_db_dir) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np @st.composite def _data(draw): return draw( hu.tensor(dtype=np.int64, elements=st.integers( min_value=np.iinfo(np.int64).min, max_value=np.iinfo(np.int64).max ) ) ) class TestMod(hu.HypothesisTestCase): @given( data=_data(), divisor=st.integers( min_value=np.iinfo(np.int64).min, max_value=np.iinfo(np.int64).max ), inplace=st.booleans(), sign_follow_divisor=st.booleans(), **hu.gcs_cpu_only ) def test_mod( self, data, divisor, inplace, sign_follow_divisor, gc, dc ): if divisor == 0: # invalid test case return None def ref(data): if sign_follow_divisor: output = data % divisor else: output = numpy.fmod(data, divisor) return [output] op = core.CreateOperator( 'Mod', ['data'], ['data' if inplace else 'output'], divisor=divisor, sign_follow_divisor=sign_follow_divisor ) self.assertReferenceChecks(gc, op, [data], ref) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from hypothesis import given import hypothesis.strategies as st from caffe2.python import core import caffe2.python.hypothesis_test_util as hu class TestLocallyConnectedOp(hu.HypothesisTestCase): @given(kernel=st.integers(1, 3), size=st.integers(1, 5), input_channels=st.integers(1, 3), output_channels=st.integers(1, 3), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), use_bias=st.booleans(), **hu.gcs) def test_lc_2d( self, kernel, size, input_channels, output_channels, batch_size, order, use_bias, gc, dc): if size < kernel: return op = core.CreateOperator( "LC2D", ["X", "W", "b"] if use_bias else ["X", "W"], ["Y"], kernel=kernel, order=order, engine="", ) L = size - kernel + 1 if order == "NCHW": X = np.random.rand( batch_size, input_channels, size, size).astype(np.float32) - 0.5 W = np.random.rand( L, L, output_channels, input_channels, kernel, kernel ).astype(np.float32) - 0.5 else: X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 W = np.random.rand( L, L, output_channels, kernel, kernel, input_channels ).astype(np.float32) - 0.5 b = np.random.rand(L, L, output_channels).astype(np.float32) - 0.5 inputs = [X, W, b] if use_bias else [X, W] def lc_2d_nchw(X, W, b=None): N, C, XH, XW = X.shape YH, YW, M, _, KH, KW = W.shape def conv(n, m, yh, yw): sum = b[yh, yw, m] if b is not None else 0 for c in range(C): for kh in range(KH): for kw in range(KW): hh = yh + kh ww = yw + kw sum += X[n, c, hh, ww] * W[yh, yw, m, c, kh, kw] return sum output = np.zeros((N, M, YH, YW), dtype=np.float32) for n in range(N): for m in range(M): for yh in range(YH): for yw in range(YW): output[n, m, yh, yw] = conv(n, m, yh, yw) return [output] def lc_2d_nhwc(X, W, b=None): XT = np.transpose(X, [0, 3, 1, 2]) WT = np.transpose(W, [0, 1, 2, 5, 3, 4]) output = lc_2d_nchw(XT, WT, b) return [np.transpose(output[0], [0, 2, 3, 1])] ref_op = lc_2d_nchw if order == "NCHW" else lc_2d_nhwc self.assertReferenceChecks( device_option=gc, op=op, inputs=inputs, reference=ref_op, ) for i in range(len(inputs)): self.assertGradientChecks(gc, op, inputs, i, [0]) @given(kernel=st.integers(1, 3), size=st.integers(1, 5), input_channels=st.integers(1, 3), output_channels=st.integers(1, 3), batch_size=st.integers(1, 3), use_bias=st.booleans(), **hu.gcs) def test_lc_1d( self, kernel, size, input_channels, output_channels, batch_size, use_bias, gc, dc): if size < kernel: return op = core.CreateOperator( "LC1D", ["X", "W", "b"] if use_bias else ["X", "W"], ["Y"], kernels=[kernel], order="NCHW", engine="", ) L = size - kernel + 1 X = np.random.rand( batch_size, input_channels, size).astype(np.float32) - 0.5 W = np.random.rand( L, output_channels, input_channels, kernel).astype(np.float32) - 0.5 b = np.random.rand(L, output_channels).astype(np.float32) - 0.5 inputs = [X, W, b] if use_bias else [X, W] def lc_1d_nchw(X, W, b=None): N, C, XL = X.shape YL, M, _, KL = W.shape def conv(n, m, yl): sum = b[yl, m] if b is not None else 0 for c in range(C): for kl in range(KL): ll = yl + kl sum += X[n, c, ll] * W[yl, m, c, kl] return sum output = np.zeros((N, M, YL), dtype=np.float32) for n in range(N): for m in range(M): for yl in range(YL): output[n, m, yl] = conv(n, m, yl) return [output] self.assertReferenceChecks( device_option=gc, op=op, inputs=inputs, reference=lc_1d_nchw, ) for i in range(len(inputs)): self.assertGradientChecks(gc, op, inputs, i, [0]) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from hypothesis import assume, given import hypothesis.strategies as st from caffe2.proto import caffe2_pb2 from caffe2.python import core import caffe2.python.hypothesis_test_util as hu class TestBooleanMaskOp(hu.HypothesisTestCase): @given(x=hu.tensor(min_dim=1, max_dim=5, elements=st.floats(min_value=0.5, max_value=1.0)), **hu.gcs) def test_boolean_mask(self, x, gc, dc): op = core.CreateOperator("BooleanMask", ["data", "mask"], "masked_data") mask = np.random.choice(a=[True, False], size=x.shape[0]) def ref(x, mask): return (x[mask],) self.assertReferenceChecks(gc, op, [x, mask], ref) self.assertDeviceChecks(dc, op, [x, mask], [0]) @given(x=hu.tensor(min_dim=1, max_dim=5, elements=st.floats(min_value=0.5, max_value=1.0)), **hu.gcs) def test_boolean_mask_indices(self, x, gc, dc): op = core.CreateOperator("BooleanMask", ["data", "mask"], ["masked_data", "masked_indices"]) mask = np.random.choice(a=[True, False], size=x.shape[0]) def ref(x, mask): return (x[mask], np.where(mask)[0]) self.assertReferenceChecks(gc, op, [x, mask], ref) self.assertDeviceChecks(dc, op, [x, mask], [0]) @staticmethod def _dtype_conversion(x, dtype, gc, dc): """SequenceMask only supports fp16 with CUDA.""" if dtype == np.float16: assume(gc.device_type == caffe2_pb2.CUDA) dc = [d for d in dc if d.device_type == caffe2_pb2.CUDA] x = x.astype(dtype) return x, dc @given(x=hu.tensor(min_dim=2, max_dim=5, elements=st.floats(min_value=0.5, max_value=1.0)), dtype=st.sampled_from([np.float32, np.float16]), **hu.gcs) def test_sequence_mask_with_lengths(self, x, dtype, gc, dc): x, dc = self._dtype_conversion(x, dtype, gc, dc) # finite fill value needed for gradient check fill_val = 1e-3 if dtype == np.float16 else 1e-9 op = core.CreateOperator("SequenceMask", ["data", "lengths"], ["masked_data"], mode="sequence", axis=len(x.shape) - 1, fill_val=fill_val) elem_dim = x.shape[-1] leading_dim = 1 for dim in x.shape[:-1]: leading_dim *= dim lengths = np.random.randint(0, elem_dim, [leading_dim])\ .astype(np.int32) def ref(x, lengths): ref = np.reshape(x, [leading_dim, elem_dim]) for i in range(leading_dim): for j in range(elem_dim): if j >= lengths[i]: ref[i, j] = fill_val return [ref.reshape(x.shape)] self.assertReferenceChecks(gc, op, [x, lengths], ref) self.assertDeviceChecks(dc, op, [x, lengths], [0]) @given(x=hu.tensor(min_dim=2, max_dim=5, elements=st.floats(min_value=0.5, max_value=1.0)), dtype=st.sampled_from([np.float32, np.float16]), **hu.gcs) def test_sequence_mask_with_window(self, x, dtype, gc, dc): x, dc = self._dtype_conversion(x, dtype, gc, dc) # finite fill value needed for gradient check fill_val = 1e-3 if dtype == np.float16 else 1e-9 radius = 2 op = core.CreateOperator("SequenceMask", ["data", "centers"], ["masked_data"], mode="window", radius=radius, axis=len(x.shape) - 1, fill_val=fill_val) elem_dim = x.shape[-1] leading_dim = 1 for dim in x.shape[:-1]: leading_dim *= dim centers = np.random.randint(0, elem_dim, [leading_dim])\ .astype(np.int32) def ref(x, centers): ref = np.reshape(x, [leading_dim, elem_dim]) for i in range(leading_dim): for j in range(elem_dim): if j > centers[i] + radius or j < centers[i] - radius: ref[i, j] = fill_val return [ref.reshape(x.shape)] self.assertReferenceChecks(gc, op, [x, centers], ref) self.assertDeviceChecks(dc, op, [x, centers], [0]) threshold = 0.4 if dtype == np.float16 else 0.005 self.assertGradientChecks(gc, op, [x, centers], 0, [0], threshold=threshold) @given(x=hu.tensor(min_dim=2, max_dim=5, elements=st.floats(min_value=0.5, max_value=1.0)), mode=st.sampled_from(['upper', 'lower', 'upperdiag', 'lowerdiag']), dtype=st.sampled_from([np.float32, np.float16]), **hu.gcs) def test_sequence_mask_triangle(self, x, mode, dtype, gc, dc): x, dc = self._dtype_conversion(x, dtype, gc, dc) # finite fill value needed for gradient check fill_val = 1e-3 if dtype == np.float16 else 1e-9 op = core.CreateOperator("SequenceMask", ["data"], ["masked_data"], mode=mode, axis=len(x.shape) - 1, fill_val=fill_val) elem_dim = x.shape[-1] leading_dim = 1 for dim in x.shape[:-1]: leading_dim *= dim if mode == 'upper': def compare(i, j): return j > i elif mode == 'lower': def compare(i, j): return j < i elif mode == 'upperdiag': def compare(i, j): return j >= i elif mode == 'lowerdiag': def compare(i, j): return j <= i def ref(x): ref = np.reshape(x, [leading_dim, elem_dim]) for i in range(leading_dim): for j in range(elem_dim): if compare(i, j): ref[i, j] = fill_val return [ref.reshape(x.shape)] self.assertReferenceChecks(gc, op, [x], ref) self.assertDeviceChecks(dc, op, [x], [0]) threshold = 0.4 if dtype == np.float16 else 0.005 stepsize = 0.1 if dtype == np.float16 else 0.05 self.assertGradientChecks(gc, op, [x], 0, [0], threshold=threshold, stepsize=stepsize) @given(x=hu.tensor(min_dim=2, max_dim=5, elements=st.floats(min_value=0.5, max_value=1.0)), dtype=st.sampled_from([np.float32, np.float16]), **hu.gcs) def test_sequence_mask_batching_lengths(self, x, dtype, gc, dc): x, dc = self._dtype_conversion(x, dtype, gc, dc) # finite fill value needed for gradient check fill_val = 1e-3 if dtype == np.float16 else 1e-9 # choose _different_ batch and axis dimensions, w/ axis != 0. axis = 0 batch = 0 while axis == 0 or axis < batch: inds = np.arange(len(x.shape)) np.random.shuffle(inds) batch = inds[0] axis = inds[1] op = core.CreateOperator("SequenceMask", ["data", "lengths"], ["masked_data"], mode='sequence', axis=axis, fill_val=fill_val, batch=batch) before = int(np.prod(x.shape[:batch + 1])) between = int(np.prod(x.shape[batch + 1:axis])) after = int(np.prod(x.shape[axis:])) lengths = np.random.randint(0, after, [between])\ .astype(np.int32) def ref(z, l): w = np.reshape(z, [before, between, after]) for b in range(before): r = w[b, :, :] for i in range(between): for j in range(after): if j >= l[i]: r[i, j] = fill_val return [w.reshape(z.shape)] self.assertReferenceChecks(gc, op, [x, lengths], ref) self.assertDeviceChecks(dc, op, [x, lengths], [0]) threshold = 0.4 if dtype == np.float16 else 0.005 self.assertGradientChecks(gc, op, [x, lengths], 0, [0], threshold=threshold) @given(x=hu.tensor(min_dim=4, max_dim=4, elements=st.floats(min_value=0.5, max_value=1.0)), dtype=st.sampled_from([np.float32, np.float16]), **hu.gcs) def test_sequence_mask_batching_window(self, x, dtype, gc, dc): x, dc = self._dtype_conversion(x, dtype, gc, dc) # finite fill value needed for gradient check fill_val = 1e-3 if dtype == np.float16 else 1e-9 radius = 1 # choose _different_ batch and axis dimensions, w/ axis != 0. axis = 0 batch = 0 while axis == 0 or axis < batch: inds = np.arange(len(x.shape)) np.random.shuffle(inds) batch = inds[0] axis = inds[1] op = core.CreateOperator("SequenceMask", ["data", "centers"], ["masked_data"], mode='window', radius=radius, axis=axis, fill_val=fill_val, batch=batch) before = int(np.prod(x.shape[:batch + 1])) between = int(np.prod(x.shape[batch + 1:axis])) after = int(np.prod(x.shape[axis:])) centers = np.random.randint(0, after, [between])\ .astype(np.int32) def ref(z, c): w = np.reshape(z, [before, between, after]) for b in range(before): r = w[b, :, :] for i in range(between): for j in range(after): if j > c[i] + radius or j < c[i] - radius: r[i, j] = fill_val return [w.reshape(z.shape)] self.assertReferenceChecks(gc, op, [x, centers], ref) self.assertDeviceChecks(dc, op, [x, centers], [0]) threshold = 0.4 if dtype == np.float16 else 0.005 self.assertGradientChecks(gc, op, [x, centers], 0, [0], threshold=threshold) @given(x=hu.tensor(min_dim=3, max_dim=5, elements=st.floats(min_value=0.5, max_value=1.0)), mode=st.sampled_from(['upper', 'lower', 'upperdiag', 'lowerdiag']), dtype=st.sampled_from([np.float32, np.float16]), **hu.gcs) def test_sequence_mask_batching_triangle(self, x, mode, dtype, gc, dc): x, dc = self._dtype_conversion(x, dtype, gc, dc) # finite fill value needed for gradient check fill_val = 1e-3 if dtype == np.float16 else 1e-9 # choose _different_ batch and axis dimensions, w/ axis != 0. axis = 0 batch = 0 while axis == 0 or axis < batch: inds = np.arange(len(x.shape)) np.random.shuffle(inds) batch = inds[0] axis = inds[1] op = core.CreateOperator("SequenceMask", ["data"], ["masked_data"], mode=mode, axis=axis, fill_val=fill_val, batch=batch) if mode == 'upper': def compare(i, j): return j > i elif mode == 'lower': def compare(i, j): return j < i elif mode == 'upperdiag': def compare(i, j): return j >= i elif mode == 'lowerdiag': def compare(i, j): return j <= i def ref(z): before = int(np.prod(z.shape[:batch + 1])) between = int(np.prod(z.shape[batch + 1:axis])) after = int(np.prod(z.shape[axis:])) w = np.reshape(z, [before, between, after]) for b in range(before): r = w[b, :, :] for i in range(between): for j in range(after): if compare(i, j): r[i, j] = fill_val return [w.reshape(z.shape)] self.assertReferenceChecks(gc, op, [x], ref) self.assertDeviceChecks(dc, op, [x], [0]) threshold = 0.4 if dtype == np.float16 else 0.005 stepsize = 0.1 if dtype == np.float16 else 0.05 self.assertGradientChecks(gc, op, [x], 0, [0], threshold=threshold, stepsize=stepsize) @given(x=hu.tensor(min_dim=3, max_dim=5, elements=st.floats(min_value=0.5, max_value=1.0)), dtype=st.sampled_from([np.float32, np.float16]), **hu.gcs) def test_sequence_mask_repeated(self, x, dtype, gc, dc): x, dc = self._dtype_conversion(x, dtype, gc, dc) # finite fill value needed for gradient check fill_val = 1e-3 if dtype == np.float16 else 1e-9 op = core.CreateOperator("SequenceMask", ["data", "lengths"], ["masked_data"], mode="sequence", axis=len(x.shape) - 2, repeat_from_axis=-1, fill_val=fill_val) elem_dim = x.shape[-2] leading_dim = 1 for dim in x.shape[:-2]: leading_dim *= dim lengths = np.random.randint(0, elem_dim, [leading_dim])\ .astype(np.int32) def ref(x, lengths): ref = np.reshape(x, [leading_dim, elem_dim, -1]) for i in range(leading_dim): for j in range(elem_dim): if j >= lengths[i]: ref[i, j, :] = fill_val return [ref.reshape(x.shape)] self.assertReferenceChecks(gc, op, [x, lengths], ref) self.assertDeviceChecks(dc, op, [x, lengths], [0])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import core from hypothesis import given import hypothesis.strategies as st import caffe2.python.hypothesis_test_util as hu class TestBatchSparseToDense(hu.HypothesisTestCase): @given( batch_size=st.integers(5, 10), dense_last_dim=st.integers(5, 10), default_value=st.floats(min_value=2.0, max_value=3.0), **hu.gcs_cpu_only ) def test_batch_sparse_to_dense( self, batch_size, dense_last_dim, default_value, gc, dc ): L = np.random.randint(1, dense_last_dim + 1, size=(batch_size)) num_data = L.sum() # The following logic ensure that indices in each batch will not be duplicated I = np.array([]).astype(np.int32) for l in L: I_l = np.random.choice(dense_last_dim, l, replace=False) I = np.concatenate((I, I_l)) V = np.random.rand(num_data).astype(np.float32) op = core.CreateOperator( 'BatchSparseToDense', ['L', 'I', 'V'], ['O'], dense_last_dim=dense_last_dim, default_value=default_value, ) S = np.random.rand(batch_size, dense_last_dim).astype(np.float32) op2 = core.CreateOperator( 'BatchSparseToDense', ['L', 'I', 'V', 'S'], ['O'], default_value=default_value, ) def batch_sparse_to_dense_ref(L, I, V, S=None): if S is None: ret = np.zeros((batch_size, dense_last_dim)) else: ret = np.zeros(S.shape) ret.fill(default_value) batch = 0 v_idx = 0 for length in L: for _ in range(length): ret[batch][I[v_idx]] = V[v_idx] v_idx += 1 batch += 1 return [ret] self.assertDeviceChecks(dc, op, [L, I, V], [0]) self.assertReferenceChecks(gc, op, [L, I, V], batch_sparse_to_dense_ref) self.assertGradientChecks(gc, op, [L, I, V], 2, [0]) self.assertDeviceChecks(dc, op2, [L, I, V, S], [0]) self.assertReferenceChecks(gc, op2, [L, I, V, S], batch_sparse_to_dense_ref) self.assertGradientChecks(gc, op2, [L, I, V, S], 2, [0]) @given( batch_size=st.integers(5, 10), dense_last_dim=st.integers(5, 10), **hu.gcs_cpu_only ) def test_batch_dense_to_sparse(self, batch_size, dense_last_dim, gc, dc): L = np.random.randint(1, dense_last_dim + 1, size=(batch_size)) # The following logic ensure that indices in each batch will not be duplicated I = np.array([]).astype(np.int32) for l in L: I_l = np.random.choice(dense_last_dim, l, replace=False) I = np.concatenate((I, I_l)) D = np.random.rand(batch_size, dense_last_dim).astype(np.float32) op = core.CreateOperator( 'BatchDenseToSparse', ['L', 'I', 'D'], ['V'], ) def batch_dense_to_sparse_ref(L, I, D): ret = np.zeros(I.shape) batch = 0 i_idx = 0 for length in L: for _ in range(length): ret[i_idx] = D[batch][I[i_idx]] i_idx += 1 batch += 1 return [ret] print(L, I, D) self.assertDeviceChecks(dc, op, [L, I, D], [0]) self.assertReferenceChecks(gc, op, [L, I, D], batch_dense_to_sparse_ref) self.assertGradientChecks(gc, op, [L, I, D], 2, [0])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import caffe2.python.hypothesis_test_util as hu from caffe2.python import core from hypothesis import given import hypothesis.strategies as st class ChannelShuffleOpsTest(hu.HypothesisTestCase): @given( channels_per_group=st.integers(min_value=1, max_value=5), groups=st.integers(min_value=1, max_value=5), n=st.integers(min_value=1, max_value=2), **hu.gcs) def test_channel_shuffle(self, channels_per_group, groups, n, gc, dc): X = np.random.randn( n, channels_per_group * groups, 5, 6).astype(np.float32) op = core.CreateOperator("ChannelShuffle", ["X"], ["Y"], group=groups, kernel=1) def channel_shuffle_ref(X): Y_r = X.reshape(X.shape[0], groups, X.shape[1] // groups, X.shape[2], X.shape[3]) Y_trns = Y_r.transpose((0, 2, 1, 3, 4)) return (Y_trns.reshape(X.shape),) self.assertReferenceChecks(gc, op, [X], channel_shuffle_ref) self.assertGradientChecks(gc, op, [X], 0, [0]) self.assertDeviceChecks(dc, op, [X], [0])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class TestPairWiseLossOps(hu.HypothesisTestCase): @given(X=hu.arrays(dims=[2, 1], elements=st.floats(min_value=0.0, max_value=10.0)), label=hu.arrays(dims=[2, 1], elements=st.integers(min_value=0, max_value=1), dtype=np.float32), **hu.gcs_cpu_only) def test_pair_wise_loss_predictions(self, X, label, gc, dc): workspace.FeedBlob('X', X) workspace.FeedBlob('label', label) new_label = np.array([label[1], label[0]]) new_x = np.array([X[1], X[0]]) workspace.FeedBlob('new_x', new_x) workspace.FeedBlob('new_label', new_label) net = core.Net('net') net.PairWiseLoss(['X', 'label'], ['output']) net.PairWiseLoss(['new_x', 'new_label'], ['new_output']) plan = core.Plan('predict_data') plan.AddStep(core.execution_step('predict_data', [net], num_iter=1)) workspace.RunPlan(plan) output = workspace.FetchBlob('output') new_output = workspace.FetchBlob('new_output') sign = 1 if label[0] > label[1] else -1 if label[0] == label[1]: self.assertEqual(np.asscalar(output), 0) return self.assertAlmostEqual( np.asscalar(output), np.asscalar(np.log(1 + np.exp(sign * (X[1] - X[0])))), delta=1e-4 ) # check swapping row order doesn't alter overall loss self.assertAlmostEqual(output, new_output) @given(X=hu.arrays(dims=[2, 1], elements=st.floats(min_value=0.0, max_value=10.0)), label=hu.arrays(dims=[2, 1], elements=st.integers(min_value=0, max_value=1), dtype=np.float32), dY=hu.arrays(dims=[1], elements=st.floats(min_value=1, max_value=10)), **hu.gcs_cpu_only) def test_pair_wise_loss_gradient(self, X, label, dY, gc, dc): workspace.FeedBlob('X', X) workspace.FeedBlob('dY', dY) workspace.FeedBlob('label', label) net = core.Net('net') net.PairWiseLossGradient( ['X', 'label', 'dY'], ['dX'], ) plan = core.Plan('predict_data') plan.AddStep(core.execution_step('predict_data', [net], num_iter=1)) workspace.RunPlan(plan) dx = workspace.FetchBlob('dX') sign = 1 if label[0] > label[1] else -1 if label[0] == label[1]: self.assertEqual(np.asscalar(dx[0]), 0) return self.assertAlmostEqual( np.asscalar(dx[0]), np.asscalar(-dY[0] * sign / (1 + np.exp(sign * (X[0] - X[1])))), delta=1e-2 * abs(np.asscalar(dx[0]))) self.assertEqual(np.asscalar(dx[0]), np.asscalar(-dx[1])) delta = 1e-3 up_x = np.array([[X[0] + delta], [X[1]]], dtype=np.float32) down_x = np.array([[X[0] - delta], [X[1]]], dtype=np.float32) workspace.FeedBlob('up_x', up_x) workspace.FeedBlob('down_x', down_x) new_net = core.Net('new_net') new_net.PairWiseLoss(['up_x', 'label'], ['up_output']) new_net.PairWiseLoss(['down_x', 'label'], ['down_output']) plan = core.Plan('predict_data') plan.AddStep(core.execution_step('predict_data', [new_net], num_iter=1)) workspace.RunPlan(plan) down_output_pred = workspace.FetchBlob('down_output') up_output_pred = workspace.FetchBlob('up_output') np.testing.assert_allclose( np.asscalar(dx[0]), np.asscalar( 0.5 * dY[0] * (up_output_pred[0] - down_output_pred[0]) / delta), rtol=1e-2, atol=1e-2) @given(n=st.integers(0, 10), k=st.integers(1, 5), **hu.gcs_cpu_only) def test_pair_wise_loss_batch(self, n, k, gc, dc): lengths = np.random.randint(k, size=n).astype(np.int32) + 1 X = np.random.rand(sum(lengths)).astype(np.float32) label = np.random.randint(k, size=sum(lengths)).astype(np.float32) def pair_wise_op(X, label, lengths): N = lengths.size output = np.zeros(N).astype(np.float32) def f(x): return np.log(1 + np.exp(x)) offset = 0 for idx in range(N): offset += lengths[idx - 1] if idx > 0 else 0 count = 0 for i in range(offset, offset + lengths[idx]): for j in range(offset, i): if label[i] == label[j]: continue sign = 1 if label[i] > label[j] else -1 output[idx] += f(sign * (X[j] - X[i])) count += 1 if count > 0: output[idx] /= count return [output] op = core.CreateOperator( 'PairWiseLoss', ['X', 'label', 'lengths'], 'out' ) # Check against numpy reference self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, label, lengths], reference=pair_wise_op, ) # Check over multiple devices self.assertDeviceChecks(dc, op, [X, label, lengths], [0]) # Gradient check self.assertGradientChecks(gc, op, [X, label, lengths], 0, [0])
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest try: import cv2 import lmdb except ImportError: pass # Handled below from PIL import Image import numpy as np import shutil import six import sys import tempfile # TODO: This test does not test scaling because # the algorithms used by OpenCV in the C and Python # version seem to differ slightly. It does test # most other features from hypothesis import given, settings, Verbosity import hypothesis.strategies as st from caffe2.proto import caffe2_pb2 import caffe2.python.hypothesis_test_util as hu from caffe2.python import workspace, core # Verification routines (applies transformations to image to # verify if the operator produces same result) def verify_apply_bounding_box(img, box): import skimage.util if any(type(box[f]) is not int or np.isnan(box[f] or box[f] < 0) for f in range(0, 4)): return img # Box is ymin, xmin, bound_height, bound_width y_bounds = (box[0], img.shape[0] - box[0] - box[2]) x_bounds = (box[1], img.shape[1] - box[1] - box[3]) c_bounds = (0, 0) if any(el < 0 for el in list(y_bounds) + list(x_bounds) + list(c_bounds)): return img bboxed = skimage.util.crop(img, (y_bounds, x_bounds, c_bounds)) return bboxed # This function is called but not used. It will trip on assert False if # the arguments are wrong (improper example) def verify_rescale(img, minsize): # Here we use OpenCV transformation to match the C code scale_amount = float(minsize) / min(img.shape[0], img.shape[1]) if scale_amount <= 1.0: return img print("Scale amount is %f -- should be < 1.0; got shape %s" % (scale_amount, str(img.shape))) assert False img_cv = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) output_shape = (int(np.ceil(scale_amount * img_cv.shape[0])), int(np.ceil(scale_amount * img_cv.shape[1]))) resized = cv2.resize(img_cv, dsize=output_shape, interpolation=cv2.INTER_AREA) resized = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB) assert resized.shape[0] >= minsize assert resized.shape[1] >= minsize return resized def verify_crop(img, crop): import skimage.util assert img.shape[0] >= crop assert img.shape[1] >= crop y_offset = 0 if img.shape[0] > crop: y_offset = (img.shape[0] - crop) // 2 x_offset = 0 if img.shape[1] > crop: x_offset = (img.shape[1] - crop) // 2 y_bounds = (y_offset, img.shape[0] - crop - y_offset) x_bounds = (x_offset, img.shape[1] - crop - x_offset) c_bounds = (0, 0) cropped = skimage.util.crop(img, (y_bounds, x_bounds, c_bounds)) assert cropped.shape[0] == crop assert cropped.shape[1] == crop return cropped def verify_color_normalize(img, means, stds): # Note the RGB/BGR inversion # Operate on integers like the C version img = img * 255.0 img[:, :, 0] = (img[:, :, 0] - means[2]) / stds[2] img[:, :, 1] = (img[:, :, 1] - means[1]) / stds[1] img[:, :, 2] = (img[:, :, 2] - means[0]) / stds[0] return img * (1.0 / 255.0) # Printing function (for debugging) def caffe2_img(img): # Convert RGB to BGR img = img[:, :, (2, 1, 0)] # Convert HWC to CHW img = img.swapaxes(1, 2).swapaxes(0, 1) img = img * 255.0 return img.astype(np.int32) # Bounding box is ymin, xmin, height, width def create_test(output_dir, width, height, default_bound, minsize, crop, means, stds, count, label_type, num_labels, output1=None, output2_size=None): print("Creating a temporary lmdb database of %d pictures..." % (count)) if default_bound is None: default_bound = [-1] * 4 LMDB_MAP_SIZE = 1 << 40 env = lmdb.open(output_dir, map_size=LMDB_MAP_SIZE, subdir=True) index = 0 # Create images and the expected results expected_results = [] with env.begin(write=True) as txn: while index < count: img_array = np.random.random_integers( 0, 255, [height, width, 3]).astype(np.uint8) img_obj = Image.fromarray(img_array) img_str = six.BytesIO() img_obj.save(img_str, 'PNG') # Create a random bounding box for every other image # ymin, xmin, bound_height, bound_width # TODO: To ensure that we never need to scale, we # ensure that the bounding-box is larger than the # minsize parameter bounding_box = list(default_bound) do_default_bound = True if index % 2 == 0: if height > minsize and width > minsize: do_default_bound = False bounding_box[0:2] = [np.random.randint(a) for a in (height - minsize, width - minsize)] bounding_box[2:4] = [np.random.randint(a) + minsize for a in (height - bounding_box[0] - minsize + 1, width - bounding_box[1] - minsize + 1)] # print("Bounding box is %s" % (str(bounding_box))) # Create expected result img_expected = img_array.astype(np.float32) * (1.0 / 255.0) # print("Orig image: %s" % (str(caffe2_img(img_expected)))) img_expected = verify_apply_bounding_box( img_expected, bounding_box) # print("Bounded image: %s" % (str(caffe2_img(img_expected)))) img_expected = verify_rescale(img_expected, minsize) img_expected = verify_crop(img_expected, crop) # print("Crop image: %s" % (str(caffe2_img(img_expected)))) img_expected = verify_color_normalize(img_expected, means, stds) # print("Color image: %s" % (str(caffe2_img(img_expected)))) tensor_protos = caffe2_pb2.TensorProtos() image_tensor = tensor_protos.protos.add() image_tensor.data_type = 4 # string data image_tensor.string_data.append(img_str.getvalue()) img_str.close() label_tensor = tensor_protos.protos.add() label_tensor.data_type = 2 # int32 data assert (label_type >= 0 and label_type <= 3) if label_type == 0: label_tensor.int32_data.append(index) expected_label = index elif label_type == 1: binary_labels = np.random.randint(2, size=num_labels) for idx, val in enumerate(binary_labels.tolist()): if val == 1: label_tensor.int32_data.append(idx) expected_label = binary_labels elif label_type == 2: embedding_label = np.random.randint(100, size=num_labels) for _idx, val in enumerate(embedding_label.tolist()): label_tensor.int32_data.append(val) expected_label = embedding_label elif label_type == 3: weight_tensor = tensor_protos.protos.add() weight_tensor.data_type = 1 # float weights binary_labels = np.random.randint(2, size=num_labels) expected_label = np.zeros(num_labels).astype(np.float32) for idx, val in enumerate(binary_labels.tolist()): expected_label[idx] = val * idx if val == 1: label_tensor.int32_data.append(idx) weight_tensor.float_data.append(idx) if output1: output1_tensor = tensor_protos.protos.add() output1_tensor.data_type = 1 # float data output1_tensor.float_data.append(output1) output2 = [] if output2_size: output2_tensor = tensor_protos.protos.add() output2_tensor.data_type = 2 # int32 data values = np.random.randint(1024, size=output2_size) for val in values.tolist(): output2.append(val) output2_tensor.int32_data.append(val) expected_results.append( [caffe2_img(img_expected), expected_label, output1, output2]) if not do_default_bound: bounding_tensor = tensor_protos.protos.add() bounding_tensor.data_type = 2 # int32 data bounding_tensor.int32_data.extend(bounding_box) txn.put( '{}'.format(index).encode('ascii'), tensor_protos.SerializeToString() ) index = index + 1 # End while # End with return expected_results def run_test( size_tuple, means, stds, label_type, num_labels, is_test, scale_jitter_type, color_jitter, color_lighting, dc, validator, output1=None, output2_size=None): # TODO: Does not test on GPU and does not test use_gpu_transform # WARNING: Using ModelHelper automatically does NHWC to NCHW # transformation if needed. width, height, minsize, crop = size_tuple means = [float(m) for m in means] stds = [float(s) for s in stds] out_dir = tempfile.mkdtemp() count_images = 2 # One with bounding box and one without expected_images = create_test( out_dir, width=width, height=height, default_bound=(3, 5, height - 3, width - 5), minsize=minsize, crop=crop, means=means, stds=stds, count=count_images, label_type=label_type, num_labels=num_labels, output1=output1, output2_size=output2_size ) for device_option in dc: with hu.temp_workspace(): reader_net = core.Net('reader') reader_net.CreateDB( [], 'DB', db=out_dir, db_type="lmdb" ) workspace.RunNetOnce(reader_net) outputs = ['data', 'label'] output_sizes = [] if output1: outputs.append('output1') output_sizes.append(1) if output2_size: outputs.append('output2') output_sizes.append(output2_size) imageop = core.CreateOperator( 'ImageInput', ['DB'], outputs, batch_size=count_images, color=3, minsize=minsize, crop=crop, is_test=is_test, bounding_ymin=3, bounding_xmin=5, bounding_height=height - 3, bounding_width=width - 5, mean_per_channel=means, std_per_channel=stds, use_gpu_transform=(device_option.device_type == 1), label_type=label_type, num_labels=num_labels, output_sizes=output_sizes, scale_jitter_type=scale_jitter_type, color_jitter=color_jitter, color_lighting=color_lighting ) imageop.device_option.CopyFrom(device_option) main_net = core.Net('main') main_net.Proto().op.extend([imageop]) workspace.RunNetOnce(main_net) validator(expected_images, device_option, count_images) # End for # End with # End for shutil.rmtree(out_dir) # end run_test @unittest.skipIf('cv2' not in sys.modules, 'python-opencv is not installed') @unittest.skipIf('lmdb' not in sys.modules, 'python-lmdb is not installed') class TestImport(hu.HypothesisTestCase): def validate_image_and_label( self, expected_images, device_option, count_images, label_type, is_test, scale_jitter_type, color_jitter, color_lighting): l = workspace.FetchBlob('label') result = workspace.FetchBlob('data').astype(np.int32) # If we don't use_gpu_transform, the output is in NHWC # Our reference output is CHW so we swap if device_option.device_type != 1: expected = [img.swapaxes(0, 1).swapaxes(1, 2) for (img, _, _, _) in expected_images] else: expected = [img for (img, _, _, _) in expected_images] for i in range(count_images): if label_type == 0: self.assertEqual(l[i], expected_images[i][1]) else: self.assertEqual( (l[i] - expected_images[i][1] > 0).sum(), 0) if is_test == 0: # when traing data preparation is randomized (e.g. random cropping, # Inception-style random sized cropping, color jittering, # color lightin), we only compare blob shape for (s1, s2) in zip(expected[i].shape, result[i].shape): self.assertEqual(s1, s2) else: self.assertEqual((expected[i] - result[i] > 1).sum(), 0) # End for # end validate_image_and_label @given(size_tuple=st.tuples( st.integers(min_value=8, max_value=4096), st.integers(min_value=8, max_value=4096)).flatmap(lambda t: st.tuples( st.just(t[0]), st.just(t[1]), st.just(min(t[0] - 6, t[1] - 4)), st.integers(min_value=1, max_value=min(t[0] - 6, t[1] - 4)))), means=st.tuples(st.integers(min_value=0, max_value=255), st.integers(min_value=0, max_value=255), st.integers(min_value=0, max_value=255)), stds=st.tuples(st.floats(min_value=1, max_value=10), st.floats(min_value=1, max_value=10), st.floats(min_value=1, max_value=10)), label_type=st.integers(0, 3), num_labels=st.integers(min_value=8, max_value=4096), is_test=st.integers(min_value=0, max_value=1), scale_jitter_type=st.integers(min_value=0, max_value=1), color_jitter=st.integers(min_value=0, max_value=1), color_lighting=st.integers(min_value=0, max_value=1), **hu.gcs) @settings(verbosity=Verbosity.verbose) def test_imageinput( self, size_tuple, means, stds, label_type, num_labels, is_test, scale_jitter_type, color_jitter, color_lighting, gc, dc): def validator(expected_images, device_option, count_images): self.validate_image_and_label( expected_images, device_option, count_images, label_type, is_test, scale_jitter_type, color_jitter, color_lighting) # End validator run_test( size_tuple, means, stds, label_type, num_labels, is_test, scale_jitter_type, color_jitter, color_lighting, dc, validator) # End test_imageinput @given(size_tuple=st.tuples( st.integers(min_value=8, max_value=4096), st.integers(min_value=8, max_value=4096)).flatmap(lambda t: st.tuples( st.just(t[0]), st.just(t[1]), st.just(min(t[0] - 6, t[1] - 4)), st.integers(min_value=1, max_value=min(t[0] - 6, t[1] - 4)))), means=st.tuples(st.integers(min_value=0, max_value=255), st.integers(min_value=0, max_value=255), st.integers(min_value=0, max_value=255)), stds=st.tuples(st.floats(min_value=1, max_value=10), st.floats(min_value=1, max_value=10), st.floats(min_value=1, max_value=10)), label_type=st.integers(0, 3), num_labels=st.integers(min_value=8, max_value=4096), is_test=st.integers(min_value=0, max_value=1), scale_jitter_type=st.integers(min_value=0, max_value=1), color_jitter=st.integers(min_value=0, max_value=1), color_lighting=st.integers(min_value=0, max_value=1), output1=st.floats(min_value=1, max_value=10), output2_size=st.integers(min_value=2, max_value=10), **hu.gcs) @settings(verbosity=Verbosity.verbose) def test_imageinput_with_additional_outputs( self, size_tuple, means, stds, label_type, num_labels, is_test, scale_jitter_type, color_jitter, color_lighting, output1, output2_size, gc, dc): def validator(expected_images, device_option, count_images): self.validate_image_and_label( expected_images, device_option, count_images, label_type, is_test, scale_jitter_type, color_jitter, color_lighting) output1_result = workspace.FetchBlob('output1') output2_result = workspace.FetchBlob('output2') for i in range(count_images): self.assertEqual(output1_result[i], expected_images[i][2]) self.assertEqual( (output2_result[i] - expected_images[i][3] > 0).sum(), 0) # End for # End validator run_test( size_tuple, means, stds, label_type, num_labels, is_test, scale_jitter_type, color_jitter, color_lighting, dc, validator, output1, output2_size) # End test_imageinput if __name__ == '__main__': import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import core, workspace from caffe2.python.test_util import TestCase, rand_array class TestPartitionOps(TestCase): def test_configs(self): # (main dims, partitions, main type, [list of (extra dims, type)]) configs = [ ((10, ), 3), ((4, ), 10), ((10, 10), 4), ((100, ), 2), ((5, ), 1), ((1, ), 1), ((2, 10), 2), ] suffixes = [ [], [((2, 2), np.float32)], [((3, ), np.int64), ((2, ), np.float32)], ] return [ (main_dims, parts, main_type, extra, pack) for main_dims, parts in configs for main_type in [np.int32, np.int64] for extra in suffixes for pack in [False, True] ] def testPartition(self): for main_dims, parts, main_type, extra_ins, pack in self.test_configs(): ins = ['in' + str(i) for i in range(1 + len(extra_ins))] outs = [ 'in{}_p{}'.format(j, i) for i in range(parts) for j in range(1 + len(extra_ins)) ] op = core.CreateOperator( 'Partition', ins, outs, pack_first_input=(1 if pack else 0)) x = [] for i, (dims, t) in enumerate([((), main_type)] + extra_ins): if t in [np.float32, np.float64]: d = rand_array(*(main_dims + dims)) else: d = np.random.randint(-100, 100, (main_dims + dims)) d = d.astype(t) workspace.FeedBlob(ins[i], d) x.append(d) def sharding(x): # numpy has proper modulo op that yields non-negative results shards = (x[0] % parts).reshape([-1]) out = [] for i in range(parts): for ind, v in enumerate(x): suffix_shape = v.shape[len(x[0].shape):] accum = [] data = v.reshape((-1, ) + suffix_shape) if pack and ind == 0: data = data // parts for j, s in enumerate(shards): if s == i: accum.append(data[j]) def join(a): if not a: return np.empty(shape=(0, ) + suffix_shape) return np.stack(a) out.append(join(accum)) return out workspace.RunOperatorOnce(op) ref = sharding(x) print(x) print(ref) for name, expected in zip(outs, ref): np.testing.assert_array_equal( expected, workspace.FetchBlob(name) ) # test inverse operation (GatherByKey) if len(main_dims) == 1: # currently only 1D key tensor supported for i in range(len(extra_ins)): expected_out = ins[i + 1] gather_ins = [ins[0]] + [ outs[len(ins) * p + i + 1] for p in range(parts)] actual_out = expected_out + '_actual' op = core.CreateOperator( 'GatherByKey', gather_ins, actual_out) workspace.RunOperatorOnce(op) expected = workspace.FetchBlob(expected_out) actual = workspace.FetchBlob(actual_out) np.testing.assert_array_equal(expected, actual) def testLengthsPartition(self): for main_dims, parts, main_type, extra_ins, pack in self.test_configs(): # For LengthsSharding only 1-D tensors supported as a first input if len(main_dims) > 1: continue ins = ['in' + str(i) for i in range(2 + len(extra_ins))] outs = [ 'in{}_p{}'.format(j, i) for i in range(parts) for j in range(2 + len(extra_ins)) ] op = core.CreateOperator( 'LengthsPartition', ins, outs, pack_first_input=(1 if pack else 0) ) x = [] for i, (dims, t) in enumerate([((), main_type)] + extra_ins): if t in [np.float32, np.float64]: d = rand_array(*(main_dims + dims)) else: d = np.random.randint(-100, 100, (main_dims + dims)) d = d.astype(t) workspace.FeedBlob(ins[i + 1], d) x.append(d) # Randomly generate length tensor as well elements = np.random.randint(2, 10) lengths = [] total_length = 0 for _ in range(elements - 1): lengths.append(np.random.randint(main_dims[0] - total_length)) total_length += lengths[-1] lengths.append(main_dims[0] - total_length) workspace.FeedBlob(ins[0], np.array(lengths, dtype=np.int32)) def sharding(x): # numpy has proper modulo op that yields non-negative results shards = (x[0] % parts).reshape([-1]) out = [] for i in range(parts): idx = 0 sharded_lengths = np.zeros(elements) for ind, length in enumerate(lengths): for _ in range(length): if shards[idx] == i: sharded_lengths[ind] += 1 idx += 1 out.append(sharded_lengths) for ind, v in enumerate(x): suffix_shape = v.shape[len(x[0].shape):] accum = [] data = v.reshape((-1, ) + suffix_shape) if pack and ind == 0: data = data // parts for j, s in enumerate(shards): if s == i: accum.append(data[j]) def join(a): if not a: return np.empty(shape=(0, ) + suffix_shape) return np.stack(a) out.append(join(accum)) return out workspace.RunOperatorOnce(op) ref = sharding(x) for name, expected in zip(outs, ref): np.testing.assert_array_equal( expected, workspace.FetchBlob(name) ) if __name__ == "__main__": import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np # Reference implementation from detectron/lib/utils/boxes.py def bbox_transform(boxes, deltas, weights=(1.0, 1.0, 1.0, 1.0)): """Forward transform that maps proposal boxes to predicted ground-truth boxes using bounding-box regression deltas. See bbox_transform_inv for a description of the weights argument. """ if boxes.shape[0] == 0: return np.zeros((0, deltas.shape[1]), dtype=deltas.dtype) boxes = boxes.astype(deltas.dtype, copy=False) widths = boxes[:, 2] - boxes[:, 0] + 1.0 heights = boxes[:, 3] - boxes[:, 1] + 1.0 ctr_x = boxes[:, 0] + 0.5 * widths ctr_y = boxes[:, 1] + 0.5 * heights wx, wy, ww, wh = weights dx = deltas[:, 0::4] / wx dy = deltas[:, 1::4] / wy dw = deltas[:, 2::4] / ww dh = deltas[:, 3::4] / wh # Prevent sending too large values into np.exp() BBOX_XFORM_CLIP = np.log(1000. / 16.) dw = np.minimum(dw, BBOX_XFORM_CLIP) dh = np.minimum(dh, BBOX_XFORM_CLIP) pred_ctr_x = dx * widths[:, np.newaxis] + ctr_x[:, np.newaxis] pred_ctr_y = dy * heights[:, np.newaxis] + ctr_y[:, np.newaxis] pred_w = np.exp(dw) * widths[:, np.newaxis] pred_h = np.exp(dh) * heights[:, np.newaxis] pred_boxes = np.zeros(deltas.shape, dtype=deltas.dtype) # x1 pred_boxes[:, 0::4] = pred_ctr_x - 0.5 * pred_w # y1 pred_boxes[:, 1::4] = pred_ctr_y - 0.5 * pred_h # x2 (note: "- 1" is correct; don't be fooled by the asymmetry) pred_boxes[:, 2::4] = pred_ctr_x + 0.5 * pred_w - 1 # y2 (note: "- 1" is correct; don't be fooled by the asymmetry) pred_boxes[:, 3::4] = pred_ctr_y + 0.5 * pred_h - 1 return pred_boxes # Reference implementation from detectron/lib/utils/boxes.py def clip_tiled_boxes(boxes, im_shape): """Clip boxes to image boundaries. im_shape is [height, width] and boxes has shape (N, 4 * num_tiled_boxes).""" assert boxes.shape[1] % 4 == 0, \ 'boxes.shape[1] is {:d}, but must be divisible by 4.'.format( boxes.shape[1] ) # x1 >= 0 boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0) # y1 >= 0 boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], im_shape[0] - 1), 0) # x2 < im_shape[1] boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], im_shape[1] - 1), 0) # y2 < im_shape[0] boxes[:, 3::4] = np.maximum(np.minimum(boxes[:, 3::4], im_shape[0] - 1), 0) return boxes def generate_rois(roi_counts, im_dims): assert len(roi_counts) == len(im_dims) all_rois = [] for i, num_rois in enumerate(roi_counts): if num_rois == 0: continue # [batch_idx, x1, y1, x2, y2] rois = np.random.uniform( 0, im_dims[i], size=(roi_counts[i], 5) ).astype(np.float32) rois[:, 0] = i # batch_idx # Swap (x1, x2) if x1 > x2 rois[:, 1], rois[:, 3] = np.minimum(rois[:, 1], rois[:, 3]), \ np.maximum(rois[:, 1], rois[:, 3]) # Swap (y1, y2) if y1 > y2 rois[:, 2], rois[:, 4] = np.minimum(rois[:, 2], rois[:, 4]), \ np.maximum(rois[:, 2], rois[:, 4]) all_rois.append(rois) if len(all_rois) > 0: return np.vstack(all_rois) return np.empty((0, 5)).astype(np.float32) class TestBBoxTransformOp(hu.HypothesisTestCase): @given( num_rois=st.integers(1, 10), num_classes=st.integers(1, 10), im_dim=st.integers(100, 600), skip_batch_id=st.booleans(), **hu.gcs_cpu_only ) def test_bbox_transform( self, num_rois, num_classes, im_dim, skip_batch_id, gc, dc ): """ Test with all rois belonging to a single image per run. """ rois = generate_rois([num_rois], [im_dim]) if skip_batch_id: rois = rois[:, 1:5] deltas = np.random.randn(num_rois, 4 * num_classes).astype(np.float32) im_info = np.array([im_dim, im_dim, 1.0]).astype(np.float32).reshape(1, 3) def bbox_transform_ref(rois, deltas, im_info): boxes = rois if rois.shape[1] == 4 else rois[:, 1:5] box_out = bbox_transform(boxes, deltas) im_shape = im_info[0, 0:2] box_out = clip_tiled_boxes(box_out, im_shape) return [box_out] op = core.CreateOperator( "BBoxTransform", ["rois", "deltas", "im_info"], ["box_out"], apply_scale=False, correct_transform_coords=True, ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[rois, deltas, im_info], reference=bbox_transform_ref, ) @given( roi_counts=st.lists(st.integers(0, 5), min_size=1, max_size=10), num_classes=st.integers(1, 10), **hu.gcs_cpu_only ) def test_bbox_transform_batch(self, roi_counts, num_classes, gc, dc): """ Test with rois for multiple images in a batch """ batch_size = len(roi_counts) total_rois = sum(roi_counts) im_dims = np.random.randint(100, 600, batch_size) rois = generate_rois(roi_counts, im_dims) deltas = np.random.randn(total_rois, 4 * num_classes).astype(np.float32) im_info = np.zeros((batch_size, 3)).astype(np.float32) im_info[:, 0] = im_dims im_info[:, 1] = im_dims im_info[:, 2] = 1.0 def bbox_transform_ref(rois, deltas, im_info): box_out = [] offset = 0 for i, num_rois in enumerate(roi_counts): if num_rois == 0: continue cur_boxes = rois[offset:offset + num_rois, 1:5] cur_deltas = deltas[offset:offset + num_rois] cur_box_out = bbox_transform(cur_boxes, cur_deltas) im_shape = im_info[i, 0:2] cur_box_out = clip_tiled_boxes(cur_box_out, im_shape) box_out.append(cur_box_out) offset += num_rois if len(box_out) > 0: box_out = np.vstack(box_out) else: box_out = np.empty(deltas.shape).astype(np.float32) return [box_out, roi_counts] op = core.CreateOperator( "BBoxTransform", ["rois", "deltas", "im_info"], ["box_out", "roi_batch_splits"], apply_scale=False, correct_transform_coords=True, ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[rois, deltas, im_info], reference=bbox_transform_ref, )
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import core import caffe2.python.hypothesis_test_util as hu from hypothesis import given class LpnormTest(hu.HypothesisTestCase): @given(inputs=hu.tensors(n=1, min_dim=1, max_dim=3, dtype=np.float32), **hu.gcs_cpu_only) def test_Lp_Norm(self, inputs, gc, dc): X = inputs[0] # avoid kinks by moving away from 0 X += 0.02 * np.sign(X) X[X == 0.0] += 0.02 self.ws.create_blob("X").feed(X) op = core.CreateOperator( 'LpNorm', ['X'], ['l1_norm'], p=1, ) self.ws.run(op) np.testing.assert_allclose(self.ws.blobs[("l1_norm")].fetch(), np.linalg.norm((X).flatten(), ord=1), rtol=1e-4, atol=1e-4) self.assertDeviceChecks(dc, op, [X], [0]) # Gradient check wrt X self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=1e-2, threshold=1e-2) op = core.CreateOperator( 'LpNorm', ['X'], ['l2_norm'], p=2, ) self.ws.run(op) np.testing.assert_allclose( self.ws.blobs[("l2_norm")].fetch(), np.linalg.norm((X).flatten(), ord=2)**2, rtol=1e-4, atol=1e-4 ) self.assertDeviceChecks(dc, op, [X], [0]) # Gradient check wrt X self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=1e-2, threshold=1e-2) op = core.CreateOperator( 'LpNorm', ['X'], ['l2_averaged_norm'], p=2, average=True ) self.ws.run(op) np.testing.assert_allclose( self.ws.blobs[("l2_averaged_norm")].fetch(), np.linalg.norm((X).flatten(), ord=2)**2 / X.size, rtol=1e-4, atol=1e-4 )
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from hypothesis import given, assume import hypothesis.strategies as st from caffe2.python import core, model_helper import caffe2.python.hypothesis_test_util as hu class TestLeakyRelu(hu.HypothesisTestCase): def _get_inputs(self, N, C, H, W, order): input_data = np.random.rand(N, C, H, W).astype(np.float32) - 0.5 # default step size is 0.05 input_data[np.logical_and( input_data >= 0, input_data <= 0.051)] = 0.051 input_data[np.logical_and( input_data <= 0, input_data >= -0.051)] = -0.051 if order == 'NHWC': input_data = np.transpose(input_data, axes=(0, 2, 3, 1)) return input_data, def _get_op(self, device_option, alpha, order, inplace=False): outputs = ['output' if not inplace else "input"] op = core.CreateOperator( 'LeakyRelu', ['input'], outputs, alpha=alpha, device_option=device_option) return op def _feed_inputs(self, input_blobs, device_option): names = ['input', 'scale', 'bias'] for name, blob in zip(names, input_blobs): self.ws.create_blob(name).feed(blob, device_option=device_option) @given(gc=hu.gcs['gc'], dc=hu.gcs['dc'], N=st.integers(2, 3), C=st.integers(2, 3), H=st.integers(2, 3), W=st.integers(2, 3), alpha=st.floats(0, 1), order=st.sampled_from(['NCHW', 'NHWC']), seed=st.integers(0, 1000)) def test_leaky_relu_gradients(self, gc, dc, N, C, H, W, order, alpha, seed): np.random.seed(seed) op = self._get_op( device_option=gc, alpha=alpha, order=order) input_blobs = self._get_inputs(N, C, H, W, order) self.assertDeviceChecks(dc, op, input_blobs, [0]) self.assertGradientChecks(gc, op, input_blobs, 0, [0]) @given(gc=hu.gcs['gc'], dc=hu.gcs['dc'], N=st.integers(2, 10), C=st.integers(3, 10), H=st.integers(5, 10), W=st.integers(7, 10), alpha=st.floats(0, 1), seed=st.integers(0, 1000)) def test_leaky_relu_layout(self, gc, dc, N, C, H, W, alpha, seed): outputs = {} for order in ('NCHW', 'NHWC'): np.random.seed(seed) input_blobs = self._get_inputs(N, C, H, W, order) self._feed_inputs(input_blobs, device_option=gc) op = self._get_op( device_option=gc, alpha=alpha, order=order) self.ws.run(op) outputs[order] = self.ws.blobs['output'].fetch() np.testing.assert_allclose( outputs['NCHW'], outputs['NHWC'].transpose((0, 3, 1, 2)), atol=1e-4, rtol=1e-4) @given(gc=hu.gcs['gc'], dc=hu.gcs['dc'], N=st.integers(2, 10), C=st.integers(3, 10), H=st.integers(5, 10), W=st.integers(7, 10), order=st.sampled_from(['NCHW', 'NHWC']), alpha=st.floats(0, 1), seed=st.integers(0, 1000), inplace=st.booleans()) def test_leaky_relu_reference_check(self, gc, dc, N, C, H, W, order, alpha, seed, inplace): np.random.seed(seed) if order != "NCHW": assume(not inplace) inputs = self._get_inputs(N, C, H, W, order) op = self._get_op( device_option=gc, alpha=alpha, order=order, inplace=inplace) def ref(input_blob): result = input_blob.copy() result[result < 0] *= alpha return result, self.assertReferenceChecks(gc, op, inputs, ref) @given(gc=hu.gcs['gc'], dc=hu.gcs['dc'], N=st.integers(2, 10), C=st.integers(3, 10), H=st.integers(5, 10), W=st.integers(7, 10), order=st.sampled_from(['NCHW', 'NHWC']), alpha=st.floats(0, 1), seed=st.integers(0, 1000)) def test_leaky_relu_device_check(self, gc, dc, N, C, H, W, order, alpha, seed): np.random.seed(seed) inputs = self._get_inputs(N, C, H, W, order) op = self._get_op( device_option=gc, alpha=alpha, order=order) self.assertDeviceChecks(dc, op, inputs, [0]) @given(N=st.integers(2, 10), C=st.integers(3, 10), H=st.integers(5, 10), W=st.integers(7, 10), order=st.sampled_from(['NCHW', 'NHWC']), alpha=st.floats(0, 1), seed=st.integers(0, 1000)) def test_leaky_relu_model_helper_helper(self, N, C, H, W, order, alpha, seed): np.random.seed(seed) arg_scope = {'order': order} model = model_helper.ModelHelper(name="test_model", arg_scope=arg_scope) model.LeakyRelu( 'input', 'output', alpha=alpha) input_blob = np.random.rand(N, C, H, W).astype(np.float32) if order == 'NHWC': input_blob = np.transpose(input_blob, axes=(0, 2, 3, 1)) self.ws.create_blob('input').feed(input_blob) self.ws.create_net(model.param_init_net).run() self.ws.create_net(model.net).run() output_blob = self.ws.blobs['output'].fetch() if order == 'NHWC': output_blob = np.transpose(output_blob, axes=(0, 3, 1, 2)) assert output_blob.shape == (N, C, H, W) if __name__ == '__main__': import unittest unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from hypothesis import assume, given import hypothesis.strategies as st import numpy as np from caffe2.python import core import caffe2.python.hypothesis_test_util as hu from caffe2.proto import caffe2_pb2 import unittest class TestChannelStats(hu.HypothesisTestCase): @given( size=st.integers(7, 10), inputChannels=st.integers(1, 10), batchSize=st.integers(1, 3), **hu.gcs ) def testChannelStats(self, size, inputChannels, batchSize, gc, dc): op = core.CreateOperator( "ChannelStats", ["X"], ["sum", "sumsq"], ) def referenceChannelStatsTest(X): sums = np.sum(X, axis=(0, 2, 3), keepdims=False) sumsq = np.zeros(inputChannels) sumsq = np.sum(X**2, axis=(0, 2, 3), keepdims=False) return sums, sumsq X = np.random.rand(batchSize, inputChannels, size, size)\ .astype(np.float32) - 0.5 self.assertReferenceChecks(gc, op, [X], referenceChannelStatsTest) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from hypothesis import given import hypothesis.strategies as st import numpy as np from caffe2.python import core import caffe2.python.hypothesis_test_util as hu class TestCosineEmbeddingCriterion(hu.HypothesisTestCase): @given(N=st.integers(min_value=10, max_value=20), seed=st.integers(min_value=0, max_value=65535), margin=st.floats(min_value=-0.5, max_value=0.5), **hu.gcs) def test_cosine_embedding_criterion(self, N, seed, margin, gc, dc): np.random.seed(seed) S = np.random.randn(N).astype(np.float32) Y = np.random.choice([-1, 1], size=N).astype(np.int32) op = core.CreateOperator( "CosineEmbeddingCriterion", ["S", "Y"], ["output"], margin=margin) def ref_cec(S, Y): result = (1 - S) * (Y == 1) + np.maximum(S - margin, 0) * (Y == -1) return (result, ) # This checks the op implementation against a reference function in # python. self.assertReferenceChecks(gc, op, [S, Y], ref_cec) # This checks the op implementation over multiple device options (e.g. # CPU and CUDA). [0] means that the 0-th output is checked. self.assertDeviceChecks(dc, op, [S, Y], [0]) # Now, since this operator's output has a "kink" around the margin # value, we move the S vector away from the margin a little bit. This # is a standard trick to avoid gradient check to fail on subgradient # points. S[np.abs(S - margin) < 0.1] += 0.2 # This checks the operator's gradient. the first 0 means that we are # checking the gradient of the first input (S), and the second [0] means # that the gradient check should initiate from the 0-th output. self.assertGradientChecks(gc, op, [S, Y], 0, [0]) if __name__ == "__main__": import unittest unittest.main()