L ibddlZddlZddlZddlmZmZddlZddlmZ ddl Z dZ gdZ dedefd Zd ZGd d Zd ZdZdedefdZ ddddedeefdZddefdZy#e $rdZ dZ YJwxYw)N)AnyOptional)_dtypeTF)autocast_decoratorautocastis_autocast_available custom_fwd custom_bwd device_typereturnc@tjj|S)a 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', 'maia', '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_availabler s ]/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/torch/amp/autocast_mode.pyrrs 88 * *; 77cTtjfd}d|_|S)NcD5|i|cdddS#1swYyxYwN)argskwargsautocast_instancefuncs rdecorate_autocastz-autocast_decorator..decorate_autocast)s(  )(( ) ) )sz5@autocast() decorator is not supported in script mode) functoolswraps__script_unsupported)rrrs`` rrr(s4__T)) @* rc \eZdZdZ ddedeededeefdZdZ d e d e d e fd Z d Z y)ra 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` 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` 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`). Args: device_type(str, required): Device type to use. Possible values are: 'cuda', 'cpu', 'mtia', 'maia', '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`` Nr dtypeenabled cache_enabledc t|tstdt|d|t j |}tj jr||_||_ ||_ |Jy||_ t|jstd|jdtjj|_t j |j|_ |j|jk(rdg}d|jd}|dz }|d z }|d z }t!t|jsJ|t#t|j|_|D]&}t!|j$|rJ|d |d zt j&|_|rX|jd k(rItj*j,j.j1rt3j4dd}|||_ |||_|jdk(rvtj6tj8g}|j|vre|rbd} | dz } | dj;d|Ddzz } t3j4| d}||_y|jdk(rUtj6tj8g}|j|vrd} | dz } t3j4| d}||_y|jdk(rUtj6tj8g}|j|vr|d} | dz } t3j4| d}||_y|jdk(rUtj6tj8g}|j|vrd} | dz } t3j4| d}||_y|jdk(rUtj6tj8g} |j| vrd } | d!z } t3j4| d}||_y|jd"k(rUtj6tj8g}|j|vrPd#} | d$z } t3j4| d}||_y|j|jk(r|j$j=}|j|vrd%|jd&|jd'} | d(|jd)z } | dj;d*|Ddzz } t3j4| d}||_y|jd k(rK|ri|jtj6k(rKtj*j?s,td+|jd,k(rtj6tj8g}|j|vr!d-} t3j4| d}||_y|jtj6k(rtj@jBjEd.d/s|d0} t3j4| d}||_y|jd1k(rLtj8tj6g}|j|vrd2} | d3z } t3j4| d}||_y)4N,Expected `device_type` of type `str`, got: ``z4User specified an unsupported autocast device_type ''get_amp_supported_dtypezTried 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]`. zBut the func `z` is missing. cudazIUser provided device_type of 'cuda', but CUDA is not available. DisablingFcpuzLIn CPU autocast, but the target dtype is not supported. Disabling autocast. z$CPU Autocast only supports dtype of z, c32K|]}t|ywrstr.0r!s r z$autocast.__init__..FUc%jFz 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.maiazMIn MAIA autocast, but the target dtype is not supported. Disabling autocast. zQMAIA 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.zIn z autocast, but the target dtype z is not supported. zDisabling autocast. z" Autocast only supports dtypes of c32K|]}t|ywrr,r.s rr0z$autocast.__init__..Jr1r2zNCurrent 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.rzuIn 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- ValueErrortyperget_autocast_dtype _jit_internal is_scripting_enableddevice fast_dtyper RuntimeErrorr_get_privateuse1_backend_namecustom_backend_namehasattrgetattrcustom_device_modis_autocast_cache_enabled_cache_enabledr)ampcommonamp_definitely_not_availablewarningswarnbfloat16float16joinr(is_bf16_supportedbackendsr9is_macos_or_newer) selfr r!r"r#necessary_funcsmessagersupported_dtype error_messagesupported_dtypess r__init__zautocast.__init__s8+s+>tK?P>QQRS  =,,[9E    + + -#DM%DK#DO$ $$ ! $T[[1Ft{{mSTU $)88#I#I#K 224;;? ;;$22 2)O4D4L4L3MMpqG s sG n nG M MG5$":":; DW D;%,UD4L4L%MD "' t55t<tf4DEE<  $==?  v% %%BBD MM[ G  #DO  $"/D  ;;% $~~u}}=Oo5' o !GG IIFoFFV  m,b  a[[F "$~~u}}=Oo5 p !tt  m,T  S[[F "$~~u}}=Oo5 p !tt  m,F  E[[E !$~~u}}=Oo5 o !ss  m,x  w[[E ! % > &66 o !ss  m,j  i[[E !$~~u}}=Oo5 o !ss  m,\  [[[D44 4"44LLNOo5"%d&>&>%??_`d`o`o_pqD!E #9$:R:R9SSu!vv IIFoFFV  m,H  G[[F "OOu~~5 446"d[[E !$~~u}}=Oo5f m,$  #ENN2~~));;BBJ"MM-0#G  [[E !$}}enn=Oo5 o S  m, rctjjr|jJ|Stj|_tj |j|_tj|j|_ tj|j|jtj|j|jtjtj|j tj"j%rtj&j)}|D]}t+|tj,j.j0j2s<|j|j|j|j f}|j5tj6j8d||cS|S)Nr)rr@rArDrKprev_cache_enabledis_autocast_enabledrCprevr?prev_fastdtypeset_autocast_enabledrBset_autocast_dtypeautocast_increment_nestingset_autocast_cache_enabledrLr_is_torch_function_mode_enabled overrides _get_current_function_mode_stackr<fx experimental proxy_tensorPreDispatchTorchFunctionMode__torch_function__rM_enter_autocast)rXstacksmoders r __enter__zautocast.__enter__ss_    + + -??. ..K"'"A"A"C--dkk: #66t{{C ""4;; >   doo> ((* (()<)<= 88 3 3 5__EEGF HH))66SS   ++ D ++EII,E,Er4PK  rexc_typeexc_valexc_tbctjjrytjdk(rtjtj |j |jtj|j |jtj|jtjjrtjj}|D]g}t!|tj"j$j&j(s<|j+tj,j.ddyy)NrrF)rr@rAautocast_decrement_nestingclear_autocast_cacherdrCrbrercrgr`rrhrirjr<rkrlrmrnrorM_exit_autocast)rXrtrurvrqrrs r__exit__zautocast.__exit__s    + + -   + + - 2  & & ( ""4;; :   d.A.AB (()@)@A 88 3 3 5__EEGF !HH))66SS++EII,D,Db"M! !rcZtjjr|St||Sr)rr@rAr)rXrs r__call__zautocast.__call__s&    + + -K!$--r)NTN) __name__ __module__ __qualname____doc__r-rrboolr^rsrr{r}rrrrr4ssgX#'(, S S S  S  ~ S j DsC6.rrc tjjr9tjjtj j gg|Stj j|}|j|Sr) rrrhrihandle_torch_functionrMrprrs)valsrrs rrprpse xx//144 II % %r ,0   99  t $DNN Krctjjr9tjj tj j g|S|jdddyr)rrrhrirrMrzr{)rrs rrzrzsF xx//144UYY5M5MrSWXXMM$d#rr!c t|tjr^|jxr7|jj k(xr|j tju}|r|jS|St|ttfr|Strt|tjr|St|tjj r:|j#Dcic]\}}t%|t%| c}}St|tjj&r5fd|D}t|t(t*frt ||S|S|Scc}}w)Nc38K|]}t|ywr)_cast)r/vr r!s rr0z_cast..s@QE![%0@s)r<rTensoris_floating_pointrCr>r!float64tor-bytes HAS_NUMPYnpndarray collectionsabcMappingitemsrIterablelisttuple)valuer r! is_eligiblekriterables `` rrrs-%&  # # % 3 !![0 3EMM1  #.uxx858 EC< ( z%4 E;??22 3  1 ![% (%;*F F   E;??33 4@%@ edE] +4;x( (O  s,#E.) cast_inputsrcttstdtdt j t St jfd}|S)ai 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` for more detail. Args: device_type(str): Device type to use. 'cuda', 'cpu', 'mtia', 'maia', '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` is a no-op and ``cast_inputs`` has no effect. r%r&)r rc `tj|d_%tj|d_|i|Stj}d|d_|r5t d5t |it |cdddS|i|S#1swYyxYw)NrF)r r")rr?rra_fwd_used_autocastrr)rrautocast_contextrr fwds r decorate_fwdz custom_fwd..decorate_fwd s11+>Q  ).)B)B;)ODG &'' '$88E ).DG &+uEt[+> [A D+F++ s 4B$$B-)r<r-r=r>rpartialr r)rr rrs``` rr r st4 k3 ':4 ;L:MQ O   {  K[  __S,," rcttstdtdt j t St jfd}|S)aOCreate 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` for more detail. Args: device_type(str): Device type to use. 'cuda', 'cpu', 'mtia', 'maia', '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&rct|dj|dj5|i|cdddS#1swYyxYw)Nr)r r"r!)rrr)rrbwdr s r decorate_bwdz custom_bwd..decorate_bwd6sJ #G..q'..  ( ''  ( ( (s <A)r<r-r=r>rrr r)rr rs`` rr r "sk k3 ':4 ;L:MQ O   {  EE__S(( rr)rrrPtypingrrr torch.typesrnumpyrrModuleNotFoundError__all__r-rrrrrprzrr r rrrrs I   8s 8t 8 ..J $c&8 5%) 55&! 5vgI BsA%% A10A1