convert_parameters.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from collections.abc import Iterable
  2. from typing import Optional
  3. import torch
  4. def parameters_to_vector(parameters: Iterable[torch.Tensor]) -> torch.Tensor:
  5. r"""Flatten an iterable of parameters into a single vector.
  6. Args:
  7. parameters (Iterable[Tensor]): an iterable of Tensors that are the
  8. parameters of a model.
  9. Returns:
  10. The parameters represented by a single vector
  11. """
  12. # Flag for the device where the parameter is located
  13. param_device = None
  14. vec = []
  15. for param in parameters:
  16. # Ensure the parameters are located in the same device
  17. param_device = _check_param_device(param, param_device)
  18. vec.append(param.view(-1))
  19. return torch.cat(vec)
  20. def vector_to_parameters(vec: torch.Tensor, parameters: Iterable[torch.Tensor]) -> None:
  21. r"""Copy slices of a vector into an iterable of parameters.
  22. Args:
  23. vec (Tensor): a single vector representing the parameters of a model.
  24. parameters (Iterable[Tensor]): an iterable of Tensors that are the
  25. parameters of a model.
  26. """
  27. # Ensure vec of type Tensor
  28. if not isinstance(vec, torch.Tensor):
  29. raise TypeError(f"expected torch.Tensor, but got: {torch.typename(vec)}")
  30. # Flag for the device where the parameter is located
  31. param_device = None
  32. # Pointer for slicing the vector for each parameter
  33. pointer = 0
  34. for param in parameters:
  35. # Ensure the parameters are located in the same device
  36. param_device = _check_param_device(param, param_device)
  37. # The length of the parameter
  38. num_param = param.numel()
  39. # Slice the vector, reshape it, and replace the old data of the parameter
  40. param.data = vec[pointer : pointer + num_param].view_as(param).data
  41. # Increment the pointer
  42. pointer += num_param
  43. def _check_param_device(param: torch.Tensor, old_param_device: Optional[int]) -> int:
  44. r"""Check if the parameters are located on the same device.
  45. Currently, the conversion between model parameters and single vector form is not supported
  46. for multiple allocations, e.g. parameters in different GPUs/PrivateUse1s, or mixture of CPU/GPU/PrivateUse1.
  47. Args:
  48. param ([Tensor]): a Tensor of a parameter of a model
  49. old_param_device (int): the device where the first parameter of a
  50. model is allocated.
  51. Returns:
  52. old_param_device (int): report device for the first time
  53. """
  54. # Meet the first parameter
  55. support_device_types = ["cuda", torch._C._get_privateuse1_backend_name()]
  56. if old_param_device is None:
  57. old_param_device = (
  58. param.get_device() if param.device.type in support_device_types else -1
  59. )
  60. else:
  61. warn = False
  62. if (
  63. param.device.type in support_device_types
  64. ): # Check if in same GPU/PrivateUse1
  65. warn = param.get_device() != old_param_device
  66. else: # Check if in CPU
  67. warn = old_param_device != -1
  68. if warn:
  69. raise TypeError(
  70. "Found two parameters on different devices, "
  71. "this is currently not supported."
  72. )
  73. return old_param_device