code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def run_evaluation(config_filepath, backend="nccl", with_clearml=True): """Main entry to run model's evaluation: - compute validation metrics Args: config_filepath (str): evaluation configuration .py file backend (str): distributed backend: nccl, gloo, horovod or None to run without dis...
Main entry to run model's evaluation: - compute validation metrics Args: config_filepath (str): evaluation configuration .py file backend (str): distributed backend: nccl, gloo, horovod or None to run without distributed config with_clearml (bool): if True, uses ClearML as experimen...
run_evaluation
python
pytorch/ignite
examples/references/classification/imagenet/main.py
https://github.com/pytorch/ignite/blob/master/examples/references/classification/imagenet/main.py
BSD-3-Clause
def make_grid( batch_img: torch.Tensor, batch_preds: torch.Tensor, img_denormalize_fn: Callable, batch_gt: Optional[torch.Tensor] = None, ): """Create a grid from batch image and mask as i+l1+gt1 | i+l2+gt2 | i+l3+gt3 | i+l4+gt4 | ... where i+l+gt = image + predicted label + gr...
Create a grid from batch image and mask as i+l1+gt1 | i+l2+gt2 | i+l3+gt3 | i+l4+gt4 | ... where i+l+gt = image + predicted label + ground truth Args: batch_img (torch.Tensor) batch of images of any type batch_preds (torch.Tensor) batch of masks img_denormalize_fn (Cal...
make_grid
python
pytorch/ignite
examples/references/classification/imagenet/vis.py
https://github.com/pytorch/ignite/blob/master/examples/references/classification/imagenet/vis.py
BSD-3-Clause
def download_datasets(output_path): """Helper tool to download datasets Args: output_path (str): path where to download and unzip the dataset """ from torchvision.datasets.sbd import SBDataset from torchvision.datasets.voc import VOCSegmentation output_path = Path(output_path) outp...
Helper tool to download datasets Args: output_path (str): path where to download and unzip the dataset
download_datasets
python
pytorch/ignite
examples/references/segmentation/pascal_voc2012/main.py
https://github.com/pytorch/ignite/blob/master/examples/references/segmentation/pascal_voc2012/main.py
BSD-3-Clause
def run_training(config_filepath, backend="nccl", with_clearml=True): """Main entry to run training experiment Args: config_filepath (str): training configuration .py file backend (str): distributed backend: nccl, gloo, horovod or None to run without distributed config with_clearml (boo...
Main entry to run training experiment Args: config_filepath (str): training configuration .py file backend (str): distributed backend: nccl, gloo, horovod or None to run without distributed config with_clearml (bool): if True, uses ClearML as experiment tracking system
run_training
python
pytorch/ignite
examples/references/segmentation/pascal_voc2012/main.py
https://github.com/pytorch/ignite/blob/master/examples/references/segmentation/pascal_voc2012/main.py
BSD-3-Clause
def make_grid(batch_img, batch_mask, img_denormalize_fn, batch_gt_mask=None): """Create a grid from batch image and mask as img1 | img2 | img3 | img4 | ... i+m1 | i+m2 | i+m3 | i+m4 | ... mask1 | mask2 | mask3 | mask4 | ... i+M1 | i+M2 | i+M3 | i+M4 | ... Mask1 |...
Create a grid from batch image and mask as img1 | img2 | img3 | img4 | ... i+m1 | i+m2 | i+m3 | i+m4 | ... mask1 | mask2 | mask3 | mask4 | ... i+M1 | i+M2 | i+M3 | i+M4 | ... Mask1 | Mask2 | Mask3 | Mask4 | ... i+m = image + mask blended with alpha=0.4 ...
make_grid
python
pytorch/ignite
examples/references/segmentation/pascal_voc2012/vis.py
https://github.com/pytorch/ignite/blob/master/examples/references/segmentation/pascal_voc2012/vis.py
BSD-3-Clause
def group_examples(self): """ To ease the accessibility of data based on the class, we will use `group_examples` to group examples based on class. The data classes have already been mapped to numeric values and so are the target outputs for each training input Every key in `grou...
To ease the accessibility of data based on the class, we will use `group_examples` to group examples based on class. The data classes have already been mapped to numeric values and so are the target outputs for each training input Every key in `grouped_examples` corresponds to a class ...
group_examples
python
pytorch/ignite
examples/siamese_network/siamese_network.py
https://github.com/pytorch/ignite/blob/master/examples/siamese_network/siamese_network.py
BSD-3-Clause
def __getitem__(self, index): """ For every sample in the batch we select 3 images. First one is the anchor image which is the image obtained from the current index. We also obtain the label of anchor image. Now we select two random images, one belonging to the same class as tha...
For every sample in the batch we select 3 images. First one is the anchor image which is the image obtained from the current index. We also obtain the label of anchor image. Now we select two random images, one belonging to the same class as that of the anchor image (named as p...
__getitem__
python
pytorch/ignite
examples/siamese_network/siamese_network.py
https://github.com/pytorch/ignite/blob/master/examples/siamese_network/siamese_network.py
BSD-3-Clause
def run( seed=543, data_dir="/tmp/data", output_dir="/tmp/output-imdb/", model="bert-base-uncased", model_dir="/tmp/model", tokenizer_dir="/tmp/tokenizer", num_classes=1, dropout=0.3, n_fc=768, max_length=256, batch_size=32, weight_decay=0.01, num_workers=4, num_e...
Main entry to fintune a transformer model on the IMDB dataset for sentiment classification. Args: seed (int): random state seed to set. Default, 543. data_dir (str): dataset cache directory. Default, "/tmp/data". output_path (str): output path. Default, "/tmp/output-IMDB". model (str...
run
python
pytorch/ignite
examples/transformers/main.py
https://github.com/pytorch/ignite/blob/master/examples/transformers/main.py
BSD-3-Clause
def convert_tensor( x: Union[torch.Tensor, collections.Sequence, collections.Mapping, str, bytes], device: Optional[Union[str, torch.device]] = None, non_blocking: bool = False, ) -> Union[torch.Tensor, collections.Sequence, collections.Mapping, str, bytes]: """Move tensors to relevant device. Args...
Move tensors to relevant device. Args: x: input tensor or mapping, or sequence of tensors. device: device type to move ``x``. non_blocking: convert a CPU Tensor with pinned memory to a CUDA Tensor asynchronously with respect to the host if possible
convert_tensor
python
pytorch/ignite
ignite/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/utils.py
BSD-3-Clause
def apply_to_tensor( x: Union[torch.Tensor, collections.Sequence, collections.Mapping, str, bytes], func: Callable ) -> Union[torch.Tensor, collections.Sequence, collections.Mapping, str, bytes]: """Apply a function on a tensor or mapping, or sequence of tensors. Args: x: input tensor or mapping, o...
Apply a function on a tensor or mapping, or sequence of tensors. Args: x: input tensor or mapping, or sequence of tensors. func: the function to apply on ``x``.
apply_to_tensor
python
pytorch/ignite
ignite/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/utils.py
BSD-3-Clause
def apply_to_type( x: Union[Any, collections.Sequence, collections.Mapping, str, bytes], input_type: Union[Type, Tuple[Type[Any], Any]], func: Callable, ) -> Union[Any, collections.Sequence, collections.Mapping, str, bytes]: """Apply a function on an object of `input_type` or mapping, or sequence of obj...
Apply a function on an object of `input_type` or mapping, or sequence of objects of `input_type`. Args: x: object or mapping or sequence. input_type: data type of ``x``. func: the function to apply on ``x``.
apply_to_type
python
pytorch/ignite
ignite/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/utils.py
BSD-3-Clause
def _to_str_list(data: Any) -> List[str]: """ Recursively flattens and formats complex data structures, including keys for dictionaries, into a list of human-readable strings. This function processes nested dictionaries, lists, tuples, numbers, and PyTorch tensors, formatting numbers to four decima...
Recursively flattens and formats complex data structures, including keys for dictionaries, into a list of human-readable strings. This function processes nested dictionaries, lists, tuples, numbers, and PyTorch tensors, formatting numbers to four decimal places and handling tensors with special fo...
_to_str_list
python
pytorch/ignite
ignite/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/utils.py
BSD-3-Clause
def to_onehot(indices: torch.Tensor, num_classes: int) -> torch.Tensor: """Convert a tensor of indices of any shape `(N, ...)` to a tensor of one-hot indicators of shape `(N, num_classes, ...)` and of type uint8. Output's device is equal to the input's device`. Args: indices: input tensor to co...
Convert a tensor of indices of any shape `(N, ...)` to a tensor of one-hot indicators of shape `(N, num_classes, ...)` and of type uint8. Output's device is equal to the input's device`. Args: indices: input tensor to convert. num_classes: number of classes for one-hot tensor. .. versi...
to_onehot
python
pytorch/ignite
ignite/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/utils.py
BSD-3-Clause
def setup_logger( name: Optional[str] = "ignite", level: int = logging.INFO, stream: Optional[TextIO] = None, format: str = "%(asctime)s %(name)s %(levelname)s: %(message)s", filepath: Optional[str] = None, distributed_rank: Optional[int] = None, reset: bool = False, encoding: Optional[s...
Setups logger: name, level, format etc. Args: name: new name for the logger. If None, the standard logger is used. level: logging level, e.g. CRITICAL, ERROR, WARNING, INFO, DEBUG. stream: logging stream. If None, the standard stream is used (sys.stderr). format: logging format. By ...
setup_logger
python
pytorch/ignite
ignite/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/utils.py
BSD-3-Clause
def manual_seed(seed: int) -> None: """Setup random state from a seed for `torch`, `random` and optionally `numpy` (if can be imported). Args: seed: Random state seed .. versionchanged:: 0.4.3 Added ``torch.cuda.manual_seed_all(seed)``. .. versionchanged:: 0.4.5 Added ``torch_...
Setup random state from a seed for `torch`, `random` and optionally `numpy` (if can be imported). Args: seed: Random state seed .. versionchanged:: 0.4.3 Added ``torch.cuda.manual_seed_all(seed)``. .. versionchanged:: 0.4.5 Added ``torch_xla.core.xla_model.set_rng_state(seed)``. ...
manual_seed
python
pytorch/ignite
ignite/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/utils.py
BSD-3-Clause
def hash_checkpoint(checkpoint_path: Union[str, Path], output_dir: Union[str, Path]) -> Tuple[Path, str]: """ Hash the checkpoint file in the format of ``<filename>-<hash>.<ext>`` to be used with ``check_hash`` of :func:`torch.hub.load_state_dict_from_url`. Args: checkpoint_path: Path to the ch...
Hash the checkpoint file in the format of ``<filename>-<hash>.<ext>`` to be used with ``check_hash`` of :func:`torch.hub.load_state_dict_from_url`. Args: checkpoint_path: Path to the checkpoint file. output_dir: Output directory to store the hashed checkpoint file (will be crea...
hash_checkpoint
python
pytorch/ignite
ignite/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/utils.py
BSD-3-Clause
def setup_common_training_handlers( trainer: Engine, train_sampler: Optional[DistributedSampler] = None, to_save: Optional[Mapping] = None, save_every_iters: int = 1000, output_path: Optional[str] = None, lr_scheduler: Optional[Union[ParamScheduler, PyTorchLRScheduler]] = None, with_gpu_stat...
Helper method to setup trainer with common handlers (it also supports distributed configuration): - :class:`~ignite.handlers.terminate_on_nan.TerminateOnNan` - handler to setup learning rate scheduling - :class:`~ignite.handlers.checkpoint.ModelCheckpoint` - :class:`~ignite.metrics.Runn...
setup_common_training_handlers
python
pytorch/ignite
ignite/contrib/engines/common.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/common.py
BSD-3-Clause
def setup_tb_logging( output_path: str, trainer: Engine, optimizers: Optional[Union[Optimizer, Dict[str, Optimizer]]] = None, evaluators: Optional[Union[Engine, Dict[str, Engine]]] = None, log_every_iters: int = 100, **kwargs: Any, ) -> TensorboardLogger: """Method to setup TensorBoard loggi...
Method to setup TensorBoard logging on trainer and a list of evaluators. Logged metrics are: - Training metrics, e.g. running average loss values - Learning rate(s) - Evaluation metrics Args: output_path: logging directory path trainer: trainer engine optimizers: si...
setup_tb_logging
python
pytorch/ignite
ignite/contrib/engines/common.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/common.py
BSD-3-Clause
def setup_visdom_logging( trainer: Engine, optimizers: Optional[Union[Optimizer, Dict[str, Optimizer]]] = None, evaluators: Optional[Union[Engine, Dict[str, Engine]]] = None, log_every_iters: int = 100, **kwargs: Any, ) -> VisdomLogger: """Method to setup Visdom logging on trainer and a list of ...
Method to setup Visdom logging on trainer and a list of evaluators. Logged metrics are: - Training metrics, e.g. running average loss values - Learning rate(s) - Evaluation metrics Args: trainer: trainer engine optimizers: single or dictionary of torch optimizer...
setup_visdom_logging
python
pytorch/ignite
ignite/contrib/engines/common.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/common.py
BSD-3-Clause
def setup_mlflow_logging( trainer: Engine, optimizers: Optional[Union[Optimizer, Dict[str, Optimizer]]] = None, evaluators: Optional[Union[Engine, Dict[str, Engine]]] = None, log_every_iters: int = 100, **kwargs: Any, ) -> MLflowLogger: """Method to setup MLflow logging on trainer and a list of ...
Method to setup MLflow logging on trainer and a list of evaluators. Logged metrics are: - Training metrics, e.g. running average loss values - Learning rate(s) - Evaluation metrics Args: trainer: trainer engine optimizers: single or dictionary of torch optimizer...
setup_mlflow_logging
python
pytorch/ignite
ignite/contrib/engines/common.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/common.py
BSD-3-Clause
def setup_neptune_logging( trainer: Engine, optimizers: Optional[Union[Optimizer, Dict[str, Optimizer]]] = None, evaluators: Optional[Union[Engine, Dict[str, Engine]]] = None, log_every_iters: int = 100, **kwargs: Any, ) -> NeptuneLogger: """Method to setup Neptune logging on trainer and a list ...
Method to setup Neptune logging on trainer and a list of evaluators. Logged metrics are: - Training metrics, e.g. running average loss values - Learning rate(s) - Evaluation metrics Args: trainer: trainer engine optimizers: single or dictionary of torch optimize...
setup_neptune_logging
python
pytorch/ignite
ignite/contrib/engines/common.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/common.py
BSD-3-Clause
def setup_wandb_logging( trainer: Engine, optimizers: Optional[Union[Optimizer, Dict[str, Optimizer]]] = None, evaluators: Optional[Union[Engine, Dict[str, Engine]]] = None, log_every_iters: int = 100, **kwargs: Any, ) -> WandBLogger: """Method to setup WandB logging on trainer and a list of eva...
Method to setup WandB logging on trainer and a list of evaluators. Logged metrics are: - Training metrics, e.g. running average loss values - Learning rate(s) - Evaluation metrics Args: trainer: trainer engine optimizers: single or dictionary of torch optimizers...
setup_wandb_logging
python
pytorch/ignite
ignite/contrib/engines/common.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/common.py
BSD-3-Clause
def setup_plx_logging( trainer: Engine, optimizers: Optional[Union[Optimizer, Dict[str, Optimizer]]] = None, evaluators: Optional[Union[Engine, Dict[str, Engine]]] = None, log_every_iters: int = 100, **kwargs: Any, ) -> PolyaxonLogger: """Method to setup Polyaxon logging on trainer and a list of...
Method to setup Polyaxon logging on trainer and a list of evaluators. Logged metrics are: - Training metrics, e.g. running average loss values - Learning rate(s) - Evaluation metrics Args: trainer: trainer engine optimizers: single or dictionary of torch optimiz...
setup_plx_logging
python
pytorch/ignite
ignite/contrib/engines/common.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/common.py
BSD-3-Clause
def setup_clearml_logging( trainer: Engine, optimizers: Optional[Union[Optimizer, Dict[str, Optimizer]]] = None, evaluators: Optional[Union[Engine, Dict[str, Engine]]] = None, log_every_iters: int = 100, **kwargs: Any, ) -> ClearMLLogger: """Method to setup ClearML logging on trainer and a list ...
Method to setup ClearML logging on trainer and a list of evaluators. Logged metrics are: - Training metrics, e.g. running average loss values - Learning rate(s) - Evaluation metrics Args: trainer: trainer engine optimizers: single or dictionary of torch optimize...
setup_clearml_logging
python
pytorch/ignite
ignite/contrib/engines/common.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/common.py
BSD-3-Clause
def setup_trains_logging( trainer: Engine, optimizers: Optional[Union[Optimizer, Dict[str, Optimizer]]] = None, evaluators: Optional[Union[Engine, Dict[str, Engine]]] = None, log_every_iters: int = 100, **kwargs: Any, ) -> ClearMLLogger: """``setup_trains_logging`` was renamed to :func:`~ignite....
``setup_trains_logging`` was renamed to :func:`~ignite.contrib.engines.common.setup_clearml_logging`.
setup_trains_logging
python
pytorch/ignite
ignite/contrib/engines/common.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/common.py
BSD-3-Clause
def gen_save_best_models_by_val_score( save_handler: Union[Callable, BaseSaveHandler], evaluator: Engine, models: Union[torch.nn.Module, Dict[str, torch.nn.Module]], metric_name: str, n_saved: int = 3, trainer: Optional[Engine] = None, tag: str = "val", score_sign: float = 1.0, **kwa...
Method adds a handler to ``evaluator`` to save ``n_saved`` of best models based on the metric (named by ``metric_name``) provided by ``evaluator`` (i.e. ``evaluator.state.metrics[metric_name]``). Models with highest metric value will be retained. The logic of how to store objects is delegated to ``save_hand...
gen_save_best_models_by_val_score
python
pytorch/ignite
ignite/contrib/engines/common.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/common.py
BSD-3-Clause
def save_best_model_by_val_score( output_path: str, evaluator: Engine, model: torch.nn.Module, metric_name: str, n_saved: int = 3, trainer: Optional[Engine] = None, tag: str = "val", score_sign: float = 1.0, **kwargs: Any, ) -> Checkpoint: """Method adds a handler to ``evaluator`...
Method adds a handler to ``evaluator`` to save on a disk ``n_saved`` of best models based on the metric (named by ``metric_name``) provided by ``evaluator`` (i.e. ``evaluator.state.metrics[metric_name]``). Models with highest metric value will be retained. Args: output_path: output path to indicate...
save_best_model_by_val_score
python
pytorch/ignite
ignite/contrib/engines/common.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/common.py
BSD-3-Clause
def add_early_stopping_by_val_score( patience: int, evaluator: Engine, trainer: Engine, metric_name: str, score_sign: float = 1.0, ) -> EarlyStopping: """Method setups early stopping handler based on the score (named by `metric_name`) provided by `evaluator`. Metric value should increase in ...
Method setups early stopping handler based on the score (named by `metric_name`) provided by `evaluator`. Metric value should increase in order to keep training and not early stop. Args: patience: number of events to wait if no improvement and then stop the training. evaluator: evaluation engin...
add_early_stopping_by_val_score
python
pytorch/ignite
ignite/contrib/engines/common.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/common.py
BSD-3-Clause
def _detach_hidden( hidden: Union[torch.Tensor, Sequence, Mapping, str, bytes] ) -> Union[torch.Tensor, collections.Sequence, collections.Mapping, str, bytes]: """Cut backpropagation graph. Auxillary function to cut the backpropagation graph by detaching the hidden vector. """ return apply_to_t...
Cut backpropagation graph. Auxillary function to cut the backpropagation graph by detaching the hidden vector.
_detach_hidden
python
pytorch/ignite
ignite/contrib/engines/tbptt.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/tbptt.py
BSD-3-Clause
def create_supervised_tbptt_trainer( model: nn.Module, optimizer: Optimizer, loss_fn: nn.Module, tbtt_step: int, dim: int = 0, device: Optional[str] = None, non_blocking: bool = False, prepare_batch: Callable = _prepare_batch, ) -> Engine: """Create a trainer for truncated backprop t...
Create a trainer for truncated backprop through time supervised models. Training recurrent model on long sequences is computationally intensive as it requires to process the whole sequence before getting a gradient. However, when the training loss is computed over many outputs (`X to many <https://karp...
create_supervised_tbptt_trainer
python
pytorch/ignite
ignite/contrib/engines/tbptt.py
https://github.com/pytorch/ignite/blob/master/ignite/contrib/engines/tbptt.py
BSD-3-Clause
def auto_dataloader(dataset: Dataset, **kwargs: Any) -> Union[DataLoader, "_MpDeviceLoader"]: """Helper method to create a dataloader adapted for non-distributed and distributed configurations (supporting all available backends from :meth:`~ignite.distributed.utils.available_backends()`). Internally, we cr...
Helper method to create a dataloader adapted for non-distributed and distributed configurations (supporting all available backends from :meth:`~ignite.distributed.utils.available_backends()`). Internally, we create a dataloader with provided kwargs while applying the following updates: - batch size is sca...
auto_dataloader
python
pytorch/ignite
ignite/distributed/auto.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/auto.py
BSD-3-Clause
def auto_model(model: nn.Module, sync_bn: bool = False, **kwargs: Any) -> nn.Module: """Helper method to adapt provided model for non-distributed and distributed configurations (supporting all available backends from :meth:`~ignite.distributed.utils.available_backends()`). Internally, we perform to followi...
Helper method to adapt provided model for non-distributed and distributed configurations (supporting all available backends from :meth:`~ignite.distributed.utils.available_backends()`). Internally, we perform to following: - send model to current :meth:`~ignite.distributed.utils.device()` if model's param...
auto_model
python
pytorch/ignite
ignite/distributed/auto.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/auto.py
BSD-3-Clause
def auto_optim(optimizer: Optimizer, **kwargs: Any) -> Optimizer: """Helper method to adapt optimizer for non-distributed and distributed configurations (supporting all available backends from :meth:`~ignite.distributed.utils.available_backends()`). Internally, this method is no-op for non-distributed and ...
Helper method to adapt optimizer for non-distributed and distributed configurations (supporting all available backends from :meth:`~ignite.distributed.utils.available_backends()`). Internally, this method is no-op for non-distributed and torch native distributed configuration. For XLA distributed configur...
auto_optim
python
pytorch/ignite
ignite/distributed/auto.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/auto.py
BSD-3-Clause
def run(self, func: Callable, *args: Any, **kwargs: Any) -> None: """Execute ``func`` with provided arguments in distributed context. Args: func: function to execute. First argument of the function should be `local_rank` - local process index. args: positional ar...
Execute ``func`` with provided arguments in distributed context. Args: func: function to execute. First argument of the function should be `local_rank` - local process index. args: positional arguments of ``func`` (without `local_rank`). kwargs: keyword argum...
run
python
pytorch/ignite
ignite/distributed/launcher.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/launcher.py
BSD-3-Clause
def sync(temporary: bool = False) -> None: """Helper method to force this module to synchronize with current distributed context. This method should be used when distributed context is manually created or destroyed. Args: temporary: If True, distributed model synchronization is done every call of `...
Helper method to force this module to synchronize with current distributed context. This method should be used when distributed context is manually created or destroyed. Args: temporary: If True, distributed model synchronization is done every call of ``idist.get_*`` methods. This may have ...
sync
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def device() -> torch.device: """Returns current device according to current distributed configuration. - `torch.device("cpu")` if no distributed configuration or torch native gloo distributed configuration - `torch.device("cuda:local_rank")` if torch native nccl or horovod distributed configuration - ...
Returns current device according to current distributed configuration. - `torch.device("cpu")` if no distributed configuration or torch native gloo distributed configuration - `torch.device("cuda:local_rank")` if torch native nccl or horovod distributed configuration - `torch.device("xla:index")` if XLA di...
device
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def backend() -> Optional[str]: """Returns computation model's backend. - `None` for no distributed configuration - "nccl" or "gloo" or "mpi" for native torch distributed configuration - "xla-tpu" for XLA distributed configuration - "horovod" for Horovod distributed framework Returns: ...
Returns computation model's backend. - `None` for no distributed configuration - "nccl" or "gloo" or "mpi" for native torch distributed configuration - "xla-tpu" for XLA distributed configuration - "horovod" for Horovod distributed framework Returns: str or None .. versionchanged:: 0....
backend
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def model_name() -> str: """Returns distributed configuration name (given by ignite) - `serial` for no distributed configuration - `native-dist` for native torch distributed configuration - `xla-dist` for XLA distributed configuration - `horovod-dist` for Horovod distributed framework .. versi...
Returns distributed configuration name (given by ignite) - `serial` for no distributed configuration - `native-dist` for native torch distributed configuration - `xla-dist` for XLA distributed configuration - `horovod-dist` for Horovod distributed framework .. versionchanged:: 0.4.2 `horov...
model_name
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def get_world_size() -> int: """Returns world size of current distributed configuration. Returns 1 if no distributed configuration.""" if _need_to_sync and isinstance(_model, _SerialModel): sync(temporary=True) return _model.get_world_size()
Returns world size of current distributed configuration. Returns 1 if no distributed configuration.
get_world_size
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def get_rank() -> int: """Returns process rank within current distributed configuration. Returns 0 if no distributed configuration.""" if _need_to_sync and isinstance(_model, _SerialModel): sync(temporary=True) return _model.get_rank()
Returns process rank within current distributed configuration. Returns 0 if no distributed configuration.
get_rank
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def get_local_rank() -> int: """Returns local process rank within current distributed configuration. Returns 0 if no distributed configuration.""" if _need_to_sync and isinstance(_model, _SerialModel): sync(temporary=True) return _model.get_local_rank()
Returns local process rank within current distributed configuration. Returns 0 if no distributed configuration.
get_local_rank
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def get_nproc_per_node() -> int: """Returns number of processes (or tasks) per node within current distributed configuration. Returns 1 if no distributed configuration. """ if _need_to_sync and isinstance(_model, _SerialModel): sync(temporary=True) return _model.get_nproc_per_node()
Returns number of processes (or tasks) per node within current distributed configuration. Returns 1 if no distributed configuration.
get_nproc_per_node
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def get_nnodes() -> int: """Returns number of nodes within current distributed configuration. Returns 1 if no distributed configuration. """ if _need_to_sync and isinstance(_model, _SerialModel): sync(temporary=True) return _model.get_nnodes()
Returns number of nodes within current distributed configuration. Returns 1 if no distributed configuration.
get_nnodes
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def get_node_rank() -> int: """Returns node rank within current distributed configuration. Returns 0 if no distributed configuration. """ if _need_to_sync and isinstance(_model, _SerialModel): sync(temporary=True) return _model.get_node_rank()
Returns node rank within current distributed configuration. Returns 0 if no distributed configuration.
get_node_rank
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def spawn( backend: str, fn: Callable, args: Tuple, kwargs_dict: Optional[Mapping] = None, nproc_per_node: int = 1, **kwargs: Any, ) -> None: """Spawns ``nproc_per_node`` processes that run ``fn`` with ``args``/``kwargs_dict`` and initialize distributed configuration defined by ``backend...
Spawns ``nproc_per_node`` processes that run ``fn`` with ``args``/``kwargs_dict`` and initialize distributed configuration defined by ``backend``. Args: backend: backend to use: `nccl`, `gloo`, `xla-tpu`, `horovod` fn: function to called as the entrypoint of the spawned process. Thi...
spawn
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def all_reduce( tensor: Union[torch.Tensor, float], op: str = "SUM", group: Optional[Union[Any, List[int]]] = None ) -> Union[torch.Tensor, float]: """Helper method to perform all reduce operation. Args: tensor: tensor or number to collect across participating processes. op: reduction opera...
Helper method to perform all reduce operation. Args: tensor: tensor or number to collect across participating processes. op: reduction operation, "SUM" by default. Possible values: "SUM", "PRODUCT", "MIN", "MAX", "AND", "OR". Horovod backend supports only "SUM", "AVERAGE", "ADASUM", "MI...
all_reduce
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def all_gather_tensors_with_shapes( tensor: torch.Tensor, shapes: Sequence[Sequence[int]], group: Optional[Union[Any, List[int]]] = None ) -> List[torch.Tensor]: """Helper method to gather tensors of possibly different shapes but with the same number of dimensions across processes. This function gets t...
Helper method to gather tensors of possibly different shapes but with the same number of dimensions across processes. This function gets the shapes of participating tensors as input so you should know them beforehand. If your tensors are of different number of dimensions or you don't know their shapes befo...
all_gather_tensors_with_shapes
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def all_gather( tensor: Union[torch.Tensor, float, str, Any], group: Optional[Union[Any, List[int]]] = None ) -> Union[torch.Tensor, float, List[float], List[str], List[Any]]: """Helper method to perform all gather operation. Args: tensor: tensor or number or str to collect across participating pro...
Helper method to perform all gather operation. Args: tensor: tensor or number or str to collect across participating processes. If tensor, it should have the same shape across processes. group: list of integer or the process group for each backend. If None, the default process group wil...
all_gather
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def broadcast( tensor: Union[torch.Tensor, float, str, None], src: int = 0, safe_mode: bool = False ) -> Union[torch.Tensor, float, str]: """Helper method to perform broadcast operation. Args: tensor: tensor or number or str to broadcast to participating processes. Make sure to respect ...
Helper method to perform broadcast operation. Args: tensor: tensor or number or str to broadcast to participating processes. Make sure to respect data type of torch tensor input for all processes, otherwise execution will crash. Can use None for non-source data with ``safe_mode=True...
broadcast
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def new_group(ranks: List[int], **kwargs: Any) -> Any: """Helper method to make group for each backend from ranks. Args: ranks: subset of ranks to be grouped. kwargs: acceptable kwargs according to provided backend: - | "nccl" or "gloo" : ``backend (=None)``, ``pg_options (=None)``...
Helper method to make group for each backend from ranks. Args: ranks: subset of ranks to be grouped. kwargs: acceptable kwargs according to provided backend: - | "nccl" or "gloo" : ``backend (=None)``, ``pg_options (=None)``. Examples: Launch single node multi-GPU training...
new_group
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def set_local_rank(index: int) -> None: """Method to hint the local rank in case if torch native distributed context is created by user without using :meth:`~ignite.distributed.utils.initialize` or :meth:`~ignite.distributed.utils.spawn`. Args: index: local rank or current process index Exampl...
Method to hint the local rank in case if torch native distributed context is created by user without using :meth:`~ignite.distributed.utils.initialize` or :meth:`~ignite.distributed.utils.spawn`. Args: index: local rank or current process index Examples: User set up torch native distribute...
set_local_rank
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def initialize(backend: str, **kwargs: Any) -> None: """Initializes distributed configuration according to provided ``backend`` Args: backend: backend: `nccl`, `gloo`, `xla-tpu`, `horovod`. kwargs: acceptable kwargs according to provided backend: - | "nccl" or "gloo" : ``timeout(=t...
Initializes distributed configuration according to provided ``backend`` Args: backend: backend: `nccl`, `gloo`, `xla-tpu`, `horovod`. kwargs: acceptable kwargs according to provided backend: - | "nccl" or "gloo" : ``timeout(=timedelta(minutes=30))``, ``init_method(=None)``, ...
initialize
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def show_config() -> None: """Helper method to display distributed configuration via ``logging``.""" # setup parallel logger logger = setup_logger(__name__) logger.info(f"distributed configuration: {model_name()}") logger.info(f"backend: {backend()}") logger.info(f"device: {device().type}") ...
Helper method to display distributed configuration via ``logging``.
show_config
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def one_rank_only(rank: int = 0, with_barrier: bool = False) -> Callable: """Decorator to filter handlers wrt a rank number Args: rank: rank number of the handler (default: 0). with_barrier: synchronisation with a barrier (default: False). Examples: .. code-block:: python ...
Decorator to filter handlers wrt a rank number Args: rank: rank number of the handler (default: 0). with_barrier: synchronisation with a barrier (default: False). Examples: .. code-block:: python engine = ... @engine.on(...) @one_rank_only() # mean...
one_rank_only
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def one_rank_first(rank: int = 0, local: bool = False) -> Any: """Context manager that ensures a specific rank runs first before others in a distributed environment. Args: rank: rank of the process that should execute the code block inside the context manager first. Default, 0. ...
Context manager that ensures a specific rank runs first before others in a distributed environment. Args: rank: rank of the process that should execute the code block inside the context manager first. Default, 0. local: flag to specify local rank or global rank. If True ...
one_rank_first
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def _rank_not_in_group(group: Optional[Union[Any, List[int]]]) -> bool: """Check if the current process's rank is not in a given group.""" if group is None: return False if isinstance(group, list) and all(isinstance(item, int) for item in group): group = new_group(group) return _model._r...
Check if the current process's rank is not in a given group.
_rank_not_in_group
python
pytorch/ignite
ignite/distributed/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/utils.py
BSD-3-Clause
def __init__(self, backend: Optional[str] = None, **kwargs: Any) -> None: """This is a private method. Please, use `create_from_backend` or `create_from_context`""" super(_HorovodDistModel, self).__init__() if backend is not None: self._create_from_backend(backend, **...
This is a private method. Please, use `create_from_backend` or `create_from_context`
__init__
python
pytorch/ignite
ignite/distributed/comp_models/horovod.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/comp_models/horovod.py
BSD-3-Clause
def _expand_hostlist(nodelist: str) -> List[str]: """Expand a compressed hostlist string and returns all hosts listed. Source : https://github.com/LLNL/py-hostlist/blob/master/hostlist/hostlist.py Args: nodelist: Compressed hostlist string .. note:: The host na...
Expand a compressed hostlist string and returns all hosts listed. Source : https://github.com/LLNL/py-hostlist/blob/master/hostlist/hostlist.py Args: nodelist: Compressed hostlist string .. note:: The host names can be composed by any character except the special ones ...
_expand_hostlist
python
pytorch/ignite
ignite/distributed/comp_models/native.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/comp_models/native.py
BSD-3-Clause
def _setup_ddp_vars_from_slurm_env(environ: Dict[str, str]) -> Dict[str, Union[str, int]]: """Method to setup DDP env vars required by PyTorch from SLURM env""" # 1) Tools like enroot can have hooks to translate slurm env vars to RANK, LOCAL_RANK, WORLD_SIZE etc # See https://github.com/NVIDIA/e...
Method to setup DDP env vars required by PyTorch from SLURM env
_setup_ddp_vars_from_slurm_env
python
pytorch/ignite
ignite/distributed/comp_models/native.py
https://github.com/pytorch/ignite/blob/master/ignite/distributed/comp_models/native.py
BSD-3-Clause
def update_dataloader(dataloader: DataLoader, new_batch_sampler: BatchSampler) -> DataLoader: """Helper function to replace current batch sampler of the dataloader by a new batch sampler. Function returns new dataloader with new batch sampler. Args: dataloader: input dataloader new_batch_sa...
Helper function to replace current batch sampler of the dataloader by a new batch sampler. Function returns new dataloader with new batch sampler. Args: dataloader: input dataloader new_batch_sampler: new batch sampler to use Returns: DataLoader
update_dataloader
python
pytorch/ignite
ignite/engine/deterministic.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/deterministic.py
BSD-3-Clause
def keep_random_state(func: Callable) -> Callable: """Helper decorator to keep random state of torch, numpy and random intact while executing a function. For more details on usage, please see :ref:`Dataflow synchronization`. Args: func: function to decorate """ @wraps(func) def wrapper...
Helper decorator to keep random state of torch, numpy and random intact while executing a function. For more details on usage, please see :ref:`Dataflow synchronization`. Args: func: function to decorate
keep_random_state
python
pytorch/ignite
ignite/engine/deterministic.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/deterministic.py
BSD-3-Clause
def register_events( self, *event_names: Union[List[str], List[EventEnum]], event_to_attr: Optional[dict] = None ) -> None: """Add events that can be fired. Registering an event will let the user trigger these events at any point. This opens the door to make the :meth:`~ignite.engin...
Add events that can be fired. Registering an event will let the user trigger these events at any point. This opens the door to make the :meth:`~ignite.engine.engine.Engine.run` loop even more configurable. By default, the events from :class:`~ignite.engine.events.Events` are registered...
register_events
python
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/engine.py
BSD-3-Clause
def add_event_handler(self, event_name: Any, handler: Callable, *args: Any, **kwargs: Any) -> RemovableEventHandle: """Add an event handler to be executed when the specified event is fired. Args: event_name: An event or a list of events to attach the handler. Valid events are ...
Add an event handler to be executed when the specified event is fired. Args: event_name: An event or a list of events to attach the handler. Valid events are from :class:`~ignite.engine.events.Events` or any ``event_name`` added by :meth:`~ignite.engine.engine.Engine...
add_event_handler
python
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/engine.py
BSD-3-Clause
def has_event_handler(self, handler: Callable, event_name: Optional[Any] = None) -> bool: """Check if the specified event has the specified handler. Args: handler: the callable event handler. event_name: The event the handler attached to. Set this to ``None`` to ...
Check if the specified event has the specified handler. Args: handler: the callable event handler. event_name: The event the handler attached to. Set this to ``None`` to search all events.
has_event_handler
python
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/engine.py
BSD-3-Clause
def remove_event_handler(self, handler: Callable, event_name: Any) -> None: """Remove event handler `handler` from registered handlers of the engine Args: handler: the callable event handler that should be removed event_name: The event the handler attached to. """ ...
Remove event handler `handler` from registered handlers of the engine Args: handler: the callable event handler that should be removed event_name: The event the handler attached to.
remove_event_handler
python
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/engine.py
BSD-3-Clause
def on(self, event_name: Any, *args: Any, **kwargs: Any) -> Callable: """Decorator shortcut for :meth:`~ignite.engine.engine.Engine.add_event_handler`. Args: event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.events.Events` or any ``e...
Decorator shortcut for :meth:`~ignite.engine.engine.Engine.add_event_handler`. Args: event_name: An event to attach the handler to. Valid events are from :class:`~ignite.engine.events.Events` or any ``event_name`` added by :meth:`~ignite.engine.engine.Engine.register_events`. ...
on
python
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/engine.py
BSD-3-Clause
def _fire_event(self, event_name: Any, *event_args: Any, **event_kwargs: Any) -> None: """Execute all the handlers associated with given event. This method executes all handlers associated with the event `event_name`. Optional positional and keyword arguments can be used to pass argumen...
Execute all the handlers associated with given event. This method executes all handlers associated with the event `event_name`. Optional positional and keyword arguments can be used to pass arguments to **all** handlers added with this event. These arguments updates arguments passed usi...
_fire_event
python
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/engine.py
BSD-3-Clause
def interrupt(self) -> None: """Sends interrupt signal to the engine, so that it interrupts the run after the current iteration. The run can be resumed by calling :meth:`~ignite.engine.engine.Engine.run`. Data iteration will continue from the interrupted state. Examples: .. ...
Sends interrupt signal to the engine, so that it interrupts the run after the current iteration. The run can be resumed by calling :meth:`~ignite.engine.engine.Engine.run`. Data iteration will continue from the interrupted state. Examples: .. testcode:: from ignite....
interrupt
python
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/engine.py
BSD-3-Clause
def terminate(self, skip_completed: bool = False) -> None: """Sends terminate signal to the engine, so that it terminates completely the run. The run is terminated after the event on which ``terminate`` method was called. The following events are triggered: - ... - Terminating event ...
Sends terminate signal to the engine, so that it terminates completely the run. The run is terminated after the event on which ``terminate`` method was called. The following events are triggered: - ... - Terminating event - :attr:`~ignite.engine.events.Events.TERMINATE` - :attr:...
terminate
python
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/engine.py
BSD-3-Clause
def terminate_epoch(self, skip_epoch_completed: bool = False) -> None: """Sends terminate signal to the engine, so that it terminates the current epoch. The run continues from the next epoch. The following events are triggered: - ... - Event on which ``terminate_epoch`` method is called...
Sends terminate signal to the engine, so that it terminates the current epoch. The run continues from the next epoch. The following events are triggered: - ... - Event on which ``terminate_epoch`` method is called - :attr:`~ignite.engine.events.Events.TERMINATE_SINGLE_EPOCH` - :...
terminate_epoch
python
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/engine.py
BSD-3-Clause
def state_dict(self) -> OrderedDict: """Returns a dictionary containing engine's state: "epoch_length", "max_epochs" and "iteration" and other state values defined by `engine.state_dict_user_keys` .. code-block:: python engine = Engine(...) engine.state_dict_user_keys.a...
Returns a dictionary containing engine's state: "epoch_length", "max_epochs" and "iteration" and other state values defined by `engine.state_dict_user_keys` .. code-block:: python engine = Engine(...) engine.state_dict_user_keys.append("alpha") engine.state_dict_use...
state_dict
python
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/engine.py
BSD-3-Clause
def load_state_dict(self, state_dict: Mapping) -> None: """Setups engine from `state_dict`. State dictionary should contain keys: `iteration` or `epoch`, `max_epochs` and `epoch_length`. If `engine.state_dict_user_keys` contains keys, they should be also present in the state dictionary. ...
Setups engine from `state_dict`. State dictionary should contain keys: `iteration` or `epoch`, `max_epochs` and `epoch_length`. If `engine.state_dict_user_keys` contains keys, they should be also present in the state dictionary. Iteration and epoch values are 0-based: the first iteration or epo...
load_state_dict
python
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/engine.py
BSD-3-Clause
def set_data(self, data: Union[Iterable, DataLoader]) -> None: """Method to set data. After calling the method the next batch passed to `processing_function` is from newly provided data. Please, note that epoch length is not modified. Args: data: Collection of batches allowing repea...
Method to set data. After calling the method the next batch passed to `processing_function` is from newly provided data. Please, note that epoch length is not modified. Args: data: Collection of batches allowing repeated iteration (e.g., list or `DataLoader`). Examples: ...
set_data
python
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/engine.py
BSD-3-Clause
def run( self, data: Optional[Iterable] = None, max_epochs: Optional[int] = None, max_iters: Optional[int] = None, epoch_length: Optional[int] = None, ) -> State: """Runs the ``process_function`` over the passed data. Engine has a state and the following logi...
Runs the ``process_function`` over the passed data. Engine has a state and the following logic is applied in this function: - At the first call, new state is defined by `max_epochs`, `max_iters`, `epoch_length`, if provided. A timer for total and per-epoch time is initialized when Events.STA...
run
python
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/engine.py
BSD-3-Clause
def __call__( self, event_filter: Optional[Callable] = None, every: Optional[int] = None, once: Optional[Union[int, List]] = None, before: Optional[int] = None, after: Optional[int] = None, ) -> "CallableEventWithFilter": """ Makes the event class call...
Makes the event class callable and accepts either an arbitrary callable as filter (which must take in the engine and current event value and return a boolean) or an every or once value Args: event_filter: a filter function to check if the event should be executed when ...
__call__
python
pytorch/ignite
ignite/engine/events.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/events.py
BSD-3-Clause
def before_and_after_event_filter(before: Optional[int] = None, after: Optional[int] = None) -> Callable: """A wrapper for before and after event filter.""" before_: Union[int, float] = float("inf") if before is None else before after_: int = 0 if after is None else after def wrapper(en...
A wrapper for before and after event filter.
before_and_after_event_filter
python
pytorch/ignite
ignite/engine/events.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/events.py
BSD-3-Clause
def every_before_and_after_event_filter( every: int, before: Optional[int] = None, after: Optional[int] = None ) -> Callable: """A wrapper which triggers for every `every` iterations after `after` and before `before`.""" before_: Union[int, float] = float("inf") if before is None else before...
A wrapper which triggers for every `every` iterations after `after` and before `before`.
every_before_and_after_event_filter
python
pytorch/ignite
ignite/engine/events.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/events.py
BSD-3-Clause
def get_event_attrib_value(self, event_name: Union[str, Events, CallableEventWithFilter]) -> int: """Get the value of Event attribute with given `event_name`.""" if event_name not in State.event_to_attr: raise RuntimeError(f"Unknown event name '{event_name}'") return getattr(self, St...
Get the value of Event attribute with given `event_name`.
get_event_attrib_value
python
pytorch/ignite
ignite/engine/events.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/events.py
BSD-3-Clause
def _to_hours_mins_secs(time_taken: Union[float, int]) -> Tuple[int, int, float]: """Convert seconds to hours, mins, seconds and milliseconds.""" mins, secs = divmod(time_taken, 60) hours, mins = divmod(mins, 60) return round(hours), round(mins), secs
Convert seconds to hours, mins, seconds and milliseconds.
_to_hours_mins_secs
python
pytorch/ignite
ignite/engine/utils.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/utils.py
BSD-3-Clause
def _prepare_batch( batch: Sequence[torch.Tensor], device: Optional[Union[str, torch.device]] = None, non_blocking: bool = False ) -> Tuple[Union[torch.Tensor, Sequence, Mapping, str, bytes], ...]: """Prepare batch for training or evaluation: pass to a device with options.""" x, y = batch return ( ...
Prepare batch for training or evaluation: pass to a device with options.
_prepare_batch
python
pytorch/ignite
ignite/engine/__init__.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/__init__.py
BSD-3-Clause
def supervised_training_step( model: torch.nn.Module, optimizer: torch.optim.Optimizer, loss_fn: Union[Callable[[Any, Any], torch.Tensor], torch.nn.Module], device: Optional[Union[str, torch.device]] = None, non_blocking: bool = False, prepare_batch: Callable = _prepare_batch, model_transfor...
Factory function for supervised training. Args: model: the model to train. optimizer: the optimizer to use. loss_fn: the loss function that receives `y_pred` and `y`, and returns the loss as a tensor. device: device type specification (default: None). Applies to batches ...
supervised_training_step
python
pytorch/ignite
ignite/engine/__init__.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/__init__.py
BSD-3-Clause
def supervised_training_step_amp( model: torch.nn.Module, optimizer: torch.optim.Optimizer, loss_fn: Union[Callable[[Any, Any], torch.Tensor], torch.nn.Module], device: Optional[Union[str, torch.device]] = None, non_blocking: bool = False, prepare_batch: Callable = _prepare_batch, model_tran...
Factory function for supervised training using ``torch.cuda.amp``. Args: model: the model to train. optimizer: the optimizer to use. loss_fn: the loss function that receives `y_pred` and `y`, and returns the loss as a tensor. device: device type specification (default: None). ...
supervised_training_step_amp
python
pytorch/ignite
ignite/engine/__init__.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/__init__.py
BSD-3-Clause
def supervised_training_step_apex( model: torch.nn.Module, optimizer: torch.optim.Optimizer, loss_fn: Union[Callable[[Any, Any], torch.Tensor], torch.nn.Module], device: Optional[Union[str, torch.device]] = None, non_blocking: bool = False, prepare_batch: Callable = _prepare_batch, model_tra...
Factory function for supervised training using apex. Args: model: the model to train. optimizer: the optimizer to use. loss_fn: the loss function that receives `y_pred` and `y`, and returns the loss as a tensor. device: device type specification (default: None). Applies ...
supervised_training_step_apex
python
pytorch/ignite
ignite/engine/__init__.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/__init__.py
BSD-3-Clause
def supervised_training_step_tpu( model: torch.nn.Module, optimizer: torch.optim.Optimizer, loss_fn: Union[Callable[[Any, Any], torch.Tensor], torch.nn.Module], device: Optional[Union[str, torch.device]] = None, non_blocking: bool = False, prepare_batch: Callable = _prepare_batch, model_tran...
Factory function for supervised training using ``torch_xla``. Args: model: the model to train. optimizer: the optimizer to use. loss_fn: the loss function that receives `y_pred` and `y`, and returns the loss as a tensor. device: device type specification (default: None). ...
supervised_training_step_tpu
python
pytorch/ignite
ignite/engine/__init__.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/__init__.py
BSD-3-Clause
def _check_arg( on_tpu: bool, on_mps: bool, amp_mode: Optional[str], scaler: Optional[Union[bool, "torch.cuda.amp.GradScaler"]] ) -> Tuple[Optional[str], Optional["torch.cuda.amp.GradScaler"]]: """Checking tpu, mps, amp and GradScaler instance combinations.""" if on_mps and amp_mode: raise ValueErro...
Checking tpu, mps, amp and GradScaler instance combinations.
_check_arg
python
pytorch/ignite
ignite/engine/__init__.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/__init__.py
BSD-3-Clause
def create_supervised_trainer( model: torch.nn.Module, optimizer: torch.optim.Optimizer, loss_fn: Union[Callable[[Any, Any], torch.Tensor], torch.nn.Module], device: Optional[Union[str, torch.device]] = None, non_blocking: bool = False, prepare_batch: Callable = _prepare_batch, model_transfo...
Factory function for creating a trainer for supervised models. Args: model: the model to train. optimizer: the optimizer to use. loss_fn: the loss function that receives `y_pred` and `y`, and returns the loss as a tensor. device: device type specification (default: None). ...
create_supervised_trainer
python
pytorch/ignite
ignite/engine/__init__.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/__init__.py
BSD-3-Clause
def supervised_evaluation_step( model: torch.nn.Module, device: Optional[Union[str, torch.device]] = None, non_blocking: bool = False, prepare_batch: Callable = _prepare_batch, model_transform: Callable[[Any], Any] = lambda output: output, output_transform: Callable[[Any, Any, Any], Any] = lambd...
Factory function for supervised evaluation. Args: model: the model to train. device: device type specification (default: None). Applies to batches after starting the engine. Model *will not* be moved. non_blocking: if True and this copy is between CPU and GPU, the copy may ...
supervised_evaluation_step
python
pytorch/ignite
ignite/engine/__init__.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/__init__.py
BSD-3-Clause
def supervised_evaluation_step_amp( model: torch.nn.Module, device: Optional[Union[str, torch.device]] = None, non_blocking: bool = False, prepare_batch: Callable = _prepare_batch, model_transform: Callable[[Any], Any] = lambda output: output, output_transform: Callable[[Any, Any, Any], Any] = l...
Factory function for supervised evaluation using ``torch.cuda.amp``. Args: model: the model to train. device: device type specification (default: None). Applies to batches after starting the engine. Model *will not* be moved. non_blocking: if True and this copy is between C...
supervised_evaluation_step_amp
python
pytorch/ignite
ignite/engine/__init__.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/__init__.py
BSD-3-Clause
def create_supervised_evaluator( model: torch.nn.Module, metrics: Optional[Dict[str, Metric]] = None, device: Optional[Union[str, torch.device]] = None, non_blocking: bool = False, prepare_batch: Callable = _prepare_batch, model_transform: Callable[[Any], Any] = lambda output: output, output...
Factory function for creating an evaluator for supervised models. Args: model: the model to train. metrics: a map of metric names to Metrics. device: device type specification (default: None). Applies to batches after starting the engine. Model *will not* be moved. ...
create_supervised_evaluator
python
pytorch/ignite
ignite/engine/__init__.py
https://github.com/pytorch/ignite/blob/master/ignite/engine/__init__.py
BSD-3-Clause
def _setup_output_metrics_state_attrs( self, engine: Engine, log_text: Optional[bool] = False, key_tuple: Optional[bool] = True ) -> Dict[Any, Any]: """Helper method to setup metrics and state attributes to log""" metrics_state_attrs = OrderedDict() if self.metric_names is not None: ...
Helper method to setup metrics and state attributes to log
_setup_output_metrics_state_attrs
python
pytorch/ignite
ignite/handlers/base_logger.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/base_logger.py
BSD-3-Clause
def attach( self, engine: Engine, log_handler: Callable, event_name: Union[str, Events, CallableEventWithFilter, EventsList], *args: Any, **kwargs: Any, ) -> RemovableEventHandle: """Attach the logger to the engine and execute `log_handler` function at `event_...
Attach the logger to the engine and execute `log_handler` function at `event_name` events. Args: engine: engine object. log_handler: a logging handler to execute event_name: event to attach the logging handler to. Valid events are from :class:`~ignite.engine....
attach
python
pytorch/ignite
ignite/handlers/base_logger.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/base_logger.py
BSD-3-Clause
def attach_opt_params_handler( self, engine: Engine, event_name: Any, *args: Any, **kwargs: Any ) -> RemovableEventHandle: """Shortcut method to attach `OptimizerParamsHandler` to the logger. Args: engine: engine object. event_name: event to attach the logging handle...
Shortcut method to attach `OptimizerParamsHandler` to the logger. Args: engine: engine object. event_name: event to attach the logging handler to. Valid events are from :class:`~ignite.engine.events.Events` or any `event_name` added by :meth:`~ignite.engi...
attach_opt_params_handler
python
pytorch/ignite
ignite/handlers/base_logger.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/base_logger.py
BSD-3-Clause
def __call__(self, checkpoint: Mapping, filename: str, metadata: Optional[Mapping] = None) -> None: """Method to save `checkpoint` with `filename`. Additionally, metadata dictionary is provided. Metadata contains: - `basename`: file prefix (if provided) with checkpoint name, e.g. `epoch_checkp...
Method to save `checkpoint` with `filename`. Additionally, metadata dictionary is provided. Metadata contains: - `basename`: file prefix (if provided) with checkpoint name, e.g. `epoch_checkpoint`. - `score_name`: score name if provided, e.g `val_acc`. - `priority`: checkpoint priority...
__call__
python
pytorch/ignite
ignite/handlers/checkpoint.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/checkpoint.py
BSD-3-Clause
def remove(self, filename: str) -> None: """Method to remove saved checkpoint. Args: filename: filename associated with checkpoint. """
Method to remove saved checkpoint. Args: filename: filename associated with checkpoint.
remove
python
pytorch/ignite
ignite/handlers/checkpoint.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/checkpoint.py
BSD-3-Clause
def setup_filename_pattern( with_prefix: bool = True, with_score: bool = True, with_score_name: bool = True, with_global_step: bool = True ) -> str: """Helper method to get the default filename pattern for a checkpoint. Args: with_prefix: If True, the ``filename_prefix`` is adde...
Helper method to get the default filename pattern for a checkpoint. Args: with_prefix: If True, the ``filename_prefix`` is added to the filename pattern: ``{filename_prefix}_{name}...``. Default, True. with_score: If True, ``score`` is added to the filename pattern: ``.....
setup_filename_pattern
python
pytorch/ignite
ignite/handlers/checkpoint.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/checkpoint.py
BSD-3-Clause
def load_objects(to_load: Mapping, checkpoint: Union[str, Mapping, Path], **kwargs: Any) -> None: """Helper method to apply ``load_state_dict`` on the objects from ``to_load`` using states from ``checkpoint``. Args: to_load: a dictionary with objects, e.g. `{"model": model, "optimizer": opt...
Helper method to apply ``load_state_dict`` on the objects from ``to_load`` using states from ``checkpoint``. Args: to_load: a dictionary with objects, e.g. `{"model": model, "optimizer": optimizer, ...}` checkpoint: a path, a string filepath or a dictionary with state_dicts to load, e.g...
load_objects
python
pytorch/ignite
ignite/handlers/checkpoint.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/checkpoint.py
BSD-3-Clause
def reload_objects(self, to_load: Mapping, load_kwargs: Optional[Dict] = None, **filename_components: Any) -> None: """Helper method to apply ``load_state_dict`` on the objects from ``to_load``. Filename components such as name, score and global state can be configured. Args: to_loa...
Helper method to apply ``load_state_dict`` on the objects from ``to_load``. Filename components such as name, score and global state can be configured. Args: to_load: a dictionary with objects, e.g. `{"model": model, "optimizer": optimizer, ...}` load_kwargs: Keyword arguments a...
reload_objects
python
pytorch/ignite
ignite/handlers/checkpoint.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/checkpoint.py
BSD-3-Clause
def state_dict(self) -> OrderedDict: """Method returns state dict with saved items: list of ``(priority, filename)`` pairs. Can be used to save internal state of the class. """ # TODO: this method should use _state_dict_all_req_keys return OrderedDict([("_saved", [(p, f) for p, f...
Method returns state dict with saved items: list of ``(priority, filename)`` pairs. Can be used to save internal state of the class.
state_dict
python
pytorch/ignite
ignite/handlers/checkpoint.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/checkpoint.py
BSD-3-Clause
def load_state_dict(self, state_dict: Mapping) -> None: """Method replaces internal state of the class with provided state dict data. Args: state_dict: a dict with "saved" key and list of ``(priority, filename)`` pairs as values. """ super().load_state_dict(state_dict) ...
Method replaces internal state of the class with provided state dict data. Args: state_dict: a dict with "saved" key and list of ``(priority, filename)`` pairs as values.
load_state_dict
python
pytorch/ignite
ignite/handlers/checkpoint.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/checkpoint.py
BSD-3-Clause
def get_default_score_fn(metric_name: str, score_sign: float = 1.0) -> Callable: """Helper method to get default score function based on the metric name. Args: metric_name: metric name to get the value from ``engine.state.metrics``. Engine is the one to which :class:`~ignite...
Helper method to get default score function based on the metric name. Args: metric_name: metric name to get the value from ``engine.state.metrics``. Engine is the one to which :class:`~ignite.handlers.checkpoint.Checkpoint` handler is added. score_sign: sign of the score...
get_default_score_fn
python
pytorch/ignite
ignite/handlers/checkpoint.py
https://github.com/pytorch/ignite/blob/master/ignite/handlers/checkpoint.py
BSD-3-Clause