: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, startup_program=None)
| 260 | |
| 261 | @signature_safe_contextmanager |
| 262 | def program_guard(main_program, startup_program=None): |
| 263 | """ |
| 264 | :api_attr: Static Graph |
| 265 | |
| 266 | Change the global main program and startup program with ``with`` statement. |
| 267 | Layer functions in the Python ``with`` block will append operators and |
| 268 | Tensors to the new main programs. |
| 269 | |
| 270 | Args: |
| 271 | main_program(Program): New main program inside ``with`` statement. |
| 272 | startup_program(Program, optional): New startup program inside ``with`` |
| 273 | statement. :code:`None` means not changing startup program, |
| 274 | default_startup_program is still used. |
| 275 | Default: None. |
| 276 | |
| 277 | Examples: |
| 278 | .. code-block:: pycon |
| 279 | :name: code-example-1 |
| 280 | |
| 281 | >>> import paddle |
| 282 | |
| 283 | >>> paddle.enable_static() |
| 284 | >>> main_program = paddle.static.Program() |
| 285 | >>> startup_program = paddle.static.Program() |
| 286 | >>> with paddle.static.program_guard(main_program, startup_program): |
| 287 | ... data = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32') |
| 288 | ... hidden = paddle.static.nn.fc(x=data, size=10, activation='relu') |
| 289 | |
| 290 | Notes: The temporary :code:`Program` can be used if the user does not need |
| 291 | to construct either of startup program or main program. |
| 292 | |
| 293 | Examples: |
| 294 | .. code-block:: pycon |
| 295 | :name: code-example-2 |
| 296 | |
| 297 | >>> import paddle |
| 298 | |
| 299 | >>> paddle.enable_static() |
| 300 | >>> main_program = paddle.static.Program() |
| 301 | >>> # does not care about startup program. Just pass a temporary value. |
| 302 | >>> with paddle.static.program_guard(main_program, paddle.static.Program()): |
| 303 | ... data = paddle.static.data(name='image', shape=[None, 784, 784], dtype='float32') |
| 304 | """ |
| 305 | from ..base.data_feeder import check_type |
| 306 | |
| 307 | check_type( |
| 308 | main_program, 'main_program', Program, 'paddle.static.program_guard' |
| 309 | ) |
| 310 | main_program, prev_insertion_point = switch_main_program(main_program) |
| 311 | if startup_program is not None: |
| 312 | check_type( |
| 313 | startup_program, |
| 314 | 'startup_program', |
| 315 | Program, |
| 316 | 'paddle.static.program_guard', |
| 317 | ) |
| 318 | startup_program = switch_startup_program(startup_program) |
| 319 | try: |