U |PhW@s$ddlmZddlZddlZddlZddlmZmZmZddl m Z ddl m Z m Z ddlZddlmZddlmZddlmZmZmZmZed ejed \ZZed d d \ZZeddd \e_Zeddd \ZZedded\ZZe rddlm Z ned ejeddd\Z ZdZ!GdddZ"dS)) annotationsN)CallableMappingSequence)Path) TYPE_CHECKINGAny)Dataset) IgniteInfo) CommonKeys ensure_tuple min_versionoptional_importz ignite.engineEventsmlflowz1Please install mlflow before using MLFlowHandler.) descriptorzmlflow.entitiesz:Please install mlflow.entities before using MLFlowHandler.pandasz0Please install pandas for recording the dataset.tqdmz4.47.0)Enginer decorator)as_typeLossc@sjeZdZdZddgZdddddddejddddded dddd d fd d d ddddddddddd ddddddddZdddddZ d dd!d"d#Z d dd!d$d%Z d&d'Z e d(d)ZdHd+ddd,d-d.Zd+dd/d0d1ZdId+d2dd3d4d5Zd6d7Zdd8d9d:Zdd8d;d<Zd dd!d=d>Zd dd!d?d@Zd dd!dAdBZd dd!dCdDZdddEdFdGZdS)J MLFlowHandlera MLFlowHandler defines a set of Ignite Event-handlers for the MLFlow tracking logics. It can be used for any Ignite Engine(trainer, validator and evaluator). And it can track both epoch level and iteration level logging, then MLFlow can store the data and visualize. The expected data source is Ignite ``engine.state.output`` and ``engine.state.metrics``. Default behaviors: - When EPOCH_COMPLETED, track each dictionary item in ``engine.state.metrics`` in MLFlow. - When ITERATION_COMPLETED, track expected item in ``self.output_transform(engine.state.output)`` in MLFlow, default to `Loss`. Usage example is available in the tutorial: https://github.com/Project-MONAI/tutorials/blob/master/3d_segmentation/unet_segmentation_3d_ignite.ipynb. Args: tracking_uri: connects to a tracking URI. can also set the `MLFLOW_TRACKING_URI` environment variable to have MLflow find a URI from there. in both cases, the URI can either be an HTTP/HTTPS URI for a remote server, a database connection string, or a local path to log data to a directory. The URI defaults to path `mlruns`. for more details: https://mlflow.org/docs/latest/python_api/mlflow.html#mlflow.set_tracking_uri. iteration_log: whether to log data to MLFlow when iteration completed, default to `True`. ``iteration_log`` can be also a function and it will be interpreted as an event filter (see https://pytorch.org/ignite/generated/ignite.engine.events.Events.html for details). Event filter function accepts as input engine and event value (iteration) and should return True/False. epoch_log: whether to log data to MLFlow when epoch completed, default to `True`. ``epoch_log`` can be also a function and it will be interpreted as an event filter. See ``iteration_log`` argument for more details. epoch_logger: customized callable logger for epoch level logging with MLFlow. Must accept parameter "engine", use default logger if None. iteration_logger: customized callable logger for iteration level logging with MLFlow. Must accept parameter "engine", use default logger if None. dataset_logger: customized callable logger to log the dataset information with MLFlow. Must accept parameter "dataset_dict", use default logger if None. dataset_dict: a dictionary in which the key is the name of the dataset and the value is a PyTorch dataset, that needs to be recorded. This arg is only useful when MLFlow version >= 2.4.0. For more details about how to log data with MLFlow, please go to the website: https://mlflow.org/docs/latest/python_api/mlflow.data.html. dataset_keys: a key or a collection of keys to indicate contents in the dataset that need to be stored by MLFlow. output_transform: a callable that is used to transform the ``ignite.engine.state.output`` into a scalar to track, or a dictionary of {key: scalar}. By default this value logging happens when every iteration completed. The default behavior is to track loss from output[0] as output is a decollated list and we replicated loss value for every item of the decollated list. `engine.state` and `output_transform` inherit from the ignite concept: https://pytorch-ignite.ai/concepts/03-state/, explanation and usage example are in the tutorial: https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb. global_epoch_transform: a callable that is used to customize global epoch number. For example, in evaluation, the evaluator engine might want to track synced epoch number with the trainer engine. state_attributes: expected attributes from `engine.state`, if provided, will extract them when epoch completed. tag_name: when iteration output is a scalar, `tag_name` is used to track, defaults to `'Loss'`. experiment_name: the experiment name of MLflow, default to `'monai_experiment'`. An experiment can be used to record several runs. run_name: the run name in an experiment. A run can be used to record information about a workflow, like the loss, metrics and so on. experiment_param: a dict recording parameters which will not change through the whole workflow, like torch version, cuda version and so on. artifacts: paths to images that need to be recorded after running the workflow. optimizer_param_names: parameter names in the optimizer that need to be recorded during running the workflow, default to `'lr'`. close_on_complete: whether to close the mlflow run in `complete` phase in workflow, default to False. For more details of MLFlow usage, please refer to: https://mlflow.org/docs/latest/index.html. max_epochs epoch_lengthNTcCs|dS)NrxrrR/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/handlers/mlflow_handler.pyzMLFlowHandler.cCs|SNrrrrrrr monai_experimentlrFz str | Nonez$bool | Callable[[Engine, int], bool]zCallable[[Engine], Any] | Nonez-Callable[[Mapping[str, Dataset]], Any] | NonezMapping[str, Dataset] | NonestrrzSequence[str] | Nonez dict | Nonezstr | Sequence[Path] | Nonezstr | Sequence[str]boolNone) tracking_uri iteration_log epoch_log epoch_loggeriteration_loggerdataset_logger dataset_dict dataset_keysoutput_transformglobal_epoch_transformstate_attributestag_nameexperiment_namerun_nameexperiment_param artifactsoptimizer_param_namesclose_on_completereturncCs||_||_||_||_||_| |_| |_| |_| |_| |_ ||_ ||_ t ||_ t ||_tj|rh|ndd|_tjjtjjj|_||_d|_d|_||_t ||_dS)N)r')r(r)r*r+r,r/r0r1r2r3r4r5r r6r7rZ MlflowClientcliententitiesZ RunStatus to_stringFINISHEDrun_finish_statusr8 experimentcur_runr-r.)selfr'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r6r7r8rrr__init__ws*  zMLFlowHandler.__init__dict) param_dictr9cCsP|jdkrdSt|}|j|jjjj}|j}|D]}||kr8||=q8dS)z Delete parameters in given dict, if they are already logged by current mlflow run. Args: param_dict: parameter dict to be logged to mlflow. N) r@listkeysr:get_runinforun_iddataparams)rArDkey_listZlog_dataZlog_param_dictkeyrrr_delete_exist_param_in_dicts  z)MLFlowHandler._delete_exist_param_in_dictr)enginer9cCs||jtjs |tj|j|jr`||jtjs`tj}t|jrR||jd}|||j|j r||j tj stj }t|j r||j d}|||j ||j tj s|tj |j |jr||jtj s|tj |jdS)z Register a set of Ignite Event-Handlers to a specified Ignite engine. Args: engine: Ignite Engine, it can be a trainer, validator or evaluator. ) event_filterN)has_event_handlerstartrSTARTEDadd_event_handlerr(iteration_completedITERATION_COMPLETEDcallabler)epoch_completedEPOCH_COMPLETEDcomplete COMPLETEDr8close)rArOeventrrrattachs     zMLFlowHandler.attachcs js tdjdjsjdkr@dtdnjj jj }fdd|D}fdd|D}|rj |d j j _njjjj d _jrjfd d jD}||jrjn jdS) z? Check MLFlow status and start if not active. zFailed to set experiment '' as the active experimentNZrun_z %Y%m%d_%H%M%Scs"g|]}|jjksjs|qSr)rHr4.0r)r4rArr s z'MLFlowHandler.start..csg|]}|jjjkr|qSr)rHstatusr>r`rArrrcs) experiment_idr4csi|]}|tj|dqSr!getattrstateraattrrOrr sz'MLFlowHandler.start..)_set_experimentr? ValueErrorr3r@r4timestrftimer:Z search_runsrgrGrHrIZ create_runr5 _log_paramsdefault_tracking_paramsrNr,r-_default_dataset_log)rArOrunsattrsr)rOr4rArrRs&    zMLFlowHandler.startcCsb|j}|s6|j|j}|s6|j|j}|j|}|jtjj j krXt d|jd||_dS)Nz!Cannot set a deleted experiment 'r_) r?r:Zget_experiment_by_namer3Zcreate_experimentZget_experimentZlifecycle_stagerr;ZLifecycleStageZACTIVErp)rAr?rgrrrros zMLFlowHandler._set_experimentcCs&|j}|d|j|d|jdiS)NZ_digest_samplesnum_rows)namedigestprofile)Zpandas_dataset dataset_namerrr_get_pandas_dataset_infos z&MLFlowHandler._get_pandas_dataset_infotrainzdict[str, Any]) sample_dictcontextr9c s|jstd|j|jjj|_fdd|jjjD}tt |}d|}t |}t j j||dttfdd|jjj}t |st jg}|jj|jjj|dt} || dS) Nz,Current Run is not Active to log the datasetcsg|]}|jjr|qSr)datasetrz startswith)rar)rrrrcsz.MLFlowHandler._log_dataset..Z _dataset_)rzcs|jjjkSr!)rr{r)rrrr r z,MLFlowHandler._log_dataset..)rIdatasets)r@rpr:rGrHrIinputsZdataset_inputsr$lenr DataFramerrJ from_pandasrEfilterr;Z DatasetInputZ_to_mlflow_entityZ log_inputsrr~rs) rArrZ logged_setZ dataset_countr}Z sample_dfZexist_dataset_listr dataset_infor)rrr _log_datasets    zMLFlowHandler._log_dataset)rKr9cCs>|jstddd|D}|jj|jjjg|gddS)Nz'Current Run is not Active to log paramscSs"g|]\}}tj|t|qSr)rr;Paramr$rarMvaluerrrrcsz-MLFlowHandler._log_params..rImetricsrKtags)r@rpitemsr: log_batchrHrI)rArKZ params_arrrrrrsszMLFlowHandler._log_paramsz int | None)rstepr9csX|jstd|jjj}ttdfdd|D}|jj||ggddS)Nz(Current Run is not Active to log metricsics&g|]\}}tj||pdqS)r)rr;Metricrr timestamprrrc"sz.MLFlowHandler._log_metrics..r) r@rprHrIintrqrr:r)rArrrIZ metrics_arrrrr _log_metricss  zMLFlowHandler._log_metricscCsjg}|jD]Z}|sq tj|r,||q t|D],\}}}|D]}tj||}||qDq6q |S)z Log artifacts to mlflow. Given a path, all files in the path will be logged recursively. Given a file, it will be logged to mlflow. )r6ospathisfileappendwalkjoin)rA artifact_list path_nameroot_ filenamesfilename file_pathrrr_parse_artifacts%s   zMLFlowHandler._parse_artifacts)r9cCs6|jr2|jr2|}|D]}|j|jjj|qdS)zM Handler for train or validation/evaluation completed Event. N)r6r@rr:Z log_artifactrHrI)rArZartifactrrrrZ8s zMLFlowHandler.completecCs&|jr"|j|jjj|jd|_dS)z9 Stop current running logger of MLFlow. N)r@r:Zset_terminatedrHrIr>rerrrr\AszMLFlowHandler.closecCs$|jdk r||n ||dS)a Handler for train or validation/evaluation epoch completed Event. Track epoch level log, default values are from Ignite `engine.state.metrics` dict. Args: engine: Ignite Engine, it can be a trainer, validator or evaluator. N)r*_default_epoch_logrArOrrrrXJs  zMLFlowHandler.epoch_completedcCs$|jdk r||n ||dS)z Handler for train or validation/evaluation iteration completed Event. Track iteration level log. Args: engine: Ignite Engine, it can be a trainer, validator or evaluator. N)r+_default_iteration_logrrrrrUXs  z!MLFlowHandler.iteration_completedcs\jj}|sdS|jj}|j||d|jdk rXfdd|jD}|j||ddS)a( Execute epoch level log operation. Default to track the values from Ignite `engine.state.metrics` dict and track the values of specified attributes of `engine.state`. Args: engine: Ignite Engine, it can be a trainer, validator or evaluator. Nrcsi|]}|tj|dqSr!rhrkrmrrrnxsz4MLFlowHandler._default_epoch_log..)rjrr0epochrr1)rArOZlog_dict current_epochrwrrmrrfs  z MLFlowHandler._default_epoch_logcs||jj}|dkrdSt|tsB|jt|tjr<|n|i}|j ||jj dt |dr|j }|j D].fddt|jD}|j ||jj dqjdS)a Execute iteration log operation based on Ignite `engine.state.output` data. Log the values from `self.output_transform(engine.state.output)`. Since `engine.state.output` is a decollated list and we replicated the loss value for every item of the decollated list, the default behavior is to track the loss from `output[0]`. Args: engine: Ignite Engine, it can be a trainer, validator or evaluator. Nr optimizercs(i|] \}}d|t|qS)Z_group_)float)rai param_group param_namerrrns z8MLFlowHandler._default_iteration_log..)r/rjoutput isinstancerCr2torchTensoritemr iterationhasattrrr7 enumerate param_groups)rArOlossZ cur_optimizerrKrrrr{s     z$MLFlowHandler._default_iteration_log)r-r9c Cs|dkr dSt|dkr"td|D]\}}|dkrJtd|di}t|dg}t|d|dD]x}|jD]l}||krg||<||kr||}ntd |d t |t std t |d |d qv|| |qvql| ||q*dS)a Execute dataset log operation based on the input dataset_dict. The dataset_dict should have a format like: { "dataset_name0": dataset0, "dataset_name1": dataset1, ...... } The keys stand for names of datasets, which will be logged as prefixes of dataset names in MLFlow. The values are PyTorch datasets from which sample names are abstracted to build a Pandas DataFrame. If the input dataset_dict is None, this function will directly return and do nothing. To use this function, every sample in the input datasets must contain keys specified by the `dataset_keys` parameter. This function will log a PandasDataset to MLFlow inputs, generated from the Pandas DataFrame. For more details about PandasDataset, please refer to this link: https://mlflow.org/docs/latest/python_api/mlflow.data.html#mlflow.data.pandas_dataset.PandasDataset Please note that it may take a while to record the dataset if it has too many samples. Args: dataset_dict: a dictionary in which the key is the name of the dataset and the value is a PyTorch dataset, that needs to be recorded. NrzThere is no dataset to log!zThe z0 dataset of is None. Cannot record it by MLFlow.rJzRecording the z datasetzUnexpect key 'z' in the sample.zExpected type string, got type z of the z( name.May log an empty dataset in MLFlow)rwarningswarnrAttributeErrorrirr.KeyErrorrr$typerr) rAr-Z dataset_typerrZdataset_samplessamplerMZ value_to_logrrrrus,      z"MLFlowHandler._default_dataset_log)r)N)__name__ __module__ __qualname____doc__rtr IMAGE DEFAULT_TAGrBrNr^rRro staticmethodr~rrsrrrZr\rXrUrrrurrrrr-sLG4+      r)# __future__rrrqrcollections.abcrrrpathlibrtypingrrrtorch.utils.datar monai.configr monai.utilsr r r rOPT_IMPORT_VERSIONrrrr;rr ignite.enginerrrrrrr s: