okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221check_cuda_spills: sm_89 baseline for the prefill, qwen35, mmq and pf_own libraries3f0f7deff

main
44.1 KiB686 linesraw
1#!/usr/bin/env python3
2"""Check that no release CUDA kernel spills registers or keeps a per-thread array in local memory.
3
4A kernel that needs more than its registers puts the rest in local memory - ptxas spills under register pressure, and
5a per-thread array it cannot promote to registers (indexed dynamically, or too large) - and every access there is a
6round trip to device memory through L1, in the hottest loops the engine has.  Nothing on the build machine says so:
7ptxas reports it only with -Xptxas -v, and a GPU is needed for a profiler to.  The compiler does write it into every
8object, though: `cuobjdump --dump-resource-usage` lists, per entry function and per SASS architecture, the registers,
9the stack frame (STACK: with CUDA 13 spills and local arrays both live there), the shared memory and the .local bytes
10(LOCAL), so this check reads the libraries that were built anyway and needs no GPU.
11
12Every kernel must have STACK 0 and LOCAL 0 on every sm_ in the library, unless ALLOWED below carries an entry for it
13with the measured allowance: the kernels that keep a per-thread array on purpose, one line each saying what the array
14is.  A byte over the allowance fails; a kernel that is not listed fails with any of either.  Kernels vendored from
15llama.cpp (ggml-cuda's mmq.cuh and quantize.cu, fetched at configure time and instantiated in strata_mmq, strata_kq
16and strata_mmq_w4a4) are skipped: they are the only kernels at global scope with no namespace at all, so a kernel
17whose demangled name carries no `::` is one of theirs, and they are llama.cpp's to gate - every kernel Strata wrote
18sits in `strata::` or in an anonymous namespace.  The report line counts what was skipped.
19
20  check_cuda_spills.py libstrata_kernels.a [libstrata_core.a ...]   (needs cuobjdump, and cu++filt or c++filt)
21  check_cuda_spills.py --list LIB ...   the full table (library, object, sm, REG, STACK, LOCAL, SHARED, kernel,
22                                        gated) as CSV, every kernel on every sm_ - the vendored ones too, gated 0 -
23                                        nothing judged: this is how the numbers in ALLOWED were produced
24  --cuobjdump PATH                      the toolkit's cuobjdump when bin/ is not on PATH (CMake passes it)
25
26Known violations (tools/cuda_spill_baseline.json): some kernels are over their allowance on the base and have not been fixed
27yet.  Raising ALLOWED for them would hide any later growth, so they are listed per architecture by exact instance name (the
28demangled name with its template arguments, without the parameter list) with the bytes measured, each with the reason
29"inherited, not yet fixed".  A violation that is such an instance, at or below its listed bytes, is counted as known and does not
30fail the check; a violation that is not listed (a new instance), and a listed instance above its bytes, fail.  The report line
31prints the known count.  An architecture with no baseline (sm_60: about 400 violations, nothing measured per instance) prints
32"no baseline for <sm>" and its violations fail as before.  --baseline FILE reads another baseline; --print-baseline prints the
33file's entries for the violations found (how the baseline was made).
34
35Exit 0 = clean (or only known violations), 1 = a new or grown violation, 2 = the baseline file cannot be read, 77 = cannot run
36here (cuobjdump missing, a library missing; ctest SKIP_RETURN_CODE).
37"""
38import argparse
39import csv
40import json
41import os
42import re
43import shutil
44import subprocess
45import sys
46
47# the known violations (see the docstring): per architecture, each inherited instance by exact name with its measured bytes
48BASELINE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cuda_spill_baseline.json")
49KNOWN_REASON = "inherited, not yet fixed"
50
51# 0.2.7 (f-027-gh-eng): re-measured on f-027-int with CUDA 13.0 for sm_120 (Windows, MSVC) and sm_86 (Linux, cuobjdump 12.9
52# reading the CUDA 13.0 objects); an allowance is only ever raised here, never lowered, and the entries that now read 0 with
53# CUDA 13.0 keep theirs (another toolkit may spill where this one does not).  New: the DFlash2 kernels gemm8_kernel and
54# rope_table_kernel (a kernel parameter struct indexed in a loop), native_gu_swiglu_kernel on sm_86.
55# Kernels with a stack frame at 011c9e60 (v0.2.2), measured with CUDA 13.1 (V13.1.80) for sm_86 and sm_120 (Release): the ones
56# that keep a per-thread array in local memory, and the ones ptxas spills.  Key: the demangled kernel name without its
57# template arguments and parameter list (namespace kept; matched exactly), so every instantiation of a template kernel
58# shares one entry.  Value: per sm_, the allowed (STACK, LOCAL) bytes - the measured maximum, so any growth fails; an
59# sm_ that is absent allows nothing.  The line above each entry says what the array is, or what spilled (ptxas -v:
60# spill stores / spill loads at the register count it settled on).  A spill is a finding, not a licence: the entries
61# document the state of 011c9e60 so the gate can hold the line from here.
62ALLOWED = {
63    # float values[V] (V = NE / 32 = 8): the lane's logits for the top-k selection (no spill)
64    "q36k::k_route_group": {"sm_86": (32, 0)},
65    # spill 4 B stores / 4 B loads at 64 registers under __launch_bounds__(256); its w[4] / o[4] stay in registers
66    "strata::kernels::native_down_amd_kernel": {"sm_120": (8, 0)},
67    # spill 12 / 12 at 80 registers under __launch_bounds__(256)
68    "strata::kernels::native_gu_amd_kernel": {"sm_120": (16, 0)},
69    # spill 12 / 24 (sm_86), 16 / 32 (sm_120) at 64 registers under __launch_bounds__(256), no local array
70    "strata::kernels::native_gu_fused_kernel": {"sm_120": (8, 0), "sm_86": (8, 0)},
71    # spill 8 / 4 at 48 registers (sm_86), 8 / 8 at 80 (sm_120) under __launch_bounds__(256), no local array
72    "strata::kernels::native_gu_lds_kernel": {"sm_120": (8, 0), "sm_86": (8, 0)},
73    # int32_t my[10]: the lane's selected expert ids (no spill)
74    "strata::kernels::route_resident_k": {"sm_86": (40, 0)},
75    # float a[HPT][32] (HPT = 3): the thread's score tile (no spill; sm_120 keeps it in 142 registers)
76    "strata::kernels::{anonymous}::attn_chunk_kernel": {"sm_86": (384, 0)},
77    # spill 4 / 4 at 64 registers under __launch_bounds__(THREADS = 256); its cc[NC] / kk[NC][8] / pp[NC][16] / acc[G]
78    # stay in registers
79    "strata::kernels::{anonymous}::attn_chunk_kernel_pre75": {"sm_86": (8, 0)},
80    # float qr[G][8] (G = 12): the thread's query rows (no spill; sm_120 keeps them in registers)
81    "strata::kernels::{anonymous}::attn_chunk_slots_kernel": {"sm_86": (384, 0)},
82    # spill 4 / 4 at 80 registers under __launch_bounds__(SCORE_WARPS * 32 = 256); its qr[NQ][IDX_HEADS] /
83    # qv[IDX_HEADS][8] stay in registers
84    "strata::kernels::{anonymous}::block_scores_rows_kernel": {"sm_120": (8, 0)},
85    # spill 4 / 4 at 80 registers under __launch_bounds__(256); its acc[8][TN] / qr[8] / kr[TN] stay in registers
86    "strata::kernels::{anonymous}::block_scores_simt_kernel": {"sm_86": (8, 0)},
87    # spill 92 / 288 (sm_86), 172 / 260 (sm_120) at the 64-register cap of __launch_bounds__(TK_T = 1024); its
88    # uint32_t key[PER] stays in registers
89    "strata::kernels::{anonymous}::block_topk_reg_kernel": {"sm_120": (88, 0), "sm_86": (96, 0)},
90    # the Runs parameter (src[4], dst[4], len[4], n) copied to the stack to index it with the run loop variable
91    # (no spill)
92    "strata::kernels::{anonymous}::copy_kernel": {"sm_120": (88, 0), "sm_86": (88, 0)},
93    # 16-byte stack frame on sm_86 and sm_120, no spill; per-thread array not located in the source
94    "strata::kernels::{anonymous}::dequant_gu_kernel": {"sm_120": (16, 0), "sm_86": (16, 0)},
95    # the TYPE 11 (Q3_K) instantiations: uint32_t aux[4], the block's unpacked scales (16 B); on sm_86 also the
96    # TYPE 14 (Q6_K) vectorised instantiation's T buf[32] flush buffer (64 B); no spill
97    # f-027-int, CUDA 13.0: sm_120 allowance raised from STACK 16 to 128 (measured)
98    "strata::kernels::{anonymous}::dequant_kernel": {"sm_120": (128, 0), "sm_86": (64, 0)},
99    # float s[R][NC]: the entry group's partial sums, plus spill 428 / 600 (sm_86), 200 / 328 (sm_120) at the
100    # 64-register cap of __launch_bounds__(256, STRATA_EXPDEC_MINB = 4)
101    "strata::kernels::{anonymous}::expdec_down_kernel": {"sm_120": (136, 0), "sm_86": (272, 0)},
102    # float s[R][NC] / s8[R][NC]: the entry group's partial sums, plus spill 60 / 92 (sm_86), 52 / 88 (sm_120) at the
103    # 64-register cap of __launch_bounds__(256, MINB)
104    # f-027-int, CUDA 13.0: sm_120 allowance raised from STACK 40 to 112 (measured)
105    "strata::kernels::{anonymous}::expdec_gu_kernel": {"sm_120": (112, 0), "sm_86": (56, 0)},
106    # the DBG instantiation only: the printf argument buffer, two ints (no spill)
107    "strata::kernels::{anonymous}::gdn_step_commit_kernel": {"sm_120": (8, 0), "sm_86": (8, 0)},
108    # spill 4 / 4 at 64 registers under __launch_bounds__(S * RG = 512), no local array (sm_120: no frame any more)
109    "strata::kernels::{anonymous}::gdn_step_norm_multi_kernel": {"sm_86": (8, 0)},
110    # on f-027-int (CUDA 13.0): a stack frame, measured; no spill or local array located in the source yet
111    "strata::kernels::{anonymous}::gemm8_kernel": {"sm_120": (136, 0), "sm_86": (104, 0)},
112    # float gw[HC] / ss[HC] (no spill)
113    "strata::kernels::{anonymous}::gr_down_kernel": {"sm_120": (16, 0)},
114    # spill 8 / 24 at 80 registers under __launch_bounds__(THREADS = 256); its acc[MAX_T] / s[MAX_T] / wv[TQ] stay in
115    # registers
116    "strata::kernels::{anonymous}::gr_down_multi_kernel": {"sm_86": (8, 0)},
117    # spill 4 / 8 at 128 registers under __launch_bounds__(THREADS = 256), no local array
118    "strata::kernels::{anonymous}::gr_down_q8_fast_kernel": {"sm_86": (8, 0)},
119    # spill 12 / 24 at 128 registers under __launch_bounds__(THREADS = 256), no local array (sm_120: 206 registers,
120    # no spill)
121    "strata::kernels::{anonymous}::gr_down_q8_kernel": {"sm_86": (16, 0)},
122    # spill 16 / 16 at 80 (sm_86) / 64 (sm_120) registers under __launch_bounds__(THREADS = 256); its acc[MAX_T] /
123    # s[MAX_T] stay in registers
124    "strata::kernels::{anonymous}::gr_down_staged_kernel": {"sm_120": (8, 0), "sm_86": (16, 0)},
125    # spill 12 / 8 at 48 registers under __launch_bounds__(THREADS = 256), no local array
126    "strata::kernels::{anonymous}::gr_down_v3_kernel": {"sm_86": (8, 0)},
127    # spill 16 / 48 at the 64-register cap of __launch_bounds__(THREADS = 256, 4); its mine[RPW] / rv[RPW] / wn[RPW] /
128    # bo[RPW] (RPW = 8) stay in registers
129    "strata::kernels::{anonymous}::gr_up75_kernel": {"sm_120": (16, 0)},
130    # spill 8 / 16 at 48 registers under __launch_bounds__(THREADS = 256), no local array
131    "strata::kernels::{anonymous}::gr_up_q8_fast_kernel": {"sm_86": (8, 0)},
132    # spill 4 / 4 at 40 registers under __launch_bounds__(THREADS = 256), no local array
133    "strata::kernels::{anonymous}::gr_up_v3_kernel": {"sm_120": (8, 0)},
134    # spill 4 / 4 at 48 registers under __launch_bounds__(256), no local array
135    "strata::kernels::{anonymous}::native_down_kernel": {"sm_86": (8, 0)},
136    # int off[GRP_NC] / float s[GRP_NC] (GRP_NC = 4): per-entry token offsets and partial sums, plus spill 16 / 16
137    # (sm_86), 12 / 12 (sm_120)
138    "strata::kernels::{anonymous}::native_down_multi_kernel": {"sm_120": (48, 0), "sm_86": (64, 0)},
139    # spill 4 / 4 at 80 (sm_86) / 48 (sm_120) registers under __launch_bounds__(256), no local array
140    "strata::kernels::{anonymous}::native_gu_kernel": {"sm_120": (8, 0), "sm_86": (8, 0)},
141    # const int off[1..4] / float s[1..4] per entry group; since v0.2.2 the 8-lane trellis rows (TG 144 / 145, STAGE_GRID)
142    # keep row_dot_160_sub8's float p[4][NC] too: 144 B at 77-80 registers with no spill, or 128 B with spill 28 / 32 at
143    # 48 (sm_86); the other instantiations spill 56 / 64 (sm_86), 52 / 64 (sm_120)
144    "strata::kernels::{anonymous}::native_gu_multi_kernel": {"sm_120": (112, 0), "sm_86": (144, 0)},
145    # const int off[1..3] / float a[1..3] / b[1..3] per entry group and gv[GRP_NC] / uv[GRP_NC], plus spill 88 / 140 at
146    # the 64-register cap of __launch_bounds__(512)
147    # f-027-int, CUDA 13.0: sm_120 allowance raised from STACK 64 to 72 (measured)
148    "strata::kernels::{anonymous}::native_gu_swiglu_kernel": {"sm_120": (72, 0), "sm_86": (8, 0)},
149    # float o[NC] plus spill 60 / 60 at 56 registers under __launch_bounds__(4 * WARP)
150    "strata::kernels::{anonymous}::native_mmvq_il_kernel": {"sm_120": (24, 0)},
151    # 16-byte stack frame on sm_86 and sm_120, no spill; per-thread array not located in the source
152    "strata::kernels::{anonymous}::pair_kernel": {"sm_120": (16, 0), "sm_86": (16, 0)},
153    # spill 24 / 24 at 168 registers under __launch_bounds__(THREADS = 128, 3); its qa[3][2][4] / x[2][2][2][4] stay in
154    # registers
155    # f-027-int, CUDA 13.0: sm_120 allowance raised from STACK 24 to 40 (measured)
156    "strata::kernels::{anonymous}::prompt_attn_i8v3_kernel": {"sm_120": (40, 0)},
157    # spill 4 / 12 at 72 registers under __launch_bounds__(THREADS = 128), no local array
158    "strata::kernels::{anonymous}::prompt_attn_kernel": {"sm_86": (8, 0)},
159    # on f-027-int (CUDA 13.0): a stack frame, measured; no spill or local array located in the source yet
160    "strata::kernels::{anonymous}::rope_table_kernel": {"sm_120": (32, 0), "sm_86": (32, 0)},
161    # float values[16]: the lane's 16 logits for the top-k selection (no spill)
162    "strata::kernels::{anonymous}::route": {"sm_86": (64, 0)},
163    # float values[16]: the lane's 16 logits for the top-k selection (no spill)
164    "strata::kernels::{anonymous}::route_multi": {"sm_86": (64, 0)},
165    # float p[16] / s[16]: s[] is cleared at the selected index (no spill)
166    "strata::kernels::{anonymous}::route_prior_k": {"sm_86": (64, 0)},
167    # float values[V] (V = 8): the lane's logits for the top-k selection (no spill)
168    "strata::kernels::{anonymous}::route_topk": {"sm_86": (32, 0)},
169    # const uint8_t* wr[RPW] / float s[RPW][GRP_NC]: per-row pointers and partial sums (no spill)
170    "strata::kernels::{anonymous}::s26_gu_l_kernel": {"sm_120": (32, 0), "sm_86": (32, 0)},
171    # spill 12 / 12 at 64 registers under __launch_bounds__(256); its wr[RPW] / s[RPW][GRP_NC] stay in registers
172    "strata::kernels::{anonymous}::s27_down_kernel": {"sm_86": (16, 0)},
173    # const uint8_t* wr[RPW] / float s[RPW][GRP_NC]: per-row pointers and partial sums; sm_120 also spills 20 / 20 at
174    # 80 registers
175    "strata::kernels::{anonymous}::s27_gu_kernel": {"sm_120": (32, 0), "sm_86": (32, 0)},
176    # spill 36 / 52 (sm_86), 32 / 32 (sm_120) at the 128-register cap of __launch_bounds__(THREADS = 512, 1); its q[8]
177    # / raw[5] / bq[4] / a[4] / d[4] stay in registers
178    "strata::prefill::fused::{anonymous}::native_kernel": {"sm_120": (32, 0), "sm_86": (32, 0)},
179    # the Qwen3.6 copy of the same kernels (moe_fused_iq_q36.cu includes moe_fused_iq.cu with the shape override and its namespace renamed): same source and
180    # instance parameters, so the same spill under the same register cap, no per-thread array found (an instance has the same STACK as its fused:: twin in 24 of 25 cases on
181    # sm_86 and 7 of 10 on sm_120, never more than 8 B apart).  Measured on f-p4-q36 7bc09fadf, CUDA 13.2 sm_120 (l620) and CUDA 12.9
182    # cuobjdump on CUDA 13.0 objects for sm_86 (z440): the maximum over 62 instances, which include the K-quant down instances <13 / 14, false, 2 / 4, 512>
183    "strata::prefill::fused_q36::{anonymous}::native_kernel": {"sm_120": (16, 0), "sm_86": (80, 0)},
184    # float x[GRW_PER] (GRW_PER = 10): the thread's rows for the norm (no spill)
185    "strata::prefill::{anonymous}::gr_write_cvec_norm_rs_kernel": {"sm_86": (40, 0)},
186    # float v[GRW_PER] (GRW_PER = 10): the thread's rows for the norm (no spill)
187    "strata::prefill::{anonymous}::gr_write_norm_rs_kernel": {"sm_86": (40, 0)},
188    # 32-byte stack frame on sm_86 and sm_120, no spill; per-thread array not located in the source
189    "strata::prefill::{anonymous}::rope_kernel": {"sm_120": (32, 0), "sm_86": (32, 0)},
190    # float v[REG] (REG = 16): the lane's logits for the top-k selection (no spill)
191    "strata::prefill::{anonymous}::route_kernel": {"sm_86": (64, 0)},
192    # 32-byte stack frame on sm_86 and sm_120, no spill; per-thread array not located in the source
193    "{anonymous}::k_attn_prep": {"sm_120": (32, 0), "sm_86": (32, 0)},
194}
195
196# INT3 (0.2.9 merge, 2026-11-01): the table above stopped matching the kernels long before the merge - on v0.2.9 itself this check
197# fails on 11 kernel families (the interleaved prefetch MMVQ among them) - so it could not tell a new spill from an old one.  Measured now, per sm_,
198# as the maximum over: CUDA 13.0 MSVC sm_120 (owner PC), CUDA 13.0 Linux sm_86 + sm_120 read with cuobjdump 12.9 (z440), CUDA 13.1 sm_86 (boston),
199# CUDA 13.2 sm_120 (l620) and CUDA 13.0 sm_121 (DGX Spark), libraries of the merged tree; merged into ALLOWED by max, never lowered.  A new spill in
200# one of these kernels now fails again only when it goes past the number below.  The ones marked NEW are the two this merge adds.
201_INT3_ALLOWED = {
202    # Spark sm_121 (never measured before)
203    "strata::kernels::native_gu_amd_kernel": {"sm_121": (8, 0)},
204    # Spark sm_121 (never measured before)
205    "strata::kernels::native_gu_fused_kernel": {"sm_121": (8, 0)},
206    # sm_120 already at v0.2.9
207    "strata::kernels::route_resident_k": {"sm_120": (40, 0)},
208    # Spark sm_121 (never measured before)
209    "strata::kernels::{anonymous}::block_scores_rows_kernel": {"sm_121": (8, 0)},
210    # Spark sm_121 (never measured before)
211    "strata::kernels::{anonymous}::block_topk_reg_kernel": {"sm_121": (88, 0)},
212    # Spark sm_121 (never measured before)
213    "strata::kernels::{anonymous}::copy_kernel": {"sm_121": (88, 0)},
214    # sm_120 already at v0.2.9; sm_86 already at v0.2.9
215    "strata::kernels::{anonymous}::dequant_gu_kernel": {"sm_120": (32, 0), "sm_121": (32, 0), "sm_86": (32, 0)},
216    # Spark sm_121 (never measured before)
217    "strata::kernels::{anonymous}::dequant_kernel": {"sm_121": (128, 0)},
218    # sm_86 288 B (272 B in the table before) with cuobjdump 12.9 reading the objects
219    "strata::kernels::{anonymous}::expdec_down_kernel": {"sm_121": (136, 0), "sm_86": (288, 0)},
220    # Spark sm_121 (never measured before)
221    "strata::kernels::{anonymous}::expdec_gu_kernel": {"sm_121": (64, 0)},
222    # Spark sm_121 (never measured before)
223    "strata::kernels::{anonymous}::gdn_step_commit_kernel": {"sm_121": (8, 0)},
224    # sm_120 already at v0.2.9
225    "strata::kernels::{anonymous}::gdn_step_norm_multi_kernel": {"sm_120": (8, 0)},
226    # NEW in 0.2.9 (DFlash2 Q4_0 drafter, opt-in): the Df2Segs parameter struct (Df2Seg s[3]) is copied to the stack to index it in a loop, as gemm8_kernel; avoidable (constant memory or unrolled segments), noted for BW-DRAFT
227    "strata::kernels::{anonymous}::gemm4_kernel": {"sm_120": (104, 0), "sm_121": (104, 0), "sm_86": (104, 0)},
228    # Spark sm_121 (never measured before)
229    "strata::kernels::{anonymous}::gemm8_kernel": {"sm_121": (136, 0)},
230    # present at v0.2.9 (not in the table then)
231    "strata::kernels::{anonymous}::gemm_iq_f16_grouped_kernel": {"sm_120": (32, 0), "sm_121": (32, 0), "sm_86": (32, 0)},
232    # Spark sm_121 (never measured before)
233    "strata::kernels::{anonymous}::gr_down_staged_kernel": {"sm_121": (8, 0)},
234    # Spark sm_121 (never measured before)
235    "strata::kernels::{anonymous}::gr_up75_kernel": {"sm_121": (8, 0)},
236    # Spark sm_121 (never measured before)
237    "strata::kernels::{anonymous}::gr_up_v3_kernel": {"sm_121": (8, 0)},
238    # present at v0.2.9 (not in the table then)
239    "strata::kernels::{anonymous}::hcp::persist_kernel": {"sm_120": (8, 0), "sm_121": (8, 0), "sm_86": (16, 0)},
240    # NEW since v0.2.9 on sm_120 (8 B); not looked at
241    "strata::kernels::{anonymous}::mmvq_multi_kernel": {"sm_120": (8, 0), "sm_121": (8, 0)},
242    # sm_120 already at v0.2.9
243    "strata::kernels::{anonymous}::native_down_kernel": {"sm_120": (8, 0)},
244    # Spark sm_121 (never measured before)
245    "strata::kernels::{anonymous}::native_down_multi_kernel": {"sm_121": (48, 0)},
246    # sm_120 already at v0.2.9
247    "strata::kernels::{anonymous}::native_gu_kernel": {"sm_120": (24, 0)},
248    # Spark sm_121 (never measured before)
249    "strata::kernels::{anonymous}::native_gu_multi_kernel": {"sm_121": (112, 0)},
250    # Spark sm_121 (never measured before)
251    "strata::kernels::{anonymous}::native_gu_swiglu_kernel": {"sm_121": (72, 0)},
252    # Spark sm_121 (never measured before)
253    "strata::kernels::{anonymous}::native_mmvq_il_kernel": {"sm_121": (8, 0)},
254    # the interleaved prefetch MMVQ (IlQ4K / IlQ5K / IlQ6K / IlIQ4XS instantiations, one entry for all): 1.3-1.6 KB of stack a thread; present at v0.2.9 and not in the table then
255    "strata::kernels::{anonymous}::native_mmvq_il_pf_kernel": {"sm_120": (1624, 0), "sm_121": (1456, 0), "sm_86": (1336, 0)},
256    # Spark sm_121 (never measured before)
257    "strata::kernels::{anonymous}::pair_kernel": {"sm_121": (16, 0)},
258    # Spark sm_121 (never measured before)
259    "strata::kernels::{anonymous}::prompt_attn_i8v3_kernel": {"sm_121": (40, 0)},
260    # Spark sm_121 (never measured before)
261    "strata::kernels::{anonymous}::rope_table_kernel": {"sm_121": (32, 0)},
262    # Spark sm_121 (never measured before)
263    "strata::kernels::{anonymous}::s26_gu_l_kernel": {"sm_121": (32, 0)},
264    # Spark sm_121 (never measured before)
265    "strata::kernels::{anonymous}::s27_gu_kernel": {"sm_121": (32, 0)},
266    # sm_86 already at v0.2.9
267    "strata::prefill::fused::{anonymous}::native_kernel": {"sm_121": (16, 0), "sm_86": (48, 0)},
268    # sm_86 present at v0.2.9; sm_120 8 B new on CUDA 13.x
269    "strata::prefill::{anonymous}::gdn_conv_w_kernel": {"sm_120": (8, 0), "sm_121": (8, 0), "sm_86": (24, 0)},
270    # present at v0.2.9 (not in the table then), sm_86
271    "strata::prefill::{anonymous}::gdn_tc_scan_kernel": {"sm_86": (128, 0)},
272    # NEW in 0.2.9 (STRATA_QSA_FUSE_NR, f-042-strix-pf): the RopeTab parameter struct is copied to the stack for rope_tab_cs; avoidable (pass the table by pointer), noted for STRIX-PF
273    "strata::prefill::{anonymous}::rms_rope_rows_kernel": {"sm_120": (32, 0), "sm_121": (32, 0), "sm_86": (32, 0)},
274    # Spark sm_121 (never measured before)
275    "strata::prefill::{anonymous}::rope_kernel": {"sm_121": (32, 0)},
276    # Spark sm_121 (never measured before)
277    "{anonymous}::k_attn_prep": {"sm_121": (32, 0)},
278    # rc1 (measured on l620, CUDA 13.2 sm_120): the HC down kernel's register-blocked instance <1,6,true,2,0,true> (df2-more, STRATA_GR_V3_PF bit 7, default 133 on sm_120) keeps 8 bytes
279    "strata::kernels::{anonymous}::gr_down_v3_kernel": {"sm_120": (8, 0)},
280    # rc1 (l620 sm_120): DFlash2's rope table builder copies its parameter struct to the stack (src/kernels/cuda/dflash2.cu, from the ring / multi-card DFlash2 line); avoidable
281    "strata::kernels::{anonymous}::rope_table_inv_kernel": {"sm_120": (32, 0)},
282}
283for _key, _per_sm in _INT3_ALLOWED.items():
284    _merged = ALLOWED.setdefault(_key, {})
285    for _sm, (_stack, _local) in _per_sm.items():
286        _old = _merged.get(_sm, (0, 0))
287        _merged[_sm] = (max(_stack, _old[0]), max(_local, _old[1]))
288
289# sm_89 (Ada: the RTX 40 cards), measured 11-13 on a CUDA 13.2 build of d6f9f68f9 (batch 15, sm_89-real; cuobjdump 13.2 reading libstrata_kernels.a):
290# 432 instances in these 40 kernels use stack, none uses .local.  36 of the keys equal the sm_86 allowance above to the byte, or are below it; gemm4_rows_kernel,
291# gemm_rows_kernel, i8_kernel and rope_table_inv_kernel have no sm_86 entry (their stack is the same size on sm_86).  The kernels are the same device code on
292# every architecture (there is no per-architecture variant of them); the sm_89 keys were only missing.  Same shape and rule as the entries above: the
293# measured maximum, so any growth fails.
294_SM89_ALLOWED = {
295    "strata::kernels::native_gu_lds_kernel": {"sm_89": (8, 0)},
296    "strata::kernels::route_resident_k": {"sm_89": (40, 0)},
297    "strata::kernels::{anonymous}::attn_chunk_kernel": {"sm_89": (384, 0)},
298    "strata::kernels::{anonymous}::attn_chunk_kernel_pre75": {"sm_89": (8, 0)},
299    "strata::kernels::{anonymous}::attn_chunk_slots_kernel": {"sm_89": (384, 0)},
300    "strata::kernels::{anonymous}::block_scores_simt_kernel": {"sm_89": (8, 0)},
301    "strata::kernels::{anonymous}::block_topk_reg_kernel": {"sm_89": (96, 0)},
302    "strata::kernels::{anonymous}::copy_kernel": {"sm_89": (88, 0)},
303    "strata::kernels::{anonymous}::dequant_gu_kernel": {"sm_89": (32, 0)},
304    "strata::kernels::{anonymous}::dequant_kernel": {"sm_89": (64, 0)},
305    "strata::kernels::{anonymous}::expdec_down_kernel": {"sm_89": (288, 0)},
306    "strata::kernels::{anonymous}::expdec_gu_kernel": {"sm_89": (56, 0)},
307    "strata::kernels::{anonymous}::gdn_step_commit_kernel": {"sm_89": (8, 0)},
308    "strata::kernels::{anonymous}::gemm4_rows_kernel": {"sm_89": (8, 0)},
309    "strata::kernels::{anonymous}::gemm_iq_f16_grouped_kernel": {"sm_89": (32, 0)},
310    "strata::kernels::{anonymous}::gemm_rows_kernel": {"sm_89": (40, 0)},
311    "strata::kernels::{anonymous}::gr_down_multi_kernel": {"sm_89": (8, 0)},
312    "strata::kernels::{anonymous}::gr_down_q8_fast_kernel": {"sm_89": (8, 0)},
313    "strata::kernels::{anonymous}::gr_down_q8_kernel": {"sm_89": (16, 0)},
314    "strata::kernels::{anonymous}::gr_down_staged_kernel": {"sm_89": (16, 0)},
315    "strata::kernels::{anonymous}::gr_down_v3_kernel": {"sm_89": (8, 0)},
316    "strata::kernels::{anonymous}::gr_up_q8_fast_kernel": {"sm_89": (8, 0)},
317    "strata::kernels::{anonymous}::hcp::persist_kernel": {"sm_89": (16, 0)},
318    "strata::kernels::{anonymous}::i8_kernel": {"sm_89": (8, 0)},
319    "strata::kernels::{anonymous}::native_down_kernel": {"sm_89": (8, 0)},
320    "strata::kernels::{anonymous}::native_down_multi_kernel": {"sm_89": (64, 0)},
321    "strata::kernels::{anonymous}::native_gu_kernel": {"sm_89": (8, 0)},
322    "strata::kernels::{anonymous}::native_gu_multi_kernel": {"sm_89": (144, 0)},
323    "strata::kernels::{anonymous}::native_mmvq_il_pf_kernel": {"sm_89": (1336, 0)},
324    "strata::kernels::{anonymous}::pair_kernel": {"sm_89": (16, 0)},
325    "strata::kernels::{anonymous}::prompt_attn_kernel": {"sm_89": (8, 0)},
326    "strata::kernels::{anonymous}::rope_table_inv_kernel": {"sm_89": (32, 0)},
327    "strata::kernels::{anonymous}::rope_table_kernel": {"sm_89": (32, 0)},
328    "strata::kernels::{anonymous}::route": {"sm_89": (64, 0)},
329    "strata::kernels::{anonymous}::route_multi": {"sm_89": (64, 0)},
330    "strata::kernels::{anonymous}::route_prior_k": {"sm_89": (64, 0)},
331    "strata::kernels::{anonymous}::route_topk": {"sm_89": (32, 0)},
332    "strata::kernels::{anonymous}::s26_gu_l_kernel": {"sm_89": (32, 0)},
333    "strata::kernels::{anonymous}::s27_down_kernel": {"sm_89": (16, 0)},
334    "strata::kernels::{anonymous}::s27_gu_kernel": {"sm_89": (32, 0)},
335}
336for _key, _per_sm in _SM89_ALLOWED.items():
337    _merged = ALLOWED.setdefault(_key, {})
338    for _sm, (_stack, _local) in _per_sm.items():
339        _old = _merged.get(_sm, (0, 0))
340        _merged[_sm] = (max(_stack, _old[0]), max(_local, _old[1]))
341
342# sm_89, the other libraries (libstrata_prefill.a, libstrata_qwen35.a, libstrata_mmq.a, libstrata_pf_own.a), from the CTest output of a CUDA 13.2 build
343# of af6226a3c on an RTX 4090 (the pod's cuda_spill_guard run, with MMQ and without): 75 and 68 kernel instances use stack, none uses .local; the 12 keys
344# below cover all of them, each at the measured maximum of its instances.  Same rule as above: any growth fails.
345_SM89_OTHER_LIBS_ALLOWED = {
346    "q36k::k_route_group": {"sm_89": (32, 0)},
347    "strata::prefill::fused::{anonymous}::native_kernel": {"sm_89": (80, 0)},
348    "strata::prefill::fused_q36::{anonymous}::native_kernel": {"sm_89": (80, 0)},
349    "strata::prefill::mmq::{anonymous}::iq4_w4a8_kernel": {"sm_89": (40, 0)},
350    "strata::prefill::{anonymous}::gdn_conv_w_kernel": {"sm_89": (24, 0)},
351    "strata::prefill::{anonymous}::gdn_tc_scan_kernel": {"sm_89": (128, 0)},
352    "strata::prefill::{anonymous}::gr_write_cvec_norm_rs_kernel": {"sm_89": (40, 0)},
353    "strata::prefill::{anonymous}::gr_write_norm_rs_kernel": {"sm_89": (40, 0)},
354    "strata::prefill::{anonymous}::rms_rope_rows_kernel": {"sm_89": (32, 0)},
355    "strata::prefill::{anonymous}::rope_kernel": {"sm_89": (32, 0)},
356    "strata::prefill::{anonymous}::route_kernel": {"sm_89": (64, 0)},
357    "{anonymous}::k_attn_prep": {"sm_89": (32, 0)},
358}
359for _key, _per_sm in _SM89_OTHER_LIBS_ALLOWED.items():
360    _merged = ALLOWED.setdefault(_key, {})
361    for _sm, (_stack, _local) in _per_sm.items():
362        _old = _merged.get(_sm, (0, 0))
363        _merged[_sm] = (max(_stack, _old[0]), max(_local, _old[1]))
364
365
366
367
368def kernel_key(demangled):
369    """The demangled name without parameter list, template arguments and return type: the ALLOWED key."""
370    # c++filt prints an anonymous namespace as "(anonymous namespace)", cu++filt as "<unnamed>": one spelling, so the
371    # key is the same whichever demangler is found
372    s = demangled.replace("(anonymous namespace)", "{anonymous}").replace("<unnamed>", "{anonymous}")
373    depth, cut = 0, len(s)
374    for i, c in enumerate(s):                       # the parameter list starts at the first '(' outside <...>
375        if c == "<":
376            depth += 1
377        elif c == ">":
378            depth -= 1
379        elif c == "(" and depth == 0:
380            cut = i
381            break
382    out, depth = [], 0
383    for c in s[:cut]:                               # drop every <...> (template arguments, nested ones too)
384        if c == "<":
385            depth += 1
386        elif c == ">":
387            depth -= 1
388        elif depth == 0:
389            out.append(c)
390    s = "".join(out).strip()
391    return s.split()[-1] if s else demangled        # a template kernel is printed with its return type: "void ns::k"
392
393
394def vendored(key):
395    """llama.cpp's ggml-cuda kernels (mul_mat_q, quantize_* ...) are the only ones at global scope with no namespace."""
396    return "::" not in key
397
398
399def find_tools(cuobjdump_hint):
400    """cuobjdump from --cuobjdump or PATH; the demangler beside it (cu++filt), on PATH, or binutils' c++filt."""
401    exe = ".exe" if os.name == "nt" else ""
402    cuobjdump = cuobjdump_hint if cuobjdump_hint and os.access(cuobjdump_hint, os.X_OK) else shutil.which("cuobjdump")
403    if cuobjdump is None:
404        return None, None
405    for cand in (os.path.join(os.path.dirname(cuobjdump), "cu++filt" + exe), shutil.which("cu++filt"),
406                 shutil.which("c++filt")):
407        if cand and os.access(cand, os.X_OK):
408            return cuobjdump, cand
409    return cuobjdump, None
410
411
412def resource_usage(cuobjdump, path):
413    """[(object, sm, mangled, {REG: n, STACK: n, SHARED: n, LOCAL: n, ...})] for every entry function of every SASS
414    image in an archive, an object, a shared library or an executable."""
415    run = subprocess.run([cuobjdump, "--dump-resource-usage", path], capture_output=True, text=True)
416    if run.returncode != 0:
417        print("check_cuda_spills: cuobjdump failed on %s:\n%s" % (path, (run.stderr or run.stdout).strip()[:2000]))
418        return None
419    rows, obj, sm, elf, func = [], os.path.basename(path), None, False, None
420    for line in run.stdout.splitlines():
421        s = line.strip()
422        m = re.match(r"^member .*:([^:]+):$", s)      # an archive: "member /path/libx.a:gdn.cu.o:"
423        if m:
424            obj, sm, elf, func = m.group(1), None, False, None
425            continue
426        if s.startswith("Fatbin elf code:"):
427            elf = True
428            continue
429        if s.startswith("Fatbin ptx code:"):            # the PTX image has an "arch =" line too, and no resources
430            elf = False
431            continue
432        m = re.match(r"^arch = (\S+)$", s)
433        if m:
434            sm = m.group(1)
435            continue
436        m = re.match(r"^Function (\S+):$", s)
437        if m and elf:
438            func = m.group(1)
439            continue
440        if func is not None and s.startswith("REG:"):
441            cols = {k: int(v) for k, v in re.findall(r"([A-Z]+(?:\[\d+\])?):(\d+)", s)}
442            rows.append((obj, sm, func, cols))
443            func = None
444    return rows
445
446
447def demangle(demangler, names):
448    """{mangled: demangled} for every name, or None when there is no demangler, it fails, prints the wrong number of
449    lines, or hands a mangled name back as it was.  A mangled name has no "::" to read, so an undemangled kernel would
450    be classified as vendored and skipped: without the demangler's answer there is no verdict, never a pass."""
451    if demangler is None:
452        print("check_cuda_spills: no demangler (cu++filt beside cuobjdump, or cu++filt / c++filt on PATH)")
453        return None
454    if not names:
455        return {}
456    run = subprocess.run([demangler], input="\n".join(names) + "\n", capture_output=True, text=True)
457    out = run.stdout.splitlines()
458    if run.returncode != 0:
459        print("check_cuda_spills: %s exited %d:\n%s" % (demangler, run.returncode,
460                                                        (run.stderr or run.stdout).strip()[:2000]))
461        return None
462    if len(out) != len(names):
463        print("check_cuda_spills: %s printed %d lines for %d names" % (demangler, len(out), len(names)))
464        return None
465    blank = [n for n, d in zip(names, out) if not d.strip()]
466    if blank:      # a blank answer would make the kernel's key empty, which reads as vendored and is skipped: no verdict
467        print("check_cuda_spills: %s printed a blank name for %d of %d names, e.g. %s" % (demangler, len(blank), len(names),
468                                                                                    blank[0][:160]))
469        return None
470    stuck = [n for n, d in zip(names, out) if n.startswith("_Z") and d.strip() == n]
471    if stuck:
472        print("check_cuda_spills: %s left %d of %d names mangled, e.g. %s" % (demangler, len(stuck), len(names),
473                                                                             stuck[0][:160]))
474        return None
475    return dict(zip(names, out))
476
477
478def instance_key(demangled):
479    """The exact instance name: the demangled name with its template arguments, without return type and parameter list, spelled the
480    same whichever demangler printed it (cu++filt: <unnamed>, (bool)1, (int)96; binutils' c++filt: (anonymous namespace), true, 96,
481    96u, "> >").  The baseline's key."""
482    s = demangled.replace("(anonymous namespace)", "{anonymous}").replace("<unnamed>", "{anonymous}")
483    s = s.replace("(bool)1", "true").replace("(bool)0", "false")
484    s = re.sub(r"\((?:unsigned )?(?:long long|long|int|short|char)\)(-?\d+)", r"\1", s)      # cu++filt's cast before a literal
485    s = re.sub(r"(?<=\d)[ul]+(?![\w])", "", s)                                                # c++filt's 96u / 96ul suffixes
486    while re.search(r">\s+>", s):
487        s = re.sub(r">\s+>", ">>", s)
488    depth, cut = 0, len(s)
489    for i, c in enumerate(s):                       # the parameter list starts at the first '(' outside <...>
490        if c == "<":
491            depth += 1
492        elif c == ">":
493            depth -= 1
494        elif c == "(" and depth == 0:
495            cut = i
496            break
497    s = s[:cut].strip()
498    depth, start = 0, 0
499    for i, c in enumerate(s):                       # a template kernel is printed with its return type: "void ns::k<1, 2>"
500        if c == "<":
501            depth += 1
502        elif c == ">":
503            depth -= 1
504        elif c == " " and depth == 0:
505            start = i + 1
506    return s[start:] or demangled
507
508
509def load_baseline(path):
510    """{sm: {instance name: (stack, local, reason)}} from the baseline file; an architecture that is not in the file has no
511    baseline.  A file that cannot be read, or an entry that is incomplete, is an error (ValueError), never an empty baseline."""
512    try:
513        with open(path, encoding="utf-8") as f:
514            raw = json.load(f)
515    except (OSError, ValueError) as e:
516        raise ValueError("cannot read the baseline %s: %s" % (path, e))
517    if not isinstance(raw, dict):
518        raise ValueError("the baseline %s is not a JSON object" % path)
519    out = {}
520    for sm, block in raw.items():
521        if sm.startswith("_") or block is None:     # "_about" and the like; null = stated as having no baseline
522            continue
523        entries = block.get("instances") if isinstance(block, dict) else None
524        if not isinstance(entries, list):
525            raise ValueError("the baseline %s: %s has no \"instances\" list" % (path, sm))
526        per = {}
527        for e in entries:
528            ok = (isinstance(e, dict) and isinstance(e.get("name"), str) and e["name"]
529                  and all(isinstance(e.get(k), int) and not isinstance(e.get(k), bool) and e[k] >= 0 for k in ("stack", "local"))
530                  and isinstance(e.get("reason"), str) and e["reason"].strip())
531            if not ok:
532                raise ValueError("the baseline %s: %s has an entry without name, stack, local and reason: %r" % (path, sm, e))
533            if e["name"] in per:
534                raise ValueError("the baseline %s: %s lists %s twice" % (path, sm, e["name"]))
535            per[e["name"]] = (e["stack"], e["local"], e["reason"])
536        out[sm] = per
537    return out
538
539
540def default_baseline():
541    """The baseline beside this script; a missing file is an empty baseline (every architecture reports "no baseline")."""
542    if not os.path.exists(BASELINE_FILE):
543        return {}
544    return load_baseline(BASELINE_FILE)
545
546
547def find_violations(rows, names):
548    """(gated entries, entries that use stack or local memory, [violation]) for the rows of one library: a violation is an entry over
549    ALLOWED (or not in it), as (demangled name, instance key, sm, stack, local, why, object)."""
550    gated = [(obj, sm, func, cols) for obj, sm, func, cols in rows if not vendored(kernel_key(names[func]))]
551    held, viols = 0, []
552    for obj, sm, func, cols in gated:
553        stack, local = cols.get("STACK", 0), cols.get("LOCAL", 0)
554        if stack == 0 and local == 0:
555            continue
556        held += 1
557        allow = ALLOWED.get(kernel_key(names[func]), {}).get(sm)
558        if allow is None:
559            why = "not in ALLOWED"
560        elif stack > allow[0] or local > allow[1]:
561            why = "over its allowance STACK %d LOCAL %d" % allow
562        else:
563            continue
564        viols.append((names[func], instance_key(names[func]), sm, stack, local, why, obj))
565    return gated, held, viols
566
567
568def check(path, rows, names, baseline=None, seen=None, verbose=False):
569    """Judge one library.  `baseline` is load_baseline's result (default: the file beside this script); `seen`, when given, collects
570    {sm: {instance names}} of the known instances found, for the caller's count over several libraries."""
571    if baseline is None:
572        baseline = default_baseline()
573    archs = sorted({sm for _, sm, _, _ in rows})
574    gated, held, viols = find_violations(rows, names)
575    known, bad, no_base = [], [], {}
576    for name, inst, sm, stack, local, why, obj in viols:
577        base = baseline.get(sm)
578        if base is None:
579            no_base[sm] = no_base.get(sm, 0) + 1
580        elif inst in base:
581            b_stack, b_local, _ = base[inst]
582            if stack <= b_stack and local <= b_local:
583                known.append((name, sm, stack, local, obj))
584                if seen is not None:
585                    seen.setdefault(sm, set()).add(inst)
586                continue
587            why = "known instance grew: over its baseline STACK %d LOCAL %d" % (b_stack, b_local)
588        bad.append((name, sm, stack, local, why, obj))
589    print("check_cuda_spills: %s: %d kernels on %s (%d entries; %d vendored ggml entries skipped), %d use stack / "
590          "local memory, %d of them known from the baseline, %d not allowed" % (
591              path, len({f for _, _, f, _ in gated}), ", ".join(archs), len(gated), len(rows) - len(gated), held, len(known),
592              len(bad)))
593    for sm in sorted(no_base):
594        print("check_cuda_spills: no baseline for %s: its %d violations cannot be told from new ones (baselines: %s)" % (
595            sm, no_base[sm], ", ".join(sorted(baseline)) or "none"))
596    if verbose:
597        for name, sm, stack, local, obj in known:
598            print("  known %s %s: STACK %d LOCAL %d [%s]" % (name[:160], sm, stack, local, obj))
599    for name, sm, stack, local, why, obj in bad:
600        print("  VIOLATION %s %s: STACK %d LOCAL %d (%s) [%s]" % (name[:160], sm, stack, local, why, obj))
601    return 1 if bad else 0
602
603
604def toolkit_line(cuobjdump):
605    """The last line of `cuobjdump --version` (the toolkit release), for the baseline's "measured_with"."""
606    try:
607        run = subprocess.run([cuobjdump, "--version"], capture_output=True, text=True, timeout=30)
608        lines = [l.strip() for l in run.stdout.splitlines() if l.strip()]
609        return lines[-1] if lines else "unknown"
610    except (OSError, subprocess.SubprocessError):
611        return "unknown"
612
613
614def main():
615    ap = argparse.ArgumentParser()
616    ap.add_argument("library", nargs="+", help="a static library, object, shared library or executable with SASS")
617    ap.add_argument("--list", action="store_true", help="print every kernel on every sm_ as CSV, judge nothing")
618    ap.add_argument("--cuobjdump", help="the toolkit's cuobjdump (default: on PATH)")
619    ap.add_argument("--baseline", help="the known-violations file (default: cuda_spill_baseline.json beside this script)")
620    ap.add_argument("--print-baseline", action="store_true",
621                    help="print the baseline entries (JSON) for the violations found, judge nothing: how the baseline was made")
622    ap.add_argument("-v", "--verbose", action="store_true", help="also print every known violation")
623    a = ap.parse_args()
624    cuobjdump, demangler = find_tools(a.cuobjdump)
625    if cuobjdump is None:
626        print("check_cuda_spills: cuobjdump not found (put the CUDA toolkit's bin/ on PATH, or pass --cuobjdump)")
627        return 77
628    if demangler is None:
629        # without a demangler every Strata kernel would read as a no-namespace (vendored) one and be skipped: the
630        # check cannot run, and a pass with nothing counted is not a pass
631        print("check_cuda_spills: no demangler found (cu++filt beside %s, or cu++filt / c++filt on PATH)" % cuobjdump)
632        return 77
633    for lib in a.library:
634        if not os.path.exists(lib):
635            print("check_cuda_spills: %s does not exist" % lib)
636            return 77
637    baseline = {}
638    if not a.list and not a.print_baseline:
639        try:
640            baseline = load_baseline(a.baseline) if a.baseline else default_baseline()
641        except ValueError as e:        # a baseline that cannot be read is never an empty one: that would pass nothing known and hide it
642            print("check_cuda_spills: %s" % e)
643            return 2
644    out = csv.writer(sys.stdout, lineterminator="\n") if a.list else None
645    if out:
646        out.writerow(["library", "object", "sm", "reg", "stack", "local", "shared", "kernel", "mangled", "gated"])
647    rc = 0
648    seen, archs_seen, found = {}, set(), {}
649    for lib in a.library:
650        rows = resource_usage(cuobjdump, lib)
651        if rows is None:
652            return 77
653        if not rows:
654            # a library without one SASS entry function is not one of the kernel libraries, or cuobjdump's output
655            # changed shape: either way this check did not run, and a pass with nothing counted is not a pass
656            print("check_cuda_spills: %s: no SASS entry function found (not a CUDA library, or cuobjdump's format "
657                  "changed)" % lib)
658            return 77
659        names = demangle(demangler, sorted({f for _, _, f, _ in rows}))
660        if names is None:
661            return 77
662        if out:
663            for obj, sm, func, cols in rows:
664                out.writerow([os.path.basename(lib), obj, sm, cols.get("REG", 0), cols.get("STACK", 0),
665                              cols.get("LOCAL", 0), cols.get("SHARED", 0), names[func], func,
666                              0 if vendored(kernel_key(names[func])) else 1])
667        elif a.print_baseline:
668            for _, inst, sm, stack, local, _, _ in find_violations(rows, names)[2]:
669                old = found.setdefault(sm, {}).get(inst, (0, 0))
670                found[sm][inst] = (max(stack, old[0]), max(local, old[1]))
671        else:
672            archs_seen.update(sm for _, sm, _, _ in rows)
673            rc = max(rc, check(lib, rows, names, baseline, seen, a.verbose))
674    if a.print_baseline:
675        print(json.dumps({sm: {"measured_with": toolkit_line(cuobjdump),
676                               "instances": [{"name": n, "stack": s, "local": l, "reason": KNOWN_REASON}
677                                             for n, (s, l) in sorted(per.items())]}
678                          for sm, per in sorted(found.items())}, indent=2))
679    elif not a.list:
680        for sm in sorted(archs_seen & set(baseline)):     # the known count over all the libraries given
681            print("check_cuda_spills: baseline %s: %d known violations seen, %d listed" % (sm, len(seen.get(sm, ())), len(baseline[sm])))
682    return rc
683
684
685if __name__ == "__main__":
686    sys.exit(main())