def test_prelu_activation_layer(self): """Test a model with a single CNTK PReLU activation layer against the equivalent ELL predictor. This verifies that the import functions reshape and reorder values appropriately and that the equivalent ELL layer produces comparable output """ # Create a test set of alpha parameters to use for both CNTK and ELL # layers # Input order for CNTK is channels, rows, columns alphaValues = np.linspace( 1, 2, num=16 * 10 * 10, dtype=np.float32).reshape(16, 10, 10) # create an ELL Tensor from the alpha parameters, which re-orders and # produces an appropriately dimensioned tensor alphaTensor = cntk_converters.\ get_tensor_from_cntk_convolutional_weight_value_shape( alphaValues, alphaValues.shape) inputValues = np.linspace( -5, 5, num=16 * 10 * 10, dtype=np.float32).reshape(16, 10, 10) # Evaluate a PReLU CNTK layer x = input((16, 10, 10)) p = parameter(shape=x.shape, init=alphaValues, name="prelu") cntkModel = param_relu(p, x) # Create the equivalent ELL predictor layerParameters = ell.neural.LayerParameters( # Input order for ELL is rows, columns, channels ell.math.TensorShape(10, 10, 16), ell.neural.NoPadding(), ell.math.TensorShape(10, 10, 16), ell.neural.NoPadding(), ell.nodes.PortType.smallReal) layer = ell.neural.PReLUActivationLayer(layerParameters, alphaTensor) predictor = ell.neural.NeuralNetworkPredictor([layer]) cntkResults = cntkModel(inputValues) orderedCntkResults = cntk_converters.get_vector_from_cntk_array( cntkResults) orderedInputValues = cntk_converters.get_vector_from_cntk_array( inputValues) ellResults = predictor.Predict(orderedInputValues) # Compare the results np.testing.assert_array_equal( orderedCntkResults, ellResults, 'results for PReLU Activation layer do not match!') # now run same over ELL compiled model self.verify_compiled( predictor, orderedInputValues, orderedCntkResults, "prelu_activation", "test")
def test_dense_layer(self): """Test a model with a single CNTK Dense layer against the equivalent ELL predictor. This verifies that the import functions reshape and reorder values appropriately and that the equivalent ELL layer produces comparable output """ # Create a Dense CNTK layer with no bias or activation denseLayer = Dense(5, bias=False) x = input((2, 3, 4)) # Input order for CNTK is channels, rows, columns cntkModel = denseLayer(x) # Create a test set of weights to use for both CNTK and ELL layers # CNTK has these in channels, rows, columns, [output shape] order weightValues = np.arange(120, dtype=np.float_).reshape(2, 3, 4, 5) # Set the weights denseLayer.parameters[0].value = weightValues # create an ELL Tensor from the cntk weights, which re-orders the # weights and produces an appropriately dimensioned tensor weightTensor = cntk_converters.\ get_tensor_from_cntk_dense_weight_parameter( denseLayer.parameters[0]) # Create the equivalent ELL predictor layerParameters = ell.neural.LayerParameters( # Input order for ELL is rows, columns, channels ell.math.TensorShape(3, 4, 2), ell.neural.NoPadding(), ell.math.TensorShape(1, 1, 5), ell.neural.NoPadding(), ell.nodes.PortType.smallReal) layer = ell.neural.FullyConnectedLayer(layerParameters, weightTensor) predictor = ell.neural.NeuralNetworkPredictor([layer]) # Get the results for both inputValues = np.arange(24, dtype=np.float32).reshape(2, 3, 4) orderedInputValues = cntk_converters.get_vector_from_cntk_array( inputValues) cntkResults = cntkModel(inputValues) orderedCntkResults = cntk_converters.get_vector_from_cntk_array( cntkResults) ellResults = predictor.Predict(orderedInputValues) # Compare the results np.testing.assert_array_equal( orderedCntkResults, ellResults, 'results for Dense layer do not match!') # now run same over ELL compiled model self.verify_compiled(predictor, orderedInputValues, orderedCntkResults, "dense", "test")
def verify_ell(self, op_name, predictor, input_data, cntk_output): """Compare this with the equivalent ELL layer, both reference and compiled. `op_name` is a human-readable name describing the layer being verified. """ ellTestInput = cntk_converters.get_vector_from_cntk_array(input_data) ellResults = np.array(predictor.Predict(ellTestInput)).ravel() ellResultsOutputShape = predictor.GetOutputShape() reshapedEllOutput = np.reshape( ellResults, (ellResultsOutputShape.rows, ellResultsOutputShape.columns, ellResultsOutputShape.channels)) if len(input_data.shape) == 3: reshapedEllOutput = np.transpose(reshapedEllOutput, (2, 0, 1)) # to match CNTK output # now compare these results. np.testing.assert_array_almost_equal( cntk_output, reshapedEllOutput.ravel(), decimal=4, err_msg=('Results for {} layer do not match!'.format(op_name))) # and verify compiled is also the same self.verify_compiled(predictor, ellTestInput, cntk_output, op_name)
def save_layer_outputs(self, op_name): name = op_name + "(" + str(self.layer_index) + ")" self.layer_index += 1 self.report.write("## %s\n" % (name)) self.report.write("````\n") shape = self.data.shape self.report.write("Output size: " + str(shape)) self.report.write("````\n") with open("Compare_" + name + ".csv", "w") as f: f.write("cntk,ell,compiled\n") a = cntk_converters.get_vector_from_cntk_array(self.data) b = self.ell_data.ravel() c = self.compiled_data.ravel() pos = 0 while pos < len(a) and pos < len(b) and pos < len(c): f.write("%f,%f,%f\n" % (a[pos], b[pos], b[pos])) pos += 1 f.close()
def test_batch_normalization_layer(self): """Test a model with a single CNTK BatchNormalization layer against the equivalent ELL predictor This verifies that the import functions reshape and reorder values appropriately and that the equivalent ELL layer produces comparable output """ # Create a test set of scales and biases to use for both CNTK and ELL # layers scaleValues = np.linspace(0.1, 0.5, num=16, dtype=np.float32) scaleVector = cntk_converters.get_vector_from_cntk_array(scaleValues) biasValues = np.linspace(1, 2, num=16, dtype=np.float32) biasVector = cntk_converters.get_vector_from_cntk_array(biasValues) meanValues = np.linspace(-0.5, 0.5, num=16, dtype=np.float32) meanVector = cntk_converters.get_vector_from_cntk_array(meanValues) varianceValues = np.linspace(-1, 1, num=16, dtype=np.float32) varianceVector = cntk_converters.get_vector_from_cntk_array( varianceValues) # Create a BatchNormalization CNTK layer # CNTK's BatchNormalization layer does not support setting the running # mean and variance, so we use a wrapper function around the # batch_normalization op batchNorm = BatchNormalizationTester(init_scale=scaleValues, norm_shape=scaleValues.shape, init_bias=biasValues, init_mean=meanValues, init_variance=varianceValues) # Input order for CNTK is channels, rows, columns x = input((16, 10, 10)) cntkModel = batchNorm(x) # Create the equivalent ELL predictor layers = [] layerParameters = ell.neural.LayerParameters( # Input order for ELL is rows, columns, channels ell.math.TensorShape(10, 10, 16), ell.neural.NoPadding(), ell.math.TensorShape(10, 10, 16), ell.neural.NoPadding(), ell.nodes.PortType.smallReal) # CNTK BatchNorm = ELL's BatchNorm + Scaling + Bias # 1e-5 is the default epsilon for CNTK's BatchNormalization Layer epsilon = 1e-5 layers.append( ell.neural.BatchNormalizationLayer( layerParameters, meanVector, varianceVector, epsilon, ell.neural.EpsilonSummand.variance)) layers.append(ell.neural.ScalingLayer(layerParameters, scaleVector)) layers.append(ell.neural.BiasLayer(layerParameters, biasVector)) predictor = ell.neural.NeuralNetworkPredictor(layers) inputValues = np.linspace(-5, 5, num=16 * 10 * 10, dtype=np.float32).reshape(16, 10, 10) cntkResults = cntkModel(inputValues) orderedCntkResults = cntk_converters.get_vector_from_cntk_array( # Note that cntk inserts an extra dimension of 1 in the front cntkResults) orderedInputValues = cntk_converters.get_vector_from_cntk_array( inputValues) ellResults = predictor.Predict(orderedInputValues) # Compare the results (precision is 1 less decimal place from epsilon) np.testing.assert_array_almost_equal( orderedCntkResults, ellResults, 6, 'results for BatchNormalization layer do not match!') # now run same over ELL compiled model self.verify_compiled(predictor, orderedInputValues, orderedCntkResults, "batch_norm", "test", precision=6)
def test_binary_convolution_layer(self): """Test a model with a single CNTK Binary Convolution layer against the equivalent ELL predictor. This verifies that the import functions reshape and reorder values appropriately and that the equivalent ELL layer produces comparable output """ # Create a test set of weights to use for both CNTK and ELL layers # CNTK has these in filters, channels, rows, columns order weightValues = np.random.uniform(low=-5, high=5, size=(5, 2, 3, 3)).astype(np.float32) # create an ELL Tensor from the cntk weights, which re-orders the # weights and produces an appropriately dimensioned tensor weightTensor = cntk_converters.\ get_tensor_from_cntk_convolutional_weight_value_shape( weightValues, weightValues.shape) # Create a Binary Convolution CNTK layer with no bias, no activation, # stride 1 # Input order for CNTK is channels, rows, columns x = input((2, 10, 10)) cntkModel = CustomSign(x) cntkModel = BinaryConvolution((10, 10), num_filters=5, channels=2, init=weightValues, pad=True, bias=False, init_bias=0, activation=False)(cntkModel) # Create the equivalent ELL predictor layerParameters = ell.neural.LayerParameters( # Input order for ELL is rows, columns, channels. Account for # padding. ell.math.TensorShape(10 + 2, 10 + 2, 2), ell.neural.ZeroPadding(1), ell.math.TensorShape(10, 10, 5), ell.neural.NoPadding(), ell.nodes.PortType.smallReal) convolutionalParameters = ell.neural.BinaryConvolutionalParameters( 3, 1, ell.neural.BinaryConvolutionMethod.bitwise, ell.neural.BinaryWeightsScale.none) layer = ell.neural.BinaryConvolutionalLayer(layerParameters, convolutionalParameters, weightTensor) predictor = ell.neural.NeuralNetworkPredictor([layer]) # Get the results for both inputValues = np.random.uniform(low=-50, high=50, size=(2, 10, 10)).astype(np.float32) cntkResults = cntkModel(inputValues) orderedCntkResults = cntk_converters.get_vector_from_cntk_array( cntkResults) orderedInputValues = cntk_converters.get_vector_from_cntk_array( inputValues) ellResults = predictor.Predict(orderedInputValues) # Compare the results np.testing.assert_array_equal( orderedCntkResults, ellResults, 'results for Binary Convolution layer do not match!') # now run same over ELL compiled model self.verify_compiled(predictor, orderedInputValues, orderedCntkResults, "binary_convolution", "test")
def test_convolution_layer(self): """Test a model with a single CNTK Convolution layer against the equivalent ELL predictor. This verifies that the import functions reshape and reorder values appropriately and that the equivalent ELL layer produces comparable output """ # Create a Convolution CNTK layer with no bias or activation, # auto-padding, stride of 1 convolutionLayer = Convolution((3, 3), 5, pad=(True, True), strides=1, bias=False, init=0) x = input((2, 3, 4)) # Input order for CNTK is channels, rows, columns cntkModel = convolutionLayer(x) # Create a test set of weights to use for both CNTK and ELL layers # CNTK has these in filters, channels, rows, columns order weightValues = np.arange(90, dtype=np.float_).reshape(5, 2, 3, 3) # Set the weights convolutionLayer.parameters[0].value = weightValues # create an ELL Tensor from the cntk weights, which re-orders the # weights and produces an appropriately dimensioned tensor weightTensor = cntk_converters.\ get_tensor_from_cntk_convolutional_weight_parameter( convolutionLayer.parameters[0]) # Create the equivalent ELL predictor layerParameters = ell.neural.LayerParameters( # Input order for ELL is rows, columns, channels. Account for # padding. ell.math.TensorShape(3 + 2, 4 + 2, 2), ell.neural.ZeroPadding(1), ell.math.TensorShape(3, 4, 5), ell.neural.NoPadding(), ell.nodes.PortType.smallReal) convolutionalParameters = ell.neural.ConvolutionalParameters( 3, 1, 0, 5) layer = ell.neural.ConvolutionalLayer(layerParameters, convolutionalParameters, weightTensor) predictor = ell.neural.NeuralNetworkPredictor([layer]) # Get the results for both inputValues = np.arange(24, dtype=np.float32).reshape(2, 3, 4) cntkResults = cntkModel(inputValues) orderedCntkResults = cntk_converters.get_vector_from_cntk_array( cntkResults) orderedInputValues = cntk_converters.get_vector_from_cntk_array( inputValues) ellResults = predictor.Predict(orderedInputValues) # Compare the results np.testing.assert_array_equal( orderedCntkResults, ellResults, 'results for Convolution layer do not match!') # now run same over ELL compiled model self.verify_compiled(predictor, orderedInputValues, orderedCntkResults, "convolution", "test")