mirror of
https://github.com/zebrajr/pytorch.git
synced 2025-12-07 12:21:27 +01:00
Summary:
To achive this, I modified the blob name scheme defined in a layer.
Before it was scope/fc_w and scope/fc_w_auto_0 (if there is another fc
within the same scope).
Now I change it to scope/fc/w and scope/fc_auto_0/w.
That is, we rely on the uniqueness of the scoped layer name to define
names for blobs.
I also overwrote the create_param method in LayerModelHelper to let it
use the resolved name for blobs given the sharingparameter context.
There are some details such as making the initializer more structured
that I need to finalize.
Reviewed By: kennyhorror
Differential Revision: D5435132
fbshipit-source-id: a0525f5ea0977e255dd5ea765b38913f5951d455
57 lines
2.1 KiB
Python
57 lines
2.1 KiB
Python
## @package fc
|
|
# Module caffe2.python.layers.fc
|
|
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.sampling_trainable_mixin import SamplingTrainableMixin
|
|
import math
|
|
import numpy as np
|
|
|
|
|
|
class FC(SamplingTrainableMixin, ModelLayer):
|
|
|
|
def __init__(self, model, input_record, output_dims, weight_init=None,
|
|
bias_init=None, weight_optim=None, bias_optim=None, name='fc',
|
|
**kwargs):
|
|
super(FC, self).__init__(model, name, input_record, **kwargs)
|
|
assert isinstance(input_record, schema.Scalar), "Incorrect input type"
|
|
assert len(input_record.field_types()[0].shape) > 0, (
|
|
"FC expects limited dimensions of the input tensor")
|
|
|
|
input_dims = input_record.field_types()[0].shape[0]
|
|
assert input_dims > 0, (
|
|
"FC expects input dimensions > 0, got {}".format(input_dims))
|
|
|
|
scale = math.sqrt(1.0 / input_dims)
|
|
weight_init = weight_init if weight_init else (
|
|
'UniformFill', {'min': -scale, 'max': scale})
|
|
bias_init = bias_init if bias_init else (
|
|
'UniformFill', {'min': -scale, 'max': scale})
|
|
|
|
self.w = self.create_param(param_name='w',
|
|
shape=[output_dims, input_dims],
|
|
initializer=weight_init,
|
|
optimizer=weight_optim)
|
|
|
|
self.b = self.create_param(param_name='b',
|
|
shape=[output_dims, ],
|
|
initializer=bias_init,
|
|
optimizer=bias_optim)
|
|
|
|
self.output_schema = schema.Scalar(
|
|
(np.float32, (output_dims, )),
|
|
self.get_next_blob_reference('output')
|
|
)
|
|
|
|
def _add_ops(self, net, params):
|
|
net.FC(self.input_record.field_blobs() + params,
|
|
self.output_schema.field_blobs(), **self.kwargs)
|
|
|
|
@property
|
|
def param_blobs(self):
|
|
return [self.w, self.b]
|