:api_attr: Static Graph Change the global main program and startup program with ``with`` statement. Layer functions in the Python ``with`` block will append operators and Tensors to the new main programs. Args: main_program(Program): New main program inside ``with`` st
(
main_program: Program, startup_program: Program | None = None
)
| 8149 | |
| 8150 | @signature_safe_contextmanager |
| 8151 | def program_guard( |
| 8152 | main_program: Program, startup_program: Program | None = None |
| 8153 | ) -> Generator[None, None, None]: |
| 8154 | """ |
| 8155 | :api_attr: Static Graph |
| 8156 | |
| 8157 | Change the global main program and startup program with ``with`` statement. |
| 8158 | Layer functions in the Python ``with`` block will append operators and |
| 8159 | Tensors to the new main programs. |
| 8160 | |
| 8161 | Args: |
| 8162 | main_program(Program): New main program inside ``with`` statement. |
| 8163 | startup_program(Program, optional): New startup program inside ``with`` |
| 8164 | statement. :code:`None` means not changing startup program, |
| 8165 | default_startup_program is still used. |
| 8166 | Default: None. |
| 8167 | |
| 8168 | Examples: |
| 8169 | .. code-block:: pycon |
| 8170 | :name: code-example-1 |
| 8171 | |
| 8172 | >>> import paddle |
| 8173 | |
| 8174 | >>> paddle.enable_static() |
| 8175 | >>> main_program = paddle.static.Program() |
| 8176 | >>> startup_program = paddle.static.Program() |
| 8177 | >>> with paddle.static.program_guard(main_program, startup_program): |
| 8178 | ... data = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32') |
| 8179 | ... hidden = paddle.static.nn.fc(x=data, size=10, activation='relu') |
| 8180 | |
| 8181 | Notes: The temporary :code:`Program` can be used if the user does not need |
| 8182 | to construct either of startup program or main program. |
| 8183 | |
| 8184 | Examples: |
| 8185 | .. code-block:: pycon |
| 8186 | :name: code-example-2 |
| 8187 | |
| 8188 | >>> import paddle |
| 8189 | |
| 8190 | >>> paddle.enable_static() |
| 8191 | >>> main_program = paddle.static.Program() |
| 8192 | >>> # does not care about startup program. Just pass a temporary value. |
| 8193 | >>> with paddle.static.program_guard(main_program, paddle.static.Program()): |
| 8194 | ... data = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32') |
| 8195 | |
| 8196 | """ |
| 8197 | from .data_feeder import check_type |
| 8198 | |
| 8199 | check_type( |
| 8200 | main_program, "main_program", Program, "paddle.static.program_guard" |
| 8201 | ) |
| 8202 | main_program = switch_main_program(main_program) |
| 8203 | if startup_program is not None: |
| 8204 | check_type( |
| 8205 | startup_program, |
| 8206 | "startup_program", |
| 8207 | Program, |
| 8208 | "paddle.static.program_guard", |