Skip to content

Commit 9488fbf

Browse files
committed
examples : add new sweep-bench benchmark
1 parent 2fb3c32 commit 9488fbf

File tree

5 files changed

+351
-0
lines changed

5 files changed

+351
-0
lines changed

examples/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ else()
5050
add_subdirectory(simple-chat)
5151
add_subdirectory(speculative)
5252
add_subdirectory(speculative-simple)
53+
add_subdirectory(sweep-bench)
5354
add_subdirectory(tokenize)
5455
add_subdirectory(tts)
5556
add_subdirectory(gen-docs)
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
set(TARGET llama-sweep-bench)
2+
add_executable(${TARGET} sweep-bench.cpp)
3+
install(TARGETS ${TARGET} RUNTIME)
4+
target_link_libraries(${TARGET} PRIVATE common llama ${CMAKE_THREAD_LIBS_INIT})
5+
target_compile_features(${TARGET} PRIVATE cxx_std_17)

examples/sweep-bench/README.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# llama.cpp/example/sweep-bench
2+
3+
Benchmark the prompt processing and token generation performance of `llama.cpp`
4+
by doing a sweep over a whole context size and gathering performance metrics
5+
in each ubatch-sized window. Only a single token sequence is used.
6+
7+
The benchmark steps are:
8+
9+
for each ubatch-sized window in context:
10+
1. generate ubatch/4 tokens (not the whole window to save some time)
11+
2. measure generation performance
12+
3. remove generated tokens from KV cache
13+
4. prepare a ubatch-sized batch of random tokens
14+
4. process prepated batch
15+
5. measure prompt processing performance
16+
17+
The purpose of the benchmark is to visualize how the performance changes with
18+
the context size without averaging the metrics values over the whole context.
19+
20+
## Usage
21+
22+
./llama-sweep-bench -c 8704 -ub 512 -m models/Meta-Llama-3.2-3B-Instruct-Q8_0.gguf
23+
24+
## Sample results
25+
26+
- `PP` - prompt tokens per ubatch
27+
- `TG` - generated tokens per ubatch
28+
- `N_KV` - current KV cache size
29+
- `T_PP` - prompt processing time (i.e. time to first token)
30+
- `S_PP` - prompt processing speed (`(B*PP)/T_PP` or `PP/T_PP`)
31+
- `T_TG` - time to generate all batches
32+
- `S_TG` - text generation speed (`(B*TG)/T_TG`)
33+
34+
| PP | TG | N_KV | T_PP s | S_PP t/s | T_TG s | S_TG t/s |
35+
|-------|--------|--------|----------|----------|----------|----------|
36+
| 512 | 128 | 0 | 1.100 | 465.51 | 2.311 | 55.38 |
37+
| 512 | 128 | 512 | 1.183 | 432.97 | 1.895 | 67.55 |
38+
| 512 | 128 | 1024 | 1.305 | 392.38 | 2.071 | 61.81 |
39+
| 512 | 128 | 1536 | 1.279 | 400.42 | 2.164 | 59.14 |
40+
| 512 | 128 | 2048 | 1.571 | 325.96 | 2.280 | 56.14 |
41+
| 512 | 128 | 2560 | 1.431 | 357.87 | 2.418 | 52.94 |
42+
| 512 | 128 | 3072 | 1.515 | 337.93 | 2.566 | 49.88 |
43+
| 512 | 128 | 3584 | 1.588 | 322.34 | 2.722 | 47.03 |
44+
| 512 | 128 | 4096 | 1.675 | 305.70 | 2.864 | 44.69 |
45+
| 512 | 128 | 4608 | 1.769 | 289.50 | 2.999 | 42.68 |
46+
| 512 | 128 | 5120 | 1.845 | 277.48 | 3.102 | 41.26 |
47+
| 512 | 128 | 5632 | 1.893 | 270.46 | 3.219 | 39.76 |
48+
| 512 | 128 | 6144 | 1.953 | 262.20 | 3.348 | 38.23 |
49+
| 512 | 128 | 6656 | 2.018 | 253.71 | 3.474 | 36.84 |
50+
| 512 | 128 | 7168 | 2.078 | 246.34 | 3.589 | 35.66 |
51+
| 512 | 128 | 7680 | 2.140 | 239.22 | 3.717 | 34.43 |
52+
| 512 | 128 | 8192 | 2.196 | 233.15 | 3.854 | 33.21 |
53+
54+
### JSONL output
55+
56+
Pass `--output-format jsonl` to output JSONL instead of Markdown, á la
57+
58+
```json lines
59+
{"n_kv_max": 8704, "n_batch": 2048, "n_ubatch": 512, "flash_attn": 0, "n_gpu_layers": -1, "n_threads": 32, "n_threads_batch": 32, "pp": 512, "tg": 128, "n_kv": 0, "t_pp": 1.093814, "speed_pp": 468.086884, "t_tg": 1.780312, "speed_tg": 71.897514 }
60+
{"n_kv_max": 8704, "n_batch": 2048, "n_ubatch": 512, "flash_attn": 0, "n_gpu_layers": -1, "n_threads": 32, "n_threads_batch": 32, "pp": 512, "tg": 128, "n_kv": 512, "t_pp": 1.169302, "speed_pp": 437.868073, "t_tg": 1.897474, "speed_tg": 67.458099 }
61+
{"n_kv_max": 8704, "n_batch": 2048, "n_ubatch": 512, "flash_attn": 0, "n_gpu_layers": -1, "n_threads": 32, "n_threads_batch": 32, "pp": 512, "tg": 128, "n_kv": 1024, "t_pp": 1.183700, "speed_pp": 432.542053, "t_tg": 2.059179, "speed_tg": 62.160694 }
62+
{"n_kv_max": 8704, "n_batch": 2048, "n_ubatch": 512, "flash_attn": 0, "n_gpu_layers": -1, "n_threads": 32, "n_threads_batch": 32, "pp": 512, "tg": 128, "n_kv": 1536, "t_pp": 1.428625, "speed_pp": 358.386566, "t_tg": 2.160639, "speed_tg": 59.241734 }
63+
{"n_kv_max": 8704, "n_batch": 2048, "n_ubatch": 512, "flash_attn": 0, "n_gpu_layers": -1, "n_threads": 32, "n_threads_batch": 32, "pp": 512, "tg": 128, "n_kv": 2048, "t_pp": 1.360647, "speed_pp": 376.291595, "t_tg": 2.274003, "speed_tg": 56.288403 }
64+
```
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import pandas as pd
2+
import matplotlib.pyplot as plt
3+
import numpy as np
4+
import argparse
5+
6+
parser = argparse.ArgumentParser()
7+
parser.add_argument('file', nargs='+')
8+
args = parser.parse_args()
9+
10+
df = None
11+
12+
for jsonl_file in args.file:
13+
# Read JSONL file into DataFrame
14+
df_part = pd.read_json(jsonl_file, lines=True)
15+
df_part['label'] = jsonl_file
16+
if df is None:
17+
df = df_part
18+
else:
19+
df = pd.concat([df, df_part])
20+
21+
# Group by model and n_kv, calculate mean and std for both speed metrics
22+
df_grouped = df.groupby(['label', 'n_kv']).agg({
23+
'speed_pp': ['mean', 'std'],
24+
'speed_tg': ['mean', 'std']
25+
}).reset_index()
26+
27+
# Flatten multi-index columns
28+
df_grouped.columns = ['label', 'n_kv', 'speed_pp_mean', 'speed_pp_std',
29+
'speed_tg_mean', 'speed_tg_std']
30+
31+
# Replace NaN with 0 (std for a single sample is NaN)
32+
33+
df_grouped['speed_pp_std'] = df_grouped['speed_pp_std'].fillna(0)
34+
df_grouped['speed_tg_std'] = df_grouped['speed_tg_std'].fillna(0)
35+
36+
# Prepare ticks values for X axis (prune for readability)
37+
x_ticks = df['n_kv'].unique()
38+
while len(x_ticks) > 16:
39+
x_ticks = x_ticks[::2]
40+
41+
# Get unique labels and color map
42+
labels = df_grouped['label'].unique()
43+
colors = plt.cm.rainbow(np.linspace(0, 1, len(labels)))
44+
45+
# Create prompt processing plot
46+
plt.figure(figsize=(10, 6))
47+
ax1 = plt.gca()
48+
49+
plt.grid()
50+
51+
ax1.set_xticks(x_ticks)
52+
53+
# Plot each label's data
54+
for label, color in zip(labels, colors):
55+
label_data = df_grouped[df_grouped['label'] == label].sort_values('n_kv')
56+
57+
# Plot prompt processing
58+
pp = ax1.errorbar(label_data['n_kv'], label_data['speed_pp_mean'],
59+
yerr=label_data['speed_pp_std'], color=color,
60+
marker='o', linestyle='-', label=label)
61+
62+
# Add labels and title
63+
ax1.set_xlabel('Context Length (tokens)')
64+
ax1.set_ylabel('Prompt Processing Rate (t/s)')
65+
plt.title('Prompt Processing Performance Comparison')
66+
67+
ax1.legend(loc='upper right')
68+
69+
# Adjust layout and save
70+
plt.tight_layout()
71+
plt.savefig('performance_comparison_pp.png', bbox_inches='tight')
72+
plt.close()
73+
74+
# Create token generation plot
75+
plt.figure(figsize=(10, 6))
76+
ax1 = plt.gca()
77+
78+
plt.grid()
79+
ax1.set_xticks(x_ticks)
80+
81+
# Plot each model's data
82+
for label, color in zip(labels, colors):
83+
label_data = df_grouped[df_grouped['label'] == label].sort_values('n_kv')
84+
85+
# Plot token generation
86+
tg = ax1.errorbar(label_data['n_kv'], label_data['speed_tg_mean'],
87+
yerr=label_data['speed_tg_std'], color=color,
88+
marker='s', linestyle='-', label=label)
89+
90+
# Add labels and title
91+
ax1.set_xlabel('Context Length (n_kv)')
92+
ax1.set_ylabel('Token Generation Rate (t/s)')
93+
plt.title('Token Generation Performance Comparison')
94+
95+
ax1.legend(loc='upper right')
96+
97+
# Adjust layout and save
98+
plt.tight_layout()
99+
plt.savefig('performance_comparison_tg.png', bbox_inches='tight')
100+
plt.close()
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
#include "arg.h"
2+
#include "common.h"
3+
#include "log.h"
4+
#include "llama.h"
5+
6+
#include <algorithm>
7+
#include <cstdlib>
8+
#include <cstdio>
9+
#include <string>
10+
#include <vector>
11+
12+
static void print_usage(int, char ** argv) {
13+
LOG("\nexample usage:\n");
14+
LOG("\n %s -m model.gguf -c 8192 -b 2048 -ub 512\n", argv[0]);
15+
LOG("\n");
16+
}
17+
18+
int main(int argc, char ** argv) {
19+
common_params params;
20+
21+
if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_BENCH, print_usage)) {
22+
return 1;
23+
}
24+
25+
common_init();
26+
27+
// init LLM
28+
29+
llama_backend_init();
30+
llama_numa_init(params.numa);
31+
32+
// initialize the model
33+
34+
llama_model_params model_params = common_model_params_to_llama(params);
35+
36+
llama_model * model = llama_model_load_from_file(params.model.c_str(), model_params);
37+
38+
if (model == NULL) {
39+
fprintf(stderr , "%s: error: unable to load model\n" , __func__);
40+
return 1;
41+
}
42+
43+
llama_context_params ctx_params = common_context_params_to_llama(params);
44+
45+
llama_context * ctx = llama_init_from_model(model, ctx_params);
46+
47+
if (ctx == NULL) {
48+
fprintf(stderr , "%s: error: failed to create the llama_context\n" , __func__);
49+
return 1;
50+
}
51+
52+
const unsigned int n_kv_max = llama_n_ctx(ctx);
53+
const llama_vocab * vocab = llama_model_get_vocab(model);
54+
const unsigned int n_vocab = llama_vocab_n_tokens(vocab);
55+
const llama_token bos = llama_vocab_bos(vocab);
56+
const llama_token eos = llama_vocab_eos(vocab);
57+
58+
// decode in batches of ctx_params.n_batch tokens
59+
auto decode_helper = [](llama_context * ctx, llama_batch & batch, int32_t n_batch) {
60+
for (int32_t i = 0; i < (int32_t) batch.n_tokens; i += n_batch) {
61+
const int32_t n_tokens = std::min(n_batch, (int32_t) (batch.n_tokens - i));
62+
63+
llama_batch batch_view = {
64+
n_tokens,
65+
batch.token + i,
66+
nullptr,
67+
batch.pos + i,
68+
batch.n_seq_id + i,
69+
batch.seq_id + i,
70+
batch.logits + i,
71+
};
72+
73+
const int ret = llama_decode(ctx, batch_view);
74+
if (ret != 0) {
75+
LOG_ERR("failed to decode the batch, n_batch = %d, ret = %d\n", n_batch, ret);
76+
return false;
77+
}
78+
79+
llama_synchronize(ctx);
80+
}
81+
82+
return true;
83+
};
84+
85+
const unsigned int pp = params.n_ubatch;
86+
const unsigned int tg = params.n_ubatch / 4;
87+
88+
if (!params.batched_bench_output_jsonl) {
89+
LOG("\n");
90+
LOG("%s: n_kv_max = %d, n_batch = %d, n_ubatch = %d, flash_attn = %d, n_gpu_layers = %d, n_threads = %u, n_threads_batch = %u\n", __func__, n_kv_max, params.n_batch, params.n_ubatch, params.flash_attn, params.n_gpu_layers, ctx_params.n_threads, ctx_params.n_threads_batch);
91+
LOG("\n");
92+
LOG("|%6s | %6s | %6s | %8s | %8s | %8s | %8s |\n", "PP", "TG", "N_KV", "T_PP s", "S_PP t/s", "T_TG s", "S_TG t/s");
93+
LOG("|%6s-|-%6s-|-%6s-|-%8s-|-%8s-|-%8s-|-%8s-|\n", "------", "------", "------", "--------", "--------", "--------", "--------");
94+
}
95+
96+
llama_batch batch = llama_batch_init(n_kv_max, 0, 1);
97+
98+
// warm up
99+
{
100+
common_batch_add(batch, bos, 0, { 0 }, false);
101+
common_batch_add(batch, eos, 1, { 0 }, false);
102+
103+
if (!decode_helper(ctx, batch, ctx_params.n_batch)) {
104+
LOG_ERR("%s: llama_decode() failed\n", __func__);
105+
return 1;
106+
}
107+
}
108+
109+
common_batch_clear(batch);
110+
llama_kv_cache_clear(ctx);
111+
112+
for (unsigned int n_kv = 0; n_kv < n_kv_max; n_kv += params.n_ubatch) {
113+
// clean up KV cache before generation
114+
llama_kv_cache_seq_rm(ctx, 0, n_kv, -1);
115+
116+
// first measure token generation performance at this context size
117+
const auto t_tg_start = ggml_time_us();
118+
119+
for (unsigned int i = 0; i < tg; ++i) {
120+
common_batch_clear(batch);
121+
common_batch_add(batch, std::rand() % n_vocab, n_kv + i, { 0 }, true);
122+
123+
if (!decode_helper(ctx, batch, ctx_params.n_batch)) {
124+
LOG_ERR("%s: llama_decode() failed\n", __func__);
125+
return 1;
126+
}
127+
}
128+
129+
const auto t_tg_end = ggml_time_us();
130+
131+
// clean up KV cache after generation
132+
llama_kv_cache_seq_rm(ctx, 0, n_kv, -1);
133+
134+
// prepare batch of pp size for prompt processing performance measurement
135+
common_batch_clear(batch);
136+
137+
for (unsigned int i = 0; i < pp; ++i) {
138+
common_batch_add(batch, std::rand() % n_vocab, n_kv + i, { 0 }, false);
139+
}
140+
batch.logits[batch.n_tokens - 1] = true;
141+
142+
// measure prompt processing performance
143+
const auto t_pp_start = ggml_time_us();
144+
145+
if (!decode_helper(ctx, batch, ctx_params.n_batch)) {
146+
LOG_ERR("%s: llama_decode() failed\n", __func__);
147+
return 1;
148+
}
149+
150+
const auto t_pp_end = ggml_time_us();
151+
152+
// calculate and print metrics
153+
const float t_pp = (t_pp_end - t_pp_start) / 1000000.0f;
154+
const float t_tg = (t_tg_end - t_tg_start) / 1000000.0f;
155+
156+
const float speed_pp = pp / t_pp;
157+
const float speed_tg = tg / t_tg;
158+
159+
if(params.batched_bench_output_jsonl) {
160+
LOG(
161+
"{\"n_kv_max\": %d, \"n_batch\": %d, \"n_ubatch\": %d, \"flash_attn\": %d, \"n_gpu_layers\": %d, \"n_threads\": %u, \"n_threads_batch\": %u, "
162+
"\"pp\": %d, \"tg\": %d, \"n_kv\": %d, \"t_pp\": %f, \"speed_pp\": %f, \"t_tg\": %f, \"speed_tg\": %f }\n",
163+
n_kv_max, params.n_batch, params.n_ubatch, params.flash_attn, params.n_gpu_layers, ctx_params.n_threads, ctx_params.n_threads_batch,
164+
pp, tg, n_kv, t_pp, speed_pp, t_tg, speed_tg
165+
);
166+
} else {
167+
LOG("|%6d | %6d | %6d | %8.3f | %8.2f | %8.3f | %8.2f |\n", pp, tg, n_kv, t_pp, speed_pp, t_tg, speed_tg);
168+
}
169+
}
170+
171+
llama_perf_context_print(ctx);
172+
173+
llama_batch_free(batch);
174+
175+
llama_free(ctx);
176+
llama_model_free(model);
177+
178+
llama_backend_free();
179+
180+
return 0;
181+
}

0 commit comments

Comments
 (0)