o
    oi                     @   s   d Z ddlZddlZddlZddlZddlZddlZddlmZ ddl	m
Z
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 eeZG d	d
 d
eZdS )z<Profiler to check if there are any bottlenecks in your code.    N)Path)DictOptionalTupleUnion)override)get_filesystem)Profiler)rank_zero_onlyc                       s   e Zd ZdZ				ddeeeef  dee dede	d	df
 fd
dZ
eded	dfddZeded	dfddZdedejd	dfddZed	efddZedee d	df fddZd	efddZ  ZS )AdvancedProfilerzThis profiler uses Python's cProfiler to record more detailed information about time spent in each function call
    recorded during a given action.

    The output is quite verbose and you should only use this if you want very detailed reports.

    N      ?Fdirpathfilenameline_count_restriction
dump_statsreturnc                    s&   t  j||d i | _|| _|| _dS )a  
        Args:
            dirpath: Directory path for the ``filename``. If ``dirpath`` is ``None`` but ``filename`` is present, the
                ``trainer.log_dir`` (from :class:`~lightning.pytorch.loggers.tensorboard.TensorBoardLogger`)
                will be used.

            filename: If present, filename where the profiler results will be saved instead of printing to stdout.
                The ``.txt`` extension will be used automatically.

            line_count_restriction: this can be used to limit the number of functions
                reported for each action. either an integer (to select a count of lines),
                or a decimal fraction between 0.0 and 1.0 inclusive (to select a percentage of lines)

            dump_stats: Whether to save raw profiler results. When ``True`` then ``dirpath`` must be provided.

        Raises:
            ValueError:
                If you attempt to stop recording an action which was never started.
        )r   r   N)super__init__profiled_actionsr   r   )selfr   r   r   r   	__class__ X/home/ubuntu/.local/lib/python3.10/site-packages/lightning/pytorch/profilers/advanced.pyr   *   s   
zAdvancedProfiler.__init__action_namec                 C   s*   || j vrt | j |< | j |   d S )N)r   cProfileProfileenable)r   r   r   r   r   startI   s   
zAdvancedProfiler.startc                 C   s0   | j |}|d u rtd| d|  d S )Nz(Attempting to stop recording an action (z) which was never started.)r   get
ValueErrordisable)r   r   prr   r   r   stopO   s   zAdvancedProfiler.stopprofilec           
   
   C   s  | j sJ tj| j | j|dd}t|}|j| j dd tjdt	t
jt dT}||d5}tj|d}|| t|}||d	}	||	  W d    n1 s[w   Y  W d    n1 sjw   Y  W d    d S W d    d S 1 sw   Y  d S )
Nz.prof)r   	extensionT)exist_oktest)prefixsuffixdirwbztmp.profrb)r   ospathjoin_prepare_filenamer   mkdirstempfileTemporaryDirectorystrr
   rankgetcwdopenr   writeread)
r   r   r$   dst_filepathdst_fstmp_dirdst_filesrc_filepathsrc_fssrc_filer   r   r   _dump_statsV   s$   

PzAdvancedProfiler._dump_statsc                 C   sl   i }| j  D ])\}}| jr| || t }tj||d 	d}|
| j | ||< q| |S )N)stream
cumulative)r   itemsr   rA   ioStringIOpstatsStats
strip_dirs
sort_statsprint_statsr   getvalue_stats_to_str)r   recorded_statsr   r"   spsr   r   r   summarye   s   
zAdvancedProfiler.summarystagec                    s   t  j|d i | _d S )N)rR   )r   teardownr   )r   rR   r   r   r   rS   q   s   
zAdvancedProfiler.teardownc                 C   s   | j d| j| j| jdfS )Nr   )r   r   r   )r   r   r   r   )r   r   r   r   
__reduce__v   s   zAdvancedProfiler.__reduce__)NNr   F)__name__
__module____qualname____doc__r   r   r4   r   floatboolr   r   r   r#   r   r   rA   rQ   rS   r   rT   __classcell__r   r   r   r   r   "   s6    	r   )rX   r   rE   loggingr-   rG   r2   pathlibr   typingr   r   r   r   typing_extensionsr   #lightning.fabric.utilities.cloud_ior   $lightning.pytorch.profilers.profilerr	   %lightning.pytorch.utilities.rank_zeror
   	getLoggerrU   logr   r   r   r   r   <module>   s   
