Transform a 1-D Tensor to the input ``parameters`` . Args: vec (Tensor): A 1-D Tensor, which will be sliced and copied to the input ``parameters`` . parameters (Iterable[Tensor]): Iterable Tensors that are trainable parameters of a Layer. name(str, optional): The de
(
vec: Tensor, parameters: Iterable[Tensor], name: str | None = None
)
| 138 | |
| 139 | @dygraph_only |
| 140 | def vector_to_parameters( |
| 141 | vec: Tensor, parameters: Iterable[Tensor], name: str | None = None |
| 142 | ) -> None: |
| 143 | """ |
| 144 | Transform a 1-D Tensor to the input ``parameters`` . |
| 145 | |
| 146 | Args: |
| 147 | vec (Tensor): A 1-D Tensor, which will be sliced and copied to the input ``parameters`` . |
| 148 | parameters (Iterable[Tensor]): Iterable Tensors that are trainable parameters of a Layer. |
| 149 | name(str, optional): The default value is None. Normally there is no need for user to set this |
| 150 | property. For more information, please refer to :ref:`api_guide_Name`. |
| 151 | |
| 152 | Examples: |
| 153 | .. code-block:: pycon |
| 154 | |
| 155 | >>> import paddle |
| 156 | >>> weight_attr = paddle.ParamAttr(initializer=paddle.nn.initializer.Constant(3.0)) |
| 157 | >>> linear1 = paddle.nn.Linear(10, 15, weight_attr) |
| 158 | |
| 159 | >>> vec = paddle.nn.utils.parameters_to_vector(linear1.parameters()) |
| 160 | |
| 161 | >>> linear2 = paddle.nn.Linear(10, 15) |
| 162 | >>> # copy weight of linear1 to linear2 |
| 163 | >>> paddle.nn.utils.vector_to_parameters(vec, linear2.parameters()) |
| 164 | >>> print((linear1.weight == linear2.weight).all()) |
| 165 | Tensor(shape=[], dtype=bool, place=Place(cpu), stop_gradient=True, |
| 166 | True) |
| 167 | """ |
| 168 | assert len(vec.shape) == 1 |
| 169 | origin_shapes = [] |
| 170 | sections = [] |
| 171 | total_elements = 0 |
| 172 | for param in parameters: |
| 173 | shape = param.shape |
| 174 | origin_shapes.append(shape) |
| 175 | numel = reduce(lambda x, y: x * y, shape, 1) |
| 176 | total_elements += numel |
| 177 | sections.append(numel) |
| 178 | |
| 179 | if len(sections) == 1: |
| 180 | sections.append(0) |
| 181 | |
| 182 | if in_dygraph_mode(): |
| 183 | with paddle.base.dygraph.no_grad(): |
| 184 | res = [] |
| 185 | if total_elements == vec.shape[0]: |
| 186 | res = _C_ops.split(vec, sections, 0) |
| 187 | elif total_elements < vec.shape[0]: |
| 188 | pointer = 0 |
| 189 | for section in sections: |
| 190 | res.append(vec[pointer : pointer + section]) |
| 191 | pointer += section |
| 192 | else: |
| 193 | raise ValueError( |
| 194 | "The total_elements of vec should be equal to or larger than the number of elements in parameters." |
| 195 | ) |
| 196 | for i in range(0, len(parameters)): |
| 197 | res[i]._share_underline_tensor_to(parameters[i]) |
nothing calls this directly
no test coverage detected