MCPcopy Create free account
hub / github.com/Project-MONAI/MONAI / train_mode

Function train_mode

monai/networks/utils.py:493–525  ·  view source on GitHub ↗

Set network(s) to train mode and then return to original state at the end. Args: nets: Input network(s) Examples .. code-block:: python t=torch.rand(1,1,16,16) p=torch.nn.Conv2d(1,1,3) p.eval() print(p.training) # False with train

(*nets: nn.Module)

Source from the content-addressed store, hash-verified

491
492@contextmanager
493def train_mode(*nets: nn.Module):
494 """
495 Set network(s) to train mode and then return to original state at the end.
496
497 Args:
498 nets: Input network(s)
499
500 Examples
501
502 .. code-block:: python
503
504 t=torch.rand(1,1,16,16)
505 p=torch.nn.Conv2d(1,1,3)
506 p.eval()
507 print(p.training) # False
508 with train_mode(p):
509 print(p.training) # True
510 print(p(t).sum().backward()) # No exception
511 """
512
513 # Get original state of network(s)
514 # Check the training attribute in case it's TensorRT based models which don't have this attribute.
515 eval_list = [n for n in nets if hasattr(n, "training") and (not n.training)]
516
517 try:
518 # set to train mode
519 with torch.set_grad_enabled(True):
520 yield [n.train() if hasattr(n, "train") else n for n in nets]
521 finally:
522 # Return required networks to eval_list
523 for n in eval_list:
524 if hasattr(n, "eval"):
525 n.eval()
526
527
528def get_state_dict(obj: torch.nn.Module | Mapping):

Calls 1

trainMethod · 0.45

Used in the wild real call sites across dependent graphs

searching dependent graphs…