Set parameters and persistable buffers in state_dict to program. An exception will throw if shape or dtype of the parameters is not match. .. note:: This function MUST called after run start_up_program Args: state_dict(dict): the dict store
(self, state_dict, scope=None)
| 7610 | return state_dict |
| 7611 | |
| 7612 | def set_state_dict(self, state_dict, scope=None): |
| 7613 | """ |
| 7614 | Set parameters and persistable buffers in state_dict to program. |
| 7615 | An exception will throw if shape or dtype of the parameters is not match. |
| 7616 | |
| 7617 | .. note:: |
| 7618 | This function MUST called after run start_up_program |
| 7619 | |
| 7620 | Args: |
| 7621 | state_dict(dict): the dict store parameters and persistable buffers. |
| 7622 | The key is the name of the parameter or the name of the buffer. |
| 7623 | The value is the tensor of this variable in the given scope. |
| 7624 | scope(Scope, optional) : If scope is None, state_dict will be set to global scope |
| 7625 | obtained through 'paddle.static.global_scope()'. Otherwise, value will be set to scope. |
| 7626 | Default: None |
| 7627 | |
| 7628 | Returns: |
| 7629 | None |
| 7630 | |
| 7631 | Examples: |
| 7632 | .. code-block:: pycon |
| 7633 | |
| 7634 | >>> import paddle |
| 7635 | >>> import paddle.static as static |
| 7636 | |
| 7637 | >>> paddle.enable_static() |
| 7638 | |
| 7639 | >>> x = static.data(name="x", shape=[10, 10], dtype='float32') |
| 7640 | >>> y = static.nn.fc(x, 10) |
| 7641 | >>> z = static.nn.fc(y, 10) |
| 7642 | |
| 7643 | >>> place = paddle.CPUPlace() |
| 7644 | >>> exe = static.Executor(place) |
| 7645 | >>> exe.run(static.default_startup_program()) |
| 7646 | >>> prog = static.default_main_program() |
| 7647 | |
| 7648 | >>> path = "./temp/model.pdparams" |
| 7649 | >>> paddle.save(prog.state_dict(), path) |
| 7650 | >>> state_dict_load = paddle.load(path) |
| 7651 | >>> prog.set_state_dict(state_dict_load) |
| 7652 | """ |
| 7653 | |
| 7654 | if not isinstance(state_dict, dict): |
| 7655 | raise TypeError( |
| 7656 | f"Type of `state_dict` should be dict, but received {type(state_dict)}." |
| 7657 | ) |
| 7658 | |
| 7659 | vars_dict = {var.name: var for var in self.list_vars()} |
| 7660 | condition = ( |
| 7661 | True if "StructuredToParameterName@@" in state_dict else False |
| 7662 | ) |
| 7663 | for name, value in state_dict.items(): |
| 7664 | if condition: |
| 7665 | if name == "StructuredToParameterName@@": |
| 7666 | continue |
| 7667 | if name in state_dict["StructuredToParameterName@@"]: |
| 7668 | name = state_dict["StructuredToParameterName@@"][name] |
| 7669 | if name in vars_dict: |