o
    h_                     @   s   d dl Z d dlZd dlZd dlmZmZ d dlZd dlmZ zd dl	Z
dZW n ey3   dZdZ
Y nw g dZdedefd	d
Zdd ZG dd dZdd Zdd ZdedefddZ	ddddedee fddZddefddZdS )    N)AnyOptional)_dtypeTF)autocast_decoratorautocastis_autocast_available
custom_fwd
custom_bwddevice_typereturnc                 C   s   t j| S )ax  
    Return a bool indicating if autocast is available on :attr:`device_type`.

    Args:
        device_type(str):  Device type to use. Possible values are: 'cuda', 'cpu', 'mtia', 'xpu' and so on.
            The type is the same as the `type` attribute of a :class:`torch.device`.
            Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
    )torch_C_is_autocast_availabler
    r   k/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/amp/autocast_mode.pyr      s   	r   c                    s"   t  fdd}d|_|S )Nc                     s6     | i |W  d    S 1 sw   Y  d S Nr   argskwargsautocast_instancefuncr   r   decorate_autocast)   s   $z-autocast_decorator.<locals>.decorate_autocastz5@autocast() decorator is not supported in script mode)	functoolswraps__script_unsupported)r   r   r   r   r   r   r   (   s   r   c                
   @   s`   e Zd ZdZ			ddedee dedee fdd	Zd
d Z	de
de
de
fddZdd ZdS )r   a  
    Instances of :class:`autocast` serve as context managers or decorators that
    allow regions of your script to run in mixed precision.

    In these regions, ops run in an op-specific dtype chosen by autocast
    to improve performance while maintaining accuracy.
    See the :ref:`Autocast Op Reference<autocast-op-reference>` for details.

    When entering an autocast-enabled region, Tensors may be any type.
    You should not call ``half()`` or ``bfloat16()`` on your model(s) or inputs when using autocasting.

    :class:`autocast` should wrap only the forward pass(es) of your network, including the loss
    computation(s).  Backward passes under autocast are not recommended.
    Backward ops run in the same type that autocast used for corresponding forward ops.

    Example for CUDA Devices::

        # Creates model and optimizer in default precision
        model = Net().cuda()
        optimizer = optim.SGD(model.parameters(), ...)

        for input, target in data:
            optimizer.zero_grad()

            # Enables autocasting for the forward pass (model + loss)
            with torch.autocast(device_type="cuda"):
                output = model(input)
                loss = loss_fn(output, target)

            # Exits the context manager before backward()
            loss.backward()
            optimizer.step()

    See the :ref:`Automatic Mixed Precision examples<amp-examples>` for usage (along with gradient scaling)
    in more complex scenarios (e.g., gradient penalty, multiple models/losses, custom autograd functions).

    :class:`autocast` can also be used as a decorator, e.g., on the ``forward`` method of your model::

        class AutocastModel(nn.Module):
            ...
            @torch.autocast(device_type="cuda")
            def forward(self, input):
                ...

    Floating-point Tensors produced in an autocast-enabled region may be ``float16``.
    After returning to an autocast-disabled region, using them with floating-point
    Tensors of different dtypes may cause type mismatch errors.  If so, cast the Tensor(s)
    produced in the autocast region back to ``float32`` (or other dtype if desired).
    If a Tensor from the autocast region is already ``float32``, the cast is a no-op,
    and incurs no additional overhead.
    CUDA Example::

        # Creates some tensors in default dtype (here assumed to be float32)
        a_float32 = torch.rand((8, 8), device="cuda")
        b_float32 = torch.rand((8, 8), device="cuda")
        c_float32 = torch.rand((8, 8), device="cuda")
        d_float32 = torch.rand((8, 8), device="cuda")

        with torch.autocast(device_type="cuda"):
            # torch.mm is on autocast's list of ops that should run in float16.
            # Inputs are float32, but the op runs in float16 and produces float16 output.
            # No manual casts are required.
            e_float16 = torch.mm(a_float32, b_float32)
            # Also handles mixed input types
            f_float16 = torch.mm(d_float32, e_float16)

        # After exiting autocast, calls f_float16.float() to use with d_float32
        g_float32 = torch.mm(d_float32, f_float16.float())

    CPU Training Example::

        # Creates model and optimizer in default precision
        model = Net()
        optimizer = optim.SGD(model.parameters(), ...)

        for epoch in epochs:
            for input, target in data:
                optimizer.zero_grad()

                # Runs the forward pass with autocasting.
                with torch.autocast(device_type="cpu", dtype=torch.bfloat16):
                    output = model(input)
                    loss = loss_fn(output, target)

                loss.backward()
                optimizer.step()


    CPU Inference Example::

        # Creates model in default precision
        model = Net().eval()

        with torch.autocast(device_type="cpu", dtype=torch.bfloat16):
            for input in data:
                # Runs the forward pass with autocasting.
                output = model(input)

    CPU Inference Example with Jit Trace::

        class TestModel(nn.Module):
            def __init__(self, input_size, num_classes):
                super().__init__()
                self.fc1 = nn.Linear(input_size, num_classes)
            def forward(self, x):
                return self.fc1(x)

        input_size = 2
        num_classes = 2
        model = TestModel(input_size, num_classes).eval()

        # For now, we suggest to disable the Jit Autocast Pass,
        # As the issue: https://github.com/pytorch/pytorch/issues/75956
        torch._C._jit_set_autocast_mode(False)

        with torch.cpu.amp.autocast(cache_enabled=False):
            model = torch.jit.trace(model, torch.randn(1, input_size))
        model = torch.jit.freeze(model)
        # Models Run
        for _ in range(3):
            model(torch.randn(1, input_size))

    Type mismatch errors *in* an autocast-enabled region are a bug; if this is what you observe,
    please file an issue.

    ``autocast(enabled=False)`` subregions can be nested in autocast-enabled regions.
    Locally disabling autocast can be useful, for example, if you want to force a subregion
    to run in a particular ``dtype``.  Disabling autocast gives you explicit control over
    the execution type.  In the subregion, inputs from the surrounding region
    should be cast to ``dtype`` before use::

        # Creates some tensors in default dtype (here assumed to be float32)
        a_float32 = torch.rand((8, 8), device="cuda")
        b_float32 = torch.rand((8, 8), device="cuda")
        c_float32 = torch.rand((8, 8), device="cuda")
        d_float32 = torch.rand((8, 8), device="cuda")

        with torch.autocast(device_type="cuda"):
            e_float16 = torch.mm(a_float32, b_float32)
            with torch.autocast(device_type="cuda", enabled=False):
                # Calls e_float16.float() to ensure float32 execution
                # (necessary because e_float16 was created in an autocasted region)
                f_float32 = torch.mm(c_float32, e_float16.float())

            # No manual casts are required when re-entering the autocast-enabled region.
            # torch.mm again runs in float16 and produces float16 output, regardless of input types.
            g_float16 = torch.mm(d_float32, f_float32)

    The autocast state is thread-local.  If you want it enabled in a new thread, the context manager or decorator
    must be invoked in that thread.  This affects :class:`torch.nn.DataParallel` and
    :class:`torch.nn.parallel.DistributedDataParallel` when used with more than one GPU per process
    (see :ref:`Working with Multiple GPUs<amp-multigpu>`).

    Args:
        device_type(str, required):  Device type to use. Possible values are: 'cuda', 'cpu', 'mtia', 'xpu', and 'hpu'.
                                     The type is the same as the `type` attribute of a :class:`torch.device`.
                                     Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
        enabled(bool, optional):  Whether autocasting should be enabled in the region.
            Default: ``True``
        dtype(torch_dtype, optional):  Data type for ops run in autocast. It uses the default value
            (``torch.float16`` for CUDA and ``torch.bfloat16`` for CPU), given by
            :func:`~torch.get_autocast_dtype`, if :attr:`dtype` is ``None``.
            Default: ``None``
        cache_enabled(bool, optional):  Whether the weight cache inside autocast should be enabled.
            Default: ``True``
    NTr
   dtypeenabledcache_enabledc                 C   s&  t |tstdt| d|d u rt|}tj r.|| _|| _	|| _
|d us,J d S || _	t| j	s?td| j	 dtj | _t| j	| _
| j	| jkrdg}d| j d}|d7 }|d	7 }|d
7 }tt| jsrJ |tt| j| _|D ]}t| j|sJ |d| d q{t | _|rtjjj r| j	dkrtd d}|d ur|| _
|d ur|| _| j	dkrtjtjg}| j
|vr|rd}	|	d7 }	|	ddd |D d 7 }	t|	 d}n)| j	dkrtjtjg}| j
|vrd}	|	d7 }	t|	 d}n| j	dkr&tjtjg}| j
|vr%d}	|	d7 }	t|	 d}n| j	dkrFtjtjg}
| j
|
vrEd}	|	d7 }	t|	 d}n| j	d krftjtjg}| j
|vred!}	|	d"7 }	t|	 d}n| j	| jkr| j }| j
|vrd#| j d$}	|	d%| j d&7 }	|	dd'd |D d 7 }	t|	 d}np| j	dkr|r| j
tjkrtj std(nU| j	d)krtjtjg}| j
|vrd*}	t|	 d}n9| j
tjkrtj j!"d+d,sd-}	t|	 d}n| j	d.krtjtjg}| j
|vrd/}	|	d07 }	t|	 d}|| _d S )1N,Expected `device_type` of type `str`, got: ``z4User specified an unsupported autocast device_type ''get_amp_supported_dtypezTried to use AMP with the `z#` backend, but the backend has not zZregistered a module or  the module miss some necessary funcs. The backend should register zTa module by `torch._register_device_module`, and the module must have these funcs: 
z3`get_amp_supported_dtype() -> List[torch.dtype]`. 
zBut the func `z` is missing. 
cudazIUser provided device_type of 'cuda', but CUDA is not available. DisablingFcpuzLIn CPU autocast, but the target dtype is not supported. Disabling autocast.
z$CPU Autocast only supports dtype of z, c                 s       | ]}t |V  qd S r   str.0r   r   r   r   	<genexpr>      z$autocast.__init__.<locals>.<genexpr>z currently.mtiazMIn MTIA autocast, but the target dtype is not supported. Disabling autocast.
zQMTIA Autocast only supports dtypes of torch.bfloat16 and torch.float16 currently.xpuzLIn XPU autocast, but the target dtype is not supported. Disabling autocast.
zPXPU Autocast only supports dtypes of torch.bfloat16 and torch.float16 currently.ipuzLIn IPU autocast, but the target dtype is not supported. Disabling autocast.
zPIPU Autocast only supports dtypes of torch.bfloat16 and torch.float16 currently.hpuzLIn HPU autocast, but the target dtype is not supported. Disabling autocast.
zPHPU Autocast only supports dtypes of torch.bfloat16 and torch.float16 currently.zIn z2 autocast, but the target dtype is not supported. zDisabling autocast.
 z" Autocast only supports dtypes of c                 s   r&   r   r'   r)   r   r   r   r+   ?  r,   zNCurrent CUDA Device does not support bfloat16. Please switch dtype to float16.mpszIn MPS autocast, but the target dtype is not supported. Disabling autocast.
MPS Autocast only supports dtype of torch.bfloat16 and torch.float16 currently.   r   zuIn MPS autocast, but the target dtype torch.bfloat16 is not supported on macOS versions below 14. Disabling autocast.xlazLIn XLA autocast, but the target dtype is not supported. Disabling autocast.
z=XLA Autocast only supports dtype of torch.bfloat16 currently.)#
isinstancer(   
ValueErrortyper   get_autocast_dtype_jit_internalis_scripting_enableddevice
fast_dtyper   RuntimeErrorr   _get_privateuse1_backend_namecustom_backend_namehasattrgetattrcustom_device_modis_autocast_cache_enabled_cache_enabledr$   ampcommonamp_definitely_not_availablewarningswarnbfloat16float16joinr#   is_bf16_supportedbackendsr1   is_macos_or_newer)selfr
   r   r   r   necessary_funcsmessager   supported_dtypeerror_messagesupported_dtypesr   r   r   __init__   s  

















zautocast.__init__c                 C   s   t j r| jd usJ | S t  | _t | j| _t 	| j| _
t | j| j t | j| j t   t | j t j rht j }|D ]"}t|t jjjjrg| j| j| j| jf}|t jjd|  S qGd S d S )Nr   )r   r8   r9   r<   rC   prev_cache_enabledis_autocast_enabledr;   prevr7   prev_fastdtypeset_autocast_enabledr:   set_autocast_dtypeautocast_increment_nestingset_autocast_cache_enabledrD   r   _is_torch_function_mode_enabled	overrides _get_current_function_mode_stackr4   fxexperimentalproxy_tensorPreDispatchTorchFunctionMode__torch_function__rE   _enter_autocast)rP   stacksmoder   r   r   r   	__enter__h  s4   




zautocast.__enter__exc_typeexc_valexc_tbc                 C   s   t j rd S t  dkrt   t | j| j t | j| j	 t 
| j t j rJt j }|D ]}t|t jjjjrI|t jjdd  S q3dS )Nr   r   F)r   r8   r9   autocast_decrement_nestingclear_autocast_cacher[   r;   rY   r\   rZ   r^   rW   r   r_   r`   ra   r4   rb   rc   rd   re   rf   rE   _exit_autocast)rP   rk   rl   rm   rh   ri   r   r   r   __exit__  s"   



zautocast.__exit__c                 C   s   t j r|S t| |S r   )r   r8   r9   r   )rP   r   r   r   r   __call__  s   

zautocast.__call__)NTN)__name__
__module____qualname____doc__r(   r   r   boolrV   rj   r   rq   rr   r   r   r   r   r   2   s&     +
 r   c                  G   s<   t j rt jjt jjg g| R  S t jj|  }|  |S r   )	r   r   r_   r`   handle_torch_functionrE   rg   r   rj   )valsri   r   r   r   rg     s   
rg   c                 C   s0   t j rt jt jjg | S | d d d  d S r   )r   r   r_   r`   rx   rE   rp   rq   )ri   r   r   r   rp     s   
rp   r   c                    s   t | tjr|  o| jj ko| jtju}|r| S | S t | t	t
fr(| S tr2t | tjr2| S t | tjjrE fdd|  D S t | tjjre fdd| D }t | ttfrct| |S |S | S )Nc                    s&   i | ]\}}t | t | qS r   _cast)r*   kvr
   r   r   r   
<dictcomp>  s    z_cast.<locals>.<dictcomp>c                 3   s    | ]	}t | V  qd S r   rz   )r*   r}   r~   r   r   r+     s    z_cast.<locals>.<genexpr>)r4   r   Tensoris_floating_pointr;   r6   r   float64tor(   bytes	HAS_NUMPYnpndarraycollectionsabcMappingitemsIterablelisttuple)valuer
   r   is_eligibleiterabler   r~   r   r{     s*   

r{   )cast_inputsr   c                   sT   t tstdt ddu rtjt dS t fdd}|S )aa  
    Create a helper decorator for ``forward`` methods of custom autograd functions.

    Autograd functions are subclasses of :class:`torch.autograd.Function`.
    See the :ref:`example page<amp-custom-examples>` for more detail.

    Args:
        device_type(str):  Device type to use. 'cuda', 'cpu', 'mtia', 'xpu' and so on.
            The type is the same as the `type` attribute of a :class:`torch.device`.
            Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
        cast_inputs (:class:`torch.dtype` or None, optional, default=None):  If not ``None``,
            when ``forward`` runs in an autocast-enabled region, casts incoming
            floating-point Tensors to the target dtype (non-floating-point Tensors are not affected),
            then executes ``forward`` with autocast disabled.
            If ``None``, ``forward``'s internal ops execute with the current autocast state.

    .. note::
        If the decorated ``forward`` is called outside an autocast-enabled region,
        :func:`custom_fwd<custom_fwd>` is a no-op and ``cast_inputs`` has no effect.
    r    r!   N)r
   r   c                     s   t | d _ d u rt | d _| i |S t }d| d _|rNtdd t|  i t| W  d    S 1 sGw   Y  d S | i |S )Nr   F)r
   r   )r   r7   r   rX   _fwd_used_autocastr   r{   )r   r   autocast_contextr   r
   fwdr   r   decorate_fwd  s   



$z custom_fwd.<locals>.decorate_fwd)r4   r(   r5   r6   r   partialr   r   )r   r
   r   r   r   r   r   r     s   
r   c                   sP   t tstdt d du rtjtdS t  fdd}|S )aG  Create a helper decorator for backward methods of custom autograd functions.

    Autograd functions are subclasses of :class:`torch.autograd.Function`.
    Ensures that ``backward`` executes with the same autocast state as ``forward``.
    See the :ref:`example page<amp-custom-examples>` for more detail.

    Args:
        device_type(str):  Device type to use. 'cuda', 'cpu', 'mtia', 'xpu' and so on.
            The type is the same as the `type` attribute of a :class:`torch.device`.
            Thus, you may obtain the device type of a tensor using `Tensor.device.type`.
    r    r!   Nr   c                     sL   t | d j| d jd  | i |W  d    S 1 sw   Y  d S )Nr   )r
   r   r   )r   r   r   r   bwdr
   r   r   decorate_bwd%  s   $z custom_bwd.<locals>.decorate_bwd)r4   r(   r5   r6   r   r   r	   r   )r   r
   r   r   r   r   r	     s   
r	   r   )r   r   rH   typingr   r   r   torch.typesr   numpyr   r   ModuleNotFoundError__all__r(   rw   r   r   r   rg   rp   r{   r   r	   r   r   r   r   <module>   s>   	
  x
;