o
    8wi%I                     @   sH  d dl mZ d dlmZ d dlmZmZmZ d dlZd dl	m
Z
 d dlZd dlmZ d dlmZ d dlmZmZ d d	lmZ d d
lmZ d dlmZmZmZ d dlmZ d dlmZ d dl m!Z! d dl"m#Z#m$Z$m%Z%m&Z&m'Z' d dl(m)Z)m*Z* d dl+m,Z, d dl-m.Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4 d dl5m6Z6 G dd deZ7dS )    OrderedDict)Iterator)AnyOptionalUnionN)WarningCache)move_data_to_device)BasePredictionWriter)_DataFetcher_DataLoaderIterDataFetcher)_Loop)	_Progress)_no_grad_context_select_data_fetcher"_verify_dataloader_idx_requirement)_IndexBatchSamplerWrapper)_MultiProcessingLauncher)call)_check_dataloader_iterable_DataLoaderSource_parse_num_batches_process_dataloader_request_dataloader)RunningStage	TrainerFn)CombinedLoader)has_len_all_ranks)MisconfigurationException)_ModuleMode)is_param_in_hook_signature)_PREDICT_OUTPUTc                
       s  e Zd ZdZdCdddeddf fdd	Zedefd
dZejdDde	e ddfddZede
e fddZedefddZedefddZede	e fddZdEddZdEddZdEddZde	e fddZdEddZd ed!ed"ed#e	e ddf
d$d%Zd ed!ed"e	e defd&d'Zd(ed)edefd*d+Zd,ede
e
e  fd-d.Z d!ed"edefd/d0Z!dEd1d2Z"dEd3d4Z#dEd5d6Z$dEd7d8Z%dEd9d:Z&dEd;d<Z'de	e fd=d>Z(dEd?d@Z)dEdAdBZ*  Z+S )F_PredictionLoopz'Top-level loop where prediction starts.Ttrainerz
pl.Trainerinference_modereturnNc                    sj   t  | || _g | _g | _t | _g | _t | _	t
d d| _d | _d | _d | _g | _d| _t | _d S )Npredict_dataloaderF)super__init__r$   epoch_batch_indicescurrent_batch_indicesr   batch_progressmax_batchesr   _warning_cacher   _data_source_combined_loader_data_fetcher_results_predictions_return_predictionsr   _module_mode)selfr#   r$   	__class__ d/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/pytorch_lightning/loops/prediction_loop.pyr(   2   s   z_PredictionLoop.__init__c                 C   s   | j S )z)Whether to return the predictions or not.)r3   r5   r8   r8   r9   return_predictionsD   s   z"_PredictionLoop.return_predictionsr;   c                 C   sT   t | jjjt }|r|std| dt| jj d|d u r%|| _d S || _d S )Nzb`return_predictions` should be set to `False` when using the strategies that spawn or fork. Found z with strategy .)
isinstancer#   strategylauncherr   r   typer3   )r5   r;   return_supportedr8   r8   r9   r;   I   s   
c                 C   s*   | j g kr| j S | jdkr| j d S | j S )zThe cached predictions.   r   )r2   num_dataloadersr:   r8   r8   r9   predictionsU   s   
z_PredictionLoop.predictionsc                 C   s   | j }|dus	J t|jS )z-Returns the number of prediction dataloaders.N)r/   len	flattened)r5   combined_loaderr8   r8   r9   rC   \   s   
z_PredictionLoop.num_dataloadersc                 C   s   t | jdkS )Nr   )sumr,   r:   r8   r8   r9   skipc   s   z_PredictionLoop.skipc                 C   s   |    | jr	d S |   |   | j}|d usJ 	 zAz+t|tr0t|}|j}|j	}|j
}n	d }t|\}}}|j| j_| |||| W n tyW   Y W d| _|  S w W d| _nd| _w q)NTF)
setup_datarI   reseton_run_startr0   r=   r   next_batch
_batch_idx_dataloader_idxdoner+   is_last_batch_predict_stepStopIteration_restarting
on_run_end)r5   data_fetcherdataloader_iterbatch	batch_idxdataloader_idxr8   r8   r9   rung   s4   

z_PredictionLoop.runc                 C   s   | j }|jdkr
d S | j}t|}|jd t|ts"t|d}n|}|jj	}|j
d ur3||j
j	O }tj}tj}g }g | _|jD ]0}t||| t||||}|| t||j|r`t|ntd}	t||	|j}
| j|
 qA||_|| _d S )Nr   zpredict_dataloader()
sequentialinf)r#   limit_predict_batchesr.   r   r>   barrierr=   r   lightning_module2allow_zero_length_dataloader_with_multiple_devices
datamoduler   
PREDICTINGr   r,   rF   r   r   appendr   rE   floatr   r/   )r5   r#   sourcedataloadersrG   allow_zero_length
trainer_fnstagedllengthnum_batchesr8   r8   r9   rJ      s2   





z_PredictionLoop.setup_datac                 C   s   | j   | jjjdusJ t| j| jjj}| j}|dus J |jdkr)td| j	|_
|| t| | j| j jj7  _| j|_| j|_|| _| j}dd t|D | _dd t|D | _dS )z4Resets the internal state of the loop for a new run.Nr]   zO`trainer.predict()` only supports the `CombinedLoader(mode="sequential")` mode.c                 S      g | ]}g qS r8   r8   .0_r8   r8   r9   
<listcomp>       z)_PredictionLoop.reset.<locals>.<listcomp>c                 S   ro   r8   r8   rp   r8   r8   r9   rs      rt   )r+   reset_on_runr#   staterk   r   r/   _mode
ValueErrorr,   limitssetupiterfetchedcurrentready_on_before_fetch_start_profiler_on_after_fetch_stop_profilerr0   rC   ranger)   r2   )r5   rW   rG   rC   r8   r8   r9   rK      s"   


z_PredictionLoop.resetc                 C   s$   |    |   |   |   dS )z^Calls ``_on_predict_model_eval``, ``_on_predict_start`` and ``_on_predict_epoch_start`` hooks.N)r   _on_predict_model_eval_on_predict_start_on_predict_epoch_startr:   r8   r8   r9   rL      s   z_PredictionLoop.on_run_startc                 C   s   |   }|   |   |S )zeCalls ``on_predict_epoch_end`` and ``on_predict_end`` hooks and returns results from all dataloaders.)_on_predict_epoch_end_on_predict_end_on_predict_model_train)r5   resultsr8   r8   r9   rV      s   z_PredictionLoop.on_run_endc                 C   s"   | j d ur| j   d | _ d S d S N)r0   teardownr:   r8   r8   r9   r      s   


z_PredictionLoop.teardownrY   rZ   r[   rX   c                 C   s  | j }| j}|dusJ t|t }s*|j|}|jj||d}tj	|d||d}| j
  |s7| ||nd}| ||| jdkrD|nd}	tj|dg|	 R   tj|dg|	 R   | j
  |sl| |	dn|f}
tj	|dg|
R  }|du r| jd | j
  |r|j}|j}|j}| ||| jdkr|nd}	tj|d	|g|	 R   tj|d	|g|	 R   | j
  | js|r| j| t|t d
 dS dS )a  Runs the actual predict step together with all the necessary bookkeeping and the hooks tied to it.

        Args:
            batch: the current batch to run the prediction on
            batch_idx: The index of the current batch.
            dataloader_idx: the index of the dataloader producing the current batch.
            dataloader_iter: The iterator if using this step flavor.

        N)r[   batch_to_deviceFrB   on_predict_batch_startpredict_stepzBpredict returned None if it was on purpose, ignore this warning...on_predict_batch_endcpu)!r#   r0   r=   r   precision_pluginconvert_inputra   _on_before_batch_transferr   _call_strategy_hookr+   increment_ready!_store_data_for_prediction_writer_build_kwargsrC   _call_callback_hooksvalues_call_lightning_module_hookincrement_started!_build_step_args_from_hook_kwargsr-   warnincrement_processedrN   rO   rP   increment_completedr3   r2   re   r	   torchdevice)r5   rY   rZ   r[   rX   r#   rW   using_dataloader_iterany_on_epochhook_kwargs	step_argsrD   r8   r8   r9   rS      sB   




 z_PredictionLoop._predict_stepc                 C   s(   t d|fd|fg}|dur||d< |S )a  Assembles the keyword arguments for the ``predict_step``

        Args:
            batch: the current batch to run the prediction on
            batch_idx: the index of the current batch.
            dataloader_idx: the index of the dataloader producing the current batch. None if not multiple dataloaders
                in sequential mode.

        Returns:
            the dictionary containing all the keyboard arguments for the predict step

        rY   rZ   Nr[   r   )r5   rY   rZ   r[   step_kwargsr8   r8   r9   r     s   z_PredictionLoop._build_kwargsr   step_hook_namec                 C   s<   |  }t| jj|}t|ddds|dd t| S )z/Helper method to build args for `predict_step`.rZ      )min_argsN)copygetattrr#   ra   r    poptupler   )r5   r   r   kwargsstep_hook_fxr8   r8   r9   r   &  s
   z1_PredictionLoop._build_step_args_from_hook_kwargs
dataloaderc                 C   s:   t |dd}t|ts| jdt|j d g S |jS )zReturns a reference to the seen batch indices if the dataloader has a batch sampler wrapped by our
        :class:`~pytorch_lightning.overrides.distributed._IndexBatchSamplerWrapper`.batch_samplerNz@Couldn't infer the batch indices fetched from your dataloader: ``)r   r=   r   r-   r   r@   __name__seen_batch_indices)r5   r   r   r8   r8   r9   _get_batch_indices.  s   
z"_PredictionLoop._get_batch_indicesc           	      C   s   dd | j jD }tdd |D }tdd |D }|s|rI| j}|d us(J |j| }| |}|s6|S || }|rD| j| | |rI|| _|S )Nc                 S   s   g | ]	}t |tr|qS r8   )r=   r
   rq   cbr8   r8   r9   rs   :  s    zE_PredictionLoop._store_data_for_prediction_writer.<locals>.<listcomp>c                 s       | ]}|j jV  qd S r   )intervalon_epochr   r8   r8   r9   	<genexpr>;      zD_PredictionLoop._store_data_for_prediction_writer.<locals>.<genexpr>c                 s   r   r   )r   on_batchr   r8   r8   r9   r   <  r   )	r#   	callbacksanyr/   rF   r   r)   re   r*   )	r5   rZ   r[   prediction_writersr   any_on_batchrG   r   batch_indicesr8   r8   r9   r   9  s    

z1_PredictionLoop._store_data_for_prediction_writerc                 C       | j jdt| j d d S N[z].predict_next)r#   profilerstartr@   r   r:   r8   r8   r9   r   M  s    z _PredictionLoop._on_before_fetchc                 C   r   r   )r#   r   stopr@   r   r:   r8   r8   r9   r   P  s    z_PredictionLoop._on_after_fetchc                 C   s.   | j }t|d t|d t|d dS )z!Calls ``on_predict_start`` hooks.on_predict_startN)r#   r   r   r   r   r5   r#   r8   r8   r9   r   U  s   z!_PredictionLoop._on_predict_startc                 C   s"   | j | jj t| jd d S )Non_predict_model_eval)r4   capturer#   ra   r   r   r:   r8   r8   r9   r   \  s   z&_PredictionLoop._on_predict_model_evalc                 C   s   | j | jj d S r   )r4   restorer#   ra   r:   r8   r8   r9   r   `  s   z'_PredictionLoop._on_predict_model_trainc                 C   s"   | j }t|d t|d dS )z'Calls ``on_predict_epoch_start`` hooks.on_predict_epoch_startN)r#   r   r   r   r   r8   r8   r9   r   c  s   z'_PredictionLoop._on_predict_epoch_startc                 C   s.   | j }t|d t|d | jr| jS dS )zlCalls ``on_predict_epoch_end`` hook.

        Returns:
            the results for all dataloaders

        on_predict_epoch_endN)r#   r   r   r   r;   rD   r   r8   r8   r9   r   i  s   z%_PredictionLoop._on_predict_epoch_endc                 C   s@   | j sg | _g | _| j}t|d t|d t|d dS )zBResets previous gradient status and calls ``on_predict_end`` hook.on_predict_endN)r;   r2   r)   r#   r   r   r   r   r   r8   r8   r9   r   x  s   z_PredictionLoop._on_predict_endc                 C   sn   | j }| jd us
J td| jjdko| jdkot| jt tj	|j
 td| jjdko/| jdktj	|j
 d S )N)r   r]   rB   )r   r   )r#   r/   r   rw   rC   r=   r0   r   r   rd   ra   r   r8   r8   r9   r     s"   z2_PredictionLoop._verify_dataloader_idx_requirement)Tr   )r%   N),r   
__module____qualname____doc__boolr(   propertyr;   setterr   listr   rD   intrC   rI   r   r!   r\   rJ   rK   rL   rV   r   r   rS   r   r   strr   r   objectr   r   r   r   r   r   r   r   r   r   r   __classcell__r8   r8   r6   r9   r"   /   sX    

#


?






r"   )8collectionsr   collections.abcr   typingr   r   r   r   lightning_utilitiesr   pytorch_lightningpllightning_fabric.utilitiesr	   pytorch_lightning.callbacksr
    pytorch_lightning.loops.fetchersr   r   pytorch_lightning.loops.loopr    pytorch_lightning.loops.progressr   !pytorch_lightning.loops.utilitiesr   r   r   'pytorch_lightning.overrides.distributedr   &pytorch_lightning.strategies.launchersr   pytorch_lightning.trainerr   3pytorch_lightning.trainer.connectors.data_connectorr   r   r   r   r    pytorch_lightning.trainer.statesr   r   +pytorch_lightning.utilities.combined_loaderr    pytorch_lightning.utilities.datar   &pytorch_lightning.utilities.exceptionsr   )pytorch_lightning.utilities.model_helpersr   +pytorch_lightning.utilities.signature_utilsr    !pytorch_lightning.utilities.typesr!   r"   r8   r8   r8   r9   <module>   s0   