/usr/local/lib64/python3.6/site-packages/torch/profiler/__pycache__
NameSizeModeActions
profiler.cpython-36.pyc161810644editdlrm
__init__.cpython-36.pyc9810644editdlrm
Edit: /usr/local/lib64/python3.6/site-packages/torch/profiler/__pycache__/profiler.cpython-36.pyc (16181B)
3 EgWF@sddlZddlZddlZddlZddlmZddlmZmZm Z m Z ddl m Z ddl Z ddljjZddlmZmZGdddeZdddeeeeeed d d Zeed d dZdee eedddZddZGdddeZdS)N)Enum)AnyCallableIterableOptional)warn)kineto_availableProfilerActivityc@s eZdZdZdZdZdZdZdS)ProfilerActionzG Profiler actions that can be taken at the specified intervals rN)__name__ __module__ __qualname____doc__NONEWARMUPRECORDRECORD_AND_SAVErrC/usr/local/lib64/python3.6/site-packages/torch/profiler/profiler.pyr s r )repeat skip_first)waitwarmupactiverrreturncs`ttdfdd }dkrDdkrDdkrDdkrDdksLtddkr\td|S)a Returns a callable that can be used as profiler ``schedule`` argument. The profiler will skip the first ``skip_first`` steps, then wait for ``wait`` steps, then do the warmup for the next ``warmup`` steps, then do the active recording for the next ``active`` steps and then repeat the cycle starting with ``wait`` steps. The optional number of cycles is specified with the ``repeat`` parameter, the zero value means that the cycles will continue until the profiling is finished. )steprcs|dks t|krtjS|8}}dkrH||krHtjS||}|kr^tjS|krptjS||dkrtjStjSdS)Nrr )AssertionErrorr rrrr)rZ num_stepsZmod_step)rrrrrrr schedule_fn s   zschedule..schedule_fnrz#Invalid profiler schedule argumentsz>Profiler won't be using warmup, this can skew profiler results)intr rr)rrrrrr r)rrrrrrschedules r")_rcCstjS)zy Default profiler behavior - immediately starts recording the events, keeps doing it on every profiler step. )r r)r#rrr_default_schedule_fn8sr$F)dir_name worker_nameuse_gzipcs8ddlddlddlddfdd }|S)a  Outputs tracing files to directory of ``dir_name``, then that directory can be directly delivered to tensorboard as logdir. ``worker_name`` should be unique for each worker in distributed scenario, it will be set to '[hostname]_[pid]' by default. rN)rc sjjs@yjddWn tk r>tdYnXs\djjtjdjt j d}r|d}|j jj |dS)NT)exist_okzCan't create directory: z{}_{}z{}.{}.pt.trace.jsoniz.gz) pathisdirmakedirs Exception RuntimeErrorformat gethostnamestrgetpidr!timeexport_chrome_tracejoin)prof file_name)r%ossocketr2r'r&rr handler_fnJs z-tensorboard_trace_handler..handler_fn)r7r8r2)r%r&r'r9r)r%r7r8r2r'r&rtensorboard_trace_handler?s  r:cCs tjjS)a Returns a set of supported profiler tracing activities. Note: profiler uses CUPTI library to trace on-device CUDA kernels. In case when CUDA is enabled but CUPTI is not available, passing ``ProfilerActivity.CUDA`` to profiler results in using the legacy CUDA profiling code (same as in the legacy ``torch.autograd.profiler``). This, in turn, results in including CUDA time in the profiler table output, but not in the JSON trace. )torchautogradZ_supported_activitiesrrrrsupported_activitiesYs r=c @seZdZdZdddddddddd eeeeeege feede fe e e e e ee d ddZ dd Z d d Zd d ZddZddZedddZd0eedddZd1e edddZddZeedd d!Zeedd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/ZdS)2profileaProfiler context manager. Args: activities (iterable): list of activity groups (CPU, CUDA) to use in profiling, supported values: ``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``. Default value: ProfilerActivity.CPU and (when available) ProfilerActivity.CUDA. schedule (callable): callable that takes step (int) as a single parameter and returns ``ProfilerAction`` value that specifies the profiler action to perform at each step. on_trace_ready (callable): callable that is called at each step when ``schedule`` returns ``ProfilerAction.RECORD_AND_SAVE`` during the profiling. record_shapes (bool): save information about operator's input shapes. profile_memory (bool): track tensor memory allocation/deallocation. with_stack (bool): record source information (file and line number) for the ops. with_flops (bool): use formula to estimate the FLOPs (floating point operations) of specific operators (matrix multiplication and 2D convolution). 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_cuda (bool): .. deprecated:: 1.8.1 use ``activities`` instead. .. note:: Use :func:`~torch.profiler.schedule` to generate the callable schedule. Non-default schedules are useful when profiling long training jobs and allow the user to obtain multiple traces at the different iterations of the training process. The default schedule simply records all the events continuously for the duration of the context manager. .. note:: Use :func:`~torch.profiler.tensorboard_trace_handler` to generate result files for TensorBoard: ``on_trace_ready=torch.profiler.tensorboard_trace_handler(dir_name)`` After profiling, result files can be found in the specified directory. Use the command: ``tensorboard --logdir dir_name`` to see the results in TensorBoard. For more information, see `PyTorch Profiler TensorBoard Plugin `__ .. note:: Enabling shape and stack tracing results in additional overhead. When record_shapes=True is specified, profiler will temporarily hold references to the tensors; that may further prevent certain optimizations that depend on the reference count and introduce extra tensor copies. Examples: .. code-block:: python with torch.profiler.profile( activities=[ torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA, ] ) as p: code_to_profile() print(p.key_averages().table( sort_by="self_cuda_time_total", row_limit=-1)) Using the profiler's ``schedule``, ``on_trace_ready`` and ``step`` functions: .. code-block:: python # Non-default profiler schedule allows user to turn profiler on and off # on different iterations of the training loop; # trace_handler is called every time a new trace becomes available def trace_handler(prof): print(prof.key_averages().table( sort_by="self_cuda_time_total", row_limit=-1)) # prof.export_chrome_trace("/tmp/test_trace_" + str(prof.step_num) + ".json") with torch.profiler.profile( activities=[ torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA, ], # In this example with wait=1, warmup=1, active=2, # profiler will skip the first step/iteration, # start warming up on the second, record # the third and the forth iterations, # after which the trace will become available # and on_trace_ready (when set) is called; # the cycle repeats starting with the next step schedule=torch.profiler.schedule( wait=1, warmup=1, active=2), on_trace_ready=trace_handler # on_trace_ready=torch.profiler.tensorboard_trace_handler('./log') # used when outputting for tensorboard ) as p: for iter in range(N): code_iteration_to_profile(iter) # send a signal to the profiler that the next iteration has started p.step() NF) activitiesr"on_trace_ready record_shapesprofile_memory with_stack with_flops with_modulesuse_cuda.c Cs|rt||_nt|_| dk rVtd| r<|jjtjntj|jkrV|jjtjt|jdkslt d|r~||_ d|_ n t |_ d|_ ||_ ||_||_||_||_||_d|_|j |j|_d|_d|_dS)Nz7use_cuda is deprecated, use activities argument insteadrz"No valid profiler activities foundTF)setr?r=raddr CUDAremovelenrr" record_stepsr$r@rArDrBrCrEstep_numcurrent_actionprofiler step_rec_fn) selfr?r"r@rArBrCrDrErFrrr__init__s2   zprofile.__init__cCs |j|S)N)start)rQrrr __enter__szprofile.__enter__cCs |jdS)N)stop)rQexc_typeexc_valexc_tbrrr__exit__szprofile.__exit__cCs2|j|jr.tjdt|j|_|jjdS)Nz ProfilerStep#)_enter_actionsrLr5record_functionr0rMrPrT)rQrrrrSsz profile.startcCs(|jr|jr|jjddd|jdS)N)rLrPrY _exit_actions)rQrrrrU s z profile.stopcCs|jr|jr|jjddd|j}|jd7_|j|j|_|jtjkr|tjkrVnf|tjkrzt d|j |j nB|tj krt d|j n&|tj kst|j |jr|j|n|jtjkr@|tjkr|jn\|tjkrnP|tj kr t d|j n2|tj kst|j |jr6|j||jn|jtj tj gkr|tjkrr|j|j n^|tjkr|j nH|tj krn:|tj kst|j |jr|j||j|j |jrtjdt|j|_|jjdS)zP Signals the profiler that the next profiling step has started. Nr z+Incorrect schedule: WARMUP followed by NONEz+Incorrect schedule: RECORD followed by NONEz-Incorrect schedule: RECORD followed by WARMUPz ProfilerStep#)rLrPrYrNrMr"r rrr _start_trace _stop_tracerrrr@ _start_warmupr5r[r0rT)rQZ prev_actionrrrrsd                    z profile.step)r)cCs|js t|jdrtjdddd}|j|jj|j}t|j(}t j|d}|j |WdQRXWdQRXt j |j|S|jj|SdS)zD Exports the collected trace in Chrome JSON format. z.gzzw+tz.jsonF)suffixdeletewtN) rOrendswithtempfileNamedTemporaryFilecloser3nameopengzip writelinesr7rJ)rQr)fpZretvalueZfinZfoutrrrr3Ls    zprofile.export_chrome_traceself_cpu_time_total)r)metriccCs|js t|jj||S)aSave stack traces in a file in a format suitable for visualization. Args: path (str): save stacks file to this location; metric (str): metric to use: "self_cpu_time_total" or "self_cuda_time_total" .. note:: Example of using FlameGraph tool: - git clone https://github.com/brendangregg/FlameGraph - cd FlameGraph - ./flamegraph.pl --title "CPU time" --countname "us." profiler.stacks > perf_viz.svg )rOr export_stacks)rQr)rmrrrrn]s zprofile.export_stacksr)group_by_input_shapegroup_by_stack_ncCs|js t|jj||S)aAverages events, grouping them by operator name and (optionally) input shapes and stack. .. note:: To use shape/stack functionality make sure to set record_shapes/with_stack when creating profiler context manager. )rOr key_averages)rQrorprrrrqns zprofile.key_averagescCs|js t|jjS)z Returns the list of unaggregated profiler events, to be used in the trace callback or after the profiling is finished )rOrZfunction_events)rQrrreventsys zprofile.events)keyvaluecCs&d|jddd}tjj||dS)zo Adds a user defined metadata with a string key and a string value into the trace file "z\"N)replacer;r<_add_metadata_json)rQrsrtZ wrapped_valuerrr add_metadataszprofile.add_metadatacCstjj||dS)zs Adds a user defined metadata with a string key and a valid json value into the trace file N)r;r<rw)rQrsrtrrradd_metadata_jsonszprofile.add_metadata_jsoncCs:ddlj}|j s|j r"dS|j|j|jdS)Nr)backendZrankZ world_size)Ztorch.distributedZ distributedZ is_availableZis_initialized get_backendZget_rankZget_world_size)rQdistrrr_get_distributed_infos  zprofile._get_distributed_infocCs<|jtjkr|jn"|jtjtjgkr8|j|jdS)N)rNr rr_rrr])rQrrrrZs   zprofile._enter_actionscCsL|jtjkr|j|jn*|jtjtjgkrH|j|jrH|j|dS)N)rNr rr]r^rrr@)rQrrrr\s  zprofile._exit_actionsc CsDtjtj|jktj|jk|j|j|j|j |j dd|_ |j j dS)NT)rFZuse_cpurArDrBrCrEZ use_kineto) r5r>r rIr?ZCPUrArDrBrCrErOZ_prepare_trace)rQrrrr_s   zprofile._start_warmupcCs@|jdk st|jjtr<|j}|r<|jdtj|dS)NZdistributedInfo)rOrr]rr}ryjsondumps)rQZ dist_inforrrr]s  zprofile._start_tracecCs"|jdk st|jjddddS)N)rOrrY)rQrrrr^szprofile._stop_trace)rl)Fr)rrrrrrr rr!r rboolrRrTrYrSrUrr0r3rnrqrrrxryr}rZr\r_r]r^rrrrr>gs6iJ!<     r>)NF)rir~r7rdenumrtypingrrrrwarningsrr;Ztorch.autograd.profilerr<rOr5Ztorch.autogradrr r r!r"r$r0rr:r=objectr>rrrrs