python_code
stringlengths
0
258k
## @package functional # Module caffe2.python.layers.functional from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, schema, scope, workspace from caffe2.python.layers.layers import ( ModelLayer, ) import caffe2.proto.caffe2_pb2 as caffe2_pb2 import numpy as np import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class Functional(ModelLayer): def __init__(self, model, input_record, output_names_or_num, function, name='functional', output_dtypes=None, **kwargs): # allow coercion input_record = schema.as_record(input_record) super(Functional, self).__init__(model, name, input_record, **kwargs) self._function = function self._kwargs = kwargs with scope.NameScope(self.name): if isinstance(output_names_or_num, int): self.output_schema = schema.NewRecord( model.net, schema.RawTuple(output_names_or_num)) elif isinstance(output_names_or_num, schema.Field): self.output_schema = output_names_or_num.clone(keep_blobs=True) return else: if not isinstance(output_names_or_num, list): output_names_or_num = [output_names_or_num] out_tuple = [(out, np.void) for out in output_names_or_num] self.output_schema = schema.NewRecord( model.net, schema.Struct(*out_tuple)) num_outputs = len(self.output_schema.field_blobs()) # If output_dtypes is provided, use it for output schema. Otherwise # the shape and type will be inferred. if output_dtypes is not None: if not isinstance(output_dtypes, list): output_dtypes = [output_dtypes] * num_outputs assert len(output_dtypes) == num_outputs for dtype, scalar in zip(output_dtypes, self.output_schema.all_scalars()): scalar.set_type(dtype) return # Fake execution of the function to infer shapes and types automatically had_issues = False try: type_net = core.Net('_temp_type_and_shape_inference_net') schema.InitEmptyRecord(type_net, input_record, enforce_types=True) function(type_net, self.input_record, self.output_schema, **kwargs) (shapes, types) = workspace.InferShapesAndTypes([type_net], {}) for i in range(num_outputs): blob = self.output_schema[i]() if blob not in types or blob not in shapes: had_issues = True continue if shapes[blob] == []: # Scalar type shape = tuple() elif shapes[blob][0] == 0: shape = tuple(shapes[blob][1:]) else: logger.warning("unexpeced shape: {}".format(shapes[blob])) # If batch dimension is not first - give up on shape # inference for that blob had_issues = True continue # TODO(amalevich): Move it to some shared library dtype = None if types[blob] == caffe2_pb2.TensorProto.DOUBLE: dtype = (np.float64, shape) elif types[blob] == caffe2_pb2.TensorProto.FLOAT: dtype = (np.float32, shape) elif types[blob] == caffe2_pb2.TensorProto.INT32: dtype = (np.int32, shape) elif types[blob] == caffe2_pb2.TensorProto.INT64: dtype = (np.int64, shape) if dtype is not None: self.output_schema[i].set_type(dtype) except TypeError as ex: had_issues = True logger.warning(str(ex)) if had_issues: logger.warning( "Type inference had problems for layer: {}".format(self.name)) def add_ops(self, net): self._function( net, self.input_record, self.output_schema, **(self._kwargs))
## @package expand_dims # Module caffe2.python.layers.expand_dims from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, schema from caffe2.python.layers.layers import ( ModelLayer, ) class ExpandDims(ModelLayer): def __init__(self, model, input_record, dims, name='expand_dims', **kwargs): super(ExpandDims, self).__init__(model, name, input_record, **kwargs) self.dims = dims # Assume that first dimension is batch, so actual dims[i] in shape is # dims[i] - 1 dims = [d - 1 for d in dims] assert all([d >= 0 for d in dims]) assert isinstance(input_record, schema.Scalar),\ "Incorrect input type. Excpected Scalar, but received: {0}".\ format(input_record) input_dims = list(input_record.field_type().shape) dims = sorted(set(dims)) assert len(input_dims) + len(dims) >= dims[-1] + 1 output_dims = input_dims[:] for dim in dims: output_dims.insert(dim, 1) self.output_schema = schema.Scalar( (input_record.field_type().base, output_dims), model.net.NextScopedBlob(name + '_output')) def add_ops(self, net): net.ExpandDims( self.input_record(), self.output_schema(), dims=self.dims, )
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging from caffe2.python import schema from caffe2.python.layers.layers import ( InstantiationContext, ModelLayer, ) logger = logging.getLogger(__name__) class SelectRecordByContext(ModelLayer): """ Allowing model to follow different paths for each instatiation context and join later at some point. The implementation use `Alias` because schema sometimes clone fields internally so we need static blob name for output """ def __init__(self, model, input_record, name='select_record_by_context', check_field_metas=True, **kwargs): super(SelectRecordByContext, self).__init__(model, name, input_record, **kwargs) assert isinstance(input_record, schema.Struct) assert len(input_record) > 1 ref_record = input_record[0] for record in input_record: assert schema.equal_schemas(record, ref_record, check_field_metas=check_field_metas) self.output_schema = schema.NewRecord(model.net, ref_record) def _set_output_blobs(self, net, context): assert context in self.input_record, ( "{} context is not in input record".format(context) ) record = self.input_record[context] for in_blob, out_blob in zip( record.field_blobs(), self.output_schema.field_blobs() ): net.Alias(in_blob, out_blob) def add_ops(self, net): self._set_output_blobs(net, InstantiationContext.PREDICTION) def add_eval_ops(self, net): self._set_output_blobs(net, InstantiationContext.EVAL) def add_train_ops(self, net): self._set_output_blobs(net, InstantiationContext.TRAINING) def add_ops_to_accumulate_pred(self, net): self._set_output_blobs(net, InstantiationContext.ACCUMULATE_PRED)
## @package split # Module caffe2.python.layers.split from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, schema from caffe2.python.layers.layers import ( ModelLayer, ) class Split(ModelLayer): def __init__(self, model, input_record, num_splits, axis=1, name='split', **kwargs): super(Split, self).__init__(model, name, input_record, **kwargs) self.axis = axis # Assume that first dimension is batch, so actual axis in shape is # axis - 1 axis -= 1 assert axis >= 0 assert isinstance(input_record, schema.Scalar),\ "Incorrect input type. Excpected Scalar, but received: {0}".\ format(input_record) input_shape = input_record.field_type().shape assert len(input_shape) >= axis assert input_shape[axis] % num_splits == 0 output_shape = list(input_shape) output_shape[axis] = int(output_shape[axis] / num_splits) data_type = input_record.field_type().base output_scalars = [ schema.Scalar( (data_type, output_shape), model.net.NextScopedBlob(name + '_output_{}'.format(i)), ) for i in range(num_splits) ] self.output_schema = schema.Tuple(*output_scalars) def add_ops(self, net): net.Split( self.input_record.field_blobs(), self.output_schema.field_blobs(), axis=self.axis, )
## @package sparse_to_dense # Module caffe2.python.layers.sparse_to_dense from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import schema from caffe2.python.layers.layers import ( ModelLayer, ) import numpy as np class SparseToDense(ModelLayer): _known_types = ['FLOAT', 'ID_LIST'] def __init__(self, model, input_record, input_specs, name='sparse_to_dense', **kwargs): """ `input_specs` follows the format of FeatureSpec from schema. To be more precise it's a namedtuple that should have: 'feature_type', 'feature_names', 'feature_ids' """ super(SparseToDense, self).__init__(model, name, input_record, **kwargs) self.input_specs = input_specs outputs = [] for field, feature_specs in self.input_specs: assert len(feature_specs.feature_names) ==\ len(feature_specs.feature_ids) if feature_specs.feature_type == 'FLOAT': outputs.append(( field, schema.Scalar( (np.float32, (len(feature_specs.feature_ids), )), model.net.NextScopedBlob(name + '_' + field + '_output') ) )) elif feature_specs.feature_type == 'ID_LIST': outputs.append(( field, schema.Struct( ('ranges', schema.Scalar( ( np.int32, (len(feature_specs.feature_ids), 2) ), model.net.NextScopedBlob( name + '_' + field + '_ranges') ), ), ('values', input_record[field].values.items), ) )) elif feature_specs.feature_type == 'ID_SCORE_LIST': outputs.append(( field, schema.Struct( ('ranges', schema.Scalar( ( np.int32, (len(feature_specs.feature_ids), 2) ), model.net.NextScopedBlob( name + '_' + field + '_ranges') ), ), ('ids', input_record[field].values.keys), ('scores', input_record[field].values.values), ) )) else: raise TypeError( "Unsupported input type: {0}". format(feature_specs.feature_type)) # TODO(amalevich): This schema is producing ranges. And thus if there is # something using it it should support ranges as well. It might be # confusing, if we don't add better support for ranges/have it as a # first layer self.output_schema = schema.Struct( *outputs ) # TODO(amalevich): Consider moving this data to schema, instead # Structs doens't support attaching metadata to them and clonning # will break things badly, but this is the most elegant way to pass # this info around. Should we change it or it'll be too much work and # not worse it? for field, feature_specs in input_specs: schema.attach_metadata_to_scalars( self.output_schema[field], schema.Metadata( feature_specs=feature_specs) ) self.zero = model.global_constants['ZERO'] self.zero_range = model.global_constants['ZERO_RANGE'] # Add operators to all types that need to be densified def add_ops(self, net): record = self.input_record for field, feature_specs in self.input_specs: if feature_specs.feature_type == 'FLOAT': net.SparseToDenseMask( [ record[field].keys(), record[field].values(), self.zero, record[field].lengths(), ], [ self.output_schema[field](), ], mask=feature_specs.feature_ids, ) elif feature_specs.feature_type == 'ID_LIST': id_list_ranges = net.LengthsToRanges( record[field].values.lengths(), net.NextScopedBlob('id_list_ranges') ) net.SparseToDenseMask( [ record[field].keys(), id_list_ranges, self.zero_range, record[field].lengths() ], self.output_schema[field].ranges(), mask=feature_specs.feature_ids, ) elif feature_specs.feature_type == 'ID_SCORE_LIST': # TODO: merge this to the case above? id_list_ranges = net.LengthsToRanges( record[field].values.lengths(), net.NextScopedBlob('id_score_list_ranges') ) net.SparseToDenseMask( [ record[field].keys(), id_list_ranges, self.zero_range, record[field].lengths() ], self.output_schema[field].ranges(), mask=feature_specs.feature_ids, ) def get_metadata(self): metadata = [] for field, feature_specs in self.input_specs: metadata.append( ( { 'type': feature_specs.feature_type, 'names': feature_specs.feature_names, 'ids': feature_specs.feature_ids, }, self.output_schema[field].field_blobs(), self.output_schema[field].field_types() ) ) if feature_specs.feature_type == 'FLOAT': metadata[-1][0]['cardinality'] = 1 return metadata
## @package dot_product # Module caffe2.python.layers.dot_product from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, schema from caffe2.python.layers.layers import ( ModelLayer, ) class DotProduct(ModelLayer): def __init__(self, model, input_record, name='dot_product', **kwargs): super(DotProduct, self).__init__(model, name, input_record, **kwargs) assert isinstance(input_record, schema.Struct),\ "Incorrect input type. Excpected Struct, but received: {0}".\ format(input_record) assert len(input_record.get_children()) == 2, ( "DotProduct accept 2 inputs") assert len(set(input_record.field_types())) == 1, ( "Inputs should be of the same field type") for field_name, field_type in input_record.fields.items(): assert isinstance(field_type, schema.Scalar),\ "Incorrect input type for {}. Excpected Scalar, but got: {}".\ format(field_name, field_type) self.output_schema = schema.Scalar( (input_record.field_types()[0].base, ()), model.net.NextScopedBlob(name + '_output')) def add_ops(self, net): net.DotProduct( self.input_record.field_blobs(), self.output_schema(), )
## @package layers # Module caffe2.python.layers.layers from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, schema, scope from caffe2.python.layers.tags import TagContext from collections import namedtuple import numpy as np # Some types to simplify descriptions of things traveling between ops IdList = schema.List(np.int64) IdScoreList = schema.Map(np.int64, np.float32) def get_categorical_limit(record): if schema.equal_schemas(record, IdList): key = 'items' elif schema.equal_schemas(record, IdScoreList): key = 'keys' else: raise NotImplementedError() assert record[key].metadata is not None, ( "Blob {} doesn't have metadata".format(str(record[key]()))) return record[key].metadata.categorical_limit def set_request_only(field): for f in field.all_scalars(): categorical_limit, expected_value = None, None if not f.metadata: feature_specs = schema.FeatureSpec( feature_is_request_only=True, ) elif not f.metadata.feature_specs: categorical_limit = f.metadata.categorical_limit expected_value = f.metadata.expected_value feature_specs = schema.FeatureSpec( feature_is_request_only=True, ) else: categorical_limit = f.metadata.categorical_limit expected_value = f.metadata.expected_value feature_specs = schema.FeatureSpec( feature_type=f.metadata.feature_specs.feature_type, feature_names=f.metadata.feature_specs.feature_names, feature_ids=f.metadata.feature_specs.feature_ids, feature_is_request_only=True, ) # make sure not to set categorical_limit for a non-integer field if not np.issubdtype(f.field_type(), np.integer): assert categorical_limit is None, \ "categorical_limit shouldn't be set for no-integer field" f.set_metadata( schema.Metadata( categorical_limit=categorical_limit, expected_value=expected_value, feature_specs=feature_specs, ) ) class InstantiationContext(object): """ List of contexts where layer could be instantitated """ # The layers support this context will accumulates predictions, labels, # weights. The accumulated data can later be used to compute # calibration or for other # purpose. ACCUMULATE_PRED = 'accumulate_pred' EVAL = 'eval' PREDICTION = 'prediction' TRAINING = 'training' _LAYER_REGISTRY = {} def register_layer(name, layer): assert name not in _LAYER_REGISTRY, "{0} already exists".format(name) _LAYER_REGISTRY[name] = layer def layer_exists(name): return name in _LAYER_REGISTRY def get_layer_class(name): return _LAYER_REGISTRY[name] def create_layer(layer_name, *args, **kwargs): return _LAYER_REGISTRY[layer_name](*args, **kwargs) LayerPsParam = namedtuple('LayerPsParam', ['sparse_key', 'average_length']) class LayerParameter(object): def __init__(self, parameter=None, optimizer=None, initializer=None, ps_param=None): assert isinstance(parameter, core.BlobReference), \ "expect {0} to be a blob reference".format(str(parameter)) self.parameter = parameter self.optimizer = optimizer self.initializer = initializer self.ps_param = ps_param def is_request_only_scalar(scalar): if len(scalar.field_metadata()) == 0: return False for metadata in scalar.field_metadata(): if not (metadata and metadata.feature_specs and getattr( metadata.feature_specs, 'feature_is_request_only', False)): return False return True class ModelLayer(object): def __init__(self, model, prefix, input_record, predict_input_record_fields=None, tags=None, **kwargs): """ Base class for model layers. Layer is an abstraction that allows to provide model description in terms of meta-operators, where each of the meta-operators can have different implementations for training, evaluation and prediction, that are instantiated later. As an example SampledSoftmax can do something related to sampling depending on supervision during the training and just apply softmax if it's used for prediction/evaluation. All inputs/outputs from layers are represented as a record (instance of schema bounded to blobs) and are accessible through input_record and output_schema. If Layer needs to have only a subset of inputs/provides subset of outputs during the inference - it should provide predict_input_record and predict_output_schema correspondingly (those records are expected to be a subset of input_record/output_schema). Each layer is also have list of Tags associated with it, that depends on current context and arguments. It's possible to use those tags during the instantiation time. """ self.name = model.next_layer_name(prefix) self.model = model self.kwargs = kwargs self._input_record = input_record if predict_input_record_fields: if not isinstance(predict_input_record_fields, list): predict_input_record_fields = [predict_input_record_fields] self._predict_input_record = self._input_record[ predict_input_record_fields] else: self._predict_input_record = None self.request_only = True if len(input_record.all_scalars()) == 0: self.request_only = False for scalar in input_record.all_scalars(): if not is_request_only_scalar(scalar): self.request_only = False break self._output_schema = None self._predict_output_schema = None self.eval_output_schema = None self.tags = set(tags or []) self.tags.update(TagContext.current().tags) self.params = [] def get_type(self): return self.__class__.__name__ def _check_output_schema(self): assert self._output_schema is not None, "Schema is not initialized" assert (self._predict_output_schema is None or schema.is_schema_subset(self._predict_output_schema, self._output_schema)), ( "predict_output_schema is not a subset of the output_schema") @property def predict_input_record(self): return self._predict_input_record or self._input_record @property def input_record(self): return self._input_record @property def predict_output_schema(self): self._check_output_schema() return self._predict_output_schema or self._output_schema @predict_output_schema.setter def predict_output_schema(self, output_schema): assert self._predict_output_schema is None self._predict_output_schema = output_schema @property def output_schema(self): if self.request_only: set_request_only(self._output_schema) self._check_output_schema() return self._output_schema @output_schema.setter def output_schema(self, output_schema): assert self._output_schema is None self._output_schema = output_schema def get_parameters(self): return self.params def get_fp16_compatible_parameters(self): """Return a subset of parameters which can be converted to fp16""" return [] def get_memory_usage(self): return 0 def add_operators(self, net, init_net=None, context=InstantiationContext.TRAINING): # Namescope below should warranty that all intermediate blobs will be # assiciated with the layer that produces them with scope.NameScope(self.name): if context not in {InstantiationContext.PREDICTION, InstantiationContext.EVAL, InstantiationContext.ACCUMULATE_PRED}: assert init_net, ( "Only prediction and eval context don't need init_net") if init_net: for param in self.params: # TODO(amalevich): Either return back to lambdas, that add # all params (looks a bit safer and breaking less # abstractions) or extend Net interface to this type of # operations better # TODO(xlwang) init_net._net.op has type google.protobuf.\ # internal.containers.RepeatedCompositeFieldContainer, but # the version of protobuf in fbcode does not support append # so extend is used init_net._net.op.extend([param.initializer]) if context == InstantiationContext.TRAINING: self.add_train_ops(net) elif context == InstantiationContext.EVAL: self.add_eval_ops(net) elif context == InstantiationContext.ACCUMULATE_PRED: self.add_ops_to_accumulate_pred(net) else: self.add_ops(net) def add_ops(self, net): raise NotImplementedError def add_eval_ops(self, net): # Default train layer implementation is completely matching predict # layer implementation. self.add_ops(net) def add_train_ops(self, net): # Default eval layer implementation is completely matching eval # layer implementation. self.add_eval_ops(net) def add_ops_to_accumulate_pred(self, net): # This adds operators to accumulate predictions/labels/weights. The # accumulated data can later be used to compute calibration or for other # purpose. Default layer implementation is completely matching eval # layer implementation. self.add_eval_ops(net)
## @package batch_mse_loss # Module caffe2.python.layers.batch_mse_loss from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import schema from caffe2.python.layers.layers import ( ModelLayer, ) from caffe2.python.layers.tags import ( Tags ) import numpy as np class BatchMSELoss(ModelLayer): def __init__(self, model, input_record, name='batch_mse_loss', **kwargs): super(BatchMSELoss, self).__init__(model, name, input_record, **kwargs) assert schema.is_schema_subset( schema.Struct( ('label', schema.Scalar()), ('prediction', schema.Scalar()) ), input_record ) self.tags.update(Tags.TRAIN_ONLY) self.output_schema = schema.Scalar( np.float32, model.net.NextScopedBlob(name + '_output')) def add_ops(self, net): prediction = net.Squeeze( self.input_record.prediction(), net.NextScopedBlob('squeezed_prediction'), dims=[1] ) label = self.input_record.label.field_blobs() if self.input_record.label.field_type().base != ( self.input_record.prediction.field_type().base): label = net.Cast( label, net.NextScopedBlob('cast_label'), to=schema.data_type_for_dtype( self.input_record.prediction.field_type() ) ) label = net.StopGradient( label, net.NextScopedBlob('stopped_label') ) l2dist = net.SquaredL2Distance( [label, prediction], net.NextScopedBlob('l2') ) net.AveragedLoss(l2dist, self.output_schema.field_blobs())
## @package uniform_sampling # Module caffe2.python.layers.uniform_sampling 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, schema from caffe2.python.layers.layers import LayerParameter, ModelLayer class UniformSampling(ModelLayer): """ Uniform sampling `num_samples - len(input_record)` unique elements from the range [0, num_elements). `samples` is the concatenation of input_record and the samples. input_record is expected to be unique. """ def __init__( self, model, input_record, num_samples, num_elements, name='uniform_sampling', **kwargs ): super(UniformSampling, self).__init__( model, name, input_record, **kwargs ) assert num_elements > 0 assert isinstance(input_record, schema.Scalar) self.num_elements = num_elements self.num_samples = model.net.NextScopedBlob(name + "_num_samples") self.params.append( LayerParameter( parameter=self.num_samples, initializer=core.CreateOperator( "GivenTensorInt64Fill", [], self.num_samples, shape=(1, ), values=[num_samples], ), optimizer=model.NoOptim, ) ) self.sampling_prob = model.net.NextScopedBlob(name + "_prob") self.params.append( LayerParameter( parameter=self.sampling_prob, initializer=core.CreateOperator( "ConstantFill", [], self.sampling_prob, shape=(num_samples, ), value=float(num_samples) / num_elements, dtype=core.DataType.FLOAT ), optimizer=model.NoOptim, ) ) self.output_schema = schema.Struct( ( 'samples', schema.Scalar( np.int32, model.net.NextScopedBlob(name + "_samples") ) ), ('sampling_prob', schema.Scalar(np.float32, self.sampling_prob)), ) def add_ops(self, net): net.StopGradient(self.sampling_prob, self.sampling_prob) shape = net.Shape([self.input_record()], net.NextScopedBlob("shape")) shape = net.Sub([self.num_samples, shape], shape) samples = net.UniqueUniformFill( [shape, self.input_record()], net.NextScopedBlob("samples"), min=0, max=self.num_elements - 1, input_as_shape=True ) net.Concat( [self.input_record(), samples], [self.output_schema.samples(), net.NextScopedBlob("split_info")], axis=0 ) net.StopGradient( self.output_schema.samples(), self.output_schema.samples() )
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 TestMatMul(hu.HypothesisTestCase): @given(M=st.integers(min_value=1, max_value=10), K=st.integers(min_value=1, max_value=10), N=st.integers(min_value=1, max_value=10), trans_a=st.booleans(), trans_b=st.booleans(), **hu.gcs) def test_matmul(self, M, K, N, trans_a, trans_b, gc, dc): X = np.random.rand(M, K).astype(np.float32) - 0.5 if trans_a: X = X.transpose() Y = np.random.rand(K, N).astype(np.float32) - 0.5 if trans_b: Y = Y.transpose() op = core.CreateOperator( 'MatMul', ['X', 'Y'], 'out', trans_a=trans_a, trans_b=trans_b) def matmul_ref(X, Y, trans_a, trans_b): XX = X.transpose() if trans_a else X YY = Y.transpose() if trans_b else Y return (XX.dot(YY),) # Check against numpy reference self.assertReferenceChecks(gc, op, [X, Y, trans_a, trans_b], matmul_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]) class TestBatchMatMul(hu.HypothesisTestCase): @given(C=st.integers(min_value=1, max_value=10), M=st.integers(min_value=1, max_value=10), K=st.integers(min_value=1, max_value=10), N=st.integers(min_value=1, max_value=10), trans_a=st.booleans(), trans_b=st.booleans(), **hu.gcs) def test_batch_matmul(self, C, M, K, N, trans_a, trans_b, gc, dc): X = np.random.rand(C, M, K).astype(np.float32) - 0.5 if trans_a: X = X.swapaxes(1, 2) Y = np.random.rand(C, K, N).astype(np.float32) - 0.5 if trans_b: Y = Y.swapaxes(1, 2) op = core.CreateOperator( 'BatchMatMul', ['X', 'Y'], 'out', trans_a=trans_a, trans_b=trans_b) def matmul_ref(X, Y, trans_a, trans_b): XX = X.swapaxes(1, 2) if trans_a else X YY = Y.swapaxes(1, 2) if trans_b else Y output = np.zeros((C, M, N)).astype(XX.dtype) for i in range(C): output[i] = XX[i].dot(YY[i]) return (output,) # Check against numpy reference self.assertReferenceChecks(gc, op, [X, Y, trans_a, trans_b], matmul_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]) 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 numpy.testing as npt from hypothesis import given import hypothesis.strategies as st import functools def primefac(n): ret = [] divisor = 2 while divisor * divisor <= n: while (n % divisor) == 0: ret.append(divisor) n = n // divisor divisor = divisor + 1 if n > 1: ret.append(n) return ret class TestReBatchingQueue(TestCase): def test_rebatching_queue_single_enqueue_dequeue(self): net = core.Net('net') tensors = [ net.ConstantFill([], 1, value=1.0, run_once=False) for times in range(3) ] queue = net.CreateRebatchingQueue([], 1, capacity=10, num_blobs=1) net.EnqueueRebatchingQueue([queue, tensors[0]], []) net.EnqueueRebatchingQueue([queue, tensors[1]], []) net.EnqueueRebatchingQueue([queue, tensors[2]], []) results = [ net.DequeueRebatchingQueue([queue], 1), net.DequeueRebatchingQueue([queue], 1), net.DequeueRebatchingQueue([queue], 1), ] workspace.RunNetOnce(net) for idx in range(3): self.assertEquals(workspace.FetchBlob(results[idx]), [1.0]) def test_rebatching_queue_multi_enqueue_dequeue(self): net = core.Net('net') workspace.FeedBlob( "tensors", np.array([x for x in range(10)], np.int32) ) queue = net.CreateRebatchingQueue([], 1, capacity=10, num_blobs=1) net.EnqueueRebatchingQueue([queue, "tensors"], [], enqueue_batch=True) results = [ net.DequeueRebatchingQueue([queue], 1, num_elements=5), net.DequeueRebatchingQueue([queue], 1, num_elements=5), ] workspace.RunNetOnce(net) npt.assert_array_equal( workspace.FetchBlob(results[0]), workspace.FetchBlob("tensors")[:5] ) npt.assert_array_equal( workspace.FetchBlob(results[1]), workspace.FetchBlob("tensors")[5:] ) def test_rebatching_queue_closes_properly(self): net = core.Net('net') workspace.FeedBlob( "tensors", np.array([x for x in range(10)], np.int32) ) queue = net.CreateRebatchingQueue([], 1, capacity=10, num_blobs=1) net.EnqueueRebatchingQueue([queue, "tensors"], 0, enqueue_batch=True) net.CloseRebatchingQueue([queue], 0) results = [ net.DequeueRebatchingQueue([queue], 1, num_elements=5), net.DequeueRebatchingQueue([queue], 1, num_elements=5), ] workspace.RunNetOnce(net) npt.assert_array_equal( workspace.FetchBlob(results[0]), workspace.FetchBlob("tensors")[:5] ) npt.assert_array_equal( workspace.FetchBlob(results[1]), workspace.FetchBlob("tensors")[5:] ) # Enqueuing more should fail now since the queue is closed net.EnqueueRebatchingQueue([queue, "tensors"], [], enqueue_batch=True) with self.assertRaises(RuntimeError): workspace.RunNetOnce(net) # Dequeuing more should fail now since the queue is closed results = [ net.DequeueRebatchingQueue([queue], 1, num_elements=5), ] with self.assertRaises(RuntimeError): workspace.RunNetOnce(net) def test_rebatching_queue_multiple_components(self): NUM_BLOBS = 4 NUM_ELEMENTS = 10 net = core.Net('net') workspace.blobs['complex_tensor'] = np.array( [[x, x + 1] for x in range(NUM_ELEMENTS)], dtype=np.int32 ) tensors = [ net.GivenTensorIntFill( [], 1, shape=[NUM_ELEMENTS], values=[x for x in range(NUM_ELEMENTS)] ), net.GivenTensorFill( [], 1, shape=[NUM_ELEMENTS], values=[x * 1.0 for x in range(NUM_ELEMENTS)] ), net.GivenTensorBoolFill( [], 1, shape=[NUM_ELEMENTS], values=[(x % 2 == 0) for x in range(NUM_ELEMENTS)] ), 'complex_tensor', ] queue = net.CreateRebatchingQueue( [], 1, capacity=10, num_blobs=NUM_BLOBS ) net.EnqueueRebatchingQueue([queue] + tensors, [], enqueue_batch=True) results = net.DequeueRebatchingQueue([queue], NUM_BLOBS, num_elements=5) workspace.RunNetOnce(net) for idx in range(NUM_BLOBS): npt.assert_array_equal( workspace.FetchBlob(results[idx]), workspace.FetchBlob(tensors[idx])[:5] ) @given( num_producers=st.integers(1, 5), num_consumers=st.integers(1, 5), producer_input_size=st.integers(1, 10), producer_num_iterations=st.integers(1, 10), capacity=st.integers(1, 10) ) def test_rebatching_parallel_producer_consumer( self, num_producers, num_consumers, producer_input_size, producer_num_iterations, capacity ): ### Init ### total_inputs = producer_num_iterations * producer_input_size * num_producers inputs = [] init_net = core.Net('init_net') queue = init_net.CreateRebatchingQueue( [], 1, capacity=capacity, num_blobs=1 ) ### Producers ### producer_steps = [] for i in range(num_producers): name = 'producer_%d' % i net = core.Net(name) values = [ producer_input_size * i + x for x in range(producer_input_size) ] for _ in range(producer_num_iterations): inputs.extend(values) tensors = net.GivenTensorIntFill( [], 1, shape=[producer_input_size], values=values ) net.EnqueueRebatchingQueue([queue, tensors], [], enqueue_batch=True) step = core.execution_step( name, net, num_iter=producer_num_iterations ) producer_steps.append(step) producer_step = core.execution_step( 'producer', [ core.execution_step( 'producers', producer_steps, concurrent_substeps=True ) ] ) ### Consumers ### outputs = [] def append(ins, outs): # Extend is atomic outputs.extend(ins[0].data.tolist()) consumer_steps = [] for i in range(num_consumers): # This is just a way of deterministally read all the elements. # We make `num_consumers` almost equal splits # (the reminder goes to the last consumer). num_elements_to_read = total_inputs // num_consumers if i == num_consumers - 1: num_elements_to_read = num_elements_to_read \ + total_inputs % num_consumers # If we have nothing to read this consumer will be idle if (num_elements_to_read == 0): continue # Now we have to make a split on number of iterations and the read # size for each iteration. This is again just one of many # deterministic ways of doing it. We factorize the total number of # elements we have to read and assign half of the factors to the # iterations half to the read size. factors = list(primefac(num_elements_to_read)) num_elements_per_iteration = functools.reduce( lambda x, y: x * y, factors[len(factors) // 2:], 1 ) num_iterations = functools.reduce( lambda x, y: x * y, factors[:len(factors) // 2], 1 ) name = 'consumer_%d' % i net = core.Net(name) blobs = net.DequeueRebatchingQueue( [queue], 1, num_elements=num_elements_per_iteration ) net.Python(append)([blobs], 0) consumer_steps.append( core.execution_step(name, net, num_iter=num_iterations) ) consumer_step = core.execution_step( 'consumer', consumer_steps, concurrent_substeps=True ) init_step = core.execution_step('init', init_net) worker_step = core.execution_step( 'worker', [consumer_step, producer_step], concurrent_substeps=True ) ### Execute Plan ### plan = core.Plan('test') plan.AddStep(init_step) plan.AddStep(worker_step) self.ws.run(plan) ### Check Results ### # We check that the outputs are a permutation of inputs inputs.sort() outputs.sort() self.assertEquals(inputs, outputs) 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 unittest class TestSoftplus(hu.HypothesisTestCase): @given(X=hu.tensor(), **hu.gcs) def test_softplus(self, X, gc, dc): op = core.CreateOperator("Softplus", ["X"], ["Y"]) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=0.0005) 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 TestReductionOps(hu.HypothesisTestCase): @given(n=st.integers(5, 8), **hu.gcs) def test_elementwise_sum(self, n, gc, dc): X = np.random.rand(n).astype(np.float32) def sum_op(X): return [np.sum(X)] op = core.CreateOperator( "SumElements", ["X"], ["y"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X], reference=sum_op, ) self.assertGradientChecks( device_option=gc, op=op, inputs=[X], outputs_to_check=0, outputs_with_grads=[0], ) @given(n=st.integers(5, 8), **hu.gcs) def test_elementwise_sqrsum(self, n, gc, dc): X = np.random.rand(n).astype(np.float32) def sumsqr_op(X): return [np.sum(X * X)] op = core.CreateOperator( "SumSqrElements", ["X"], ["y"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X], reference=sumsqr_op, ) @given(n=st.integers(5, 8), **hu.gcs) def test_elementwise_avg(self, n, gc, dc): X = np.random.rand(n).astype(np.float32) def avg_op(X): return [np.mean(X)] op = core.CreateOperator( "SumElements", ["X"], ["y"], average=1 ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X], reference=avg_op, ) self.assertGradientChecks( device_option=gc, op=op, inputs=[X], outputs_to_check=0, outputs_with_grads=[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 from caffe2.python import core, workspace import caffe2.python.hypothesis_test_util as hu import unittest class TestSpatialBN(hu.HypothesisTestCase): @given(size=st.integers(7, 10), input_channels=st.integers(1, 10), batch_size=st.integers(1, 3), seed=st.integers(0, 65535), order=st.sampled_from(["NCHW", "NHWC"]), epsilon=st.floats(min_value=1e-5, max_value=1e-2), **hu.gcs) def test_spatialbn_test_mode_3d( self, size, input_channels, batch_size, seed, order, epsilon, gc, dc): op = core.CreateOperator( "SpatialBN", ["X", "scale", "bias", "mean", "var"], ["Y"], order=order, is_test=True, epsilon=epsilon, engine="CUDNN", ) def reference_spatialbn_test(X, scale, bias, mean, var): if order == "NCHW": scale = scale[np.newaxis, :, np.newaxis, np.newaxis, np.newaxis] bias = bias[np.newaxis, :, np.newaxis, np.newaxis, np.newaxis] mean = mean[np.newaxis, :, np.newaxis, np.newaxis, np.newaxis] var = var[np.newaxis, :, np.newaxis, np.newaxis, np.newaxis] return ((X - mean) / np.sqrt(var + epsilon) * scale + bias,) np.random.seed(1701) scale = np.random.rand(input_channels).astype(np.float32) + 0.5 bias = np.random.rand(input_channels).astype(np.float32) - 0.5 mean = np.random.randn(input_channels).astype(np.float32) var = np.random.rand(input_channels).astype(np.float32) + 0.5 X = np.random.rand(batch_size, input_channels, size, size, size)\ .astype(np.float32) - 0.5 if order == "NHWC": X = X.transpose(0, 2, 3, 4, 1) self.assertReferenceChecks(gc, op, [X, scale, bias, mean, var], reference_spatialbn_test) self.assertDeviceChecks(dc, op, [X, scale, bias, mean, var], [0]) @unittest.skipIf(not workspace.has_gpu_support, "No gpu support") @given(size=st.integers(7, 10), input_channels=st.integers(1, 10), batch_size=st.integers(1, 3), seed=st.integers(0, 65535), order=st.sampled_from(["NCHW", "NHWC"]), epsilon=st.floats(min_value=1e-5, max_value=1e-2), **hu.gcs) def test_spatialbn_test_mode_1d( self, size, input_channels, batch_size, seed, order, epsilon, gc, dc): op = core.CreateOperator( "SpatialBN", ["X", "scale", "bias", "mean", "var"], ["Y"], order=order, is_test=True, epsilon=epsilon, engine="CUDNN", ) def reference_spatialbn_test(X, scale, bias, mean, var): if order == "NCHW": scale = scale[np.newaxis, :, np.newaxis] bias = bias[np.newaxis, :, np.newaxis] mean = mean[np.newaxis, :, np.newaxis] var = var[np.newaxis, :, np.newaxis] return ((X - mean) / np.sqrt(var + epsilon) * scale + bias,) np.random.seed(1701) scale = np.random.rand(input_channels).astype(np.float32) + 0.5 bias = np.random.rand(input_channels).astype(np.float32) - 0.5 mean = np.random.randn(input_channels).astype(np.float32) var = np.random.rand(input_channels).astype(np.float32) + 0.5 X = np.random.rand( batch_size, input_channels, size).astype(np.float32) - 0.5 if order == "NHWC": X = X.swapaxes(1, 2) self.assertReferenceChecks(gc, op, [X, scale, bias, mean, var], reference_spatialbn_test) @given(size=st.integers(7, 10), input_channels=st.integers(1, 10), batch_size=st.integers(1, 3), seed=st.integers(0, 65535), order=st.sampled_from(["NCHW", "NHWC"]), epsilon=st.floats(min_value=1e-5, max_value=1e-2), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_spatialbn_test_mode( self, size, input_channels, batch_size, seed, order, epsilon, engine, gc, dc): op = core.CreateOperator( "SpatialBN", ["X", "scale", "bias", "mean", "var"], ["Y"], order=order, is_test=True, epsilon=epsilon, engine=engine ) def reference_spatialbn_test(X, scale, bias, mean, var): if order == "NCHW": scale = scale[np.newaxis, :, np.newaxis, np.newaxis] bias = bias[np.newaxis, :, np.newaxis, np.newaxis] mean = mean[np.newaxis, :, np.newaxis, np.newaxis] var = var[np.newaxis, :, np.newaxis, np.newaxis] return ((X - mean) / np.sqrt(var + epsilon) * scale + bias,) np.random.seed(1701) scale = np.random.rand(input_channels).astype(np.float32) + 0.5 bias = np.random.rand(input_channels).astype(np.float32) - 0.5 mean = np.random.randn(input_channels).astype(np.float32) var = np.random.rand(input_channels).astype(np.float32) + 0.5 X = np.random.rand( batch_size, input_channels, size, size).astype(np.float32) - 0.5 if order == "NHWC": X = X.swapaxes(1, 2).swapaxes(2, 3) self.assertReferenceChecks(gc, op, [X, scale, bias, mean, var], reference_spatialbn_test) self.assertDeviceChecks(dc, op, [X, scale, bias, mean, var], [0]) @given(size=st.integers(7, 10), input_channels=st.integers(1, 10), batch_size=st.integers(1, 3), seed=st.integers(0, 65535), order=st.sampled_from(["NCHW", "NHWC"]), epsilon=st.floats(1e-5, 1e-2), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_spatialbn_train_mode( self, size, input_channels, batch_size, seed, order, epsilon, engine, gc, dc): op = core.CreateOperator( "SpatialBN", ["X", "scale", "bias", "running_mean", "running_var"], ["Y", "running_mean", "running_var", "saved_mean", "saved_var"], order=order, is_test=False, epsilon=epsilon, engine=engine, ) np.random.seed(1701) scale = np.random.rand(input_channels).astype(np.float32) + 0.5 bias = np.random.rand(input_channels).astype(np.float32) - 0.5 mean = np.random.randn(input_channels).astype(np.float32) var = np.random.rand(input_channels).astype(np.float32) + 0.5 X = np.random.rand( batch_size, input_channels, size, size).astype(np.float32) - 0.5 if order == "NHWC": X = X.swapaxes(1, 2).swapaxes(2, 3) self.assertDeviceChecks(dc, op, [X, scale, bias, mean, var], [0, 1, 2, 3, 4]) @given(size=st.integers(7, 10), input_channels=st.integers(1, 10), batch_size=st.integers(1, 3), seed=st.integers(0, 65535), order=st.sampled_from(["NCHW", "NHWC"]), epsilon=st.floats(min_value=1e-5, max_value=1e-2), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_spatialbn_train_mode_gradient_check( self, size, input_channels, batch_size, seed, order, epsilon, engine, gc, dc): op = core.CreateOperator( "SpatialBN", ["X", "scale", "bias", "mean", "var"], ["Y", "mean", "var", "saved_mean", "saved_var"], order=order, is_test=False, epsilon=epsilon, engine=engine ) np.random.seed(seed) scale = np.random.rand(input_channels).astype(np.float32) + 0.5 bias = np.random.rand(input_channels).astype(np.float32) - 0.5 mean = np.random.randn(input_channels).astype(np.float32) var = np.random.rand(input_channels).astype(np.float32) + 0.5 X = np.random.rand( batch_size, input_channels, size, size).astype(np.float32) - 0.5 if order == "NHWC": X = X.swapaxes(1, 2).swapaxes(2, 3) for input_to_check in [0, 1, 2]: # dX, dScale, dBias self.assertGradientChecks(gc, op, [X, scale, bias, mean, var], input_to_check, [0]) @given(size=st.integers(7, 10), input_channels=st.integers(1, 10), batch_size=st.integers(1, 3), seed=st.integers(0, 65535), order=st.sampled_from(["NCHW", "NHWC"]), epsilon=st.floats(min_value=1e-5, max_value=1e-2), **hu.gcs) def test_spatialbn_train_mode_gradient_check_1d( self, size, input_channels, batch_size, seed, order, epsilon, gc, dc): op = core.CreateOperator( "SpatialBN", ["X", "scale", "bias", "mean", "var"], ["Y", "mean", "var", "saved_mean", "saved_var"], order=order, is_test=False, epsilon=epsilon, engine="CUDNN", ) np.random.seed(seed) scale = np.random.rand(input_channels).astype(np.float32) + 0.5 bias = np.random.rand(input_channels).astype(np.float32) - 0.5 mean = np.random.randn(input_channels).astype(np.float32) var = np.random.rand(input_channels).astype(np.float32) + 0.5 X = np.random.rand( batch_size, input_channels, size).astype(np.float32) - 0.5 if order == "NHWC": X = X.swapaxes(1, 2) for input_to_check in [0, 1, 2]: # dX, dScale, dBias self.assertGradientChecks(gc, op, [X, scale, bias, mean, var], input_to_check, [0], stepsize=0.01) 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 scipy.sparse import coo_matrix from hypothesis import given import hypothesis.strategies as st from caffe2.python import core import caffe2.python.hypothesis_test_util as hu class TestSparseGradient(hu.HypothesisTestCase): @given(M=st.integers(min_value=5, max_value=20), N=st.integers(min_value=5, max_value=20), K=st.integers(min_value=5, max_value=15), sparsity=st.floats(min_value=0.1, max_value=1.0), **hu.gcs_cpu_only) def test_sparse_gradient(self, M, N, K, sparsity, gc, dc): X = np.random.randn(M, K).astype(np.float32) X[X > sparsity] = 0 X_coo = coo_matrix(X) val, key, seg = X_coo.data, X_coo.col, X_coo.row val = val.astype(np.float32) key = key.astype(np.int64) seg = seg.astype(np.int32) Y = np.random.randn(K, N).astype(np.float32) op = core.CreateOperator( 'SparseUnsortedSegmentWeightedSum', ['Y', 'val', 'key', 'seg'], ['out'], num_segments=M) # Gradient check wrt Y self.assertGradientChecks( gc, op, [Y, val, key, seg], 0, [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, assume import hypothesis.strategies as st from itertools import izip from caffe2.python import core, model_helper, brew import caffe2.python.hypothesis_test_util as hu class TestInstanceNorm(hu.HypothesisTestCase): def _get_inputs(self, N, C, H, W, order): if order == 'NCHW': input_data = np.random.rand(N, C, H, W).astype(np.float32) elif order == 'NHWC': # Allocate in the same order as NCHW and transpose to make sure # the inputs are identical on freshly-seeded calls. input_data = np.random.rand(N, C, H, W).astype(np.float32) input_data = np.transpose(input_data, axes=(0, 2, 3, 1)) else: raise Exception('unknown order type ({})'.format(order)) scale_data = np.random.rand(C).astype(np.float32) bias_data = np.random.rand(C).astype(np.float32) return input_data, scale_data, bias_data def _get_op(self, device_option, store_mean, store_inv_stdev, epsilon, order, inplace=False): outputs = ['output' if not inplace else "input"] if store_mean or store_inv_stdev: outputs += ['mean'] if store_inv_stdev: outputs += ['inv_stdev'] op = core.CreateOperator( 'InstanceNorm', ['input', 'scale', 'bias'], outputs, order=order, epsilon=epsilon, device_option=device_option) return op def _feed_inputs(self, input_blobs, device_option): names = ['input', 'scale', 'bias'] for name, blob in izip(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), order=st.sampled_from(['NCHW', 'NHWC']), epsilon=st.floats(1e-6, 1e-4), store_mean=st.booleans(), seed=st.integers(0, 1000), store_inv_stdev=st.booleans()) def test_instance_norm_gradients( self, gc, dc, N, C, H, W, order, store_mean, store_inv_stdev, epsilon, seed): np.random.seed(seed) # force store_inv_stdev if store_mean to match existing forward pass # implementation store_inv_stdev |= store_mean op = self._get_op( device_option=gc, store_mean=store_mean, store_inv_stdev=store_inv_stdev, epsilon=epsilon, order=order) input_blobs = self._get_inputs(N, C, H, W, order) output_indices = [0] # if store_inv_stdev is turned on, store_mean must also be forced on if store_mean or store_inv_stdev: output_indices += [1] if store_inv_stdev: output_indices += [2] self.assertDeviceChecks(dc, op, input_blobs, output_indices) # The gradient only flows from output #0 since the other two only # store the temporary mean and inv_stdev buffers. # Check dl/dinput self.assertGradientChecks(gc, op, input_blobs, 0, [0], stepsize=0.005, threshold=0.01) # Check dl/dscale self.assertGradientChecks(gc, op, input_blobs, 1, [0]) # Check dl/dbias self.assertGradientChecks(gc, op, input_blobs, 2, [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), seed=st.integers(0, 1000), epsilon=st.floats(1e-6, 1e-4), store_mean=st.booleans(), store_inv_stdev=st.booleans()) def test_instance_norm_layout(self, gc, dc, N, C, H, W, store_mean, store_inv_stdev, epsilon, seed): # force store_inv_stdev if store_mean to match existing forward pass # implementation store_inv_stdev |= store_mean 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, store_mean=store_mean, store_inv_stdev=store_inv_stdev, epsilon=epsilon, 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']), epsilon=st.floats(1e-6, 1e-4), store_mean=st.booleans(), seed=st.integers(0, 1000), store_inv_stdev=st.booleans(), inplace=st.booleans()) def test_instance_norm_reference_check( self, gc, dc, N, C, H, W, order, store_mean, store_inv_stdev, epsilon, seed, inplace): np.random.seed(seed) # force store_inv_stdev if store_mean to match existing forward pass # implementation store_inv_stdev |= store_mean if order != "NCHW": assume(not inplace) inputs = self._get_inputs(N, C, H, W, order) op = self._get_op( device_option=gc, store_mean=store_mean, store_inv_stdev=store_inv_stdev, epsilon=epsilon, order=order, inplace=inplace) def ref(input_blob, scale_blob, bias_blob): if order == 'NHWC': input_blob = np.transpose(input_blob, axes=(0, 3, 1, 2)) mean_blob = input_blob.reshape((N, C, -1)).mean(axis=2) inv_stdev_blob = 1.0 / \ np.sqrt(input_blob.reshape((N, C, -1)).var(axis=2) + epsilon) # _bc indicates blobs that are reshaped for broadcast scale_bc = scale_blob[np.newaxis, :, np.newaxis, np.newaxis] mean_bc = mean_blob[:, :, np.newaxis, np.newaxis] inv_stdev_bc = inv_stdev_blob[:, :, np.newaxis, np.newaxis] bias_bc = bias_blob[np.newaxis, :, np.newaxis, np.newaxis] normalized_blob = scale_bc * (input_blob - mean_bc) * inv_stdev_bc \ + bias_bc if order == 'NHWC': normalized_blob = np.transpose( normalized_blob, axes=(0, 2, 3, 1)) if not store_mean and not store_inv_stdev: return normalized_blob, elif not store_inv_stdev: return normalized_blob, mean_blob else: return normalized_blob, mean_blob, inv_stdev_blob 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']), epsilon=st.floats(1e-6, 1e-4), store_mean=st.booleans(), seed=st.integers(0, 1000), store_inv_stdev=st.booleans()) def test_instance_norm_device_check( self, gc, dc, N, C, H, W, order, store_mean, store_inv_stdev, epsilon, seed): np.random.seed(seed) # force store_inv_stdev if store_mean to match existing forward pass # implementation store_inv_stdev |= store_mean inputs = self._get_inputs(N, C, H, W, order) op = self._get_op( device_option=gc, store_mean=store_mean, store_inv_stdev=store_inv_stdev, epsilon=epsilon, order=order) self.assertDeviceChecks(dc, op, inputs, [0]) @given(is_test=st.booleans(), 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']), epsilon=st.floats(1e-6, 1e-4), seed=st.integers(0, 1000)) def test_instance_norm_model_helper_helper(self, N, C, H, W, order, epsilon, seed, is_test): np.random.seed(seed) model = model_helper.ModelHelper(name="test_model") brew.instance_norm( model, 'input', 'output', C, epsilon=epsilon, is_test=is_test) 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() if is_test: scale = self.ws.blobs['output_s'].fetch() assert scale is not None assert scale.shape == (C, ) bias = self.ws.blobs['output_b'].fetch() assert bias is not None assert bias.shape == (C, ) 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 caffe2.python import core, workspace from caffe2.python.test_util import TestCase import numpy as np lengths = [[0], [1, 2], [1, 0, 2, 0]] features1 = [[], [1, 2, 2], [[1, 1], [2, 2], [2, 2]] ] features2 = [[], [2, 4, 4], [[2, 2], [4, 4], [4, 4]] ] lengths_exp = [[1], [1, 2], [1, 1, 2, 1]] features1_exp = [[0], [1, 2, 2], [[1, 1], [0, 0], [2, 2], [2, 2], [0, 0]]] features2_exp = [[0], [2, 4, 4], [[2, 2], [0, 0], [4, 4], [4, 4], [0, 0]]] class TestEmptySampleOps(TestCase): def test_emptysample(self): for i in range(0, 3): PadEmptyTest = core.CreateOperator( 'PadEmptySamples', ['lengths', 'features1', 'features2'], ['out_lengths', 'out_features1', 'out_features2'], ) workspace.FeedBlob( 'lengths', np.array(lengths[i], dtype=np.int32)) workspace.FeedBlob( 'features1', np.array(features1[i], dtype=np.int64)) workspace.FeedBlob( 'features2', np.array(features2[i], dtype=np.int64)) workspace.RunOperatorOnce(PadEmptyTest) np.testing.assert_allclose( lengths_exp[i], workspace.FetchBlob('out_lengths'), atol=1e-4, rtol=1e-4, err_msg='Mismatch in lengths') np.testing.assert_allclose( features1_exp[i], workspace.FetchBlob('out_features1'), atol=1e-4, rtol=1e-4, err_msg='Mismatch in features1') np.testing.assert_allclose( features2_exp[i], workspace.FetchBlob('out_features2'), atol=1e-4, rtol=1e-4, err_msg='Mismatch in features2') 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 given import numpy as np import unittest from caffe2.proto import caffe2_pb2, hsm_pb2 from caffe2.python import workspace, core, gradient_checker import caffe2.python.hypothesis_test_util as hu import caffe2.python.hsm_util as hsmu # User inputs tree using protobuf file or, in this case, python utils # The hierarchy in this test looks as shown below. Note that the final subtrees # (with word_ids as leaves) have been collapsed for visualization # * # / \ # * 5,6,7,8 # / \ # 0,1,2 3,4 tree = hsm_pb2.TreeProto() words = [[0, 1, 2], [3, 4], [5, 6, 7, 8]] node1 = hsmu.create_node_with_words(words[0], "node1") node2 = hsmu.create_node_with_words(words[1], "node2") node3 = hsmu.create_node_with_words(words[2], "node3") node4 = hsmu.create_node_with_nodes([node1, node2], "node4") node = hsmu.create_node_with_nodes([node4, node3], "node5") tree.root_node.MergeFrom(node) # structure: # node5: [0, 2, ["node4", "node3"]] # offset, length, "node4, node3" # node4: [2, 2, ["node1", "node2"]] # node1: [4, 3, [0, 1 ,2]] # node2: [7, 2, [3, 4] # node3: [9, 4, [5, 6, 7, 8] struct = [[0, 2, ["node4", "node3"], "node5"], [2, 2, ["node1", "node2"], "node4"], [4, 3, [0, 1, 2], "node1"], [7, 2, [3, 4], "node2"], [9, 4, [5, 6, 7, 8], "node3"]] # Internal util to translate input tree to list of (word_id,path). serialized # hierarchy is passed into the operator_def as a string argument, hierarchy_proto = hsmu.create_hierarchy(tree) arg = caffe2_pb2.Argument() arg.name = "hierarchy" arg.s = hierarchy_proto.SerializeToString() beam = 5 args_search = [] arg_search = caffe2_pb2.Argument() arg_search.name = "tree" arg_search.s = tree.SerializeToString() args_search.append(arg_search) arg_search = caffe2_pb2.Argument() arg_search.name = "beam" arg_search.f = beam args_search.append(arg_search) class TestHsm(hu.HypothesisTestCase): def test_hsm_search(self): samples = 10 dim_in = 5 X = np.random.rand(samples, dim_in).astype(np.float32) - 0.5 w = np.random.rand(hierarchy_proto.size, dim_in) \ .astype(np.float32) - 0.5 b = np.random.rand(hierarchy_proto.size).astype(np.float32) - 0.5 labels = np.array([np.random.randint(0, 8) for i in range(samples)]) \ .astype(np.int32) workspace.GlobalInit(['caffe2']) workspace.FeedBlob("data", X) workspace.FeedBlob("weights", w) workspace.FeedBlob("bias", b) workspace.FeedBlob("labels", labels) op = core.CreateOperator( 'HSoftmaxSearch', ['data', 'weights', 'bias'], ['names', 'scores'], 'HSoftmaxSearch', arg=args_search) workspace.RunOperatorOnce(op) names = workspace.FetchBlob('names') scores = workspace.FetchBlob('scores') def simulation_hsm_search(): names = [] scores = [] for line in struct: s, e = line[0], line[0] + line[1] score = np.dot(X, w[s:e].transpose()) + b[s:e] score = np.exp(score - np.max(score, axis=1, keepdims=True)) score /= score.sum(axis=1, keepdims=True) score = -np.log(score) score = score.transpose() idx = -1 for j, n in enumerate(names): if n == line[3]: idx = j score += scores[j] if idx == -1: score[score > beam] = np.inf else: score[score - scores[idx] > beam] = np.inf for i, name in enumerate(line[2]): scores.append(score[i]) names.append(name) scores = np.vstack(scores) return names, scores.transpose() p_names, p_scores = simulation_hsm_search() idx = np.argsort(p_scores, axis=1) p_scores = np.sort(p_scores, axis=1) p_names = np.array(p_names)[idx] for i in range(names.shape[0]): for j in range(names.shape[1]): if names[i][j]: assert(names[i][j] == p_names[i][j]) self.assertAlmostEqual( scores[i][j], p_scores[i][j], delta=0.001) def test_hsm_run_once(self): workspace.GlobalInit(['caffe2']) workspace.FeedBlob("data", np.random.randn(1000, 100).astype(np.float32)) workspace.FeedBlob("weights", np.random.randn(1000, 100).astype(np.float32)) workspace.FeedBlob("bias", np.random.randn(1000).astype(np.float32)) workspace.FeedBlob("labels", np.random.rand(1000).astype(np.int32) * 9) op = core.CreateOperator( 'HSoftmax', ['data', 'weights', 'bias', 'labels'], ['output', 'intermediate_output'], 'HSoftmax', arg=[arg]) self.assertTrue(workspace.RunOperatorOnce(op)) # Test to check value of sum of squared losses in forward pass for given # input def test_hsm_forward(self): cpu_device_option = caffe2_pb2.DeviceOption() grad_checker = gradient_checker.GradientChecker( 0.01, 0.05, cpu_device_option, "default") samples = 9 dim_in = 5 X = np.zeros((samples, dim_in)).astype(np.float32) + 1 w = np.zeros((hierarchy_proto.size, dim_in)).astype(np.float32) + 1 b = np.array([i for i in range(hierarchy_proto.size)])\ .astype(np.float32) labels = np.array([i for i in range(samples)]).astype(np.int32) workspace.GlobalInit(['caffe2']) workspace.FeedBlob("data", X) workspace.FeedBlob("weights", w) workspace.FeedBlob("bias", b) workspace.FeedBlob("labels", labels) op = core.CreateOperator( 'HSoftmax', ['data', 'weights', 'bias', 'labels'], ['output', 'intermediate_output'], 'HSoftmax', arg=[arg]) grad_ops, g_input = core.GradientRegistry.GetGradientForOp( op, [s + '_grad' for s in op.output]) loss, _ = grad_checker.GetLossAndGrad( op, grad_ops, X, op.input[0], g_input[0], [0] ) self.assertAlmostEqual(loss, 44.269, delta=0.001) # Test to compare gradient calculated using the gradient operator and the # symmetric derivative calculated using Euler Method # TODO : convert to both cpu and gpu test when ready. @given(**hu.gcs_cpu_only) def test_hsm_gradient(self, gc, dc): samples = 10 dim_in = 5 X = np.random.rand(samples, dim_in).astype(np.float32) - 0.5 w = np.random.rand(hierarchy_proto.size, dim_in) \ .astype(np.float32) - 0.5 b = np.random.rand(hierarchy_proto.size).astype(np.float32) - 0.5 labels = np.array([np.random.randint(0, 8) for i in range(samples)]) \ .astype(np.int32) workspace.GlobalInit(['caffe2']) workspace.FeedBlob("data", X) workspace.FeedBlob("weights", w) workspace.FeedBlob("bias", b) workspace.FeedBlob("labels", labels) op = core.CreateOperator( 'HSoftmax', ['data', 'weights', 'bias', 'labels'], ['output', 'intermediate_output'], 'HSoftmax', arg=[arg]) self.assertDeviceChecks(dc, op, [X, w, b, labels], [0]) for i in range(3): self.assertGradientChecks(gc, op, [X, w, b, labels], i, [0]) def test_huffman_tree_hierarchy(self): workspace.GlobalInit(['caffe2']) labelSet = range(0, 6) counts = [1, 2, 3, 4, 5, 6] labels = sum([[l] * c for (l, c) in zip(labelSet, counts)], []) Y = np.array(labels).astype(np.int64) workspace.FeedBlob("labels", Y) arg = caffe2_pb2.Argument() arg.name = 'num_classes' arg.i = 6 op = core.CreateOperator( 'HuffmanTreeHierarchy', ['labels'], ['huffman_tree'], 'HuffmanTreeHierarchy', arg=[arg]) workspace.RunOperatorOnce(op) huffmanTreeOutput = workspace.FetchBlob('huffman_tree') treeOutput = hsm_pb2.TreeProto() treeOutput.ParseFromString(huffmanTreeOutput[0]) treePathOutput = hsmu.create_hierarchy(treeOutput) label_to_path = {} for path in treePathOutput.paths: label_to_path[path.word_id] = path def checkPath(label, indices, code): path = label_to_path[label] self.assertEqual(len(path.path_nodes), len(code)) self.assertEqual(len(path.path_nodes), len(code)) for path_node, index, target in \ zip(path.path_nodes, indices, code): self.assertEqual(path_node.index, index) self.assertEqual(path_node.target, target) checkPath(0, [0, 4, 6, 8], [1, 0, 0, 0]) checkPath(1, [0, 4, 6, 8], [1, 0, 0, 1]) checkPath(2, [0, 4, 6], [1, 0, 1]) checkPath(3, [0, 2], [0, 0]) checkPath(4, [0, 2], [0, 1]) checkPath(5, [0, 4], [1, 1]) 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 TestReduceFrontSum(hu.HypothesisTestCase): def reduce_op_test(self, op_name, op_ref, in_data, num_reduce_dims, device): op = core.CreateOperator( op_name, ["inputs"], ["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(1, 3), **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, num_reduce_dim, gc) @given(num_reduce_dim=st.integers(1, 3), **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, num_reduce_dim, gc) @given(num_reduce_dim=st.integers(1, 3), **hu.gcs) def test_reduce_back_sum(self, num_reduce_dim, dc, gc): 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, num_reduce_dim, gc) @given(num_reduce_dim=st.integers(1, 3), **hu.gcs) def test_reduce_back_mean(self, num_reduce_dim, dc, gc): num_reduce_dim = 2 X = np.random.rand(6, 7, 8, 2).astype(np.float32) def ref_sum(X): return [np.mean(X, axis=(0, 1, 2, 3)[4 - num_reduce_dim:])] self.reduce_op_test("ReduceBackMean", ref_sum, X, 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 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), **hu.gcs) def test_momentum_sgd(self, n, 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): adjgrad = lr * grad + momentum * param_momentum if param is None: return [adjgrad, adjgrad] else: paramup = param - adjgrad return [adjgrad, adjgrad, paramup] op = core.CreateOperator( "MomentumSGDUpdate", ["grad", "param_momentum", "lr", "param"], ["grad", "param_momentum", "param"], momentum=momentum, nesterov=0, ) 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=0, ) 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(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] # 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) 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 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 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 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 _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( 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)) def test_one_hot(self, hot_indices, end_padding): 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( hu.cpu_do, op, [hot_indices, size], one_hot_ref) @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, workspace import caffe2.python.hypothesis_test_util as hu from hypothesis import given import numpy as np class TestTensorPackOps(hu.HypothesisTestCase): @given(**hu.gcs) def test_pack_ops(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']) print(gc, dc) 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)) return [arr] workspace.FeedBlob('l', lengths) workspace.FeedBlob('d', data) inputs = [lengths, data] self.assertReferenceChecks( device_option=gc, op=op, inputs=inputs, reference=pack_segments_ref, ) workspace.FeedBlob('l', lengths) workspace.FeedBlob('d', data) workspace.RunOperatorOnce(core.CreateOperator( 'PackSegments', ['l', 'd'], ['t'])) workspace.RunOperatorOnce(core.CreateOperator( 'UnpackSegments', ['l', 't'], ['newd'])) assert((workspace.FetchBlob('newd') == workspace.FetchBlob('d')).all()) 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'])) workspace.RunOperatorOnce(core.CreateOperator( 'UnpackSegments', ['l', 't'], ['newd'])) 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.0], [2.0, 2.0], [2.0, 2.0], [3.0, 3.0], [3.0, 3.0], [3.0, 3.0]], 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) 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, 5), m=st.integers(1, 5), k=st.integers(1, 5), **hu.gcs) def test_fc(self, n, m, k, gc, dc): 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 def fc_op(X, W, b): return [np.dot(X, W.transpose()) + b] op = core.CreateOperator( 'FC', ['X', 'W', 'b'], 'out' ) # Check against numpy reference self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, W, b], reference=fc_op, ) # Check over multiple devices self.assertDeviceChecks(dc, op, [X, W, b], [0]) # Gradient check wrt X self.assertGradientChecks(gc, op, [X, W, b], 0, [0]) # Gradient check wrt W self.assertGradientChecks(gc, op, [X, W, b], 1, [0]) # Gradient check wrt b self.assertGradientChecks(gc, op, [X, W, b], 2, [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 collections import OrderedDict import numpy as np import random from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import caffe2.python.mkl_test_util as mu class TestTopK(hu.HypothesisTestCase): @given(X=hu.tensor(), **mu.gcs) def test_top_k(self, X, gc, dc): X = X.astype(dtype=np.float32) k = random.randint(1, X.shape[-1]) op = core.CreateOperator( "TopK", ["X"], ["Values", "Indices"], k=k, device_option=gc ) def top_k_ref(X): X_flat = X.reshape((-1, X.shape[-1])) indices_ref = np.ndarray(shape=X_flat.shape, dtype=np.int32) values_ref = np.ndarray(shape=X_flat.shape, dtype=np.float32) 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) j = 0 for val, idxs in sorted(od.items(), reverse=True): for idx in idxs: indices_ref[i, j] = idx values_ref[i, j] = val j = j + 1 indices_ref = np.reshape(indices_ref, X.shape) values_ref = np.reshape(values_ref, X.shape) indices_ref = indices_ref.take(range(k), axis=-1) values_ref = values_ref.take(range(k), axis=-1) return (values_ref, indices_ref) self.assertReferenceChecks(hu.cpu_do, op, [X], top_k_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.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 import os 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 = zip(*col_data) txt_file = tempfile.NamedTemporaryFile(delete=False) txt_file.write( '\n'.join(['\t'.join(map(str, f)) for f in row_data]) + '\n') txt_file.close() 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]) os.remove(txt_file.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, workspace from caffe2.python.test_util import TestCase import numpy as np class TestCounterOps(TestCase): def test_stats_ops(self): workspace.FeedBlob('k', np.array(['k0', 'k1'], dtype=str)) workspace.FeedBlob('v', np.array([34, 45], dtype=np.int64)) for _ in range(2): workspace.RunOperatorOnce(core.CreateOperator( 'StatRegistryUpdate', ['k', 'v'], [])) workspace.RunOperatorOnce(core.CreateOperator( 'StatRegistryExport', [], ['k2', 'v2', 'ts'])) workspace.RunOperatorOnce(core.CreateOperator( 'StatRegistryCreate', [], ['reg'])) workspace.RunOperatorOnce(core.CreateOperator( 'StatRegistryUpdate', ['k2', 'v2', 'reg'], [])) workspace.RunOperatorOnce(core.CreateOperator( 'StatRegistryExport', ['reg'], ['k3', 'v3', 'ts'])) self.assertTrue(len(workspace.FetchBlob('k3')) == 2) self.assertTrue(len(workspace.FetchBlob('v3')) == 2)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from hypothesis import given import numpy as np 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]) @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]) @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]) @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) self.assertDeviceChecks(dc, op, [X, Y], [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 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) 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 element 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=map(all_inputs.index, 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=map( all_inputs.index, initial_recurrent_states, ), link_internal=map( str, [input_state_t_prev, input_state_t, 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=str(step_model.net.Proto()), backward_step_net='', 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 import functools from hypothesis import given, 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): mom_out = mom_in + 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)) @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_sparse_adagrad(self, inputs, lr, epsilon, gc, dc): param, momentum, grad = inputs indices = np.arange(grad.shape[0]) indices = indices[indices % 2 == 0] grad = grad[indices] momentum = np.abs(momentum) lr = np.array([lr], dtype=np.float32) 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) for i, index in enumerate(indices): param_out[index], momentum_out[index] = self.ref_adagrad( param[index], momentum[index], grad[i], lr, epsilon) return (param_out, momentum_out) self.assertReferenceChecks( gc, op, [param, momentum, indices, grad, lr], ref_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 import numpy as np from caffe2.python import core, workspace from caffe2.python.test_util import TestCase from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st class TestGatherOps(hu.HypothesisTestCase): @given(rows_num=st.integers(1, 10000), index_num=st.integers(1, 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,1)).astype('int32') op = core.CreateOperator( 'Gather', ['data', 'ind'], ['output']) def ref_gather(data, ind): output = [r for r in [data[i] for i in ind]] return [output] self.assertReferenceChecks( gc, op=op, inputs=[data, ind], reference=ref_gather, ) 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 import collections from caffe2.python import core, workspace import caffe2.python.hypothesis_test_util as hu class TestConvolution(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(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, 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( "Conv", ["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(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, 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( "Conv", ["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(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, stride, pad, kernel, dilation, size, input_channels, output_channels, batch_size, order, engine, use_bias, gc, dc): dkernel = dilation * (kernel - 1) + 1 # cuDNN v6+ supports dilated convolutions if (workspace.GetCuDNNVersion() < 6000): assume("" == engine or 1 == dilation) assume(engine != "MKLDNN" or use_bias is True) op = core.CreateOperator( "Conv", ["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 op = core.CreateOperator( "Conv", ["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(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, 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( "Conv", ["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(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, 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"]: cudnn_v6p = workspace.GetCuDNNVersion() >= 6000 dilated_conv = dilation > 1 dilated_conv_nchw = (dilated_conv and order == "NCHW") # cuDNN v6+ supports dilated convolutions only for NCHW engine_list = ["", "CUDNN"] \ if (not dilated_conv) or (cudnn_v6p and dilated_conv_nchw) \ else [""] for engine in engine_list: op = core.CreateOperator( "Conv", ["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): from caffe2.python.model_helper import ModelHelper from caffe2.python import brew m = ModelHelper(name="test_model") n = 1 d = 2 depth = 3 iters = 5 h = 5 w = 5 workspace.ResetWorkspace() 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, 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), 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) 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) 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) 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) 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) 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) 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 caffe2.python import core from hypothesis import given from hypothesis import strategies as st import caffe2.python.hypothesis_test_util as hu import unittest class TestPowOp(hu.HypothesisTestCase): @given(X=hu.tensor(), exponent=st.floats(min_value=2.0, max_value=3.0), **hu.gcs) def test_elementwise_power(self, X, exponent, gc, dc): def powf(X): return (X ** exponent,) def powf_grad(g_out, outputs, fwd_inputs): return (exponent * (fwd_inputs[0] ** (exponent - 1)) * g_out,) op = core.CreateOperator( "Pow", ["X"], ["Y"], exponent=exponent) self.assertReferenceChecks(gc, op, [X], powf, output_to_grad="Y", grad_reference=powf_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 from caffe2.python import core from functools import partial from hypothesis import given import caffe2.python.hypothesis_test_util as hu import numpy as np 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, **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_cpu_only) def test_segment_ops(self, X, gc, dc): 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 ) 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] 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 if out == flat_inputs[idx]: flat_grad_in[idx] = out_grad break 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), ] 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_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=10, allow_empty=True ), REFERENCES_ALL )(self) def test_sparse_lengths_ops(self): LengthsTester()._test( 'SparseLengths', hu.sparse_lengths_tensor( dtype=np.float32, min_value=1, max_value=10, allow_empty=True ), REFERENCES_ALL )(self) @given(**hu.gcs) def test_lengths_sum_gpu(self, gc, dc): X = np.random.rand(50, 3, 4, 5).astype(np.float32) Y = np.asarray([20, 20, 10]).astype(np.int32) op = core.CreateOperator("LengthsSum", ["X", "Y"], "out") self.assertDeviceChecks(dc, op, [X, Y], [0]) self.assertGradientChecks(gc, op, [X, Y], 0, [0]) X = np.random.rand(3, 64).astype(np.float32) Y = np.asarray([20, 20, 10]).astype(np.int32) op = core.CreateOperator("LengthsSumGradient", ["X", "Y"], "out") self.assertDeviceChecks(dc, op, [X, Y], [0]) @given(**hu.gcs) def test_sparse_lengths_sum_gpu(self, gc, dc): X = np.random.rand(50, 3, 4, 5).astype(np.float32) Y = np.random.randint(0, 50, size=10).astype(np.int64) Z = np.asarray([4, 4, 2]).astype(np.int32) 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]) X = np.random.rand(3, 64).astype(np.float32) Y = np.asarray([20, 20, 10]).astype(np.int32) op = core.CreateOperator("SparseLengthsSumGradient", ["X", "Y"], "out") self.assertDeviceChecks(dc, op, [X, Y], [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 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 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 @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), **hu.gcs) def test_sparse_adam(self, inputs, ITER, LR, beta1, beta2, epsilon, gc, dc): param, mom1, mom2, grad = inputs mom1 = np.absolute(mom1) mom2 = np.absolute(mom2) ITER = np.array([ITER], dtype=np.int64) LR = np.array([LR], dtype=np.float32) indices = np.arange(grad.shape[0]) indices = indices[indices % 2 == 0] 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)
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 from caffe2.python.attention import AttentionType from caffe2.python.model_helper import ModelHelper import caffe2.python.hypothesis_test_util as hu from functools import partial from hypothesis import given from hypothesis import settings as ht_settings import hypothesis.strategies as st import numpy as np def sigmoid(x): return 1.0 / (1.0 + np.exp(-x)) def tanh(x): return 2.0 * sigmoid(2.0 * x) - 1 def lstm_unit(hidden_t_prev, cell_t_prev, gates, seq_lengths, timestep, forget_bias=0.0, drop_states=False): 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) seq_lengths = (np.ones(shape=(N, D)) * seq_lengths.reshape(N, 1)).astype(np.int32) assert seq_lengths.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) valid = (t < seq_lengths).astype(np.int32) 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 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=hidden_t_prev, cell_t_prev=cell_t_prev, gates=gates, seq_lengths=seq_lengths, timestep=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 lstm_with_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, ): encoder_outputs = np.transpose(encoder_outputs_transposed, axes=[2, 0, 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 = weighted_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 ) 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, 0) hidden[t + 1] = hidden_t cell[t + 1] = cell_t 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]) attention_logits_t = np.sum( attention_v * np.tanh(weighted_encoder_outputs + weighted_hidden_t), axis=2, ) 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]) ) 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_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, ): encoder_outputs = np.transpose(encoder_outputs_transposed, axes=[2, 0, 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 = weighted_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 ) 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, 0) hidden[t + 1] = hidden_t cell[t + 1] = cell_t 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]) attention_logits_t = np.sum( attention_v * np.tanh( weighted_encoder_outputs + weighted_hidden_t + weighted_prev_attention_context ), axis=2, ) 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]) ) 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 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, 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_lstm(t, n, d, create_lstm, outputs_with_grads, memory_optim, forget_bias, forward_only, drop_states): print("Dims: ", t, n, d) model = ModelHelper(name='external') input_blob, seq_lengths, hidden_init, cell_init = ( model.net.AddExternalInputs( 'input_blob', 'seq_lengths', 'hidden_init', 'cell_init')) create_lstm( model, input_blob, seq_lengths, (hidden_init, cell_init), d, d, scope="external/recurrent", outputs_with_grads=outputs_with_grads, memory_optimization=memory_optim, forget_bias=forget_bias, forward_only=forward_only, drop_states=drop_states, ) workspace.RunNetOnce(model.param_init_net) def generate_random_state(n, d): ndim = int(np.random.choice(3, 1)) + 1 if ndim == 1: return np.random.randn(1, n, d).astype(np.float32) random_state = np.random.randn(n, d).astype(np.float32) if ndim == 3: random_state = random_state.reshape([1, n, d]) return random_state workspace.FeedBlob("hidden_init", generate_random_state(n, d)) workspace.FeedBlob("cell_init", generate_random_state(n, d)) workspace.FeedBlob( "seq_lengths", np.random.randint(1, t + 1, size=(n,)).astype(np.int32) ) return model.net class RNNCellTest(hu.HypothesisTestCase): @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=5) 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 = _prepare_lstm( *input_tensor.shape, create_lstm=rnn_cell.layered_LSTM, outputs_with_grads=outputs_with_grads, memory_optim=memory_optim, **kwargs ) workspace.FeedBlob("input_blob", input_tensor) workspace.RunNetOnce(net) workspace.ResetWorkspace() @given( input_tensor=lstm_input(), forget_bias=st.floats(-10.0, 10.0), fwd_only=st.booleans(), drop_states=st.booleans(), ) @ht_settings(max_examples=15) def test_lstm_main(self, **kwargs): for lstm_type in [(rnn_cell.LSTM, lstm_reference), (rnn_cell.MILSTM, milstm_reference)]: for outputs_with_grads in [[0], [1], [0, 1, 2, 3]]: for memory_optim in [False, True]: self.lstm_base(lstm_type, outputs_with_grads=outputs_with_grads, memory_optim=memory_optim, **kwargs) def lstm_base(self, lstm_type, outputs_with_grads, memory_optim, input_tensor, forget_bias, fwd_only, drop_states): print("LSTM test parameters: ", locals()) 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_lstm(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, ) workspace.FeedBlob("external/recurrent/i2h", input_tensor) op = net._net.op[-1] inputs = [workspace.FetchBlob(name) for name in op.input] self.assertReferenceChecks( hu.cpu_do, op, inputs, ref, outputs_to_check=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, ) @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_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_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, ) 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, 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( 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) ) 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=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(n=st.integers(1, 10), d=st.integers(1, 10), t=st.integers(1, 10), **hu.gcs) def test_lstm_unit_recurrent_network(self, n, d, t, dc, gc): op = core.CreateOperator( 'LSTMUnit', [ 'hidden_t_prev', 'cell_t_prev', 'gates_t', 'seq_lengths', 'timestep', ], ['hidden_t', 'cell_t']) cell_t_prev = np.random.randn(1, n, d).astype(np.float32) hidden_t_prev = np.random.randn(1, n, d).astype(np.float32) gates = np.random.randn(1, n, 4 * d).astype(np.float32) seq_lengths = np.random.randint(1, t + 1, size=(n,)).astype(np.int32) timestep = np.random.randint(0, t, size=(1,)).astype(np.int32) inputs = [hidden_t_prev, cell_t_prev, gates, seq_lengths, timestep] input_device_options = {'timestep': hu.cpu_do} self.assertDeviceChecks( dc, op, inputs, [0], input_device_options=input_device_options) self.assertReferenceChecks( gc, op, inputs, lstm_unit, input_device_options=input_device_options) for i in range(2): self.assertGradientChecks( gc, op, inputs, i, [0, 1], input_device_options=input_device_options) @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('test/initial_hidden_state_{}'.format(i)), ) cell_input_list.append( workspace.FetchBlob('test/initial_cell_state_{}'.format(i)), ) i2h_w_list.append( workspace.FetchBlob('test/layer_{}/i2h_w'.format(i)), ) i2h_b_list.append( workspace.FetchBlob('test/layer_{}/i2h_b'.format(i)), ) gates_w_list.append( workspace.FetchBlob('test/layer_{}/gates_t_w'.format(i)), ) gates_b_list.append( workspace.FetchBlob('test/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, )
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) np.testing.assert_array_equal( np.concatenate((my_entries, new_entries)), 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(range(8), np.int32, 'IntIndexCreate') def test_long_index_ops(self): self._test_index_ops(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 TestGivenTensorFillOps(hu.HypothesisTestCase): @given(X=hu.tensor(min_dim=1, max_dim=4, dtype=np.int32), t=st.sampled_from([ (core.DataType.FLOAT, np.float32, "GivenTensorFill"), (core.DataType.INT32, np.int32, "GivenTensorIntFill"), (core.DataType.BOOL, np.bool_, "GivenTensorBoolFill"), ]), **hu.gcs_cpu_only) 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 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 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"]), method=st.sampled_from(["MaxPool", "AveragePool", "LpPool"]), **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, method, gc, dc): assume(np.max([pad_t, pad_l, pad_b, pad_r]) < kernel) op = core.CreateOperator( method, ["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 method not in ('MaxPool'): 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"]), method=st.sampled_from(["MaxPool", "AveragePool"]), **hu.gcs) def test_pooling_1d(self, stride, pad, kernel, size, input_channels, batch_size, order, method, gc, dc): assume(pad < kernel) op = core.CreateOperator( method, ["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 method not in ('MaxPool'): self.assertGradientChecks(gc, op, [X], 0, [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"]), method=st.sampled_from(["MaxPool", "AveragePool"]), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_pooling_3d(self, stride, pad, kernel, size, input_channels, batch_size, order, method, engine, gc, dc): assume(pad < kernel) op = core.CreateOperator( method, ["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]) if method not in ('MaxPool'): self.assertGradientChecks(gc, op, [X], 0, [0]) @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", ) 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(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"]), method=st.sampled_from(["MaxPool", "AveragePool", "LpPool"]), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_pooling(self, stride, pad, kernel, size, input_channels, batch_size, order, method, engine, gc, dc): assume(pad < kernel) op = core.CreateOperator( method, ["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 method not in ('MaxPool'): 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"]), method=st.sampled_from(["MaxPool", "AveragePool", "LpPool"]), engine=st.sampled_from(["", "CUDNN"]), **hu.gcs) def test_global_pooling(self, size, input_channels, batch_size, order, method, engine, gc, dc): op = core.CreateOperator( method, ["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 method not in ('MaxPool'): 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_cpu_only) 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_cpu_only) 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_cpu_only) 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_cpu_only) 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_cpu_only) 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 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 xrange(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 inp 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), ind_type=st.sampled_from([np.int32, np.int64]), **hu.gcs_cpu_only) def testScatterAssign( self, first_dim, index_dim, extra_dims, 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) ind = np.random.choice(first_dim, index_dim, replace=False).astype(ind_type) x = rand_array(index_dim, *extra_dims) 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])) 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 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(width_scale=st.floats(0.2, 4.0) | st.just(2.0), height_scale=st.floats(0.2, 4.0) | st.just(2.0), size_w=st.integers(16, 128), size_h=st.integers(16, 128), input_channels=st.integers(1, 4), batch_size=st.integers(1, 4), **hu.gcs_cpu_only) def test_nearest(self, width_scale, height_scale, size_w, size_h, input_channels, batch_size, gc, dc): op = core.CreateOperator( "ResizeNearest", ["X"], ["Y"], width_scale=width_scale, height_scale=height_scale, ) X = np.random.rand( batch_size, input_channels, size_h, size_w).astype(np.float32) """ This reference check is disabled because PIL's nearest neighbor resizing works differently than torch's SpatialUpSamplingNearest, which is the behavior we really care about matching def ref(X): from scipy import misc N = X.shape[0] C = X.shape[1] Y_h = int(size_h * height_scale) Y_w = int(size_w * width_scale) Y = np.zeros((N, C, Y_h, Y_w)).astype(np.float32) for n in range(N): for c in range(C): X_ = X[n][c] assert len(X_.shape) == 2 Y_ = misc.imresize(X_, (Y_h, Y_w), 'nearest', 'F') Y[n][c] = Y_ return (Y,) 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 core 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) )) 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 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, ) 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 hypothesis import given import caffe2.python.hypothesis_test_util as hu import numpy as np 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_cpu_only ) def test_uniform_int_fill_op_blob_input(self, shape, a, b, gc, dc): net = core.Net('test_net') 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) for device_option in dc: net._net.device_option.CopyFrom(device_option) 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_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 class DistanceTest(hu.HypothesisTestCase): @given(inputs=hu.tensors(n=2, min_dim=1, max_dim=4, dtype=np.float32), **hu.gcs) def test_L1_distance(self, inputs, gc, dc): X, Y = inputs # 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).flatten(), ord=1), 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(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])
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 @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.floats(min_value=-10, max_value=10), )), draw(st.lists( elements=st.floats(min_value=-2, 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): 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) 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] op = core.CreateOperator( 'BatchBoxCox', ['data', 'lambda1', 'lambda2'], ['output'] ) 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_cpu_only) 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"]), **hu.gcs) def test_prelu(self, X, alpha, inplace, shared, order, gc, dc): #np.random.seed(20) 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]) # Gradient check wrt W self.assertGradientChecks(gc, op, [X, W], 1, [0]) @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]) 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 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, 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) return (out, lengths_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)) def test_add_padding(self, start_pad_width, end_pad_width, args): 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) op = core.CreateOperator( 'AddPadding', ['data', 'lengths', 'start_padding', 'end_padding'], ['output', 'lengths_out'], padding_width=start_pad_width, end_padding_width=end_pad_width) self.assertReferenceChecks( hu.cpu_do, op, [data, lengths, start_padding, end_padding], partial(_add_padding_ref, start_pad_width, end_pad_width)) @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)) def test_add_zero_padding(self, start_pad_width, end_pad_width, args): 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( hu.cpu_do, op, [data, lengths], partial(_add_padding_ref, start_pad_width, end_pad_width)) @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)) def test_add_padding_no_length(self, start_pad_width, end_pad_width, data): op = core.CreateOperator( 'AddPadding', ['data'], ['output', 'output_lens'], padding_width=start_pad_width, end_padding_width=end_pad_width) self.assertReferenceChecks( hu.cpu_do, op, [data], partial( _add_padding_ref, start_pad_width, end_pad_width, lengths=np.array([data.shape[0]]))) @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)) def test_remove_padding(self, start_pad_width, end_pad_width, args): 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( hu.cpu_do, op, [data, lengths], partial(_remove_padding_ref, start_pad_width, end_pad_width)) @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)) def test_gather_padding(self, start_pad_width, end_pad_width, args): lengths, data, start_padding, end_padding = args padded_data, padded_lengths = _add_padding_ref( start_pad_width, end_pad_width, 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( hu.cpu_do, op, [padded_data, padded_lengths], 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): dims_ = 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), ) return dims_.flatmap( lambda dims: st.tuples( hu.arrays([dims[0], dims[1]], dtype=dtype), hu.arrays( [dims[0]], np.int32, st.integers(min_value=5, max_value=10), ) ) ) 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( map(lambda a: a.encode('utf-8'), strings), dtype=np.object) def string_prefix_ref(strings): return ( np.array(map(lambda a: a[:length], 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( map(lambda a: a.encode('utf-8'), strings), dtype=np.object) def string_suffix_ref(strings): return ( np.array(map(lambda a: a[-length:], 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( map(lambda a: str(strings), strings), dtype=np.object) def string_starts_with_ref(strings): return (np.array( map(lambda a: a.startswith(prefix), 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( map(lambda a: str(strings), strings), dtype=np.object) def string_ends_with_ref(strings): return (np.array( map(lambda a: a.endswith(suffix), 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(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 import random from hypothesis import given import hypothesis.strategies as st from caffe2.python import core, workspace 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])) def test(self, N, dtype): M = np.random.randint(1, N) all_value = np.random.rand(N).astype(dtype) split = sorted(np.random.randint(1, N, size=(M,))) indices = np.array(range(N)) random.shuffle(indices) pieces = np.split(indices, split) masks_and_values_name = [] for i, piece in enumerate(pieces): mask = np.zeros(N, dtype=np.bool_) mask[piece] = True values = all_value[piece] mask_name = "mask%d" % i value_name = "value%d" % i workspace.FeedBlob(mask_name, mask) workspace.FeedBlob(value_name, values) masks_and_values_name.append(mask_name) masks_and_values_name.append(value_name) net = core.Net('net') net.BooleanUnmask(masks_and_values_name, ["output"]) workspace.RunNetOnce(net) output = workspace.FetchBlob('output') self.assertAlmostEqual( output.all(), all_value.all(), delta=1e-4 ) 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 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 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(), **hu.gcs) def test_convolution_transpose_layout(self, stride, pad, kernel, adj, size, input_channels, output_channels, batch_size, engine, shared_buffer, 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"], ["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.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"]), **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, 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"], ["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.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"]), **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, 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"], ["Y"], stride=stride, kernel=kernel, pad=pad, adj=adj, order=order, engine=engine, ) if order == "NCHW": X = X.transpose((0, 3, 1, 2)) w = w.transpose((0, 3, 1, 2)) self.assertDeviceChecks(dc, op, [X, w, b], [0]) for i in range(3): self.assertGradientChecks(gc, op, [X, w, b], 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"]), **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, 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"], ["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, ) if order == "NCHW": X = X.transpose((0, 3, 1, 2)) w = w.transpose((0, 3, 1, 2)) self.assertDeviceChecks(dc, op, [X, w, b], [0]) for i in range(3): self.assertGradientChecks(gc, op, [X, w, b], 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 sys import os import shutil import lmdb import unittest 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 def test_read_from_db(self): random_label = np.random.randint(0, 100) VIDEO = "/mnt/vol/gfsdataswarm-oregon/users/trandu/sample.avi" 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.VideoInput( reader, ["data", "label"], name="data", batch_size=10, width=171, height=128, crop=112, length=8, sampling_rate=2, mirror=1, use_local_file=0, temporal_jitter=1) 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, [10, 3, 8, 112, 112]) 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 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') self.assertAlmostEqual( np.asscalar(dx[0]), np.asscalar( 0.5 * dY[0] * (up_output_pred[0] - down_output_pred[0]) / delta), delta=abs(np.asscalar(dx[0]) * 1e-2))
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from PIL import Image import cv2 import numpy as np import lmdb import shutil import StringIO 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): 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 = StringIO.StringIO() 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)))) expected_results.append(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 label_tensor.int32_data.append(index) 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 class TestImport(hu.HypothesisTestCase): @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)), **hu.gcs) @settings(verbosity=Verbosity.verbose) def test_imageinput(self, size_tuple, means, stds, gc, dc): # 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 ) 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) imageop = core.CreateOperator( 'ImageInput', ['DB'], ["data", "label"], batch_size=count_images, color=3, minsize=minsize, crop=crop, is_test=True, 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) ) imageop.device_option.CopyFrom(device_option) main_net = core.Net('main') main_net.Proto().op.extend([imageop]) workspace.RunNetOnce(main_net) 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 = expected_images for i in range(count_images): self.assertEqual(l[i], i) self.assertEqual((expected[i] - result[i] > 1).sum(), 0) # End for # End with # End for shutil.rmtree(out_dir) # 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(i, j) 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) ) 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 i 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 j 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 import numpy as np from hypothesis import given, assume import hypothesis.strategies as st from itertools import izip 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) # 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 izip(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 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()
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 TestLengthsTileOp(hu.HypothesisTestCase): @given( inputs=st.integers(min_value=1, max_value=20).flatmap( lambda size: st.tuples( hu.arrays([size]), hu.arrays([size], dtype=np.int32, elements=st.integers(min_value=0, max_value=20)), ) ), **hu.gcs_cpu_only) def test_lengths_tile(self, inputs, gc, dc): data, lengths = inputs def lengths_tile_op(data, lengths): return [np.concatenate([ [d] * l for d, l in zip(data, lengths) ])] op = core.CreateOperator( "LengthsTile", ["data", "lengths"], ["output"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[data, lengths], reference=lengths_tile_op, ) self.assertGradientChecks( device_option=gc, op=op, inputs=[data, lengths], outputs_to_check=0, outputs_with_grads=[0] )
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 import unittest class TestGroupConvolution(hu.HypothesisTestCase): @given(stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), size=st.integers(7, 10), group=st.integers(1, 4), input_channels_per_group=st.integers(1, 8), output_channels_per_group=st.integers(1, 8), batch_size=st.integers(1, 3), # TODO(jiayq): if needed, add NHWC support. order=st.sampled_from(["NCHW"]), # Note: Eigen does not support group convolution, but it should # fall back to the default engine without failing. engine=st.sampled_from(["", "CUDNN", "EIGEN"]), use_bias=st.booleans(), **hu.gcs) @settings(max_examples=2, timeout=100) def test_group_convolution( self, stride, pad, kernel, size, group, input_channels_per_group, output_channels_per_group, batch_size, order, engine, use_bias, gc, dc): assume(size >= kernel) input_channels = input_channels_per_group * group output_channels = output_channels_per_group * group op = core.CreateOperator( "Conv", ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], stride=stride, kernel=kernel, pad=pad, order=order, engine=engine, group=group, ) 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_per_group).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] self.assertDeviceChecks(dc, op, inputs, [0]) for i in range(len(inputs)): self.assertGradientChecks(gc, op, inputs, i, [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 TestLossOps(hu.HypothesisTestCase): @given(n=st.integers(1, 8), **hu.gcs) def test_averaged_loss(self, n, gc, dc): X = np.random.rand(n).astype(np.float32) def avg_op(X): return [np.mean(X)] op = core.CreateOperator( "AveragedLoss", ["X"], ["y"], ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X], reference=avg_op, ) self.assertGradientChecks( device_option=gc, op=op, inputs=[X], outputs_to_check=0, outputs_with_grads=[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.test_util import TestCase import tempfile class TestCounterOps(TestCase): def test_counter_ops(self): workspace.RunOperatorOnce(core.CreateOperator( 'CreateCounter', [], ['c'], init_count=1)) workspace.RunOperatorOnce(core.CreateOperator( 'CountDown', ['c'], ['t1'])) # 1 -> 0 assert not workspace.FetchBlob('t1') workspace.RunOperatorOnce(core.CreateOperator( 'CountDown', ['c'], ['t2'])) # 0 -> -1 assert workspace.FetchBlob('t2') workspace.RunOperatorOnce(core.CreateOperator( 'CountUp', ['c'], ['t21'])) # -1 -> 0 assert workspace.FetchBlob('t21') == -1 workspace.RunOperatorOnce(core.CreateOperator( 'RetrieveCount', ['c'], ['t22'])) assert workspace.FetchBlob('t22') == 0 workspace.RunOperatorOnce(core.CreateOperator( 'ResetCounter', ['c'], [], init_count=1)) # -> 1 workspace.RunOperatorOnce(core.CreateOperator( 'CountDown', ['c'], ['t3'])) # 1 -> 0 assert not workspace.FetchBlob('t3') workspace.RunOperatorOnce(core.CreateOperator( 'ResetCounter', ['c'], ['t31'], init_count=5)) # 0 -> 5 assert workspace.FetchBlob('t31') == 0 workspace.RunOperatorOnce(core.CreateOperator( 'ResetCounter', ['c'], ['t32'])) # 5 -> 0 assert workspace.FetchBlob('t32') == 5 workspace.RunOperatorOnce(core.CreateOperator( 'ConstantFill', [], ['t4'], value=False, shape=[], dtype=core.DataType.BOOL)) assert workspace.FetchBlob('t4') == workspace.FetchBlob('t1') workspace.RunOperatorOnce(core.CreateOperator( 'ConstantFill', [], ['t5'], value=True, shape=[], dtype=core.DataType.BOOL)) assert workspace.FetchBlob('t5') == workspace.FetchBlob('t2') assert workspace.RunOperatorOnce(core.CreateOperator( 'And', ['t1', 't2'], ['t6'])) assert not workspace.FetchBlob('t6') # True && False assert workspace.RunOperatorOnce(core.CreateOperator( 'And', ['t2', 't5'], ['t7'])) assert workspace.FetchBlob('t7') # True && True workspace.RunOperatorOnce(core.CreateOperator( 'CreateCounter', [], ['serialized_c'], init_count=22)) with tempfile.NamedTemporaryFile() as tmp: workspace.RunOperatorOnce(core.CreateOperator( 'Save', ['serialized_c'], [], absolute_path=1, db_type='minidb', db=tmp.name)) for i in range(10): workspace.RunOperatorOnce(core.CreateOperator( 'CountDown', ['serialized_c'], ['t8'])) workspace.RunOperatorOnce(core.CreateOperator( 'RetrieveCount', ['serialized_c'], ['t8'])) assert workspace.FetchBlob('t8') == 12 workspace.RunOperatorOnce(core.CreateOperator( 'Load', [], ['serialized_c'], absolute_path=1, db_type='minidb', db=tmp.name)) workspace.RunOperatorOnce(core.CreateOperator( 'RetrieveCount', ['serialized_c'], ['t8'])) assert workspace.FetchBlob('t8') == 22 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 model_helper, workspace, core, rnn_cell from caffe2.proto import caffe2_pb2 import numpy as np import unittest @unittest.skipIf(not workspace.has_gpu_support, "No gpu support.") class TestLSTMs(unittest.TestCase): def testEqualToCudnn(self): with core.DeviceScope(core.DeviceOption(caffe2_pb2.CUDA)): T = 8 batch_size = 4 input_dim = 8 hidden_dim = 31 workspace.FeedBlob( "seq_lengths", np.array([T] * batch_size, dtype=np.int32) ) workspace.FeedBlob("target", np.zeros( [T, batch_size, hidden_dim], dtype=np.float32 )) workspace.FeedBlob("hidden_init", np.zeros( [1, batch_size, hidden_dim], dtype=np.float32 )) workspace.FeedBlob("cell_init", np.zeros( [1, batch_size, hidden_dim], dtype=np.float32 )) own_model = model_helper.ModelHelper(name="own_lstm") input_shape = [T, batch_size, input_dim] cudnn_model = model_helper.ModelHelper(name="cudnn_lstm") input_blob = cudnn_model.param_init_net.UniformFill( [], "input", shape=input_shape) workspace.FeedBlob("CUDNN/hidden_init_cudnn", np.zeros( [1, batch_size, hidden_dim], dtype=np.float32 )) workspace.FeedBlob("CUDNN/cell_init_cudnn", np.zeros( [1, batch_size, hidden_dim], dtype=np.float32 )) cudnn_output, cudnn_last_hidden, _, param_extract = rnn_cell.cudnn_LSTM( model=cudnn_model, input_blob=input_blob, initial_states=("hidden_init_cudnn", "hidden_init_cudnn"), dim_in=input_dim, dim_out=hidden_dim, scope="CUDNN", return_params=True, ) cudnn_loss = cudnn_model.AveragedLoss( cudnn_model.SquaredL2Distance( [cudnn_output, "target"], "CUDNN/dist" ), "CUDNN/loss" ) own_output, own_last_hidden, _, last_state, own_params = rnn_cell.LSTM( model=own_model, input_blob=input_blob, seq_lengths="seq_lengths", initial_states=("hidden_init", "cell_init"), dim_in=input_dim, dim_out=hidden_dim, scope="OWN", return_params=True, ) own_loss = own_model.AveragedLoss( own_model.SquaredL2Distance([own_output, "target"], "OWN/dist"), "OWN/loss" ) # Add gradients cudnn_model.AddGradientOperators([cudnn_loss]) own_model.AddGradientOperators([own_loss]) # Add parameter updates LR = cudnn_model.param_init_net.ConstantFill( [], shape=[1], value=0.01 ) ONE = cudnn_model.param_init_net.ConstantFill( [], shape=[1], value=1.0 ) for param in cudnn_model.GetParams(): cudnn_model.WeightedSum( [param, ONE, cudnn_model.param_to_grad[param], LR], param ) for param in own_model.GetParams(): own_model.WeightedSum( [param, ONE, own_model.param_to_grad[param], LR], param ) workspace.RunNetOnce(cudnn_model.param_init_net) workspace.CreateNet(cudnn_model.net) ## ## CUDNN LSTM MODEL EXECUTION ## # Get initial values from CuDNN LSTM so we can feed them # to our own. (param_extract_net, param_extract_mapping) = param_extract workspace.RunNetOnce(param_extract_net) cudnn_lstm_params = {} for input_type, pars in param_extract_mapping.items(): cudnn_lstm_params[input_type] = {} for k, v in pars.items(): cudnn_lstm_params[input_type][k] = workspace.FetchBlob(v[0]) # Run the model 3 times, so that some parameter updates are done workspace.RunNet(cudnn_model.net.Proto().name, 3) ## ## OWN LSTM MODEL EXECUTION ## # Map the cuDNN parameters to our own workspace.RunNetOnce(own_model.param_init_net) rnn_cell.InitFromLSTMParams(own_params, cudnn_lstm_params) # Run the model 3 times, so that some parameter updates are done workspace.CreateNet(own_model.net) workspace.RunNet(own_model.net.Proto().name, 3) ## ## COMPARE RESULTS ## # Then compare that final results after 3 runs are equal own_output_data = workspace.FetchBlob(own_output) own_last_hidden = workspace.FetchBlob(own_last_hidden) own_loss = workspace.FetchBlob(own_loss) cudnn_output_data = workspace.FetchBlob(cudnn_output) cudnn_last_hidden = workspace.FetchBlob(cudnn_last_hidden) cudnn_loss = workspace.FetchBlob(cudnn_loss) self.assertTrue(np.allclose(own_output_data, cudnn_output_data)) self.assertTrue(np.allclose(own_last_hidden, cudnn_last_hidden)) self.assertTrue(np.allclose(own_loss, cudnn_loss))
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 unittest from caffe2.python import core, workspace import caffe2.python.hypothesis_test_util as hu class TestTile(hu.HypothesisTestCase): @given(M=st.integers(min_value=1, max_value=10), K=st.integers(min_value=1, max_value=10), N=st.integers(min_value=1, max_value=10), tiles=st.integers(min_value=1, max_value=3), axis=st.integers(min_value=0, max_value=2), **hu.gcs) def test_tile(self, M, K, N, tiles, axis, gc, dc): X = np.random.rand(M, K, N).astype(np.float32) op = core.CreateOperator( 'Tile', ['X'], 'out', tiles=tiles, axis=axis, ) def tile_ref(X, tiles, axis): dims = [1, 1, 1] dims[axis] = tiles tiled_data = np.tile(X, tuple(dims)) return (tiled_data,) # Check against numpy reference self.assertReferenceChecks(gc, op, [X, tiles, axis], tile_ref) # Check over multiple devices self.assertDeviceChecks(dc, op, [X], [0]) # Gradient check wrt X self.assertGradientChecks(gc, op, [X], 0, [0]) @unittest.skipIf(not workspace.has_gpu_support, "No gpu support") @given(M=st.integers(min_value=1, max_value=200), N=st.integers(min_value=1, max_value=200), tiles=st.integers(min_value=50, max_value=100), **hu.gcs) def test_tile_grad(self, M, N, tiles, gc, dc): X = np.random.rand(M, N).astype(np.float32) axis = 1 op = core.CreateOperator( 'Tile', ['X'], 'out', tiles=tiles, axis=axis, ) def tile_ref(X, tiles, axis): dims = [1, 1] dims[axis] = tiles tiled_data = np.tile(X, tuple(dims)) return (tiled_data,) # Check against numpy reference self.assertReferenceChecks(gc, op, [X, tiles, axis], tile_ref) # Check over multiple devices self.assertDeviceChecks(dc, op, [X], [0]) # Gradient check wrt X grad_op = core.CreateOperator( 'TileGradient', ['dOut'], 'dX', tiles=tiles, axis=axis, ) dX = np.random.rand(M, N * tiles).astype(np.float32) self.assertDeviceChecks(dc, grad_op, [dX], [0]) @given(M=st.integers(min_value=1, max_value=10), K=st.integers(min_value=1, max_value=10), N=st.integers(min_value=1, max_value=10), tiles=st.integers(min_value=1, max_value=3), axis=st.integers(min_value=0, max_value=2), **hu.gcs) def test_tilewinput(self, M, K, N, tiles, axis, gc, dc): X = np.random.rand(M, K, N).astype(np.float32) tiles_arg = np.array([tiles], dtype=np.int32) axis_arg = np.array([axis], dtype=np.int32) op = core.CreateOperator( 'Tile', ['X', 'tiles', 'axis'], 'out', ) def tile_ref(X, tiles, axis): dims = [1, 1, 1] dims[axis] = tiles tiled_data = np.tile(X, tuple(dims)) return (tiled_data,) # Check against numpy reference self.assertReferenceChecks(gc, op, [X, tiles_arg, axis_arg], tile_ref) # Check over multiple devices self.assertDeviceChecks(dc, op, [X, tiles_arg, axis_arg], [0]) # Gradient check wrt X self.assertGradientChecks(gc, op, [X, tiles_arg, axis_arg], 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 TestUtilityOps(hu.HypothesisTestCase): @given(dtype=st.sampled_from([np.float32, np.int32, np.int64]), ndims=st.integers(min_value=1, max_value=5), seed=st.integers(min_value=0, max_value=65536), null_axes=st.booleans(), engine=st.sampled_from(['CUDNN', None]), **hu.gcs) def test_transpose(self, dtype, ndims, seed, null_axes, engine, gc, dc): dims = (np.random.rand(ndims) * 16 + 1).astype(np.int32) X = (np.random.rand(*dims) * 16).astype(dtype) if null_axes: axes = None op = core.CreateOperator( "Transpose", ["input"], ["output"], engine=engine) else: np.random.seed(int(seed)) axes = [int(v) for v in list(np.random.permutation(X.ndim))] op = core.CreateOperator( "Transpose", ["input"], ["output"], axes=axes, engine=engine) def transpose_ref(x, axes): return (np.transpose(x, axes),) self.assertReferenceChecks(gc, op, [X, axes], transpose_ref) @given(m=st.integers(5, 10), n=st.integers(5, 10), o=st.integers(5, 10), nans=st.booleans(), **hu.gcs) def test_nan_check(self, m, n, o, nans, gc, dc): other = np.array([1, 2, 3]).astype(np.float32) X = np.random.rand(m, n, o).astype(np.float32) if nans: x_nan = np.random.randint(0, m) y_nan = np.random.randint(0, n) z_nan = np.random.randint(0, o) X[x_nan, y_nan, z_nan] = float('NaN') # print('nans: {}'.format(nans)) # print(X) def nan_reference(X, Y): if not np.isnan(X).any(): return [X] else: return [np.array([])] op = core.CreateOperator( "NanCheck", ["X", "other"], ["Y"] ) try: self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, other], reference=nan_reference, ) if nans: self.assertTrue(False, "Did not fail when presented with NaN!") except RuntimeError: self.assertTrue(nans, "No NaNs but failed") try: self.assertGradientChecks( device_option=gc, op=op, inputs=[X], outputs_to_check=0, outputs_with_grads=[0], ) if nans: self.assertTrue(False, "Did not fail when gradient had NaN!") except RuntimeError: pass @given(n=st.integers(4, 5), m=st.integers(6, 7), d=st.integers(2, 3), **hu.gcs) def test_elementwise_max(self, n, m, d, gc, dc): X = np.random.rand(n, m, d).astype(np.float32) Y = np.random.rand(n, m, d).astype(np.float32) Z = np.random.rand(n, m, d).astype(np.float32) def max_op(X, Y, Z): return [np.maximum(np.maximum(X, Y), Z)] op = core.CreateOperator( "Max", ["X", "Y", "Z"], ["mx"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, Y, Z], reference=max_op, ) @given( inputs=hu.lengths_tensor(max_value=30).flatmap( lambda pair: st.tuples( st.just(pair[0]), st.just(pair[1]), hu.dims(max_value=len(pair[1])), ) ).flatmap( lambda tup: st.tuples( st.just(tup[0]), st.just(tup[1]), hu.arrays( tup[2], dtype=np.int32, elements=st.integers( min_value=0, max_value=len(tup[1]) - 1)), ) ), **hu.gcs_cpu_only) def test_lengths_gather(self, inputs, gc, dc): items = inputs[0] lengths = inputs[1] indices = inputs[2] def lengths_gather_op(items, lengths, indices): ends = np.cumsum(lengths) return [np.concatenate( list(items[ends[i] - lengths[i]:ends[i]] for i in indices))] op = core.CreateOperator( "LengthsGather", ["items", "lengths", "indices"], ["output"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[items, lengths, indices], reference=lengths_gather_op, )
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 class TestDuplicateOperands(TestCase): def test_duplicate_operands(self): net = core.Net('net') shape = (2, 4) x_in = np.random.uniform(size=shape) x = net.GivenTensorFill([], 'X', shape=shape, values=x_in.flatten().tolist()) xsq = net.Mul([x, x]) y = net.DotProduct([xsq, xsq]) net.AddGradientOperators([y]) workspace.RunNetOnce(net) self.assertTrue(np.allclose(workspace.FetchBlob('X_grad'), 4 * x_in**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 numpy as np from caffe2.python import core, workspace, dataset from caffe2.python.dataset import Const from caffe2.python.schema import ( List, Field, Struct, Scalar, Map, from_blob_list, FetchRecord, NewRecord, FeedRecord ) from caffe2.python.test_util import TestCase import numpy.testing as npt import string from hypothesis import given import hypothesis.strategies as st def _assert_arrays_equal(actual, ref, err_msg): if ref.dtype.kind in ('S', 'O'): np.testing.assert_array_equal(actual, ref, err_msg=err_msg) else: np.testing.assert_allclose( actual, ref, atol=1e-4, rtol=1e-4, err_msg=err_msg ) def _assert_records_equal(actual, ref): assert isinstance(actual, Field) assert isinstance(ref, Field) b1 = actual.field_blobs() b2 = ref.field_blobs() assert (len(b1) == len(b2)), 'Records have different lengths: %d vs. %d' % ( len(b1), len(b2) ) for name, d1, d2 in zip(ref.field_names(), b1, b2): _assert_arrays_equal(d1, d2, err_msg='Mismatch in field %s.' % name) @st.composite def _sparse_features_map(draw, num_records, **kwargs): sparse_maps_lengths = draw( st.lists( st.integers(min_value=1, max_value=10), min_size=num_records, max_size=num_records ) ) sparse_maps_total_length = sum(sparse_maps_lengths) sparse_keys = draw( st.lists( st.integers(min_value=1, max_value=100), min_size=sparse_maps_total_length, max_size=sparse_maps_total_length, unique=True ) ) sparse_values_lengths = draw( st.lists( st.integers(min_value=1, max_value=10), min_size=sparse_maps_total_length, max_size=sparse_maps_total_length ) ) total_sparse_values_lengths = sum(sparse_values_lengths) sparse_values = draw( # max_value is max int64 st.lists( st.integers(min_value=1, max_value=9223372036854775807), min_size=total_sparse_values_lengths, max_size=total_sparse_values_lengths ) ) return [ sparse_maps_lengths, sparse_keys, sparse_values_lengths, sparse_values, ] @st.composite def _dense_features_map(draw, num_records, **kwargs): float_lengths = draw( st.lists( st.integers(min_value=1, max_value=10), min_size=num_records, max_size=num_records ) ) total_length = sum(float_lengths) float_keys = draw( st.lists( st.integers(min_value=1, max_value=100), min_size=total_length, max_size=total_length, unique=True ) ) float_values = draw( st.lists(st.floats(), min_size=total_length, max_size=total_length) ) return [float_lengths, float_keys, float_values] @st.composite def _dataset(draw, min_elements=3, max_elements=10, **kwargs): schema = Struct( # Dense Features Map ('floats', Map( Scalar(np.int32), Scalar(np.float32) )), # Sparse Features Map ('int_lists', Map( Scalar(np.int32), List(Scalar(np.int64)), )), # Complex Type ('text', Scalar(str)), ) num_records = draw( st.integers(min_value=min_elements, max_value=max_elements) ) raw_dense_features_map_contents = draw(_dense_features_map(num_records)) raw_sparse_features_map_contents = draw(_sparse_features_map(num_records)) raw_text_contents = [ draw( st.lists( st.text(alphabet=string.ascii_lowercase), min_size=num_records, max_size=num_records ) ) ] # Concatenate all raw contents to a single one contents_raw = raw_dense_features_map_contents + raw_sparse_features_map_contents + raw_text_contents contents = from_blob_list(schema, contents_raw) return (schema, contents, num_records) class TestDatasetOps(TestCase): @given(_dataset()) def test_pack_unpack(self, input): """ Tests if packing and unpacking of the whole dataset is an identity. """ (schema, contents, num_records) = input dataset_fields = schema.field_names() net = core.Net('pack_unpack_net') batch = NewRecord(net, contents) FeedRecord(batch, contents) packed = net.PackRecords( batch.field_blobs(), 1, fields=dataset_fields ) unpacked = packed.UnPackRecords( [], len(dataset_fields), fields=dataset_fields ) workspace.RunNetOnce(net) for initial_tensor, unpacked_tensor in zip( batch.field_blobs(), unpacked ): npt.assert_array_equal( workspace.FetchBlob(initial_tensor), workspace.FetchBlob(unpacked_tensor) ) def test_dataset_ops(self): """ 1. Defining the schema of our dataset. This example schema could represent, for example, a search query log. """ schema = Struct( # fixed size vector, which will be stored as a matrix when batched ('dense', Scalar((np.float32, 3))), # could represent a feature map from feature ID to float value ('floats', Map( Scalar(np.int32), Scalar(np.float32) )), # could represent a multi-valued categorical feature map ('int_lists', Map( Scalar(np.int32), List(Scalar(np.int64)), )), # could represent a multi-valued, weighted categorical feature map ( 'id_score_pairs', Map( Scalar(np.int32), Map( Scalar(np.int64), Scalar(np.float32), keys_name='ids', values_name='scores' ), ) ), # additional scalar information ( 'metadata', Struct( ('user_id', Scalar(np.int64)), ('user_embed', Scalar((np.float32, 2))), ('query', Scalar(str)), ) ), ) """ This is what the flattened fields for this schema look like, along with its type. Each one of these fields will be stored, read and writen as a tensor. """ expected_fields = [ ('dense', (np.float32, 3)), ('floats:lengths', np.int32), ('floats:values:keys', np.int32), ('floats:values:values', np.float32), ('int_lists:lengths', np.int32), ('int_lists:values:keys', np.int32), ('int_lists:values:values:lengths', np.int32), ('int_lists:values:values:values', np.int64), ('id_score_pairs:lengths', np.int32), ('id_score_pairs:values:keys', np.int32), ('id_score_pairs:values:values:lengths', np.int32), ('id_score_pairs:values:values:values:ids', np.int64), ('id_score_pairs:values:values:values:scores', np.float32), ('metadata:user_id', np.int64), ('metadata:user_embed', (np.float32, 2)), ('metadata:query', str), ] zipped = zip( expected_fields, schema.field_names(), schema.field_types() ) for (ref_name, ref_type), name, dtype in zipped: self.assertEquals(ref_name, name) self.assertEquals(np.dtype(ref_type), dtype) """ 2. The contents of our dataset. Contents as defined below could represent, for example, a log of search queries along with dense, sparse features and metadata. The datset below has 3 top-level entries. """ contents_raw = [ # dense [[1.1, 1.2, 1.3], [2.1, 2.2, 2.3], [3.1, 3.2, 3.3]], # floats [1, 2, 3], # len [11, 21, 22, 31, 32, 33], # key [1.1, 2.1, 2.2, 3.1, 3.2, 3.3], # value # int lists [2, 0, 1], # len [11, 12, 31], # key [2, 4, 3], # value:len [111, 112, 121, 122, 123, 124, 311, 312, 313], # value:value # id score pairs [1, 2, 2], # len [11, 21, 22, 31, 32], # key [1, 1, 2, 2, 3], # value:len [111, 211, 221, 222, 311, 312, 321, 322, 323], # value:ids [11.1, 21.1, 22.1, 22.2, 31.1, 31.2, 32.1, 32.2, 32.3], # val:score # metadata [123, 234, 456], # user_id [[0.2, 0.8], [0.5, 0.5], [0.7, 0.3]], # user_embed ['dog posts', 'friends who like to', 'posts about ca'], # query ] # convert the above content to ndarrays, checking against the schema contents = from_blob_list(schema, contents_raw) """ 3. Creating and appending to the dataset. We first create an empty dataset with the given schema. Then, a Writer is used to append these entries to the dataset. """ ds = dataset.Dataset(schema) net = core.Net('init') with core.NameScope('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) workspace.RunNetOnce(net) """ 4. Iterating through the dataset contents. If we were to iterate through the top level entries of our dataset, this is what we should expect to see: """ entries_raw = [ ( [[1.1, 1.2, 1.3]], # dense [1], [11], [1.1], # floats [2], [11, 12], [2, 4], [111, 112, 121, 122, 123, 124], # intlst [1], [11], [1], [111], [11.1], # id score pairs [123], [[0.2, 0.8]], ['dog posts'], # metadata ), ( [[2.1, 2.2, 2.3]], # dense [2], [21, 22], [2.1, 2.2], # floats [0], [], [], [], # int list [2], [21, 22], [1, 2], [211, 221, 222], [21.1, 22.1, 22.2], [234], [[0.5, 0.5]], ['friends who like to'], # metadata ), ( [[3.1, 3.2, 3.3]], # dense [3], [31, 32, 33], [3.1, 3.2, 3.3], # floats [1], [31], [3], [311, 312, 313], # int lst [2], [31, 32], [2, 3], [311, 312, 321, 322, 323], [31.1, 31.2, 32.1, 32.2, 32.3], # id score list [456], [[0.7, 0.3]], ['posts about ca'], # metadata ), # after the end of the dataset, we will keep getting empty vectors ([], ) * 16, ([], ) * 16, ] entries = [from_blob_list(schema, e) for e in entries_raw] """ Let's go ahead and create the reading nets. We will run `read` net multiple times and assert that we are reading the entries the way we stated above. """ read_init_net = core.Net('read_init') read_next_net = core.Net('read_next') reader = ds.reader(read_init_net) should_continue, batch = reader.read_record(read_next_net) workspace.RunNetOnce(read_init_net) workspace.CreateNet(read_next_net, True) for entry in entries: workspace.RunNet(str(read_next_net)) actual = FetchRecord(batch) _assert_records_equal(actual, entry) """ 5. Reading/writing in a single plan If all of operations on the data are expressible as Caffe2 operators, we don't need to load the data to python, iterating through the dataset in a single Plan. Where we will process the dataset a little and store it in a second dataset. We can reuse the same Reader since it supports reset. """ reset_net = core.Net('reset_net') reader.reset(reset_net) read_step, batch = reader.execution_step() """ We will add the line number * 1000 to the feature ids. """ process_net = core.Net('process') line_no = Const(process_net, 0, dtype=np.int32) const_one = Const(process_net, 1000, dtype=np.int32) process_net.Add([line_no, const_one], [line_no]) field = batch.floats.keys.get() process_net.Print(field, []) process_net.Add([field, line_no], field, broadcast=1, axis=0) """ Lets create a second dataset and append to it. """ ds2 = dataset.Dataset(schema, name='dataset2') ds2.init_empty(reset_net) writer = ds2.writer(reset_net) writer.write_record(process_net, batch) # commit is not necessary for DatasetWriter but will add it for # generality of the example commit_net = core.Net('commit') writer.commit(commit_net) """ Time to create and run a plan which will do the processing """ plan = core.Plan('process') plan.AddStep(core.execution_step('reset', reset_net)) plan.AddStep(read_step.AddNet(process_net)) plan.AddStep(core.execution_step('commit', commit_net)) workspace.RunPlan(plan) """ Now we should have dataset2 populated. """ ds2_data = FetchRecord(ds2.content()) field = ds2_data.floats.keys field.set(blob=field.get() - [1000, 2000, 2000, 3000, 3000, 3000]) _assert_records_equal(contents, ds2_data) """ 6. Slicing a dataset You can create a new schema from pieces of another schema and reuse the same data. """ subschema = Struct(('top_level', schema.int_lists.values)) int_list_contents = contents.int_lists.values.field_names() self.assertEquals(len(subschema.field_names()), len(int_list_contents)) """ 7. Random Access a dataset """ read_init_net = core.Net('read_init') read_next_net = core.Net('read_next') idx = np.array([2, 1, 0]) indices_blob = Const(read_init_net, idx, name='indices') reader = ds.random_reader(read_init_net, indices_blob) reader.computeoffset(read_init_net) should_continue, batch = reader.read_record(read_next_net) workspace.CreateNet(read_init_net, True) workspace.RunNetOnce(read_init_net) workspace.CreateNet(read_next_net, True) for i in range(len(entries)): k = idx[i] if i in idx else i entry = entries[k] workspace.RunNet(str(read_next_net)) actual = FetchRecord(batch) _assert_records_equal(actual, entry) """ 8. Sort and shuffle a dataset This sort the dataset using the score of a certain column, and then shuffle within each chunk of size batch_size * shuffle_size before shuffling the chunks. """ read_init_net = core.Net('read_init') read_next_net = core.Net('read_next') reader = ds.random_reader(read_init_net) reader.sort_and_shuffle(read_init_net, 'int_lists:lengths', 1, 2) reader.computeoffset(read_init_net) should_continue, batch = reader.read_record(read_next_net) workspace.CreateNet(read_init_net, True) workspace.RunNetOnce(read_init_net) workspace.CreateNet(read_next_net, True) expected_idx = np.array([2, 1, 0]) for i in range(len(entries)): k = expected_idx[i] if i in expected_idx else i entry = entries[k] workspace.RunNet(str(read_next_net)) actual = FetchRecord(batch) _assert_records_equal(actual, entry) def test_last_n_window_ops(self): collect_net = core.Net('collect_net') collect_net.GivenTensorFill( [], 'input', shape=[3, 2], values=[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], ) input_array = np.array(range(1, 7), dtype=np.float32).reshape(3, 2) workspace.CreateBlob('output') workspace.FeedBlob('next', np.array(0, dtype=np.int32)) collect_net.LastNWindowCollector( ['output', 'next', 'input'], ['output', 'next'], num_to_collect=7, ) plan = core.Plan('collect_data') plan.AddStep( core.execution_step('collect_data', [collect_net], num_iter=1) ) workspace.RunPlan(plan) reference_result = workspace.FetchBlob('output') npt.assert_array_equal(input_array, reference_result) plan = core.Plan('collect_data') plan.AddStep( core.execution_step('collect_data', [collect_net], num_iter=2) ) workspace.RunPlan(plan) reference_result = workspace.FetchBlob('output') npt.assert_array_equal(input_array[[1, 2, 2, 0, 1, 2, 0]], reference_result) plan = core.Plan('collect_data') plan.AddStep( core.execution_step('collect_data', [collect_net], num_iter=3) ) workspace.RunPlan(plan) reference_result = workspace.FetchBlob('output') npt.assert_array_equal(input_array[[2, 0, 1, 2, 2, 0, 1]], reference_result) def test_collect_tensor_ops(self): init_net = core.Net('init_net') blobs = ['blob_1', 'blob_2', 'blob_3'] bvec_map = {} ONE = init_net.ConstantFill([], 'ONE', shape=[1, 2], value=1) for b in blobs: init_net.ConstantFill([], [b], shape=[1, 2], value=0) bvec_map[b] = b + '_vec' init_net.CreateTensorVector([], [bvec_map[b]]) reader_net = core.Net('reader_net') for b in blobs: reader_net.Add([b, ONE], [b]) collect_net = core.Net('collect_net') num_to_collect = 1000 max_example_to_cover = 100000 bvec = [bvec_map[b] for b in blobs] collect_net.CollectTensor( bvec + blobs, bvec, num_to_collect=num_to_collect, ) print('Collect Net Proto: {}'.format(collect_net.Proto())) plan = core.Plan('collect_data') plan.AddStep(core.execution_step('collect_init', init_net)) plan.AddStep( core.execution_step( 'collect_data', [reader_net, collect_net], num_iter=max_example_to_cover ) ) workspace.RunPlan(plan) # concat the collected tensors concat_net = core.Net('concat_net') bconcated_map = {} bsize_map = {} for b in blobs: bconcated_map[b] = b + '_concated' bsize_map[b] = b + '_size' concat_net.ConcatTensorVector([bvec_map[b]], [bconcated_map[b]]) concat_net.TensorVectorSize([bvec_map[b]], [bsize_map[b]]) workspace.RunNetOnce(concat_net) # check data reference_result = workspace.FetchBlob(bconcated_map[blobs[0]]) self.assertEqual( reference_result.shape, (min(num_to_collect, max_example_to_cover), 2) ) size = workspace.FetchBlob(bsize_map[blobs[0]]) self.assertEqual(tuple(), size.shape) self.assertEqual(min(num_to_collect, max_example_to_cover), size.item()) hist, _ = np.histogram( reference_result[:, 0], bins=10, range=(1, max_example_to_cover) ) print('Sample histogram: {}'.format(hist)) self.assertTrue(all(hist > 0.7 * (num_to_collect / 10))) for i in range(1, len(blobs)): result = workspace.FetchBlob(bconcated_map[blobs[i]]) self.assertEqual(reference_result.tolist(), result.tolist()) 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 import unittest from caffe2.proto import caffe2_pb2 from caffe2.python import workspace, test_util, model_helper, brew class TestShapeInference(test_util.TestCase): def testShapeInferenceSimpleFC(self): m = model_helper.ModelHelper(name="test_model") brew.fc(m, "data", "fc1", dim_in=96, dim_out=32) brew.fc(m, "fc1", "fc2", dim_in=32, dim_out=55) (shapes, types) = workspace.InferShapesAndTypes( [m.param_init_net, m.net], {'data': [64, 96]} ) self.assertEquals(shapes['data'], [64, 96]) self.assertEquals(shapes['fc1_w'], [32, 96]) self.assertEquals(shapes['fc1_b'], [32]) self.assertEquals(shapes['fc1'], [64, 32]) self.assertEquals(shapes['fc2_w'], [55, 32]) self.assertEquals(shapes['fc2_b'], [55]) self.assertEquals(shapes['fc2'], [64, 55]) def testShapeInferenceDistances(self): model = model_helper.ModelHelper(name="test_model") model.SquaredL2Distance(["x", "y"], "zsq") model.CosineSimilarity(["x", "y"], "zcos") model.DotProduct(["x", "y"], "zdot") workspace.FeedBlob("x", np.random.rand(10).astype(np.float32)) workspace.FeedBlob("y", np.random.rand(10).astype(np.float32)) self.InferTensorRunAndCompare(model) def testShapeInferenceConvNet(self): model = model_helper.ModelHelper(name="convtest") model.NHWC2NCHW("data", "data_nchw") brew.conv(model, "data_nchw", 'conv1', 3, 64, weight_init=("MSRAFill", {}), kernel=7, stride=2, pad=3, no_bias=0) brew.spatial_bn(model, 'conv1', 'conv1_spatbn_relu', 64, epsilon=1e-3) brew.relu(model, 'conv1_spatbn_relu', 'conv1_spatbn_relu') brew.max_pool(model, 'conv1_spatbn_relu', 'pool1', kernel=3, stride=2) brew.fc(model, 'pool1', 'fc', dim_in=(64 * 56 * 56), dim_out=100) model.Sigmoid('fc', 'fc_sigm') brew.softmax(model, 'fc_sigm', 'softmax') model.LabelCrossEntropy(['softmax', 'label'], 'xent') loss = model.AveragedLoss('xent', 'loss') model.AddGradientOperators([loss]) LR = model.param_init_net.ConstantFill( [], 'LR', shape=[1], value=0.1 ) for param in model.GetParams(): param_grad = model.param_to_grad[param] param_momentum = model.param_init_net.ConstantFill( [param], param + '_momentum', value=0.0 ) model.net.MomentumSGDUpdate( [param_grad, param_momentum, LR, param], [param_grad, param_momentum, param], ) workspace.FeedBlob( "data", np.random.rand(16, 227, 227, 3).astype(np.float32), ) workspace.FeedBlob( "label", (100 * np.random.rand(16)).astype(np.int32), ) workspace.FeedBlob( "label", (100 * np.random.rand(16)).astype(np.int32), ) # Then do automatic comparison test: run the next once to # initialize everything self.InferTensorRunAndCompare(model) def testShapeInferenceTranspose(self): model = model_helper.ModelHelper(name="test_model") workspace.FeedBlob( "tensor", np.random.rand(4, 2, 3, 3, 5).astype(np.float32) ) # Testing with axes undefined brew.transpose( model, ["tensor"], "transpose", ) self.InferTensorRunAndCompare(model) # Testing with axes defined brew.transpose( model, ["tensor"], "transpose", axes=np.random.permutation(5) ) return self.InferTensorRunAndCompare(model) def testShapeInferencePad(self): model = model_helper.ModelHelper(name="padtest") model.PadImage("data", 'padded', pad_t=100, pad_l=37, pad_b=28, pad_r=20, mode="constant", order="NCHW") workspace.FeedBlob( "data", np.random.rand(16, 3, 228, 228).astype(np.float32), ) self.InferTensorRunAndCompare(model) def testShapeInferenceTwoClass(self): model = model_helper.ModelHelper(name="twoclass") model.MakeTwoClass("v", "v2") workspace.FeedBlob("v", np.random.rand(32).astype(np.float32)) self.InferTensorRunAndCompare(model) def testShapeInferencePadZero(self): model = model_helper.ModelHelper(name="padtest") model.PadImage("data", 'padded', pad=0, mode="constant", order="NCHW") workspace.FeedBlob( "data", np.random.rand(16, 3, 228, 228).astype(np.float32), ) self.InferTensorRunAndCompare(model) def testShapeInferenceMatMul(self): model = model_helper.ModelHelper(name="test_model") model.MatMul(["x", "y"], "MatMul") workspace.FeedBlob("x", np.random.rand(10, 5).astype(np.float32)) workspace.FeedBlob("y", np.random.rand(5, 10).astype(np.float32)) self.InferTensorRunAndCompare(model) def testShapeInferenceSoftmaxWithLoss(self): model = model_helper.ModelHelper(name="test_model") model.SoftmaxWithLoss( ["logits", "labels"], ["softmax", "loss"], ) # 2D Shape of [batch_size, num_classes] workspace.FeedBlob( "logits", np.random.rand(4, 3).astype(np.float32), ) # Shape of size batch_size with all values [0, num_classes) workspace.FeedBlob( "labels", np.random.randint(low=0, high=3, size=(4, 1)).astype(np.int32), ) self.InferTensorRunAndCompare(model) # Testing with 1D labels arg workspace.FeedBlob( "logits", np.random.rand(4, 3).astype(np.float32), ) workspace.FeedBlob( "labels", np.random.randint(low=0, high=3, size=4).astype(np.int32), ) self.InferTensorRunAndCompare(model) # Testing with weight_tensor model.SoftmaxWithLoss( ["logits", "labels", "weight_tensor"], ["softmax", "loss"], ) workspace.FeedBlob( "logits", np.random.rand(4, 3).astype(np.float32), ) workspace.FeedBlob( "labels", np.random.randint(low=0, high=3, size=4).astype(np.int32), ) workspace.FeedBlob( "weight_tensor", np.random.rand(4).astype(np.float32), ) self.InferTensorRunAndCompare(model) # Test spatial model model = model_helper.ModelHelper(name="test_model") workspace.FeedBlob( "img", np.random.rand(32, 19, 33, 28).astype(np.float32) ) workspace.FeedBlob( "img_labels", (np.random.rand(32, 33, 28) * 19).astype(np.int32) ) model.SoftmaxWithLoss( ["img", "img_labels"], ["softmax_img", "loss"], spatial=1 ) self.InferTensorRunAndCompare(model) def testShapeInferenceIm2Col(self): # Test with NCHW model = model_helper.ModelHelper(name="test_model") model.Im2Col("X", "Y", pad=1, kernel=4, dilation=2, stride=2, order="NCHW") workspace.FeedBlob( "X", np.random.rand(16, 3, 228, 228).astype(np.float32), ) self.InferTensorRunAndCompare(model) # Test with NHWC model = model_helper.ModelHelper(name="test_model") model.Im2Col("X", "Y", pad=1, kernel=4, dilation=2, stride=2, order="NHWC") workspace.FeedBlob( "X", np.random.rand(16, 228, 228, 3).astype(np.float32), ) self.InferTensorRunAndCompare(model) # Test with different width and height model = model_helper.ModelHelper(name="test_model") model.Im2Col("X", "Y", pad=1, kernel_h=8, kernel_w=4, dilation=2, stride=2) workspace.FeedBlob( "X", np.random.rand(16, 3, 228, 114).astype(np.float32), ) self.InferTensorRunAndCompare(model) def testShapeInferenceTile(self): m = model_helper.ModelHelper(name="test_model") workspace.FeedBlob( "tensor", np.random.rand(4, 2, 3, 3, 5).astype(np.float32) ) # Testing with axes undefined for i in range(0, 4): m.net.Tile( "tensor", "tiled_tensor_{}".format(i), tiles=5, axis=i) self.InferTensorRunAndCompare(m) def testShapeInferenceFlatten(self): model = model_helper.ModelHelper(name="test_model") model.FlattenToVec("X", "FlatVec") workspace.FeedBlob("X", np.random.rand(17, 5, 13).astype(np.float32)) self.InferTensorRunAndCompare(model) model = model_helper.ModelHelper(name="test_model") model.Flatten("X", "Flat") workspace.FeedBlob("X", np.random.rand(17, 5, 13).astype(np.float32)) self.InferTensorRunAndCompare(model) def testShapeInferenceReshape(self): model = model_helper.ModelHelper(name="test_model") model.Reshape("X", ["Reshaped", "Old_Shape"], shape=[8, 0, -1, 2]) workspace.FeedBlob("X", np.random.rand(4, 26, 32).astype(np.float32)) self.InferTensorRunAndCompare(model) def testCast(self): model = model_helper.ModelHelper(name="test_model") types = [ ('bool', np.bool, caffe2_pb2.TensorProto.BOOL), #('byte', None, caffe2_pb2.TensorProto.BYTE), ('int8', np.int8, caffe2_pb2.TensorProto.INT8), ('uint8', np.uint8, caffe2_pb2.TensorProto.UINT8), ('int16', np.int16, caffe2_pb2.TensorProto.INT16), ('uint16', np.uint16, caffe2_pb2.TensorProto.UINT16), #('float16', np.float16, caffe2_pb2.TensorProto.FLOAT16), ('int32', np.int32, caffe2_pb2.TensorProto.INT32), ('float', np.float32, caffe2_pb2.TensorProto.FLOAT), ('int64', np.int64, caffe2_pb2.TensorProto.INT64), ('double', np.float64, caffe2_pb2.TensorProto.DOUBLE), #('string', None, caffe2_pb2.TensorProto.STRING), ] for (xstr, xnp, _) in types: xname = 'X%s' % xstr workspace.FeedBlob(xname, np.random.rand(1).astype(xnp)) for (ystr, _, yc2) in types: yname = 'Y%s_to_%s' % (xstr, ystr) model.Cast(xname, yname, to=yc2) self.InferTensorRunAndCompare(model) def testShapeInferenceRoiPool(self): for is_test in [True, False]: model = model_helper.ModelHelper(name="test_model") outputs = ['Y'] if is_test else ['Y', 'argmaxes'] model.net.RoIPool( ['X', 'R'], outputs, pooled_h=4, pooled_w=5, is_test=is_test) workspace.FeedBlob( "X", np.random.rand(100, 3, 4, 5).astype(np.float32)) workspace.FeedBlob( "R", np.random.rand(2, 5).astype(np.float32)) self.InferTensorRunAndCompare(model) def InferTensorRunAndCompare(self, model): ''' Runs shape inference, and then the model to check that the inferred shapes agree with the actual ones ''' (shapes, types) = workspace.InferShapesAndTypes( [model.param_init_net, model.net], ) # .. Create net workspace.RunNetOnce(model.param_init_net) workspace.CreateNet(model.net, True) workspace.RunNet(model.Proto().name) # ... and then check the shapes mismatch correct_shapes = {} correct_types = {} for b in workspace.Blobs(): arr = workspace.FetchBlob(b) correct_shapes[b] = arr.shape if type(arr) is np.ndarray: if arr.dtype == np.dtype('float32'): correct_types[b] = caffe2_pb2.TensorProto.FLOAT elif arr.dtype == np.dtype('int32'): correct_types[b] = caffe2_pb2.TensorProto.INT32 # BYTE # STRING elif arr.dtype == np.dtype('bool'): correct_types[b] = caffe2_pb2.TensorProto.BOOL elif arr.dtype == np.dtype('uint8'): correct_types[b] = caffe2_pb2.TensorProto.UINT8 elif arr.dtype == np.dtype('int8'): correct_types[b] = caffe2_pb2.TensorProto.INT8 elif arr.dtype == np.dtype('uint16'): correct_types[b] = caffe2_pb2.TensorProto.UINT16 elif arr.dtype == np.dtype('int16'): correct_types[b] = caffe2_pb2.TensorProto.INT16 elif arr.dtype == np.dtype('int64'): correct_types[b] = caffe2_pb2.TensorProto.INT64 elif arr.dtype == np.dtype('float16'): correct_types[b] = caffe2_pb2.TensorProto.FLOAT16 elif arr.dtype == np.dtype('float64'): correct_types[b] = caffe2_pb2.TensorProto.DOUBLE else: correct_types[b] = "unknown {}".format(arr.dtype) else: correct_types[b] = str(type(arr)) for b in correct_shapes: self.assertTrue( np.array_equal( np.array(shapes[b]).astype(np.int32), np.array(correct_shapes[b]).astype(np.int32) ), "Shape {} mismatch: {} vs. {}".format( b, shapes[b], correct_shapes[b] ) ) self.assertFalse( b not in types and b in correct_types, "Type for {} not defined".format(b), ) self.assertEqual( types[b], correct_types[b], "Type {} mismatch: {} vs. {}".format( b, types[b], correct_types[b], ) ) 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 TestSoftmaxOps(hu.HypothesisTestCase): @given(n=st.sampled_from([2, 4, 71, 103]), D=st.sampled_from([4, 8, 64, 79, 256, 333]), engine=st.sampled_from([None, 'CUDNN']), **hu.gcs) def test_softmax(self, n, D, engine, gc, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability X = np.random.rand(n, D).astype(np.float32) X = X + 1e-2 # Reference implementation of cross entropy with soft labels def label_softmax(X): probs = np.zeros((n, D)) rowmax = np.zeros(n) for i in range(n): rowmax[i] = max(X[i, ]) # We need to subtract the max to avoid numerical issues probs[i] = X[i] - rowmax[i] exps = np.exp(probs[i, ]) norm = sum(exps) probs[i, ] = exps / norm return [probs] op = core.CreateOperator( "Softmax", ["X"], ["probs"], engine=engine ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X], reference=label_softmax, ) @given(n=st.sampled_from([2, 4, 71, 103, 555, 751, 1201]), D=st.sampled_from([4, 8, 64, 79, 256, 333, 1000]), engine=st.sampled_from([None, 'CUDNN']), **hu.gcs) def test_softmax_grad(self, n, D, engine, gc, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability Y = np.random.rand(n, D).astype(np.float32) dY = np.random.rand(n, D).astype(np.float32) Y = Y + 1e-2 # Reference implementation of cross entropy with soft labels def label_softmax_grad(X, dY): dX = Y * 0.0 for i in range(n): d = np.dot(Y[i, :], dY[i, :]) dX[i, :] = Y[i, :] * (dY[i, :] - d) return [dX] op = core.CreateOperator( "SoftmaxGradient", ["Y", "dY"], ["dX"], engine=engine ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[Y, dY], reference=label_softmax_grad, ) @given(axis=st.integers(min_value=1, max_value=4), engine=st.sampled_from([None, 'CUDNN']), **hu.gcs) def test_softmax_axis(self, axis, engine, gc, dc): np.random.seed(1) X = np.random.randn(1, 2, 3, 2, 1).astype(np.float32) X = X + 1e-2 def prod(xs): p = 1 for x in xs: p *= x return p N = prod(list(X.shape)[:axis]) D = prod(list(X.shape)[axis:]) # Reference implementation of cross entropy with soft labels def label_softmax(X): X_ = X.reshape(N, D) probs = np.zeros((N, D)) rowmax = np.zeros(N) for i in range(N): rowmax[i] = max(X_[i, ]) # We need to subtract the max to avoid numerical issues probs[i] = X_[i] - rowmax[i] exps = np.exp(probs[i, ]) norm = sum(exps) probs[i, ] = exps / norm return [probs.reshape(*X.shape)] op = core.CreateOperator( "Softmax", ["X"], ["probs"], axis=axis, engine=engine ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X], reference=label_softmax, ) self.assertGradientChecks( gc, op, [X], 0, [0], stepsize=1e-4, threshold=1e-2) @given(n=st.integers(2, 10), D=st.integers(4, 16), only_loss=st.booleans(), **hu.gcs) def test_softmax_with_loss(self, n, D, gc, only_loss, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability X = np.random.rand(n, D).astype(np.float32) X = X + 1e-2 # Initialize label label = (np.random.rand(n) * D).astype(np.int32) # Reference implementation of cross entropy with soft labels def label_softmax_crossent(X, label): probs = np.zeros((n, D)) rowmax = np.zeros(n) for i in range(n): rowmax[i] = max(X[i, ]) # We need to subtract the max to avoid numerical issues probs[i] = X[i] - rowmax[i] exps = np.exp(probs[i, ]) norm = sum(exps) probs[i, ] = exps / norm label_xent = [-np.log(max(probs[i][label[i]], 1e-20)) for i in range(n)] avgloss = np.sum(label_xent) / float(n) return (probs, avgloss) op = core.CreateOperator( "SoftmaxWithLoss", ["X", "label"], ["probs", "avgloss"], only_loss=only_loss, ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, label], reference=label_softmax_crossent, ) self.assertGradientChecks( gc, op, [X, label], 0, [1], stepsize=1e-4, threshold=1e-2) @given( n=st.integers(2, 5), D=st.integers(4, 16), only_loss=st.booleans(), label_prob=st.booleans(), **hu.gcs ) def test_softmax_with_loss_axis_2( self, n, D, only_loss, label_prob, gc, dc ): X = np.random.rand(n, n, D).astype(np.float32) X = X + 1e-2 if label_prob: label = np.random.rand(n, n, D).astype(np.float32) label /= label.sum(axis=2, keepdims=True) else: label = (np.random.rand(n, n) * D).astype(np.int32) # Reference implementation of cross entropy with soft labels def label_softmax_crossent(X, label): probs = np.zeros((n, n, D)) rowmax = np.zeros((n, n)) for i in range(n): for j in range(n): rowmax[i, j] = max(X[i, j, ]) # We need to subtract the max to avoid numerical issues probs[i, j] = X[i, j] - rowmax[i, j] exps = np.exp(probs[i, j, ]) norm = sum(exps) probs[i, j, ] = exps / norm label_xent = 0 for i in range(n): for j in range(n): if label_prob: for k in range(D): label_xent += ( -np.log(max(probs[i, j, k], 1e-20)) * label[i, j, k] ) else: label_xent += -np.log(max(probs[i, j, label[i, j]], 1e-20)) avgloss = label_xent / float(n * n) return (probs, avgloss) op = core.CreateOperator( "SoftmaxWithLoss", ["X", "label"], ["probs", "avgloss"], only_loss=only_loss, label_prob=label_prob, axis=2, ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, label], reference=label_softmax_crossent, ) self.assertGradientChecks( gc, op, [X, label], 0, [1], stepsize=1e-4, threshold=1e-2) @unittest.skipIf(not workspace.has_gpu_support, "No gpu support") @given(**hu.gcs_gpu_only) def test_softmax_with_loss_large(self, gc, dc): for n in [64, 512]: for D in [1000, 5000, 50000]: # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability X = np.random.rand(n, D).astype(np.float32) X = X + 1e-2 # Initialize label label = (np.random.rand(n) * D).astype(np.int32) # Reference implementation of cross entropy with soft labels def label_softmax_crossent(X, label): probs = np.zeros((n, D)) rowmax = np.zeros(n) for i in range(n): rowmax[i] = max(X[i, ]) # We need to subtract the max to avoid numerical issues probs[i] = X[i] - rowmax[i] exps = np.exp(probs[i, ]) norm = sum(exps) probs[i, ] = exps / norm label_xent = [-np.log(max(probs[i][label[i]], 1e-20)) for i in range(n)] avgloss = np.sum(label_xent) / float(n) return (probs, avgloss) op = core.CreateOperator( "SoftmaxWithLoss", ["X", "label"], ["probs", "avgloss"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, label], reference=label_softmax_crossent, ) @given(n=st.integers(2, 10), D=st.integers(4, 16), **hu.gcs) def test_softmax_with_loss_label_prob(self, n, D, gc, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability X = np.random.rand(n, D).astype(np.float32) X = X + 1e-2 # Initialize label label = np.random.rand(D, n).astype(np.float32) # normalize labels to sum to 1 label /= np.sum(label, axis=0) label = label.transpose() # Reference implementation of cross entropy with soft labels def label_softmax_crossent(X, label): probs = np.zeros((n, D)) rowmax = np.zeros(n) for i in range(n): rowmax[i] = max(X[i, ]) # We need to subtract the max to avoid numerical issues probs[i] = X[i] - rowmax[i] exps = np.exp(probs[i, ]) norm = sum(exps) probs[i, ] = exps / norm label_xent = np.zeros(X.shape) for i in range(n): for j in range(D): label_xent[i][j] = -np.log( max(probs[i, j], 1e-20)) * label[i, j] avgloss = np.sum(label_xent) / float(n) return (probs, avgloss) op = core.CreateOperator( "SoftmaxWithLoss", ["X", "label"], ["probs", "avgloss"], label_prob=1 ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, label], reference=label_softmax_crossent, ) self.assertGradientChecks( gc, op, [X, label], 0, [1], stepsize=1e-4, threshold=1e-2) @given(n=st.integers(2, 10), D=st.integers(4, 16), only_loss=st.booleans(), **hu.gcs) def test_softmax_with_loss_weighted(self, n, D, only_loss, gc, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability X = np.random.rand(n, D).astype(np.float32) X = X + 1e-2 # Initialize label label = (np.random.rand(n) * D).astype(np.int32) # Init weights (weight by sample) weights = np.random.rand(n).astype(np.float32) # Reference implementation of cross entropy with soft labels def label_softmax_crossent_weighted(X, label, weights): probs = np.zeros((n, D)) rowmax = np.zeros(n) for i in range(n): rowmax[i] = max(X[i, ]) # We need to subtract the max to avoid numerical issues probs[i] = X[i] - rowmax[i] exps = np.exp(probs[i, ]) norm = sum(exps) probs[i, ] = exps / norm label_xent = [-weights[i] * np.log(max(probs[i][label[i]], 1e-20)) for i in range(n)] avgloss = np.sum(label_xent) / sum(weights) return (probs, avgloss) op = core.CreateOperator( "SoftmaxWithLoss", ["X", "label", "weights"], ["probs", "avgloss"], only_loss=only_loss, ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, label, weights], reference=label_softmax_crossent_weighted, ) self.assertGradientChecks( gc, op, [X, label, weights], 0, [1], stepsize=1e-4, threshold=1e-2) @given(n=st.integers(2, 10), D=st.integers(4, 16), **hu.gcs) def test_softmax_with_loss_label_prob_weighted(self, n, D, gc, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability X = np.random.rand(n, D).astype(np.float32) X = X + 1e-2 # Initialize label label = np.random.rand(D, n).astype(np.float32) # normalize labels to sum to 1 label /= np.sum(label, axis=0) label = label.transpose() # Init weights (weight by sample) weights = np.random.rand(n).astype(np.float32) # Reference implementation of cross entropy with soft labels def label_softmax_crossent_weighted(X, label, weights): probs = np.zeros((n, D)) rowmax = np.zeros(n) for i in range(n): rowmax[i] = max(X[i, ]) # We need to subtract the max to avoid numerical issues probs[i] = X[i] - rowmax[i] exps = np.exp(probs[i, ]) norm = sum(exps) probs[i, ] = exps / norm label_xent = np.zeros(X.shape) for i in range(n): for j in range(D): label_xent[i][j] = -np.log( max(probs[i, j], 1e-20)) * label[i, j] * weights[i] avgloss = np.sum(label_xent) / sum(weights) return (probs, avgloss) op = core.CreateOperator( "SoftmaxWithLoss", ["X", "label", "weights"], ["probs", "avgloss"], label_prob=1 ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, label, weights], reference=label_softmax_crossent_weighted, ) self.assertGradientChecks( gc, op, [X, label, weights], 0, [1], stepsize=1e-4, threshold=1e-2) @given(n=st.integers(2, 5), D=st.integers(2, 4), weighted=st.booleans(), **hu.gcs) def test_spatial_softmax_with_loss(self, n, D, weighted, gc, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability W = 18 H = 12 X = np.random.rand(n, D, H, W).astype(np.float32) X = X + 1e-2 weighted = True weights = None if weighted: weights = np.random.rand(n, H, W).astype(np.float32) # Initialize label. Some of the labels are (-1), i.e "DONT CARE" label = (np.random.rand(n, H, W) * (D + 1)).astype(np.int32) - 1 def label_softmax_crossent_spatial(X, label, weights=None): probs = np.zeros((n, D, H, W)) rowmax = np.zeros((n, H, W)) label_xent = np.zeros((n, H, W)) for i in range(n): for x in range(W): for y in range(H): rowmax[i, y, x] = max(X[i, :, y, x]) # We need to subtract the max to avoid numerical issues probs[i, :, y, x] = X[i, :, y, x] - rowmax[i, y, x] exps = np.exp(probs[i, :, y, x]) probs[i, :, y, x] = exps / sum(exps) label_xent[:, y, x] = \ [-np.log(max(probs[j, label[i, y, x], y, x], 1e-20)) for j in range(n)] total_xent = 0.0 total_weight = 0.0 for y in range(H): for x in range(W): for i in range(n): l = label[i, y, x] if (l != (-1)): w = 1.0 if weights is None else weights[i, y, x] total_xent += \ -np.log(max(probs[i, l, y, x], 1e-20)) * w total_weight += w print("Total weight {}".format(total_weight)) return (probs, total_xent / total_weight) op = core.CreateOperator( "SoftmaxWithLoss", ["X", "label"] + ([] if weights is None else ["weights"]), ["probs", "avgloss"], spatial=1 ) inputs = [X, label] + ([] if weights is None else [weights]) self.assertReferenceChecks( device_option=gc, op=op, inputs=inputs, reference=label_softmax_crossent_spatial, ) self.assertGradientChecks( gc, op, inputs, 0, [1], stepsize=1e-4, threshold=1e-2) @given(n=st.integers(4, 5), D=st.integers(3, 4), weighted=st.booleans(), **hu.gcs) def test_spatial_softmax_with_loss_allignore(self, n, D, weighted, gc, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability W = 18 H = 12 X = np.random.rand(n, D, H, W).astype(np.float32) X = X + 1e-2 weighted = True weights = None if weighted: weights = np.random.rand(n, H, W).astype(np.float32) # Initialize label. All labels as "DONT CARE" label = np.zeros((n, H, W)).astype(np.int32) - 1 print(label) def label_softmax_crossent_spatial(X, label, weights=None): probs = np.zeros((n, D, H, W)) rowmax = np.zeros((n, H, W)) label_xent = np.zeros((n, H, W)) for i in range(n): for x in range(W): for y in range(H): rowmax[i, y, x] = max(X[i, :, y, x]) # We need to subtract the max to avoid numerical issues probs[i, :, y, x] = X[i, :, y, x] - rowmax[i, y, x] exps = np.exp(probs[i, :, y, x]) probs[i, :, y, x] = exps / sum(exps) label_xent[:, y, x] = \ [-np.log(max(probs[j, label[i, y, x], y, x], 1e-20)) for j in range(n)] return (probs, 0.0) op = core.CreateOperator( "SoftmaxWithLoss", ["X", "label"] + ([] if weights is None else ["weights"]), ["probs", "avgloss"], spatial=1 ) inputs = [X, label] + ([] if weights is None else [weights]) self.assertReferenceChecks( device_option=gc, op=op, inputs=inputs, reference=label_softmax_crossent_spatial, ) @given(n=st.integers(4, 5), D=st.integers(3, 4), weighted=st.booleans(), **hu.gcs) def test_softmax_with_loss_zero_weight(self, n, D, weighted, gc, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability X = np.random.rand(n, D).astype(np.float32) X = X + 1e-2 weights = np.zeros(n).astype(np.float32) # Initialize label label = (np.random.rand(n) * D).astype(np.int32) def label_softmax_crossent(X, label, weights=None): probs = np.zeros((n, D)) rowmax = np.zeros((n)) for i in range(n): rowmax[i] = max(X[i, ]) # We need to subtract the max to avoid numerical issues probs[i] = X[i] - rowmax[i] exps = np.exp(probs[i, ]) norm = sum(exps) probs[i, ] = exps / norm return (probs, 0.0) op = core.CreateOperator( "SoftmaxWithLoss", ["X", "label", "weights"], ["probs", "avgloss"] ) inputs = [X, label] + ([] if weights is None else [weights]) self.assertReferenceChecks( device_option=gc, op=op, inputs=inputs, reference=label_softmax_crossent, ) @unittest.skipIf(not workspace.has_gpu_support, "No gpu support") def test_compare_cpugpu(self): ''' Additional test that checks CPU and GPU returns same values with larger examples. This is mainly to test the more complex GPU implementation is correct. ''' from caffe2.proto import caffe2_pb2 for _j in range(3): gpuop = core.CreateOperator( "SoftmaxWithLoss", ["X_gpu", "label_gpu"], ["probs_gpu", "avgloss_gpu"], spatial=1, device_option=core.DeviceOption(caffe2_pb2.CUDA, 0) ) cpuop = core.CreateOperator( "SoftmaxWithLoss", ["X_cpu", "label_cpu"], ["probs_cpu", "avgloss_cpu"], spatial=1, device_option=core.DeviceOption(caffe2_pb2.CPU) ) n = 8 D = 4 W = 64 + int(np.random.rand(1) * 1024) H = 64 + int(np.random.rand(1) * 1024) print("W: {} H: {}".format(W, H)) X = np.random.rand(n, D, H, W).astype(np.float32) X = X + 1e-2 # Initialize label. Some of the labels are (-1), i.e "DONT CARE" label = (np.random.rand(n, H, W) * (D + 1)).astype(np.int32) - 1 gpu0 = core.DeviceOption(caffe2_pb2.CUDA, 0) workspace.FeedBlob("X_cpu", X) workspace.FeedBlob("label_cpu", label) workspace.FeedBlob("X_gpu", X, device_option=gpu0) workspace.FeedBlob("label_gpu", label, device_option=gpu0) workspace.RunOperatorOnce(gpuop) workspace.RunOperatorOnce(cpuop) probs_gpu = workspace.FetchBlob("probs_gpu") probs_cpu = workspace.FetchBlob("probs_cpu") loss_gpu = workspace.FetchBlob("avgloss_gpu") loss_cpu = workspace.FetchBlob("avgloss_cpu") np.testing.assert_allclose(probs_gpu, probs_cpu, rtol=1e-4) np.testing.assert_allclose(loss_gpu, loss_cpu, rtol=1e-1) if __name__ == "__main__": import unittest import random random.seed(2603) 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 TestElementwiseOps(hu.HypothesisTestCase): @given(n=st.integers(2, 10), m=st.integers(4, 6), d=st.integers(2, 3), **hu.gcs) def test_div(self, n, m, d, gc, dc): X = np.random.rand(n, m, d).astype(np.float32) Y = np.random.rand(n, m, d).astype(np.float32) + 5.0 def div_op(X, Y): return [np.divide(X, Y)] op = core.CreateOperator( "Div", ["X", "Y"], ["Z"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, Y], reference=div_op, ) self.assertGradientChecks( gc, op, [X, Y], 0, [0], stepsize=1e-4, threshold=1e-2) @given(n=st.integers(5, 6), m=st.integers(4, 6), **hu.gcs) def test_log(self, n, m, gc, dc): X = np.random.rand(n, m).astype(np.float32) + 1.0 def log_op(X): return [np.log(X)] op = core.CreateOperator( "Log", ["X"], ["Z"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X], reference=log_op, ) self.assertGradientChecks( gc, op, [X], 0, [0], stepsize=1e-4, threshold=1e-2) @given(n=st.integers(5, 6), m=st.integers(4, 6), **hu.gcs) def test_sqr(self, n, m, gc, dc): X = np.random.rand(n, m).astype(np.float32) def sqr_op(X): return [np.square(X)] op = core.CreateOperator( "Sqr", ["X"], ["Z"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X], reference=sqr_op, ) self.assertGradientChecks( gc, op, [X], 0, [0], stepsize=1e-4, threshold=1e-2) @given(n=st.integers(5, 6), m=st.integers(4, 6), **hu.gcs) def test_sigmoid(self, n, m, gc, dc): X = np.random.rand(n, m).astype(np.float32) def sigmoid(X): return [1. / (1. + np.exp(-X))] op = core.CreateOperator( "Sigmoid", ["X"], ["Z"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X], reference=sigmoid, ) self.assertGradientChecks( gc, op, [X], 0, [0], stepsize=1e-4, threshold=1e-2)
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 TestNormalizeOp(hu.HypothesisTestCase): @given(X=hu.tensor(min_dim=2, max_dim=2, elements=st.floats(min_value=0.5, max_value=1.0)), **hu.gcs) def test_normalize(self, X, gc, dc): op = core.CreateOperator("Normalize", "X", "Y") def ref_normalize(X): x_normed = X / ( np.sqrt((X**2).sum(-1))[:, np.newaxis] + np.finfo(X.dtype).tiny) return (x_normed,) self.assertReferenceChecks(gc, op, [X], ref_normalize) self.assertDeviceChecks(dc, op, [X], [0]) 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 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 TestMarginRankingCriterion(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_margin_ranking_criterion(self, N, seed, margin, gc, dc): np.random.seed(seed) X1 = np.random.randn(N).astype(np.float32) X2 = np.random.randn(N).astype(np.float32) Y = np.random.choice([-1, 1], size=N).astype(np.int32) op = core.CreateOperator( "MarginRankingCriterion", ["X1", "X2", "Y"], ["loss"], margin=margin) def ref_cec(X1, X2, Y): result = np.maximum(-Y * (X1 - X2) + margin, 0) return (result, ) inputs = [X1, X2, Y] # This checks the op implementation against a reference function in # python. self.assertReferenceChecks(gc, op, inputs, 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, inputs, [0]) # Make singular points less sensitive X1[np.abs(margin - Y * (X1 - X2)) < 0.1] += 0.1 X2[np.abs(margin - Y * (X1 - X2)) < 0.1] -= 0.1 # Check dX1 self.assertGradientChecks(gc, op, inputs, 0, [0]) # Check dX2 self.assertGradientChecks(gc, op, inputs, 1, [0]) if __name__ == "__main__": import unittest unittest.main()
## @package download # Module caffe2.python.models.download from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import os import sys import signal import re # Import urllib try: import urllib.error as urlliberror import urllib.request as urllib HTTPError = urlliberror.HTTPError URLError = urlliberror.URLError except ImportError: import urllib2 as urllib HTTPError = urllib.HTTPError URLError = urllib.URLError DOWNLOAD_BASE_URL = "https://s3.amazonaws.com/caffe2/models/" DOWNLOAD_COLUMNS = 70 # Don't let urllib hang up on big downloads def signalHandler(signal, frame): print("Killing download...") exit(0) signal.signal(signal.SIGINT, signalHandler) def deleteDirectory(top_dir): for root, dirs, files in os.walk(top_dir, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) os.rmdir(top_dir) def progressBar(percentage): full = int(DOWNLOAD_COLUMNS * percentage / 100) bar = full * "#" + (DOWNLOAD_COLUMNS - full) * " " sys.stdout.write(u"\u001b[1000D[" + bar + "] " + str(percentage) + "%") sys.stdout.flush() def downloadFromURLToFile(url, filename): try: print("Downloading from {url}".format(url=url)) response = urllib.urlopen(url) size = int(response.info().getheader('Content-Length').strip()) downloaded_size = 0 chunk = min(size, 8192) print("Writing to {filename}".format(filename=filename)) progressBar(0) with open(filename, "wb") as local_file: while True: data_chunk = response.read(chunk) if not data_chunk: break local_file.write(data_chunk) downloaded_size += len(data_chunk) progressBar(int(100 * downloaded_size / size)) print("") # New line to fix for progress bar except HTTPError as e: raise Exception("Could not download model. [HTTP Error] {code}: {reason}." .format(code=e.code, reason=e.reason)) except URLError as e: raise Exception("Could not download model. [URL Error] {reason}." .format(reason=e.reason)) except Exception as e: raise e def getURLFromName(name, filename): return "{base_url}{name}/{filename}".format(base_url=DOWNLOAD_BASE_URL, name=name, filename=filename) def downloadModel(model, args): # Figure out where to store the model model_folder = '{folder}'.format(folder=model) dir_path = os.path.dirname(os.path.realpath(__file__)) if args.install: model_folder = '{dir_path}/{folder}'.format(dir_path=dir_path, folder=model) # Check if that folder is already there if os.path.exists(model_folder) and not os.path.isdir(model_folder): if not args.force: raise Exception("Cannot create folder for storing the model,\ there exists a file of the same name.") else: print("Overwriting existing file! ({filename})" .format(filename=model_folder)) os.remove(model_folder) if os.path.isdir(model_folder): if not args.force: response = "" query = "Model already exists, continue? [y/N] " try: response = raw_input(query) except NameError: response = input(query) if response.upper() == 'N' or not response: print("Cancelling download...") exit(0) print("Overwriting existing folder! ({filename})".format(filename=model_folder)) deleteDirectory(model_folder) # Now we can safely create the folder and download the model os.makedirs(model_folder) for f in ['predict_net.pb', 'init_net.pb']: try: downloadFromURLToFile(getURLFromName(model, f), '{folder}/{f}'.format(folder=model_folder, f=f)) except Exception as e: print("Abort: {reason}".format(reason=str(e))) print("Cleaning up...") deleteDirectory(model_folder) exit(0) if args.install: os.symlink("{folder}/__sym_init__.py".format(folder=dir_path), "{folder}/__init__.py".format(folder=model_folder)) def validModelName(name): invalid_names = ['__init__'] if name in invalid_names: return False if not re.match("^[a-zA-Z_]+$", name): return False return True if __name__ == "__main__": parser = argparse.ArgumentParser( description='Download or install pretrained models.') parser.add_argument('model', nargs='+', help='Model to download/install.') parser.add_argument('-i', '--install', action='store_true', help='Install the model.') parser.add_argument('-f', '--force', action='store_true', help='Force a download/installation.') args = parser.parse_args() for model in args.model: if validModelName(model): downloadModel(model, args) else: print("'{model}' is not a valid model name.".format(model))
## @package resnet # Module caffe2.python.models.resnet from __future__ import absolute_import from __future__ import division from __future__ import print_function from caffe2.python import brew ''' Utility for creating ResNets See "Deep Residual Learning for Image Recognition" by He, Zhang et. al. 2015 ''' class ResNetBuilder(): ''' Helper class for constructing residual blocks. ''' def __init__(self, model, prev_blob, no_bias, is_test, spatial_bn_mom=0.9): self.model = model self.comp_count = 0 self.comp_idx = 0 self.prev_blob = prev_blob self.is_test = is_test self.spatial_bn_mom = spatial_bn_mom self.no_bias = 1 if no_bias else 0 def add_conv(self, in_filters, out_filters, kernel, stride=1, pad=0): self.comp_idx += 1 self.prev_blob = brew.conv( self.model, self.prev_blob, 'comp_%d_conv_%d' % (self.comp_count, self.comp_idx), in_filters, out_filters, weight_init=("MSRAFill", {}), kernel=kernel, stride=stride, pad=pad, no_bias=self.no_bias, ) return self.prev_blob def add_relu(self): self.prev_blob = brew.relu( self.model, self.prev_blob, self.prev_blob, # in-place ) return self.prev_blob def add_spatial_bn(self, num_filters): self.prev_blob = brew.spatial_bn( self.model, self.prev_blob, 'comp_%d_spatbn_%d' % (self.comp_count, self.comp_idx), num_filters, epsilon=1e-3, momentum=self.spatial_bn_mom, is_test=self.is_test, ) return self.prev_blob ''' Add a "bottleneck" component as decribed in He et. al. Figure 3 (right) ''' def add_bottleneck( self, input_filters, # num of feature maps from preceding layer base_filters, # num of filters internally in the component output_filters, # num of feature maps to output down_sampling=False, spatial_batch_norm=True, ): self.comp_idx = 0 shortcut_blob = self.prev_blob # 1x1 self.add_conv( input_filters, base_filters, kernel=1, stride=1 ) if spatial_batch_norm: self.add_spatial_bn(base_filters) self.add_relu() # 3x3 (note the pad, required for keeping dimensions) self.add_conv( base_filters, base_filters, kernel=3, stride=(1 if down_sampling is False else 2), pad=1 ) if spatial_batch_norm: self.add_spatial_bn(base_filters) self.add_relu() # 1x1 last_conv = self.add_conv(base_filters, output_filters, kernel=1) if spatial_batch_norm: last_conv = self.add_spatial_bn(output_filters) # Summation with input signal (shortcut) # If we need to increase dimensions (feature maps), need to # do do a projection for the short cut if (output_filters > input_filters): shortcut_blob = brew.conv( self.model, shortcut_blob, 'shortcut_projection_%d' % self.comp_count, input_filters, output_filters, weight_init=("MSRAFill", {}), kernel=1, stride=(1 if down_sampling is False else 2), no_bias=self.no_bias, ) if spatial_batch_norm: shortcut_blob = brew.spatial_bn( self.model, shortcut_blob, 'shortcut_projection_%d_spatbn' % self.comp_count, output_filters, epsilon=1e-3, momentum=self.spatial_bn_mom, is_test=self.is_test, ) self.prev_blob = brew.sum( self.model, [shortcut_blob, last_conv], 'comp_%d_sum_%d' % (self.comp_count, self.comp_idx) ) self.comp_idx += 1 self.add_relu() # Keep track of number of high level components if this ResNetBuilder self.comp_count += 1 def add_simple_block( self, input_filters, num_filters, down_sampling=False, spatial_batch_norm=True ): self.comp_idx = 0 shortcut_blob = self.prev_blob # 3x3 self.add_conv( input_filters, num_filters, kernel=3, stride=(1 if down_sampling is False else 2), pad=1 ) if spatial_batch_norm: self.add_spatial_bn(num_filters) self.add_relu() last_conv = self.add_conv(num_filters, num_filters, kernel=3, pad=1) if spatial_batch_norm: last_conv = self.add_spatial_bn(num_filters) # Increase of dimensions, need a projection for the shortcut if (num_filters != input_filters): shortcut_blob = brew.conv( self.model, shortcut_blob, 'shortcut_projection_%d' % self.comp_count, input_filters, num_filters, weight_init=("MSRAFill", {}), kernel=1, stride=(1 if down_sampling is False else 2), no_bias=self.no_bias, ) if spatial_batch_norm: shortcut_blob = brew.spatial_bn( self.model, shortcut_blob, 'shortcut_projection_%d_spatbn' % self.comp_count, num_filters, epsilon=1e-3, is_test=self.is_test, ) self.prev_blob = brew.sum( self.model, [shortcut_blob, last_conv], 'comp_%d_sum_%d' % (self.comp_count, self.comp_idx) ) self.comp_idx += 1 self.add_relu() # Keep track of number of high level components if this ResNetBuilder self.comp_count += 1 # The conv1 and final_avg kernel/stride args provide a basic mechanism for # adapting resnet50 for different sizes of input images. def create_resnet50( model, data, num_input_channels, num_labels, label=None, is_test=False, no_loss=False, no_bias=0, conv1_kernel=7, conv1_stride=2, final_avg_kernel=7, ): # conv1 + maxpool brew.conv( model, data, 'conv1', num_input_channels, 64, weight_init=("MSRAFill", {}), kernel=conv1_kernel, stride=conv1_stride, pad=3, no_bias=no_bias ) brew.spatial_bn( model, 'conv1', 'conv1_spatbn_relu', 64, epsilon=1e-3, momentum=0.1, is_test=is_test ) brew.relu(model, 'conv1_spatbn_relu', 'conv1_spatbn_relu') brew.max_pool(model, 'conv1_spatbn_relu', 'pool1', kernel=3, stride=2) # Residual blocks... builder = ResNetBuilder(model, 'pool1', no_bias=no_bias, is_test=is_test, spatial_bn_mom=0.1) # conv2_x (ref Table 1 in He et al. (2015)) builder.add_bottleneck(64, 64, 256) builder.add_bottleneck(256, 64, 256) builder.add_bottleneck(256, 64, 256) # conv3_x builder.add_bottleneck(256, 128, 512, down_sampling=True) for _ in range(1, 4): builder.add_bottleneck(512, 128, 512) # conv4_x builder.add_bottleneck(512, 256, 1024, down_sampling=True) for _ in range(1, 6): builder.add_bottleneck(1024, 256, 1024) # conv5_x builder.add_bottleneck(1024, 512, 2048, down_sampling=True) builder.add_bottleneck(2048, 512, 2048) builder.add_bottleneck(2048, 512, 2048) # Final layers final_avg = brew.average_pool( model, builder.prev_blob, 'final_avg', kernel=final_avg_kernel, stride=1, ) # Final dimension of the "image" is reduced to 7x7 last_out = brew.fc( model, final_avg, 'last_out_L{}'.format(num_labels), 2048, num_labels ) if no_loss: return last_out # If we create model for training, use softmax-with-loss if (label is not None): (softmax, loss) = model.SoftmaxWithLoss( [last_out, label], ["softmax", "loss"], ) return (softmax, loss) else: # For inference, we just return softmax return brew.softmax(model, last_out, "softmax") def create_resnet_32x32( model, data, num_input_channels, num_groups, num_labels, is_test=False ): ''' Create residual net for smaller images (sec 4.2 of He et. al (2015)) num_groups = 'n' in the paper ''' # conv1 + maxpool brew.conv( model, data, 'conv1', num_input_channels, 16, kernel=3, stride=1 ) brew.spatial_bn( model, 'conv1', 'conv1_spatbn', 16, epsilon=1e-3, is_test=is_test ) brew.relu(model, 'conv1_spatbn', 'relu1') # Number of blocks as described in sec 4.2 filters = [16, 32, 64] builder = ResNetBuilder(model, 'relu1', is_test=is_test) prev_filters = 16 for groupidx in range(0, 3): for blockidx in range(0, 2 * num_groups): builder.add_simple_block( prev_filters if blockidx == 0 else filters[groupidx], filters[groupidx], down_sampling=(True if blockidx == 0 and groupidx > 0 else False)) prev_filters = filters[groupidx] # Final layers brew.average_pool( model, builder.prev_blob, 'final_avg', kernel=8, stride=1 ) brew.fc(model, 'final_avg', 'last_out', 64, num_labels) softmax = brew.softmax(model, 'last_out', 'softmax') return softmax
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os from caffe2.proto import caffe2_pb2 def _parseFile(filename): out_net = caffe2_pb2.NetDef() # TODO(bwasti): A more robust handler for pathnames. dir_path = os.path.dirname(__file__) with open('{dir_path}/{filename}'.format(dir_path=dir_path, filename=filename), 'rb') as f: out_net.ParseFromString(f.read()) return out_net init_net = _parseFile('init_net.pb') predict_net = _parseFile('predict_net.pb')
## @package translate # Module caffe2.python.models.seq2seq.translate from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse from itertools import izip import logging import numpy as np import sys from caffe2.python import attention, core, rnn_cell, workspace from caffe2.python.models.seq2seq.beam_search import BeamSearchForwardOnly from caffe2.python.models.seq2seq.seq2seq_model_helper import Seq2SeqModelHelper import caffe2.python.models.seq2seq.seq2seq_util as seq2seq_util logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stderr)) def _weighted_sum(model, values, weight, output_name): values_weights = zip(values, [weight] * len(values)) values_weights_flattened = [x for v_w in values_weights for x in v_w] return model.net.WeightedSum( values_weights_flattened, output_name, ) class Seq2SeqModelCaffe2EnsembleDecoder(object): def scope(self, scope_name, blob_name): return ( scope_name + '/' + blob_name if scope_name is not None else blob_name ) def _build_decoder( self, model, step_model, model_params, scope, previous_tokens, timestep, fake_seq_lengths, ): attention_type = model_params['attention'] assert attention_type in ['none', 'regular'] use_attention = (attention_type != 'none') with core.NameScope(scope): encoder_embeddings = seq2seq_util.build_embeddings( model=model, vocab_size=self.source_vocab_size, embedding_size=model_params['encoder_embedding_size'], name='encoder_embeddings', freeze_embeddings=False, ) ( encoder_outputs, weighted_encoder_outputs, final_encoder_hidden_state, final_encoder_cell_state, encoder_output_dim, ) = seq2seq_util.build_embedding_encoder( model=model, encoder_params=model_params['encoder_type'], inputs=self.encoder_inputs, input_lengths=self.encoder_lengths, vocab_size=self.source_vocab_size, embeddings=encoder_embeddings, embedding_size=model_params['encoder_embedding_size'], use_attention=use_attention, num_gpus=0, scope=scope, ) with core.NameScope(scope): # [max_source_length, beam_size, encoder_output_dim] encoder_outputs = model.net.Tile( encoder_outputs, 'encoder_outputs_tiled', tiles=self.beam_size, axis=1, ) if weighted_encoder_outputs is not None: weighted_encoder_outputs = model.net.Tile( weighted_encoder_outputs, 'weighted_encoder_outputs_tiled', tiles=self.beam_size, axis=1, ) decoder_embeddings = seq2seq_util.build_embeddings( model=model, vocab_size=self.target_vocab_size, embedding_size=model_params['decoder_embedding_size'], name='decoder_embeddings', freeze_embeddings=False, ) embedded_tokens_t_prev = step_model.net.Gather( [decoder_embeddings, previous_tokens], 'embedded_tokens_t_prev', ) decoder_num_units = ( model_params['decoder_layer_configs'][0]['num_units'] ) with core.NameScope(scope): if not use_attention and final_encoder_hidden_state is not None: final_encoder_hidden_state = model.net.Tile( final_encoder_hidden_state, 'final_encoder_hidden_state_tiled', tiles=self.beam_size, axis=1, ) if not use_attention and final_encoder_cell_state is not None: final_encoder_cell_state = model.net.Tile( final_encoder_cell_state, 'final_encoder_cell_state_tiled', tiles=self.beam_size, axis=1, ) initial_states = seq2seq_util.build_initial_rnn_decoder_states( model=model, encoder_num_units=encoder_output_dim, decoder_num_units=decoder_num_units, final_encoder_hidden_state=final_encoder_hidden_state, final_encoder_cell_state=final_encoder_cell_state, use_attention=use_attention, ) if use_attention: decoder_cell = rnn_cell.LSTMWithAttentionCell( encoder_output_dim=encoder_output_dim, encoder_outputs=encoder_outputs, decoder_input_dim=model_params['decoder_embedding_size'], decoder_state_dim=decoder_num_units, name=self.scope(scope, 'decoder'), attention_type=attention.AttentionType.Regular, weighted_encoder_outputs=weighted_encoder_outputs, forget_bias=0.0, lstm_memory_optimization=False, attention_memory_optimization=True, ) decoder_output_dim = decoder_num_units + encoder_output_dim else: decoder_cell = rnn_cell.LSTMCell( name=self.scope(scope, 'decoder'), input_size=model_params['decoder_embedding_size'], hidden_size=decoder_num_units, forget_bias=0.0, memory_optimization=False, ) decoder_output_dim = decoder_num_units states_prev = step_model.net.AddExternalInputs(*[ s + '_prev' for s in decoder_cell.get_state_names() ]) _, states = decoder_cell.apply( model=step_model, input_t=embedded_tokens_t_prev, seq_lengths=fake_seq_lengths, states=states_prev, timestep=timestep, ) if use_attention: with core.NameScope(scope or ''): decoder_outputs, _ = step_model.net.Concat( [states[0], states[2]], [ 'states_and_context_combination', '_states_and_context_combination_concat_dims', ], axis=2, ) else: decoder_outputs = states[0] state_configs = [ BeamSearchForwardOnly.StateConfig( initial_value=initial_state, state_prev_link=BeamSearchForwardOnly.LinkConfig( blob=state_prev, offset=0, window=1, ), state_link=BeamSearchForwardOnly.LinkConfig( blob=state, offset=1, window=1, ), ) for initial_state, state_prev, state in zip( initial_states, states_prev, states, ) ] with core.NameScope(scope): decoder_outputs_flattened, _ = step_model.net.Reshape( [decoder_outputs], [ 'decoder_outputs_flattened', 'decoder_outputs_and_contexts_combination_old_shape', ], shape=[-1, decoder_output_dim], ) output_logits = seq2seq_util.output_projection( model=step_model, decoder_outputs=decoder_outputs_flattened, decoder_output_size=decoder_output_dim, target_vocab_size=self.target_vocab_size, decoder_softmax_size=model_params['decoder_softmax_size'], ) # [1, beam_size, target_vocab_size] output_probs = step_model.net.Softmax( output_logits, 'output_probs', ) output_log_probs = step_model.net.Log( output_probs, 'output_log_probs', ) if use_attention: attention_weights = decoder_cell.get_attention_weights() else: attention_weights = step_model.net.ConstantFill( [self.encoder_inputs], 'zero_attention_weights_tmp_1', value=0.0, ) attention_weights = step_model.net.Transpose( attention_weights, 'zero_attention_weights_tmp_2', ) attention_weights = step_model.net.Tile( attention_weights, 'zero_attention_weights_tmp', tiles=self.beam_size, axis=0, ) return ( state_configs, output_log_probs, attention_weights, ) def build_word_rewards(self, vocab_size, word_reward, unk_reward): word_rewards = np.full([vocab_size], word_reward, dtype=np.float32) word_rewards[seq2seq_util.PAD_ID] = 0 word_rewards[seq2seq_util.GO_ID] = 0 word_rewards[seq2seq_util.EOS_ID] = 0 word_rewards[seq2seq_util.UNK_ID] = word_reward + unk_reward return word_rewards def __init__( self, translate_params, ): self.models = translate_params['ensemble_models'] decoding_params = translate_params['decoding_params'] self.beam_size = decoding_params['beam_size'] assert len(self.models) > 0 source_vocab = self.models[0]['source_vocab'] target_vocab = self.models[0]['target_vocab'] for model in self.models: assert model['source_vocab'] == source_vocab assert model['target_vocab'] == target_vocab self.source_vocab_size = len(source_vocab) self.target_vocab_size = len(target_vocab) self.decoder_scope_names = [ 'model{}'.format(i) for i in range(len(self.models)) ] self.model = Seq2SeqModelHelper(init_params=True) self.encoder_inputs = self.model.net.AddExternalInput('encoder_inputs') self.encoder_lengths = self.model.net.AddExternalInput( 'encoder_lengths' ) self.max_output_seq_len = self.model.net.AddExternalInput( 'max_output_seq_len' ) fake_seq_lengths = self.model.param_init_net.ConstantFill( [], 'fake_seq_lengths', shape=[self.beam_size], value=100000, dtype=core.DataType.INT32, ) beam_decoder = BeamSearchForwardOnly( beam_size=self.beam_size, model=self.model, go_token_id=seq2seq_util.GO_ID, eos_token_id=seq2seq_util.EOS_ID, ) step_model = beam_decoder.get_step_model() state_configs = [] output_log_probs = [] attention_weights = [] for model, scope_name in izip( self.models, self.decoder_scope_names, ): ( state_configs_per_decoder, output_log_probs_per_decoder, attention_weights_per_decoder, ) = self._build_decoder( model=self.model, step_model=step_model, model_params=model['model_params'], scope=scope_name, previous_tokens=beam_decoder.get_previous_tokens(), timestep=beam_decoder.get_timestep(), fake_seq_lengths=fake_seq_lengths, ) state_configs.extend(state_configs_per_decoder) output_log_probs.append(output_log_probs_per_decoder) if attention_weights_per_decoder is not None: attention_weights.append(attention_weights_per_decoder) assert len(attention_weights) > 0 num_decoders_with_attention_blob = ( self.model.param_init_net.ConstantFill( [], 'num_decoders_with_attention_blob', value=1 / float(len(attention_weights)), shape=[1], ) ) # [beam_size, encoder_length, 1] attention_weights_average = _weighted_sum( model=step_model, values=attention_weights, weight=num_decoders_with_attention_blob, output_name='attention_weights_average', ) num_decoders_blob = self.model.param_init_net.ConstantFill( [], 'num_decoders_blob', value=1 / float(len(output_log_probs)), shape=[1], ) # [beam_size, target_vocab_size] output_log_probs_average = _weighted_sum( model=step_model, values=output_log_probs, weight=num_decoders_blob, output_name='output_log_probs_average', ) word_rewards = self.model.param_init_net.ConstantFill( [], 'word_rewards', shape=[self.target_vocab_size], value=0, ) ( self.output_token_beam_list, self.output_prev_index_beam_list, self.output_score_beam_list, self.output_attention_weights_beam_list, ) = beam_decoder.apply( inputs=self.encoder_inputs, length=self.max_output_seq_len, log_probs=output_log_probs_average, attentions=attention_weights_average, state_configs=state_configs, word_rewards=word_rewards, ) workspace.RunNetOnce(self.model.param_init_net) workspace.FeedBlob( 'word_rewards', self.build_word_rewards( vocab_size=self.target_vocab_size, word_reward=translate_params['decoding_params']['word_reward'], unk_reward=translate_params['decoding_params']['unk_reward'], ) ) workspace.CreateNet( self.model.net, input_blobs=map(str, [ self.encoder_inputs, self.encoder_lengths, self.max_output_seq_len, ]), ) logger.info('Params created: ') for param in self.model.params: logger.info(param) def load_models(self): db_reader = 'reader' for model, scope_name in izip( self.models, self.decoder_scope_names, ): params_for_current_model = [ param for param in self.model.GetAllParams() if str(param).startswith(scope_name) ] assert workspace.RunOperatorOnce(core.CreateOperator( 'CreateDB', [], [db_reader], db=model['model_file'], db_type='minidb') ), 'Failed to create db {}'.format(model['model_file']) assert workspace.RunOperatorOnce(core.CreateOperator( 'Load', [db_reader], params_for_current_model, load_all=1, add_prefix=scope_name + '/', strip_prefix='gpu_0/', )) logger.info('Model {} is loaded from a checkpoint {}'.format( scope_name, model['model_file'], )) def decode(self, numberized_input, max_output_seq_len): workspace.FeedBlob( self.encoder_inputs, np.array([ [token_id] for token_id in reversed(numberized_input) ]).astype(dtype=np.int32), ) workspace.FeedBlob( self.encoder_lengths, np.array([len(numberized_input)]).astype(dtype=np.int32), ) workspace.FeedBlob( self.max_output_seq_len, np.array([max_output_seq_len]).astype(dtype=np.int64), ) workspace.RunNetOnce(self.model.net) num_steps = max_output_seq_len score_beam_list = workspace.FetchBlob(self.output_score_beam_list) token_beam_list = ( workspace.FetchBlob(self.output_token_beam_list) ) prev_index_beam_list = ( workspace.FetchBlob(self.output_prev_index_beam_list) ) attention_weights_beam_list = ( workspace.FetchBlob(self.output_attention_weights_beam_list) ) best_indices = (num_steps, 0) for i in range(num_steps + 1): for hyp_index in range(self.beam_size): if ( ( token_beam_list[i][hyp_index][0] == seq2seq_util.EOS_ID or i == num_steps ) and ( score_beam_list[i][hyp_index][0] > score_beam_list[best_indices[0]][best_indices[1]][0] ) ): best_indices = (i, hyp_index) i, hyp_index = best_indices output = [] attention_weights_per_token = [] best_score = -score_beam_list[i][hyp_index][0] while i > 0: output.append(token_beam_list[i][hyp_index][0]) attention_weights_per_token.append( attention_weights_beam_list[i][hyp_index] ) hyp_index = prev_index_beam_list[i][hyp_index][0] i -= 1 attention_weights_per_token = reversed(attention_weights_per_token) # encoder_inputs are reversed, see get_batch func attention_weights_per_token = [ list(reversed(attention_weights))[:len(numberized_input)] for attention_weights in attention_weights_per_token ] output = list(reversed(output)) return output, attention_weights_per_token, best_score def run_seq2seq_beam_decoder(args, model_params, decoding_params): source_vocab = seq2seq_util.gen_vocab( args.source_corpus, args.unk_threshold, ) logger.info('Source vocab size {}'.format(len(source_vocab))) target_vocab = seq2seq_util.gen_vocab( args.target_corpus, args.unk_threshold, ) inversed_target_vocab = {v: k for (k, v) in target_vocab.items()} logger.info('Target vocab size {}'.format(len(target_vocab))) decoder = Seq2SeqModelCaffe2EnsembleDecoder( translate_params=dict( ensemble_models=[dict( source_vocab=source_vocab, target_vocab=target_vocab, model_params=model_params, model_file=args.checkpoint, )], decoding_params=decoding_params, ), ) decoder.load_models() for line in sys.stdin: numerized_source_sentence = seq2seq_util.get_numberized_sentence( line, source_vocab, ) translation, alignment, _ = decoder.decode( numerized_source_sentence, 2 * len(numerized_source_sentence) + 5, ) print(' '.join([inversed_target_vocab[tid] for tid in translation])) def main(): parser = argparse.ArgumentParser( description='Caffe2: Seq2Seq Translation', ) parser.add_argument('--source-corpus', type=str, default=None, help='Path to source corpus in a text file format. Each ' 'line in the file should contain a single sentence', required=True) parser.add_argument('--target-corpus', type=str, default=None, help='Path to target corpus in a text file format', required=True) parser.add_argument('--unk-threshold', type=int, default=50, help='Threshold frequency under which token becomes ' 'labeled unknown token') parser.add_argument('--use-bidirectional-encoder', action='store_true', help='Set flag to use bidirectional recurrent network ' 'in encoder') parser.add_argument('--use-attention', action='store_true', help='Set flag to use seq2seq with attention model') parser.add_argument('--encoder-cell-num-units', type=int, default=256, help='Number of cell units in the encoder layer') parser.add_argument('--decoder-cell-num-units', type=int, default=512, help='Number of cell units in the decoder layer') parser.add_argument('--encoder-embedding-size', type=int, default=256, help='Size of embedding in the encoder layer') parser.add_argument('--decoder-embedding-size', type=int, default=512, help='Size of embedding in the decoder layer') parser.add_argument('--decoder-softmax-size', type=int, default=None, help='Size of softmax layer in the decoder') parser.add_argument('--beam-size', type=int, default=6, help='Size of beam for the decoder') parser.add_argument('--word-reward', type=float, default=0.0, help='Reward per each word generated.') parser.add_argument('--unk-reward', type=float, default=0.0, help='Reward per each UNK token generated. ' 'Typically should be negative.') parser.add_argument('--checkpoint', type=str, default=None, help='Path to checkpoint', required=True) args = parser.parse_args() run_seq2seq_beam_decoder( args, model_params=dict( attention=('regular' if args.use_attention else 'none'), decoder_layer_configs=[ dict( num_units=args.decoder_cell_num_units, ), ], encoder_type=dict( encoder_layer_configs=[ dict( num_units=args.encoder_cell_num_units, ), ], use_bidirectional_encoder=args.use_bidirectional_encoder, ), encoder_embedding_size=args.encoder_embedding_size, decoder_embedding_size=args.decoder_embedding_size, decoder_softmax_size=args.decoder_softmax_size, ), decoding_params=dict( beam_size=args.beam_size, word_reward=args.word_reward, unk_reward=args.unk_reward, ), ) if __name__ == '__main__': main()
## @package seq2seq_model_helper # Module caffe2.python.models.seq2seq.seq2seq_model_helper from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import scope from caffe2.python.cnn import CNNModelHelper class Seq2SeqModelHelper(CNNModelHelper): def __init__(self, init_params=True, **kwargs): super(Seq2SeqModelHelper, self).__init__( order='NHWC', init_params=init_params, **kwargs ) self.non_trainable_params = [] def AddParam(self, name, init=None, init_value=None, trainable=True): """Adds a parameter to the model's net and it's initializer if needed Args: init: a tuple (<initialization_op_name>, <initialization_op_kwargs>) init_value: int, float or str. Can be used instead of `init` as a simple constant initializer trainable: bool, whether to compute gradient for this param or not """ if init_value is not None: assert init is None assert type(init_value) in [int, float, str] init = ('ConstantFill', dict( shape=[1], value=init_value, )) if self.init_params: param = self.param_init_net.__getattr__(init[0])( [], name, **init[1] ) else: param = self.net.AddExternalInput(name) if trainable: self.params.append(param) else: self.non_trainable_params.append(param) return param def GetNonTrainableParams(self, namescope=None): ''' Returns the params in current namescope ''' if namescope is None: namescope = scope.CurrentNameScope() else: if not namescope.endswith(scope._NAMESCOPE_SEPARATOR): namescope += scope._NAMESCOPE_SEPARATOR if namescope == '': return self.non_trainable_params[:] else: return [ p for p in self.non_trainable_params if p.GetNameScope() == namescope ] def GetAllParams(self, namescope=None): return ( self.GetParams(namescope) + self.GetComputedParams(namescope) + self.GetNonTrainableParams(namescope) )
## @package seq2seq_util # Module caffe2.python.examples.seq2seq_util """ A bunch of util functions to build Seq2Seq models with Caffe2.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import collections import caffe2.proto.caffe2_pb2 as caffe2_pb2 from caffe2.python import core, rnn_cell PAD_ID = 0 PAD = '<PAD>' GO_ID = 1 GO = '<GO>' EOS_ID = 2 EOS = '<EOS>' UNK_ID = 3 UNK = '<UNK>' def gen_vocab(corpus, unk_threshold): vocab = collections.defaultdict(lambda: len(vocab)) freqs = collections.defaultdict(lambda: 0) # Adding padding tokens to the vocabulary to maintain consistency with IDs vocab[PAD] vocab[GO] vocab[EOS] vocab[UNK] with open(corpus) as f: for sentence in f: tokens = sentence.strip().split() for token in tokens: freqs[token] += 1 for token, freq in freqs.items(): if freq > unk_threshold: vocab[token] return vocab def get_numberized_sentence(sentence, vocab): numerized_sentence = [] for token in sentence.strip().split(): if token in vocab: numerized_sentence.append(vocab[token]) else: numerized_sentence.append(vocab[UNK]) return numerized_sentence def build_embeddings( model, vocab_size, embedding_size, name, freeze_embeddings, ): embeddings = model.param_init_net.GaussianFill( [], name, shape=[vocab_size, embedding_size], std=0.1, ) if not freeze_embeddings: model.params.append(embeddings) return embeddings def rnn_unidirectional_encoder( model, embedded_inputs, input_lengths, initial_hidden_state, initial_cell_state, embedding_size, encoder_num_units, use_attention, scope=None, ): """ Unidirectional (forward pass) LSTM encoder.""" outputs, final_hidden_state, _, final_cell_state = rnn_cell.LSTM( model=model, input_blob=embedded_inputs, seq_lengths=input_lengths, initial_states=(initial_hidden_state, initial_cell_state), dim_in=embedding_size, dim_out=encoder_num_units, scope=(scope + '/' if scope else '') + 'encoder', outputs_with_grads=([0] if use_attention else [1, 3]), ) return outputs, final_hidden_state, final_cell_state def rnn_bidirectional_encoder( model, embedded_inputs, input_lengths, initial_hidden_state, initial_cell_state, embedding_size, encoder_num_units, use_attention, scope=None, ): """ Bidirectional (forward pass and backward pass) LSTM encoder.""" # Forward pass ( outputs_fw, final_hidden_state_fw, _, final_cell_state_fw, ) = rnn_cell.LSTM( model=model, input_blob=embedded_inputs, seq_lengths=input_lengths, initial_states=(initial_hidden_state, initial_cell_state), dim_in=embedding_size, dim_out=encoder_num_units, scope=(scope + '/' if scope else '') + 'forward_encoder', outputs_with_grads=([0] if use_attention else [1, 3]), ) # Backward pass reversed_embedded_inputs = model.net.ReversePackedSegs( [embedded_inputs, input_lengths], ['reversed_embedded_inputs'], ) ( outputs_bw, final_hidden_state_bw, _, final_cell_state_bw, ) = rnn_cell.LSTM( model=model, input_blob=reversed_embedded_inputs, seq_lengths=input_lengths, initial_states=(initial_hidden_state, initial_cell_state), dim_in=embedding_size, dim_out=encoder_num_units, scope=(scope + '/' if scope else '') + 'backward_encoder', outputs_with_grads=([0] if use_attention else [1, 3]), ) outputs_bw = model.net.ReversePackedSegs( [outputs_bw, input_lengths], ['outputs_bw'], ) # Concatenate forward and backward results outputs, _ = model.net.Concat( [outputs_fw, outputs_bw], ['outputs', 'outputs_dim'], axis=2, ) final_hidden_state, _ = model.net.Concat( [final_hidden_state_fw, final_hidden_state_bw], ['final_hidden_state', 'final_hidden_state_dim'], axis=2, ) final_cell_state, _ = model.net.Concat( [final_cell_state_fw, final_cell_state_bw], ['final_cell_state', 'final_cell_state_dim'], axis=2, ) return outputs, final_hidden_state, final_cell_state def build_embedding_encoder( model, encoder_params, inputs, input_lengths, vocab_size, embeddings, embedding_size, use_attention, num_gpus=0, scope=None, ): with core.NameScope(scope or ''): if num_gpus == 0: embedded_encoder_inputs = model.net.Gather( [embeddings, inputs], ['embedded_encoder_inputs'], ) else: with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)): embedded_encoder_inputs_cpu = model.net.Gather( [embeddings, inputs], ['embedded_encoder_inputs_cpu'], ) embedded_encoder_inputs = model.CopyCPUToGPU( embedded_encoder_inputs_cpu, 'embedded_encoder_inputs', ) assert len(encoder_params['encoder_layer_configs']) == 1 encoder_num_units = ( encoder_params['encoder_layer_configs'][0]['num_units'] ) with core.NameScope(scope or ''): encoder_initial_cell_state = model.param_init_net.ConstantFill( [], ['encoder_initial_cell_state'], shape=[encoder_num_units], value=0.0, ) encoder_initial_hidden_state = model.param_init_net.ConstantFill( [], 'encoder_initial_hidden_state', shape=[encoder_num_units], value=0.0, ) # Choose corresponding rnn encoder function if encoder_params['use_bidirectional_encoder']: rnn_encoder_func = rnn_bidirectional_encoder encoder_output_dim = 2 * encoder_num_units else: rnn_encoder_func = rnn_unidirectional_encoder encoder_output_dim = encoder_num_units ( encoder_outputs, final_encoder_hidden_state, final_encoder_cell_state, ) = rnn_encoder_func( model, embedded_encoder_inputs, input_lengths, encoder_initial_hidden_state, encoder_initial_cell_state, embedding_size, encoder_num_units, use_attention, scope=scope, ) weighted_encoder_outputs = None return ( encoder_outputs, weighted_encoder_outputs, final_encoder_hidden_state, final_encoder_cell_state, encoder_output_dim, ) def build_initial_rnn_decoder_states( model, encoder_num_units, decoder_num_units, final_encoder_hidden_state, final_encoder_cell_state, use_attention, ): if use_attention: decoder_initial_hidden_state = model.param_init_net.ConstantFill( [], 'decoder_initial_hidden_state', shape=[decoder_num_units], value=0.0, ) decoder_initial_cell_state = model.param_init_net.ConstantFill( [], 'decoder_initial_cell_state', shape=[decoder_num_units], value=0.0, ) initial_attention_weighted_encoder_context = ( model.param_init_net.ConstantFill( [], 'initial_attention_weighted_encoder_context', shape=[encoder_num_units], value=0.0, ) ) return ( decoder_initial_hidden_state, decoder_initial_cell_state, initial_attention_weighted_encoder_context, ) else: decoder_initial_hidden_state = model.FC( final_encoder_hidden_state, 'decoder_initial_hidden_state', encoder_num_units, decoder_num_units, axis=2, ) decoder_initial_cell_state = model.FC( final_encoder_cell_state, 'decoder_initial_cell_state', encoder_num_units, decoder_num_units, axis=2, ) return ( decoder_initial_hidden_state, decoder_initial_cell_state, ) def output_projection( model, decoder_outputs, decoder_output_size, target_vocab_size, decoder_softmax_size, ): if decoder_softmax_size is not None: decoder_outputs = model.FC( decoder_outputs, 'decoder_outputs_scaled', dim_in=decoder_output_size, dim_out=decoder_softmax_size, ) decoder_output_size = decoder_softmax_size output_projection_w = model.param_init_net.XavierFill( [], 'output_projection_w', shape=[target_vocab_size, decoder_output_size], ) output_projection_b = model.param_init_net.XavierFill( [], 'output_projection_b', shape=[target_vocab_size], ) model.params.extend([ output_projection_w, output_projection_b, ]) output_logits = model.net.FC( [ decoder_outputs, output_projection_w, output_projection_b, ], ['output_logits'], ) return output_logits
## @package beam_search # Module caffe2.python.models.seq2seq.beam_search from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import namedtuple from caffe2.python import core from caffe2.python.models.seq2seq.seq2seq_model_helper import Seq2SeqModelHelper class BeamSearchForwardOnly(object): """ Class generalizing forward beam search for seq2seq models. Also provides types to specify the recurrent structure of decoding: StateConfig: initial_value: blob providing value of state at first step_model state_prev_link: LinkConfig describing how recurrent step receives input from global state blob in each step state_link: LinkConfig describing how step writes (produces new state) to global state blob in each step LinkConfig: blob: blob connecting global state blob to step application offset: offset from beginning of global blob for link in time dimension window: width of global blob to read/write in time dimension """ LinkConfig = namedtuple('LinkConfig', ['blob', 'offset', 'window']) StateConfig = namedtuple( 'StateConfig', ['initial_value', 'state_prev_link', 'state_link'], ) def __init__(self, beam_size, model, go_token_id, eos_token_id): self.beam_size = beam_size self.model = model self.step_model = Seq2SeqModelHelper( name='step_model', param_model=self.model, ) self.go_token_id = go_token_id self.eos_token_id = eos_token_id ( self.timestep, self.scores_t_prev, self.tokens_t_prev, self.hypo_t_prev, self.attention_t_prev, ) = self.step_model.net.AddExternalInputs( 'timestep', 'scores_t_prev', 'tokens_t_prev', 'hypo_t_prev', 'attention_t_prev', ) tokens_t_prev_int32 = self.step_model.net.Cast( self.tokens_t_prev, 'tokens_t_prev_int32', to=core.DataType.INT32, ) self.tokens_t_prev_int32_flattened, _ = self.step_model.net.Reshape( [tokens_t_prev_int32], [tokens_t_prev_int32, 'input_t_int32_old_shape'], shape=[1, -1], ) def get_step_model(self): return self.step_model def get_previous_tokens(self): return self.tokens_t_prev_int32_flattened def get_timestep(self): return self.timestep # TODO: make attentions a generic state def apply( self, inputs, length, log_probs, attentions, state_configs, word_rewards=None, possible_translation_tokens=None, ): # [beam_size, beam_size] best_scores_per_hypo, best_tokens_per_hypo = self.step_model.net.TopK( log_probs, ['best_scores_per_hypo', 'best_tokens_per_hypo_indices'], k=self.beam_size, ) if possible_translation_tokens: # [beam_size, beam_size] best_tokens_per_hypo = self.step_model.net.Gather( [possible_translation_tokens, best_tokens_per_hypo], ['best_tokens_per_hypo'] ) # [beam_size] scores_t_prev_squeezed, _ = self.step_model.net.Reshape( self.scores_t_prev, ['scores_t_prev_squeezed', 'scores_t_prev_old_shape'], shape=[self.beam_size], ) # [beam_size, beam_size] output_scores = self.step_model.net.Add( [best_scores_per_hypo, scores_t_prev_squeezed], 'output_scores', broadcast=1, axis=0, ) if word_rewards is not None: # [beam_size, beam_size] word_rewards_for_best_tokens_per_hypo = self.step_model.net.Gather( [word_rewards, best_tokens_per_hypo], 'word_rewards_for_best_tokens_per_hypo', ) # [beam_size, beam_size] output_scores = self.step_model.net.Add( [output_scores, word_rewards_for_best_tokens_per_hypo], 'output_scores', ) # [beam_size * beam_size] output_scores_flattened, _ = self.step_model.net.Reshape( [output_scores], [output_scores, 'output_scores_old_shape'], shape=[-1], ) ZERO = self.model.param_init_net.ConstantFill( [], 'ZERO', shape=[1], value=0, dtype=core.DataType.INT32, ) SLICE_END = self._hack_get_slice_end( self.model, self.step_model, self.timestep, ) # [current_beam_size * beam_size] output_scores_flattened_slice = self.step_model.net.Slice( [output_scores_flattened, ZERO, SLICE_END], 'output_scores_flattened_slice', ) # [1, current_beam_size * beam_size] output_scores_flattened_slice, _ = self.step_model.net.Reshape( output_scores_flattened_slice, [ output_scores_flattened_slice, 'output_scores_flattened_slice_old_shape', ], shape=[1, -1], ) # [1, beam_size] scores_t, best_indices = self.step_model.net.TopK( output_scores_flattened_slice, ['scores_t', 'best_indices'], k=self.beam_size, ) BEAM_SIZE = self.model.param_init_net.ConstantFill( [], 'beam_size', shape=[1], value=self.beam_size, dtype=core.DataType.INT64, ) # [1, beam_size] hypo_t_int32 = self.step_model.net.Div( [best_indices, BEAM_SIZE], 'hypo_t_int32', broadcast=1, ) hypo_t = self.step_model.net.Cast( hypo_t_int32, 'hypo_t', to=core.DataType.FLOAT, ) # [beam_size, encoder_length, 1] attention_t = self.step_model.net.Gather( [attentions, hypo_t_int32], 'attention_t', ) # [1, beam_size, encoder_length] attention_t, _ = self.step_model.net.Reshape( attention_t, [attention_t, 'attention_t_old_shape'], shape=[1, self.beam_size, -1], ) # [beam_size * beam_size] best_tokens_per_hypo_flatten, _ = self.step_model.net.Reshape( best_tokens_per_hypo, [ 'best_tokens_per_hypo_flatten', 'best_tokens_per_hypo_old_shape', ], shape=[-1], ) tokens_t_int32 = self.step_model.net.Gather( [best_tokens_per_hypo_flatten, best_indices], 'tokens_t_int32', ) tokens_t = self.step_model.net.Cast( tokens_t_int32, 'tokens_t', to=core.DataType.FLOAT, ) def choose_state_per_hypo(state_config): state_flattened, _ = self.step_model.net.Reshape( state_config.state_link.blob, [ state_config.state_link.blob, 'state_old_shape_before_choosing_per_hypo', ], shape=[self.beam_size, -1], ) state_chosen_per_hypo = self.step_model.net.Gather( [state_flattened, hypo_t_int32], str(state_config.state_link.blob) + '_chosen_per_hypo', ) return self.StateConfig( initial_value=state_config.initial_value, state_prev_link=state_config.state_prev_link, state_link=self.LinkConfig( blob=state_chosen_per_hypo, offset=state_config.state_link.offset, window=state_config.state_link.window, ) ) state_configs = map(choose_state_per_hypo, state_configs) initial_scores = self.model.param_init_net.ConstantFill( [], 'initial_scores', shape=[1], value=0.0, dtype=core.DataType.FLOAT, ) initial_tokens = self.model.param_init_net.ConstantFill( [], 'initial_tokens', shape=[1], value=float(self.go_token_id), dtype=core.DataType.FLOAT, ) initial_hypo = self.model.param_init_net.ConstantFill( [], 'initial_hypo', shape=[1], value=-1.0, dtype=core.DataType.FLOAT, ) encoder_inputs_flattened, _ = self.model.net.Reshape( inputs, ['encoder_inputs_flattened', 'encoder_inputs_old_shape'], shape=[-1], ) init_attention = self.model.net.ConstantFill( encoder_inputs_flattened, 'init_attention', value=0.0, dtype=core.DataType.FLOAT, ) state_configs = state_configs + [ self.StateConfig( initial_value=initial_scores, state_prev_link=self.LinkConfig(self.scores_t_prev, 0, 1), state_link=self.LinkConfig(scores_t, 1, 1), ), self.StateConfig( initial_value=initial_tokens, state_prev_link=self.LinkConfig(self.tokens_t_prev, 0, 1), state_link=self.LinkConfig(tokens_t, 1, 1), ), self.StateConfig( initial_value=initial_hypo, state_prev_link=self.LinkConfig(self.hypo_t_prev, 0, 1), state_link=self.LinkConfig(hypo_t, 1, 1), ), self.StateConfig( initial_value=init_attention, state_prev_link=self.LinkConfig(self.attention_t_prev, 0, 1), state_link=self.LinkConfig(attention_t, 1, 1), ), ] fake_input = self.model.net.ConstantFill( length, 'beam_search_fake_input', input_as_shape=True, extra_shape=[self.beam_size, 1], value=0.0, dtype=core.DataType.FLOAT, ) all_inputs = ( [fake_input] + self.step_model.params + [state_config.initial_value for state_config in state_configs] ) forward_links = [] recurrent_states = [] for state_config in state_configs: state_name = str(state_config.state_prev_link.blob) + '_states' recurrent_states.append(state_name) forward_links.append(( state_config.state_prev_link.blob, state_name, state_config.state_prev_link.offset, state_config.state_prev_link.window, )) forward_links.append(( state_config.state_link.blob, state_name, state_config.state_link.offset, state_config.state_link.window, )) link_internal, link_external, link_offset, link_window = ( zip(*forward_links) ) all_outputs = map( lambda s: str(s) + '_all', [scores_t, tokens_t, hypo_t, attention_t], ) results = self.model.net.RecurrentNetwork( all_inputs, all_outputs + ['step_workspaces'], param=map(all_inputs.index, self.step_model.params), alias_src=map( lambda s: str(s) + '_states', [ self.scores_t_prev, self.tokens_t_prev, self.hypo_t_prev, self.attention_t_prev, ], ), alias_dst=all_outputs, alias_offset=[0] * 4, recurrent_states=recurrent_states, initial_recurrent_state_ids=map( all_inputs.index, [state_config.initial_value for state_config in state_configs], ), link_internal=map(str, link_internal), link_external=map(str, link_external), link_offset=link_offset, link_window=link_window, backward_link_internal=[], backward_link_external=[], backward_link_offset=[], step_net=str(self.step_model.net.Proto()), backward_step_net='', timestep=str(self.timestep), outputs_with_grads=[], ) score_t_all, tokens_t_all, hypo_t_all, attention_t_all = results[:4] output_token_beam_list = self.model.net.Cast( tokens_t_all, 'output_token_beam_list', to=core.DataType.INT32, ) output_prev_index_beam_list = self.model.net.Cast( hypo_t_all, 'output_prev_index_beam_list', to=core.DataType.INT32, ) output_score_beam_list = self.model.net.Alias( score_t_all, 'output_score_beam_list', ) output_attention_weights_beam_list = self.model.net.Alias( attention_t_all, 'output_attention_weights_beam_list', ) return ( output_token_beam_list, output_prev_index_beam_list, output_score_beam_list, output_attention_weights_beam_list, ) def _max_int32(self, model, a_int32, b_int32, output_name): a_float = model.net.Cast(a_int32, 'a_float', to=core.DataType.FLOAT) b_float = model.net.Cast(b_int32, 'b_float', to=core.DataType.FLOAT) m_float = model.net.Max([a_float, b_float], output_name + '_float') m_int32 = model.net.Cast(m_float, output_name, to=core.DataType.INT32) return m_int32 # Function returns (beam_size if timestep == 0 else -1) def _hack_get_slice_end(self, param_init_model, model, timestep): timestep_negative = model.net.Negative( timestep, 'timestep_negative', ) ONE_INT32 = param_init_model.param_init_net.ConstantFill( [], 'ONE_INT32', value=1, shape=[1], dtype=core.DataType.INT32, ) MINUS_ONE_INT32 = param_init_model.param_init_net.ConstantFill( [], 'MINUS_ONE_INT32', value=-1, shape=[1], dtype=core.DataType.INT32, ) zero_or_minus_one = self._max_int32( model=model, a_int32=timestep_negative, b_int32=MINUS_ONE_INT32, output_name='zero_or_minus_one', ) BEAM_SIZE_PLUS_ONE = param_init_model.param_init_net.ConstantFill( [], 'BEAM_SIZE_PLUS_ONE', value=self.beam_size + 1, shape=[1], dtype=core.DataType.INT32, ) one_or_zero = model.net.Add( [zero_or_minus_one, ONE_INT32], 'one_or_zero', ) beam_size_plus_one_or_zero = model.net.Mul( [BEAM_SIZE_PLUS_ONE, one_or_zero], 'beam_size_plus_one_or_zero', ) beam_size_or_minus_one = model.net.Add( [beam_size_plus_one_or_zero, MINUS_ONE_INT32], 'beam_size_or_minus_one' ) return beam_size_or_minus_one
## @package train # Module caffe2.python.models.seq2seq.train from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import collections import logging import math import numpy as np import random import time import sys from itertools import izip import caffe2.proto.caffe2_pb2 as caffe2_pb2 from caffe2.python import core, workspace, rnn_cell, data_parallel_model import caffe2.python.models.seq2seq.seq2seq_util as seq2seq_util from caffe2.python.models.seq2seq.seq2seq_model_helper import Seq2SeqModelHelper logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stderr)) Batch = collections.namedtuple('Batch', [ 'encoder_inputs', 'encoder_lengths', 'decoder_inputs', 'decoder_lengths', 'targets', 'target_weights', ]) def prepare_batch(batch): encoder_lengths = [len(entry[0]) for entry in batch] max_encoder_length = max(encoder_lengths) decoder_lengths = [] max_decoder_length = max([len(entry[1]) for entry in batch]) batch_encoder_inputs = [] batch_decoder_inputs = [] batch_targets = [] batch_target_weights = [] for source_seq, target_seq in batch: encoder_pads = ( [seq2seq_util.PAD_ID] * (max_encoder_length - len(source_seq)) ) batch_encoder_inputs.append( list(reversed(source_seq)) + encoder_pads ) decoder_pads = ( [seq2seq_util.PAD_ID] * (max_decoder_length - len(target_seq)) ) target_seq_with_go_token = [seq2seq_util.GO_ID] + target_seq decoder_lengths.append(len(target_seq_with_go_token)) batch_decoder_inputs.append(target_seq_with_go_token + decoder_pads) target_seq_with_eos = target_seq + [seq2seq_util.EOS_ID] targets = target_seq_with_eos + decoder_pads batch_targets.append(targets) if len(source_seq) + len(target_seq) == 0: target_weights = [0] * len(targets) else: target_weights = [ 1 if target != seq2seq_util.PAD_ID else 0 for target in targets ] batch_target_weights.append(target_weights) return Batch( encoder_inputs=np.array( batch_encoder_inputs, dtype=np.int32, ).transpose(), encoder_lengths=np.array(encoder_lengths, dtype=np.int32), decoder_inputs=np.array( batch_decoder_inputs, dtype=np.int32, ).transpose(), decoder_lengths=np.array(decoder_lengths, dtype=np.int32), targets=np.array( batch_targets, dtype=np.int32, ).transpose(), target_weights=np.array( batch_target_weights, dtype=np.float32, ).transpose(), ) class Seq2SeqModelCaffe2: def _build_model( self, init_params, ): model = Seq2SeqModelHelper(init_params=init_params) self._build_shared(model) self._build_embeddings(model) forward_model = Seq2SeqModelHelper(init_params=init_params) self._build_shared(forward_model) self._build_embeddings(forward_model) if self.num_gpus == 0: loss_blobs = self.model_build_fun(model) model.AddGradientOperators(loss_blobs) self.norm_clipped_grad_update( model, scope='norm_clipped_grad_update' ) self.forward_model_build_fun(forward_model) else: assert (self.batch_size % self.num_gpus) == 0 data_parallel_model.Parallelize_GPU( forward_model, input_builder_fun=lambda m: None, forward_pass_builder_fun=self.forward_model_build_fun, param_update_builder_fun=None, devices=range(self.num_gpus), ) def clipped_grad_update_bound(model): self.norm_clipped_grad_update( model, scope='norm_clipped_grad_update', ) data_parallel_model.Parallelize_GPU( model, input_builder_fun=lambda m: None, forward_pass_builder_fun=self.model_build_fun, param_update_builder_fun=clipped_grad_update_bound, devices=range(self.num_gpus), ) self.norm_clipped_sparse_grad_update( model, scope='norm_clipped_sparse_grad_update', ) self.model = model self.forward_net = forward_model.net def _build_shared(self, model): optimizer_params = self.model_params['optimizer_params'] with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)): self.learning_rate = model.AddParam( name='learning_rate', init_value=float(optimizer_params['learning_rate']), trainable=False, ) self.global_step = model.AddParam( name='global_step', init_value=0, trainable=False, ) self.start_time = model.AddParam( name='start_time', init_value=time.time(), trainable=False, ) def _build_embeddings(self, model): with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)): sqrt3 = math.sqrt(3) self.encoder_embeddings = model.param_init_net.UniformFill( [], 'encoder_embeddings', shape=[ self.source_vocab_size, self.model_params['encoder_embedding_size'], ], min=-sqrt3, max=sqrt3, ) model.params.append(self.encoder_embeddings) self.decoder_embeddings = model.param_init_net.UniformFill( [], 'decoder_embeddings', shape=[ self.target_vocab_size, self.model_params['decoder_embedding_size'], ], min=-sqrt3, max=sqrt3, ) model.params.append(self.decoder_embeddings) def model_build_fun(self, model, forward_only=False, loss_scale=None): encoder_inputs = model.net.AddExternalInput( workspace.GetNameScope() + 'encoder_inputs', ) encoder_lengths = model.net.AddExternalInput( workspace.GetNameScope() + 'encoder_lengths', ) decoder_inputs = model.net.AddExternalInput( workspace.GetNameScope() + 'decoder_inputs', ) decoder_lengths = model.net.AddExternalInput( workspace.GetNameScope() + 'decoder_lengths', ) targets = model.net.AddExternalInput( workspace.GetNameScope() + 'targets', ) target_weights = model.net.AddExternalInput( workspace.GetNameScope() + 'target_weights', ) attention_type = self.model_params['attention'] assert attention_type in ['none', 'regular'] ( encoder_outputs, weighted_encoder_outputs, final_encoder_hidden_state, final_encoder_cell_state, encoder_output_dim, ) = seq2seq_util.build_embedding_encoder( model=model, encoder_params=self.encoder_params, inputs=encoder_inputs, input_lengths=encoder_lengths, vocab_size=self.source_vocab_size, embeddings=self.encoder_embeddings, embedding_size=self.model_params['encoder_embedding_size'], use_attention=(attention_type != 'none'), num_gpus=self.num_gpus, ) assert len(self.model_params['decoder_layer_configs']) == 1 decoder_num_units = ( self.model_params['decoder_layer_configs'][0]['num_units'] ) initial_states = seq2seq_util.build_initial_rnn_decoder_states( model=model, encoder_num_units=encoder_output_dim, decoder_num_units=decoder_num_units, final_encoder_hidden_state=final_encoder_hidden_state, final_encoder_cell_state=final_encoder_cell_state, use_attention=(attention_type != 'none'), ) if self.num_gpus == 0: embedded_decoder_inputs = model.net.Gather( [self.decoder_embeddings, decoder_inputs], ['embedded_decoder_inputs'], ) else: with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)): embedded_decoder_inputs_cpu = model.net.Gather( [self.decoder_embeddings, decoder_inputs], ['embedded_decoder_inputs_cpu'], ) embedded_decoder_inputs = model.CopyCPUToGPU( embedded_decoder_inputs_cpu, 'embedded_decoder_inputs', ) # seq_len x batch_size x decoder_embedding_size if attention_type == 'none': decoder_outputs, _, _, _ = rnn_cell.LSTM( model=model, input_blob=embedded_decoder_inputs, seq_lengths=decoder_lengths, initial_states=initial_states, dim_in=self.model_params['decoder_embedding_size'], dim_out=decoder_num_units, scope='decoder', outputs_with_grads=[0], ) decoder_output_size = decoder_num_units else: ( decoder_outputs, _, _, _, attention_weighted_encoder_contexts, _ ) = rnn_cell.LSTMWithAttention( model=model, decoder_inputs=embedded_decoder_inputs, decoder_input_lengths=decoder_lengths, initial_decoder_hidden_state=initial_states[0], initial_decoder_cell_state=initial_states[1], initial_attention_weighted_encoder_context=initial_states[2], encoder_output_dim=encoder_output_dim, encoder_outputs=encoder_outputs, decoder_input_dim=self.model_params['decoder_embedding_size'], decoder_state_dim=decoder_num_units, scope='decoder', outputs_with_grads=[0, 4], ) decoder_outputs, _ = model.net.Concat( [decoder_outputs, attention_weighted_encoder_contexts], [ 'states_and_context_combination', '_states_and_context_combination_concat_dims', ], axis=2, ) decoder_output_size = decoder_num_units + encoder_output_dim # we do softmax over the whole sequence # (max_length in the batch * batch_size) x decoder embedding size # -1 because we don't know max_length yet decoder_outputs_flattened, _ = model.net.Reshape( [decoder_outputs], [ 'decoder_outputs_flattened', 'decoder_outputs_and_contexts_combination_old_shape', ], shape=[-1, decoder_output_size], ) output_logits = seq2seq_util.output_projection( model=model, decoder_outputs=decoder_outputs_flattened, decoder_output_size=decoder_output_size, target_vocab_size=self.target_vocab_size, decoder_softmax_size=self.model_params['decoder_softmax_size'], ) targets, _ = model.net.Reshape( [targets], ['targets', 'targets_old_shape'], shape=[-1], ) target_weights, _ = model.net.Reshape( [target_weights], ['target_weights', 'target_weights_old_shape'], shape=[-1], ) output_probs = model.net.Softmax( [output_logits], ['output_probs'], engine=('CUDNN' if self.num_gpus > 0 else None), ) label_cross_entropy = model.net.LabelCrossEntropy( [output_probs, targets], ['label_cross_entropy'], ) weighted_label_cross_entropy = model.net.Mul( [label_cross_entropy, target_weights], 'weighted_label_cross_entropy', ) total_loss_scalar = model.net.SumElements( [weighted_label_cross_entropy], 'total_loss_scalar', ) total_loss_scalar_weighted = model.net.Scale( [total_loss_scalar], 'total_loss_scalar_weighted', scale=1.0 / self.batch_size, ) return [total_loss_scalar_weighted] def forward_model_build_fun(self, model, loss_scale=None): return self.model_build_fun( model=model, forward_only=True, loss_scale=loss_scale ) def _calc_norm_ratio(self, model, params, scope, ONE): with core.NameScope(scope): grad_squared_sums = [] for i, param in enumerate(params): logger.info(param) grad = ( model.param_to_grad[param] if not isinstance( model.param_to_grad[param], core.GradientSlice, ) else model.param_to_grad[param].values ) grad_squared = model.net.Sqr( [grad], 'grad_{}_squared'.format(i), ) grad_squared_sum = model.net.SumElements( grad_squared, 'grad_{}_squared_sum'.format(i), ) grad_squared_sums.append(grad_squared_sum) grad_squared_full_sum = model.net.Sum( grad_squared_sums, 'grad_squared_full_sum', ) global_norm = model.net.Pow( grad_squared_full_sum, 'global_norm', exponent=0.5, ) clip_norm = model.param_init_net.ConstantFill( [], 'clip_norm', shape=[], value=float(self.model_params['max_gradient_norm']), ) max_norm = model.net.Max( [global_norm, clip_norm], 'max_norm', ) norm_ratio = model.net.Div( [clip_norm, max_norm], 'norm_ratio', ) return norm_ratio def _apply_norm_ratio( self, norm_ratio, model, params, learning_rate, scope, ONE ): for param in params: param_grad = model.param_to_grad[param] nlr = model.net.Negative( [learning_rate], 'negative_learning_rate', ) with core.NameScope(scope): update_coeff = model.net.Mul( [nlr, norm_ratio], 'update_coeff', broadcast=1, ) if isinstance(param_grad, core.GradientSlice): param_grad_values = param_grad.values model.net.ScatterWeightedSum( [ param, ONE, param_grad.indices, param_grad_values, update_coeff, ], param, ) else: model.net.WeightedSum( [ param, ONE, param_grad, update_coeff, ], param, ) def norm_clipped_grad_update(self, model, scope): if self.num_gpus == 0: learning_rate = self.learning_rate else: learning_rate = model.CopyCPUToGPU(self.learning_rate, 'LR') params = [] for param in model.GetParams(top_scope=True): if param in model.param_to_grad: if not isinstance( model.param_to_grad[param], core.GradientSlice, ): params.append(param) ONE = model.param_init_net.ConstantFill( [], 'ONE', shape=[1], value=1.0, ) logger.info('Dense trainable variables: ') norm_ratio = self._calc_norm_ratio(model, params, scope, ONE) self._apply_norm_ratio( norm_ratio, model, params, learning_rate, scope, ONE ) def norm_clipped_sparse_grad_update(self, model, scope): learning_rate = self.learning_rate params = [] for param in model.GetParams(top_scope=True): if param in model.param_to_grad: if isinstance( model.param_to_grad[param], core.GradientSlice, ): params.append(param) ONE = model.param_init_net.ConstantFill( [], 'ONE', shape=[1], value=1.0, ) logger.info('Sparse trainable variables: ') norm_ratio = self._calc_norm_ratio(model, params, scope, ONE) self._apply_norm_ratio( norm_ratio, model, params, learning_rate, scope, ONE ) def total_loss_scalar(self): if self.num_gpus == 0: return workspace.FetchBlob('total_loss_scalar') else: total_loss = 0 for i in range(self.num_gpus): name = 'gpu_{}/total_loss_scalar'.format(i) gpu_loss = workspace.FetchBlob(name) total_loss += gpu_loss return total_loss def _init_model(self): workspace.RunNetOnce(self.model.param_init_net) def create_net(net): workspace.CreateNet( net, input_blobs=map(str, net.external_inputs), ) create_net(self.model.net) create_net(self.forward_net) def __init__( self, model_params, source_vocab_size, target_vocab_size, num_gpus=1, num_cpus=1, ): self.model_params = model_params self.encoder_type = 'rnn' self.encoder_params = model_params['encoder_type'] self.source_vocab_size = source_vocab_size self.target_vocab_size = target_vocab_size self.num_gpus = num_gpus self.num_cpus = num_cpus self.batch_size = model_params['batch_size'] workspace.GlobalInit([ 'caffe2', # NOTE: modify log level for debugging purposes '--caffe2_log_level=0', # NOTE: modify log level for debugging purposes '--v=0', # Fail gracefully if one of the threads fails '--caffe2_handle_executor_threads_exceptions=1', '--caffe2_mkl_num_threads=' + str(self.num_cpus), ]) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): workspace.ResetWorkspace() def initialize_from_scratch(self): logger.info('Initializing Seq2SeqModelCaffe2 from scratch: Start') self._build_model(init_params=True) self._init_model() logger.info('Initializing Seq2SeqModelCaffe2 from scratch: Finish') def get_current_step(self): return workspace.FetchBlob(self.global_step)[0] def inc_current_step(self): workspace.FeedBlob( self.global_step, np.array([self.get_current_step() + 1]), ) def step( self, batch, forward_only ): if self.num_gpus < 1: batch_obj = prepare_batch(batch) for batch_obj_name, batch_obj_value in izip( Batch._fields, batch_obj, ): workspace.FeedBlob(batch_obj_name, batch_obj_value) else: for i in range(self.num_gpus): gpu_batch = batch[i::self.num_gpus] batch_obj = prepare_batch(gpu_batch) for batch_obj_name, batch_obj_value in izip( Batch._fields, batch_obj, ): name = 'gpu_{}/{}'.format(i, batch_obj_name) if batch_obj_name in ['encoder_inputs', 'decoder_inputs']: dev = core.DeviceOption(caffe2_pb2.CPU) else: dev = core.DeviceOption(caffe2_pb2.CUDA, i) workspace.FeedBlob(name, batch_obj_value, device_option=dev) if forward_only: workspace.RunNet(self.forward_net) else: workspace.RunNet(self.model.net) self.inc_current_step() return self.total_loss_scalar() def gen_batches(source_corpus, target_corpus, source_vocab, target_vocab, batch_size, max_length): with open(source_corpus) as source, open(target_corpus) as target: parallel_sentences = [] for source_sentence, target_sentence in zip(source, target): numerized_source_sentence = seq2seq_util.get_numberized_sentence( source_sentence, source_vocab, ) numerized_target_sentence = seq2seq_util.get_numberized_sentence( target_sentence, target_vocab, ) if ( len(numerized_source_sentence) > 0 and len(numerized_target_sentence) > 0 and ( max_length is None or ( len(numerized_source_sentence) <= max_length and len(numerized_target_sentence) <= max_length ) ) ): parallel_sentences.append(( numerized_source_sentence, numerized_target_sentence, )) parallel_sentences.sort(key=lambda s_t: (len(s_t[0]), len(s_t[1]))) batches, batch = [], [] for sentence_pair in parallel_sentences: batch.append(sentence_pair) if len(batch) >= batch_size: batches.append(batch) batch = [] if len(batch) > 0: while len(batch) < batch_size: batch.append(batch[-1]) assert len(batch) == batch_size batches.append(batch) random.shuffle(batches) return batches def run_seq2seq_model(args, model_params=None): source_vocab = seq2seq_util.gen_vocab( args.source_corpus, args.unk_threshold, ) target_vocab = seq2seq_util.gen_vocab( args.target_corpus, args.unk_threshold, ) logger.info('Source vocab size {}'.format(len(source_vocab))) logger.info('Target vocab size {}'.format(len(target_vocab))) batches = gen_batches(args.source_corpus, args.target_corpus, source_vocab, target_vocab, model_params['batch_size'], args.max_length) logger.info('Number of training batches {}'.format(len(batches))) batches_eval = gen_batches(args.source_corpus_eval, args.target_corpus_eval, source_vocab, target_vocab, model_params['batch_size'], args.max_length) logger.info('Number of eval batches {}'.format(len(batches_eval))) with Seq2SeqModelCaffe2( model_params=model_params, source_vocab_size=len(source_vocab), target_vocab_size=len(target_vocab), num_gpus=args.num_gpus, num_cpus=20, ) as model_obj: model_obj.initialize_from_scratch() for i in range(args.epochs): logger.info('Epoch {}'.format(i)) total_loss = 0 for batch in batches: total_loss += model_obj.step( batch=batch, forward_only=False, ) logger.info('\ttraining loss {}'.format(total_loss)) total_loss = 0 for batch in batches_eval: total_loss += model_obj.step( batch=batch, forward_only=False, ) logger.info('\teval loss {}'.format(total_loss)) if args.checkpoint is not None: checkpoint_path = '{0}-{1}'.format(args.checkpoint, i) assert workspace.RunOperatorOnce(core.CreateOperator( 'Save', model_obj.model.GetAllParams(), [], absolute_path=True, db=checkpoint_path, db_type='minidb', )) logger.info('Model saved to ' + checkpoint_path) def main(): random.seed(31415) parser = argparse.ArgumentParser( description='Caffe2: Seq2Seq Training' ) parser.add_argument('--source-corpus', type=str, default=None, help='Path to source corpus in a text file format. Each ' 'line in the file should contain a single sentence', required=True) parser.add_argument('--target-corpus', type=str, default=None, help='Path to target corpus in a text file format', required=True) parser.add_argument('--max-length', type=int, default=None, help='Maximal lengths of train and eval sentences') parser.add_argument('--unk-threshold', type=int, default=50, help='Threshold frequency under which token becomes ' 'labeled unknown token') parser.add_argument('--batch-size', type=int, default=32, help='Training batch size') parser.add_argument('--epochs', type=int, default=10, help='Number of iterations over training data') parser.add_argument('--learning-rate', type=float, default=0.5, help='Learning rate') parser.add_argument('--max-gradient-norm', type=float, default=1.0, help='Max global norm of gradients at the end of each ' 'backward pass. We do clipping to match the number.') parser.add_argument('--num-gpus', type=int, default=0, help='Number of GPUs for data parallel model') parser.add_argument('--use-bidirectional-encoder', action='store_true', help='Set flag to use bidirectional recurrent network ' 'in encoder') parser.add_argument('--use-attention', action='store_true', help='Set flag to use seq2seq with attention model') parser.add_argument('--source-corpus-eval', type=str, default=None, help='Path to source corpus for evaluation in a text ' 'file format', required=True) parser.add_argument('--target-corpus-eval', type=str, default=None, help='Path to target corpus for evaluation in a text ' 'file format', required=True) parser.add_argument('--encoder-cell-num-units', type=int, default=256, help='Number of cell units in the encoder layer') parser.add_argument('--decoder-cell-num-units', type=int, default=512, help='Number of cell units in the decoder layer') parser.add_argument('--encoder-embedding-size', type=int, default=256, help='Size of embedding in the encoder layer') parser.add_argument('--decoder-embedding-size', type=int, default=512, help='Size of embedding in the decoder layer') parser.add_argument('--decoder-softmax-size', type=int, default=None, help='Size of softmax layer in the decoder') parser.add_argument('--checkpoint', type=str, default=None, help='Path to checkpoint') args = parser.parse_args() run_seq2seq_model(args, model_params=dict( attention=('regular' if args.use_attention else 'none'), decoder_layer_configs=[ dict( num_units=args.decoder_cell_num_units, ), ], encoder_type=dict( encoder_layer_configs=[ dict( num_units=args.encoder_cell_num_units, ), ], use_bidirectional_encoder=args.use_bidirectional_encoder, ), batch_size=args.batch_size, optimizer_params=dict( learning_rate=args.learning_rate, ), encoder_embedding_size=args.encoder_embedding_size, decoder_embedding_size=args.decoder_embedding_size, decoder_softmax_size=args.decoder_softmax_size, max_gradient_norm=args.max_gradient_norm, )) if __name__ == '__main__': main()
## @package formatter # Module caffe2.python.docs.formatter from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python.docs.parser import Parser class Formatter(object): def __init__(self): self.content = "" def clone(self): return self.__class__() def dump(self): return self.content def parseAndAdd(self, text): text = Parser(text, self).parse() self.addRaw(text) def addRaw(self, text): raise Exception('Not yet implemented.') def addLine(self, text): raise Exception('Not yet implemented.') def addLinebreak(self): raise Exception('Not yet implemented.') def addHeader(self, text): raise Exception('Not yet implemented.') def addEmphasis(self, text): raise Exception('Not yet implemented.') def addList(self, textList): raise Exception('Not yet implemented.') def addLink(self, text, url): raise Exception('Not yet implemented.') def addCode(self, text): raise Exception('Not yet implemented.') def addCodeLink(self, text): raise Exception('Not yet implemented.') def addTable(self, table): raise Exception('Not yet implemented.') def addBreak(self): raise Exception('Not yet implemented.') class Markdown(Formatter): def addRaw(self, text): self.content += "{text}".format(text=text) def addLine(self, text, new_line=False): self.content += "{line}{text}\n".format(line=('\n' if new_line else ''), text=text) def addLinebreak(self): self.content += "\n" def addHeader(self, text, h=1): self.addLine("{header} {text}".format(header=h * '#', text=text), True) def addEmphasis(self, text, s=1): self.addRaw("{stars}{text}{stars}".format(stars=s * '*', text=text)) def addList(self, textList): for text in textList: self.addLine("- {text}".format(text=text), True) self.addLinebreak() def addLink(self, text, url): self.addRaw("[{text}]({url})".format(text=text, url=url)) def addCodeLink(self, path, options=None): self.addRaw("({path})".format(path=path)) def addCode(self, text, inline=False): if (inline): self.content += "`{text}`".format(text=text) else: self.addRaw("\n\n```\n{text}```\n\n".format(text=text)) def addTable(self, table, noTitle=False): self.addLinebreak() assert(len(table) > 1) if noTitle: table.insert(0, [' ' for i in range(len(table[0]))]) self.addLine(' | '.join(table[0])) self.addLine(' | '.join(['----' for i in range(len(table[0]))])) for row in table[1:]: self.addLine(' | '.join(row)) self.addLinebreak() def addBreak(self): self.addLine('\n---\n', True)
## @package parser # Module caffe2.python.docs.parser from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import re class Parser(object): # List of tuples (regex_str, lambda(regex_match, formatter)) # If a lambda returns True it will be called repeatedly with replacement # otherwise it will only be called on text that hasn't been parsed yet. regexes = [ # Code blocks of various formats ('````(.+?)````', lambda m, f: f.addCode(m.group(1)) ), ('```(.+?)```', lambda m, f: f.addCode(m.group(1)) ), ('((( {2})+)(\S.*)(\n\s*\n|\n))+', lambda m, f: f.addCode(m.group(0)) ), ('([^\.])\n', lambda m, f: f.addRaw('{c} '.format(c=m.group(1))) or True ), ('`(.+?)`', lambda m, f: f.addCode(m.group(1), True) ), # Make links clickable ('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]' '|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', lambda m, f: f.addLink(m.group(0), m.group(0)) ), ('\*\*(.+?)\*\*', lambda m, f: f.addEmphasis(m.group(1), 2) ), ('\*(.+?)\*', lambda m, f: f.addEmphasis(m.group(1), 1) ), ] def __init__(self, text, formatter): self.text = text self.lines = [] self.formatter = formatter def parseText(self): UNPARSED = 0 PARSED = 1 parsed_block = [(UNPARSED, self.text)] for regex, func in self.regexes: index = 0 while index < len(parsed_block): label, text = parsed_block[index] # Already been parsed if (label == PARSED): index += 1 continue match = re.search(regex, text) if match: parsed_block.pop(index) start = match.start(0) end = match.end(0) f = self.formatter.clone() merge = func(match, f) if merge: merged = text[:start] + f.dump() + text[end:] parsed_block.insert(index, (UNPARSED, merged)) else: if text[:start]: parsed_block.insert(index, (UNPARSED, text[:start])) index += 1 parsed_block.insert(index, (PARSED, f.dump())) index += 1 if text[end:]: parsed_block.insert(index, (UNPARSED, text[end:])) else: index += 1 self.lines += [i for _, i in parsed_block] self.text = ' '.join(self.lines) def parse(self): self.parseText() return self.text