Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions frontend/src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export type { ChatBubbleProps } from '@cloudscape-design/chat-components/chat-bu
export { default as Avatar } from '@cloudscape-design/chat-components/avatar';
export type { AvatarProps } from '@cloudscape-design/chat-components/avatar';
export { default as LineChart } from '@cloudscape-design/components/line-chart';
export { default as BarChart } from '@cloudscape-design/components/bar-chart';
export { default as PropertyFilter } from '@cloudscape-design/components/property-filter';
export type { PropertyFilterProps } from '@cloudscape-design/components/property-filter';
export { default as DateRangePicker } from '@cloudscape-design/components/date-range-picker';
Expand Down
70 changes: 12 additions & 58 deletions frontend/src/libs/presets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,71 +24,25 @@ export const formatTokenCount = (value: number): string => {
return String(value);
};

/** As the CLI prints a sweep: one value when they agree, otherwise `min..max`. */
export const formatTokenRange = (values: number[]): string => {
const low = Math.min(...values);
const high = Math.max(...values);
return low === high ? formatTokenCount(low) : `${formatTokenCount(low)}..${formatTokenCount(high)}`;
};

const trimZero = (value: string): string => (value.endsWith('.0') ? value.slice(0, -2) : value);

/** As the CLI prints durations: 999.6 reads as 1s rather than 1000ms. */
const formatDurationMs = (value: number): string => (value < 999.5 ? `${round(value)}ms` : `${round(value / 1000)}s`);

const round = (value: number): string => String(Math.round(value * 100) / 100);

/**
* Request counts, wall time, and token totals say nothing about how the preset
* performs: the totals are the workload multiplied by the request count, which
* the constraints already state.
*/
const HIDDEN_METRICS = new Set([
'successful_requests',
'failed_requests',
'duration_seconds',
'total_input_tokens',
'total_output_tokens',
]);

const METRIC_LABELS: Record<string, string> = {
output_tok_per_s: 'TPS',
per_user_tok_per_s: 'TPS/user',
total_input_tokens: 'Input tokens',
total_output_tokens: 'Output tokens',
ttft_ms: 'TTFT',
tpot_ms: 'TPOT',
};

const TOKEN_COUNT_METRICS = new Set(['total_input_tokens', 'total_output_tokens']);

export type BenchmarkMetric = { label: string; value: string };

const formatMetricValue = (key: string, value: number): string => {
if (TOKEN_COUNT_METRICS.has(key)) return formatTokenCount(value);
if (key.endsWith('_ms')) return formatDurationMs(value);
return round(value);
};

/**
* The metrics worth showing, flattened: a metric measured as a distribution
* becomes one entry per statistic.
*/
export const getBenchmarkMetrics = (metrics: HashMap): BenchmarkMetric[] => {
const entries: BenchmarkMetric[] = [];

Object.entries(metrics ?? {}).forEach(([key, value]) => {
if (HIDDEN_METRICS.has(key)) return;
const label = METRIC_LABELS[key] ?? key;

if (typeof value === 'number') {
entries.push({ label, value: formatMetricValue(key, value) });
return;
}

if (value && typeof value === 'object') {
Object.entries(value as HashMap).forEach(([statistic, statisticValue]) => {
if (typeof statisticValue !== 'number') return;
entries.push({
label: `${label} ${statistic}`,
value: formatMetricValue(key, statisticValue),
});
});
}
});

return entries;
/** How a benchmark metric's values are printed, picked by the metric's name. */
export const getMetricFormatter = (key: string): ((value: number) => string) => {
if (TOKEN_COUNT_METRICS.has(key)) return formatTokenCount;
if (key.endsWith('_ms')) return formatDurationMs;
return round;
};
2 changes: 2 additions & 0 deletions frontend/src/locale/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -911,6 +911,8 @@
"no_cli_description": "To use dstack, install the CLI on your local machine.",
"constraints": "Constraints",
"concurrency": "Concurrency",
"metric": "Metric",
"no_benchmark_data": "No data",
"dataset": "Dataset",
"input_tokens": "Input tokens",
"output_tokens": "Output tokens",
Expand Down
93 changes: 93 additions & 0 deletions frontend/src/pages/Presets/Details/Benchmark/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { formatTokenCount, getMetricFormatter } from 'libs/presets';

export type BenchmarkChart = {
group: string;
title: string;
formatValue: (value: number) => string;
data: { x: string; y: number }[];
};

/**
* Request counts, wall time, and token totals say nothing about how the preset
* performs: the totals are the workload multiplied by the request count, which
* the constraints already state.
*/
const HIDDEN_METRICS = new Set([
'successful_requests',
'failed_requests',
'duration_seconds',
'total_input_tokens',
'total_output_tokens',
]);

const METRIC_LABELS: Record<string, string> = {
output_tok_per_s: 'tok/s',
per_user_tok_per_s: 'tok/s/user',
total_input_tokens: 'Input tokens',
total_output_tokens: 'Output tokens',
ttft_ms: 'TTFT',
tpot_ms: 'TPOT',
};

/** The tab a metric is shown under. A metric not listed here gets a tab of its own. */
const METRIC_GROUPS: Record<string, string> = {
output_tok_per_s: 'tok/s',
per_user_tok_per_s: 'tok/s',
ttft_ms: 'TTFT',
tpot_ms: 'TPOT',
};

/** The x axis: every concurrency of the sweep, in ascending order. */
export const getConcurrencies = (results: IPresetResult[]): string[] =>
sortResults(results).map(({ concurrency }) => String(concurrency));

/**
* One chart per metric worth showing, each with a value per concurrency, and
* one for the context length. A metric measured as a distribution becomes one
* chart per statistic. A concurrency without a benchmark has no point.
*/
export const getBenchmarkCharts = (results: IPresetResult[], contextLengthLabel: string): BenchmarkChart[] => {
const charts = new Map<string, BenchmarkChart>();
const sorted = sortResults(results);

const addPoint = (title: string, key: string, concurrency: number, value: unknown) => {
if (typeof value !== 'number') return;
if (!charts.has(title)) {
const group = METRIC_GROUPS[key] ?? METRIC_LABELS[key] ?? key;
charts.set(title, { group, title, formatValue: getMetricFormatter(key), data: [] });
}
charts.get(title)?.data.push({ x: String(concurrency), y: value });
};

sorted.forEach(({ concurrency, benchmark }) => {
Object.entries(benchmark?.metrics ?? {}).forEach(([key, value]) => {
if (HIDDEN_METRICS.has(key)) return;
const label = METRIC_LABELS[key] ?? key;

if (value && typeof value === 'object') {
Object.entries(value as HashMap).forEach(([statistic, statisticValue]) =>
addPoint(`${label} ${statistic}`, key, concurrency, statisticValue),
);
return;
}

addPoint(label, key, concurrency, value);
});
});

const contextLengthChart: BenchmarkChart = {
group: contextLengthLabel,
title: contextLengthLabel,
formatValue: formatTokenCount,
data: sorted.flatMap(({ concurrency, context_length }) =>
typeof context_length === 'number' ? [{ x: String(concurrency), y: context_length }] : [],
),
};

return [...Array.from(charts.values()), contextLengthChart];
};

/** The tabs, in the order their first chart appears. */
export const getChartGroups = (charts: BenchmarkChart[]): string[] => Array.from(new Set(charts.map(({ group }) => group)));

const sortResults = (results: IPresetResult[]): IPresetResult[] => [...results].sort((a, b) => a.concurrency - b.concurrency);
75 changes: 52 additions & 23 deletions frontend/src/pages/Presets/Details/Benchmark/index.tsx
Original file line number Diff line number Diff line change
@@ -1,50 +1,79 @@
import React, { FC } from 'react';
import React, { FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';

import { Box, ColumnLayout, Container, Header, Loader } from 'components';
import { BarChart, Box, Container, Header, Loader, SelectCSD, Tabs } from 'components';

import { formatTokenCount, getBenchmarkMetrics } from 'libs/presets';
import { useGetPresetQuery } from 'services/preset';
import { useBenchmarkCharts } from './useBenchmarkCharts';

export const PresetBenchmark: FC = () => {
const { t } = useTranslation();
const params = useParams();
const paramProjectName = params.projectName ?? '';
const paramPresetId = params.presetId ?? '';
const [activeGroup, setActiveGroup] = useState<string | null>(null);
// Each tab remembers the metric last picked in it.
const [metricByGroup, setMetricByGroup] = useState<Record<string, string>>({});

const { data, isLoading } = useGetPresetQuery({
const { isLoading, concurrencies, charts, groups } = useBenchmarkCharts({
project_name: paramProjectName,
id: paramPresetId,
});

if (isLoading || !data)
if (isLoading)
return (
<Container>
<Loader />
</Container>
);

const metrics = getBenchmarkMetrics(data.spec.preset.benchmark.metrics as HashMap);
const group = activeGroup ?? groups[0];
const groupCharts = charts.filter((chart) => chart.group === group);
const chart = groupCharts.find(({ title }) => title === metricByGroup[group]) ?? groupCharts[0];

// Only the open tab's chart is drawn, so the others carry no content.
const tabs = groups.map((id) => ({
id,
label: id,
content: id === group && (
<BarChart
series={[{ title: chart.title, type: 'bar', data: chart.data, valueFormatter: chart.formatValue }]}
xDomain={concurrencies}
xScaleType="categorical"
xTitle={t('presets.concurrency')}
i18nStrings={{ yTickFormatter: chart.formatValue }}
ariaLabel={chart.title}
height={300}
hideFilter
hideLegend
empty={<Box textAlign="center">{t('presets.no_benchmark_data')}</Box>}
/>
),
}));

return (
<Container header={<Header variant="h2">{t('presets.benchmark')}</Header>}>
<ColumnLayout columns={4} variant="text-grid">
<div>
<Box variant="awsui-key-label">{t('presets.context_length')}</Box>
<div>{formatTokenCount(data.spec.preset.context_length)}</div>
</div>
<div>
<Box variant="awsui-key-label">{t('presets.concurrency')}</Box>
<div>{String((data.spec.preset.benchmark.workload as HashMap)?.concurrency)}</div>
</div>
{metrics.map(({ label, value }) => (
<div key={label}>
<Box variant="awsui-key-label">{label}</Box>
<div>{value}</div>
</div>
))}
</ColumnLayout>
<Tabs
tabs={tabs}
activeTabId={group}
onChange={({ detail }) => setActiveGroup(detail.activeTabId)}
// A tab with a single metric has nothing to pick.
actions={
groupCharts.length > 1 && (
<SelectCSD
selectedOption={{ label: chart.title, value: chart.title }}
options={groupCharts.map(({ title }) => ({ label: title, value: title }))}
onChange={({ detail }) =>
setMetricByGroup((current) => ({
...current,
[group]: detail.selectedOption.value ?? chart.title,
}))
}
ariaLabel={t('presets.metric')}
/>
)
}
/>
</Container>
);
};
19 changes: 19 additions & 0 deletions frontend/src/pages/Presets/Details/Benchmark/useBenchmarkCharts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';

import { useGetPresetQuery } from 'services/preset';

import { getBenchmarkCharts, getChartGroups, getConcurrencies } from './helpers';

export const useBenchmarkCharts = (params: { project_name: string; id: string }) => {
const { t } = useTranslation();
const { data, isLoading } = useGetPresetQuery(params);

const concurrencies = useMemo(() => getConcurrencies(data?.spec.preset.result ?? []), [data]);

const charts = useMemo(() => getBenchmarkCharts(data?.spec.preset.result ?? [], t('presets.context_length')), [data, t]);

const groups = useMemo(() => getChartGroups(charts), [charts]);

return { isLoading: isLoading || !data, concurrencies, charts, groups };
};
13 changes: 9 additions & 4 deletions frontend/src/pages/Presets/Details/Constraints/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useParams } from 'react-router-dom';

import { Box, ColumnLayout, Container, Header, Loader } from 'components';

import { formatTokenCount } from 'libs/presets';
import { formatTokenCount, formatTokenRange } from 'libs/presets';
import { useGetPresetQuery } from 'services/preset';

export const PresetConstraints: FC = () => {
Expand All @@ -27,7 +27,12 @@ export const PresetConstraints: FC = () => {

// The conditions the benchmark holds for: the workload it measured and the
// context the service was verified to serve.
const workload = (data.spec.preset.benchmark.workload ?? {}) as HashMap;
// The dataset and shared prefix are the same across concurrencies, so the
// first benchmarked result stands for all of them. The measured token
// averages can differ, so those show as ranges.
const results = data.spec.preset.result;
const workloads = results.flatMap(({ benchmark }) => (benchmark ? [benchmark.workload as HashMap] : []));
const workload = workloads[0] ?? {};
const dataset = workload.dataset as string | undefined;
const inputTokens = workload.input_tokens as number;
const sharedPrefix = (workload.shared_prefix_tokens as number) ?? 0;
Expand All @@ -43,11 +48,11 @@ export const PresetConstraints: FC = () => {
)}
<div>
<Box variant="awsui-key-label">{t('presets.input_tokens')}</Box>
<div>{formatTokenCount(inputTokens)}</div>
<div>{formatTokenRange(workloads.map((w) => w.input_tokens as number))}</div>
</div>
<div>
<Box variant="awsui-key-label">{t('presets.output_tokens')}</Box>
<div>{formatTokenCount(workload.output_tokens as number)}</div>
<div>{formatTokenRange(workloads.map((w) => w.output_tokens as number))}</div>
</div>
{sharedPrefix > 0 && (
<div>
Expand Down
9 changes: 7 additions & 2 deletions frontend/src/types/preset.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,18 @@ declare interface IPresetVerificationReplicaGroup {
replicas: HashMap[];
}

declare interface IPresetResult {
concurrency: number;
context_length?: number | null;
benchmark?: IPresetBenchmark | null;
}

declare interface IPresetSpec {
preset: {
base: string;
repo: string;
context_length: number;
service: HashMap;
benchmark: IPresetBenchmark;
result: IPresetResult[];
verified_on: IPresetVerificationReplicaGroup[];
};
file_archives: { id: string; path: string }[];
Expand Down
Loading