4 def parameters_to_vector(parameters):
5 r"""Convert parameters to one vector 8 parameters (Iterable[Tensor]): an iterator of Tensors that are the 12 The parameters represented by a single vector 18 for param
in parameters:
20 param_device = _check_param_device(param, param_device)
22 vec.append(param.view(-1))
26 def vector_to_parameters(vec, parameters):
27 r"""Convert one vector to the parameters 30 vec (Tensor): a single vector represents the parameters of a model. 31 parameters (Iterable[Tensor]): an iterator of Tensors that are the 32 parameters of a model. 35 if not isinstance(vec, torch.Tensor):
36 raise TypeError(
'expected torch.Tensor, but got: {}' 43 for param
in parameters:
45 param_device = _check_param_device(param, param_device)
48 num_param = param.numel()
50 param.data = vec[pointer:pointer + num_param].view_as(param).data
56 def _check_param_device(param, old_param_device):
57 r"""This helper function is to check if the parameters are located 58 in the same device. Currently, the conversion between model parameters 59 and single vector form is not supported for multiple allocations, 60 e.g. parameters in different GPUs, or mixture of CPU/GPU. 63 param ([Tensor]): a Tensor of a parameter of a model 64 old_param_device (int): the device where the first parameter of a 68 old_param_device (int): report device for the first time 72 if old_param_device
is None:
73 old_param_device = param.get_device()
if param.is_cuda
else -1
77 warn = (param.get_device() != old_param_device)
79 warn = (old_param_device != -1)
81 raise TypeError(
'Found two parameters on different devices, ' 82 'this is currently not supported.')
83 return old_param_device
def typename(o)
Define basic utilities.