L i  UddlZddlZddlZddlZddlZddlmZddlddlZddlm Z ddl Z ddl m cm ZddlmZddlmZmZddlmZgdZd Zdaeeed <ej8d eefd Zd eedfdee j@dffdZ!d e"eddfdZ#dSdZ$GddZ%dZ&dee'e(e'e j@ffdZ)dddTdZ*dSdZ+Gdde jXjZZ.dZ/e j`de/edddd eed!e1gee2e2ffd"e3d#ed$ef d%Z4dUd&Z5d'Z6da7eeed(<ej8d)efd*Z8Gd+d,Z9Gd-d.Z:Gd/d0e jXjZZ;Gd1d2ZGd5d6e?Z@dee1gefe1e@gdfffd7ZAd8e j@deBe3effd9ZCeeCd:d;iZDeBe3e1e j@geffed<<Gd=d>eEZFGd?d@e jXjjZIe j`dAZJGdBdCe jXjjZKdDZLGdEdFZMdGZNGdHdIZOGdJdKejZQdLZRe jjjje jjjjheYe jjjjzZ^GdMdNeZ_GdOdPeZ`dVdQZade/eddfd!e1gee2e2ffd"e3d#ed$efdRZby)WN) defaultdict)*) ReferenceType)tree_map) capture_logsLoggingTensorMode)TorchDispatchMode) checkpointcheckpoint_sequentialCheckpointErrorCheckpointFunctioncheck_backward_validitydetach_variableget_device_statesset_device_statesnoop_context_fnset_checkpoint_early_stopDefaultDeviceTypeset_checkpoint_debug_enabledCheckpointPolicySelectiveCheckpointContext$create_selective_checkpoint_contextsSAC_IGNORED_OPSdefault_checkpoint_debug_enabledenabledc#8K t}|ad|ay#awxYww)a Context manager that sets whether checkpoint should print additional debug information when running. See the ``debug`` flag for :func:`~torch.utils.checkpoint.checkpoint` for more information. Note that when set, this context manager overrides the value of ``debug`` passed to checkpoint. To defer to the local setting, pass ``None`` to this context. Args: enabled (bool): Whether checkpoint should print debug information. Default is 'None'. N)r)rprevs \/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/torch/utils/checkpoint.pyrr*s%)($+! $(!D! inputs.returncDt|trrg}|D]`}t|tjs|j |/|j }|j |_|j |bt|Stdt|j)Nz@Only tuple of tensors is supported. Got Unsupported input type: ) isinstancetupletorchTensorappenddetach requires_grad RuntimeErrortype__name__)r!outinpxs rrr@s&%  Cc5<<0 3 A!//AO JJqM Sz N L ! !  cTtd|Dstjdyy)Nc3jK|]+}t|tjs|j-ywN)r$r&r'r*.0r/s r z*check_backward_validity..Ts#TSjell6Ss  Ts33zBNone of the inputs have requires_grad=True. Gradients will be None)anywarningswarn)r!s rrrSs% TFT T P  Ur1cZ|dk(rtjdStt|}|S)Nmeta)r&devicegetattr)r= device_modules r_get_device_moduler@Zs+ ||F##E6*M r1cBeZdZdZdZeddefdZedefdZy) raA A class that manages the default device type for checkpointing. If no non-CPU tensors are present, the default device type will be used. The default value is 'cuda'. The device type is used in the checkpointing process when determining which device states to save and restore for recomputation. cudar=c|t_y)z Set the default device type for checkpointing. Args: device (str): The device type to be set as default. Default is 'cuda'. Nr_default_device_type)r=s rset_device_typez!DefaultDeviceType.set_device_typems 28.r1r"c"tjS)z Get the current default device type for checkpointing. Returns: str: The current default device type. rDr1rget_device_typez!DefaultDeviceType.get_device_typews!555r1NrB) r- __module__ __qualname____doc__rE staticmethodstrrFrIrHr1rrrasC"8886S66r1rcgfd}t||t}t|dkDr'tjdt |ddtdk(rt jSd|vrydS)Nct|tjr@|jjdk(s&j |jjyyy)Ncpu)r$r&r'r=r,r()arg device_typess radd_device_typesz,_infer_device_type..add_device_typess? c5<< (E1I     02J (r1aTensor arguments, excluding CPU tensors, are detected on at least two types of devices. Device state will only be saved for devices of a single device type, and the remaining devices will be ignored. Consequently, if any checkpointed functions involve randomness, this may result in incorrect gradients. (Note that if CUDA devices are among the devices detected, it will be prioritized; otherwise, the first device encountered will be selected.) Device types: z first device type: rrB)rsetlenr9r:sortedrrI)argsrUdevice_types_setrTs @r_infer_device_typer\sL1 t$<( q    &&6788L\Z[_L]  _  <A 0022 # #Ar1cgfd}t||g}tt|}D];}|j|5|j |j ddd=|fS#1swYKxYw)Nct|tjr9|jjdvr j |j yyy)N>rRr<)r$r&r'r=r,r( get_device)rSfwd_device_idss radd_device_idsz)get_device_states..add_device_idss> c5<< (SZZ__O-S  ! !#.."2 3.T (r1)rr@r\r=r( get_rng_state)rZrafwd_device_statesr? device_idr`s @rrrsN4 ^T"&'94'@AM#D  ! !) , D  $ $]%@%@%B C D DD , ,, D Ds A,,A5  device_typec|tj}|dk(ryt|}t||D]0\}}|j |5|j |ddd2y#1swY=xYw)aSets random number generator states for the specified devices. Args: devices: Device ids to set states for. states: States to set. device_type: ``device_type`` of the devices to set states for. Default is the device returned by a call to ``DefaultDeviceType.get_device_type()``, which is ``cuda`` if not changed by calling ``DefaultDeviceType::set_device_type()``. Nr<)rrIr@zipr= set_rng_state)devicesstatesrfr?r=states rrrs}'779 f&{3MWf-/   ! !& ) /  ' ' . / // / /s A((A1 cFtjj|r?tj|tj|tj d}nd}tjdtjdtj d}||fS)N)rdtype cache_enabledrR)r&ampis_autocast_availableis_autocast_enabledget_autocast_dtypeis_autocast_cache_enabled)rfdevice_autocast_kwargscpu_autocast_kwargss r_get_autocast_kwargsrws yy&&{300=--k:"<<>"  "&,,U3))%088: "#6 66r1c,eZdZedZedZy)r ct|||_||_t||_t |j\|_|_|r^tj|_ d|_ t|j}t|ddrd|_ t|\|_|_g|_g|_g}t'|D]}\}}tj(|rH|j+||j$j+||j"j+dc|j"j+||j,|tj.5||}ddd|S#1swYSxYw)NF _initializedT)r run_functionpreserve_rng_stater\rfrwrurvr&rb fwd_cpu_statehad_device_in_fwdr@r>r fwd_devicesrcr!tensor_indices enumerate is_tensorr(save_for_backwardno_grad) ctxr{r|rZr? tensor_inputsirSoutputss rforwardzCheckpointFunction.forwardsV%'!3,d3>R OO? ;"C$;  % 3 3 5C  %*C !.s?M}ne<(,%9JD9Q6!6  o 'FAss#$$S)""))!, !!$' !!#&  ' }- ]]_ *"D)G * *s 'E77Fc ntjjs tdt |j }|j }|j}t|D] \}}||||<g}|jr|jr |j}tjj||j|j5|jrWtj|j |jr,t#|j|j$|jt't)|}tj*j-|jr5tj*j.d d|ji|j0nt3j4} tj65| 5tj*j.d i|j85|j:|} ddddddddddddt= tj>r| f} g} g} tAtC| D]S}tjD| |s| |jFs,| jI| || jI||UtC| dk(r tdtjjK| | t)dD} d| zS#1swYxYw#1swYxYw#1swYxYw#1swY xYw) NzWhen use_reentrant=True, torch.utils.checkpoint is incompatible with .grad() or passing an `inputs` parameter to .backward(). To resolve this error, you can either set use_reentrant=False, or call .backward() without passing the `inputs` argument.rjrrfrerfrzInone of output has requires_grad=True, this checkpoint() is not necessaryc3lK|],}t|tjr |jnd.ywr4)r$r&r'gradr5s rr7z.CheckpointFunction.backward..@s. #3 5CHH4 ? s24)NNrHrR)&r&autograd_is_checkpoint_validr+listr!r saved_tensorsrr|r~rrandomfork_rngrfrir}rrcrr%rprqautocastru contextlib nullcontext enable_gradrvr{r$r'rangerXrr*r(backward)rrZr!rtensorsridx rng_devicesdetached_inputsdevice_autocast_ctxroutputs_with_gradargs_with_gradgradss rrzCheckpointFunction.backward s~~224N cjj!++## / %FAs!!*F3K %   ! !c&;&;//K \\ " ")?)?S__# =%%##C$5$56((%coos7L7LZ]ZiZij-eFmB &   e##1 = = = = = = = =sUC>L* L*L9L LLL*L LL LL' "L**L4N)r-rKrLrNrrrHr1rr r s)&&P;$;$r1r cRtjtjfSr4)rrrHr1rrrHs  ! ! #Z%;%;%= ==r1FT) use_reentrant context_fndeterminism_checkdebug early_stoprrrrrc|tjddd}|jdd}|r&|r$tddj d |Dz|r.|t us|d ur td t j||g|St||||||g|i|} t| ||i|} t| y#t$r| cYSwxYw) aCheckpoint a model or part of the model. Activation checkpointing is a technique that trades compute for memory. Instead of keeping tensors needed for backward alive until they are used in gradient computation during backward, forward computation in checkpointed regions omits saving tensors for backward and recomputes them during the backward pass. Activation checkpointing can be applied to any part of a model. There are currently two checkpointing implementations available, determined by the :attr:`use_reentrant` parameter. It is recommended that you use ``use_reentrant=False``. Please refer the note below for a discussion of their differences. .. warning:: If the :attr:`function` invocation during the backward pass differs from the forward pass, e.g., due to a global variable, the checkpointed version may not be equivalent, potentially causing an error being raised or leading to silently incorrect gradients. .. warning:: The ``use_reentrant`` parameter should be passed explicitly. In version 2.9 we will raise an exception if ``use_reentrant`` is not passed. If you are using the ``use_reentrant=True`` variant, please refer to the note below for important considerations and potential limitations. .. note:: The reentrant variant of checkpoint (``use_reentrant=True``) and the non-reentrant variant of checkpoint (``use_reentrant=False``) differ in the following ways: * Non-reentrant checkpoint stops recomputation as soon as all needed intermediate activations have been recomputed. This feature is enabled by default, but can be disabled with :func:`set_checkpoint_early_stop`. Reentrant checkpoint always recomputes :attr:`function` in its entirety during the backward pass. * The reentrant variant does not record the autograd graph during the forward pass, as it runs with the forward pass under :func:`torch.no_grad`. The non-reentrant version does record the autograd graph, allowing one to perform backward on the graph within checkpointed regions. * The reentrant checkpoint only supports the :func:`torch.autograd.backward` API for the backward pass without its `inputs` argument, while the non-reentrant version supports all ways of performing the backward pass. * At least one input and output must have ``requires_grad=True`` for the reentrant variant. If this condition is unmet, the checkpointed part of the model will not have gradients. The non-reentrant version does not have this requirement. * The reentrant version does not consider tensors in nested structures (e.g., custom objects, lists, dicts, etc) as participating in autograd, while the non-reentrant version does. * The reentrant checkpoint does not support checkpointed regions with detached tensors from the computational graph, whereas the non-reentrant version does. For the reentrant variant, if the checkpointed segment contains tensors detached using ``detach()`` or with :func:`torch.no_grad`, the backward pass will raise an error. This is because ``checkpoint`` makes all the outputs require gradients and this causes issues when a tensor is defined to have no gradient in the model. To avoid this, detach the tensors outside of the ``checkpoint`` function. Args: function: describes what to run in the forward pass of the model or part of the model. It should also know how to handle the inputs passed as the tuple. For example, in LSTM, if user passes ``(activation, hidden)``, :attr:`function` should correctly use the first input as ``activation`` and the second input as ``hidden`` args: tuple containing inputs to the :attr:`function` Keyword args: preserve_rng_state(bool, optional): Omit stashing and restoring the RNG state during each checkpoint. Note that under torch.compile, this flag doesn't take effect and we always preserve RNG state. Default: ``True`` use_reentrant(bool): specify whether to use the activation checkpoint variant that requires reentrant autograd. This parameter should be passed explicitly. In version 2.9 we will raise an exception if ``use_reentrant`` is not passed. If ``use_reentrant=False``, ``checkpoint`` will use an implementation that does not require reentrant autograd. This allows ``checkpoint`` to support additional functionality, such as working as expected with ``torch.autograd.grad`` and support for keyword arguments input into the checkpointed function. context_fn(Callable, optional): A callable returning a tuple of two context managers. The function and its recomputation will be run under the first and second context managers respectively. This argument is only supported if ``use_reentrant=False``. determinism_check(str, optional): A string specifying the determinism check to perform. By default it is set to ``"default"`` which compares the shapes, dtypes, and devices of the recomputed tensors against those the saved tensors. To turn off this check, specify ``"none"``. Currently these are the only two supported values. Please open an issue if you would like to see more determinism checks. This argument is only supported if ``use_reentrant=False``, if ``use_reentrant=True``, the determinism check is always disabled. debug(bool, optional): If ``True``, error messages will also include a trace of the operators ran during the original forward computation as well as the recomputation. This argument is only supported if ``use_reentrant=False``. early_stop(bool, optional): If ``True``, non-reentrant checkpoint stops recomputation as soon as it has computed all needed Tensors. This argument is ignored if ``use_reentrant=True``. Can be overridden globally using :func:`set_checkpoint_early_stop` context manager. Default: ``True``. Returns: Output of running :attr:`function` on :attr:`*args` Navtorch.utils.checkpoint: the use_reentrant parameter should be passed explicitly. Starting in PyTorch 2.9, calling checkpoint without use_reentrant will raise an exception. use_reentrant=False is recommended, but if you need to preserve the current default behavior, you can pass use_reentrant=True. Refer to docs for more details on the differences between the two variants.) stacklevelTr|Unexpected keyword arguments: ,c3 K|]}|ywr4rHr6rSs rr7zcheckpoint..7N7N FzKPassing `context_fn` or `debug` is only supported when use_reentrant=False.) r9r:pop ValueErrorjoinrr apply'_checkpoint_without_reentrant_generatornext StopIteration) functionrrrrrrZkwargspreservegenrets rr r VsB  C   zz.5H - ,sxx7Nv7N/N N   _ ,U0B' "''(BTBB5 h ,=uj SW [a  S ''  I J s. B:: CCc |tjdd}|jdd}|r$tddj d|Dzd}t |t jjrt|j}t||z}d}td ||d z z|D]!} | |zd z }t|| ||||| }#||d zt|d z ||S) a Checkpoint a sequential model to save memory. Sequential models execute a list of modules/functions in order (sequentially). Therefore, we can divide such a model in various segments and checkpoint each segment. All segments except the last will not store the intermediate activations. The inputs of each checkpointed segment will be saved for re-running the segment in the backward pass. .. warning:: The ``use_reentrant`` parameter should be passed explicitly. In version 2.9 we will raise an exception if ``use_reentrant`` is not passed. If you are using the ``use_reentrant=True` variant, please see :func:`~torch.utils.checkpoint.checkpoint` for the important considerations and limitations of this variant. It is recommended that you use ``use_reentrant=False``. .. warning: Since PyTorch 1.4, it allows only one Tensor as the input and intermediate outputs, just like :class:`torch.nn.Sequential`. Args: functions: A :class:`torch.nn.Sequential` or the list of modules or functions (comprising the model) to run sequentially. segments: Number of chunks to create in the model input: A Tensor that is input to :attr:`functions` preserve_rng_state(bool, optional): Omit stashing and restoring the RNG state during each checkpoint. Default: ``True`` use_reentrant(bool): specify whether to use the activation checkpoint variant that requires reentrant autograd. This parameter should be passed explicitly. In version 2.5 we will raise an exception if ``use_reentrant`` is not passed. If ``use_reentrant=False``, ``checkpoint`` will use an implementation that does not require reentrant autograd. This allows ``checkpoint`` to support additional functionality, such as working as expected with ``torch.autograd.grad`` and support for keyword arguments input into the checkpointed function. Returns: Output of running :attr:`functions` sequentially on :attr:`*inputs` Example: >>> # xdoctest: +SKIP("stub") >>> model = nn.Sequential(...) >>> input_var = checkpoint_sequential(model, chunks, input_var) a{torch.utils.checkpoint.checkpoint_sequential: the use_reentrant parameter should be passed explicitly. In version 2.9 we will raise an exception if use_reentrant is not passed. use_reentrant=False is recommended, but if you need to preserve the current default behavior, you can pass use_reentrant=True. Refer to docs for more details on the differences between the two variants.Tr|rrc3 K|]}|ywr4rHrs rr7z(checkpoint_sequential..?rrcfd}|S)NcFtdzD] }||}|SNrV)r)inputjend functionsstarts rrz.run_function..forwardCs25#'* ,$ ! U+ ,Lr1rH)rrrrs``` rr{z+checkpoint_sequential..run_functionBs  r1rrV)rr|)r9r:rrrr$r&nn SequentialrchildrenrXrr ) rsegmentsrrrrr{ segment_sizerrs rr r s`  C  zz.5H  ,sxx7Nv7N/N N  )UXX001++-. y>X-L Cq,(Q,7F l"Q& Y / ''    @<aY!!3Y ? FFr1c|s tdy)NzqSomething went unexpectedly wrong in activation checkpoint. Please report this bug by filing an issue to PyTorch.AssertionError)conds r_internal_assertr[s  D   r1_enable_checkpoint_early_stopenablec#8K t}|ad|ay#awxYww)a)Context manager that sets whether checkpoint should stop recomputation early. By default, non-reentrant checkpoint stops recomputation as soon as it has computed all needed Tensors. This context manager can be used to disable that feature if it is problematic for your specific application. This context manager only needs to be active when forward is run. It does not need to be active during backward. Example:: >>> # xdoctest: +SKIP(failing) >>> message = "saved tensors default hooks are disabled" >>> with set_checkpoint_early_stop(False): ... # Any checkpoint under this context manager will respect this ... # context manager, even if its backward is performed outside. ... out = checkpoint(fn, inputs) ... >>> out.backward() N)r)rrs rrrs%.-,(.% (,%%r c eZdZy)_HandleNr-rKrLrHr1rrrr1rceZdZdZy)_Holderci|_yr4)handlesselfs r__init__z_Holder.__init__ s 57 r1N)r-rKrLrrHr1rrr s8r1rc XeZdZedZededeedfdeddfdZed Zy) _NoopSaveInputsc,tjdS)Nr)r&empty)rZs rrz_NoopSaveInputs.forwards{{4  r1rr!.outputr"Nc  tt|Dcgc]$\}}t|tjs!||f&c}}\ }t Dcic]\}}|| c}} |Dcgc] }t|tjrdn|"c} fd}||_|j |ycc}}wcc}}wcc}w)NcltDcgc]\}}|vr||n|}}}|ddScc}}wr)r)rrorrZ idx2saved_idxrs rget_argsz/_NoopSaveInputs.setup_context..get_args!sR&dOAq453F mA./AMC qr7N s0)rhrr$r&r'rr) rr!rrrrabrrZrrs @@@r setup_contextz_NoopSaveInputs.setup_contexts#&!*6!2 RAjELL6Qq!f R# +4N*CD$!QAD DJKq 1ell3:K   w')SDKs"B1 B1  B7+%B=ctd)Nz(Did not expect to backward on this graphr)r grad_outputss rrz_NoopSaveInputs.backward1sGHHr1) r-rKrLrNrAnyTuplerrrHr1rrrsb!!(3(c3h((((4IIr1rceZdZdZdZy)_CheckpointFramec||_d|_g|_ttj |_tt|_tt|_ ||_ ||_ ||_ g|_d|_d|_yNF) recompute_fn input_saver weak_holdersrweakrefWeakKeyDictionary recomputedintrecomp_counterbool is_recomputedr metadata_fnunpack_error_cb x_metadatasforward_completedignore_saved_mismatch)rrrrrs rrz_CheckpointFrame.__init__7s(13 11 2  6A5E5@5F%'.!&%*"r1c $|jryt|j|j|k(s8t dt|jd|j|dt g}t |jD]\}}|}|t||jvt|j|dut|j||j|v|j|}|j||j|}||j|k7s|j|||j|ft|dkDr1d}|D]\}}} |d|d|d| d z }t d |dt y) Nztorch.utils.checkpoint: A different number of tensors was saved during the original forward and recomputation. Number of tensors saved during forward: z/ Number of tensors saved during recomputation: z. rztensor at position z: saved metadata: z recomputed metadata:  zztorch.utils.checkpoint: Recomputed values for the following tensors have different metadata than during the forward pass. ) rrXrrr _debug_tip_msgrrrrrrr() rgidnb_meta_differentr weak_holderholderx_meta recomputed_xmismatched_tensorsrecomputed_metas rcheck_recomputed_tensors_matchz/_CheckpointFrame.check_recomputed_tensors_matchPs  % % 4$$%)<)t?P?P;Q:RSAAEATATUXAY@ZZ]!" $  )$*;*; < X C ]F~ SFNN2 3 V^^C0< = V^^C0DOOC4HH I%%c*F??3/s0CDL)),77!((#vt7G7G 7U)VW% X(  !A %!# 0A ,V_")#/''-h/,,;+.CaptureLogsc d|_d|_yr4)logstbsrs rrz7_get_debug_context_and_cb..CaptureLogs.__init__sDIDHr1cFtjfd}|S)Nc3Kt5tddd5}|\__|ddddddy#1swYxYw#1swYyxYww)NT) python_tb script_tbcpp_tb)rrrr) logs_and_tbr rs r logging_modezX_get_debug_context_and_cb..CaptureLogs.get_context_manager..logging_modes[&(&!$$$vV&Ze*5'DItx%%&&&&&&s1 AAAA AA AAA)rcontextmanager)rr"r s` rget_context_managerzB_get_debug_context_and_cb..CaptureLogs.get_context_managers%  & & &' &  > !r1N)r-rKrLrr$)r sr CaptureLogsrs   "r1r%ec d}jJjJttj|d|ddj jdj j|)Nc 2d}t|j}tt|j|jD]S\}\}}||d|dzd|d|dz }d}|D]+}|dd k(} |s| s| rd }||d d |d d |ddz }-|dz }U|S)Nrz (rVz of z in z) Fname__torch_dispatch__Tfilename:linerz )rXrrrhr) labelrr. total_lenrlogtbfound_torch_dispatchr-is_torch_dispatchs r get_str_tbzF_get_debug_context_and_cb..unpack_error_cb..get_str_tbsCL--.I )#l.?.?AQAQ*R S  9C#d1q5'i[UG5II',$QD(,V 8L(L%/8I */3, d:./qfaV ~RPPCQv  Jr1original recomputer)forward_tracesrecompute_traces forward_ops recompute_ops)rr _checkpoint_error_templateformatr)r&r4capture_logs_fwdcapture_logs_recomputes rrz2_get_debug_context_and_cb..unpack_error_cbs " $$000%**666 & - -)*6FG!+K9O!P II&6&;&;<"ii(>(C(CD .   r1cDjjfSr4)r$)r=r>srrz-_get_debug_context_and_cb..context_fns!3357M7a7a7cccr1)platformmachinesystemr )r%rrr=r>r s @@@r_get_debug_context_and_cbrCsd    8 + L0AW0LF " "#}(]?:d  &&r1r0cJ|j|j|jdS)Nshapernr=rEr0s r_default_meta_extractorrHs#(( r1nonecyr4rH)_s rrL$sr1"_allowed_determinism_checks_to_fnsc eZdZy)_StopRecomputationErrorNrrHr1rrOrO(rr1rOc(eZdZdedeffd ZxZS)_recomputation_hooktarget_frame_refr c<fd}d}t|||y)Nc|jr|jn|}}|J|j}|jxxdz cc<|t|jk\r5|j rJ|j s d|_|Stdt|j|}|]t|jjddut|j<||j|j<|j r+|jt|jk(rt|S)NrVTzptorch.utils.checkpoint: trying to save more tensors during recomputation than during the original forward pass. )r*r)rrXrrrrr r rrgetrrrO)r0 target_frame recomp_idxr r rRs r pack_hookz/_recomputation_hook.__init__..pack_hook.sLoo 1A+-L+ ++%44S9J  ' ' , 1 ,S!:!:;;'2222#55 :>L6H%M%&( ;\..z:$!FG&-is#DE '',V^^C-@A&&<+F+Fs+Ks))P,.-Hr1c|Sr4rHrGs r unpack_hookz1_recomputation_hook.__init__..unpack_hookUs Hr1)superr)rrRr rXrZ __class__s `` rrz_recomputation_hook.__init__-s% N  K0r1)r-rKrLrrr __classcell__r\s@rrQrQ,s-1-1S-1-1r1rQc||i|Sr4rH)fnrZrs r_run_fn_with_dynamo_disabledrabs t v r1ceZdZfdZxZS)_checkpoint_hookcfd}fdjfd}t| ||yt| |y)Nc<t}jjtj|j It j5jjj |ddd|S|S#1swY|SxYwr4) rrr(rrefrr&rr)r0r frames rrXz,_checkpoint_hook.__init__..pack_hookis|YF    % %gkk&&9 :  ,]]_C%%,,U->->q-ABCM6MCMs +BBcntjj}|dk(rtt j }j |sjj}|j|j} ttj|5tjj5t!j"g|dddddddj |<j'|t)||j*v|j*| t-dt)|j*|j.|vj.||j*|}d|j*|<|S#1swYxYw#1swYxYw#t$$rYwxYw)NrTztorch.utils.checkpoint: Unpack is being triggered for a tensor that was already unpacked once. If you are calling ctx.saved_tensors in backward, make sure to do so only once. Otherwise please open an issue with details on your use case.)r&_C_current_graph_task_idruuiduuid4rrgrad_fnrrrQrrfrrrarrOrrrr r)r r rrZrrgs rrZz._checkpoint_hook.__init__..unpack_hookss((113Cby$**,'&&s+''//||C$5$56, E*CP~~113P5U5G5GO$O PP,0##C(44S9 SFNN2 3~~c"*%b V^^C0E4D4DS4II J""3's(;.unpack_hook_with_error_cbs4-&v..&-))!,,-s /*/)rr[r)rrgrXrorZr\s ` @rrz_checkpoint_hook.__init__hsB  D  , - G Y(A B G Y 4r1)r-rKrLrr]r^s@rrcrcgs 5555r1rcctjjtjjjduSr4)r&ri_get_dispatch_mode_TorchDispatchModeKey FUNCTIONAL)funcrZrs r _is_compilingrus/ 88 & &uxx'E'E'P'P QY] ]]r1ceZdZdZdZy)_VersionWrappercx||_t|tjr|j|_yd|_yr4)valr$r&r'_versionversion)rrys rrz_VersionWrapper.__init__s(-06@ell6Scll Y] r1c|j0|s.|jj|jk7r td|jS)NzETensor cached during selective activation checkpoint has been mutated)r{ryrzr+)rallow_cache_entry_mutations rget_valz_VersionWrapper.get_vals@ << #,Fxx  DLL0"[xxr1N)r-rKrLrr~rHr1rrwrws ^r1rwcRt|tjr|js|j s|r]tj j tj jjd5|j}ddd|S|S#1swY|SxYwr) r$r&r'is_floating_point is_complexri_SetExcludeDispatchKeyGuard DispatchKeyADInplaceOrViewr)r0any_ret_has_alias_infos r _maybe_detachrs|!U\\"(;(;(=Si XX 1 1%((2F2F2V2VX] ^   A   H1H  Hs ?BB&ceZdZdZdZy)ra Context passed to policy function during selective checkpointing. This class is used to pass relevant metadata to the policy function during selective checkpointing. The metadata includes whether the current invocation of the policy function is during recomputation or not. Example: >>> # xdoctest: +SKIP(stub) >>> >>> def policy_fn(ctx, op, *args, **kwargs): >>> print(ctx.is_recompute) >>> >>> context_fn = functools.partial(create_selective_checkpoint_contexts, policy_fn) >>> >>> out = torch.utils.checkpoint.checkpoint( >>> fn, x, y, >>> use_reentrant=False, >>> context_fn=context_fn, >>> ) c||_yr4 is_recompute)rrs rrz#SelectiveCheckpointContext.__init__s (r1N)r-rKrLrMrrHr1rrrs *)r1rc eZdZdZdZdZdZdZy)ra Enum for specifying the policy for checkpointing during backpropagation. The following policies are supported: - ``{MUST,PREFER}_SAVE``: The operation's output will be saved during the forward pass and will not be recomputed during the backward pass - ``{MUST,PREFER}_RECOMPUTE``: The operation's output will not be saved during the forward pass and will be recomputed during the backward pass Use ``MUST_*`` over ``PREFER_*`` to indicate that the policy should not be overridden by other subsystems like `torch.compile`. .. note:: A policy function that always returns ``PREFER_RECOMPUTE`` is equivalent to vanilla checkpointing. A policy function that returns ``PREFER_SAVE`` every op is NOT equivalent to not using checkpointing. Using such a policy would save additional tensors not limited to ones that are actually needed for gradient computation. rrVrN)r-rKrLrM MUST_SAVE PREFER_SAVEMUST_RECOMPUTEPREFER_RECOMPUTErHr1rrrs,IKNr1rcF|rtjStjSr4rrr)rs r_policy_from_boolrs)*  % %Q0@0Q0QQr1ceZdZdZddZy)_CachingTorchDispatchModec ||_||_yr4) policy_fnstorage)rrrs rrz"_CachingTorchDispatchMode.__init__s" r1Nc8|tvr||i|S|in|}|jtd|g|i|}t|tr t |}t |||}|r|tjd<||i|}t|tjjrdn&td|jjD|tj tj"fvs|r+|j$|j't)fd||S)NFrr6c38K|]}|jduywr4) alias_info)r6rs rr7z?_CachingTorchDispatchMode.__torch_dispatch__..-s(dt)C(dsc.tt|Sr4)rwrrs rrLz>_CachingTorchDispatchMode.__torch_dispatch__..0sWXZpIq9rr1)rrrr$rrru fx_traceback current_metar&_opsHigherOrderOperatorr8_schemareturnsrrrrr(r) rrttypesrZrpolicy is_compilingr.rs @rr*z,_CachingTorchDispatchMode.__torch_dispatch__s ? "(( (~6 : N $7'+7/57 fd #&v.F$T48 5;L % %k 2D#F# dEJJ:: ;%* "%((dt||OcOc(d%d " &002B2N2NO OS_ LL  % %h/rtw&x y r1rHNr-rKrLrr*rHr1rrrs r1rceZdZdZddZy)_CachedTorchDispatchModec.||_||_||_yr4)rrr})rrrr}s rrz!_CachedTorchDispatchMode.__init__5s" *D'r1Nc|tvr||i|S|in|}jtd|g|i|}t|tr t |}t |||}|tjtjfvs|rdjj|}|t|dt|dk(r tdtfd|jd}|S||i|}|S)NTrz6 encountered during backward, but not found in storagerzTrying to backward an extra time. You are only allowed to backward once on any region computed under selective activation checkpoint.c:|jjSr4)r~r})r0rs rrLz=_CachedTorchDispatchMode.__torch_dispatch__..OsQYYt/N/N%Or1)rrrr$rrrurrrrrUr+rXrr) rrtrrZrrrrr.s ` rr*z+_CachedTorchDispatchMode.__torch_dispatch__:s ? "(( (~6 : M $7'+7/57 fd #&v.F$T48 &002B2N2NO OS_ll&&t,G"dV+a#bcc7|q "TOQXQ\Q\]^Q_`C ''C r1rrrHr1rrr3s E r1rc ttrD]}t|tjjtjj frBt|tjj rdnd}td|dt|d|fd}ntr}n tdtt}t||t|||fS)a Helper to avoid recomputing certain ops during activation checkpointing. Use this with `torch.utils.checkpoint.checkpoint` to control which operations are recomputed during the backward pass. Args: policy_fn_or_list (Callable or List): - If a policy function is provided, it should accept a :class:`SelectiveCheckpointContext`, the :class:`OpOverload`, args and kwargs to the op, and return a :class:`CheckpointPolicy` enum value indicating whether the execution of the op should be recomputed or not. - If a list of operations is provided, it is equivalent to a policy returning `CheckpointPolicy.MUST_SAVE` for the specified operations and `CheckpointPolicy.PREFER_RECOMPUTE` for all other operations. allow_cache_entry_mutation (bool, optional): By default, an error is raised if any tensors cached by selective activation checkpoint are mutated in order to ensure correctness. If set to `True`, this check is disabled. Returns: A tuple of two context managers. Example: >>> # xdoctest: +REQUIRES(LINUX) >>> import functools >>> >>> x = torch.rand(10, 10, requires_grad=True) >>> y = torch.rand(10, 10, requires_grad=True) >>> >>> ops_to_save = [ >>> torch.ops.aten.mm.default, >>> ] >>> >>> def policy_fn(ctx, op, *args, **kwargs): >>> if op in ops_to_save: >>> return CheckpointPolicy.MUST_SAVE >>> else: >>> return CheckpointPolicy.PREFER_RECOMPUTE >>> >>> context_fn = functools.partial(create_selective_checkpoint_contexts, policy_fn) >>> >>> # or equivalently >>> context_fn = functools.partial(create_selective_checkpoint_contexts, ops_to_save) >>> >>> def fn(x, y): >>> return torch.sigmoid(torch.matmul(torch.matmul(x, y), y)) * y >>> >>> out = torch.utils.checkpoint.checkpoint( >>> fn, x, y, >>> use_reentrant=False, >>> context_fn=context_fn, >>> ) zPlease update the OpOverloadPacket to a specific OpOverload.For example, if you have `torch.ops.aten.mm`, change it to `torch.ops.aten.mm.default`.rz6Expected op in `op_list` to be an OpOverload but got: z of type z. cL|vrtjStjSr4r)roprZrpolicy_fn_or_lists rrz7create_selective_checkpoint_contexts..policy_fns$&&'111'888r1z=policy_fn_or_list must be either a function or a list of ops.)r$rr&r OpOverloadrOpOverloadPacketrr,callable TypeErrorrrr)rr}r _extra_msgrrs` rrrUsr#T*# Bb5::#8#8%**:X:X"YZ EJJ$?$?@nFH!LRDQ#Bxj:,8  9 # $% WXX$/$5G!)W5 G5OP r1c /Kd}ttr$n|r!|tk7r tdt\}}|tvr t|} n,tdt tj d|t|t} |\} t||r0|tk7r't| trttsJdt\r0tjdt| ddr d t!|\f d } t#| t$t$n||| } tj&d d }t)j*||g|| _| j,j.dyt1| 5| 5dddddddd | _t| ddrr s t5d y#1swY5xYw#1swY9xYww)alCheckpointing without reentrant autograd. Args: fn: describes what to run in the forward pass of the model or part of the model. It should also know how to handle the inputs passed as the tuple. For example, in LSTM, if user passes ``(activation, hidden)``, :attr:`function` should correctly use the first input as ``activation`` and the second input as ``hidden`` preserve_rng_state(bool, optional): Omit stashing and restoring the RNG state during each checkpoint. Default: ``True`` context_fn(Callable, optional): A callable returning a tuple of two context managers. The function and its recomputation will be run under the first and second context managers respectively. determinism_check(str, optional): A string specifying the determinism check to perform. By default it is set to ``"default"`` which compares the shapes, dtypes, and devices of the recomputed tensors against those the saved tensors. To turn off this check, specify ``"none"``. Currently these are the only two supported values. Please open an issue if you would like to see more determinism checks. debug(bool, optional): If ``True``, error messages will also include a trace of the operators ran during the original forward computation as well as the recomputation. early_stop(bool, optional): If ``True``, non-reentrant checkpoint stops recomputation as soon as it has computed all needed Tensors. Can be overridden globally using :func:`set_checkpoint_early_stop` context manager. Default: ``True``. *args: Arguments to pass in to the given ``function``. **kwargs: Keyword arguments to pass into the given ``function``. Nz6debug=True is incompatible with non-default context_fnz#determinism_check should be one of z , but got z}In torch.compile mode, `context_fn` arg passed to `torch.utils.checkpoint` must generate a tuple of two `TorchDispatchMode`s.reFrzTc V |^}}g} r r }tjj| 5 r%tj  rt tj j r!tj jddintj}|5tj jdi55|i|ddddddddddddy#1swY"xYw#1swY&xYw#1swY*xYw#1swYyxYw)NrrerfrHr) r&rrrirrprqrrr)r!rrZrrrvrurfr`r}rcrr~r|recompute_contexts rrz=_checkpoint_without_reentrant_generator..recompute_fns-  "3%K \\ " ");# $"##M2$%k3DR]^00=#())"4"4#'#+A#CMCYCYC[ % $eii&8&8&VBU&V $Xi $D#F# $ $ $ $ $ $ $ $ $ $ $ $ $sTA>D. DD C; D"D*D;D DD DD DD(r)r*zPyTorch's device state was initialized in the forward pass of a Checkpoint, which is not allowed. Please open an issue if you need this feature.)rrrrCrMrkeysr\r@rur$r rwr&rbr>rrrrrrrrmrcrr+)r`r|rrrrrZrrrr?forward_contextr new_framedummyrvrurfr}rcrr~rs`` @@@@@@@@rrrsRO$=$I u  (H '@&A# O>>89JK 1$7Y7^7^7`2a1bc() +  %d+K&{3M)3&O&Rv&:+H (9 : (*; < A A  A = 3GS^2_//++- " =.% 8 $ ->-E *K*$$*!)F)R%Xb I KKD 1E+11%G$GI$$,  ) $o "&I}ne4"3 (   s6F G-G!G!G!),G-G G!!G*&G-rJ)r"Nr4)F)crr@rkr9r collectionsrtypingenumrr&torch.fx.tracebackfx tracebackrtorch.utils._pytreer&torch.testing._internal.logging_tensorrrtorch.utils._python_dispatchr __all___DEFAULT_DETERMINISM_MODErOptionalr__annotations__r#rrrr'rIterablerr@rr\ListrrrrwrFunctionr r_disable_dynamoCallableContextManagerrOr r rrrrrrrr r;r+r rCDictrHrM ExceptionrOgraphsaved_tensors_hooksrQrarcrurwrrEnumrropsatenr)rprimr=rW _subclassesfunctional_tensorFunctionalTensor metadata_fnsrrrrrrHr1rrs" # ! ))(R: &&,08D>0 )(4.))* E#s(O ellC6G0H & HSM d 66BD-d3iell1C&C D-(7;/(7&f$00f$R>%)FU6eD>eU>>#ABBC e  e  eeePYGx V15x~4 -d--<  88 "Ienn--"IJ^^B:x l 9'5"c'):HoEVX\E\<])]#^9'vu||S#X6 NP"Dh ~s7J.K)K$L  i .1%....BB.1l65u~~++??65r^    &))4tyy:R IINN!! IINN!! ++<<IIJK" 1"H0DStFU6 D U>>#ABBCD  D  D  D r1