File: stackcollapse_nsys.py

package info (click to toggle)
nvidia-cuda-toolkit 12.4.1-3
  • links: PTS, VCS
  • area: non-free
  • in suites: forky, sid
  • size: 18,505,836 kB
  • sloc: ansic: 203,477; cpp: 64,769; python: 34,699; javascript: 22,006; xml: 13,410; makefile: 3,085; sh: 2,343; perl: 352
file content (448 lines) | stat: -rwxr-xr-x 14,988 bytes parent folder | download | duplicates (9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
#! /usr/bin/env python3

# SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation and any modifications thereto. Any use, reproduction,
# disclosure or distribution of this material and related documentation
# without an express license agreement from NVIDIA CORPORATION or
# its affiliates is strictly prohibited.

import argparse
import os
import re
import sqlite3
import subprocess
import sys
import tempfile
from pathlib import Path

NSYS_CLI_BINARY_NAME = "nsys.exe" if os.name == "nt" else "nsys"

SELECT_CALLCHAIN_TABLE_EXISTENCE = """
SELECT
    count(name)
FROM
    sqlite_master 
WHERE 
    type='table' AND name = 'sampling_callchains'
COLLATE NOCASE
"""

SELECT_CALLSTACKS = """
WITH usage(id, cycles) AS 
(
    SELECT
        sc.id,
        SUM(cpucycles) AS cycles 
    FROM
        sampling_callchains sc 
        LEFT JOIN
            composite_events se 
            ON sc.id == se.id 
    WHERE
        sc.stackdepth == 0 
    GROUP BY
        sc.symbol,
        sc.module 
)
SELECT
    GROUP_CONCAT(value, ';') || ' ' || cycles 
FROM
    (
        SELECT
            si.value,
            sc.id,
            u.cycles 
        FROM
            usage u 
            INNER JOIN
                sampling_callchains sc 
                ON sc.id = u.id 
            INNER JOIN
                stringids AS si 
                ON sc.symbol == si.id 
            INNER JOIN
                stringids AS sm 
                ON sc.module == sm.id 
        WHERE
            si.value <> '[Max depth]' 
        ORDER BY
            stackdepth DESC 
    )
GROUP BY
    id 
ORDER BY
    cycles DESC
"""


REGEX_TYPE_MODIFIER = "(?:(?:(?:unsigned)|(?:signed)|(?:long)) *){0,2}"
REGEX_TYPE_SPECIFIER = "[ \*&]*(?:const)?[ \*&]*"
REGEX_IDENTIFIER = "(?:(?:[^\W\d]|~)(?:[^\W]|[<>\*&\[\]])*)"

REGEX_SPECIAL_IDENTIFIERS = "(?:\(anonymous namespace\))|(?:\{lambda\(\)#?\d*\})|(?:decltype ?\(\))"

REGEX_NON_SPEC_TYPE_IDENTIFIER = "(?:{type_modifier}{identifier})".format(
    type_modifier=REGEX_TYPE_MODIFIER, identifier=REGEX_IDENTIFIER
)
REGEX_QUALIFIED_NON_SPEC_TYPE_IDENTIFIER = (
    "{non_spec_type_id}{type_specifier}(?:::{non_spec_type_id}{type_specifier})*(?:(?:::)?)?".format(
        non_spec_type_id=REGEX_NON_SPEC_TYPE_IDENTIFIER, type_specifier=REGEX_TYPE_SPECIFIER
    )
)

OVERLOADED_OPERATORS_LIST = [
    "+",
    "-",
    "*",
    "/",
    "%",
    "^",
    "&",
    "|",
    "~",
    "!",
    "=",
    "<",
    ">",
    "+=",
    "-=",
    "*=",
    "/=",
    "%=",
    "^=",
    "&=",
    "|=",
    "<<",
    ">>",
    "<<=",
    ">>=",
    "==",
    "!=",
    "<=",
    ">=",
    "&&",
    "||",
    "++",
    "--",
    ",",
    "->*",
    "->",
    "()",
    "[",
    "]",
    "new",
    "delete",
    "new[]",
    "delete[]",
]

REGEX_OVERLOADED_OPERATORS_LIST = [re.escape(op) for op in OVERLOADED_OPERATORS_LIST]
REGEX_OPERATOR_OVERLOADS = "(?:" + ")|(?:".join(REGEX_OVERLOADED_OPERATORS_LIST) + ")"
REGEX_OPERATOR_IDENTIFIER = "(?:operator *(?:<>)?(?:{type_id}|(?:{operator_overloads}))?(?:<>)?)".format(
    type_id=REGEX_QUALIFIED_NON_SPEC_TYPE_IDENTIFIER, operator_overloads=REGEX_OPERATOR_OVERLOADS
)

REGEX_TYPE_IDENTIFIER = "(?:{type_modifier}{identifier}|{special_ids}|{operator_id})".format(
    type_modifier=REGEX_TYPE_MODIFIER,
    identifier=REGEX_IDENTIFIER,
    special_ids=REGEX_SPECIAL_IDENTIFIERS,
    operator_id=REGEX_OPERATOR_IDENTIFIER,
)
REGEX_QUALIFIED_TYPE_IDENTIFIER = "{type_id}{type_specifier}(?:::{type_id}{type_specifier})*(?:(?:::)?)?".format(
    type_id=REGEX_TYPE_IDENTIFIER, type_specifier=REGEX_TYPE_SPECIFIER
)

FUNCTION_NAME_DELIMITER = "(?:[ &\*>])"
FUNCTION_ARGUMENTS = "(?:\(\))?"

APPROXIMATE_FUNCTION_STRING = "^((?:(?:{type_specifier}{func_name_delimiter})?{qualified_type_id}(?:{func_name_delimiter}{type_specifier})?{func_name_delimiter}))?({qualified_type_id})(?:{func_arg}{type_specifier})?$".format(
    qualified_type_id=REGEX_QUALIFIED_TYPE_IDENTIFIER,
    func_name_delimiter=FUNCTION_NAME_DELIMITER,
    func_arg=FUNCTION_ARGUMENTS,
    type_specifier=REGEX_TYPE_SPECIFIER,
)
APPROXIMATE_FUNCTION_REGEX = re.compile(APPROXIMATE_FUNCTION_STRING, re.U)


def collapse_parentheses(str_, left_p, right_p):
    """Collapse everything between matching left_p and right_p (including collapsing of nested matches)

    Args:
        str_ (string): String to collapse.
        left_p (string): Left delimiter
        right_p (string): Right delimiter

    Returns:
        string: Collapsed string.
    """
    shortened_str = ""
    inner_value = ""
    parentheses_lvl = 0
    for c in str_:
        if parentheses_lvl == 0 or (parentheses_lvl == 1 and c == right_p):
            if c == right_p:
                if inner_value == "anonymous namespace":
                    shortened_str += inner_value
                inner_value = ""
            shortened_str += c

        if c == right_p:
            parentheses_lvl -= 1
        if parentheses_lvl == 1:
            inner_value += c
        if c == left_p:
            parentheses_lvl += 1
    return shortened_str


def shorten_function_name_approximately(full_function_def):
    """Try to shorten function name (in some cases shortening may fail and return the original filename).

    Args:
        full_function_def (string): Original filename.

    Returns:
        string: Shortened or full function name.
    """
    prepared_function_def = collapse_parentheses(full_function_def, "(", ")")
    prepared_function_def = collapse_parentheses(prepared_function_def, "<", ">")
    prepared_function_def = collapse_parentheses(prepared_function_def, "[", "]")
    prepared_function_def = re.sub(r"[\n\t\s]+", " ", prepared_function_def)
    prepared_function_def = re.sub(r"([ \*\&>\}\)\]])const::", r"\1::", prepared_function_def)
    prepared_function_def = re.sub(r"\(\) *::", "::", prepared_function_def)
    m = re.search(APPROXIMATE_FUNCTION_REGEX, prepared_function_def)
    # may be a function address or a complex function name
    if not m:
        return full_function_def

    function_name = ""
    if m.group(1) and m.group(1).find("operator") != -1 and m.group(2):
        function_name = m.group(1) + " " + m.group(2)
        function_name = re.sub(r"[\n\t\s]+", " ", function_name)
    elif m.group(2):
        function_name = m.group(2)
    else:
        function_name = full_function_def
    return function_name


def shorten_func_names_approximately(flamegraph_row, full_function_names):
    """Try to shorten function names (in some cases shortening may fail and return the original filenames).

    Args:
        flamegraph_row (string): String suitable for flamegraph with original function names
        full_function_names (string): Use full function names with return type, arguments and expanded templates, if available.

    Returns:
        list[string]: List of shortened or full function names.
    """
    if full_function_names:
        return flamegraph_row
    flamegraph_parts = flamegraph_row.split(" ")
    if len(flamegraph_parts) < 2:
        return flamegraph_row
    cycles_cnt = flamegraph_parts[-1]
    full_function_defs = " ".join(flamegraph_parts[:-1]).split(";")
    full_function_defs_wo_recursive = []
    if len(full_function_defs) > 1:
        prev_val = full_function_defs[0]
        for val in full_function_defs[1:]:
            if val != prev_val:
                full_function_defs_wo_recursive.append(val)
    else:
        full_function_defs_wo_recursive = full_function_defs

    flamegraph_row = ";".join(
        [
            shorten_function_name_approximately(full_function_def)
            for full_function_def in full_function_defs_wo_recursive
        ]
    )

    flamegraph_row += " {}".format(cycles_cnt)

    return flamegraph_row


def check_cpu_samples_exists(conn):
    """Check if CPU callstacks exist in SQLite database

    Args:
        conn: SQLite database connection

    Returns:
        bool: True if CPU callstacks exist in SQLite database
    """
    c = conn.cursor()
    c.execute(SELECT_CALLCHAIN_TABLE_EXISTENCE)
    if c.fetchone()[0] == 1:
        return True

    return False


def convert_to_collapsed(sqlite_db_path, outfile_name, full_function_names):
    """Convert CPU callstacks from a SQLite database file to an output suitable for flamegraph.pl

    Args:
        sqlite_db_path (string): _description_
        outfile_name (string): Path to a results file. If None or empty an output is written to stdout.
        full_function_names (bool): Use full function names with return type, arguments and expanded templates, if available.
    """
    with sqlite3.connect(sqlite_db_path) as conn:
        if not check_cpu_samples_exists(conn):
            sys.stderr.write("Report does not contain CPU samples. Folded output will not be generated.\n")
            return

        c = conn.cursor()
        c.execute(SELECT_CALLSTACKS)
        if outfile_name:
            with open(outfile_name, "w", encoding="utf-8") as outfile:
                for row in c:
                    outfile.write(shorten_func_names_approximately(row[0], full_function_names) + "\n")
        else:
            for row in c:
                print(shorten_func_names_approximately(row[0], full_function_names))


def export_to_sqlite(nsys_target_bin_path, nsys_rep_path, sqlite_db_path):
    """Export Nsight Systems report to a SQLite database file

    Args:
        nsys_target_bin_path (string): Path to a target Nsight Systems binary.
        nsys_rep_path (string): Path to a Nsight Systems report.
        sqlite_db_path (string): Path to a SQLite database file.

    Raises:
        ChildProcessError
    """
    popen = subprocess.Popen([nsys_target_bin_path, "export", "--type", "sqlite", "-o", sqlite_db_path, nsys_rep_path])
    stdout, stderr = popen.communicate()
    exit_code = popen.wait()
    if exit_code != 0:
        err_str = "Nsight Systems CLI export failed with exit code {}: {}\n{}".format(
            exit_code, (stdout or b"").decode("utf-8", "ignore"), (stderr or b"").decode("utf-8", "ignore")
        )
        print(err_str)
        raise ChildProcessError(err_str)


def get_arm_type_target_path_part(arch):
    """Get the folder name part identifying the current supported armv8 arch (SBSA or tegra)

    Args:
        arch (string): Current architecture

    Returns:
        string: "-sbsa", "-tegra" or ""
    """
    if arch != "armv8":
        return ""

    tegra_check_popen = subprocess.Popen(
        "find /proc/device-tree/ -maxdepth 1 -name 'tegra*' || echo ERROR",
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
    )
    tegra_check_output, _ = tegra_check_popen.communicate()
    if (tegra_check_output or b"").decode("utf-8", "ignore").startswith("/"):
        return "-tegra"

    sbsa_check_popen = subprocess.Popen(
        "lsmod | grep 'nvidia' || echo ERROR", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
    )
    sbsa_check_output, _ = sbsa_check_popen.communicate()
    if (sbsa_check_output or b"").decode("utf-8", "ignore").startswith("nvidia"):
        return "-sbsa"

    return ""


def get_target_bin_path(nsys_target_bin_path_arg):
    """Try to retrieve a Nsight Systems CLI path from argument (if it exists) or from the default installation path.
    Args:
        nsys_target_bin_path_arg (string): User path to the Nsight Systems CLI binary

    Raises:
        FileNotFoundError: Nsight Systems CLI not found

    Returns:
        string: Path to the Nsight Systems CLI binary.
    """

    if nsys_target_bin_path_arg:
        nsys_target_search_path = Path(nsys_target_bin_path_arg) / NSYS_CLI_BINARY_NAME
        if nsys_target_search_path.is_file():
            return str(nsys_target_search_path)

    nsys_host_path = Path(__file__).resolve().parent.parent.parent
    nsys_host_folder_name = nsys_host_path.name
    nsys_host_folder_name_parts = nsys_host_folder_name.split("-")
    nsys_target_path = None
    if len(nsys_host_folder_name_parts) == 3:
        host_os = nsys_host_folder_name_parts[1]
        # assume actual host architecture
        host_arch = nsys_host_folder_name_parts[2]
        nsys_target_folder_name = "target-" + host_os + get_arm_type_target_path_part(host_arch) + "-" + host_arch
        nsys_target_search_path = nsys_host_path.parent / nsys_target_folder_name / NSYS_CLI_BINARY_NAME
        if nsys_target_search_path.is_file():
            nsys_target_path = str(nsys_target_search_path)

    if not nsys_target_path:
        raise FileNotFoundError(
            "Nsight Systems CLI binary (nsys) not found."
            'Use "--nsys" argument to set an Nsight Systems CLI binary path.'
        )
    return nsys_target_path


def collapse_callstacks(nsys_target_bin_path, nsys_rep_path, outfile_name, full_function_names):
    """Export CPU callstacks from a Nsight Systems report file to a SQLite database and
    convert them to an output suitable for flamegraph.pl

    Args:
        nsys_target_bin_path (string): Path to a Nsight Systems CLI directory.
        nsys_rep_path (string): Path to a Nsight Systems report.
        outfile_name (string): Path to a results file. If None or empty an output is written to stdout.
        full_function_names (bool): Use full function names with return type, arguments and expanded templates, if available.
    """
    with tempfile.TemporaryDirectory() as tmp_dir:
        sqlite_db_path = os.path.join(tmp_dir, "db.sqlite")
        export_to_sqlite(nsys_target_bin_path, nsys_rep_path, sqlite_db_path)
        convert_to_collapsed(sqlite_db_path, outfile_name, full_function_names)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Script for parsing Nsight Systems report files containing CPU call stacks and producing an output"
        "suitable for flamegraph.pl."
    )
    parser.add_argument("--nsys", action="store", help="Path to the Nsight Systems CLI directory", required=False)
    parser.add_argument(
        "-o",
        "--out",
        action="store",
        help="Path to the output file name (by default an output is written to stdout)",
    )
    parser.add_argument(
        "--full_function_names",
        default=False,
        action="store_true",
        help="Use full function names with return type, arguments and expanded "
        "templates, if available (default: false).",
    )
    parser.add_argument("nsys_rep_file", help="Nsight Systems report file path")
    args = parser.parse_args()

    custom_outfile_name = None
    if "out" in args and args.out:
        custom_outfile_name = args.out

    collapse_callstacks(
        get_target_bin_path(args.nsys), args.nsys_rep_file, custom_outfile_name, args.full_function_names
    )