o
    	Ti                     @   s   d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZm	Z	 e	 r'd dl
Z
e r.d dlZe jdededed fd	d
ZdedefddZdS )    N)	Generator)Trainer)is_mlflow_availableis_wandb_availabletrainernamereturn)NNNc                 c   s    t  }dV  t  }|| }d| jj d| |i}d| jjv r0tjdur0| jj	r0t
| d| jjv rJtjdurL| jj	rNtj|| jjd dS dS dS dS )aB  
    A context manager function for profiling a block of code. Results are logged to Weights & Biases or MLflow
    depending on the trainer's configuration.

    Args:
        trainer (`~transformers.Trainer`):
            Trainer object.
        name (`str`):
            Name of the block to be profiled. Used as a key in the logged dictionary.

    Example:
    ```python
    from transformers import Trainer
    from trl.extras.profiling import profiling_context


    class MyTrainer(Trainer):
        def some_method(self):
            A = np.random.rand(1000, 1000)
            B = np.random.rand(1000, 1000)
            with profiling_context(self, "matrix_multiplication"):
                # Code to profile: simulate a computationally expensive operation
                result = A @ B  # Matrix multiplication
    ```
    Nzprofiling/Time taken: .wandbmlflow)step)timeperf_counter	__class____name__args	report_tor
   runacceleratoris_main_processlogr   log_metricsstateglobal_step)r   r   
start_timeend_timedurationprofiling_metrics r   H/home/ubuntu/.local/lib/python3.10/site-packages/trl/extras/profiling.pyprofiling_context   s   
r    funcc                    s   t   fdd}|S )aV  
    Decorator to profile a function and log execution time using [`extras.profiling.profiling_context`].

    Args:
        func (`callable`):
            Function to be profiled.

    Example:
    ```python
    from transformers import Trainer
    from trl.extras.profiling import profiling_decorator


    class MyTrainer(Trainer):
        @profiling_decorator
        def some_method(self):
            A = np.random.rand(1000, 1000)
            B = np.random.rand(1000, 1000)
            # Code to profile: simulate a computationally expensive operation
            result = A @ B
    ```
    c                    sF   t |  j  | g|R i |W  d    S 1 sw   Y  d S )N)r    r   )selfr   kwargsr!   r   r   wrapper_   s   $z$profiling_decorator.<locals>.wrapper)	functoolswraps)r!   r%   r   r$   r   profiling_decoratorG   s   r(   )
contextlibr&   r   collections.abcr   transformersr   transformers.integrationsr   r   r
   r   contextmanagerstrr    callabler(   r   r   r   r   <module>   s   '