Packer¶
-
class
xitorch.
Packer
(obj: Any)[source]¶ Packer is an object that could extract the tensors in a structure and rebuild the structure from the given tensors. This object preserves the structure of the object by performing the deepcopy of the object, except for the tensor.
- Parameters
obj (Any) – Any structure object that contains tensors.
Example
>>> a = torch.tensor(1.0) >>> obj = { ... "a": a, ... "b": a * 3, ... "c": a, ... } >>> packer = xitorch.Packer(obj) >>> tensors = packer.get_param_tensor_list() >>> print(tensors) [tensor(1.), tensor(3.)] >>> new_tensors = [torch.tensor(2.0), torch.tensor(4.0)] >>> new_obj = packer.construct_from_tensor_list(new_tensors) >>> print(new_obj) {'a': tensor(2.), 'b': tensor(4.), 'c': tensor(2.)}
-
get_param_tensor_list
(unique: bool = True) → List[torch.Tensor][source]¶ Returns the list of tensors contained in the object. It will traverse down the object via elements for list, values for dictionary, or
__dict__
for object that has__dict__
attribute.- Parameters
unique (bool) – If True, then only returns the unique tensors. Otherwise, duplicates can also be returned.
- Returns
List of tensors contained in the object.
- Return type
list of torch.Tensor
-
get_param_tensor
(unique: bool = True) → Optional[torch.Tensor][source]¶ Returns the tensor parameters as a single tensor. This can be used, for example, if there are multiple parameters to be optimized using
xitorch.optimize.minimize
.- Parameters
unique (bool) – If True, then only returns the tensor from unique tensors list. Otherwise, duplicates can also be returned.
- Returns
The parameters of the object in a single tensor or None if there is no tensor contained in the object.
- Return type
torch.Tensor or None
-
construct_from_tensor_list
(tensors: List[torch.Tensor], unique: bool = True) → Any[source]¶ Construct the object from the tensor list and returns the object structure with the new tensors. Executing this does not change the state of the Packer object.
- Parameters
tensors (list of torch.Tensor) – The tensor parameters to be filled into the object.
unique (bool) – Indicating if the tensor list
tensors
is from the unique parameters of the object.
- Returns
A new object with the same structure as the input to
__init__
object except the tensor is changed according totensors
.- Return type
Any
-
construct_from_tensor
(a: torch.Tensor, unique: bool = True) → Any[source]¶ Construct the object from the single tensor (i.e. it is the parameters tensor merged into a single tensor) and returns the object structure with the new tensor. Executing this does not change the state of the Packer object.
- Parameters
a (torch.Tensor) – The single tensor parameter to be filled.
unique (bool) – Indicating if the tensor
a
is from the unique parameters of the object.
- Returns
A new object with the same structure as the input to
__init__
object except the tensor is changed according toa
.- Return type
Any