mirror of
https://github.com/zebrajr/pytorch.git
synced 2026-01-15 12:15:51 +00:00
Summary: this diff adds optimizer into param_info, and the associated implementations for modelhelper and brew to set optimizer for each individual parameter. Reviewed By: kennyhorror Differential Revision: D5385432 fbshipit-source-id: 5d682f9d1ab077e04a5d76a24d71470f4e64fc92
77 lines
2.2 KiB
Python
77 lines
2.2 KiB
Python
from __future__ import absolute_import
|
|
from __future__ import division
|
|
from __future__ import print_function
|
|
from __future__ import unicode_literals
|
|
|
|
from caffe2.python import core
|
|
|
|
import numpy as np
|
|
|
|
|
|
class ParameterTags(object):
|
|
BIAS = 'BIAS'
|
|
WEIGHT = 'WEIGHT'
|
|
COMPUTED_PARAM = 'COMPUTED_PARAM'
|
|
|
|
|
|
class ParameterType(object):
|
|
DENSE = 'dense'
|
|
SPARSE = 'sparse'
|
|
|
|
|
|
class ParameterInfo(object):
|
|
|
|
def __init__(
|
|
self, param_id, param, key=None, shape=None, length=None,
|
|
grad=None, blob_copy=None):
|
|
assert isinstance(param, core.BlobReference)
|
|
self.param_id = param_id
|
|
self.name = str(param)
|
|
self.blob = param
|
|
self.key = key
|
|
self.shape = shape
|
|
self.size = None if shape is None else np.prod(shape)
|
|
self.length = max(1, length if length is not None else 1)
|
|
self.grad = grad
|
|
self._cloned_init_net = None
|
|
# Optionally store equivalent copies of the blob
|
|
# in different precisions (i.e. half and float copies)
|
|
# stored as a dict of TensorProto.DataType -> BlobReference
|
|
self.blob_copy = blob_copy
|
|
# each param_info can have its own optimizer. It can be set within
|
|
# OptimizerContext (caffe2/python/optimizer.py)
|
|
self._optimizer = None
|
|
|
|
def grad_type(self):
|
|
# self.grad could be None for model parallelism with parameter server
|
|
if self.grad is None:
|
|
return
|
|
return (
|
|
ParameterType.SPARSE if isinstance(self.grad, core.GradientSlice)
|
|
else ParameterType.DENSE)
|
|
|
|
def cloned_init_net(self):
|
|
if not self._cloned_init_net:
|
|
init_net, outputs = self.blob.Net().ClonePartial(
|
|
'param_%d_%s_init' % (self.param_id, self.name),
|
|
inputs=[],
|
|
outputs=[self.blob])
|
|
self._cloned_init_net = (init_net, outputs[0])
|
|
return self._cloned_init_net
|
|
|
|
@property
|
|
def parameter(self):
|
|
return self.blob
|
|
|
|
@property
|
|
def optimizer(self):
|
|
return self._optimizer
|
|
|
|
@optimizer.setter
|
|
def optimizer(self, value):
|
|
assert self._optimizer is None, "optimizer has already been set"
|
|
self._optimizer = value
|
|
|
|
def __str__(self):
|
|
return self.name
|