Caffe2 - Python API
A deep learning, cross platform ML framework
simple_operator_layers.py
1 
3 from __future__ import absolute_import
4 from __future__ import division
5 from __future__ import print_function
6 from __future__ import unicode_literals
7 
8 from caffe2.python import schema
9 from caffe2.python.layers.layers import (
10  ModelLayer,
11 )
12 
13 
14 def simple_init(self, model, input_record, *args, **kwargs):
15  ModelLayer.__init__(self, model, self.operator, input_record, **kwargs)
16  assert self.operator is not None, "Try to create invalid operator layer"
17  self.args = args
18  self.output_schema = schema.NewRecord(self.model.net, input_record)
19 
20 
21 def first_field_schema_init(self, model, input_record, *args, **kwargs):
22  ModelLayer.__init__(self, model, self.operator, input_record, **kwargs)
23  assert self.operator is not None, "Try to create invalid operator layer"
24  assert isinstance(input_record, schema.Struct),\
25  "Operator {0} expects schema.Struct as input, received {1} instead".\
26  format(self.operator, input_record)
27  self.args = args
28  self.output_schema = schema.NewRecord(self.model.net, input_record[0])
29 
30 
31 def simple_add_ops(self, net):
32  getattr(
33  net,
34  self.operator)(
35  self.input_record.field_blobs(),
36  self.output_schema.field_blobs(),
37  *self.args,
38  **self.kwargs
39  )
40 
41 _simple_operators = ['Softmax', 'Relu', 'Sigmoid', 'Tanh']
42 _first_field_schema_operators = ['Sum']
43 
44 # We need to store refs for all created types, to make sure that they won't be
45 # GCed before we actually register them.
46 _known_layers = []
47 
48 for operator in _simple_operators:
49  # Generate class instance with name 'operator', that is doing going to use
50  # simple_init and simple_add_ops implementations for __init__ and add_ops
51  # calls. It'll also get automatically registered in the registry.
52  _known_layers.append(
53  type(
54  str(operator),
55  (ModelLayer,),
56  {'__init__': simple_init,
57  'add_ops': simple_add_ops,
58  'operator': operator
59  }
60  )
61  )
62 
63 for operator in _first_field_schema_operators:
64  # Generate class instance with name 'operator', that is doing going to use
65  # first_field_schema_init and simple_add_ops implementations for __init__
66  # and add_ops calls. It'll also get automatically registered in the
67  # registry.
68  _known_layers.append(
69  type(
70  str(operator),
71  (ModelLayer,),
72  {'__init__': first_field_schema_init,
73  'add_ops': simple_add_ops,
74  'operator': operator
75  }
76  )
77  )
def NewRecord(net, schema)
Definition: schema.py:908