U vPh6i@sddlmZddlZddlmZmZmZmZmZddl Z ddl m Z ddl m Z mZddlmZddlmZmZmZddlmZdd lmZmZdd lmZmZdd lmZdd lm Z m!Z!m"Z"m#Z#dd l$m%Z&ddl$m'Z(ddl)m*Z*m+Z+erddl,m-Z-m.Z.ddl/m0Z0nr?zunsupported mode: z, should be 'eval' or 'train'.) super__init__rrEVALrr:TRAINr ValueError)selfr.r/r0r1r2r3r4r5r6r7r8r9r:r;r<r=r>r? __class__L/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/engines/evaluator.pyrGYs4   zEvaluator.__init__rAint) global_epochr@cs0t|d|j_|d|j_d|j_tdS)z Execute validation/evaluation based on Ignite Engine. Args: global_epoch: the overall epoch if during a training. evaluator engine can get it from trainer. rArN)maxstaterBepoch iterationrFrun)rKrQrLrNrOrVs  z Evaluator.runcGsBtj|jjtj|jjtj|jji}|D]}t|j|d||<q&|S)a Get the statistics information of the validation process. Default to return the `rank`, `best_validation_epoch` and `best_validation_metric`. Args: vars: except for the default stats, other variables name in the `self.state` to return, will use the variable name as the key and the state content as the value. if the variable doesn't exist, default value is `None`. N) ESKeysRANKrSrankBEST_VALIDATION_EPOCHZbest_metric_epochBEST_VALIDATION_METRIC best_metricgetattr)rKvarsstatskrNrNrO get_statss zEvaluator.get_stats)rA) __name__ __module__ __qualname____doc__rr rrHrGrVra __classcell__rNrNrLrOr +s(181cseZdZdZddedddddeddejdddddddfddddd d d d d ddd dd dddd ddd dddfdd ZddddddZ Z S)r!a Standard supervised evaluation method with image and label(optional), inherits from evaluator and Workflow. Args: device: an object representing the device on which to run. val_data_loader: Ignite engine use data_loader to run, must be Iterable, typically be torch.DataLoader. network: network to evaluate in the evaluator, should be regular PyTorch `torch.nn.Module`. epoch_length: number of iterations for one epoch, default to `len(val_data_loader)`. non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously with respect to the host. For other cases, this argument has no effect. prepare_batch: function to parse expected data (usually `image`, `label` and other network args) from `engine.state.batch` for every iteration, for more details please refer to: https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html. iteration_update: the callable function for every iteration, expect to accept `engine` and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`. if not provided, use `self._iteration()` instead. for more details please refer to: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html. inferer: inference method that execute model forward on input data, like: SlidingWindow, etc. postprocessing: execute additional transformation for the model output data. Typically, several Tensor based transforms composed by `Compose`. key_val_metric: compute metric when every iteration completed, and save average value to engine.state.metrics when epoch completed. key_val_metric is the main metric to compare and save the checkpoint into files. additional_metrics: more Ignite metrics that also attach to Ignite Engine. metric_cmp_fn: function to compare current key metric with previous best key metric value, it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`. val_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like: CheckpointHandler, StatsHandler, etc. amp: whether to enable auto-mixed-precision evaluation, default is False. mode: model forward mode during evaluation, should be 'eval' or 'train', which maps to `model.eval()` or `model.train()`, default to 'eval'. event_names: additional custom ignite events that will register to the engine. new events can be a list of str or `ignite.engine.events.EventEnum`. event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`. for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html #ignite.engine.engine.Engine.register_events. decollate: whether to decollate the batch-first data to a list of data after model computation, recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`. default to `True`. to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for `device`, `non_blocking`. amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details: https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast. compile: whether to use `torch.compile`, default is False. If True, MetaTensor inputs will be converted to `torch.Tensor` before forward pass, then converted back afterward with copied meta information. compile_kwargs: dict of the args for `torch.compile()` API, for more details: https://pytorch.org/docs/stable/generated/torch.compile.html#torch-compile. NFT torch.devicer#ztorch.nn.Moduler$r%rr&Inferer | Noner'r(r)r*r+r,r-)r.r/networkr0r1r2r3infererr4r5r6r7r8r9r:r;r<r=r>r?compilecompile_kwargsr@cstj||||||| | | | | |||||||d|rhtddr^|dkrJin|}tj|f|}n td||_||_|dkrtn||_ dS)Nr.r/r0r1r2r3r4r5r6r7r8r9r:r;r<r=r>r?rAzeNetwork compilation (compile=True) not supported for Pytorch versions before 2.1, no compilation done) rFrGrtorchrkwarningswarnrirrj)rKr.r/rir0r1r2r3rjr4r5r6r7r8r9r:r;r<r=r>r?rkrlrLrNrOrGs< zSupervisedEvaluator.__init__dict[str, torch.Tensor]dictengine batchdatar@c Cs|dkrtd|j||jj|jf|j}t|dkrH|\}}d}i}n |\}}}}|jrd\}} } } t|t rt d| |j |j}}} t|t r| |j |j}} } tj|tj|i|j_||jn|jrtjjjf|j&|j||jf|||jjtj<W5QRXn |j||jf|||jjtj<W5QRX|jr|dk rt ||| d|jjtj<t |jjtj|| d|jjtj<| dk rt || | d|jjtj<|tj|tj|jjS)a callback function for the Supervised Evaluation processing logic of 1 iteration in Ignite Engine. Return below items in a dictionary: - IMAGE: image Tensor data for model input, already moved to device. - LABEL: label Tensor data corresponding to the image, already moved to device. - PRED: prediction result of model. Args: engine: `SupervisedEvaluator` to execute operation for an iteration. batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data. Raises: ValueError: When ``batchdata`` is None. N.Must provide batch data for current iteration.rnrN)NNNNzgWill convert to PyTorch Tensor if using compile, and casting back to MetaTensor after the forward pass.)metaapplied_operations) rJr2rSr.r1r>lenrk isinstancer rprq as_tensorrxryKeysIMAGELABELoutputr:rir9rocudaautocastr?rjPRED fire_eventr FORWARD_COMPLETEDMODEL_COMPLETED) rKrurvbatchinputstargetsargskwargsZ inputs_metaZ targets_metaZinputs_applied_operationsZtargets_applied_operationsrNrNrO _iterationsd       ,*     zSupervisedEvaluator._iteration rbrcrdrerr rrHrGrrfrNrNrLrOr!s,8@9cseZdZdZdddedddddeddejdddddfddddd d d d d dddd dd dddd ddddfdd ZddddddZ Z S)r"a Ensemble evaluation for multiple models, inherits from evaluator and Workflow. It accepts a list of models for inference and outputs a list of predictions for further operations. Args: device: an object representing the device on which to run. val_data_loader: Ignite engine use data_loader to run, must be Iterable, typically be torch.DataLoader. epoch_length: number of iterations for one epoch, default to `len(val_data_loader)`. networks: networks to evaluate in order in the evaluator, should be regular PyTorch `torch.nn.Module`. pred_keys: the keys to store every prediction data. the length must exactly match the number of networks. if None, use "pred_{index}" as key corresponding to N networks, index from `0` to `N-1`. non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously with respect to the host. For other cases, this argument has no effect. prepare_batch: function to parse expected data (usually `image`, `label` and other network args) from `engine.state.batch` for every iteration, for more details please refer to: https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html. iteration_update: the callable function for every iteration, expect to accept `engine` and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`. if not provided, use `self._iteration()` instead. for more details please refer to: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html. inferer: inference method that execute model forward on input data, like: SlidingWindow, etc. postprocessing: execute additional transformation for the model output data. Typically, several Tensor based transforms composed by `Compose`. key_val_metric: compute metric when every iteration completed, and save average value to engine.state.metrics when epoch completed. key_val_metric is the main metric to compare and save the checkpoint into files. additional_metrics: more Ignite metrics that also attach to Ignite Engine. metric_cmp_fn: function to compare current key metric with previous best key metric value, it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`. val_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like: CheckpointHandler, StatsHandler, etc. amp: whether to enable auto-mixed-precision evaluation, default is False. mode: model forward mode during evaluation, should be 'eval' or 'train', which maps to `model.eval()` or `model.train()`, default to 'eval'. event_names: additional custom ignite events that will register to the engine. new events can be a list of str or `ignite.engine.events.EventEnum`. event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`. for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html #ignite.engine.engine.Engine.register_events. decollate: whether to decollate the batch-first data to a list of data after model computation, recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`. default to `True`. to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for `device`, `non_blocking`. amp_kwargs: dict of the args for `torch.cuda.amp.autocast()` API, for more details: https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.autocast. NFTrgr#zSequence[torch.nn.Module]zKeysCollection | Noner$r%rr&rhr'r(r)r*r+r,r-)r.r/networks pred_keysr0r1r2r3rjr4r5r6r7r8r9r:r;r<r=r>r?r@cstj||||||| | | | ||||||||dt||_|dkrZddtt|jDnt||_t|jt|jkrtd| dkrtn| |_ dS)NrmcSsg|]}tjd|qS)_)r}r).0irNrNrO sz.EnsembleEvaluator.__init__..z?length of `pred_keys` must be same as the length of `networks`.) rFrGrrrangerzrrJrrj)rKr.r/rrr0r1r2r3rjr4r5r6r7r8r9r:r;r<r=r>r?rLrNrOrGs4 &zEnsembleEvaluator.__init__rrrsrtc CsF|dkrtd|j||jj|jf|j}t|dkrH|\}}d}i}n |\}}}}tj|tj |i|j_ t |j D]\}} | | |jrtjjjf|j<t|jj tr|jj |j||j|| f||iW5QRXn8t|jj tr|jj |j||j|| f||iW5QRXqr|tj|tj|jj S)a# callback function for the Supervised Evaluation processing logic of 1 iteration in Ignite Engine. Return below items in a dictionary: - IMAGE: image Tensor data for model input, already moved to device. - LABEL: label Tensor data corresponding to the image, already moved to device. - pred_keys[0]: prediction result of network 0. - pred_keys[1]: prediction result of network 1. - ... ... - pred_keys[N]: prediction result of network N. Args: engine: `EnsembleEvaluator` to execute operation for an iteration. batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data. Raises: ValueError: When ``batchdata`` is None. NrwrnrN)rJr2rSr.r1r>rzr}r~rr enumeraterr:r9rorrr?r{rsupdaterrjrr rr) rKrurvrrrrridxrirNrNrOrs0     zEnsembleEvaluator._iterationrrNrNrLrOr"bs*8>5)7 __future__rrptypingrrrrrrotorch.utils.datar monai.configr r monai.datar Zmonai.engines.utilsr r rZmonai.engines.workflowrZmonai.inferersrrmonai.networks.utilsrrmonai.transformsr monai.utilsrrrrmonai.utils.enumsrr}rrWmonai.utils.modulerr ignite.enginerrZignite.metricsrOPT_IMPORT_VERSIONr__all__r r!r"rNrNrNrO s6        6