L iUddlZddlmZddlmZddlmZddlmZddl m Z m Z ddl m Z ddlZddlZddlmZdd lmZdd lmZmZmZmZmZmZmZmZmZmZmZm Z dd l!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)dd l*m+Z+gd Z, ddl-m.Z/da2e3e4d<de3fdZ5dZ6dZ7eGddZ8GddZ9Gdde/Z:GddZ;Gdd Zd$Z?Gd%d&Z@y#e0$rddl1Z1GddZ/Y{wxYw)'N) defaultdict)Iterable) dataclass)perf_counter_ns)AnyOptional)warn)_get_privateuse1_backend_name)_ExperimentalConfig) _disable_profiler_enable_profiler _kineto_step_prepare_profiler_ProfilerResult_supported_activities_toggle_collection_dynamic DeviceTypekineto_availableProfilerActivityProfilerConfig ProfilerState) _filter_name_filter_stack_entry _rewrite_name EventList FunctionEventMEMORY_EVENT_NAME MemRecordsAccOUT_OF_MEMORY_EVENT_NAME)Future) profilerecord_functionemit_itt emit_nvtx load_nvprof EnforceUniqueparse_nvprof_traceKinetoStepTrackerrrr)ContextDecoratorceZdZdZdZdZy)_ContextDecoratorctNNotImplementedErrorselfs ]/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/torch/autograd/profiler.py __enter__z_ContextDecorator.__enter__>% %ctr-r.r1exc_typeexc_valexc_tbs r2__exit__z_ContextDecorator.__exit__Ar4r5cFtjfd}|S)NcD5|i|cdddS#1swYyxYwr-)argskwargsfuncr1s r2wrappedz+_ContextDecorator.__call__..wrappedEs(100111s) functoolswraps)r1rArBs`` r2__call__z_ContextDecorator.__call__Ds% __T " 1# 1Nr5N)__name__ __module__ __qualname__r3r;rEr>r5r2r+r+=s & & r5r+F_is_profiler_enabledenablec|ayr-)rI)rJs r2_set_is_profiler_enabledrLRs!r5ctdy)NTrLr>r5r2_run_on_profiler_startrOWs T"r5ctdyNFrNr>r5r2_run_on_profiler_stoprR[s U#r5cteZdZUdZdZeed<dZeed<dZ eed<dZ eed<dZ eed<dZ eed<dZ eed <y ) _ProfilerStatszHProfiler timing and stats used by developers to catch issues/regressionsrprofiling_window_duration_secnumber_of_events!profiler_prepare_call_duration_us profiler_enable_call_duration_us!profiler_disable_call_duration_usparse_kineto_call_duration_us+function_events_build_tree_call_duration_usN)rFrGrH__doc__rUfloat__annotations__rVintrWrXrYrZr[r>r5r2rTrT_sRN+,!5,c-.%s.,-$c--.%s.)*!3*78/8r5rTceZdZdZ dddddddddddddd dZdZdZd d Zd Zd Z d Z d Z dZ dZ dZedZ d!dZej"je_dZej&je_d"dedefdZdedeefdZ d#dZej4je_dZej6je_edZdefdZy)$r!aContext manager that manages autograd profiler state and holds a summary of results. .. note:: This is the backend, most people should use :mod:`torch.profiler` instead. Under the hood it just records events of functions being executed in C++ and exposes those events to Python. You can wrap any code into it and it will only report runtime of PyTorch functions. Note: profiler is thread local and is automatically propagated into the async tasks Args: enabled (bool, optional): Setting this to False makes this context manager a no-op. use_cuda (bool, optional): Enables timing of CUDA events as well using the cudaEvent API. (will be deprecated) use_device (str, optional): Enables timing of device events. Adds approximately 4us of overhead to each tensor operation when use cuda. The valid devices options are 'cuda', 'xpu', 'mtia' and 'privateuseone'. record_shapes (bool, optional): If shapes recording is set, information about input dimensions will be collected. This allows one to see which dimensions have been used under the hood and further group by them using prof.key_averages(group_by_input_shape=True). Please note that shape recording might skew your profiling data. It is recommended to use separate runs with and without shape recording to validate the timing. Most likely the skew will be negligible for bottom most events (in a case of nested function calls). But for higher level functions the total self cpu time might be artificially increased because of the shape collection. with_flops (bool, optional): If with_flops is set, the profiler will estimate the FLOPs (floating point operations) value using the operator's input shape. This allows one to estimate the hardware performance. Currently, this option only works for the matrix multiplication and 2D convolution operators. profile_memory (bool, optional): track tensor memory allocation/deallocation. with_stack (bool, optional): record source information (file and line number) for the ops. with_modules (bool): record module hierarchy (including function names) corresponding to the callstack of the op. e.g. If module A's forward call's module B's forward which contains an aten::add op, then aten::add's module hierarchy is A.B Note that this support exist, at the moment, only for TorchScript models and not eager mode models. use_kineto (bool, optional): experimental, enable profiling with Kineto profiler. use_cpu (bool, optional): profile CPU events; setting to ``False`` requires ``use_kineto=True`` and can be used to lower the overhead for GPU-only profiling. experimental_config (_ExperimentalConfig) : A set of experimental options used by profiler libraries like Kineto. Note, backward compatibility is not guaranteed. acc_events (bool): Enable the accumulation of FunctionEvents across multiple profiling cycles .. warning:: Enabling memory profiling or source attribution incurs additional profiler overhead .. warning:: This context managers should not be called recursively, i.e. no nested instances are allowed .. warning:: Due to some CUDA multiprocessing limitations (see :ref:`multiprocessing-cuda-note`), one cannot use the profiler with ``use_device = 'cuda'`` to benchmark DataLoaders with ``num_workers > 0``. If you wish to benchmark data loading, please use ``use_device = None`` or ``num_workers = 0``. Example: >>> # xdoctest: +SKIP >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD_PROFILER) >>> x = torch.randn((1, 1), requires_grad=True) >>> with torch.autograd.profiler.profile() as prof: >>> for _ in range(100): # any normal python code, really! >>> y = x ** 2 >>> y.backward() >>> # NOTE: some columns were removed for brevity >>> print(prof.key_averages().table(sort_by="self_cpu_time_total")) ----------------------------------- --------------- --------------- --------------- Name Self CPU total CPU time avg Number of Calls ----------------------------------- --------------- --------------- --------------- mul 32.048ms 32.048ms 200 pow 27.041ms 27.041ms 200 PowBackward0 9.727ms 55.483ms 100 torch::autograd::AccumulateGrad 9.148ms 9.148ms 100 torch::autograd::GraphRoot 691.816us 691.816us 100 ----------------------------------- --------------- --------------- --------------- TFN) use_cuda use_device record_shapes with_flopsprofile_memory with_stack with_modules use_kinetouse_cpuexperimental_config acc_eventscustom_trace_id_callbackc  ||_|jsy||_|jrtdtdd|_n||_d|_d|_d|_d|_||_ ||_ |xj|jzc_ ||_ ||_ ||_ | |_| |_| t!} | |_d|_d|_d|_t+|_| |_d|_|js | sJd|j,gd }t3d k7r|j5t3|j|vr td |jd d|_|jdk(r7t6j8j;std d|_d|_|jdk(r0t6j<j;stdd|_|jdk(r@t?t6drt6j@j;stdd|_tC|_"|jr)|jDjGtHjJtLjN|_(|jdk(rq| rtHjRtUvr*|jsJdtLjV|_(n|jDjGtHjRn|jdk(rN| rtHjXtUvsJd|jDjGtHjXnA|jdk(rM| rtHjZtUvsJd|jDjGtHjZn|jdk(rM| rtHj\tUvsJd|jDjGtHj\n|j}|jd k7rn| rtHj^tUvr)|jsJdtLj`|_(n)|jDjGtHj^tc|jDdkDsJdy)Nz]The attribute `use_cuda` will be deprecated soon, please use ``use_device = 'cuda'`` instead.) stacklevelcudaFrz?Device-only events supported only with Kineto (use_kineto=True))rpxpumtiahpu privateuseonezThe z is not a valid device option.z/CUDA is not available, disabling CUDA profilingrrz-XPU is not available, disabling XPU profilingrtz-HPU is not available, disabling HPU profilingz+Legacy CUDA profiling requires use_cpu=TruezOLegacy XPU profiling is not supported. Requires use_kineto=True on XPU devices.rszQLegacy MTIA profiling is not supported. Requires use_kineto=True on MTIA devices.zOLegacy HPU profiling is not supported. Requires use_kineto=True on HPU devices.z4Legacy custombackend profiling requires use_cpu=Truez(No activities specified for the profiler)2enabledrar FutureWarningrb_function_events_old_function_events_needs_processingenteredrcrdrerfrgrirkr rjkineto_resultsprofiling_start_time_nsprofiling_end_time_nsrT_statsrltrace_idr appendtorchrp is_availablerrhasattrrtsetkineto_activitiesaddrCPUrKINETO profiler_kindCUDArKINETO_GPU_FALLBACKXPUMTIAHPU PrivateUse1KINETO_PRIVATEUSE1_FALLBACKlen)r1rvrarbrcrdrerfrgrhrirjrkrlVALID_DEVICE_OPTIONSs r2__init__zprofile.__init__s "% ||   == >   .4DO(DO599=!!& *$ doo-,$( $  &"5"7 #6 9='($%&"$& (@% || Q : ?? &#A ,./A$++,I,KL&::tDOO,,JKL"&&(1H1H1JFG % "&%' 0F0F0HDE"&%'u%%))*@*@*BDE"&!$ <<  " " & &'7';'; <*11 ??f $!1!6!6>S>U!U||R%RR|%2%F%F"&&**+;+@+@A __ %"2"6"6:O:Q"Q a Q  " " & &'7';'; < __ &"2"7"7;P;R"R c R  " " & &'7'<'< = __ %"2"6"6:O:Q"Q a Q  " " & &'7';'; < __ (T__-O#//7L7NN||J|&3%N%N"&&**+;+G+GH4))*Q. 6 .r5cFtj}|jdS)N032X)uuiduuid4r_)r1uuid_raws r2default_trace_idzprofile.default_trace_idGs::<,,t$%r5cZ|jr|jS|jSr-)rlrr0s r2create_trace_idzprofile.create_trace_idMs)  ( (002 2$$&&r5c |r|j}||_t|j|j|j |j |j|j|j|jSr-) rrrrrcrerfrdrgrj)r1rrs r2configzprofile.configRsi ++-H$DM          OO OO     $ $ MM  r5c|jsy|jr td|j|j |S)Nz)Profiler context manager is not reentrant)rvr{ RuntimeError_prepare_trace _start_tracer0s r2r3zprofile.__enter__bs<||  <<JK K   r5cd|_t}t|jd|jt}t ||z dz |j _y)NTr)r{rrrrr_rrWr1t0t1s r2rzprofile._prepare_traceksN  $++d+;T=S=ST  8;R"W#E4??;M}m4))+  T__(,(=(=D % $!%  /1  8;R"W)rzrrxreprr0s r2__repr__zprofile.__repr__s7  ! !  ( ( *  (8D))**r5c~|jr|j|jyt|jSr)rzrrxstrr0s r2__str__zprofile.__str__s7  ! !  ( ( *  (84(())r5c|jyd|_t}g}|jr|j |j}t}t ||z dz |j _t||j|j|j|_t}|jjt}t ||z dz |j _ t|j|j _|j r?|j"r3|j D]}|jj%|d|_|j t'dy)z*Process function events lazily if requiredNFr)rbrerdzProfiler didn't finish running)rxrzrr|_parse_kineto_resultsr_rrZrrbrerd _build_treer[rrVryrkrr)r1rparsed_resultsrevts r2rzprofile._ensure_function_eventssA  , !&     !778K8KLN  47bD8H4I 1 ) .. !    ))+  BErBwRVFVBW ?'*4+@+@'A $  $ $00 2%%,,S1 2(,D %  (?@ @ )r5cj|j |jr|j|jSr-)rxrzrr0s r2function_eventszprofile.function_eventss.  (D,B,B  ( ( *$$$r5c |j|jJ|jj|||||||S)N)sort_by row_limitmax_src_column_widthmax_name_column_widthmax_shapes_column_widthheadertop_level_events_only)rrxtable)r1rrrrrrrs r2rz profile.tablesU $$&$$000$$**!5"7$;"7+  r5ctr|jj|y|j|jj |S)z Exports the collected trace in Chrome JSON format. If kineto is enabled, only last cycle in schedule is exported. N)rr|saverrxexport_chrome_trace)r1paths r2rzprofile.export_chrome_tracesA      $ $T *  ( ( *((<||jFD]}|jtjXk(s|jtjZk(rS|jM|j|j<|j\j^|j\j`z |jtjk(s|jb|_1fd%}|D])}|d r d z ||d}|jS|+|D] }d z ||}|jS|"|jed&'|Scc}wcc}wcc}w))NFc|jtjtjtjfvr|j SdSNr) device_typerrMKLDNNIDEEPnbytes mem_records r2_cpu_memory_usagez8profile._parse_kineto_results.._cpu_memory_usage.sM))+NNJ$5$5z7G7GHI!!#   r5c|jtjtjtjtj fvr|j SdSr)rrrrHIPrrrs r2_device_memory_usagez;profile._parse_kineto_results.._device_memory_usage6sU))+OO**NNNN !!#  r5ris_hidden_eventcyrQr>r>r5r2z/profile._parse_kineto_results..Osr5rTidname)r with_wildcard overload_name trace_namethreadstart_usend_us fwd_thread input_shapesconcrete_inputskwinputsstackscoperbcpu_memory_usagedevice_memory_usageis_async sequence_nrr device_indexdevice_resource_idflopsis_user_annotationrpzGot negative correlation id z in profiler post processingcT|jz }tdidd|jddddd|jd|dz d |dz d |jd gd gd ddjd|d|dddddt j dd}|S)NrrrrqrrrrrrrrrrrbrrrFrrrr>)start_nsrrstart_thread_idrbrr)r rel_start_nsferr max_evt_idr1trace_start_nss r2"createFunctionEventForMemoryEventszIprofile._parse_kineto_results..createFunctionEventForMemoryEventss<<>N:LXXZ!  **,  &, $d*..0  ??"33!7%9$= !"'NN#$%B(Ir5c\|jj|jj gSr-) time_rangestartendrs r2rz/profile._parse_kineto_results..s"S^^11CNN4F4F3FGr5keyr>)3r eventsrrrrrrrend_nsrrr in_intervalrr end_thread_idrcorrelation_idrr fwd_thread_idshapesrrrrrrbrrrrrmaxrr privateuse1_elapsed_us append_kernel is_legacycuda_elapsed_usrlinked_correlation_idrrrr rrrsort)r1rr mem_records oom_recordsmem_records_accall_function_eventsfrontend_function_eventsdevice_corr_map kineto_eventr rel_end_ns abs_end_nsrrrrentryrprivateuse1_time cuda_timecorr_idf_evtr  oom_recordrrr r s` @@@@r2rzprofile._parse_kineto_results"s6 ..0$*MMO  sxxzEV7VS%L  "==? chhj&..0".!3!3!5*51"#((*#$ ??%&"2'(%8)*"+,)446-.)446/0*66812$0#B#B#D34#((*56$0#B#B#D7B:Z/J~~/ ??&C&EE'3'J'J'L$'!+(("//CST'+ __. , < < >I 1}(("//9M'+  & &r *"88:G{/1/1OG,(//3A(//3"27);WXYN b+ 1B*..0 EE_,,RUU31E))Z__< ,, 0F0FF((!JJ!..!,,0053C3C3I3II **jnn<(*yy 1  1,  2& /Ja=a 7 1 F#**2.  / & +J !OJ3J?B  & &r * +   G ! #"i  PsXXX<X X)T)F)NdK7PNF)r)FrF)rFrGrHr\rrrrr3rrr;rrrpropertyrrrrrrboolrrrrrrrrr>r5r2r!r!lsl\@z  !%z x& '  N*@+*AB%% "# ,OO++EM C#,"?"?"G"GA#AsA DD)12B)CD#$  %1199L5 &33;;M 99x#Ox#r5r!c^eZdZdZddedeefdZdZdeded efd Z d e ed e efd Z y)r"aContext manager/function decorator that adds a label to a code block/function when running autograd profiler. Label will only appear if CPU activity tracing is enabled. It is useful when tracing the code profile. Args: name (str): Label assigned to the block of code. node_id (int): ID of node, for distributed profiling. Unset in non-distributed cases. Example: >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD_PROFILER) >>> x = torch.randn((1, 1), requires_grad=True) >>> with torch.autograd.profiler.profile() as prof: ... y = x**2 ... with torch.autograd.profiler.record_function( ... "label-z" ... ): # label the block ... z = y**3 ... y.backward() >>> # xdoctest: +IGNORE_WANT >>> # NOTE: some columns were removed for brevity >>> print(prof.key_averages().table(sort_by="self_cpu_time_total")) ----------------------------------- --------------- --------------- --------------- Name Self CPU total % CPU time avg Number of Calls ----------------------------------- --------------- --------------- --------------- pow 60.77% 47.470us 3 mul 21.73% 25.465us 2 PowBackward0 12.03% 121.891us 1 torch::autograd::AccumulateGrad 2.70% 6.324us 1 label-z 2.13% 12.421us 1 torch::autograd::GraphRoot 0.64% 1.503us 1 ----------------------------------- --------------- --------------- --------------- Self CPU time total: 234.344us CUDA time total: 0.000us Nrr?c||_||_d|_tjj t dd|_y)NTz&torch.classes.profiler._RecordFunction)rr?run_callbacks_on_exitrjitannotaterrecord)r1rr?s r2rzrecord_function.__init__s; #' +/"ii(( = >  r5ctjjj|j|j |_|Sr-)ropsprofiler_record_function_enter_newrr?r;r0s r2r3zrecord_function.__enter__s2ii((CC IItyy   r5r8 exc_value tracebackc|jsy|j}|Jtjj s[tj j 5tjjjj|dddytjjj|y#1swYyxYwr-) r8r;rr9 is_scripting_CDisableTorchFunctionSubclassr=r>_record_function_exit_RecordFunction)r1r8r@rAr;s r2r;zrecord_function.__exit__s)) !!!yy%%'668 Q ""88HHP Q Q II   4 4V < Q Qs 4CC futreturnc|js tdd|_|j}|Jtjj s]tj j5tjjjj||}ddd|Stjjj||}|S#1swYSxYw)avUse for profiling async calls that return a future. Calling this function will extend recording beyond this scope, until the future is satisfied. It is useful for profiling the end to end time of asynchronous calls. This function should only be called once to attach the callback onto the future, and will throw if called multiple times. Args: fut: (torch._C.Future): future for which to schedule callback for. Returns: A future that completes with the value of the passed in future when the profiling callbacks have ran. z6_call_end_callbacks_on_future can only be called once.FN) r8rr;rr9rCrDrEr=r>_call_end_callbacks_on_jit_futrG)r1rHr;profiled_futures r2_call_end_callbacks_on_futurez-record_function._call_end_callbacks_on_future%s$))WX X&+"!!!yy%%'668 II&&EEUU  $ii00OOO s +5CC r-) rFrGrHr\rrrr3rr;r rMr>r5r2r"r"sY$L  S     ==== ***r5r"c$eZdZdZddZdZdZy)r#aContext manager that makes every autograd operation emit an ITT range. It is useful when running the program under Intel(R) VTune Profiler:: vtune <--vtune-flags> The Instrumentation and Tracing Technology (ITT) API enables your application to generate and control the collection of trace data during its execution across different Intel tools. This context manager is to annotate Intel(R) VTune Profiling trace. With help of this context manager, you will be able to see labeled ranges in Intel(R) VTune Profiler GUI. .. warning: This context manager should not be called recursively, i.e. at most one instance should be enabled at any given time. Args: enabled (bool, optional): Setting ``enabled=False`` makes this context manager a no-op. Default: ``True``. record_shapes (bool, optional): If ``record_shapes=True``, the itt range wrapping each autograd op will append information about the sizes of Tensor arguments received by that op, in the following format: ``[[arg0.size(0), arg0.size(1), ...], [arg1.size(0), arg1.size(1), ...], ...]`` Non-tensor arguments will be represented by ``[]``. Arguments will be listed in the order they are received by the backend op. Please note that this order may not match the order in which those arguments were passed on the Python side. Also note that shape recording may increase the overhead of itt range creation. Default: ``False`` Example: >>> # xdoctest: +SKIP("Undefined variables") >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD_PROFILER) >>> with torch.autograd.profiler.emit_itt(): ... model(x) c.||_d|_||_yrQrvr{rcr1rvrcs r2rzemit_itt.__init__w  *r5c |jsy|jr tdd|_tt t t j|jddddtt|S)Nz/ITT annotation context manager is not reentrantTF) rvr{rrOr rrITTrcr rr0s r2r3zemit_itt.__enter__|sn||  <<PQ Q   !!""#%  E  r5cF|jsyttyrQ)rvr rRr7s r2r;zemit_itt.__exit__s|| r5NTFrFrGrHr\rr3r;r>r5r2r#r#Rs"H+ *r5r#c$eZdZdZddZdZdZy)r$a7Context manager that makes every autograd operation emit an NVTX range. It is useful when running the program under nvprof:: nvprof --profile-from-start off -o trace_name.prof -- Unfortunately, there's no way to force nvprof to flush the data it collected to disk, so for CUDA profiling one has to use this context manager to annotate nvprof traces and wait for the process to exit before inspecting them. Then, either NVIDIA Visual Profiler (nvvp) can be used to visualize the timeline, or :func:`torch.autograd.profiler.load_nvprof` can load the results for inspection e.g. in Python REPL. .. warning: This context manager should not be called recursively, i.e. at most one instance should be enabled at any given time. Args: enabled (bool, optional): Setting ``enabled=False`` makes this context manager a no-op. Default: ``True``. record_shapes (bool, optional): If ``record_shapes=True``, the nvtx range wrapping each autograd op will append information about the sizes of Tensor arguments received by that op, in the following format: ``[[arg0.size(0), arg0.size(1), ...], [arg1.size(0), arg1.size(1), ...], ...]`` Non-tensor arguments will be represented by ``[]``. Arguments will be listed in the order they are received by the backend op. Please note that this order may not match the order in which those arguments were passed on the Python side. Also note that shape recording may increase the overhead of nvtx range creation. Default: ``False`` Example: >>> # xdoctest: +SKIP("undefined variables") >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD_PROFILER) >>> with torch.cuda.profiler.profile(): ... model(x) # Warmup CUDA memory allocator and profiler ... with torch.autograd.profiler.emit_nvtx(): ... model(x) **Forward-backward correlation** When viewing a profile created using :class:`emit_nvtx` in the Nvidia Visual Profiler, correlating each backward-pass op with the corresponding forward-pass op can be difficult. To ease this task, :class:`emit_nvtx` appends sequence number information to the ranges it generates. During the forward pass, each function range is decorated with ``seq=``. ``seq`` is a running counter, incremented each time a new backward Function object is created and stashed for backward. Thus, the ``seq=`` annotation associated with each forward function range tells you that if a backward Function object is created by this forward function, the backward object will receive sequence number N. During the backward pass, the top-level range wrapping each C++ backward Function's ``apply()`` call is decorated with ``stashed seq=``. ``M`` is the sequence number that the backward object was created with. By comparing ``stashed seq`` numbers in backward with ``seq`` numbers in forward, you can track down which forward op created each backward Function. Any functions executed during the backward pass are also decorated with ``seq=``. During default backward (with ``create_graph=False``) this information is irrelevant, and in fact, ``N`` may simply be 0 for all such functions. Only the top-level ranges associated with backward Function objects' ``apply()`` methods are useful, as a way to correlate these Function objects with the earlier forward pass. **Double-backward** If, on the other hand, a backward pass with ``create_graph=True`` is underway (in other words, if you are setting up for a double-backward), each function's execution during backward is given a nonzero, useful ``seq=``. Those functions may themselves create Function objects to be executed later during double-backward, just as the original functions in the forward pass did. The relationship between backward and double-backward is conceptually the same as the relationship between forward and backward: The functions still emit current-sequence-number-tagged ranges, the Function objects they create still stash those sequence numbers, and during the eventual double-backward, the Function objects' ``apply()`` ranges are still tagged with ``stashed seq`` numbers, which can be compared to `seq` numbers from the backward pass. .. warning: The sequence number is thread-local, and some forward functions don't create an associated backward Function object (instead delegating that to sub-functions further down the call chain). For these reasons, the correspondence of stashed sequence numbers in backward Function ``apply()`` ranges with `seq` numbers in forward-pass ranges is not guaranteed to be 1 to 1. The sequence numbers alone may not be enough to fully disambiguate which forward function created which backward Function object. You may need to make a judgment based on analytic knowledge of what the expected correspondence should be. c.||_d|_||_yrQrPrQs r2rzemit_nvtx.__init__rRr5c 2|jsy|jr tdd|_tjj t tttj|jddddtt|S)Nz0NVTX annotation context manager is not reentrantTF)rvr{rrrprrOr rrNVTXrcr rr0s r2r3zemit_nvtx.__enter__s~||  <<QR R     """"#%  E  r5c|jsytjjt t yrQ)rvrrprr rRr7s r2r;zemit_nvtx.__exit__ s+||   r5NrVrWr>r5r2r$r$sRh+ ,r5r$c*tt|S)zsOpen an nvprof trace file and parses autograd annotations. Args: path (str): path to nvprof trace )rr')rs r2r%r%s '- ..r5ceZdZdZdZdZy)r&z0Raises an error if a key is seen more than once.c"t|_yr-)rseenr0s r2rzEnforceUnique.__init__s E r5c||jvrtdt|z|jj|y)zP Observe a key and raise an error if it is seen multiple times. zduplicate key: N)r`rrr)r1rs r2seezEnforceUnique.see!s5 $)) 03s8;< < cr5N)rFrGrHr\rrbr>r5r2r&r&s:r5r&c ddl}|j|}|j|_i}|j dD]*}t j j|d||d<,d}g}i}t}|j |D]V} |j| dt| dd|| d| d| d d } |j| | || j<Xd } t}|j | D]K} |j| d| d | d dk(sJ|| d} | j| dd| d| dz M|jd|S)Nrz)SELECT _id_ as id, value FROM StringTablevaluera& SELECT start.id AS marker_id, start.name, start.timestamp AS start_time, end.timestamp AS end_time FROM CUPTI_ACTIVITY_KIND_MARKER AS start INNER JOIN CUPTI_ACTIVITY_KIND_MARKER AS end ON start.id = end.id WHERE start.name != 0 AND end.name = 0 marker_idr start_timeend_time)rnode_idrrrra SELECT start.id AS marker_id, start.name, start.timestamp, end.timestamp, runtime._id_ AS runtime_id, runtime.cbid, runtime.start AS runtime_start, runtime.end AS runtime_end, kernel.start AS kernel_start, kernel.end AS kernel_end, kernel.name AS kernel_name FROM CUPTI_ACTIVITY_KIND_MARKER AS start INNER JOIN CUPTI_ACTIVITY_KIND_MARKER AS end ON start.id = end.id INNER JOIN CUPTI_ACTIVITY_KIND_RUNTIME as runtime ON (start.timestamp < runtime.start AND runtime.end < end.timestamp) INNER JOIN CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL AS kernel ON kernel.correlationId = runtime.correlationId runtime_idcbid kernel_name kernel_end kernel_startc.|jjSr-)r rrs r2rz$parse_nvprof_trace..is3>>#7#7r5r)sqlite3connectRow row_factoryexecuterrD _demangler&rbrrrrr ) rrpconnstringsr marker_query functions functions_mapuniquerowr kernel_querys r2r'r'*s ??4 D{{DG \\E F: 88--aj9$:LIM _F||L) $ 3{#$;V%&z?   # cff $ L_F||L)  3{#S%676{c!!!C ,-   3|#4s>7J#J  NN7N8 r5ceZdZUdZdZeeZee efe d<e de fdZ e de de fdZe de defdZe defd Zy ) r(aProvides an abstraction for incrementing the step count globally. Previously, we only had one place to mark that a step() has occurred in the program via pytorch profiler step(). We will now add step hooks in the Optimizer class https://github.com/pytorch/pytorch/issues/88446 - This could mean programs that already call profiler.step() every iteration can end up double incrementing step count. - If a model uses multiple optimizers we can also have double or more counting of the step. We fix this by adding a layer of abstraction before calling step() to the kineto library. The idea is to maintain steps per requester in a dict: .. code-block:: { "ProfilerStep": 100, # triggered by profiler step() call "Optimizer1Step": 100, # Optimizer 1 or 2 are just examples, could be SGD, Adam etc "Optimizer2Step": 100, } To figure out the global step count just take the max of dict values (100). If one of the count increments the max will go up. .. code-block:: { "ProfilerStep": 100, "Optimizer1Step": 101, # Optimizer1 got incremented first say "Optimizer2Step": 100, } Then global step count is 101 We only call the kineto step() function when global count increments. NOTE: Please do not use the KinetoStepTracker in modules beside the Optimizer for now. The result could be incorrect increments of the step count. r _step_dict requesterc6|j|j|<y)z3 Initialize for a given requester. N) _current_steprclsrs r2init_step_countz!KinetoStepTracker.init_step_counts %($5$5y!r5rIc>|jj|dduS)z+ Remove a given requester. N)rpoprs r2erase_step_countz"KinetoStepTracker.erase_step_counts ~~!!)T2$>>r5c||jvr|j||j|xxdz cc<t|jj}||jkDr[||jz }|dkDr%t d|jd|jt d|D] }t||_|jS)zIncrements the step count for the requester. Additionally if the max over all step counts has incremented then trigger the _kineto_step() returns global step count rz?Profiler step count has increased more than 1 - current_step = z step dict = r)rrrvaluesrr ranger)rrnew_stepdelta_s r2increment_stepz KinetoStepTracker.increment_steps CNN *    * y!Q&!s~~,,./ c'' 's000Eqy&&)&7&7%8s~~FVX1e_   (C    r5c|jS)z7 Get the latest step for any requester )r)rs r2 current_stepzKinetoStepTracker.current_steps    r5N)rFrGrHr\rrr_rdictrr^ classmethodrr5rrrr>r5r2r(r(ms'RM!,S!1JS#X1666 ???? !s!s!!.!S!!r5r()Ar collectionsrcollections.abcr dataclassesrtimertypingrrwarningsr r torch.cudatorch._Cr torch._C._profilerr torch.autogradr r rrrrrrrrrrtorch.autograd.profiler_utilrrrrrrrr torch.futuresr __all__ contextlibr)r+ ImportErrorrCrIr5r^rLrOrRrTr!r"r#r$r%r&r'r(r>r5r2rs #$!  22       ! @,#d""T" #$  9 9  9n #n #br'rjDDNvvr/  @FX!X!g!  s;C''C=<C=