Caffe2 - Python API
A deep learning, cross platform ML framework
blob_weighted_sum.py
1 ## @package BlobWeightedSum
2 # Module caffe2.python.layers.blob_weighted_sum
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 ModelLayer
10 
11 
13  """
14  This layer implements the weighted sum:
15  weighted element-wise sum of input blobs.
16  """
17  def __init__(
18  self,
19  model,
20  input_record,
21  init_weights=None,
22  weight_optim=None,
23  name='blob_weighted_sum',
24  **kwargs
25  ):
26  super(BlobWeightedSum, self).__init__(model, name, input_record, **kwargs)
27 
28  self.blobs = self.input_record.field_blobs()
29 
30  self.num_weights = len(self.blobs)
31  assert self.num_weights > 1, (
32  "BlobWeightedSum expects more than one input blobs"
33  )
34 
35  assert len(input_record.field_types()[0].shape) > 0, (
36  "BlobWeightedSum expects limited dimensions of the input tensor"
37  )
38 
39  assert all(
40  input_record.field_types()[0].shape == input_record.field_types()[i].shape
41  for i in range(1, self.num_weights)
42  ), "Shape of input blobs should be the same shape {}".format(
43  input_record.field_types()[0].shape
44  )
45 
46  if init_weights:
47  assert self.num_weights == len(init_weights), (
48  "the size of init_weights should be the same as input blobs, "
49  "expects {}, got {}".format(self.num_weights, len(init_weights))
50  )
51  else:
52  init_weights = [1.0] * self.num_weights
53 
54  self.weights = [
55  self.create_param(
56  param_name="w_{}".format(idx),
57  shape=[1],
58  initializer=('ConstantFill', {'value': float(init_weights[idx])}),
59  optimizer=weight_optim
60  ) for idx in range(self.num_weights)
61  ]
62 
64  input_record.field_types()[0],
65  self.get_next_blob_reference('blob_weighted_sum_out')
66  )
67 
68  def add_ops(self, net):
69  net.WeightedSum(
70  [x for pair in zip(self.blobs, self.weights) for x in pair],
71  self.output_schema(),
72  grad_on_w=True,
73  )
def get_next_blob_reference(self, name)
Definition: layers.py:349
def create_param(self, param_name, shape, initializer, optimizer, ps_param=None, regularizer=None)
Definition: layers.py:334