
    biE4                         d dl mZmZ d dlZd dlmZ d dlZd dlZd dlZd dl	m
Z
mZmZ d dlmZ  G d de      Z G d d	e      Z G d
 de      ZeedZy)    )ABCabstractmethodN)Path)ListOptionalSet)	ServerAppc                   d   e Zd Z G d de      Z G d de      ZdededefdZed	efd
       Z	ed	e
e   fd       Zed	efd       Zeded	e
e   fd       Zed	ee   fd       Zeded	e
e   fd       Zed	efd       Zed	efd       Zed        Zed        Zedefd       Zdee   fdZy)
NsightToolc                       e Zd Zy)NsightTool.VersionErrorN__name__
__module____qualname__     `/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jupyterlab_nvidia_nsight/nsight_tools.pyVersionErrorr          r   r   c                       e Zd Zy)NsightTool.ArgumentErrorNr   r   r   r   ArgumentErrorr      r   r   r   	kernel_idinstallation_pathargsc                 4   || _         || _        t        j                  |      | _        t        j                  | j                         | j                               | _	        t        j                  | j                         | j                               | _        y )Npath)r   r   shlexsplitr   shutilwhichtarget_exe_nametarget_exe_dir
target_exehost_exe_namehost_exe_dirhost_exe)selfr   r   r   s       r   __init__zNsightTool.__init__   si    "!2KK%	 ,,t';';'=DDWDWDYZT%7%7%9@Q@Q@STr   returnc                      y)z9
        Returns the name of the tool executable
        Nr   r*   s    r   r$   zNsightTool.target_exe_name#       r   c                      y)zK
        Returns the path to the directory of the tool executable.
        Nr   r.   s    r   r%   zNsightTool.target_exe_dir)   r/   r   c                      y)z@
        Returns the name of the tool's host executable
        Nr   r.   s    r   r'   zNsightTool.host_exe_name/   r/   r   c                      y)zR
        Returns the path to the directory of the tool's host executable.
        Nr   )r*   r   s     r   r(   zNsightTool.host_exe_dir5   r/   r   c                      y)zR
        Returns the tool command to inject to the kernel launch command.
        Nr   r.   s    r   launch_kernel_cmdzNsightTool.launch_kernel_cmd;   r/   r   versionc                      y)a9  
        Set and validate the version of the tool.
        The version argument is the output of the tool executable when called with --version.
        The optional returned string is a warning that should be displayed to the user.
        Raises NsightTool.VersionError if the version is not supported.
        Nr   r*   r5   s     r   set_versionzNsightTool.set_versionA   r/   r   c                      y)z[
        Returns the Python code to start the tool (to be executed by the kernel).
        Nr   r*   kwargss     r   get_start_codezNsightTool.get_start_codeJ   r/   r   c                      y)zZ
        Returns the Python code to stop the tool (to be executed by the kernel).
        Nr   r:   s     r   get_stop_codezNsightTool.get_stop_codeP   r/   r   c                      y Nr   r.   s    r   cleanupzNsightTool.cleanupV   s    r   c                      y)zY
        Returns a set of options that are not allowed to be used with the tool.
        Nr   r.   s    r   get_not_allowed_optionsz"NsightTool.get_not_allowed_optionsZ   r/   r   r   c                     t        |       j                         } | j                         s*t        t        j                         j
                        | z  } | j                         S r@   )r   
expanduseris_absoluter	   instanceroot_dirresolver   s    r   normalize_pathzNsightTool.normalize_path`   sJ    Dz$$&!	**,556=D||~r   c                 L    || j                         z  }|rdt        |       dS y)Nz=The following options are not supported by Nsight extension: .  )rC   list)r*   r   not_alloweds      r   _check_supported_argsz NsightTool._check_supported_argsg   s5    T99;;R$%R) )r   N)r   r   r   	Exceptionr   r   strr+   r   r$   r   r   r%   r'   r(   r   r4   r8   r<   r>   rA   rC   staticmethodrJ   r   rP   r   r   r   r   r      s   y 	 U# U# US U   
   
 s  
 c htn  
 49  
 3 8C=   #  
   
    
 S  #c( r   r   c                        e Zd ZdZdZdZ fdZdefdZde	e
   fdZdefdZde	e
   fd	Zdee   fd
ZdefdZdededefdZdefdZd Zd Z xZS )NsysProfilerztarget-linux-x64zhost-linux-x64z2024.1.1c                     t        |   |i | d | _        | j                  t	        | j
                              }|rt        j                  |      y r@   )superr+   requested_stats_report_pathrP   setr   r   r   )r*   r   r;   error_message	__class__s       r   r+   zNsysProfiler.__init__v   sN    $)&);?(223tyy>B**=99 r   r,   c                      y)Nnsysr   r.   s    r   r$   zNsysProfiler.target_exe_name}   s    r   c                 `    | j                   r"t        | j                         | j                  z  S y r@   )r   r   nsys_target_dir_namer.   s    r   r%   zNsysProfiler.target_exe_dir   s,    !!../$2K2KKK "r   c                      y)Nznsys-uir   r.   s    r   r'   zNsysProfiler.host_exe_name   s    r   c                 `    | j                   r"t        | j                         | j                  z  S y r@   )r   r   nsys_host_dir_namer.   s    r   r(   zNsysProfiler.host_exe_dir   s,    !!../$2I2III "r   c                 T    | j                   dd| j                   g| j                  z   S )Nlaunchz
--session=)r&   r   r   r.   s    r   r4   zNsysProfiler.launch_kernel_cmd   s(    Z7G+HIDIIUUr   r5   c           	      |   |j                         d   }|t        j                         k7  r|j                  d      d   }t        t	        t
        |j                  d                  t        t	        t
        | j                  j                  d                  k  r"| j                  d| j                   d| d      y y )N-r   .z+jupyterlab-nvidia-nsight requires nsys >= "z". Found: "")r!   socketgethostnametuplemapintmin_supported_versionr   r7   s     r   r8   zNsysProfiler.set_version   s    --/"%f((**mmC(+GSgmmC012U3sDD^D^DdDdehDi;j5kk''*UVZVpVpUq r44;9A)? @ @ l +r   report_pathr   c           	         | j                  t        t        j                  |                  }|r| j	                  |      | j                  |      }|j                  j                  dd       t        j                  |      }d|v s>d|v rAt        |      |j                  d      dz   kD  r!||j                  d      dz      dk(  r|| _
        d| j                   d| j                   d	| d
| d	S )NTparentsexist_okz--stats=truez--stats   truez
subprocess.check_call(
    ['z', 'start', '--session=z', '--output=z'] + z)
)rP   rY   r    r!   r   rJ   parentmkdirlenindexrX   r&   r   )r*   rp   r   rZ   s       r   r<   zNsysProfiler.get_start_code   s    223u{{47H3IJ$$]33))+6   ={{4 T!#d)djj.Ca.G"GDQUQ[Q[\eQfijQjLkouLu/:D,.t~~.>mK=X]^b]c d 	r   c                     d| j                    d| j                   d}| j                  r-|d| j                   d| j                    d| j                   dz  }d | _        |S )Nz%subprocess.check_call(
            ['z', 'stop', '--session=z'], stderr=subprocess.PIPE)
z
if pathlib.Path('z2').exists():
    subprocess.check_call(
        ['z', 'stats', 'z', '--force-export=true'])
)r&   r   rX   )r*   codes     r   r>   zNsysProfiler.get_stop_code   s    5dnn5E F ++ 223 4??
=)I)I(J K D
 ,0(r   c                      y r@   r   r.   s    r   rA   zNsysProfiler.cleanup   s    r   c                 
    h dS )N>	   -x--output	--session--session-new--stop-on-exit--hotkey-capture-h-o--helpr   r.   s    r   rC   z$NsysProfiler.get_not_allowed_options   s    
 	
r   )r   r   r   r_   rb   ro   r+   rR   r$   r   r   r%   r'   r(   r   r4   r8   r<   r>   rA   rC   __classcell__r[   s   @r   rU   rU   o   s     .)&: L Ls Jhtn JV49 V@3 @# S S "s 
r   rU   c                        e Zd ZdZdZ fdZdefdZdee	   fdZ
defdZdee	   fdZdee   fd	Zd
efdZdedefdZdedededefdZd Zd Zdee   fdZd Zh dZh dZ xZS )NcuProfilerJupyterLabNvidiaNsightz2024.3c                     t        |   |i | | j                          d| _        t	        j
                         | _        t        | j                  j                        dz  | _	        t        | j                  j                        dz  | _
        y )NTzreport.ncu-repztmp_report.ncu-rep)rW   r+   validate_enable_argsncu_ui_supporttempfileTemporaryDirectorytmp_dirr   namerp   tmp_report_path)r*   r   r;   r[   s      r   r+   zNcuProfiler.__init__   su    $)&)!!#"  224 1 125EE#DLL$5$569MMr   r,   c                      y)Nncur   r.   s    r   r$   zNcuProfiler.target_exe_name   s    r   c                 F    | j                   rt        | j                         S y r@   )r   r   r.   s    r   r%   zNcuProfiler.target_exe_dir   s!    !!..// "r   c                      y)Nzncu-uir   r.   s    r   r'   zNcuProfiler.host_exe_name   s    r   c                 "    | j                         S r@   )r%   r.   s    r   r(   zNcuProfiler.host_exe_dir   s    ""$$r   c                 ~    | j                   dt        | j                        d| j                   dg| j                  z   S )Nr   --nvtx-excludez@exclude)r&   rR   rp   nvtx_domainr   r.   s    r   r4   zNcuProfiler.launch_kernel_cmd   sE    c$**+ T%5%5$6h"?ACG99M 	Mr   r5   c           	      R   |j                         j                         d   j                         d   }t        t	        t
        |j                  d                  t        t	        t
        | j                  j                  d                  k  rd| _        d| j                   d| dS y )Nrf   ru   rh   Fz*jupyterlab-nvidia-nsight requires ncu >= "z" for full support.
Found: "z". Using console output only.)strip
splitlinesr!   rl   rm   rn   ro   r   r7   s     r   r8   zNcuProfiler.set_version   s    --/,,.r288:1=S'--,-.s3@Z@Z@`@`ad@e7f1gg"'DA$B\B\A] ^			.2 2 hr   r   c                 ^    | j                  t        t        j                  |                   y r@   )validate_start_argsrY   r    r!   )r*   r   s     r   r<   zNcuProfiler.get_start_code   s      U[[%6!78r   rp   range_idc                    | j                   j                         sy| j                  s0d| j                   d| j                    d| j                   d| d| dS | j                  |      }|j                  j                  dd	       d
| j                   d| j                    d| j                   d| d| j                   d| j                   d| j                   d| d| d| j                   d| j                   d| dS )NrM   z
subprocess.check_call(
    'z -i z --nvtx-include @ z',
    shell=True)
Trr   z
# First, filter from the full report the last cell(s) profiling results.
# This prevents flag conflict when the user uses "--nvtx-include".
subprocess.check_call(
    ['z
', '-i', 'z',
     '--nvtx-include', 'z
', '-o', 'z', '-f'],
    stdout=subprocess.DEVNULL)

# Export the new report, using the CLI flags provided by the user.
subprocess.check_call(
    'z -o z -f --log-file stderr z',
    shell=True)

# Generate console output of the new report, using the CLI flags provided by the user.
subprocess.check_call('z', shell=True)
)	rp   existsr   r&   r   rJ   rw   rx   r   )r*   rp   r   r   s       r   r>   zNcuProfiler.get_stop_code   s:   &&(""
ood4++,,<T=M=M<NaPXzYZ[_Z` a  ))+6   = z$"2"2!3 4))*!H:Z@T@T?U V
 ood4//0[MAWX\W] ^ (T-A-A,B!D6 J 	r   c                 8    | j                   j                          y r@   )r   rA   r.   s    r   rA   zNcuProfiler.cleanup
  s    r   c                    d| j                   vr| j                   j                  d       t        | j                         }| j                  |      }|| j                  z  }|r|dt        |       dz  }|r| j                  |      y )Nz--nvtxzTThe following options can be used only when profiling cells, not when enabling ncu: rL   )r   appendrY   rP   NOT_ALLOWED_OPTIONS_ON_ENABLErN   r   )r*   r   rZ   not_allowed_on_enables       r   r   z NcuProfiler.validate_enable_args  s    499$IIX&499~2248 $t'I'I I  **./D*E)FbJ JM $$]33 r   c                     | j                  |      }|| j                  z  }|r|dt        t        |            z   z  }|r| j	                  |      y )Nz>The following options can be used only when enabling NCU tool )rP   NOT_ALLOWED_OPTIONS_ON_STARTrR   rN   r   )r*   r   rZ   not_allowed_on_starts       r   r   zNcuProfiler.validate_start_args  sa    2248#d&G&GG]d/012 2M $$]33 r   c                 
    h dS )N>&   -f-i-v--kill--mode--chips--quiet--export--import	--version
--hostname
--log-file--list-sets--list-chips--list-rules--null-stdin--open-in-ui--config-file--replay-mode--list-metrics--range-filter--list-sections--query-metrics--app-replay-mode--check-exit-code--force-overwrite--app-replay-match--config-file-path--app-replay-buffer--profile-from-start--query-metrics-mode--range-replay-options--rename-kernels-export--section-folder-restore--query-metrics-collectionr   r   r   r   r.   s    r   rC   z#NcuProfiler.get_not_allowed_options'  s    "
 "	
r   >   -c-k-s--csv--page	--devices
--print-fp--kernel-id--filter-mode--kernel-name--launch-skip--print-units--launch-count--nvtx-include--print-source--print-details--print-summary--rename-kernels--kernel-name-base--print-kernel-base--print-metric-name--print-nvtx-rename--print-rule-details--rename-kernels-path--resolve-source-file--disable-extra-suffixes--print-metric-instances--launch-skip-before-match--print-metric-attributionr   >   -p--set--port--rule	--metrics	--section	--verbose--call-stack--apply-rules--cache-control--clock-control--import-source--support-32bit--section-folder--source-folders--call-stack-type--graph-profiling--max-connections--preload-library--target-processes--injection-path-32--injection-path-64--pm-sampling-interval--pm-sampling-max-passes--warp-sampling-interval--pm-sampling-buffer-size--target-processes-filter--section-folder-recursive--warp-sampling-max-passes--warp-sampling-buffer-size--disable-profiler-start-stop)r   r   r   r   ro   r+   rR   r$   r   r   r%   r'   r(   r   r4   r8   r<   r>   rA   r   r   r   rC   r   r   r   r   s   @r   r   r      s    *K$N 0 0s %htn %M49 M
23 293 93 9 C 3 3 <4	4C 	4#
J%!<$ r   r   )r]   r   )abcr   r   r"   pathlibr   r   r    rj   typingr   r   r   jupyter_server.serverappr	   r   rU   r   toolsr   r   r   <module>r     s^    $      & & .W WtP
: P
fG* GV 	r   