o
    hc                     @   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Zg dZdDdeddfdd	Zdefd
dZdDdeddfddZdefddZdDdeddfddZdefddZdeddfddZdefddZdeddfddZdefddZdEded eddfd!d"Zdefd#d$Zdeeeeef fd%d&Zdeeef fd'd(Zdeddfd)d*Z dFde
e defd+d,Z!dFde
e defd-d.Z"d/eddfd0d1Z#defd2d3Z$deddfd4d5Z%d6ede&e fd7d8Z'dGd9d:Z(d;ed<eddfd=d>Z)dGd?d@Z*d6edAeddfdBdCZ+dS )Ha]#  
This module exposes a TunableOp interface.

Some operations, such as GEMMs, could be implemented using more than one library
or more than one technique. For example, a GEMM could be implemented for CUDA or
ROCm using either the blas or blasLt libraries. Further, ROCm's rocblas and
hipblaslt libraries allow the user to query for all possible algorithms and then
choose one. How does one know which implementation is the fastest and should be
chosen? That's what TunableOp provides.

Enabling TunableOp and Tuning Separately
========================================

The TunableOp feature is enabled separately from enabling the tuning phase
itself. Enabling TunableOp means that PyTorch will replace any standard
operators with their Tunable implementations. Any call to a TunableOp first
checks whether it has already been tuned for the given operator inputs. If so,
it will immediately call the tuned operation; no further tuning will take place
even when the tuning setting is enabled. Instead if no tuning result is found,
and tuning is enabled, the TunableOp will benchmark every registered
implementation of that operator for the given set of inputs and select the
fastest.

File Input and Output
=====================

The first time any TunableOp is invoked, the internal database of tuned
operations will be prepared by attempting to read the results from the given
file. The default filename is 'tunableop_results.csv'. To support tuning when
multiple GPUs are used across multiple processes, the GPU device ordinal is
automatically inserted into the filename to avoid multiple processes overwriting
the same file.

If tuning is enabled and new tunings are discovered during the course of your
workload, it will also write out to this same filename with all tunings, both
the ones it read in at startup as well as the new ones found at runtime. This
can be used, for example, to build up a tunings file across many workloads by
reusing the same file. The output file is automatically created when the
application terminates. This behavior can be controlled by the C++ and Python
APIs but not the environment variables.

Assuming you specified a filename, you'll end up with a CSV file with contents
like so::

  Validator,PT_VERSION,2.2.0
  Validator,ROCM_VERSION,6.0.0.0-12969-1544e39
  Validator,HIPBLASLT_VERSION,0.6.0-a9c5cc7
  Validator,ROCBLAS_VERSION,4.0.0-72e57364-dirty
  GemmTunableOp_float_NT,nt_25088_4096_64,Gemm_Hipblaslt_1219,1.262
  GemmTunableOp_float_NT,nt_4096_4096_64,Gemm_Rocblas_1216,0.033

Note the "Validator" lines. If you change a library version, or ROCm version, or
PyTorch version, TunableOp will detect this and reject the tunings file because
the prior tunings are likely affected by other software changes.

The remaining lines are the tuned solutions for each TunableOp encountered
during your execution. Each line consists of 4 comma-separated fields: operator
name, operator parameters, solution name, and average execution time. The
execution time is an optional field. The CSV file can be edited, but with
caution. For example, the solution name (field 3) can be changed to "Default"
and it will fall back to the original PyTorch untuned implementation. Or, in the
case of ROCm's hipBLAS or hipBLASLt libraries, if you know the specific solution
index you can override the solution that TunableOp selected by replacing the
value. The operator name and parameters (fields 1 and 2) are internally named
and should not be modified. In the case of GemmTunableOp, field 1 indicates the
datatype and whether the inputs are transposed (T) or not (N) and field 2
indicates the M, N, K input shapes.

There is an option to enable verbose output but it is only recommended for
debugging purposes. This will produce a lot of diagnostic messages but may be
useful to see if TunableOp is being used at all. Otherwise, TunableOp is
completely silent, besides file output, unless there is a warning or error
during its use. The verbose option is only available by setting the environment
variable PYTORCH_TUNABLEOP_VEROBSE=1.

A Note on Tuning Behavior, Warmup, and Cache Effects
====================================================

Tuning an operator consists of iterating through the list or registered
implementations and profiling each one. The profile is established by running a
single implementation in a loop multiple times and taking the average execution
time. There is also an optional warmup phase prior to tuning that can help with
reaching stable power states by the hardware. During tuning of a workload the
various hardware caches will more likely produce hits than when not tuning.
There are options for flushing the instruction cache and rotate the input tensors
which might help produce a more faithful profile of the tuned operator as if the
operator were run within a larger workload instead of in a tight, repetitive loop.

By default, each possible solution for a given operator will be run for either
100 iterations or as many iterations that can be run within 30ms, whichever is
smaller, and its average execution will be calculated. The fastest solution
among all that were successfully profiled will be chosen. A profile might fail
if the given solution doesn't achieve the same accuracy as the default
implementation or if the solution returns an error code.

Current Tunable Operators
=========================

TunableGemm for ROCm
--------------------

Currently only a TunableGemm for ROCm is implemented. Note that CUDA builds of
PyTorch will function correctly when using TunableOp but the only solution
available to CUDA builds is the 'Default' implementation i.e. the original
cuBLAS default, now called through TunableOp. Any call to at::cuda::blas::gemm()
or ::bgemm() will be routed through TunableOp when enabled. Calling gemm() for a
given set of input arguments (transa, transb, m, n, k) will attempt to use the
fastest available implementation across both rocblas and hipblaslt.

Offline Tuning
==============

Motivation
----------
There are several use cases for offline tuning.

One use case involves a workload with a high-memory utilization, where regular tuning might lead to running out of memory.

Another use case is for compute-intensive workloads. In such cases, it is more resource-efficient to collect
the GEMMs for the workload once and then tune repeatedly with different tuning parameters or libraries.

Workflow
--------
There are basically two steps:
1) Set the environment variables to collect the untuned GEMM and this will generate ``tunableop_untuned0.csv``:

.. code-block:: python

   PYTORCH_TUNABLEOP_ENABLED=1
   PYTORCH_TUNABLEOP_TUNING=0
   PYTORCH_TUNABLEOP_RECORD_UNTUNED=1
   ...

2) Run a Python script that reads the ``tunableop_untuned0.csv`` and generates the ``tunableop_results0.csv``, like this:

.. code-block:: python

   import torch.cuda.tunable as tunable
   import os

   os.putenv('PYTORCH_TUNABLEOP_ENABLED', '1')
   os.putenv('PYTORCH_TUNABLEOP_TUNING', '1')
   os.putenv('PYTORCH_TUNABLEOP_RECORD_UNTUNED', '0')
   tunable.tune_gemm_in_file("tunableop_untuned0.csv")


It is also possible to take multiple untuned files and distribute the GEMMs for tuning to multiple GPUs
within a single node. In the first step, the GEMMs are first gathered and duplicate GEMMs are eliminated.
Next, the GEMMs are distributed to different GPUs for tuning. After all GEMMs are tuned, the results from
all the GPUs are then gathered into a single file whose base filename has ``_full0`` appended to it
(for example ``tunableop_results_full0.csv``). Finally, this new file, containing the gathered results, will be
duplicated N times, once for each GPU as convenience to the user will run the workload with the tuned
configuration on N GPUs.

.. code-block:: python

   if __name__ == "__main__":
       num_gpus = 8 # number of GPUs that will be used during the tuning process
       tunable.mgpu_tune_gemm_in_file("tunableop_untuned?.csv", num_gpus)

Note that the usage of the ``mgpu_tune_gemm_in_file`` API is different from its single GPU counterpart
(``tune_gemm_in_file``). The body of the Python script that calls the API must be wrapped in ``main()`` as shown
due to the use of concurrent futures module. The argument to ``mgpu_tune_gemm_in_file`` must contain a wild card
expression (``?`` or ``*``) to generate the list of untuned files containing the GEMMs to be processed. The ``num_gpus``
must between 1 and the total number of GPUs available.

Tuning Context
==============

The behavior of TunableOp is currently manipulated through environment
variables, the C++ interface of at::cuda::tunable::getTuningContext(), or the
torch.cuda.tunable python interfaces. The environment variables take precedence
over any setting you manipulate using the C++ or Python APIs.

Environment Variable Interface
------------------------------
Environment variables are cached the first time they are read. You cannot use the
environment variable interface programmatically since the settings become fixed.
Use the C++ or Python APIs instead.

    N)Optional)enable
is_enabledtuning_enabletuning_is_enabledrecord_untuned_enablerecord_untuned_is_enabledset_max_tuning_durationget_max_tuning_durationset_max_tuning_iterationsget_max_tuning_iterationsset_filenameget_filenameget_resultsget_validatorswrite_file_on_exit
write_file	read_filetune_gemm_in_filemgpu_tune_gemm_in_fileset_rotating_buffer_sizeget_rotating_buffer_sizeTvalreturnc                 C      t j|  dS )z@This is the big on/off switch for all TunableOp implementations.N)torch_C_cuda_tunableop_enabler    r   f/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/cuda/tunable.pyr      s   r   c                   C   
   t j S )z1Returns whether the TunableOp feature is enabled.)r   r   _cuda_tunableop_is_enabledr   r   r   r    r         
r   c                 C   r   )zEnable tuning of TunableOp implementations.

    When enabled, if a tuned entry isn't found, run the tuning step and record
    the entry.
    N)r   r   _cuda_tunableop_tuning_enabler   r   r   r    r         r   c                   C   r!   )z7Returns whether TunableOp implementations can be tuned.)r   r   !_cuda_tunableop_tuning_is_enabledr   r   r   r    r      r#   r   c                 C   r   )zEnable recording untuned of TunableOp perations for offline tuning.

    When enabled, if a tuned entry isn't found, write it to the untuned file.
    N)r   r   _cuda_record_untuned_enabler   r   r   r    r      s   r   c                   C   r!   )zEReturns whether TunableOp operations are recorded for offline tuning.)r   r   _cuda_record_untuned_is_enabledr   r   r   r    r      r#   r   durationc                 C   r   )zSet max time in milliseconds to spend tuning a given solution.

    If both max tuning duration and iterations are set, the smaller of the two
    will be honored. At minimum 1 tuning iteration will always be run.
    N)r   r   '_cuda_tunableop_set_max_tuning_duration)r)   r   r   r    r	      r%   r	   c                   C   r!   )z.Get max time to spend tuning a given solution.)r   r   '_cuda_tunableop_get_max_tuning_durationr   r   r   r    r
     r#   r
   
iterationsc                 C   r   )zSet max number of iterations to spend tuning a given solution.

    If both max tuning duration and iterations are set, the smaller of the two
    will be honored. At minimum 1 tuning iteration will always be run.
    N)r   r   )_cuda_tunableop_set_max_tuning_iterations)r,   r   r   r    r     r%   r   c                   C   r!   )z4Get max iterations to spend tuning a given solution.)r   r   )_cuda_tunableop_get_max_tuning_iterationsr   r   r   r    r     r#   r   Ffilenameinsert_device_ordinalc                 C   s   t j| | dS )a/  Set the filename to use for input/output of tuning results.

    If :attr:`insert_device_ordinal` is ``True`` then the current device ordinal
    will be added to the given filename automatically. This can be used in a
    1-process-per-gpu cenario to ensure all processes write to a separate file.
    N)r   r   _cuda_tunableop_set_filename)r/   r0   r   r   r    r     s   r   c                   C   r!   )zGet the results filename.)r   r   _cuda_tunableop_get_filenamer   r   r   r    r   %  r#   r   c                   C   r!   )zReturn all TunableOp results.)r   r   _cuda_tunableop_get_resultsr   r   r   r    r   *  r#   r   c                   C   r!   )z Return the TunableOp validators.)r   r   _cuda_tunableop_get_validatorsr   r   r   r    r   /  r#   r   c                 C   r   )a  During Tuning Context destruction, write file to disk.

    This is useful as a final flush of your results to disk if your application
    terminates as result of normal operation or an error. Manual flushing of
    your results can be achieved by manually calling ``write_file()``.N)r   r   "_cuda_tunableop_write_file_on_exitr   r   r   r    r   4  r%   r   c                 C      | du rt  } tj| S )zfWrite results to a CSV file.

    If :attr:`filename` is not given, ``get_filename()`` is called.
    N)r   r   r   _cuda_tunableop_write_filer/   r   r   r    r   =     r   c                 C   r6   )zqRead results from a TunableOp CSV file.

    If :attr:`filename` is not given, ``get_filename()`` is called.
    N)r   r   r   _cuda_tunableop_read_filer8   r   r   r    r   G  r9   r   buffer_sizec                 C   s   t j| S )zSet rotating buffer size to this value in MB, if the buffer size is greater than zero.

    If less than zero, query L2 cache size. If equal to zero, means deactivate rotating buffer.
    )r   r   (_cuda_tunableop_set_rotating_buffer_size)r;   r   r   r    r   Q  s   r   c                   C   r!   )z*Get the rotating buffer size in kilobytes.)r   r   (_cuda_tunableop_get_rotating_buffer_sizer   r   r   r    r   Y  r#   r   c                 C   sj   t  sJ t s
J tj }t| }|D ]}|dr"t|| qW d   dS 1 s.w   Y  dS )ztune GEMM in file.Gemm
ScaledGemmN)r   r   r   cudacurrent_deviceopen
startswith_process_single_offline_gemm)r/   deviceidfileliner   r   r    r   ^  s   





"r   filename_patternc              	   C   s`   t  }t| D ]%}t|}|D ]}|dr|| qW d   n1 s(w   Y  q|S )zOProcess multiple untuned results file and return a set with duplicates removed.r>   N)setglobrC   rD   add)rI   unique_gemm_entries	file_pathrG   rH   r   r   r    &_gather_unique_untuned_gemm_from_filesl  s   


rO   c               	   C   s  t  } g }t }|dur1|dkr1|d}|dkr.|dkr.|d|d  d ||d  }n$d}n!td}|du s>|dkrAd	}nd
|v rL|d
d}n|dd}d|v sXJ d}t|}t|}|D ]/}	t|	}
|
D ]}|	dr}|s||
| qn| | qnW d   n1 sw   Y  d}qe|dd}t|d}|D ]}|| q| D ]}|| qW d   n1 sw   Y  td|D ]}|dt|}t|| qdS )zMGather results from multiple tunableop results file and create a single file.N .r      ?PYTORCH_TUNABLEOP_FILENAMEztunableop_results?.csvz%dz?.F	ValidatorT_full0w0)rJ   r   findosgetenvreplacerK   lenrC   rD   appendrL   writerangestrshutilcopy)
gemm_linesvalidator_linesresults_filenamedot_posrI   results_filename_env	FirstFilematching_filesnum_matching_filesrN   rG   rH   output_fileout_fileiduplicate_filer   r   r    _gather_tunableop_resultsy  sT   





	rq   untuned_gemm_linegpu_idc           #      C   s   dt | }tjtjtjtjtjtjtjtj	tj
tjd
}|  ddd }|d d}d}d}d}d}	|dkrW|d d\}
}}|d dk}|d	 dk}||}nV|d d}|d}|d }
|d	 d |d  }|d
 d |d  }|dkr|d d |d  }n|d }|| d dk}|| d	 dk}||}||}||}	|d	 d}dd |d	d D \}}}|
dkr|rtj||||d ntj||||d}|rtj||||d ntj||||d}t|| dS |
dkrWdd |dd D \}|rtj|||||dn	tj|||||d}|r/tj|||||dn	tj|||||d}|rB|d	dn|}|rM|d	dn|}t|| dS |
dkrd}d}|rptj||f|||d n
tj||f|||d}|rtj||f|||dntj||f|||d }|d dksJ |d dkrd}nd}|rtj|jd d	f|d}tjd	|jd f|d}ntjd|d}tjd |d}|d! d"ksJ |d# d$krtj|||||	d% dS d&}||d# } |rtj|f|| |dn	tj|f|| |d}!tj|||||	|!d' dS |
d(krv||ks*J |r8tj||||d ntj||||d}"|rMtj||||dn
tj||||d }|rctj|||dntj|||d}!tjj|"||! dS td)|
  dS )*zProcess a single untuned GEMM.zcuda:)
floatdoubleBFloat16Halfzc10::complex<double>zc10::complex<float>Float8_e4m3fnFloat8_e5m2Float8_e4m3fnuzFloat8_e5m2fnuz,Nr   _   TrS                  c                 S      g | ]}t |qS r   int.0gr   r   r    
<listcomp>      z0_process_single_offline_gemm.<locals>.<listcomp>GemmTunableOp)dtypedeviceGemmStridedBatchedTunableOpc                 S   r   r   r   r   r   r   r    r     r   ScaledGemmTunableOpg      ?g      ?   rw	   1TF)r   g?g?
   bias   None)scale_ascale_b	out_dtypeg?)r   r   r   r   GemmAndBiasTunableOpzerror: unknown op )rb   r   float32float64bfloat16half
complex128	complex64float8_e4m3fnfloat8_e5m2float8_e4m3fnuzfloat8_e5m2fnuzstripsplitcountgetrandtmm	transposebmmfullonesshapetensor
_scaled_mmnn
functionallinearwarningswarn)#rr   rs   rF   
dtype_dictuntuned_gemmunderscore_countr   dtypeAdtypeBdtypeCop_sig	data_typelayouttransAtransBuntuned_gemm_tempr   
data_typeA
data_typeB
data_typeCnmkmatAmatBbfillAfillBrowwisescaleAscaleBfillbias
bias_dtyper   Xr   r   r    rE     s   









rE   c                   C   sJ   t  du rtd td t  du sJ t du sJ t du s#J dS )zHelper function for multi-GPU tuning case. Need to check that TunableOp feature
    is enabled and that tuning is enabled.
    Fz-TunableOp was disabled. Trying to enable now.TN)r   r   r   r   r   r   r   r   r   r    _check_tuning_assertionsK  s   

r   num_gpusc                 C   s  t | }tj }d|  kr|ksJ  J td}g }g }d}tjj||t	dJ}|D ]}	|
t|	|}
||
 |d | }q.tj|D ]}
|
  qIt|D ]}|
t}|| qTtj|D ]}|  qgW d   n1 sxw   Y  tj  t  dS )zDProcess one or more files and distribute work over one or more GPUs.rS   spawnr   )max_workers
mp_contextinitializerN)rO   r   rA   device_countmpget_context
concurrentfuturesProcessPoolExecutorr   submitrE   r_   as_completedresultra   r   synchronizerq   )rI   r   rM   
total_gpusr   r   flush_resultshexecutorrH   futurer   flush_resultr   r   r    r   X  s8   







r   )T)F)N)r   N),__doc__concurrent.futuresr   rK   multiprocessingr   r[   rc   r   typingr   r   __all__boolr   r   r   r   r   r   r   r	   r
   r   r   rb   r   r   tuplert   r   r   r   r   r   r   r   r   rJ   rO   rq   rE   r   r   r   r   r   r    <module>   sJ     6			
	


? 
