§
    “©ºjÇ  ã                   ó¦   — d Z ddlmZ ddlmZmZm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 dd	lmZ  G d
„ de¦  «        Z G d„ de¦  «        ZdS )zG
BasePredictionWriter
====================

Aids in saving predictions
é    )ÚSequence)ÚAnyÚLiteralÚOptional)ÚoverrideN)ÚCallback)ÚLightningEnum)ÚMisconfigurationException)Úis_param_in_hook_signaturec                   óR   — e Zd ZdZdZdZedefd„¦   «         Zedefd„¦   «         Z	dS )ÚWriteIntervalÚbatchÚepochÚbatch_and_epochÚreturnc                 ó"   — | | j         | j        fv S ©N)ÚBATCHÚBATCH_AND_EPOCH©Úselfs    ú}/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/pytorch_lightning/callbacks/prediction_writer.pyÚon_batchzWriteInterval.on_batch&   ó   € à˜œ
 DÔ$8Ð9Ð9Ð9ó    c                 ó"   — | | j         | j        fv S r   )ÚEPOCHr   r   s    r   Úon_epochzWriteInterval.on_epoch*   r   r   N)
Ú__name__Ú
__module__Ú__qualname__r   r   r   ÚpropertyÚboolr   r   © r   r   r   r   !   so   € € € € € Ø€EØ€EØ'€Oàð:˜$ð :ð :ð :ñ „Xð:ð ð:˜$ð :ð :ð :ñ „Xð:ð :ð :r   r   c                   ó  — e Zd ZdZdded         ddfd„Zedd	d
ddeddfd„¦   «         Zdd	d
dde	de
ee                  de	dededdfd„Zdd	d
ddee	         dee	         ddf
d„Ze	 ddd	d
dde	de	dededdfd„¦   «         Zedd„¦   «         ZdS )ÚBasePredictionWritera 	  Base class to implement how the predictions should be stored.

    Args:
        write_interval: When to write.

    Example::

        import torch
        from pytorch_lightning.callbacks import BasePredictionWriter

        class CustomWriter(BasePredictionWriter):

            def __init__(self, output_dir, write_interval):
                super().__init__(write_interval)
                self.output_dir = output_dir

            def write_on_batch_end(
                self, trainer, pl_module, prediction, batch_indices, batch, batch_idx, dataloader_idx
            ):
                torch.save(prediction, os.path.join(self.output_dir, dataloader_idx, f"{batch_idx}.pt"))

            def write_on_epoch_end(self, trainer, pl_module, predictions, batch_indices):
                torch.save(predictions, os.path.join(self.output_dir, "predictions.pt"))


        pred_writer = CustomWriter(output_dir="pred_path", write_interval="epoch")
        trainer = Trainer(callbacks=[pred_writer])
        model = BoringModel()
        trainer.predict(model, return_predictions=False)

    Example::

        # multi-device inference example

        import torch
        from pytorch_lightning.callbacks import BasePredictionWriter

        class CustomWriter(BasePredictionWriter):

            def __init__(self, output_dir, write_interval):
                super().__init__(write_interval)
                self.output_dir = output_dir

            def write_on_epoch_end(self, trainer, pl_module, predictions, batch_indices):
                # this will create N (num processes) files in `output_dir` each containing
                # the predictions of it's respective rank
                torch.save(predictions, os.path.join(self.output_dir, f"predictions_{trainer.global_rank}.pt"))

                # optionally, you can also save `batch_indices` to get the information about the data index
                # from your prediction data
                torch.save(batch_indices, os.path.join(self.output_dir, f"batch_indices_{trainer.global_rank}.pt"))


        # or you can set `write_interval="batch"` and override `write_on_batch_end` to save
        # predictions at batch level
        pred_writer = CustomWriter(output_dir="pred_path", write_interval="epoch")
        trainer = Trainer(accelerator="gpu", strategy="ddp", devices=8, callbacks=[pred_writer])
        model = BoringModel()
        trainer.predict(model, return_predictions=False)

    r   Úwrite_interval)r   r   r   r   Nc                 óž   — |t          t          ¦  «        vr"t          dd„ t          D ¦   «         › d�¦  «        ‚t          |¦  «        | _        d S )Nz"`write_interval` should be one of c                 ó   — g | ]	}|j         ‘Œ
S r$   )Úvalue)Ú.0Úis     r   ú
<listcomp>z1BasePredictionWriter.__init__.<locals>.<listcomp>p   s   € ÐQqÐQqÐQqÐ^_ÐRSÔRYÐQqÐQqÐQqr   ú.)Úlistr   r
   Úinterval)r   r'   s     r   Ú__init__zBasePredictionWriter.__init__n   sR   € Ø¥¥mÑ!4Ô!4Ð4Ð4Ý+Ð,tÐQqÐQqÕcpÐQqÑQqÔQqÐ,tÐ,tÐ,tÑuÔuÐuÝ% nÑ5Ô5ˆŒˆˆr   Útrainerú
pl.TrainerÚ	pl_moduleúpl.LightningModuleÚstagec                 óR   — t          |j        dd¬¦  «        rt          d¦  «        ‚d S )NÚdataloader_iterT)ÚexplicitzHThe `PredictionWriterCallback` does not support using `dataloader_iter`.)r   Úpredict_stepÚNotImplementedError)r   r2   r4   r6   s       r   ÚsetupzBasePredictionWriter.setups   s:   € å% iÔ&<Ð>OÐZ^Ð_Ñ_Ô_ð 	rÝ%Ð&pÑqÔqÐqð	rð 	rr   Ú
predictionÚbatch_indicesÚ	batch_idxÚdataloader_idxc                 ó   — t          ¦   «         ‚)z0Override with the logic to write a single batch.©r;   )r   r2   r4   r=   r>   r   r?   r@   s           r   Úwrite_on_batch_endz'BasePredictionWriter.write_on_batch_endx   s   € õ "Ñ#Ô#Ð#r   Úpredictionsc                 ó   — t          ¦   «         ‚)z-Override with the logic to write all batches.rB   )r   r2   r4   rD   r>   s        r   Úwrite_on_epoch_endz'BasePredictionWriter.write_on_epoch_end…   s   € õ "Ñ#Ô#Ð#r   r   Úoutputsc           	      óp   — | j         j        sd S |j        j        }|                      |||||||¦  «         d S r   )r0   r   Úpredict_loopÚcurrent_batch_indicesrC   )r   r2   r4   rG   r   r?   r@   r>   s           r   Úon_predict_batch_endz)BasePredictionWriter.on_predict_batch_end�   sI   € ð Œ}Ô%ð 	ØˆFØÔ,ÔBˆØ×Ò ¨°G¸]ÈEÐS\Ð^lÑmÔmÐmÐmÐmr   c                 ó~   — | j         j        sd S |j        j        }|                      |||j        j        |¦  «         d S r   )r0   r   rI   Úepoch_batch_indicesrF   rD   )r   r2   r4   rM   s       r   Úon_predict_epoch_endz)BasePredictionWriter.on_predict_epoch_endž   sG   € àŒ}Ô%ð 	ØˆFØ%Ô2ÔFÐØ×Ò ¨°GÔ4HÔ4TÐViÑjÔjÐjÐjÐjr   )r   )r   )r2   r3   r4   r5   r   N)r   r    r!   Ú__doc__r   r1   r   Ústrr<   r   r   r   ÚintrC   rF   rK   rN   r$   r   r   r&   r&   /   së  € € € € € ð<ð <ð|6ð 6 wÐ/RÔ'Sð 6Ðbfð 6ð 6ð 6ð 6ð
 ðr˜\ð rÐ6Jð rÐSVð rÐ[_ð rð rð rñ „Xðrð$àð$ð (ð$ð ð	$ð
   ¨¤Ô.ð$ð ð$ð ð$ð ð$ð 
ð$ð $ð $ð $ð$àð$ð (ð$ð ˜c”]ð	$ð
   ”}ð$ð 
ð$ð $ð $ð $ð ð  ðnð nàðnð (ðnð ð	nð
 ðnð ðnð ðnð 
ðnð nð nñ „Xðnð ðkð kð kñ „Xðkð kð kr   r&   )rO   Úcollections.abcr   Útypingr   r   r   Útyping_extensionsr   Úpytorch_lightningÚplÚ$pytorch_lightning.callbacks.callbackr   Úpytorch_lightning.utilitiesr	   Ú&pytorch_lightning.utilities.exceptionsr
   Ú+pytorch_lightning.utilities.signature_utilsr   r   r&   r$   r   r   ú<module>r[      s  ððð ð %Ð $Ð $Ð $Ð $Ð $Ø )Ð )Ð )Ð )Ð )Ð )Ð )Ð )Ð )Ð )à &Ð &Ð &Ð &Ð &Ð &à Ð Ð Ð Ø 9Ð 9Ð 9Ð 9Ð 9Ð 9Ø 5Ð 5Ð 5Ð 5Ð 5Ð 5Ø LÐ LÐ LÐ LÐ LÐ LØ RÐ RÐ RÐ RÐ RÐ Rð:ð :ð :ð :ð :�Mñ :ô :ð :ðtkð tkð tkð tkð tk˜8ñ tkô tkð tkð tkð tkr   