-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathGPUGraph.tsx
More file actions
1047 lines (999 loc) · 39.4 KB
/
Copy pathGPUGraph.tsx
File metadata and controls
1047 lines (999 loc) · 39.4 KB
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use client';
import { track } from '@/lib/analytics';
import * as d3 from 'd3';
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import { useTheme } from 'next-themes';
import { useInference } from '@/components/inference/InferenceContext';
import ChartLegend from '@/components/ui/chart-legend';
import { getHardwareConfig, getModelSortIndex } from '@/lib/constants';
import { getChartWatermark } from '@/lib/data-mappings';
import { generateGpuDateColors } from '@/lib/dynamic-colors';
import { useLocale } from '@/lib/use-locale';
import { formatNumber, getDisplayLabel, updateRepoUrl } from '@/lib/utils';
import { useThemeColors } from '@/hooks/useThemeColors';
import { useTraceAvailability } from '@/hooks/api/use-trace-availability';
import { D3Chart } from '@/lib/d3-chart/D3Chart';
import type {
CustomLayerConfig,
D3ChartHandle,
RenderContext,
ZoomContext,
} from '@/lib/d3-chart/D3Chart/types';
import type { ContinuousScale } from '@/lib/d3-chart/types';
import {
applyHoverState,
applyNormalState,
formatLargeNumber,
getShapeKeyForPrecision,
logTickFormat,
POINT_SIZE,
} from '@/lib/chart-rendering';
import {
isFrontierEligible,
paretoFrontLowerLeft,
paretoFrontLowerRight,
paretoFrontUpperLeft,
paretoFrontUpperRight,
} from '@/lib/chart-utils';
import type {
ChartDefinition,
InferenceData,
ScatterGraphProps,
} from '@/components/inference/types';
import {
buildRunNumbering,
comparisonEntryLabel,
comparisonEntrySortValue,
resolveComparisonEntries,
} from '@/components/inference/utils/comparisonEntry';
import {
generateGPUGraphTooltipContent,
getPointLabel,
} from '@/components/inference/utils/tooltipUtils';
import {
type KnownIssueAnnotation,
measureLegendRightInset,
renderKnownIssueAnnotations,
} from '@/components/inference/utils/knownIssueAnnotations';
import { matchKnownConfigIssues, pointMatchesIssue } from '@/lib/known-issues';
const CHART_MARGIN = { top: 24, right: 10, bottom: 60, left: 60 };
// Label text combines the hw config (display label) and the date so
// both dimensions of the GPU comparison view are legible on the chart,
// not only the legend. Falls back to the raw hwKey if the config
// lookup misses (legacy data).
function labelTextFor(pts: InferenceData[], numbering: Map<string, number>): string {
const hwKey = String(pts[0].hwKey);
const cfg = getHardwareConfig(hwKey, pts[0].model);
const hwLabel = cfg ? getDisplayLabel(cfg) : hwKey;
return `${hwLabel} • ${comparisonEntryLabel(String(pts[0].date), numbering)}`;
}
const GPU_STRINGS = {
en: {
logScale: 'Log Scale',
highContrast: 'High Contrast',
optimalOnly: 'Optimal Only',
labels: 'Labels',
parallelismLabels: 'Parallelism Labels',
lineLabels: 'Line Labels',
resetFilter: 'Reset filter',
},
zh: {
logScale: '对数缩放',
highContrast: '高对比度',
optimalOnly: '仅最优',
labels: '标签',
parallelismLabels: '并行配置标签',
lineLabels: '曲线标签',
resetFilter: '重置筛选',
},
} as const;
const GPUGraph = React.memo(
({
chartId,
modelLabel,
data,
xLabel,
yLabel,
chartDefinition,
caption,
runNumbering: providedRunNumbering,
}: ScatterGraphProps) => {
const {
hardwareConfig,
selectedPrecisions,
selectedYAxisMetric,
selectedGPUs,
selectedDateRange,
selectedDates,
setSelectedDates,
toggleActiveDate,
removeActiveDate,
activeDates,
hideNonOptimal,
setHideNonOptimal,
showPointLabels,
setShowPointLabels,
logScale,
setLogScale,
isLegendExpanded,
setIsLegendExpanded,
useAdvancedLabels,
setUseAdvancedLabels,
highContrast,
setHighContrast,
selectAllActiveDates,
showLineLabels,
setShowLineLabels,
} = useInference();
const locale = useLocale();
const legendT = GPU_STRINGS[locale];
const { resolvedTheme } = useTheme();
const chartRef = useRef<D3ChartHandle>(null);
// Shared date+GPU pairs. `dates` holds comparison-series entries (plain dates
// and/or specific-run entries); a same-day range endpoint is dropped when that
// date also has run entries (resolveComparisonEntries), then sorted earliest →
// latest so a day's runs read #1 → #N.
const gpuDatePairs = useMemo(() => {
const deduplicated = resolveComparisonEntries(selectedDates, selectedDateRange);
deduplicated.sort((a, b) => {
const [ta, ia] = comparisonEntrySortValue(a);
const [tb, ib] = comparisonEntrySortValue(b);
return ta - tb || ia - ib;
});
const sortedGPUs = [...selectedGPUs].toSorted(
(a, b) => getModelSortIndex(a) - getModelSortIndex(b) || a.localeCompare(b),
);
return { dates: deduplicated, sortedGPUs };
}, [selectedDateRange, selectedDates, selectedGPUs]);
// Run numbers for legend/line labels. Prefer the stable numbering passed by
// the parent (shared with the changelog, so labels match it and removed runs
// leave a gap); fall back to gap-free numbering of the on-chart series.
const runNumbering = useMemo(
() => providedRunNumbering ?? buildRunNumbering(gpuDatePairs.dates),
[providedRunNumbering, gpuDatePairs.dates],
);
// Removing a series from the legend should also drop it from the comparison
// selection so the config changelog stays in sync (two-way binding). Legend
// ids are `${entry}_${gpu}`; strip the gpu suffix to recover the entry. Range
// endpoints aren't individual selections, so those fall back to a visibility hide.
const handleLegendRemove = useCallback(
(id: string) => {
const gpu = selectedGPUs.find((g) => id.endsWith(`_${g}`));
const entry = gpu ? id.slice(0, id.length - gpu.length - 1) : id;
if (selectedDates.includes(entry)) {
setSelectedDates((prev) => prev.filter((e) => e !== entry));
} else {
removeActiveDate(id);
}
},
[selectedGPUs, selectedDates, setSelectedDates, removeActiveDate],
);
const graphIdentifiers = useMemo(() => {
const ids: string[] = [];
gpuDatePairs.sortedGPUs.forEach((gpu) =>
gpuDatePairs.dates.forEach((date) => ids.push(`${date}_${gpu}`)),
);
return ids;
}, [gpuDatePairs]);
const { resolveColor, getCssColor } = useThemeColors({
highContrast,
identifiers: graphIdentifiers,
});
// Dynamic GPU×date color map
const gpuDateColorMap = useMemo(() => {
const { dates, sortedGPUs } = gpuDatePairs;
if (sortedGPUs.length === 0 || dates.length === 0) return {};
const theme = resolvedTheme === 'dark' || resolvedTheme === 'minecraft' ? 'dark' : 'light';
return generateGpuDateColors(sortedGPUs, dates.length, theme);
}, [gpuDatePairs, resolvedTheme]);
const allGraphs = useMemo(() => {
const { dates, sortedGPUs } = gpuDatePairs;
const result: { date: string; color: string; hwKey: string; id: string }[] = [];
sortedGPUs.forEach((gpu) => {
dates.forEach((date, dateIndex) => {
const id = `${date}_${gpu}`;
const dynamicColor = gpuDateColorMap[`${dateIndex}_${gpu}`];
result.push({
date,
hwKey: gpu,
id,
color: highContrast
? getCssColor(resolveColor(id))
: dynamicColor || 'var(--foreground)',
});
});
});
return result;
}, [gpuDatePairs, gpuDateColorMap, highContrast, resolveColor, getCssColor]);
const groupedData = useMemo(
() =>
data.reduce(
(acc, point) => {
if (!selectedPrecisions.includes(point.precision)) return acc;
const key = `${point.date}_${point.hwKey}_${point.precision}`;
if (!acc[key]) acc[key] = [];
acc[key].push(point);
return acc;
},
{} as Record<string, InferenceData[]>,
),
[data, selectedPrecisions],
);
// Track which date+GPU combos have actual data points
const idsWithData = useMemo(() => {
const ids = new Set<string>();
for (const key of Object.keys(groupedData)) {
// key = "date_hwKey_precision" — strip last segment
const lastUnderscore = key.lastIndexOf('_');
ids.add(key.slice(0, lastUnderscore));
}
return ids;
}, [groupedData]);
const rooflines = useMemo(() => {
const result: Record<string, InferenceData[]> = {};
const rooflineKey = `${selectedYAxisMetric}_roofline` as keyof ChartDefinition;
const dir = chartDefinition[rooflineKey] as
| 'upper_right'
| 'upper_left'
| 'lower_left'
| 'lower_right'
| undefined;
for (const key of Object.keys(groupedData)) {
// Exclude degenerate x <= 0 points (interactivity = 0, etc.) from the
// frontier so they are never drawn as optimal.
const eligible = groupedData[key].filter(isFrontierEligible);
result[key] =
dir === 'upper_right'
? paretoFrontUpperRight(eligible)
: dir === 'upper_left'
? paretoFrontUpperLeft(eligible)
: dir === 'lower_left'
? paretoFrontLowerLeft(eligible)
: paretoFrontLowerRight(eligible);
}
return result;
}, [groupedData, selectedYAxisMetric, chartDefinition]);
const optimalPointKeys = useMemo(() => {
const keys = new Set<string>();
Object.values(rooflines).forEach((pts) =>
pts.forEach((p) => keys.add(`${p.date}_${p.hwKey}_${p.precision}-${p.x}-${p.y}`)),
);
return keys;
}, [rooflines]);
const filteredData = useMemo(() => {
let pts = Object.values(groupedData)
.flat()
.filter((p) => activeDates.has(`${p.date}_${p.hwKey}`));
if (hideNonOptimal)
pts = pts.filter((p) =>
optimalPointKeys.has(`${p.date}_${p.hwKey}_${p.precision}-${p.x}-${p.y}`),
);
return pts;
}, [groupedData, activeDates, hideNonOptimal, optimalPointKeys]);
// GPU comparison currently renders official DB-backed points only. Unofficial
// overlays have no benchmark_results id or persisted trace, so they cannot
// open the dedicated per-point charts route.
const agenticIds = useMemo(
() =>
filteredData.flatMap((point) =>
point.benchmark_type === 'agentic_traces' && typeof point.id === 'number'
? [point.id]
: [],
),
[filteredData],
);
const { data: traceAvailability } = useTraceAvailability(agenticIds);
// Warning annotations for visible series with known upstream issues —
// same treatment the scatter view gets, applied to the date-comparison view.
// Lines here are colored per (gpu, date) pair, so take the first active
// pair's color as the series swatch.
const knownIssueAnnotations = useMemo(
(): KnownIssueAnnotation[] =>
matchKnownConfigIssues(modelLabel, filteredData).map((issue) => {
const cfg = getHardwareConfig(issue.hwKey, modelLabel);
const colorEntry = allGraphs.find(
(entry) => entry.hwKey === issue.hwKey && activeDates.has(entry.id),
);
return {
issue,
label: cfg ? getDisplayLabel(cfg) : issue.hwKey,
color: getCssColor(colorEntry?.color ?? resolveColor(issue.hwKey)),
points: filteredData
.filter((p) => pointMatchesIssue(issue, p))
.map((p) => ({ x: p.x, y: p.y })),
};
}),
[modelLabel, filteredData, allGraphs, activeDates, resolveColor, getCssColor],
);
const drawKnownIssues = (
ctx: RenderContext,
xScale: ContinuousScale,
yScale: ContinuousScale,
) => {
renderKnownIssueAnnotations(ctx.layout.g, ctx.layout.defs, {
chartId,
width: ctx.width,
height: ctx.height,
xScale,
yScale,
annotations: knownIssueAnnotations,
// Only measure the legend overlap when there are boxes to place —
// this runs on every zoom frame, and the measurement forces layout.
rightInset:
knownIssueAnnotations.length === 0
? 0
: measureLegendRightInset(
chartId,
ctx.layout.svg.node(),
ctx.layout.margin.left,
ctx.width,
),
background: getCssColor('--background'),
foreground: getCssColor('--foreground'),
mutedForeground: getCssColor('--muted-foreground'),
onLinkClick: (a) =>
track('inference_known_issue_clicked', {
hwKey: a.issue.hwKey,
issue: a.issue.issueRef,
}),
});
};
const knownIssueLayer: CustomLayerConfig = {
type: 'custom',
key: 'known-issues',
render: (_zoomGroup, ctx) =>
drawKnownIssues(ctx, ctx.xScale as ContinuousScale, ctx.yScale as ContinuousScale),
onZoom: (_zoomGroup, ctx) =>
drawKnownIssues(ctx, ctx.newXScale as ContinuousScale, ctx.newYScale as ContinuousScale),
};
// Compute scale domains
const xExtent = useMemo(() => {
if (filteredData.length === 0) return [0, 100] as [number, number];
const ext = d3.extent(filteredData, (d) => d.x) as [number, number];
return [0, ext[1] * 1.05] as [number, number];
}, [filteredData]);
const yDomain = useMemo(() => {
if (filteredData.length === 0) return [0, 100] as [number, number];
const yExtent = d3.extent(filteredData, (d) => d.y) as [number, number];
const yRange = yExtent[1] - yExtent[0];
let yMin: number;
if (logScale) {
const dataMin = yExtent[0];
yMin =
dataMin <= 0 ? 0.1 : dataMin < 1 ? 10 ** Math.floor(Math.log10(dataMin)) : dataMin * 0.95;
} else {
yMin = Math.max(0, yExtent[0] - yRange * 0.05);
}
return [yMin, yExtent[1] * 1.05] as [number, number];
}, [filteredData, logScale]);
// Color resolver for points/rooflines
const getColor = useMemo(
() => (d: InferenceData) => {
const graphIndex = allGraphs.findIndex(
({ date, hwKey }) => d.date === date && d.hwKey === hwKey,
);
return graphIndex === -1 ? '#6b7280' : allGraphs[graphIndex].color;
},
[allGraphs],
);
const getRooflineColor = useMemo(
() => (key: string) => {
const graphId = key.split('_').slice(0, -1).join('_');
const graphIndex = allGraphs.findIndex((d) => d.id === graphId);
return graphIndex === -1 ? '#6b7280' : allGraphs[graphIndex].color;
},
[allGraphs],
);
const isRooflineVisible = useMemo(
() => (key: string) => {
const graphId = key.split('_').slice(0, -1).join('_');
return activeDates.has(graphId);
},
[activeDates],
);
// ── Line labels (date along each roofline) ──
// One label per (date, hwKey) pair — keys with multiple precisions for the
// same combo dedupe down to the longest roofline so the label rides the
// line that has the most placement options. Labels track the active filter
// (`activeDates`) so removing a series via the legend hides its label too.
const lineLabelLayer: CustomLayerConfig = useMemo(
() => ({
type: 'custom',
key: 'line-labels',
render: (zoomGroup, ctx) => {
// Always run the data-join so toggling the switch off cleans the DOM.
interface LineLabel {
key: string;
graphId: string;
label: string;
color: string;
x: number;
y: number;
visible: boolean;
}
if (!showLineLabels) {
zoomGroup.selectAll('.line-label').remove();
return;
}
const xScale = ctx.xScale as ContinuousScale;
const yScale = ctx.yScale as ContinuousScale;
const isInteractivity = chartDefinition.chartType === 'interactivity';
const LABEL_H = 18;
const LABEL_W = 160;
// Pick longest roofline per (date, hwKey) so we get one label per series.
const bestByGraph = new Map<string, { key: string; pts: InferenceData[] }>();
for (const [key, pts] of Object.entries(rooflines)) {
if (pts.length < 2) continue;
const graphId = key.slice(0, key.lastIndexOf('_'));
if (!isRooflineVisible(key)) continue;
const prev = bestByGraph.get(graphId);
if (!prev || pts.length > prev.pts.length) bestByGraph.set(graphId, { key, pts });
}
const lineLabels: LineLabel[] = [];
if (isInteractivity) {
// Greedy placement: try start → midpoint → 2/3-along → endpoint.
const placed: { x: number; y: number }[] = [];
const collides = (cx: number, cy: number) =>
placed.some((p) => Math.abs(p.y - cy) < LABEL_H && Math.abs(p.x - cx) < LABEL_W);
const sorted = [...bestByGraph.entries()].toSorted(
([, a], [, b]) => yScale(a.pts[0].y) - yScale(b.pts[0].y),
);
for (const [graphId, { key, pts }] of sorted) {
const candidates = [
pts[Math.min(1, pts.length - 1)],
pts[Math.floor(pts.length / 2)],
pts[Math.max(0, Math.floor((pts.length * 2) / 3))],
pts.at(-1)!,
];
const labelText = labelTextFor(pts, runNumbering);
let placedLabel = false;
for (const pt of candidates) {
const px = xScale(pt.x);
const py = yScale(pt.y);
if (!collides(px, py)) {
lineLabels.push({
key,
graphId,
label: labelText,
color: getRooflineColor(key),
x: px,
y: py,
visible: true,
});
placed.push({ x: px, y: py });
placedLabel = true;
break;
}
}
if (!placedLabel) {
const pt = pts[0];
lineLabels.push({
key,
graphId,
label: labelText,
color: getRooflineColor(key),
x: xScale(pt.x),
y: yScale(pt.y),
visible: false,
});
}
}
} else {
// TTFT / E2EL: endpoint labels with vertical nudge to avoid overlap.
for (const [graphId, { key, pts }] of bestByGraph.entries()) {
const pt = pts.at(-1)!;
lineLabels.push({
key,
graphId,
label: labelTextFor(pts, runNumbering),
color: getRooflineColor(key),
x: xScale(pt.x),
y: yScale(pt.y),
visible: true,
});
}
if (lineLabels.length > 1) {
const yRange = yScale.range();
const top = Math.min(yRange[0], yRange[1]) + LABEL_H;
const bottom = Math.max(yRange[0], yRange[1]) - LABEL_H;
lineLabels.sort((a, b) => a.y - b.y);
for (let pass = 0; pass < 5; pass++) {
for (let i = 1; i < lineLabels.length; i++) {
const overlap = lineLabels[i - 1].y + LABEL_H - lineLabels[i].y;
if (overlap > 0) {
const half = overlap / 2;
lineLabels[i - 1].y -= half;
lineLabels[i].y += half;
}
}
for (const l of lineLabels) {
l.y = Math.max(top, Math.min(bottom, l.y));
}
}
}
}
const llSel = zoomGroup
.selectAll<SVGGElement, LineLabel>('.line-label')
.data(lineLabels, (d) => d.key)
.join(
(enter) => {
const g = enter
.append('g')
.attr('class', 'line-label')
.style('pointer-events', 'none');
g.append('rect').attr('class', 'll-bg').attr('rx', 4).attr('ry', 4);
g.append('text')
.attr('class', 'll-text')
.attr('text-anchor', 'start')
.attr('dominant-baseline', 'central')
.attr('fill', 'white')
.attr('font-size', '10px')
.attr('font-weight', '600');
return g;
},
(update) => update,
(exit) => exit.remove(),
)
.attr('data-line-key', (d) => d.key)
.attr('data-graph-id', (d) => d.graphId)
.attr('transform', (d) => `translate(${d.x + 8},${d.y - 14})`)
.style('opacity', (d) => (d.visible ? 0.95 : 0));
// Size each label's background to its text in two passes — write all
// texts, then measure all bboxes — so the batch forces one layout
// instead of one per label (mirrors ScatterGraph's label loops).
llSel.each(function (d) {
d3.select(this).select<SVGTextElement>('.ll-text').text(d.label);
});
const llMeasured: { node: SVGGElement; d: LineLabel; bbox: DOMRect }[] = [];
llSel.each(function (d) {
const text = this.querySelector<SVGTextElement>('.ll-text');
if (text) llMeasured.push({ node: this, d, bbox: text.getBBox() });
});
for (const { node, d, bbox } of llMeasured) {
const px = 5;
const py = 3;
d3.select(node)
.select('.ll-bg')
.attr('x', bbox.x - px)
.attr('y', bbox.y - py)
.attr('width', bbox.width + px * 2)
.attr('height', bbox.height + py * 2)
.attr('fill', d.color);
}
},
onZoom: (zoomGroup, ctx) => {
if (!showLineLabels) return;
const newXScale = ctx.newXScale as ContinuousScale;
const newYScale = ctx.newYScale as ContinuousScale;
// Mirror the placement algorithm with the zoomed scales so labels
// stay anchored to their rooflines without jumping on zoom.
const isInteractivity = chartDefinition.chartType === 'interactivity';
const LABEL_H = 18;
const LABEL_W = 160;
const bestByGraph = new Map<string, { key: string; pts: InferenceData[] }>();
for (const [key, pts] of Object.entries(rooflines)) {
if (pts.length < 2 || !isRooflineVisible(key)) continue;
const graphId = key.slice(0, key.lastIndexOf('_'));
const prev = bestByGraph.get(graphId);
if (!prev || pts.length > prev.pts.length) bestByGraph.set(graphId, { key, pts });
}
const zoomResults = new Map<string, { x: number; y: number; vis: boolean }>();
if (isInteractivity) {
const placed: { x: number; y: number }[] = [];
const collides = (cx: number, cy: number) =>
placed.some((p) => Math.abs(p.y - cy) < LABEL_H && Math.abs(p.x - cx) < LABEL_W);
const sorted = [...bestByGraph.entries()].toSorted(
([, a], [, b]) => newYScale(a.pts[0].y) - newYScale(b.pts[0].y),
);
for (const [, { key, pts }] of sorted) {
const candidates = [
pts[Math.min(1, pts.length - 1)],
pts[Math.floor(pts.length / 2)],
pts[Math.max(0, Math.floor((pts.length * 2) / 3))],
pts.at(-1)!,
];
let found = false;
for (const pt of candidates) {
const px = newXScale(pt.x);
const py = newYScale(pt.y);
if (!collides(px, py)) {
zoomResults.set(key, { x: px, y: py, vis: true });
placed.push({ x: px, y: py });
found = true;
break;
}
}
if (!found) {
zoomResults.set(key, {
x: newXScale(pts[0].x),
y: newYScale(pts[0].y),
vis: false,
});
}
}
} else {
interface ZL {
key: string;
x: number;
y: number;
}
const zls: ZL[] = [];
for (const [, { key, pts }] of bestByGraph.entries()) {
const pt = pts.at(-1)!;
zls.push({ key, x: newXScale(pt.x), y: newYScale(pt.y) });
}
if (zls.length > 1) {
const yRange = newYScale.range();
const top = Math.min(yRange[0], yRange[1]) + LABEL_H;
const bottom = Math.max(yRange[0], yRange[1]) - LABEL_H;
zls.sort((a, b) => a.y - b.y);
for (let pass = 0; pass < 5; pass++) {
for (let i = 1; i < zls.length; i++) {
const overlap = zls[i - 1].y + LABEL_H - zls[i].y;
if (overlap > 0) {
const half = overlap / 2;
zls[i - 1].y -= half;
zls[i].y += half;
}
}
for (const z of zls) z.y = Math.max(top, Math.min(bottom, z.y));
}
}
for (const z of zls) zoomResults.set(z.key, { x: z.x, y: z.y, vis: true });
}
zoomGroup.selectAll<SVGGElement, unknown>('.line-label').each(function () {
const el = d3.select(this);
const k = el.attr('data-line-key');
const zl = zoomResults.get(k);
if (zl) {
el.attr('transform', `translate(${zl.x + 8},${zl.y - 14})`);
el.style('opacity', zl.vis ? 0.95 : 0);
} else {
el.style('opacity', 0);
}
});
},
}),
[
showLineLabels,
rooflines,
isRooflineVisible,
getRooflineColor,
chartDefinition.chartType,
runNumbering,
],
);
// Dismiss tooltip when pinned point's combo is hidden
useEffect(() => {
const pp = chartRef.current?.getPinnedPoint() as InferenceData | null;
if (pp && !activeDates.has(`${pp.date}_${pp.hwKey}`)) chartRef.current?.dismissTooltip();
}, [activeDates]);
// Dismiss on filter changes
useEffect(() => {
chartRef.current?.dismissTooltip();
}, [selectedPrecisions, selectedYAxisMetric, selectedGPUs, selectedDates, selectedDateRange]);
// Hover dimming animates via the inline `transition: opacity 150ms ease`
// onRender puts on dots and rooflines — a single style write per node. A
// d3 `.transition()` here would re-write opacity every animation frame,
// each write restarting the CSS transition (transitionrun/cancel per node
// per frame). Same rationale as ScatterGraph's hover handlers.
const handleLegendHover = useCallback((seriesId: string) => {
const svg = chartRef.current?.getSvgElement?.();
if (!svg) return;
const root = d3.select(svg);
root
.selectAll<SVGGElement, InferenceData>('.dot-group')
.style('opacity', (d) => (`${d.date}_${d.hwKey}` === seriesId ? 1 : 0.15));
root.selectAll<SVGPathElement, unknown>('.roofline-path').style('opacity', function () {
const key = (d3.select(this).datum() as { key: string } | null)?.key ?? '';
const series = key.slice(0, key.lastIndexOf('_'));
return series === seriesId ? null : '0.15';
});
}, []);
const handleLegendHoverEnd = useCallback(() => {
const svg = chartRef.current?.getSvgElement?.();
if (!svg) return;
const root = d3.select(svg);
root.selectAll('.dot-group').style('opacity', null);
root.selectAll('.roofline-path').style('opacity', null);
}, []);
if (data.length === 0) {
return (
<div className="relative w-full p-3">
<div className="flex flex-col items-center justify-center min-h-100 text-center">
<div className="text-muted-foreground">
<svg
className="mx-auto size-12 mb-4"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={1.5}
d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
/>
</svg>
<h3 className="text-sm font-medium mb-1">No data available</h3>
<p className="text-xs">
Please change the model, sequence, precision, date range or GPU selection.
</p>
</div>
</div>
</div>
);
}
return (
<D3Chart<InferenceData>
ref={chartRef}
chartId={chartId}
data={filteredData}
margin={CHART_MARGIN}
watermark={getChartWatermark()}
testId="gpu-graph"
grabCursor={true}
caption={caption}
xScale={{ type: 'linear', domain: xExtent, nice: true }}
yScale={{ type: logScale ? 'log' : 'linear', domain: yDomain, nice: true }}
xAxis={{
label: xLabel,
tickFormat: (d) => formatNumber(d as number),
tickCount: 10,
}}
yAxis={{
label: yLabel,
tickFormat: logScale ? undefined : (d) => formatLargeNumber(d as number),
tickCount: 10,
}}
layers={[
{
type: 'roofline',
key: 'rooflines',
rooflines: rooflines as Record<string, { x: number; y: number }[]>,
config: {
getColor: getRooflineColor,
isVisible: isRooflineVisible,
},
},
{
type: 'scatter',
key: 'points',
data: filteredData,
config: {
getColor,
hideLabels: !showPointLabels,
// Match ScatterGraph: append the concurrency (C=) to the
// parallelism/tp label so compare-mode points are annotated the
// same way as the single-run scatter chart.
getLabelText: (d) =>
useAdvancedLabels ? `${getPointLabel(d)}\nC=${d.conc}` : `${d.tp}\nC=${d.conc}`,
foreground: 'var(--foreground)',
dataAttrs: {
series: (d) => `${d.date}_${d.hwKey}`,
},
selectedPrecisions,
},
},
lineLabelLayer,
knownIssueLayer,
]}
zoom={{
enabled: true,
axes: 'both',
scaleExtent: [1, 20],
resetEventName: `gpu_timeseries_zoom_reset_${chartId}`,
onReset: () => {
track('interactivity_zoom_reset');
},
onZoom: (_event, ctx: ZoomContext) => {
if (logScale) {
const newYScale = ctx.newYScale as d3.ScaleLogarithmic<number, number>;
ctx.layout.yAxisGroup.call(
d3.axisLeft(newYScale).ticks(10).tickFormat(logTickFormat(newYScale)) as any,
);
}
},
}}
tooltip={{
rulerType: 'crosshair',
content: (d: InferenceData, isPinned: boolean) =>
generateGPUGraphTooltipContent({
data: d,
isPinned,
xLabel,
yLabel,
selectedYAxisMetric,
hardwareConfig,
runUrl: d.run_url ? updateRepoUrl(d.run_url) : undefined,
hasTrace: typeof d.id === 'number' ? traceAvailability?.[d.id] === true : false,
locale,
}),
getRulerX: (d, xScale) => (xScale as d3.ScaleLinear<number, number>)(d.x),
getRulerY: (d, yScale) => (yScale as d3.ScaleLinear<number, number>)(d.y),
onHoverStart: (sel, d) =>
applyHoverState(
sel.select('.visible-shape') as any,
getShapeKeyForPrecision(d.precision, selectedPrecisions),
),
onHoverEnd: (sel, d) =>
applyNormalState(
sel.select('.visible-shape') as any,
getShapeKeyForPrecision(d.precision, selectedPrecisions),
),
onPointClick: (d: InferenceData) => {
track('gpu_timeseries_data_point_clicked', {
id: d.id,
hw: String(d.hwKey),
x: d.x,
y: d.y,
});
const tooltipEl = chartRef.current?.getTooltipElement();
if (!tooltipEl) return;
const viewBtn = tooltipEl.querySelector('[data-action="view-charts"]');
if (!viewBtn || typeof d.id !== 'number') return;
viewBtn.addEventListener('click', (event) => {
event.stopPropagation();
track('gpu_timeseries_view_charts_opened', {
id: d.id,
hwKey: String(d.hwKey),
conc: d.conc,
});
});
// Pinning updates D3Chart's React state. GPU comparison rebuilds
// several inline layer configs on that render, whose cleanup can
// briefly hide the otherwise-pinned portal tooltip. Restore its
// pinned visibility after that render settles.
requestAnimationFrame(() => {
const pinnedTooltip = chartRef.current?.getTooltipElement();
if (!pinnedTooltip || chartRef.current?.getPinnedPoint() !== d) return;
pinnedTooltip.style.opacity = '1';
pinnedTooltip.style.display = 'block';
pinnedTooltip.style.pointerEvents = 'auto';
});
},
attachToLayer: 1,
}}
onRender={(ctx: RenderContext) => {
// Apply log tick format on initial render (needs the built scale)
if (logScale) {
const yScale = ctx.yScale as d3.ScaleLogarithmic<number, number>;
ctx.layout.yAxisGroup.call(
d3.axisLeft(yScale).ticks(10).tickFormat(logTickFormat(yScale)) as any,
);
}
// Set foreground color on scatter point labels
ctx.layout.zoomGroup.selectAll('.point-label').style('fill', 'var(--foreground)');
// CSS transitions for smooth opacity animation on legend hover —
// the hover handlers write opacity once and let these animate.
ctx.layout.zoomGroup
.selectAll('.dot-group, .roofline-path')
.style('transition', 'opacity 150ms ease');
// Offload halo: dashed ring on every point that used KV offload
// (mirrors ScatterGraph so compare mode shows the same CPU-offload
// indicator). The ring is a child of the dot-group, so it travels
// with the point on zoom/pan without a separate onZoom pass.
ctx.layout.zoomGroup
.selectAll<SVGGElement, InferenceData>('.dot-group')
.each(function (d) {
const showHalo = d.offload_mode === 'on';
d3.select(this)
.selectAll<SVGCircleElement, boolean>('.offload-halo')
.data(showHalo ? [true] : [])
.join('circle')
.attr('class', 'offload-halo')
.attr('r', POINT_SIZE + 4)
.attr('fill', 'none')
.attr('stroke', 'var(--foreground)')
.attr('stroke-width', 1.5)
.attr('stroke-dasharray', '3 2')
.attr('opacity', 0.9)
.attr('pointer-events', 'none');
});
}}
legendElement={
<ChartLegend
variant="sidebar"
grouped={true}
disableActiveSort={true}
onItemHover={handleLegendHover}
onItemHoverEnd={handleLegendHoverEnd}
onItemRemove={handleLegendRemove}
legendItems={allGraphs
.filter(({ id }) => idsWithData.has(id))
.map(({ date, color, hwKey, id }) => ({
name: `${hwKey} ${comparisonEntryLabel(date, runNumbering)}`,
hw: id,
label: comparisonEntryLabel(date, runNumbering),
color,
title: getDisplayLabel(getHardwareConfig(hwKey, modelLabel)),
isActive: activeDates.has(id),
onClick: () => {
toggleActiveDate(id);
track('interactivity_date_toggled', { date, hw: hwKey });
},
}))}
isLegendExpanded={isLegendExpanded}
onExpandedChange={(expanded) => {
setIsLegendExpanded(expanded);
track('interactivity_legend_expanded', { expanded });
}}
switches={[
{
id: 'gpu-log-scale',
label: legendT.logScale,
checked: logScale,
onCheckedChange: (c) => {
setLogScale(c);
track('interactivity_log_scale_toggled', { enabled: c });
},
},
{
id: 'gpu-high-contrast',
label: legendT.highContrast,
checked: highContrast,
onCheckedChange: (c) => {
setHighContrast(c);
track('interactivity_high_contrast_toggled', { enabled: c });
},
},
{
id: 'gpu-hide-non-optimal',
label: legendT.optimalOnly,
checked: hideNonOptimal,
onCheckedChange: (c) => {
setHideNonOptimal(c);
track('interactivity_hide_non_optimal_toggled', { enabled: c });
},
},
{
id: 'gpu-point-labels',
label: legendT.labels,
checked: showPointLabels,