o
    oiH                     @   sH  d dl mZ d dlmZmZmZmZmZ d dlZd dl	m
Z
 d dlm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l0m1Z1 d dl2m3Z3 d dl4m5Z5 d dl6m7Z7 G dd deZ8dS )    OrderedDict)AnyIteratorList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__ [/home/ubuntu/.local/lib/python3.10/site-packages/lightning/pytorch/loops/prediction_loop.pyr)   1   s   z_PredictionLoop.__init__c                 C   s   | j S )z)Whether to return the predictions or not.)r4   r6   r9   r9   r:   return_predictionsC   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   typer4   )r6   r<   return_supportedr9   r9   r:   r<   H   s   
c                 C   s*   | j g kr| j S | jdkr| j d S | j S )zThe cached predictions.   r   )r3   num_dataloadersr;   r9   r9   r:   predictionsT   s   
z_PredictionLoop.predictionsc                 C   s   | j }|dus	J t|jS )z-Returns the number of prediction dataloaders.N)r0   len	flattened)r6   combined_loaderr9   r9   r:   rD   [   s   
z_PredictionLoop.num_dataloadersc                 C   s   t | jdkS )Nr   )sumr-   r;   r9   r9   r:   skipb   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_datarJ   reseton_run_startr1   r>   r   next_batch
_batch_idx_dataloader_idxdoner,   is_last_batch_predict_stepStopIteration_restarting
on_run_end)r6   data_fetcherdataloader_iterbatch	batch_idxdataloader_idxr9   r9   r:   runf   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-   rG   r   r   appendr   rF   floatr   r0   )r6   r$   sourcedataloadersrH   allow_zero_length
trainer_fnstagedllengthnum_batchesr9   r9   r:   rK      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 r9   r9   .0_r9   r9   r:   
<listcomp>       z)_PredictionLoop.reset.<locals>.<listcomp>c                 S   rp   r9   r9   rq   r9   r9   r:   rt      ru   )r,   reset_on_runr$   staterl   r   r0   _mode
ValueErrorr-   limitssetupiterfetchedcurrentready_on_before_fetch_start_profiler_on_after_fetch_stop_profilerr1   rD   ranger*   r3   )r6   rX   rH   rD   r9   r9   r:   rL      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;   r9   r9   r:   rM      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)r6   resultsr9   r9   r:   rW      s   z_PredictionLoop.on_run_endc                 C   s"   | j d ur| j   d | _ d S d S N)r1   teardownr;   r9   r9   r:   r      s   


z_PredictionLoop.teardownrZ   r[   r\   rY   c                 C   s  | j }| j}|dusJ t|t }s*|j|}|jj||d}tj	|d||d}| j
  |s7| ||}| ||| jdkrB|nd}	tj|dg|	 R   tj|dg|	 R   | j
  |sj| |	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_devicerC   on_predict_batch_startpredict_stepzBpredict returned None if it was on purpose, ignore this warning...on_predict_batch_endcpu)!r$   r1   r>   r   precision_pluginconvert_inputrb   _on_before_batch_transferr   _call_strategy_hookr,   increment_ready!_store_data_for_prediction_writer_build_kwargsrD   _call_callback_hooksvalues_call_lightning_module_hookincrement_started!_build_step_args_from_hook_kwargsr.   warnincrement_processedrO   rP   rQ   increment_completedr4   r3   rf   r
   torchdevice)r6   rZ   r[   r\   rY   r$   rX   using_dataloader_iterany_on_epochhook_kwargs	step_argsrE   r9   r9   r:   rT      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

        rZ   r[   Nr\   r   )r6   rZ   r[   r\   step_kwargsr9   r9   r:   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`.r[      )min_argsN)copygetattrr$   rb   r!   poptupler   )r6   r   r   kwargsstep_hook_fxr9   r9   r:   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:`~lightning.pytorch.overrides.distributed._IndexBatchSamplerWrapper`.batch_samplerNz@Couldn't infer the batch indices fetched from your dataloader: ``)r   r>   r   r.   r   rA   __name__seen_batch_indices)r6   r   r   r9   r9   r:   _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 r9   )r>   r   rr   cbr9   r9   r:   rt   8  s    zE_PredictionLoop._store_data_for_prediction_writer.<locals>.<listcomp>c                 s       | ]}|j jV  qd S r   )intervalon_epochr   r9   r9   r:   	<genexpr>9      zD_PredictionLoop._store_data_for_prediction_writer.<locals>.<genexpr>c                 s   r   r   )r   on_batchr   r9   r9   r:   r   :  r   )	r$   	callbacksanyr0   rG   r   r*   rf   r+   )	r6   r[   r\   prediction_writersr   any_on_batchrH   r   batch_indicesr9   r9   r:   r   7  s    

z1_PredictionLoop._store_data_for_prediction_writerc                 C       | j jdt| j d d S N[z].predict_next)r$   profilerstartrA   r   r;   r9   r9   r:   r   K  s    z _PredictionLoop._on_before_fetchc                 C   r   r   )r$   r   stoprA   r   r;   r9   r9   r:   r   N  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   r6   r$   r9   r9   r:   r   S  s   z!_PredictionLoop._on_predict_startc                 C   s"   | j | jj t| jd d S )Non_predict_model_eval)r5   capturer$   rb   r   r   r;   r9   r9   r:   r   Z  s   z&_PredictionLoop._on_predict_model_evalc                 C   s   | j | jj d S r   )r5   restorer$   rb   r;   r9   r9   r:   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   r9   r9   r:   r   a  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<   rE   r   r9   r9   r:   r   g  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<   r3   r*   r$   r   r   r   r   r   r9   r9   r:   r   v  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^   rC   )r   r   )r$   r0   r   rx   rD   r>   r1   r   r   re   rb   r   r9   r9   r:   r     s"   z2_PredictionLoop._verify_dataloader_idx_requirement)Tr   )r&   N),r   
__module____qualname____doc__boolr)   propertyr<   setterr   r   r   rE   intrD   rJ   r   r"   r]   rK   rL   rM   rW   r   r   rT   r   r   strr   r   objectr   r   r   r   r   r   r   r   r   r   r   __classcell__r9   r9   r7   r:   r#   .   sX    

#


>






r#   )9collectionsr   typingr   r   r   r   r   r   lightning_utilitiesr	   lightning.pytorchpytorchpllightning.fabric.utilitiesr
   lightning.pytorch.callbacksr    lightning.pytorch.loops.fetchersr   r   lightning.pytorch.loops.loopr    lightning.pytorch.loops.progressr   !lightning.pytorch.loops.utilitiesr   r   r   'lightning.pytorch.overrides.distributedr   &lightning.pytorch.strategies.launchersr   lightning.pytorch.trainerr   3lightning.pytorch.trainer.connectors.data_connectorr   r   r   r   r    lightning.pytorch.trainer.statesr   r   +lightning.pytorch.utilities.combined_loaderr    lightning.pytorch.utilities.datar   &lightning.pytorch.utilities.exceptionsr   )lightning.pytorch.utilities.model_helpersr    +lightning.pytorch.utilities.signature_utilsr!   !lightning.pytorch.utilities.typesr"   r#   r9   r9   r9   r:   <module>   s.   