okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6e1085c1d
main
1import json 2import re 3from pathlib import Path 4from statistics import median 5import matplotlib 6matplotlib .use ('Agg' ) 7import matplotlib .pyplot as plt 8import numpy as np 9 10OUT = Path (__file__ ).resolve ().parent 11DATA = OUT / 'p4-roofline' 12base = json .loads ((DATA / 'results.json' ).read_text ()) 13control = json .loads ((DATA / 'control/results.json' ).read_text ()) 14auto = json .loads ((DATA / 'auto/results.json' ).read_text ()) 15roofs = [json .loads (l )for l in (DATA / 'roofs.jsonl' ).read_text ().splitlines ()] 16host = [json .loads (l )for l in (DATA / 'host-roofs.jsonl' ).read_text ().splitlines ()] 17assert base ['complete' ]and control ['complete' ]and auto ['complete' ] 18bandwidth = {k :median ([r ['GB_s' ]for r in roofs if r ['kind' ]== k ])for k in ['vram_read' ,'h2d' ,'d2h' ]} 19bandwidth ['host_read' ]= median (r ['GB_s' ]for r in host ) 20 21def phase_data (row ): 22line = next (l for l in row ['log' ].splitlines ()if 'GPU timeline' in l ) 23total = float (re .search (r'GPU timeline (\d+) ms' ,line )[1 ]) 24parts = re .findall (r'([\w +/]+) (\d+) \([\d.]+%\)' ,line .split ('ms:' ,1 )[1 ]) 25phases = {k .strip ():float (v )for k ,v in parts } 26io = re .search (r'OS read ([\d.]+) MB from storage \((\d+) major faults\) for ([\d.]+) MB of expert reads' ,row ['log' ]) 27return dict (total_ms = total ,phases_ms = phases ,disk_MB = float (io [1 ])if io else None , 28major_faults = int (io [2 ])if io else None ,logical_expert_MB = float (io [3 ])if io else None ) 29 30summary = {'bandwidth_GB_s' :bandwidth ,'baseline' : [],'control' : [],'notes' : []} 31for n in [512 ,4096 ,8192 ]: 32rows = [r for r in base ['runs' ]if r ['phase' ]== 'measured' and r ['tokens' ]== n ] 33assert len (rows )== 3 34rates = [n * 1000 / r ['timing' ]['prompt_ms' ]for r in rows ] 35data = [phase_data (r )for r in rows ] 36phases = {k :median (d ['phases_ms' ][k ]for d in data )for k in data [0 ]['phases_ms' ]} 37total = median (d ['total_ms' ]for d in data ) 38# This scenario leaves every non-expert phase at its measured runtime. 39expert_names = ['host grouping' ,'gather' ,'wait copy' ,'dequant' ,'gemm gate/up' ,'gemm down' ,'combine' ] 40expert = sum (phases .get (k ,0 )for k in expert_names ) 41wait = phases .get ('wait copy' ,0 ) 42stream_group = wait + phases .get ('dequant' ,0 ) 43summary ['baseline' ].append (dict (tokens = n ,rates = rates ,median_tps = median (rates ),min_tps = min (rates ),max_tps = max (rates ), 44prompt_ms_median = median (r ['timing' ]['prompt_ms' ]for r in rows ),phases_ms = phases ,total_ms = total , 45logical_expert_MB_median = median (d ['logical_expert_MB' ]for d in data ),disk_MB = [d ['disk_MB' ]for d in data ], 46major_faults = [d ['major_faults' ]for d in data ], 47wait_only_zero_speedup = total / (total - wait ), 48wait_and_dequant_zero_speedup = total / (total - stream_group ), 49expert_phase_zero_speedup = total / (total - expert ), 50fixed_nonexpert_ms = total - expert )) 51 52# Routed experts only: 48 layers * top-10 * three (2560 x 640) products, multiply+add = 2 ops. 53ops_per_token = 48 * 10 * 3 * 2560 * 640 * 2 54for setting ,row in [('512' ,r )for r in control ['runs' ]]+ [('auto' ,r )for r in auto ['runs' ]]: 55if row ['phase' ]!= 'measured' :continue 56m = re .search (r'roofline: tokens (\d+) H2D_bytes (\d+) copies (\d+) unique_bytes (\d+) unique_experts (\d+)' ,row ['log' ]) 57assert m ,row ['log' ][- 2000 :] 58n ,b ,copies ,unique ,experts = map (int ,m .groups ()) 59work = n * ops_per_token 60item = dict (prefill_setting = setting ,prompt_tokens = row ['tokens' ],prefill_tokens = n ,h2d_bytes = b ,copies = copies ,unique_bytes = unique ,unique_experts = experts , 61repetition_ratio = b / unique ,avoidable_repeated_bytes = b - unique , 62h2d_floor_s = b / (bandwidth ['h2d' ]* 1e9 ),unique_h2d_floor_s = unique / (bandwidth ['h2d' ]* 1e9 ), 63prompt_ms = row ['timing' ]['prompt_ms' ],tps = row ['tokens' ]* 1000 / row ['timing' ]['prompt_ms' ], 64routed_ops = work ,h2d_ops_per_byte = work / b ,unique_h2d_ops_per_byte = work / unique , 65routed_equiv_TOP_s = work / (row ['timing' ]['prompt_ms' ]/ 1000 )/ 1e12 , 66phases = phase_data (row )) 67item ['copy_only_saving_at_peak_s' ]= item ['h2d_floor_s' ]- item ['unique_h2d_floor_s' ] 68summary ['control' ].append (item ) 69summary ['ops_per_token_routed_only' ]= ops_per_token 70summary ['notes' ]= [ 71'Baseline: main fb58e0d, one P4, IQ3_XXS, int8 KV, 512-token prefill chunks, mmap experts, three repetitions, CPU share default.' , 72'Controls: same base plus host-only byte counters, CPU expert share disabled, one observation per length and chunk policy. Auto selected 1792 tokens.' , 73'Logical file-tier reads are not physical disk bytes or measured GPU DRAM traffic.' , 74'CUDA-event phase times include host-issue/copy stalls; dequant includes quantized group gathering, not just dequantization.' , 75'Host staging in the engine log is cumulative and overlapping, not an additive per-request component.' , 76'Routed-equivalent ops omit dense, attention, recurrent, and quantization work; the 22-TOPS roof is an optimistic INT8 hardware budget, not a measured IQ3 kernel ceiling.' , 77'Unique H2D bytes assume each observed streamed expert is copied once across the request. This models reuse only, not an implemented layer-major run.' , 78'Zero-phase scenarios hold remaining phase time fixed. They are conditional sensitivity calculations, not universal hardware bounds.' , 79] 80(OUT / 'roofline-summary.json' ).write_text (json .dumps (summary ,indent = 2 )) 81 82plt .rcParams .update ({'font.size' :10 ,'axes.spines.top' :False ,'axes.spines.right' :False }) 83fig ,axs = plt .subplots (1 ,2 ,figsize = (14 ,6 ),layout = 'constrained' ) 84fig .suptitle ('Tesla P4 prefill: repeated transfers matter, but do not explain the whole request' ,fontsize = 15 ,fontweight = 'bold' ) 85ax = axs [0 ] 86labels = ['512 tokens' ,'4K tokens' ,'8K tokens' ] 87groups = [('Wait for copy' ,['wait copy' ],'#d58c3d' ),('Gather / dequant / issue' ,['dequant' ,'gather' ,'host grouping' ],'#efbc71' ),('Expert math + combine' ,['gemm gate/up' ,'gemm down' ,'combine' ],'#447fbd' ),('Other model stages' ,None ,'#8cacc4' )] 88bottom = np .zeros (3 ) 89for title ,names ,color in groups : 90vals = [] 91for r in summary ['baseline' ]: 92ms = sum (r ['phases_ms' ].get (k ,0 )for k in names )if names else r ['total_ms' ]- sum (r ['phases_ms' ].get (k ,0 )for _ ,ns ,_ in groups if ns for k in ns ) 93vals .append (ms / r ['total_ms' ]* 100 ) 94ax .bar (labels ,vals ,bottom = bottom ,label = title ,color = color ,width = .6 ) 95for i ,v in enumerate (vals ): 96if v > 5 :ax .text (i ,bottom [i ]+ v / 2 ,f' { v :.1f } %' ,ha = 'center' ,va = 'center' ,color = 'white' if color == '#447fbd' else '#172535' ) 97bottom += np .array (vals ) 98ax .set_ylabel ('Share of profiled compute-stream timeline (%)' ) 99ax .set_title ('Measured baseline, 512-token chunks\n3 repeats; all expert data served from page cache' ,fontsize = 11 ) 100ax .legend (loc = 'upper center' ,bbox_to_anchor = (.5 ,- .12 ),ncol = 2 ,fontsize = 9 ,frameon = False ) 101ax .set_ylim (0 ,104 ) 102 103ax = axs [1 ] 104I = np .logspace (0 ,5 ,300 ) 105ax .loglog (I ,np .minimum (22 ,bandwidth ['h2d' ]* I / 1000 ),label = f"PCIe roof: { bandwidth [ 'h2d' ]:.2f } GB/s" ,color = '#d58c3d' ,lw = 2 ) 106ax .loglog (I ,np .minimum (22 ,bandwidth ['vram_read' ]* I / 1000 ),label = f"Same bytes read locally: { bandwidth [ 'vram_read' ]:.1f } GB/s" ,color = '#447fbd' ,ls = '--' ) 107ax .axhline (22 ,color = '#666666' ,lw = 1 ,ls = ':' ,label = '22 INT8 TOP/s: vendor peak' ) 108for r ,c in zip ([r for r in summary ['control' ]if r ['prefill_setting' ]== '512' ],['#28875c' ,'#814bae' ]): 109x ,y = r ['h2d_ops_per_byte' ],r ['routed_equiv_TOP_s' ] 110xx = r ['unique_h2d_ops_per_byte' ] 111ax .scatter ([x ],[y ],s = 55 ,color = c ,zorder = 4 ) 112ax .annotate ('' ,xy = (xx ,y ),xytext = (x ,y ),arrowprops = dict (arrowstyle = '->' ,color = c ,lw = 2 )) 113ax .annotate (f" { r [ 'prompt_tokens' ] // 1024 } K: { r [ 'repetition_ratio' ]:.1f } x fewer bytes\nif each streamed expert is copied once" ,xy = (x ,y ),xytext = (4 ,12 if r ['prompt_tokens' ]== 4096 else - 32 ),textcoords = 'offset points' ,fontsize = 8 ,color = c ) 114ax .set_xlabel ('Useful routed-expert operations / byte\nPoints use measured H2D bytes; arrows model reuse only' ) 115ax .set_ylabel ('Routed-expert equivalent TOP/s over full prefill' ) 116ax .set_title ('Bandwidth roofs and GPU-only expert controls\nNot a full-model FLOP or measured VRAM-traffic roofline' ,fontsize = 11 ) 117ax .set_xlim (1 ,1e5 );ax .set_ylim (.01 ,40 );ax .grid (True ,which = 'major' ,alpha = .15 ) 118ax .legend (loc = 'lower right' ,fontsize = 8 ,frameon = False ) 119fig .savefig (OUT / 'p4-prefill-roofline.png' ,dpi = 180 ) 120fig .savefig (OUT / 'p4-prefill-roofline.svg' ) 121json .dumps ({'bandwidth' :bandwidth ,'baseline' :[{k :r [k ]for k in ['tokens' ,'median_tps' ,'expert_phase_zero_speedup' ]}for r in summary ['baseline' ]],'controls' :[{k :r [k ]for k in ['prefill_setting' ,'prompt_tokens' ,'tps' ,'h2d_bytes' ,'unique_bytes' ,'repetition_ratio' ]}for r in summary ['control' ]]},indent = 2 ))