pytorch/caffe2/python/layers/functional.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

124 lines
4.8 KiB
Python
Raw Normal View History

# @package functional
# Module caffe2.python.layers.functional
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,
Update from facebook (#7855) * [mpscnn] MPSCNNChannelShuffle att * [Easy] Adding tags as an argument to the functional layer Without it "tags" would be added as an argument to the operator. The change here is based on the assumption that there is no operator that takes "tags" as an argument. * Fix locally_connected_op schema check. Fix locally_connected_op schema check. * [C2] Add TypeAndShape inference for few more operators As desc * [c2] Shape inference should support 0 as dimension Tensors can have 0 in their dimension. * Make MockHiveReader loop over and support max_examples Replace DatasetReader with RandomDatasetReader. So that Mock Hive Reader can simulate a large data input using a small sample file as source. * Utility function to wipe cache between benchmark runs Caffe2 benchmark does not wipe out cache between runs, and this potentially creates an unrealistically optimistic picture of performance. This diff adds utility function to wipe out the cache. * Allow caffe2 GlobalInit to be invoked multiple times Allow caffe2 GlobalInit to be invoked multiple times. Will re-parse gflags and update logging levels on successive invocations, but will not re-run init functions or perform other one-time initialization. * Add Caffe2 GlobalInitIsCalledGuard to base net and operator classes Warn if caffe2's GlobalInit function has not been invoked before creating an operator or net object. This is based on discussion here: https://fb.quip.com/kqGIAbmK7vNG * Rethrow current exception on failure Rethrow current exception instead of copy constructing a new one on op failure. * Make `clone()` return subclass of List/Struct `clone()` is not working correctly when we subclass those classes * Wipe the cache before the net run the util function is copied from D7409424 will rebase once D7409424 is landed. * [Caffe2] [Mobile] Support utils/cast.h::GetCastDataType with LITE_PROTO builds * Correct includes async_polling include -> async_base include * Prepare execution flags for executor migration Making async_scheduling aware of underlying net type to prepare for executor migration * Add operator level observers into async executor Adding operator level observers into RunAsync operators' calls * Cleanup TEST_Benchmark Remove duplicate code and provide default implementation in NetBase * [C2] Fix type and shape inference for binary comparison ops As desc. * Add GlobalInit to predictor to ensure initialization is always done before prediction FACEBOOK: Redo D7651453 the correct way. Now use a static variable for the arguments passed to GLog * Remove spammy log message This method is currently used in various places inside Caffe itself. * Disable events for operators inside a chain We don't need to use events in operators within a chain because the chain is always scheduled on a single stream, keeping only first and last event for scheduling purposes * Ensure correct finish run order In rare cases we might call finishRun and trigger net's destruction while another worker is still holding shared_ptr to a thread pool, that can cause thread pool destruction from within a worker thread in case no other nets are using the pool. This diff fixes the order of calling finishRun and also changes pool() to return raw pointer to keep pool's ownership within the net * Reduce unnecessary polling Make sure we don't waste CPU by polling operators that we can set an efficient callbacks on * Squash commit of syncing 9506eeb from github to fbcode Patch xplat buck fix add virtual destructor to OptimizationPass add virtual destructor to OptimizationPass build fixes for sync build fixes for sync * Fix net tracing Fix net tracing from async_scheduling * Fix logging
2018-05-29 18:38:02 +00:00
name='functional', output_dtypes=None, tags=None, **kwargs):
# allow coercion
input_record = schema.as_record(input_record)
Update from facebook (#7855) * [mpscnn] MPSCNNChannelShuffle att * [Easy] Adding tags as an argument to the functional layer Without it "tags" would be added as an argument to the operator. The change here is based on the assumption that there is no operator that takes "tags" as an argument. * Fix locally_connected_op schema check. Fix locally_connected_op schema check. * [C2] Add TypeAndShape inference for few more operators As desc * [c2] Shape inference should support 0 as dimension Tensors can have 0 in their dimension. * Make MockHiveReader loop over and support max_examples Replace DatasetReader with RandomDatasetReader. So that Mock Hive Reader can simulate a large data input using a small sample file as source. * Utility function to wipe cache between benchmark runs Caffe2 benchmark does not wipe out cache between runs, and this potentially creates an unrealistically optimistic picture of performance. This diff adds utility function to wipe out the cache. * Allow caffe2 GlobalInit to be invoked multiple times Allow caffe2 GlobalInit to be invoked multiple times. Will re-parse gflags and update logging levels on successive invocations, but will not re-run init functions or perform other one-time initialization. * Add Caffe2 GlobalInitIsCalledGuard to base net and operator classes Warn if caffe2's GlobalInit function has not been invoked before creating an operator or net object. This is based on discussion here: https://fb.quip.com/kqGIAbmK7vNG * Rethrow current exception on failure Rethrow current exception instead of copy constructing a new one on op failure. * Make `clone()` return subclass of List/Struct `clone()` is not working correctly when we subclass those classes * Wipe the cache before the net run the util function is copied from D7409424 will rebase once D7409424 is landed. * [Caffe2] [Mobile] Support utils/cast.h::GetCastDataType with LITE_PROTO builds * Correct includes async_polling include -> async_base include * Prepare execution flags for executor migration Making async_scheduling aware of underlying net type to prepare for executor migration * Add operator level observers into async executor Adding operator level observers into RunAsync operators' calls * Cleanup TEST_Benchmark Remove duplicate code and provide default implementation in NetBase * [C2] Fix type and shape inference for binary comparison ops As desc. * Add GlobalInit to predictor to ensure initialization is always done before prediction FACEBOOK: Redo D7651453 the correct way. Now use a static variable for the arguments passed to GLog * Remove spammy log message This method is currently used in various places inside Caffe itself. * Disable events for operators inside a chain We don't need to use events in operators within a chain because the chain is always scheduled on a single stream, keeping only first and last event for scheduling purposes * Ensure correct finish run order In rare cases we might call finishRun and trigger net's destruction while another worker is still holding shared_ptr to a thread pool, that can cause thread pool destruction from within a worker thread in case no other nets are using the pool. This diff fixes the order of calling finishRun and also changes pool() to return raw pointer to keep pool's ownership within the net * Reduce unnecessary polling Make sure we don't waste CPU by polling operators that we can set an efficient callbacks on * Squash commit of syncing 9506eeb from github to fbcode Patch xplat buck fix add virtual destructor to OptimizationPass add virtual destructor to OptimizationPass build fixes for sync build fixes for sync * Fix net tracing Fix net tracing from async_scheduling * Fix logging
2018-05-29 18:38:02 +00:00
super(Functional, self).__init__(model, name, input_record, tags=tags, **kwargs)
self._function = function
self._kwargs = kwargs
return_struct = (
isinstance(output_names_or_num, list) or
(isinstance(output_names_or_num, int) and
output_names_or_num != 1)
)
with scope.NameScope(self.name, reset=True):
if isinstance(output_names_or_num, int):
struct_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]
struct_output_schema = schema.NewRecord(
model.net, schema.Struct(*out_tuple))
num_outputs = len(struct_output_schema.field_blobs())
# functional layer returns Struct if more than one outputs or output is
# a list, otherwise Scalar
if return_struct:
self.output_schema = struct_output_schema
else:
self.output_schema = struct_output_schema[0]
# 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):
scalar_schema = (self.output_schema[i] if return_struct
else self.output_schema)
blob = scalar_schema()
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("unexpected 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)
elif types[blob] == caffe2_pb2.TensorProto.FLOAT16:
dtype = (np.float16, shape)
if dtype is not None:
scalar_schema.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))