diff --git a/.github/ISSUE_TEMPLATE/bench-report.yml b/.github/ISSUE_TEMPLATE/bench-report.yml new file mode 100644 index 000000000..1b7fc7198 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bench-report.yml @@ -0,0 +1,49 @@ +name: Bench report +description: Post the report strata-poly --bench-report wrote on your PC, so the maintainers see where speed is left on hardware they do not have +title: "[Benchmark] bench report: " +labels: ["benchmark"] +body: + - type: markdown + value: | + The title must start with **[Benchmark]**. Add your GPU and model after it, for example `[Benchmark] bench report: RTX 3060 12 GB, Inkling 2 Mini IQ4_NL`. + + Make the report with the settings you use every day. With the server stopped (it needs the GPU): + + ``` + python polystrata.py bench-report --model # about a minute after the model loads, more on a slow card + python polystrata.py bench-report --model --long # adds one long conversation read up to your context + ``` + + It writes `bench-report.json` and `bench-report.md` in the folder you run it from. They hold the GPU, CPU, RAM, + the engine's version, your settings, the speeds and where the GPU's time went, and no paths, user or host names, + serial numbers or prompts (the prompts are a fixed synthetic text). Read them before you post; `python tools/bench_reports.py + --check-privacy bench-report.json` checks them again. + - type: textarea + id: markdown + attributes: + label: The report (bench-report.md) + description: Paste the whole Markdown file. + render: markdown + validations: + required: true + - type: textarea + id: json + attributes: + label: The JSON (bench-report.json) + description: Attach the file (drag it here) or paste it. The tools compare reports from it. + validations: + required: true + - type: textarea + id: notes + attributes: + label: Anything else + description: What else ran on the PC, a laptop on battery, a changed power limit, other settings you tried. + - type: dropdown + id: reproduction-status + attributes: + label: Reproduction status + options: + - Measured locally + - Unconfirmed (I did not run it) + validations: + required: true diff --git a/docs/COMMUNITY_BENCHMARKS.md b/docs/COMMUNITY_BENCHMARKS.md index 4cd8e2f08..4bd264217 100644 --- a/docs/COMMUNITY_BENCHMARKS.md +++ b/docs/COMMUNITY_BENCHMARKS.md @@ -250,6 +250,28 @@ fast. [Q2_0](bench-results/2026-11-17-community-rx-7600-xt-qwen3-8-flash-next-q2-0/README.md), `--kv int8 --kv-resident 32768`, `tools/strata_bench.py`: chat 22.1 / 11.3 tok/s (8.3 to 30.9 and 4.6 to 42.9 over the runs), prompt 169 / 114 tok/s at 4K and 187 / 111 at 16K. The same PC's strata-poly models are in the table above. +## Post a bench report (strata-poly) + +The engine of the models PolyStrata adds can write a report of its own: what your card, link, RAM and CPU measure, +the speeds with your settings, and where the GPU's time went. It shows the maintainers where speed is left on hardware +they do not have. Stop the server first (the report needs the GPU), then: + +``` +python polystrata.py bench-report --model # quick: about a minute after the model loads (RTX 2070 Super), more on a slow card +python polystrata.py bench-report --model --long # and one conversation read in chunks up to your context (about 6 minutes more at 128K) +``` + +It writes `bench-report.json` and `bench-report.md`: probes (H2D pinned and pageable, D2H, GPU memory, RAM read on +all threads, the CPU experts' dot kernel), then prompts of 302, 2,048 and 8,192 tokens of a fixed synthetic English text (the same on every PC) with 128 tokens answered +after each (greedy), each with its event profile and an "Explain" section that holds every phase against the probes. +The files have no paths, user or host names, serial numbers or prompts. With `--layer-split` the profile is the first card's stream alone. Post them with the **Bench report** issue form; +`python tools/bench_reports.py --check-privacy bench-report.json` checks a file, and `python tools/bench_reports.py +*.json` puts several reports in one table per card and flags the ones far from the same card's others. + +`STRATA_PROFILE=1` in the server's environment profiles normal use the same way, at no extra wait: after every request +the engine writes the session's profile, by phase and by context length, to `strata-profile.json` in its working +folder (`STRATA_PROFILE_OUT` names another file), and a line to the log. + ## Run the standard benchmark ```sh diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md index bb8fe2806..a690d6421 100644 --- a/docs/SETTINGS.md +++ b/docs/SETTINGS.md @@ -11,7 +11,7 @@ A number or a word is set like any environment variable, for example `STRATA_KVA (`terminal/strata-.json`), which the server passes to the engine. The Strata project's Terminal writes it there with `strata launch --set NAME=value`. -## Switches you can turn on (347) +## Switches you can turn on (350) Off unless you set them. The last column says where each one is described. @@ -277,6 +277,9 @@ Off unless you set them. The last column says where each one is described. | `STRATA_PREFILL_ROUTED_STREAM_DEPTH` | on / off | NVIDIA and AMD | [DETAILS.md](DETAILS.md) | | `STRATA_PREFILL_STREAM_ALL` | on / off | Intel Arc | [INTEL.md](INTEL.md) | | `STRATA_PRIMARY_DEVICE` | number | NVIDIA and AMD | [SECOND_GPU.md](SECOND_GPU.md) | +| `STRATA_PROFILE` | on / off | NVIDIA and AMD | [COMMUNITY_BENCHMARKS.md](COMMUNITY_BENCHMARKS.md) | +| `STRATA_PROFILE_EVERY` | number | NVIDIA and AMD | - | +| `STRATA_PROFILE_OUT` | text | NVIDIA and AMD | [COMMUNITY_BENCHMARKS.md](COMMUNITY_BENCHMARKS.md) | | `STRATA_PROMPT_ATTN_IMMA` | on / off | NVIDIA and AMD | [DETAILS.md](DETAILS.md) | | `STRATA_PROMPT_DIRECT` | on / off | NVIDIA and AMD | [QUANTS.md](QUANTS.md) | | `STRATA_PW_WITH_BATCH` | on / off | NVIDIA and AMD | [DETAILS.md](DETAILS.md) | diff --git a/engine/cmake/strata_poly.cmake b/engine/cmake/strata_poly.cmake index 11a4ab043..c1e374cea 100644 --- a/engine/cmake/strata_poly.cmake +++ b/engine/cmake/strata_poly.cmake @@ -10,8 +10,42 @@ # builds the products llama.cpp's way instead (its MMQ kernels, its flash-attention kernel from its headers and the GDN # adapter that needs them), from a llama.cpp checkout given as -DSTRATA_GGML_DIR: an override kept for two releases. +# --bench-report names the commit the engine was built from: -DSTRATA_GIT_COMMIT= when given (a build host that +# copies the tree without .git passes its own: rbuild does), else git's at configure time, else a COMMIT file beside +# engine/ (a source package can carry one), else "unknown". +set(STRATA_GIT_COMMIT "" CACHE STRING "the commit --bench-report names (empty: git describe at configure time)") +function(strata_poly_commit src) + set(_commit "${STRATA_GIT_COMMIT}") + if(NOT _commit) + find_package(Git QUIET) + if(GIT_FOUND) + execute_process(COMMAND ${GIT_EXECUTABLE} describe --always --dirty --abbrev=10 + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} OUTPUT_VARIABLE _out RESULT_VARIABLE _rc + OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) + if(_rc EQUAL 0 AND _out) + set(_commit "${_out}") + endif() + endif() + endif() + if(NOT _commit AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../COMMIT") + file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/../COMMIT" _lines LIMIT_COUNT 1) + if(_lines) + list(GET _lines 0 _commit) + endif() + endif() + if(NOT _commit) + set(_commit "unknown") + endif() + string(REGEX REPLACE "[^A-Za-z0-9._+-]" "" _commit "${_commit}") # a short id, nothing that needs quoting + set_property(SOURCE ${src} APPEND PROPERTY COMPILE_DEFINITIONS "STRATA_GIT_COMMIT=\"${_commit}\"") +endfunction() + macro(strata_poly) if(STRATA_BUILD_TESTS) + # --bench-report's JSON, Markdown, explain section and privacy scrub, from figures of the test's own (no card) + add_executable(poly_bench_report_test src/poly/bench_report_test.cpp src/poly/bench_report.cpp) + target_include_directories(poly_bench_report_test PRIVATE include) + add_test(NAME poly_bench_report_test COMMAND poly_bench_report_test) add_executable(glm_conversations_test src/poly/conversations_test.cpp src/poly/spill.cpp) add_test(NAME glm_conversations_test COMMAND glm_conversations_test) add_executable(poly_guesses_test src/poly/guesses_test.cpp src/spec/draft_policy.cpp) @@ -205,8 +239,20 @@ if(STRATA_BUILD_POLY AND STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA add_executable(strata-poly src/poly/main.cpp src/poly/engine.cpp src/poly/expert_card.cpp src/poly/glm5next.cpp src/poly/qwen35.cpp src/poly/gemma4.cpp src/poly/deepseek4.cpp src/poly/lfm2moe.cpp src/poly/flint.cpp src/poly/kolibri1.cpp src/poly/laguna.cpp src/poly/inkling2.cpp src/poly/inkling2_pictures.cpp src/poly/inkling2.cu src/poly/cpu_experts.cpp src/poly/kernels.cu src/poly/kernels_dsv4.cu - src/poly/spill.cpp src/core/conversation_memory.cpp src/core/conversation_file.cpp) + src/poly/spill.cpp src/core/conversation_memory.cpp src/core/conversation_file.cpp + src/poly/bench_report.cpp src/poly/bench_probe.cpp src/poly/bench_kernels.cu) target_include_directories(strata-poly PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) + strata_poly_commit(src/poly/bench_report.cpp) + # the profiler's launch counter (src/poly/launch_count.cpp): the runtime's launch call wrapped at link time, Linux + # only (elsewhere the profile counts the recordings' kernel nodes alone) + if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + target_sources(strata-poly PRIVATE src/poly/launch_count.cpp) + if(STRATA_ENABLE_HIP) + target_link_options(strata-poly PRIVATE "LINKER:--wrap=hipLaunchKernel") + else() + target_link_options(strata-poly PRIVATE "LINKER:--wrap=cudaLaunchKernel" "LINKER:--wrap=cudaLaunchKernelExC") + endif() + endif() # the driver's virtual memory calls: the attention caches grow with the conversation; on HIP they are HIP's # memory management calls, which the HIP runtime itself provides (hip_compat/cuda.h) if(STRATA_ENABLE_HIP) diff --git a/engine/src/poly/bench_kernels.cu b/engine/src/poly/bench_kernels.cu new file mode 100644 index 000000000..10a8ea32e --- /dev/null +++ b/engine/src/poly/bench_kernels.cu @@ -0,0 +1,236 @@ +// src/poly/bench_kernels.cu - --bench-report's kernel probes (bench_report.hpp probe_kernels()): what a launch costs +// (back to back, and as a node of a replayed recording), how fast a kernel can read the card's memory (a read-only +// kernel, not a copy), and an fp32 FMA rate. Run before the model loads; ~1 s. +#include "bench_report.hpp" + +#include + +#include +#include +#include +#include + +namespace strata::poly::bench { +namespace { + +__global__ void empty_kernel() {} + +// every thread reads 16-byte words with a grid stride; one word a block written so the reads are not dropped +__global__ void read_kernel(const uint4* __restrict__ p, size_t n, uint4* __restrict__ out) { + uint32_t a = 0, b = 0, c = 0, d = 0; + const size_t step = (size_t) gridDim.x * blockDim.x; + size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; + for (; i + 3 * step < n; i += 4 * step) { // four loads in flight a thread + const uint4 v0 = p[i], v1 = p[i + step], v2 = p[i + 2 * step], v3 = p[i + 3 * step]; + a ^= v0.x ^ v1.x ^ v2.x ^ v3.x, b ^= v0.y ^ v1.y ^ v2.y ^ v3.y; + c ^= v0.z ^ v1.z ^ v2.z ^ v3.z, d ^= v0.w ^ v1.w ^ v2.w ^ v3.w; + } + for (; i < n; i += step) { + const uint4 v = p[i]; + a ^= v.x, b ^= v.y, c ^= v.z, d ^= v.w; + } + if ((a ^ b ^ c ^ d) == 0x9e3779b9u) out[blockIdx.x] = make_uint4(a, b, c, d); // practically never +} + +// a small dependent step, as a norm or a mix of one token is: one block reads 4 KiB the last kernel wrote, writes 4 KiB +__global__ void small_kernel(const float* __restrict__ x, float* __restrict__ y) { + for (int i = threadIdx.x; i < 1024; i += blockDim.x) y[i] = fmaf(x[i], 0.999f, 0.001f); +} + +// the same across the card: a thread a float, every block of a grid as wide as a token's products are +__global__ void wide_kernel(const float* __restrict__ x, float* __restrict__ y) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + y[i] = fmaf(x[i], 0.999f, 0.001f); +} + +// 2 FLOPs a multiply-add, 8 independent chains a thread +__global__ void fma_kernel(float* out, int iters, float s) { + float x[8]; + for (int k = 0; k < 8; ++k) x[k] = (float) (threadIdx.x + k) * 1e-3f; + for (int i = 0; i < iters; ++i) + for (int k = 0; k < 8; ++k) x[k] = fmaf(x[k], s, 0.5f); + float t = 0; + for (int k = 0; k < 8; ++k) t += x[k]; + if (t == 1234.5f) out[blockIdx.x] = t; +} + +using Clock = std::chrono::steady_clock; +double secs(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } + +} // namespace + +void probe_kernels(Probes& p, int device) { + const Clock::time_point t0 = Clock::now(); + (void) cudaSetDevice(device); + cudaStream_t s = nullptr; + if (cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking) != cudaSuccess) { + (void) cudaGetLastError(); + return; + } + // a launch back to back: the host's cost to hand the card an empty kernel, and the card's to run it + const int n = 2000; + for (int i = 0; i < 100; ++i) empty_kernel<<<1, 32, 0, s>>>(); + (void) cudaStreamSynchronize(s); + Clock::time_point t = Clock::now(); + for (int i = 0; i < n; ++i) empty_kernel<<<1, 32, 0, s>>>(); + if (cudaStreamSynchronize(s) == cudaSuccess) p.launch_us = secs(t) * 1e6 / n; + // a host round trip: an empty kernel, then the host waits for its event (as the host waits for a router's scores); + // and a small copy to the host waited for on the stream + { + cudaEvent_t ev = nullptr; + if (cudaEventCreateWithFlags(&ev, cudaEventDisableTiming) == cudaSuccess) { + const int trips = 300; + for (int i = 0; i < 20; ++i) { + empty_kernel<<<1, 32, 0, s>>>(); + (void) cudaEventRecord(ev, s); + (void) cudaEventSynchronize(ev); + } + t = Clock::now(); + bool ok = true; + for (int i = 0; i < trips && ok; ++i) { + empty_kernel<<<1, 32, 0, s>>>(); + ok = cudaEventRecord(ev, s) == cudaSuccess && cudaEventSynchronize(ev) == cudaSuccess; + } + if (ok) p.sync_us = secs(t) * 1e6 / trips; + (void) cudaEventDestroy(ev); + } + void* d = nullptr; + void* h = nullptr; + if (cudaMalloc(&d, 4096) == cudaSuccess && cudaMallocHost(&h, 4096) == cudaSuccess) { + const int trips = 300; + for (int i = 0; i < 20; ++i) { + (void) cudaMemcpyAsync(h, d, 1024, cudaMemcpyDeviceToHost, s); + (void) cudaStreamSynchronize(s); + } + t = Clock::now(); + bool ok = true; + for (int i = 0; i < trips && ok; ++i) + ok = cudaMemcpyAsync(h, d, 1024, cudaMemcpyDeviceToHost, s) == cudaSuccess && + cudaStreamSynchronize(s) == cudaSuccess; + if (ok) p.copy_sync_us = secs(t) * 1e6 / trips; + } + if (d) (void) cudaFree(d); + if (h) (void) cudaFreeHost(h); + (void) cudaGetLastError(); + } + // a node of a replayed recording: n empty kernels recorded once, replayed + cudaGraph_t g = nullptr; + cudaGraphExec_t exec = nullptr; + const int nodes = 500; + if (cudaStreamBeginCapture(s, cudaStreamCaptureModeThreadLocal) == cudaSuccess) { + for (int i = 0; i < nodes; ++i) empty_kernel<<<1, 32, 0, s>>>(); + if (cudaStreamEndCapture(s, &g) == cudaSuccess && g && + cudaGraphInstantiateWithFlags(&exec, g, 0) == cudaSuccess) { + (void) cudaGraphLaunch(exec, s); + (void) cudaStreamSynchronize(s); + const int reps = 8; + t = Clock::now(); + for (int r = 0; r < reps; ++r) (void) cudaGraphLaunch(exec, s); + if (cudaStreamSynchronize(s) == cudaSuccess) p.graph_node_us = secs(t) * 1e6 / (reps * nodes); + } + } + if (exec) (void) cudaGraphExecDestroy(exec); + if (g) (void) cudaGraphDestroy(g); + (void) cudaGetLastError(); + // the floor of a real kernel: small dependent kernels back to back, launched and as a replayed recording. An + // empty kernel only shows the queue's rate; a kernel that reads what the last one wrote also pays the boundary + // between them (the wait for the last one, its writes made visible), which is what a token's ~1,500 small + // kernels pay + { + float* xy = nullptr; + if (cudaMalloc(&xy, 2 * 1024 * sizeof(float)) == cudaSuccess) { + (void) cudaMemsetAsync(xy, 0, 2 * 1024 * sizeof(float), s); + float* a = xy; + float* b = xy + 1024; + for (int i = 0; i < 100; ++i) small_kernel<<<1, 256, 0, s>>>(i % 2 ? b : a, i % 2 ? a : b); + (void) cudaStreamSynchronize(s); + const int k = 2000; + t = Clock::now(); + for (int i = 0; i < k; ++i) small_kernel<<<1, 256, 0, s>>>(i % 2 ? b : a, i % 2 ? a : b); + if (cudaStreamSynchronize(s) == cudaSuccess) p.small_us = secs(t) * 1e6 / k; + cudaGraph_t sg = nullptr; + cudaGraphExec_t se = nullptr; + const int kn = 500; + if (cudaStreamBeginCapture(s, cudaStreamCaptureModeThreadLocal) == cudaSuccess) { + for (int i = 0; i < kn; ++i) small_kernel<<<1, 256, 0, s>>>(i % 2 ? b : a, i % 2 ? a : b); + if (cudaStreamEndCapture(s, &sg) == cudaSuccess && sg && + cudaGraphInstantiateWithFlags(&se, sg, 0) == cudaSuccess) { + (void) cudaGraphLaunch(se, s); + (void) cudaStreamSynchronize(s); + const int reps = 8; + t = Clock::now(); + for (int r = 0; r < reps; ++r) (void) cudaGraphLaunch(se, s); + if (cudaStreamSynchronize(s) == cudaSuccess) p.small_node_us = secs(t) * 1e6 / (reps * kn); + } + } + if (se) (void) cudaGraphExecDestroy(se); + if (sg) (void) cudaGraphDestroy(sg); + (void) cudaFree(xy); + } + int cus = 0; + (void) cudaDeviceGetAttribute(&cus, cudaDevAttrMultiProcessorCount, device); + const int wb = std::max(1, cus) * 2, wn = wb * 256; + float* w = nullptr; + if (cudaMalloc(&w, 2 * (size_t) wn * sizeof(float)) == cudaSuccess) { + (void) cudaMemsetAsync(w, 0, 2 * (size_t) wn * sizeof(float), s); + float* a = w; + float* b = w + wn; + cudaGraph_t wg = nullptr; + cudaGraphExec_t we = nullptr; + const int kn = 500; + if (cudaStreamBeginCapture(s, cudaStreamCaptureModeThreadLocal) == cudaSuccess) { + for (int i = 0; i < kn; ++i) wide_kernel<<>>(i % 2 ? b : a, i % 2 ? a : b); + if (cudaStreamEndCapture(s, &wg) == cudaSuccess && wg && + cudaGraphInstantiateWithFlags(&we, wg, 0) == cudaSuccess) { + (void) cudaGraphLaunch(we, s); + (void) cudaStreamSynchronize(s); + const int reps = 8; + t = Clock::now(); + for (int r = 0; r < reps; ++r) (void) cudaGraphLaunch(we, s); + if (cudaStreamSynchronize(s) == cudaSuccess) p.wide_node_us = secs(t) * 1e6 / (reps * kn); + } + } + if (we) (void) cudaGraphExecDestroy(we); + if (wg) (void) cudaGraphDestroy(wg); + (void) cudaFree(w); + } + (void) cudaGetLastError(); + } + // a read-only kernel over 512 MiB: the rate a matrix-vector product can at best read its weights at + const size_t bytes = 512ull << 20, words = bytes / sizeof(uint4); + uint4* buf = nullptr; + uint4* out = nullptr; + int sms = 0; + (void) cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, device); + const int blocks = std::max(1, sms) * 8; + if (cudaMalloc(&buf, bytes) == cudaSuccess && cudaMalloc(&out, (size_t) blocks * sizeof(uint4)) == cudaSuccess) { + (void) cudaMemsetAsync(buf, 1, bytes, s); + read_kernel<<>>(buf, words, out); // warm + (void) cudaStreamSynchronize(s); + const int reps = 10; + t = Clock::now(); + for (int r = 0; r < reps; ++r) read_kernel<<>>(buf, words, out); + if (cudaStreamSynchronize(s) == cudaSuccess) p.read_gbs = (double) bytes * reps / 1e9 / secs(t); + } + if (buf) (void) cudaFree(buf); + if (out) (void) cudaFree(out); + (void) cudaGetLastError(); + // fp32 multiply-adds: the card's plain arithmetic rate (not its int8 or tensor-core one) + float* f = nullptr; + if (cudaMalloc(&f, (size_t) blocks * 4 * sizeof(float)) == cudaSuccess) { + const int iters = 4096, threads = 256, grid = std::max(1, sms) * 4 * 4; + fma_kernel<<>>(f, 64, 1.0001f); + (void) cudaStreamSynchronize(s); + const int reps = 4; + t = Clock::now(); + for (int r = 0; r < reps; ++r) fma_kernel<<>>(f, iters, 1.0001f); + if (cudaStreamSynchronize(s) == cudaSuccess) + p.fma_gflops = 2.0 * 8 * (double) iters * threads * grid * reps / 1e9 / secs(t); + (void) cudaFree(f); + } + (void) cudaGetLastError(); + (void) cudaStreamDestroy(s); + p.seconds += secs(t0); +} + +} // namespace strata::poly::bench diff --git a/engine/src/poly/bench_probe.cpp b/engine/src/poly/bench_probe.cpp new file mode 100644 index 000000000..cf79c220a --- /dev/null +++ b/engine/src/poly/bench_probe.cpp @@ -0,0 +1,532 @@ +// src/poly/bench_probe.cpp - --bench-report's hardware: what the card and the CPU are (gpu_info(), host_info()) and +// what they measure (probe_hardware(), probe_dots()). The probes run before the model loads, so the card's memory is +// free for their buffers: 256 MiB of pinned memory and 1 GiB of VRAM at most, given back after. +#include "bench_report.hpp" + +#include "strata/quant/dot.hpp" +#include "strata/quant/isa.hpp" +#include "strata/quant/types.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || defined(_M_IX86) +#define STRATA_PROBE_X86 1 +#if defined(_MSC_VER) +#include +#else +#include +#endif +#endif +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#include // types only: the functions are loaded at run time (setupapi.dll), nothing is linked +#else +#include +#include +#include +#include +#endif + +namespace strata::poly::bench { +namespace { + +using Clock = std::chrono::steady_clock; +double secs(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } + +std::string trim(std::string s) { + while (!s.empty() && (s.back() == ' ' || s.back() == '\n' || s.back() == '\r' || s.back() == '\0')) s.pop_back(); + size_t a = 0; + while (a < s.size() && s[a] == ' ') ++a; + return s.substr(a); +} + +std::string read_line(const std::string& path) { + std::ifstream f(path); + std::string s; + if (f) std::getline(f, s); + return trim(s); +} + +int pcie_gen_of(const std::string& speed) { // "8.0 GT/s PCIe" -> 3 + const double gt = std::atof(speed.c_str()); + if (gt <= 0) return -1; + if (gt < 4) return 1; + if (gt < 7) return 2; + if (gt < 12) return 3; + if (gt < 24) return 4; + if (gt < 48) return 5; + return 6; +} + +// one timed copy loop on a stream: GB/s of `bytes` a copy. Timed by the host's clock from the first copy to the +// stream's end, not by events: on Windows (WDDM, HIP) a copy from pinned memory can run on a copy engine that the +// stream's events do not bracket, and 8 copies of 256 MiB read as 32 TB/s. A few microseconds of launch in 2 GiB of +// copies do not show. +double timed_copies(void* dst, const void* src, size_t bytes, cudaMemcpyKind kind, int reps, cudaStream_t s) { + double gbs = 0.0; + if (cudaMemcpyAsync(dst, src, bytes, kind, s) == cudaSuccess && cudaStreamSynchronize(s) == cudaSuccess) { // warm + const Clock::time_point t0 = Clock::now(); + bool ok = true; + for (int i = 0; i < reps && ok; ++i) ok = cudaMemcpyAsync(dst, src, bytes, kind, s) == cudaSuccess; + ok = ok && cudaStreamSynchronize(s) == cudaSuccess; + const double sec = secs(t0); + if (ok && sec > 0) gbs = (double) bytes * reps / 1e9 / sec; + } + (void) cudaGetLastError(); + return gbs; +} + +int usable_threads() { +#if defined(__linux__) + cpu_set_t set; + if (sched_getaffinity(0, sizeof set, &set) == 0) return std::max(1, (int) CPU_COUNT(&set)); +#elif defined(_WIN32) + DWORD_PTR mine = 0, all = 0; + if (GetProcessAffinityMask(GetCurrentProcess(), &mine, &all) && mine) { + int n = 0; + for (DWORD_PTR m = mine; m; m &= m - 1) ++n; + // (one processor group's mask: past 64 logical CPUs, all the groups' CPUs) + return n >= 64 ? (int) std::max(64u, std::thread::hardware_concurrency()) : n; + } +#endif + return std::max(1u, std::thread::hardware_concurrency()); +} + +// The PCIe link of the card at bus id `bus` ("0000:01:00.0" or CUDA's "00000000:01:00.0"): now (a card in a low-power +// state reports a lower one) and at most. The bus id is only read here, never written out. +struct Link { + int gen = -1, width = -1, gen_max = -1, width_max = -1; + bool any() const { return gen > 0 || width > 0; } +}; + +#ifdef _WIN32 +void* open_lib(const char* name) { return (void*) LoadLibraryA(name); } +void* lib_fn(void* lib, const char* name) { return lib ? (void*) GetProcAddress((HMODULE) lib, name) : nullptr; } +#else +void* open_lib(const char* name) { return dlopen(name, RTLD_NOW | RTLD_LOCAL); } +void* lib_fn(void* lib, const char* name) { return lib ? dlsym(lib, name) : nullptr; } +#endif + +// NVIDIA, any OS: NVML, loaded at run time (the driver installs it; nothing is linked). False where it is missing. +bool nvml_link(const std::string& bus, Link& l) { +#if defined(STRATA_USE_HIP) + (void) bus, (void) l; + return false; +#else +#ifdef _WIN32 + void* lib = open_lib("nvml.dll"); + if (!lib) { // older drivers keep it here, off the search path + char pf[MAX_PATH] = {}; + if (GetEnvironmentVariableA("ProgramW6432", pf, MAX_PATH) || GetEnvironmentVariableA("ProgramFiles", pf, MAX_PATH)) + lib = open_lib((std::string(pf) + "\\NVIDIA Corporation\\NVSMI\\nvml.dll").c_str()); + } +#else + void* lib = open_lib("libnvidia-ml.so.1"); // (WSL2: /usr/lib/wsl/lib) +#endif + using Init = int (*)(); + using ByBus = int (*)(const char*, void**); + using Get = int (*)(void*, unsigned*); + const auto init = (Init) lib_fn(lib, "nvmlInit_v2"); + const auto stop = (Init) lib_fn(lib, "nvmlShutdown"); + const auto by_bus = (ByBus) lib_fn(lib, "nvmlDeviceGetHandleByPciBusId_v2"); + const Get get[4] = {(Get) lib_fn(lib, "nvmlDeviceGetCurrPcieLinkGeneration"), + (Get) lib_fn(lib, "nvmlDeviceGetCurrPcieLinkWidth"), + (Get) lib_fn(lib, "nvmlDeviceGetMaxPcieLinkGeneration"), + (Get) lib_fn(lib, "nvmlDeviceGetMaxPcieLinkWidth")}; + if (!init || !stop || !by_bus || init() != 0) return false; // (the library stays loaded: the process is short) + void* dev = nullptr; + if (by_bus(bus.c_str(), &dev) == 0 && dev) { + int* out[4] = {&l.gen, &l.width, &l.gen_max, &l.width_max}; + for (int k = 0; k < 4; ++k) { + unsigned v = 0; + if (get[k] && get[k](dev, &v) == 0 && v > 0 && v < 64) *out[k] = (int) v; + } + } + stop(); + return l.any(); +#endif +} + +// Windows, any vendor: the PCI device's link properties through SetupAPI (loaded at run time), found by bus number, +// device and function among the display adapters. +bool setupapi_link(const std::string& bus, Link& l) { +#ifdef _WIN32 + unsigned dom = 0, b = 0, d = 0, f = 0; + if (std::sscanf(bus.c_str(), "%x:%x:%x.%x", &dom, &b, &d, &f) != 4) return false; + void* lib = open_lib("setupapi.dll"); + using ClassDevs = HDEVINFO(WINAPI*)(const GUID*, PCWSTR, HWND, DWORD); + using Enum = BOOL(WINAPI*)(HDEVINFO, DWORD, PSP_DEVINFO_DATA); + using RegProp = BOOL(WINAPI*)(HDEVINFO, PSP_DEVINFO_DATA, DWORD, PDWORD, PBYTE, DWORD, PDWORD); + using DevProp = BOOL(WINAPI*)(HDEVINFO, PSP_DEVINFO_DATA, const DEVPROPKEY*, DEVPROPTYPE*, PBYTE, DWORD, PDWORD, DWORD); + using Destroy = BOOL(WINAPI*)(HDEVINFO); + const auto class_devs = (ClassDevs) lib_fn(lib, "SetupDiGetClassDevsW"); + const auto enum_dev = (Enum) lib_fn(lib, "SetupDiEnumDeviceInfo"); + const auto reg_prop = (RegProp) lib_fn(lib, "SetupDiGetDeviceRegistryPropertyW"); + const auto dev_prop = (DevProp) lib_fn(lib, "SetupDiGetDevicePropertyW"); + const auto destroy = (Destroy) lib_fn(lib, "SetupDiDestroyDeviceInfoList"); + if (!class_devs || !enum_dev || !reg_prop || !dev_prop || !destroy) return false; + static const GUID display = {0x4d36e968, 0xe325, 0x11ce, {0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18}}; + // DEVPKEY_PciDevice_CurrentLinkSpeed (9), CurrentLinkWidth (10), MaxLinkSpeed (11), MaxLinkWidth (12) of pciprop.h + static const GUID pci = {0x3ab22e31, 0x8264, 0x4b4e, {0x9a, 0xf5, 0xa8, 0xd2, 0xd8, 0xe3, 0x3e, 0x62}}; + const HDEVINFO set = class_devs(&display, nullptr, nullptr, DIGCF_PRESENT); + if (set == INVALID_HANDLE_VALUE) return false; + SP_DEVINFO_DATA info{}; + info.cbSize = sizeof info; + for (DWORD i = 0; enum_dev(set, i, &info); ++i) { + DWORD bus_no = 0, addr = 0, type = 0; + if (!reg_prop(set, &info, SPDRP_BUSNUMBER, &type, (PBYTE) &bus_no, sizeof bus_no, nullptr) || + !reg_prop(set, &info, SPDRP_ADDRESS, &type, (PBYTE) &addr, sizeof addr, nullptr)) + continue; + if (bus_no != b || (addr >> 16) != d || (addr & 0xffff) != f) continue; + int* out[4] = {&l.gen, &l.width, &l.gen_max, &l.width_max}; + const ULONG pid[4] = {9, 10, 11, 12}; + for (int k = 0; k < 4; ++k) { + DEVPROPKEY key{pci, pid[k]}; + DEVPROPTYPE t = 0; + UINT32 v = 0; + if (dev_prop(set, &info, &key, &t, (PBYTE) &v, sizeof v, nullptr, 0) && v > 0 && v < 64) + *out[k] = (int) v; // the speeds are 1 = 2.5 GT/s, 2 = 5, 3 = 8, 4 = 16, 5 = 32: the generation + } + break; + } + destroy(set); + return l.any(); +#else + (void) bus, (void) l; + return false; +#endif +} + +// Linux: sysfs, the kernel's own view of the link. +bool sysfs_link(std::string id, Link& l) { +#if defined(__linux__) + if (id.size() == 16) id = id.substr(4); // 00000000:01:00.0 (CUDA's) -> 0000:01:00.0 (sysfs') + const std::string dir = "/sys/bus/pci/devices/" + id + "/"; + l.gen = pcie_gen_of(read_line(dir + "current_link_speed")); + l.gen_max = pcie_gen_of(read_line(dir + "max_link_speed")); + const std::string w = read_line(dir + "current_link_width"), wm = read_line(dir + "max_link_width"); + l.width = w.empty() ? -1 : std::max(-1, std::atoi(w.c_str())); + l.width_max = wm.empty() ? -1 : std::max(-1, std::atoi(wm.c_str())); + if (l.width == 0) l.width = -1; + if (l.width_max == 0) l.width_max = -1; + return l.any(); +#else + (void) id, (void) l; + return false; +#endif +} + +} // namespace + +Gpu gpu_info(int device) { + Gpu g; +#if defined(STRATA_USE_HIP) + g.backend = "hip"; +#else + g.backend = "cuda"; +#endif + cudaDeviceProp p{}; + if (cudaGetDeviceProperties(&p, device) != cudaSuccess) { + (void) cudaGetLastError(); + g.name = "unknown"; + return g; + } + g.name = trim(p.name); + g.sms = p.multiProcessorCount; + g.vram_gib = (double) p.totalGlobalMem / (double) (1ull << 30); +#if defined(STRATA_USE_HIP) + g.arch = trim(p.gcnArchName); + const size_t colon = g.arch.find(':'); // gfx1201:sramecc-:xnack- -> gfx1201 + if (colon != std::string::npos) g.arch.resize(colon); +#else + g.arch = "sm_" + std::to_string(p.major) + std::to_string(p.minor); +#endif + int v = 0; + if (cudaDriverGetVersion(&v) == cudaSuccess) { +#if defined(STRATA_USE_HIP) + g.driver = "HIP driver " + std::to_string(v); +#else + g.driver = "CUDA " + std::to_string(v / 1000) + "." + std::to_string(v % 1000 / 10); +#endif + } + if (cudaRuntimeGetVersion(&v) == cudaSuccess) { +#if defined(STRATA_USE_HIP) + g.runtime = "HIP " + std::to_string(v / 10000000) + "." + std::to_string(v / 100000 % 100); +#else + g.runtime = "CUDA " + std::to_string(v / 1000) + "." + std::to_string(v % 1000 / 10); +#endif + } + int clock_khz = 0, bus_bits = 0; + if (cudaDeviceGetAttribute(&clock_khz, cudaDevAttrMemoryClockRate, device) == cudaSuccess && + cudaDeviceGetAttribute(&bus_bits, cudaDevAttrGlobalMemoryBusWidth, device) == cudaSuccess && clock_khz > 0) + g.mem_peak_gbs = 2.0 * clock_khz * 1e3 * (bus_bits / 8.0) / 1e9; // double data rate + (void) cudaGetLastError(); + char bus[32] = {}; +#if defined(STRATA_USE_HIP) + const bool have_bus = hipDeviceGetPCIBusId(bus, (int) sizeof bus, device) == hipSuccess; +#else + const bool have_bus = cudaDeviceGetPCIBusId(bus, (int) sizeof bus, device) == cudaSuccess; +#endif + (void) cudaGetLastError(); + if (have_bus) { + std::string id = bus; + for (char& c : id) c = (char) std::tolower((unsigned char) c); + // NVML (NVIDIA, any OS), then SetupAPI (Windows, any vendor), then sysfs (Linux) + Link l; + if (nvml_link(id, l)) g.pcie_source = "nvml"; + else if (setupapi_link(id, l = Link{})) g.pcie_source = "setupapi"; + else if (sysfs_link(id, l = Link{})) g.pcie_source = "sysfs"; + g.pcie_gen = l.gen, g.pcie_width = l.width, g.pcie_gen_max = l.gen_max, g.pcie_width_max = l.width_max; + } + return g; +} + +Host host_info() { + Host h; +#if defined(STRATA_PROBE_X86) + unsigned r[12] = {}; + bool brand = false; +#if defined(_MSC_VER) + int x[4]; + __cpuid(x, (int) 0x80000000); + if ((unsigned) x[0] >= 0x80000004u) { + for (int i = 0; i < 3; ++i) __cpuid((int*) (r + 4 * i), (int) (0x80000002 + i)); + brand = true; + } +#else + if (__get_cpuid_max(0x80000000, nullptr) >= 0x80000004u) { + for (unsigned i = 0; i < 3; ++i) __get_cpuid(0x80000002 + i, r + 4 * i, r + 4 * i + 1, r + 4 * i + 2, r + 4 * i + 3); + brand = true; + } +#endif + if (brand) { + char b[49] = {}; + std::memcpy(b, r, 48); + h.cpu = trim(b); + } +#endif +#if defined(__linux__) + if (h.cpu.empty()) { // arm64: the first "model name" or "Hardware" line + std::ifstream f("/proc/cpuinfo"); + for (std::string line; std::getline(f, line);) + if (line.rfind("model name", 0) == 0 || line.rfind("Hardware", 0) == 0) { + const size_t c = line.find(':'); + if (c != std::string::npos) h.cpu = trim(line.substr(c + 1)); + break; + } + } +#endif + if (h.cpu.empty()) h.cpu = "unknown"; + // repeated spaces in brand strings ("Intel(R) Core(TM) i7 CPU") + std::string c; + for (char ch : h.cpu) + if (!(ch == ' ' && !c.empty() && c.back() == ' ')) c += ch; + h.cpu = c; + namespace Q = strata::quant; + const Q::Caps& k = Q::caps(); + h.isa = Q::isa_name(Q::best_isa()); + const std::pair flags[] = {{k.sse42, "sse4.2"}, {k.avx, "avx"}, + {k.avx2, "avx2"}, {k.bmi2, "bmi2"}, + {k.avx_vnni, "avx_vnni"}, {k.avx512, "avx512"}, + {k.avx512_vnni, "avx512_vnni"}, {k.avx512_vbmi, "avx512_vbmi"}, + {k.neon, "neon"}, {k.dotprod, "dotprod"}, + {k.i8mm, "i8mm"}}; + for (const auto& [on, name] : flags) + if (on) h.flags.push_back(name); + h.threads = usable_threads(); +#ifdef _WIN32 + MEMORYSTATUSEX ms{}; + ms.dwLength = sizeof ms; + if (GlobalMemoryStatusEx(&ms)) h.ram_gib = (double) ms.ullTotalPhys / (double) (1ull << 30); + h.os = "Windows"; +#else + const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGESIZE); + if (pages > 0 && page > 0) h.ram_gib = (double) pages * (double) page / (double) (1ull << 30); + utsname u{}; + if (uname(&u) == 0) h.os = std::string(u.sysname) + " " + u.release; // the kernel's release, not the host name +#endif + return h; +} + +void probe_hardware(Probes& p, int device, void (*log)(const char*)) { + const Clock::time_point t0 = Clock::now(); + const auto say = [&](const char* what) { + if (log) log(what); + }; + (void) cudaSetDevice(device); + cudaStream_t s = nullptr; + if (cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking) != cudaSuccess) { + (void) cudaGetLastError(); + return; + } + const size_t mb = 256ull << 20, big = 512ull << 20; + // a card that something else is using: its probes would measure that too, and take its memory + size_t free_b = 0, total_b = 0; + if (cudaMemGetInfo(&free_b, &total_b) != cudaSuccess) (void) cudaGetLastError(); + const bool room = free_b >= 2 * big + (512ull << 20); + if (!room) say("skipped the copies: under 1.5 GiB of the card's memory is free (another program is using it)"); + void* pin = nullptr; + void* dev = nullptr; + void* dev2 = nullptr; + if (room && cudaMallocHost(&pin, mb) == cudaSuccess && cudaMalloc(&dev, mb) == cudaSuccess) { + std::memset(pin, 1, mb); + p.h2d_pinned_gbs = timed_copies(dev, pin, mb, cudaMemcpyHostToDevice, 8, s); + say("probe H2D pinned done"); + p.d2h_pinned_gbs = timed_copies(pin, dev, mb, cudaMemcpyDeviceToHost, 8, s); + say("probe D2H pinned done"); + std::unique_ptr pageable(new (std::nothrow) uint8_t[mb]); + if (pageable) { + std::memset(pageable.get(), 1, mb); + p.h2d_pageable_gbs = timed_copies(dev, pageable.get(), mb, cudaMemcpyHostToDevice, 4, s); + say("probe H2D pageable done"); + } + } + (void) cudaGetLastError(); + if (dev) (void) cudaFree(dev); + if (pin) (void) cudaFreeHost(pin); + dev = nullptr; + // the card's memory: device-to-device copies of 512 MiB, each a read and a write of it + if (room && cudaMalloc(&dev, big) == cudaSuccess && cudaMalloc(&dev2, big) == cudaSuccess) { + (void) cudaMemsetAsync(dev, 1, big, s); + p.gpu_mem_gbs = 2.0 * timed_copies(dev2, dev, big, cudaMemcpyDeviceToDevice, 10, s); + say("probe GPU memory done"); + } + (void) cudaGetLastError(); + if (dev) (void) cudaFree(dev); + if (dev2) (void) cudaFree(dev2); + (void) cudaStreamDestroy(s); + (void) cudaGetLastError(); + + // RAM: every usable thread sums its part of 1 GiB (a sixteenth of the RAM at most), best of three passes + const int threads = usable_threads(); + size_t ram = 1ull << 30; +#ifndef _WIN32 + const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGESIZE); + if (pages > 0 && page > 0) ram = std::min(ram, (size_t) pages * (size_t) page / 16); +#endif + const size_t n = ram / sizeof(uint64_t); + std::unique_ptr buf(new (std::nothrow) uint64_t[n]); + if (buf) { + std::vector th; + for (int t = 0; t < threads; ++t) // touched by the threads that read it: on a NUMA PC, each on its node + th.emplace_back([&, t] { + const size_t a = n * (size_t) t / (size_t) threads, b = n * (size_t) (t + 1) / (size_t) threads; + for (size_t i = a; i < b; ++i) buf[i] = i; + }); + for (std::thread& x : th) x.join(); + double best = 0.0; + std::atomic sink{0}; + for (int pass = 0; pass < 3; ++pass) { + th.clear(); + std::atomic ready{0}; + std::atomic go{false}; + Clock::time_point start; + for (int t = 0; t < threads; ++t) + th.emplace_back([&, t] { + const size_t a = n * (size_t) t / (size_t) threads, b = n * (size_t) (t + 1) / (size_t) threads; + ready.fetch_add(1); + while (!go.load(std::memory_order_acquire)) std::this_thread::yield(); + uint64_t s0 = 0, s1 = 0, s2 = 0, s3 = 0; + size_t i = a; + for (; i + 4 <= b; i += 4) s0 += buf[i], s1 += buf[i + 1], s2 += buf[i + 2], s3 += buf[i + 3]; + for (; i < b; ++i) s0 += buf[i]; + sink.fetch_add(s0 + s1 + s2 + s3, std::memory_order_relaxed); + }); + while (ready.load() < threads) std::this_thread::yield(); + start = Clock::now(); + go.store(true, std::memory_order_release); + for (std::thread& x : th) x.join(); + const double sec = secs(start); + if (sec > 0) best = std::max(best, (double) ram / 1e9 / sec); + } + p.ram_read_gbs = best; + p.ram_threads = threads; + say("probe RAM read done"); + } + p.seconds += secs(t0); +} + +void probe_dots(Probes& p, const std::vector>& type_cols, int threads) { + namespace Q = strata::quant; + const Clock::time_point t0 = Clock::now(); + threads = std::max(threads, 1); + std::vector seen; + for (const auto& [type, cols] : type_cols) { + if (std::find(seen.begin(), seen.end(), type) != seen.end()) continue; // a rate a type + seen.push_back(type); + const Q::TypeInfo* ti = Q::type_info(type); + const Q::DotKernel* k = ti ? Q::dot_kernel(ti->type, Q::default_arith()) : nullptr; + // the activation format the kernel takes (DotKernel::act), which is the one cpu_experts() quantizes to + const size_t rb = Q::row_bytes(type, cols), ab = k ? Q::row_bytes((int) k->act, cols) : 0; + if (!k || !k->fn || rb == 0 || ab == 0) continue; + // 512 MiB of rows: far more than any cache, as the experts outside VRAM are + const size_t rows = std::max((512ull << 20) / rb, (size_t) threads); + std::unique_ptr w(new (std::nothrow) uint8_t[rows * rb]); + if (!w) continue; + std::vector act(ab, 0); + // small, finite scales in every block (0x11 bytes: an fp16 of 2^-11 and so on); the values do not change the time + std::vector th; + for (int t = 0; t < threads; ++t) + th.emplace_back([&, t] { + const size_t a = rows * (size_t) t / (size_t) threads, b = rows * (size_t) (t + 1) / (size_t) threads; + std::memset(w.get() + a * rb, 0x11, (b - a) * rb); + }); + for (std::thread& x : th) x.join(); + const auto pass = [&](int nt, size_t nrows) { + std::vector ts; + std::atomic ready{0}; + std::atomic go{false}; + std::atomic sink{0}; + for (int t = 0; t < nt; ++t) + ts.emplace_back([&, t] { + const size_t a = nrows * (size_t) t / (size_t) nt, b = nrows * (size_t) (t + 1) / (size_t) nt; + ready.fetch_add(1); + while (!go.load(std::memory_order_acquire)) std::this_thread::yield(); + float acc = 0.f, s = 0.f; + for (size_t r = a; r < b; ++r) { + k->fn(cols, &s, w.get() + r * rb, act.data()); + acc += s; + } + uint32_t bits; + std::memcpy(&bits, &acc, 4); + sink.fetch_add(bits, std::memory_order_relaxed); + }); + while (ready.load() < nt) std::this_thread::yield(); + const Clock::time_point start = Clock::now(); + go.store(true, std::memory_order_release); + for (std::thread& x : ts) x.join(); + const double sec = secs(start); + return sec > 0 ? (double) nrows * (double) rb / 1e9 / sec : 0.0; + }; + DotRate d; + d.type = ti->name; + d.kernel = k->name; + d.isa = Q::isa_name(k->isa); + d.threads = threads; + pass(threads, rows); // warm + d.gbs_all = std::max(pass(threads, rows), pass(threads, rows)); + d.gbs_one = pass(1, std::min(rows, (size_t) ((64ull << 20) / rb) + 1)); + p.dots.push_back(d); + } + p.seconds += secs(t0); +} + +} // namespace strata::poly::bench diff --git a/engine/src/poly/bench_report.cpp b/engine/src/poly/bench_report.cpp new file mode 100644 index 000000000..9b315817e --- /dev/null +++ b/engine/src/poly/bench_report.cpp @@ -0,0 +1,925 @@ +// src/poly/bench_report.cpp - --bench-report's JSON and Markdown, the explain section and the privacy scrub +// (bench_report.hpp). No GPU code: bench_report_test.cpp builds a report from figures of its own. +#include "bench_report.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif + +#ifndef STRATA_GIT_COMMIT +#define STRATA_GIT_COMMIT "unknown" +#endif + +namespace strata::poly::bench { + +using prof::Acc; + +const char* build_commit() { return STRATA_GIT_COMMIT; } +using prof::Json; + +bool looks_like_path(const std::string& v) { + if (v.empty()) return false; + if (v.find('/') != std::string::npos || v.find('\\') != std::string::npos) return true; + if (v[0] == '~' || v[0] == '.') return true; + static const char* const ext[] = {".gguf", ".json", ".txt", ".bin", ".md", ".log", ".csv", ".ids"}; + for (const char* e : ext) { + const size_t n = std::strlen(e); + if (v.size() > n && v.compare(v.size() - n, n, e) == 0) return true; + } + return false; +} + +std::vector> clean_args(const std::vector& argv) { + // options whose value is a file or a prompt, whatever it looks like + static const std::set files{"--model", "--expert-profile", "--draft-model", "--pinned-session", + "--images", "--bench-report", "--follow"}; + static const std::set ids{"--tokens", "--eos-ids", "--follow"}; + std::vector> out; + for (size_t i = 0; i < argv.size(); ++i) { + const std::string& a = argv[i]; + if (a.rfind("--", 0) != 0) continue; // a stray value: left out + const bool has_value = i + 1 < argv.size() && argv[i + 1].rfind("--", 0) != 0; + std::string v = has_value ? argv[i + 1] : ""; + if (has_value) ++i; + if (a == "--model" || a == "--bench-report") continue; // the model is described apart; the report is this file + if (ids.count(a)) v = ""; + else if (files.count(a) || looks_like_path(v)) v = ""; + out.emplace_back(a, v); + } + return out; +} + +std::vector> clean_env(char** envp) { + std::vector> out; + for (char** e = envp; e && *e; ++e) { + const std::string kv = *e; + if (kv.rfind("STRATA_", 0) != 0) continue; + const size_t eq = kv.find('='); + if (eq == std::string::npos) continue; + std::string k = kv.substr(0, eq), v = kv.substr(eq + 1); + for (const char* hide : {"KEY", "TOKEN", "SECRET", "PASS", "AUTH"}) + if (k.find(hide) != std::string::npos) v = ""; + if (looks_like_path(v)) v = ""; + out.emplace_back(k, v); + } + std::sort(out.begin(), out.end()); + return out; +} + +std::vector private_strings() { + std::vector s; + const auto add = [&](const std::string& v) { + if (v.size() >= 4 && std::find(s.begin(), s.end(), v) == s.end()) s.push_back(v); + }; + for (const char* k : {"USER", "USERNAME", "LOGNAME", "HOME", "USERPROFILE", "COMPUTERNAME", "HOSTNAME"}) + if (const char* v = std::getenv(k)) add(v); +#ifdef _WIN32 + char host[256] = {}; + DWORD n = sizeof host; + if (GetComputerNameA(host, &n)) add(host); +#else + char host[256] = {}; + if (gethostname(host, sizeof host - 1) == 0) add(host); +#endif + std::error_code ec; + const std::filesystem::path cwd = std::filesystem::current_path(ec); + if (!ec) add(cwd.string()); + // longest first: a home folder goes before the user name inside it + std::sort(s.begin(), s.end(), [](const std::string& a, const std::string& b) { return a.size() > b.size(); }); + return s; +} + +std::string scrub(std::string text, const std::vector& secrets) { + const auto word = [](char c) { return std::isalnum((unsigned char) c) || c == '_'; }; + for (const std::string& x : secrets) { + if (x.size() < 4) continue; + // a folder anywhere; a name only as a whole word, so a user called "cuda" leaves the backend's name alone + const bool folder = x.find('/') != std::string::npos || x.find('\\') != std::string::npos; + for (size_t at = text.find(x); at != std::string::npos;) { + const bool whole = folder || ((at == 0 || !word(text[at - 1])) && + (at + x.size() >= text.size() || !word(text[at + x.size()]))); + if (whole) { + text.replace(at, x.size(), ""); + at = text.find(x, at + 10); + } else { + at = text.find(x, at + 1); + } + } + } + return text; +} + +namespace { + +std::string fmt(const char* f, double v) { + char b[64]; + std::snprintf(b, sizeof b, f, v); + return b; +} + +std::string pct(double share) { return fmt("%.0f%%", 100.0 * share); } + +// one run's profiles of a phase, added +Acc sum_of(const std::vector& runs, int phase, bool split) { + Acc a; + for (const Run& r : runs) a.add(split ? r.profile.split[phase] : r.profile.all[phase]); + return a; +} + +double share(const Acc& a, int f) { + const double tl = a.timeline_ms(); + return tl > 0 ? a.fam_ms[f] / tl : 0.0; +} + +double busy_share(const Acc& a) { + double s = 0; + for (int f = 0; f < prof::kFams; ++f) + if (!prof::fam_idle(f)) s += share(a, f); + return s; +} + +} // namespace + +namespace { + +// `a` less `b`: the unsplit calls of a phase (every call less the split ones) +Acc minus(const Acc& a, const Acc& b) { + Acc c = a; + for (int f = 0; f < prof::kFams; ++f) { + c.fam_ms[f] -= b.fam_ms[f], c.fam_launches[f] -= b.fam_launches[f]; + c.fam_graph_nodes[f] -= b.fam_graph_nodes[f], c.fam_bytes[f] -= b.fam_bytes[f]; + } + c.wall_ms -= b.wall_ms, c.tokens -= b.tokens, c.calls -= b.calls, c.cpu_ms -= b.cpu_ms; + c.route_wait_ms -= b.route_wait_ms, c.route_waits -= b.route_waits; + c.cpu_experts -= b.cpu_experts, c.gpu_experts -= b.gpu_experts, c.staged_experts -= b.staged_experts; + c.upload_bytes -= b.upload_bytes, c.side_ms -= b.side_ms, c.side_bytes -= b.side_bytes; + c.cpu_expert_bytes -= b.cpu_expert_bytes; + return c; +} + +// One phase's figures into a diagnosis. The whole token's (or call's) figures come from the calls the profiler left +// alone (`all` less `split`: replays as in normal use), where there are any; the families' from the split calls, +// launched kernel by kernel with their families timed. `per` divides into the unit (tokens, or 1 for a call). +// +// Launch cost: a replayed recording's nodes run one after the other, so their probed cost adds to the token's time; +// a direct launch overlaps the kernels before it, so it only bounds the time where the kernels are no longer than a +// launch (the family's time a launch near the probed latency). Launch figures are upper bounds. +Diagnosis diagnose_one(const Report& r, const std::string& phase, const std::string& unit, const Acc& all_in, + const Acc& split, double split_per, bool prompt) { + Diagnosis g; + g.phase = phase; + g.unit = unit; + const Probes& p = r.probes; + if (all_in.calls == 0 || split.calls == 0 || split_per <= 0) return g; + const Acc rest = minus(all_in, split); + const bool use_rest = !prompt && rest.tokens > 0 && rest.calls > 0; + const Acc& all = use_rest ? rest : all_in; + const double all_per = prompt ? 1.0 : (double) all.tokens; + if (all_per <= 0) return g; + g.ok = true; + g.total_ms = all.wall_ms / all_per; + double nodes = 0; + for (double v : all.fam_graph_nodes) nodes += v; + g.launches = all.launches() / all_per; + g.nodes = nodes / all_per; + g.direct = g.launches - g.nodes; + // a kernel's floor: the probed small dependent kernel (launched, or a replayed node), else the empty one's. The + // kernels of a stream run one after another, so each costs at least its floor: launches x floor is what the + // kernel count alone costs, whatever the kernels do + const double k_us = p.small_us > 0 ? p.small_us : p.launch_us; + // (a token's kernels span the card: the wide kernel's floor where it is the higher) + const double n_us = std::max(p.wide_node_us, p.small_node_us > 0 ? p.small_node_us : p.graph_node_us); + g.launch_ms = (g.nodes * n_us + g.direct * k_us) / 1000.0; + const double gpu_b = (all.fam_bytes[prof::kDense] + all.fam_bytes[prof::kRouting] + all.fam_bytes[prof::kAttention] + + all.fam_bytes[prof::kExpertsGpu]) / all_per; + g.gpu_gb = gpu_b / 1e9; + g.ideal_ms = p.read_gbs > 0 ? gpu_b / (p.read_gbs * 1e9) * 1000.0 : 0.0; + g.wait_cpu_ms = split.fam_ms[prof::kWaitCpu] / split_per; + g.wait_upload_ms = split.fam_ms[prof::kWaitUpload] / split_per; + g.host_gap_ms = split.fam_ms[prof::kHostGap] / split_per; + const double setup_ms = split.fam_ms[prof::kHostSetup] / split_per; + const double looked = (double) (all.gpu_experts + all.cpu_experts) + all.staged_experts; + if (looked > 0) g.hit_rate = (double) all.gpu_experts / looked; + g.cpu_gb = all.cpu_expert_bytes / all_per / 1e9; + g.warm_cache = !prompt && g.hit_rate > 0.97; + g.pcie_gb = (all.upload_bytes + all.side_bytes) / all_per / 1e9; + // host round trips (no doorbell: the host routes, from the scores it waits for): the routing family's time beyond + // its kernels is the card's idle while the host waits, routes and launches the experts + g.round_trips = all.route_waits / all_per; + const double split_calls = (double) split.calls; + { + const double rms = split.fam_ms[prof::kRouting] / split_per; + const double rl = split.fam_launches[prof::kRouting] / split_per; + const double rkernels = std::min(rms, rl * k_us / 1000.0); + g.round_trip_ms = split.route_waits > 0 ? std::max(0.0, rms - rkernels) : 0.0; + if (split.route_waits <= 0) g.round_trips = 0; + } + (void) split_calls; + // a split call that replays a recording books its time to "recorded launches": its bytes are then not the + // families', and no GB/s is given a family + const bool bytes_by_family = split.fam_ms[prof::kGraph] < 0.05 * split.timeline_ms(); + const auto fam_name = [](int f) { return std::string(prof::fam_title(f)); }; + std::vector> rec; + for (int f = 0; f < prof::kFams; ++f) { + const double ms = split.fam_ms[f] / split_per; + if (ms <= 0.005 && split.fam_launches[f] <= 0) continue; + FamilyVerdict v; + v.fam = f; + v.ms = ms; + v.launches = split.fam_launches[f] / split_per; + const double fnodes = split.fam_graph_nodes[f] / split_per; + v.avg_kernel_us = v.launches > 0 ? 1000.0 * ms / v.launches : 0.0; + v.launch_ms = std::min(ms, (fnodes * n_us + (v.launches - fnodes) * k_us) / 1000.0); + const bool fam_direct_bound = k_us > 0 && v.launches > 0 && v.launch_ms >= 0.5 * ms; + v.gb = bytes_by_family ? split.fam_bytes[f] / split_per / 1e9 : 0.0; + v.gbs = ms > 0 ? v.gb / (ms / 1000.0) : 0.0; + v.read_share = p.read_gbs > 0 ? v.gbs / p.read_gbs : 0.0; + v.tiny = v.launches > 0 && k_us > 0 && v.avg_kernel_us < 2.0 * k_us; + const double kernel_ms = std::max(0.0, ms - v.launch_ms); + if (f == prof::kWaitCpu) v.verdict = "waiting on the CPU's experts"; + else if (f == prof::kRouting && split.route_waits > 0 && g.round_trip_ms > 0.5 * ms) + v.verdict = "host round trips (" + fmt("%.0f", g.round_trips) + " " + unit + + "): the card idles while the host routes"; + else if (f == prof::kWaitUpload) v.verdict = "waiting on expert uploads"; + else if (f == prof::kHostGap) v.verdict = "idle: the host between calls"; + else if (f == prof::kHostSetup) v.verdict = "idle: the host setting the read up"; + else if (v.launches > 0 && fam_direct_bound && r.launches_wrapped) + v.verdict = "launch-bound (" + fmt("%.1f", v.avg_kernel_us) + " us a kernel, the probed floor " + + fmt("%.1f", k_us) + " us)"; + else if (v.gb > 0 && v.read_share >= 0.6) + v.verdict = "bandwidth-bound (" + pct(v.read_share) + " of the probed read bandwidth)"; + else if (v.gb > 0) + v.verdict = "under bandwidth (" + pct(v.read_share) + " of the probed read): compute or latency in the kernels"; + else if (f == prof::kAttention && split.fam_bytes[prof::kAttention] <= 0 && ms > 0) + v.verdict = "KV rows not modelled for this architecture: compute or latency"; + else if (ms > 0) + v.verdict = "no byte model: compute or latency"; + if (!r.launches_wrapped && v.launches <= 0 && ms > 0) v.verdict += " (direct launches not counted in this build)"; + if (v.tiny) v.verdict += "; small kernels (" + fmt("%.1f", v.avg_kernel_us) + " us on average)"; + const bool routed_on_host = f == prof::kRouting && split.route_waits > 0; // (round trips, below) + if (v.gb > 0 && p.read_gbs > 0 && !routed_on_host) { + const double gap = kernel_ms - v.gb * 1e9 / (p.read_gbs * 1e9) * 1000.0; + if (gap > 0) rec.push_back({gap, "a faster " + fam_name(f) + " kernel (now " + pct(v.read_share) + " of the probed read bandwidth)"}); + } + g.families.push_back(v); + } + if (g.launch_ms > 0) + rec.push_back({g.launch_ms, "fewer launches: fused kernels or fewer recorded nodes (" + fmt("%.0f", g.launches) + + " " + unit + ")"}); + if (g.wait_cpu_ms > 0.05) + rec.push_back({g.wait_cpu_ms, "more experts in VRAM" + (g.hit_rate >= 0 ? " (hit rate " + pct(g.hit_rate) + ")" : std::string())}); + if (g.wait_upload_ms > 0.05) rec.push_back({g.wait_upload_ms, "faster or fewer expert uploads"}); + if (g.round_trip_ms > 0.05) + rec.push_back({g.round_trip_ms, "fewer host round trips (" + fmt("%.0f", g.round_trips) + " " + unit + + "): routing on the card, or the host's experts behind a doorbell"}); + if (g.host_gap_ms > 0.05) rec.push_back({g.host_gap_ms, "less host work between calls"}); + if (setup_ms > 0.05) + rec.push_back({setup_ms, "less host setup before a read (the caches' growth, staging taken back from the expert " + "cache)"}); + std::sort(rec.begin(), rec.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); + if (rec.size() > 3) rec.resize(3); + g.recover = rec; + const double T = g.total_ms, waits = g.wait_cpu_ms + g.wait_upload_ms; + if (k_us <= 0 || p.read_gbs <= 0) + g.verdict = "not judged: the kernel probes did not run or failed"; + else if (g.launch_ms >= 0.4 * T && g.launch_ms >= g.ideal_ms && g.launch_ms >= waits) + g.verdict = "launch-bound: " + fmt("%.0f", g.launches) + " kernels " + unit + " at the probed floor (" + + fmt("%.1f", n_us) + " us a replayed node, " + fmt("%.1f", k_us) + " us launched) cost ~" + + fmt("%.1f", g.launch_ms) + " of " + fmt("%.1f", T) + " ms"; + else if (g.wait_cpu_ms >= 0.3 * T && g.wait_cpu_ms >= g.ideal_ms) + g.verdict = "waiting on CPU experts: " + fmt("%.1f", g.wait_cpu_ms) + " of " + fmt("%.1f", T) + " ms"; + else if (g.round_trip_ms >= 0.25 * T && g.round_trip_ms >= g.ideal_ms) + g.verdict = "host round trips: the host waits for router scores " + fmt("%.0f", g.round_trips) + " times " + unit + + " and the card idles ~" + fmt("%.1f", g.round_trip_ms) + " of " + fmt("%.1f", T) + " ms meanwhile"; + else if (g.wait_upload_ms >= 0.3 * T) + g.verdict = "waiting on expert uploads: " + fmt("%.1f", g.wait_upload_ms) + " of " + fmt("%.1f", T) + " ms"; + else if (g.ideal_ms >= 0.6 * T) + g.verdict = "bandwidth-bound: " + fmt("%.2f", g.gpu_gb) + " GB " + unit + " at the probed read bandwidth take " + + fmt("%.1f", g.ideal_ms) + " of " + fmt("%.1f", T) + " ms"; + else + g.verdict = "compute- or latency-bound: launches up to ~" + fmt("%.1f", g.launch_ms) + " ms, bytes at the probed " + "bandwidth " + fmt("%.1f", g.ideal_ms) + " ms, waits " + fmt("%.1f", waits) + " ms, of " + + fmt("%.1f", T) + " ms"; + if (!r.launches_wrapped) g.verdict += " (direct launches are not counted in this build: replays only)"; + return g; +} + +} // namespace + +std::vector diagnose(const Report& r) { + std::vector out; + std::vector singles; + for (const Run& run : r.runs) + if (run.single) singles.push_back(run); + const std::vector& dec = singles.empty() ? r.runs : singles; + const Acc d = sum_of(dec, prof::kDecode, false), ds = sum_of(dec, prof::kDecode, true); + Diagnosis dg = diagnose_one(r, singles.empty() ? "decode" : "decode, a token a call", "a token", d, ds, + (double) ds.tokens, false); + if (dg.ok) out.push_back(dg); + const Run* big = nullptr; + for (const Run& run : r.runs) + if (!big || run.read > big->read) big = &run; + if (big) { + const Acc& a = big->profile.all[prof::kPrompt]; + const Acc& sp = big->profile.split[prof::kPrompt]; + Diagnosis pg = diagnose_one(r, "prompt " + std::to_string(big->read), "a prompt", a, sp, 1.0, true); + if (pg.ok) out.push_back(pg); + } + return out; +} + +std::vector explain(const Report& r) { + std::vector out; + const Probes& p = r.probes; + const double expert_b = r.model.expert_mib * 1048576.0; + // The prompt: the quick tier's longest read + const Run* big = nullptr; + for (const Run& run : r.runs) + if (!big || run.read > big->read) big = &run; + if (big && big->profile.split[prof::kPrompt].calls > 0) { + const Acc& a = big->profile.split[prof::kPrompt]; + const std::string ph = "prompt " + std::to_string(big->read); + const double up = share(a, prof::kWaitUpload), wait_ms = a.fam_ms[prof::kWaitUpload]; + if (wait_ms > 0 || a.side_bytes > 0) { + // copies in the stream: their rate with the host's staging; beside it: their own rate while copying + const double in_gbs = a.upload_bytes > 0 && wait_ms > 0 ? a.upload_bytes / 1e9 / (wait_ms / 1000.0) : 0.0; + const double side_gbs = a.side_ms > 0 ? a.side_bytes / 1e9 / (a.side_ms / 1000.0) : 0.0; + std::string t = pct(up) + " of the GPU's time (" + fmt("%.0f", wait_ms) + " ms) waits for expert uploads"; + if (a.upload_bytes > 0) + t += "; " + fmt("%.1f", a.upload_bytes / 1e9) + " GB copied in the stream at " + fmt("%.1f", in_gbs) + + " GB/s with the host's staging"; + if (a.side_bytes > 0) + t += "; " + fmt("%.1f", a.side_bytes / 1e9) + " GB copied beside the work, " + fmt("%.1f", side_gbs) + + " GB/s over the copies' span"; + t += "; probed H2D " + fmt("%.1f", p.h2d_pinned_gbs) + " GB/s pinned, " + fmt("%.1f", p.h2d_pageable_gbs) + + " GB/s pageable"; + Finding f{ph, t}; + // only the copies in the stream are a rate the stream waited on; the side copies' span holds their own + // waits and staging, so it says nothing against the link + f.flag = up > 0.2 && p.h2d_pinned_gbs > 0 && a.upload_bytes > 0 && in_gbs > 0 && in_gbs < 0.6 * p.h2d_pinned_gbs; + if (f.flag) f.text += " (the uploads run well under the link's speed)"; + out.push_back(f); + } + out.push_back({ph, "GPU work " + pct(busy_share(a)) + " of the time: experts " + + pct(share(a, prof::kExpertsGpu)) + ", dense products " + pct(share(a, prof::kDense)) + + ", attention " + pct(share(a, prof::kAttention)) + ", norms/mixes " + + pct(share(a, prof::kNorms)) + ", KV store " + pct(share(a, prof::kKvStore)) + + ", routing " + pct(share(a, prof::kRouting))}); + const double h2d = share(a, prof::kCopyH2D); + if (h2d > 0.1) { // tables, embeddings and the CPU experts' sums: a few MB, so a share like this is a slow path + Finding f{ph, pct(h2d) + " of the GPU's time (" + fmt("%.0f", a.fam_ms[prof::kCopyH2D]) + + " ms) is copies to the GPU in the stream (tables, embeddings, the CPU experts' sums), " + "a few MB that should take a few ms"}; + f.flag = h2d > 0.2; + out.push_back(f); + } + const double gap = share(a, prof::kHostGap), cpu = share(a, prof::kWaitCpu); + if (gap > 0.05) { + Finding f{ph, pct(gap) + " of the GPU's time it is idle between calls (the host's own work)"}; + f.flag = gap > 0.15; + out.push_back(f); + } + const double setup = share(a, prof::kHostSetup); + if (setup > 0.05) { + Finding f{ph, pct(setup) + " of the GPU's time (" + fmt("%.0f", a.fam_ms[prof::kHostSetup]) + + " ms) it is idle while the host sets a read up (the caches' growth, staging taken back " + "from the expert cache)"}; + f.flag = setup > 0.15; + out.push_back(f); + } + if (cpu > 0.05) { + Finding f{ph, pct(cpu) + " of the GPU's time waits for the CPU's experts (" + + fmt("%.0f", a.cpu_ms) + " ms of CPU experts)"}; + f.flag = cpu > 0.25; + out.push_back(f); + } + } + // The answers: the quick runs' decode tokens together, the ones written a token a call where there are any + std::vector singles; + for (const Run& run : r.runs) + if (run.single) singles.push_back(run); + const std::vector& dec = singles.empty() ? r.runs : singles; + const Acc d = sum_of(dec, prof::kDecode, false), ds = sum_of(dec, prof::kDecode, true); + if (d.tokens > 0) { + const double tok = (double) d.tokens, ms_tok = d.wall_ms / tok; + const std::string ph = singles.empty() ? "decode" : "decode, a token a call"; + // A split token is launched kernel by kernel: where the others replay recordings, its launch gaps are in its + // families, and on a fast card they can be most of them + if (ds.tokens > 0 && d.tokens > ds.tokens) { + const double split_ms = ds.wall_ms / (double) ds.tokens; + const double rest_ms = (d.wall_ms - ds.wall_ms) / (double) (d.tokens - ds.tokens); + if (rest_ms > 0 && split_ms > 1.3 * rest_ms) + out.push_back({ph, "a split token took " + fmt("%.1f", split_ms) + " ms against " + fmt("%.1f", rest_ms) + + " ms for the others (" + fmt("%.1f", split_ms / rest_ms) + + "x): launched kernel by kernel, its families hold the launch gaps too, so read " + "their shares as kernels plus launches"}); + } + out.push_back({ph, fmt("%.1f", ms_tok) + " ms a token (" + fmt("%.1f", 1000.0 / std::max(ms_tok, 1e-9)) + + " tok/s over the quick runs); split tokens: GPU work " + pct(busy_share(ds)) + + ", waits for CPU experts " + pct(share(ds, prof::kWaitCpu)) + ", for uploads " + + pct(share(ds, prof::kWaitUpload)) + ", host gaps " + pct(share(ds, prof::kHostGap)) + + (ds.fam_ms[prof::kGraph] > 0 ? ", not split " + pct(share(ds, prof::kGraph)) : "")}); + if (d.cpu_experts > 0 && d.cpu_ms > 0) { + const double per_tok = (double) d.cpu_experts / tok; + const double gbs = expert_b > 0 ? (double) d.cpu_experts * expert_b / 1e9 / (d.cpu_ms / 1000.0) : 0.0; + const double dot = p.dots.empty() ? 0.0 : p.dots.front().gbs_all; + const double limit = dot > 0 && p.ram_read_gbs > 0 ? std::min(dot, p.ram_read_gbs) : std::max(dot, p.ram_read_gbs); + Finding f{ph, "CPU experts " + fmt("%.1f", d.cpu_ms / tok) + " ms a token for " + fmt("%.0f", per_tok) + + " experts (" + fmt("%.0f", per_tok * expert_b / 1048576.0) + " MiB): " + fmt("%.1f", gbs) + + " GB/s of weights; probed dot kernel " + fmt("%.1f", dot) + " GB/s on " + + std::to_string(p.dots.empty() ? 0 : p.dots.front().threads) + " threads, RAM read " + + fmt("%.1f", p.ram_read_gbs) + " GB/s"}; + f.flag = limit > 0 && gbs > 0 && gbs < 0.5 * limit && share(ds, prof::kWaitCpu) > 0.2; + if (f.flag) f.text += " (the CPU experts run well under what the probes reach)"; + out.push_back(f); + } + if (d.launches() > 0) + out.push_back({ph, fmt("%.0f", d.launches() / tok) + " kernel launches a token (" + + fmt("%.1f", d.launches() > 0 ? 1000.0 * ms_tok / (d.launches() / tok) : 0.0) + + " us of the token's time each)"}); + if (d.route_wait_ms > 0) + out.push_back({ph, "router wait " + fmt("%.2f", d.route_wait_ms / tok) + " ms a token: the host waiting for " + "each layer's router scores, which is the GPU's work up to the router (GPU time, " + "not idle) where the host routes"}); + const double gap = share(ds, prof::kHostGap); + if (gap > 0.1) { + Finding f{ph, pct(gap) + " of a split token's time the GPU is idle between calls (sampling, guesses, " + "the host's bookkeeping)"}; + f.flag = gap > 0.2; + out.push_back(f); + } + const double upw = share(ds, prof::kWaitUpload); + if (upw > 0.1) { + Finding f{ph, pct(upw) + " of a split token's time the GPU waits for expert uploads"}; + f.flag = upw > 0.25; + out.push_back(f); + } + } + // --long: decode against the context + if (r.long_points.size() >= 2) { + const Run& a = r.long_points.front(); + const Run& b = r.long_points.back(); + const Acc& sa = a.profile.split[prof::kDecode]; + const Acc& sb = b.profile.split[prof::kDecode]; + Finding f{"long", "decode " + fmt("%.1f", a.decode_tok_s()) + " tok/s at " + std::to_string(a.context_end / 1024) + + "K, " + fmt("%.1f", b.decode_tok_s()) + " tok/s at " + std::to_string(b.context_end / 1024) + + "K; attention " + pct(share(sa, prof::kAttention)) + " -> " + + pct(share(sb, prof::kAttention)) + " of a split token"}; + f.flag = a.decode_tok_s() > 0 && b.decode_tok_s() < 0.5 * a.decode_tok_s(); + out.push_back(f); + } + return out; +} + +namespace { + +void gpu_json(Json& j, const Gpu& g) { + j.open("gpu"); + j.str("name", g.name); + j.str("backend", g.backend); + j.str("arch", g.arch); + j.integer("sms_or_cus", g.sms); + j.num("vram_gib", g.vram_gib, 2); + j.num("mem_peak_gbs", g.mem_peak_gbs, 1); + j.str("driver", g.driver); + j.str("runtime", g.runtime); + if (g.pcie_gen > 0) j.integer("pcie_gen", g.pcie_gen); else j.null("pcie_gen"); + if (g.pcie_width > 0) j.integer("pcie_width", g.pcie_width); else j.null("pcie_width"); + if (g.pcie_gen_max > 0) j.integer("pcie_gen_max", g.pcie_gen_max); else j.null("pcie_gen_max"); + if (g.pcie_width_max > 0) j.integer("pcie_width_max", g.pcie_width_max); else j.null("pcie_width_max"); + j.str("pcie_source", g.pcie_source.empty() ? "none" : g.pcie_source); + j.close(); +} + +void host_json(Json& j, const Host& h) { + j.open("cpu"); + j.str("model", h.cpu); + j.str("os", h.os); + j.str("isa", h.isa); + j.open_list("flags"); + for (const std::string& f : h.flags) j.str(nullptr, f); + j.close_list(); + j.integer("threads", h.threads); + j.integer("engine_threads", h.engine_threads); + j.num("ram_gib", h.ram_gib, 1); + j.close(); +} + +void probes_json(Json& j, const Probes& p) { + j.open("probes"); + j.num("h2d_pinned_gbs", p.h2d_pinned_gbs, 2); + j.num("h2d_pageable_gbs", p.h2d_pageable_gbs, 2); + j.num("d2h_pinned_gbs", p.d2h_pinned_gbs, 2); + j.num("gpu_mem_gbs", p.gpu_mem_gbs, 1); + j.num("ram_read_gbs", p.ram_read_gbs, 1); + j.num("launch_us", p.launch_us, 2); + j.num("graph_node_us", p.graph_node_us, 2); + j.num("small_kernel_us", p.small_us, 2); + j.num("small_kernel_node_us", p.small_node_us, 2); + j.num("wide_kernel_node_us", p.wide_node_us, 2); + j.num("sync_round_trip_us", p.sync_us, 2); + j.num("copy_to_host_sync_us", p.copy_sync_us, 2); + j.num("gpu_read_gbs", p.read_gbs, 1); + j.num("fp32_fma_gflops", p.fma_gflops, 0); + j.integer("ram_threads", p.ram_threads); + j.open_list("cpu_dot"); + for (const DotRate& d : p.dots) { + j.open(); + j.str("type", d.type); + j.str("kernel", d.kernel); + j.str("isa", d.isa); + j.integer("threads", d.threads); + j.num("gbs_all_threads", d.gbs_all, 2); + j.num("gbs_one_thread", d.gbs_one, 2); + j.close(); + } + j.close_list(); + j.num("seconds", p.seconds, 1); + j.close(); +} + +void model_json(Json& j, const Model& m) { + j.open("model"); + j.str("name", m.name); + j.str("arch", m.arch); + j.str("expert_types", m.file_type); + j.num("size_gib", m.size_gib, 2); + j.integer("experts", m.n_expert); + j.integer("experts_used", m.n_used); + j.integer("moe_layers", m.n_moe); + j.num("expert_mib", m.expert_mib, 3); + j.close(); +} + +void pairs_json(Json& j, const char* key, const std::vector>& v) { + j.open_list(key); + for (const auto& [k, x] : v) { + j.open_list(); + j.str(nullptr, k); + j.str(nullptr, x); + j.close_list(); + } + j.close_list(); +} + +void run_json(Json& j, const Run& r) { + j.open(); + j.str("name", r.name); + j.boolean("one_token_a_call", r.single); + j.integer("prompt_tokens", r.prompt_tokens); + j.integer("reused", r.reused); + j.integer("read", r.read); + j.num("prompt_ms", r.prompt_ms, 1); + j.num("prompt_tok_s", r.prompt_tok_s(), 1); + j.integer("produced", r.produced); + j.num("decode_ms", r.decode_ms, 1); + j.num("decode_tok_s", r.decode_tok_s(), 2); + j.integer("guessed", r.guessed); + j.integer("guessed_right", r.guessed_right); + j.integer("context_end", r.context_end); + prof::profile_json(j, "profile", r.profile); + j.close(); +} + +void header_json(Json& j, const Report& r, const char* kind) { + j.str("kind", kind); + j.integer("schema", 1); + j.open("engine"); + j.str("version", r.engine_version); + j.str("commit", r.commit); + j.close(); + model_json(j, r.model); + j.open("settings"); + pairs_json(j, "args", r.settings); + pairs_json(j, "env", r.env); + j.integer("max_context", r.max_context); + j.close(); + j.open("hardware"); + gpu_json(j, r.gpu); + host_json(j, r.host); + j.close(); + j.integer("cached_experts", r.cached_experts); + j.integer("total_experts", r.total_experts); + j.num("cached_gib", r.cached_gib, 2); +} + +} // namespace + +namespace { +const std::vector* json_secrets = nullptr; // to_json() / session_json() set it for Json::filter +std::string json_scrub(const std::string& v) { return json_secrets ? scrub(v, *json_secrets) : v; } +} // namespace + +std::string to_json(const Report& r) { + const std::vector secrets = private_strings(); + json_secrets = &secrets; + Json j; + j.filter = json_scrub; + j.open(); + header_json(j, r, "strata-bench-report"); + j.str("tier", r.tier); + j.str("prompts", r.prompt_source); + j.boolean("direct_launches_counted", r.launches_wrapped); + j.str("measures", "this build and these settings, one request at a time after a warm-up; decode a token a call = " + "the same answer with no guesses"); + probes_json(j, r.probes); + j.open_list("runs"); + for (const Run& run : r.runs) run_json(j, run); + j.close_list(); + j.open_list("long"); + for (const Run& run : r.long_points) run_json(j, run); + j.close_list(); + if (!r.long_error.empty()) j.str("long_error", r.long_error); + j.open_list("diagnosis"); + for (const Diagnosis& g : diagnose(r)) { + j.open(); + j.str("phase", g.phase); + j.str("verdict", g.verdict); + j.num("ms", g.total_ms, 3); + j.num("launches", g.launches, 1); + j.num("direct_launches", g.direct, 1); + j.num("replayed_nodes", g.nodes, 1); + j.num("launch_ms_estimate", g.launch_ms, 3); + j.num("gpu_gb", g.gpu_gb, 4); + j.num("ideal_ms_at_probed_read", g.ideal_ms, 3); + j.num("wait_cpu_ms", g.wait_cpu_ms, 3); + j.num("wait_upload_ms", g.wait_upload_ms, 3); + j.num("host_gap_ms", g.host_gap_ms, 3); + j.num("host_round_trips", g.round_trips, 1); + j.num("round_trip_idle_ms", g.round_trip_ms, 3); + j.boolean("hit_rate_above_real_text", g.warm_cache); + if (g.hit_rate >= 0) j.num("expert_hit_rate", g.hit_rate, 4); else j.null("expert_hit_rate"); + j.num("cpu_expert_gb", g.cpu_gb, 4); + j.num("pcie_gb", g.pcie_gb, 4); + j.open_list("families"); + for (const FamilyVerdict& v : g.families) { + j.open(); + j.str("family", prof::fam_key(v.fam)); + j.num("ms", v.ms, 3); + j.num("launches", v.launches, 1); + j.num("launch_ms_estimate", v.launch_ms, 3); + j.num("gb", v.gb, 4); + j.num("gbs", v.gbs, 1); + j.num("share_of_probed_read", v.read_share, 3); + j.num("avg_kernel_us", v.avg_kernel_us, 2); + j.boolean("tiny_kernels", v.tiny); + j.str("verdict", v.verdict); + j.close(); + } + j.close_list(); + j.open_list("recover"); + for (const auto& [ms, what] : g.recover) { + j.open(); + j.num("ms", ms, 3); + j.str("by", what); + j.close(); + } + j.close_list(); + j.close(); + } + j.close_list(); + j.open_list("explain"); + for (const Finding& f : explain(r)) { + j.open(); + j.str("phase", f.phase); + j.str("text", f.text); + j.boolean("flag", f.flag); + j.close(); + } + j.close_list(); + j.open("seconds"); + j.num("probes", r.probe_s, 1); + j.num("load", r.load_s, 1); + j.num("warm_up", r.warm_s, 1); + j.num("quick", r.quick_s, 1); + j.num("long", r.long_s, 1); + j.num("total", r.total_s, 1); + j.close(); + j.close(); + json_secrets = nullptr; + return j.s + "\n"; // (scrubbed value by value: a key that happens to be a name stays a key) +} + +std::string session_json(const Report& r, const prof::Profile& p) { + const std::vector secrets = private_strings(); + json_secrets = &secrets; + Json j; + j.filter = json_scrub; + j.open(); + header_json(j, r, "strata-session-profile"); + prof::profile_json(j, "profile", p); + j.close(); + json_secrets = nullptr; + return j.s + "\n"; +} + +namespace { + +// A value in a table cell or a line: no cell breaks, no line breaks, no HTML, no headings, links or images. +std::string md_escape(const std::string& s) { + std::string o; + for (char c : s) { + if (c == '\n' || c == '\r') o += ' '; + else if (c == '<') o += "<"; + else if (c == '>') o += ">"; + else if (c == '|' || c == '#' || c == '!' || c == '[' || c == ']' || c == '*' || c == '_' || c == '`' || + c == '\\') + o += '\\', o += c; + else o += c; + } + return o; +} + +std::string num(double v, int digits) { return fmt(digits == 0 ? "%.0f" : digits == 1 ? "%.1f" : "%.2f", v); } + +void profile_table(std::string& m, const Run& run, int phase) { + const Acc& a = run.profile.split[phase]; + if (a.calls == 0) return; + const double tl = a.timeline_ms(), tok = (double) std::max(a.tokens, 1); + const bool prompt = phase == prof::kPrompt; + m += "\n" + md_escape(run.name) + ", " + prof::phase_key(phase) + " (" + std::to_string(a.calls) + " split calls, " + + std::to_string(a.tokens) + " tokens):\n\n"; + m += prompt ? "| Family | ms | Launches | Share |\n| --- | ---: | ---: | ---: |\n" + : "| Family | ms a token | Launches a token | Share |\n| --- | ---: | ---: | ---: |\n"; + for (int f = 0; f < prof::kFams; ++f) { + if (a.fam_ms[f] <= 0 && a.fam_launches[f] <= 0) continue; + const double v = prompt ? a.fam_ms[f] : a.fam_ms[f] / tok; + const double n = prompt ? a.fam_launches[f] : a.fam_launches[f] / tok; + m += "| " + std::string(prof::fam_title(f)) + " | " + num(v, prompt ? 0 : 2) + " | " + num(n, prompt ? 0 : 1) + + " | " + pct(tl > 0 ? a.fam_ms[f] / tl : 0) + " |\n"; + } + m += "| (all) | " + num(prompt ? tl : tl / tok, prompt ? 0 : 2) + " | " + + num(prompt ? a.launches() : a.launches() / tok, prompt ? 0 : 1) + " | 100% |\n"; + if (!prompt) { // every token, the replayed ones too: what the card is handed for a token + const Acc& all = run.profile.all[phase]; + if (all.tokens > 0 && all.launches() > 0) + m += "\nLaunches a token over all " + std::to_string(all.tokens) + " tokens (replayed ones included): " + + num(all.launches() / (double) all.tokens, 0) + ".\n"; + } +} + +} // namespace + +std::string to_markdown(const Report& r) { + std::string m; + const Gpu& g = r.gpu; + const Host& h = r.host; + m += "# strata-poly bench report (" + r.tier + ")\n\n"; + m += "Engine " + md_escape(r.engine_version) + " (" + md_escape(r.commit) + "), " + md_escape(r.model.name) + ", " + md_escape(g.name) + + ".\n\n"; + m += "**What this measures:** this engine build with the settings listed below, on the prompts named under Results, " + "one request at a time after a warm-up. Speeds from another build, other settings (`--kv`, `--window`, " + "`--prompt-int8`, the `STRATA_*` switches), other prompts or a cold engine are not comparable with these. " + "\"Decode, one token a call\" writes the same answer with no guesses (`--window 1` and no lookups): what the " + "hardware does for a token. The plain decode column includes the settings' guesses, which depend on the text.\n\n"; + m += "## Hardware\n\n| Part | Value |\n| --- | --- |\n"; + m += "| GPU | " + md_escape(g.name) + " (" + md_escape(g.arch) + ", " + std::to_string(g.sms) + " " + + (g.backend == "hip" ? "CUs" : "SMs") + ", " + num(g.vram_gib, 1) + " GiB) |\n"; + m += "| GPU driver | " + md_escape(g.driver) + ", runtime " + md_escape(g.runtime) + " |\n"; + m += "| PCIe | " + + (g.pcie_gen > 0 ? "gen" + std::to_string(g.pcie_gen) + " x" + std::to_string(g.pcie_width) + + (g.pcie_gen_max > 0 ? " (up to gen" + std::to_string(g.pcie_gen_max) + " x" + + std::to_string(g.pcie_width_max) + ")" + : std::string()) + : std::string("not known")) + + " |\n"; + m += "| CPU | " + md_escape(h.cpu) + ", " + std::to_string(h.threads) + " threads (" + + std::to_string(h.engine_threads) + " for the experts), " + h.isa + " |\n"; + m += "| RAM | " + num(h.ram_gib, 1) + " GiB |\n"; + m += "| OS | " + md_escape(h.os) + " |\n"; + m += "\n## Probes\n\n| Probe | GB/s |\n| --- | ---: |\n"; + m += "| H2D pinned | " + num(r.probes.h2d_pinned_gbs, 1) + " |\n"; + m += "| H2D pageable | " + num(r.probes.h2d_pageable_gbs, 1) + " |\n"; + m += "| D2H pinned | " + num(r.probes.d2h_pinned_gbs, 1) + " |\n"; + m += "| GPU memory (copy, read + write) | " + num(r.probes.gpu_mem_gbs, 0) + + // the peak is the memory clock times the bus width as the driver reports them: on AMD the clock is not the + // data rate (GDDR6 moves 8 bits a pin per clock), so a peak under the measured copy is left out + (g.mem_peak_gbs > 0 && g.mem_peak_gbs >= r.probes.gpu_mem_gbs ? " (peak " + num(g.mem_peak_gbs, 0) + ")" + : std::string()) + " |\n"; + if (r.probes.read_gbs > 0) m += "| GPU memory, read-only kernel | " + num(r.probes.read_gbs, 0) + " |\n"; + m += "| RAM read, " + std::to_string(r.probes.ram_threads) + " threads | " + num(r.probes.ram_read_gbs, 1) + " |\n"; + for (const DotRate& d : r.probes.dots) + m += "| CPU expert dot " + d.type + " (" + d.kernel + ", " + d.isa + "), " + std::to_string(d.threads) + + " threads / 1 | " + num(d.gbs_all, 1) + " / " + num(d.gbs_one, 1) + " |\n"; + if (r.probes.launch_us > 0) + m += "\nLaunch: " + fmt("%.2f", r.probes.small_us) + " us a small dependent kernel back to back (" + + fmt("%.2f", r.probes.small_node_us) + " us replayed, " + fmt("%.2f", r.probes.wide_node_us) + " us replayed across the card): a kernel's floor; " + fmt("%.2f", r.probes.launch_us) + + " us an empty kernel back to back, " + + fmt("%.2f", r.probes.graph_node_us) + " us a node of a replayed recording, " + fmt("%.1f", r.probes.sync_us) + " us a host round trip (kernel, " + "event, wait), " + fmt("%.1f", r.probes.copy_sync_us) + " us a small copy to the host waited for; fp32 FMA " + + num(r.probes.fma_gflops, 0) + " GFLOP/s.\n"; + m += "\n## Model and settings\n\n"; + m += md_escape(r.model.name) + " (" + md_escape(r.model.arch) + ", experts " + md_escape(r.model.file_type) + ", " + + num(r.model.size_gib, 1) + " GiB); " + std::to_string(r.cached_experts) + " of " + + std::to_string(r.total_experts) + " routed experts in VRAM (" + num(r.cached_gib, 1) + + " GiB); context " + std::to_string(r.max_context) + "; loaded in " + num(r.load_s, 1) + " s.\n\n"; + m += "Arguments:"; + if (r.settings.empty()) m += " none"; + const auto code = [](std::string v) { // inside a code span: no backtick, no line break + for (char& c : v) + if (c == '`' || c == '\n' || c == '\r') c = '\''; + return v; + }; + for (const auto& [k, v] : r.settings) m += " `" + code(k + (v.empty() ? "" : " " + v)) + "`"; + m += "\n\nEnvironment:"; + if (r.env.empty()) m += " none"; + for (const auto& [k, v] : r.env) m += " `" + code(k + "=" + v) + "`"; + m += "\n\n## Results\n\nGreedy. Prompts: " + md_escape(r.prompt_source) + + ". Prompt tok/s counts the tokens read; decode tok/s the tokens after the first, with the settings' guesses " + "and then again one token a call (the same prompt, read again from the conversation). The requests run one " + "after the other after a warm-up, so the expert cache has followed what they use (its swaps): a cold engine's " + "first answer is slower.\n\n"; + m += "| Prompt tokens | Prompt tok/s | Decode tok/s | Guesses right | Decode tok/s, one token a call |\n" + "| ---: | ---: | ---: | ---: | ---: |\n"; + for (size_t i = 0; i < r.runs.size(); ++i) { + const Run& run = r.runs[i]; + if (run.single) continue; + const Run* one = i + 1 < r.runs.size() && r.runs[i + 1].single ? &r.runs[i + 1] : nullptr; + m += "| " + std::to_string(run.read) + " | " + num(run.prompt_tok_s(), 0) + " | " + num(run.decode_tok_s(), 1) + + " | " + (run.guessed > 0 ? std::to_string(run.guessed_right) + " of " + std::to_string(run.guessed) : "-") + + " | " + (one ? num(one->decode_tok_s(), 1) : "-") + " |\n"; + } + if (!r.long_points.empty() || !r.long_error.empty()) { + m += "\n### Long context (one conversation, read in chunks; decode one token a call)\n\n"; + if (!r.long_error.empty()) m += "The long tier " + md_escape(r.long_error) + ".\n\n"; + m += "| Context | Chunk read | Chunk tok/s | Decode tok/s |\n| ---: | ---: | ---: | ---: |\n"; + for (const Run& run : r.long_points) + m += "| " + std::to_string(run.context_end) + " | " + std::to_string(run.read) + " | " + + num(run.prompt_tok_s(), 0) + " | " + num(run.decode_tok_s(), 1) + " |\n"; + } + m += "\n## Diagnosis\n\n"; + const auto diags = diagnose(r); + if (diags.empty()) m += "Not enough split calls to diagnose.\n"; + for (const Diagnosis& g : diags) { + m += "**" + md_escape(g.phase) + ": " + md_escape(g.verdict) + ".**\n\n"; + m += "- Roofline: " + fmt("%.2f", g.gpu_gb) + " GB " + g.unit + " (dense weights, KV rows, experts on the GPU) at the " + "probed read bandwidth would take " + fmt("%.2f", g.ideal_ms) + " ms; it takes " + fmt("%.2f", g.total_ms) + + " ms. Launches: " + fmt("%.0f", g.launches) + " " + g.unit + " (" + fmt("%.0f", g.direct) + " direct, " + + fmt("%.0f", g.nodes) + " replayed), ~" + fmt("%.2f", g.launch_ms) + " ms at the probed floor of a small kernel.\n"; + if (g.hit_rate >= 0) + m += "- Cache: " + pct(g.hit_rate) + " of the routed experts from VRAM (" + std::to_string(r.cached_experts) + " of " + + std::to_string(r.total_experts) + " held); " + fmt("%.3f", g.cpu_gb) + " GB " + g.unit + + " read by the CPU experts from RAM, " + fmt("%.3f", g.pcie_gb) + " GB over PCIe." + + (g.warm_cache ? " **Above 97%: this text keeps to the cached experts more than a real chat does (~87% " + "on real text on an 8-16 GB card), so the misses' cost is understated here; " + "`STRATA_PROFILE=1` on real chats, or `--text docs`, shows it.**" + : std::string()) + + "\n"; + if (g.round_trips > 0) + m += "- Host round trips: " + fmt("%.0f", g.round_trips) + " " + g.unit + " (the host waits for a router's " + "scores, routes and hands the card its experts), the card idle ~" + fmt("%.2f", g.round_trip_ms) + + " ms meanwhile" + (r.probes.copy_sync_us > 0 ? " (the probed copy-and-wait alone: ~" + + fmt("%.2f", g.round_trips * r.probes.copy_sync_us / 1000.0) + " ms)" : std::string()) + ".\n"; + if (!g.recover.empty()) { + m += "- Most to recover:"; + for (size_t i = 0; i < g.recover.size(); ++i) + m += std::string(i ? ";" : "") + " " + fmt("%.2f", g.recover[i].first) + " ms by " + md_escape(g.recover[i].second); + m += " (estimates: launches at the probed latency, kernels at the probed read bandwidth).\n"; + } + m += "\n| Family | ms | Launches | Launch ms (est.) | GB | GB/s | % of read | Verdict |\n" + "| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |\n"; + for (const FamilyVerdict& v : g.families) + m += "| " + std::string(prof::fam_title(v.fam)) + " | " + num(v.ms, 2) + " | " + num(v.launches, 0) + " | " + + num(v.launch_ms, 2) + " | " + (v.gb > 0 ? fmt("%.3f", v.gb) : std::string("-")) + " | " + + (v.gb > 0 ? num(v.gbs, 0) : std::string("-")) + " | " + (v.gb > 0 ? pct(v.read_share) : std::string("-")) + + " | " + md_escape(v.verdict) + " |\n"; + m += "\n"; + } + m += "Family rows are from the split calls (launched kernel by kernel); the verdict, roofline and launch lines from " + "every call. Bytes are the engine's model: each dense matrix once a visit, the KV rows attention reads, an " + "expert's weights each time a token routes to one on the card. Kernel time per launch is not measured, so " + "\"tiny kernels\" is a family's average.\n"; + m += "\n## Explain\n\n"; + for (const Finding& f : explain(r)) m += std::string("- ") + (f.flag ? "**far off:** " : "") + f.phase + ": " + f.text + "\n"; + m += "\n
Profile tables\n\nLaunches: the kernels the engine hands the card, " + + std::string(prof::launches_wrapped() ? "its direct launches and the nodes of the recordings it replays" + : "only the nodes of the recordings it replays (this build does not count " + "direct launches)") + + "; a BLAS call's own kernels are not counted.\n"; + for (const Run& run : r.runs) { + profile_table(m, run, prof::kPrompt); + profile_table(m, run, prof::kDecode); + } + for (const Run& run : r.long_points) profile_table(m, run, prof::kDecode); + m += "\n
\n\nThe run took " + num(r.total_s, 0) + " s: probes " + num(r.probe_s, 0) + ", load " + + num(r.load_s, 0) + ", warm-up " + num(r.warm_s, 0) + ", quick tier " + num(r.quick_s, 0) + + (r.long_points.empty() ? std::string() : ", long tier " + num(r.long_s, 0)) + " s.\n"; + return scrub(m, private_strings()); +} + +} // namespace strata::poly::bench diff --git a/engine/src/poly/bench_report.hpp b/engine/src/poly/bench_report.hpp new file mode 100644 index 000000000..e3e567a32 --- /dev/null +++ b/engine/src/poly/bench_report.hpp @@ -0,0 +1,163 @@ +// src/poly/bench_report.hpp - strata-poly --bench-report: what the report holds, the hardware probes, and the JSON and +// Markdown it is written as. +// +// The report is meant to be posted: it holds the card, the CPU, the engine's version, the settings, the speeds, the +// event profile (profile.hpp) and the probes, and nothing that names the person or the PC. No path (a setting's value +// that looks like one is written as ), no user or host name, no serial number or bus address, no prompt (the +// prompts are random tokens from a fixed seed). scrub() takes out of the finished text every string of +// private_strings() as a last line of defence, and bench_report_test.cpp checks a report for them. +// +// The probes (bench_probe.cpp) are measured before the model loads, so the card's memory is free for them. +#pragma once + +#include "profile.hpp" + +#include +#include +#include +#include + +namespace strata::poly::bench { + +struct Gpu { + std::string name, arch, driver, runtime, backend; // backend: "cuda" or "hip" + int sms = 0; // SMs (NVIDIA) or CUs (AMD) + double vram_gib = 0; + double mem_peak_gbs = 0; // from the memory clock and bus width, 0 if unknown + int pcie_gen = -1, pcie_width = -1, pcie_gen_max = -1, pcie_width_max = -1; // -1: not known + std::string pcie_source; // "nvml", "setupapi", "sysfs" or "" (not known) +}; + +struct Host { + std::string cpu, os, isa; // isa: the CPU experts' instruction set (strata::quant::best_isa()) + std::vector flags; + int threads = 0; // the CPUs this process may use + int engine_threads = 0; // the engine's CPU expert threads + double ram_gib = 0; +}; + +struct DotRate { + std::string type, kernel, isa; + double gbs_all = 0, gbs_one = 0; // GB/s of weights, all the engine's threads and one + int threads = 0; +}; + +struct Probes { + double h2d_pinned_gbs = 0, h2d_pageable_gbs = 0, d2h_pinned_gbs = 0, gpu_mem_gbs = 0, ram_read_gbs = 0; + int ram_threads = 0; + double launch_us = 0; // an empty kernel launched back to back + double graph_node_us = 0; // a node of a replayed recording of empty kernels + double small_us = 0; // a small dependent kernel (4 KiB in, 4 KiB out) back to back: a kernel's floor + double small_node_us = 0; // the same as a node of a replayed recording + double wide_node_us = 0; // a replayed node of a kernel across the whole card (2 blocks a CU, a float a thread) + double sync_us = 0; // a host round trip: an empty kernel and the host waiting for its event + double copy_sync_us = 0; // a 1 KiB copy to the host, waited for (a router's scores) + double read_gbs = 0; // a read-only kernel over 512 MiB of the card's memory + double fma_gflops = 0; // fp32 multiply-adds + std::vector dots; + double seconds = 0; +}; + +struct Model { + std::string name, arch, file_type; + double size_gib = 0; + int n_expert = 0, n_used = 0, n_moe = 0; + double expert_mib = 0; // one routed expert's gate, up and down +}; + +/// One request of the run: a prompt read (some of it may be the conversation's already) and an answer. +struct Run { + std::string name; + bool single = false; // its answer one token a call, no guesses + int64_t prompt_tokens = 0, reused = 0, read = 0, produced = 0, context_end = 0; + double prompt_ms = 0, decode_ms = 0; + int64_t guessed = 0, guessed_right = 0; + prof::Profile profile; + + double prompt_tok_s() const { return prompt_ms > 0 ? 1000.0 * (double) read / prompt_ms : 0.0; } + /// The first token is the prompt's (as Session::Result counts it): the rate of the ones after it. + double decode_tok_s() const { return decode_ms > 0 && produced > 1 ? 1000.0 * (double) (produced - 1) / decode_ms : 0.0; } +}; + +struct Finding { + std::string phase, text; + bool flag = false; // far from what the probes say the hardware does +}; + +struct Report { + std::string engine_version = "dev", commit = "unknown", tier = "quick"; + std::string prompt_source = "random tokens of the vocabulary"; + bool launches_wrapped = false; // direct launches counted (prof::launches_wrapped()); else only replays + Model model; + std::vector> settings; // the engine's arguments, paths taken out + std::vector> env; // STRATA_* settings, paths taken out + Gpu gpu; + Host host; + Probes probes; + double load_s = 0, total_s = 0, probe_s = 0, warm_s = 0, quick_s = 0, long_s = 0; // seconds + int cached_experts = 0, total_experts = 0, max_context = 0; + double cached_gib = 0; + std::vector runs; // the quick tier's requests + std::vector long_points; // --long: the checkpoints of the one long conversation + std::string long_error; // why the long tier stopped early ("" when it did not) +}; + +/// The engine's arguments as (option, value) pairs: a value that looks like a path or a file is "", and +/// --model's is left out (Report::model says what the file is). +std::vector> clean_args(const std::vector& argv); +/// The STRATA_* variables set in this process, with values that look like paths as ""; the API key's never. +std::vector> clean_env(char** envp); +/// True for a value that names a file or a folder. +bool looks_like_path(const std::string& v); + +/// This user's and this PC's names and folders as they could show up in a text: user and host names, the home +/// and working folders. Strings under four characters are left out (they would match everywhere). +std::vector private_strings(); +/// `text` with every one of `secrets` replaced by . +std::string scrub(std::string text, const std::vector& secrets); + +/// The explain section: each phase against what the probes measured. +std::vector explain(const Report& r); + +/// The diagnosis of one phase (decode: the one-token-a-call answers; prompt: the longest read): each family's time, +/// launches, bytes and verdict, the whole token's (or call's) verdict, its roofline and what would recover the most. +struct FamilyVerdict { + int fam = 0; + double ms = 0, launches = 0, launch_ms = 0, gb = 0, gbs = 0, read_share = 0, avg_kernel_us = 0; + bool tiny = false; + std::string verdict; +}; +struct Diagnosis { + std::string phase, unit; // "decode" / "prompt NNNN", "a token" / "the call" + bool ok = false; + double total_ms = 0, launches = 0, direct = 0, nodes = 0, launch_ms = 0, gpu_gb = 0, ideal_ms = 0; + double wait_cpu_ms = 0, wait_upload_ms = 0, host_gap_ms = 0; + double round_trips = 0, round_trip_ms = 0; // the host's waits for router scores, and the GPU's idle meanwhile + bool warm_cache = false; // the hit rate is above what real text gives (bench text) + double hit_rate = -1, cpu_gb = 0, pcie_gb = 0; + std::vector families; + std::string verdict; + std::vector> recover; // ms, what would recover it; the largest first, at most 3 +}; +std::vector diagnose(const Report& r); + +/// The commit the engine was built from (git describe at configure time), or "unknown". +const char* build_commit(); + +std::string to_json(const Report& r); +std::string to_markdown(const Report& r); + +/// A request's profile written alone (STRATA_PROFILE=1 in normal use): hardware without probes, and the profile. +std::string session_json(const Report& r, const prof::Profile& p); + +// ---- bench_probe.cpp, bench_kernels.cu (need the card) ---- +/// The kernel probes: launch latency, a replay's cost a node, a read-only kernel's bandwidth, fp32 FMA; ~1 s. +void probe_kernels(Probes& p, int device); +Gpu gpu_info(int device); +Host host_info(); +/// The copies and memory reads, ~10 s; before the model is loaded. `log` gets a line a probe (may be null). +void probe_hardware(Probes& p, int device, void (*log)(const char*)); +/// The CPU experts' dot product for each (ggml type id, row length) on `threads` threads and one, ~2 s a type. +void probe_dots(Probes& p, const std::vector>& type_cols, int threads); + +} // namespace strata::poly::bench diff --git a/engine/src/poly/bench_report_test.cpp b/engine/src/poly/bench_report_test.cpp new file mode 100644 index 000000000..5354f8ebf --- /dev/null +++ b/engine/src/poly/bench_report_test.cpp @@ -0,0 +1,437 @@ +// src/poly/bench_report_test.cpp - --bench-report's report without a card: the profile's sums, the settings with +// their paths taken out, the explain section's flags, and a whole report scanned for this PC's and user's names. +#include "bench_report.hpp" + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#endif + +namespace B = strata::poly::bench; +namespace P = strata::poly::prof; + +namespace { + +int failed = 0; +#define CHECK(c) \ + do { \ + if (!(c)) { \ + std::fprintf(stderr, "bench_report_test:%d: CHECK(%s) failed\n", __LINE__, #c); \ + ++failed; \ + } \ + } while (0) + +bool has(const std::string& s, const std::string& x) { return s.find(x) != std::string::npos; } + +void set_env(const char* k, const char* v) { +#ifdef _WIN32 + _putenv_s(k, v); +#else + setenv(k, v, 1); +#endif +} + +// a call's figures: `ms` of family f, `tokens` tokens +P::Acc call(int f, double ms, int64_t tokens, double wall) { + P::Acc a; + a.fam_ms[f] = ms; + a.tokens = tokens; + a.calls = 1; + a.wall_ms = wall; + return a; +} + +void test_profile() { + P::Profile p; + p.add_call(P::kPrompt, 0, true, call(P::kExpertsGpu, 100, 1024, 110)); + p.add_call(P::kPrompt, 1024, true, call(P::kWaitUpload, 50, 1024, 55)); + p.add_call(P::kDecode, 2048, true, call(P::kWaitCpu, 30, 1, 31)); + p.add_call(P::kDecode, 9000, false, call(P::kUnsplit, 40, 1, 41)); + CHECK(p.all[P::kPrompt].tokens == 2048); + CHECK(p.all[P::kPrompt].timeline_ms() == 150); + CHECK(p.split[P::kDecode].calls == 1 && p.all[P::kDecode].calls == 2); + CHECK(p.by_ctx_all[P::kDecode].size() == 3); // 0-2K, 2K-8K, 8K-32K + CHECK(p.by_ctx_all[P::kDecode][1].calls == 1 && p.by_ctx_all[P::kDecode][2].calls == 1); + CHECK(P::bucket_name(0) == "0K-2K" && P::bucket_name(2) == "8K-32K" && P::bucket_name(6) == "256K+"); + P::Acc la = call(P::kExpertsGpu, 10, 2, 11); + la.fam_launches[P::kExpertsGpu] = 900; + la.fam_launches[P::kNorms] = 700; + p.add_call(P::kDecode, 100, true, la); + CHECK(p.all[P::kDecode].launches() == 1600 && p.split[P::kDecode].fam_launches[P::kNorms] == 700); + P::Json j; + j.open(); + P::profile_json(j, "profile", p); + j.close(); + CHECK(has(j.s, "\"experts_gpu\":100")); + CHECK(has(j.s, "\"context\":\"8K-32K\"")); + CHECK(has(j.s, "\"launches_by_family\":{\"norms\":700,\"experts_gpu\":900}") && has(j.s, "\"launches_per_token\":")); + CHECK(has(j.s, "\"share\":{\"experts_gpu\":0.6667,\"wait_upload\":0.3333}")); + int depth = 0; + for (char c : j.s) depth += c == '{' || c == '[' ? 1 : c == '}' || c == ']' ? -1 : 0; + CHECK(depth == 0); + p.reset(); + CHECK(p.all[P::kPrompt].calls == 0 && p.every == 16); + // the JSON writer's strings and numbers + P::Json q; + q.open(); + q.str("s", "a\"b\\c\nd\x01"); + q.num("x", 2.50); + q.num("y", -0.0001, 2); + q.num("z", 1.0 / 0.0); + q.close(); + CHECK(q.s == "{\"s\":\"a\\\"b\\\\c\\nd\\u0001\",\"x\":2.5,\"y\":0,\"z\":null}"); +} + +void test_settings() { + const std::vector argv{"--model", "/home/someone/models/Inkling-2-Mini-IQ4_NL.gguf", + "--expert-profile", "/home/someone/data/expert-profile.txt", + "--max-context", "32768", + "--kv", "q8_0", + "--tokens", "1,2,3", + "--draft-model", "D:\\models\\d.gguf", + "--no-graphs", "--cache-bias", + "0.5", "--pinned-session", + "system.bin", "--bench-report", + "out/report"}; + const auto a = B::clean_args(argv); + std::string all; + for (const auto& [k, v] : a) all += k + "=" + v + " "; + CHECK(!has(all, "--model") && !has(all, "someone") && !has(all, "Inkling") && !has(all, "models")); + CHECK(has(all, "--expert-profile=") && has(all, "--draft-model=") && has(all, "--pinned-session=")); + CHECK(has(all, "--tokens=") && has(all, "--max-context=32768") && has(all, "--kv=q8_0")); + CHECK(has(all, "--no-graphs= ") && has(all, "--cache-bias=0.5") && !has(all, "--bench-report")); + std::vector env_s{"STRATA_API_KEY=sk-secret", "STRATA_PROFILE_OUT=/home/someone/p.json", + "STRATA_PROFILE=1", "PATH=/usr/bin", "STRATA_PF_I8MMA=0", "HOME=/home/someone"}; + std::vector envp; + for (std::string& e : env_s) envp.push_back(e.data()); + envp.push_back(nullptr); + const auto e = B::clean_env(envp.data()); + std::string ev; + for (const auto& [k, v] : e) ev += k + "=" + v + " "; + CHECK(has(ev, "STRATA_API_KEY=") && !has(ev, "sk-secret")); + CHECK(has(ev, "STRATA_PROFILE_OUT=") && has(ev, "STRATA_PROFILE=1 ") && has(ev, "STRATA_PF_I8MMA=0")); + CHECK(!has(ev, "PATH=") && !has(ev, "HOME") && !has(ev, "someone")); + CHECK(B::looks_like_path("C:x") == false && B::looks_like_path("C:\\x") && B::looks_like_path("~/m") && + B::looks_like_path("m.gguf") && !B::looks_like_path("q8_0") && !B::looks_like_path("0.5")); +} + +void test_scrub() { + const std::string t = B::scrub("alice ran it in /home/alice/m on wonderbox; malice, alice_2 and Alice stay", + {"/home/alice", "alice", "wonderbox", "ab"}); + CHECK(t == " ran it in /m on ; malice, alice_2 and Alice stay"); +} + +B::Report sample() { + B::Report r; + r.engine_version = "0.1.66"; + r.commit = "1a41ff673"; + r.model = {"Inkling 2 Mini", "inkling2_loop", "iq4_nl/iq4_nl", 17.6, 64, 8, 24, 3.375}; + r.gpu.name = "NVIDIA GeForce RTX 2070 SUPER"; + r.gpu.backend = "cuda"; + r.gpu.arch = "sm_75"; + r.gpu.sms = 40; + r.gpu.vram_gib = 8; + r.gpu.pcie_gen = 3; + r.gpu.pcie_width = 16; + r.host.cpu = "AMD Ryzen 5 3600XT 6-Core Processor"; + r.host.threads = 12; + r.host.engine_threads = 8; + r.host.ram_gib = 31.3; + r.host.isa = "avx2"; + r.probes.h2d_pinned_gbs = 12.2; + r.probes.h2d_pageable_gbs = 6.1; + r.probes.ram_read_gbs = 38; + r.probes.dots.push_back({"iq4_nl", "avx2", "avx2", 30, 6, 8}); + r.settings = {{"--max-context", "32768"}, {"--expert-profile", ""}}; + B::Run pr; + pr.name = "prompt 8192"; + pr.read = pr.prompt_tokens = 8192; + pr.prompt_ms = 10000; + pr.produced = 129; + pr.decode_ms = 6400; + P::Acc a; + a.fam_ms[P::kWaitUpload] = 5000; // half the time, 23 GB in 5 s = 4.6 GB/s against 12.2 probed + a.fam_ms[P::kExpertsGpu] = 4000; + a.fam_ms[P::kHostGap] = 1000; + a.upload_bytes = 23e9; + a.tokens = 8192; + a.calls = 8; + a.wall_ms = 10000; + pr.profile.add_call(P::kPrompt, 0, true, a); + P::Acc d; + d.fam_ms[P::kWaitCpu] = 25; + d.fam_ms[P::kExpertsGpu] = 20; + d.fam_ms[P::kHostGap] = 5; + d.tokens = 1; + d.calls = 1; + d.wall_ms = 50; + d.cpu_ms = 24; + d.cpu_experts = 200; // 675 MiB at 24 ms: 29 GB/s + for (int i = 0; i < 128; ++i) pr.profile.add_call(P::kDecode, 8192 + i, i % 16 == 0, d); + r.runs.push_back(pr); + r.total_s = 100; + return r; +} + +void test_explain() { + B::Report r = sample(); + auto f = B::explain(r); + bool upload_flag = false, decode_line = false, cpu_line = false; + for (const B::Finding& x : f) { + if (has(x.text, "waits for expert uploads")) upload_flag = x.flag && has(x.text, "12.2 GB/s pinned"); + if (x.phase == "decode" && has(x.text, "tok/s over")) decode_line = has(x.text, "50.0 ms a token"); + if (has(x.text, "CPU experts 24.0 ms a token")) cpu_line = !x.flag; // near the probes: no flag + } + if (!(upload_flag && decode_line && cpu_line)) + for (const B::Finding& x : f) std::fprintf(stderr, " [%d] %s: %s\n", (int) x.flag, x.phase.c_str(), x.text.c_str()); + CHECK(upload_flag && decode_line && cpu_line); + r.probes.h2d_pinned_gbs = 6.0; // 4.6 of 6.0: not far off + for (const B::Finding& x : B::explain(r)) + if (has(x.text, "waits for expert uploads")) CHECK(!x.flag); +} + +void test_report_privacy() { + // names this "PC" has for the test; the report is scrubbed of whatever private_strings() finds + set_env("USER", "zq_tester_9"); + set_env("HOME", "/home/zq_tester_9"); + set_env("HOSTNAME", "zq-host-box"); + B::Report r = sample(); + r.model.name = "zq_tester_9's Inkling"; // a model named after its user + r.host.cpu = "CPU of zq-host-box"; + r.settings.push_back({"--note", "/home/zq_tester_9/x"}); + const std::string json = B::to_json(r), md = B::to_markdown(r); + for (const std::string* s : {&json, &md}) { + CHECK(!has(*s, "zq_tester_9") && !has(*s, "zq-host-box") && !has(*s, "/home/")); + CHECK(has(*s, "")); + for (const std::string& x : B::private_strings()) CHECK(!has(*s, x)); + } + CHECK(has(json, "\"kind\":\"strata-bench-report\"") && has(json, "\"explain\":[") && has(json, "\"probes\":{")); + CHECK(has(md, "## Explain") && has(md, "| 8192 | 819 | ") && has(md, "**far off:**")); + int depth = 0; + bool in_str = false, esc = false; + for (char c : json) { + if (in_str) { + if (esc) esc = false; + else if (c == '\\') esc = true; + else if (c == '"') in_str = false; + continue; + } + if (c == '"') in_str = true; + else if (c == '{' || c == '[') ++depth; + else if (c == '}' || c == ']') --depth; + CHECK(depth >= 0); + } + CHECK(depth == 0 && !in_str); + const std::string sess = B::session_json(r, r.runs[0].profile); + CHECK(has(sess, "\"kind\":\"strata-session-profile\"") && !has(sess, "zq_tester_9")); + if (const char* dump = std::getenv("BENCH_REPORT_TEST_DUMP")) { // for tools/test_bench_reports.py + if (FILE* f = std::fopen(dump, "wb")) { + std::fwrite(json.data(), 1, json.size(), f); + std::fclose(f); + } + } +} + +// A user whose name is a key of the JSON keeps the JSON whole: values are scrubbed, keys are not. And a home folder +// with backslashes (Windows) is found before JSON escapes them. +void test_scrub_values_only() { + set_env("USER", "share"); + set_env("HOME", "C:\\Users\\zq_win_home"); + B::Report r = sample(); + r.model.name = "share's model in C:\\Users\\zq_win_home\\m"; + const std::string json = B::to_json(r); + CHECK(has(json, "\"share\":{")); // the profile's shares stay + CHECK(!has(json, "zq_win_home") && has(json, "'s model")); + set_env("USER", "zq_tester_9"); + set_env("HOME", "/home/zq_tester_9"); +} + +// A synthetic launch-bound card (not a measured one): ~1,580 kernels a 25 ms token at an 8.5 us floor each (~13 ms), +// experts a quarter of the time: the report must say launch-bound on its own. +void test_diagnosis_launch_bound() { + B::Report r = sample(); + r.runs.clear(); + r.probes.launch_us = 8.5; + r.probes.graph_node_us = 8.2; + r.probes.small_us = 8.5, r.probes.small_node_us = 8.2; + r.probes.read_gbs = 560; + r.launches_wrapped = true; + B::Run run; + run.name = "prompt 2048, one token a call"; + run.single = true; + run.produced = 129; + run.decode_ms = 25.0 * 128; + P::Acc unsplit; // a replayed token: 25 ms, 1,580 kernels of recordings + unsplit.fam_ms[P::kUnsplit] = 25; + unsplit.fam_launches[P::kUnsplit] = 1580; + unsplit.fam_graph_nodes[P::kUnsplit] = 1580; + unsplit.fam_bytes[P::kDense] = 0.9e9; + unsplit.fam_bytes[P::kExpertsGpu] = 0.5e9; + unsplit.tokens = 1, unsplit.calls = 1, unsplit.wall_ms = 25; + unsplit.gpu_experts = 300, unsplit.cpu_experts = 84; + P::Acc split; // a split token, launched kernel by kernel: the families + split.fam_ms[P::kExpertsGpu] = 7; + split.fam_launches[P::kExpertsGpu] = 400; + split.fam_bytes[P::kExpertsGpu] = 0.5e9; + split.fam_ms[P::kDense] = 6; + split.fam_launches[P::kDense] = 300; + split.fam_bytes[P::kDense] = 0.9e9; + split.fam_ms[P::kNorms] = 8; + split.fam_launches[P::kNorms] = 700; + split.fam_ms[P::kAttention] = 3; + split.fam_launches[P::kAttention] = 180; + split.fam_ms[P::kWaitCpu] = 1; + split.tokens = 1, split.calls = 1, split.wall_ms = 25; + for (int i = 0; i < 128; ++i) run.profile.add_call(P::kDecode, 2048 + i, i % 16 == 0, i % 16 == 0 ? split : unsplit); + r.runs.push_back(run); + const auto d = B::diagnose(r); + CHECK(!d.empty() && d[0].verdict.rfind("launch-bound", 0) == 0); + if (!d.empty()) { + CHECK(d[0].launch_ms > 10 && d[0].launch_ms < 16); + CHECK(!d[0].recover.empty() && has(d[0].recover[0].second, "fewer launches")); + bool norms_launch = false; + for (const auto& v : d[0].families) + if (v.fam == P::kNorms) norms_launch = has(v.verdict, "launch-bound") && v.tiny; + CHECK(norms_launch); + std::fprintf(stderr, " diagnosis: %s\n", d[0].verdict.c_str()); + } + const std::string md = B::to_markdown(r); + CHECK(has(md, "## Diagnosis") && has(md, "launch-bound")); +} + +// The RX 9070 XT measured under WSL2 (IQ4_NL, reserve 700): a small kernel's floor 3.1 us (2.2 us across the card), +// 1,491 kernels a 24.1 ms token (~4.6 ms), 48 host round trips with the card idle ~5 ms, 4.3 GB at 594 GB/s (7.3 ms): +// not launch-bound; the round trips come first among what to recover. +void test_diagnosis_rx9070xt_measured() { + B::Report r = sample(); + r.runs.clear(); + r.probes.launch_us = 1.5, r.probes.graph_node_us = 1.4; + r.probes.small_us = 3.1, r.probes.small_node_us = 3.1, r.probes.wide_node_us = 2.2; + r.probes.read_gbs = 594; + r.launches_wrapped = true; + B::Run run; + run.name = "prompt 2048, one token a call"; + run.single = true; + P::Acc unsplit; + unsplit.fam_ms[P::kUnsplit] = 24.1; + unsplit.fam_launches[P::kUnsplit] = 1491; + unsplit.fam_graph_nodes[P::kUnsplit] = 1246; + unsplit.fam_bytes[P::kDense] = 2.217e9; + unsplit.fam_bytes[P::kRouting] = 0.028e9; + unsplit.fam_bytes[P::kAttention] = 0.132e9; + unsplit.fam_bytes[P::kExpertsGpu] = 1.95e9; + unsplit.tokens = 1, unsplit.calls = 1, unsplit.wall_ms = 24.1, unsplit.route_waits = 48; + unsplit.gpu_experts = 381, unsplit.cpu_experts = 3; + P::Acc split; + const struct { int f; double ms, n, gb; } fams[] = { + {P::kAttention, 2.8, 192, 0.132}, {P::kKvStore, 1.8, 384, 0}, {P::kDense, 5.9, 231, 2.217}, + {P::kNorms, 4.2, 343, 0}, {P::kRouting, 5.2, 96, 0.028}, {P::kExpertsGpu, 6.3, 240, 1.95}, + {P::kCopyH2D, 0.2, 5, 0}, {P::kWaitCpu, 0.3, 0, 0}}; + for (const auto& x : fams) split.fam_ms[x.f] = x.ms, split.fam_launches[x.f] = x.n, split.fam_bytes[x.f] = x.gb * 1e9; + split.tokens = 1, split.calls = 1, split.wall_ms = 27, split.route_waits = 48; + for (int i = 0; i < 128; ++i) run.profile.add_call(P::kDecode, 2048 + i, i % 16 == 0, i % 16 == 0 ? split : unsplit); + r.runs.push_back(run); + const auto d = B::diagnose(r); + CHECK(!d.empty() && d[0].verdict.rfind("launch-bound", 0) != 0); + if (!d.empty()) { + CHECK(d[0].launch_ms > 4 && d[0].launch_ms < 5); + CHECK(d[0].round_trips == 48 && d[0].round_trip_ms > 4); + CHECK(!d[0].recover.empty() && has(d[0].recover[0].second, "host round trips")); + std::fprintf(stderr, " diagnosis: %s\n", d[0].verdict.c_str()); + } +} + +// A card with everything in VRAM, replayed nodes at 1.5 us, a token of 2.2 GB at 300 GB/s probed: it must say +// bandwidth-bound, not launch-bound. And kernels twice a launch long are not launch-bound (the launches hide). +void test_diagnosis_bandwidth_and_hidden_launches() { + B::Report r = sample(); + r.runs.clear(); + r.probes.launch_us = 4.0; + r.probes.graph_node_us = 1.5; + r.probes.read_gbs = 300; // 2.2 GB a token at 300 GB/s: 7.3 of 11 ms + r.launches_wrapped = true; + B::Run run; + run.name = "prompt 2048, one token a call"; + run.single = true; + P::Acc unsplit; + unsplit.fam_ms[P::kUnsplit] = 11; + unsplit.fam_launches[P::kUnsplit] = 900; + unsplit.fam_graph_nodes[P::kUnsplit] = 900; + unsplit.fam_bytes[P::kDense] = 1.2e9; + unsplit.fam_bytes[P::kExpertsGpu] = 1.0e9; + unsplit.tokens = 1, unsplit.calls = 1, unsplit.wall_ms = 11; + unsplit.gpu_experts = 384; + P::Acc split; + split.fam_ms[P::kExpertsGpu] = 6; // 200 launches of 30 us: the kernels hide the launches + split.fam_launches[P::kExpertsGpu] = 200; + split.fam_bytes[P::kExpertsGpu] = 1.0e9; + split.fam_ms[P::kDense] = 5; + split.fam_launches[P::kDense] = 300; // 16.7 us a launch against 4 us: not launch-bound + split.fam_bytes[P::kDense] = 1.2e9; + split.tokens = 1, split.calls = 1, split.wall_ms = 13; + for (int i = 0; i < 128; ++i) run.profile.add_call(P::kDecode, 2048 + i, i % 16 == 0, i % 16 == 0 ? split : unsplit); + r.runs.push_back(run); + const auto d = B::diagnose(r); + CHECK(!d.empty() && d[0].verdict.rfind("bandwidth-bound", 0) == 0); + for (const auto& v : d.empty() ? std::vector{} : d[0].families) + CHECK(v.verdict.find("launch-bound") == std::string::npos); + if (!d.empty()) std::fprintf(stderr, " diagnosis: %s\n", d[0].verdict.c_str()); +} + +// A prompt: experts counted once a visit (in VRAM, copied in), the KV rows a tile of queries at a time +void test_diagnosis_prompt() { + B::Report r = sample(); + r.probes.launch_us = 4.0; + r.probes.graph_node_us = 1.5; + r.probes.read_gbs = 400; + r.launches_wrapped = true; + P::Acc a; + a.fam_ms[P::kExpertsGpu] = 2000; + a.fam_launches[P::kExpertsGpu] = 20000; + a.fam_ms[P::kWaitUpload] = 300; + a.fam_bytes[P::kExpertsGpu] = 3.0e9; + a.fam_bytes[P::kDense] = 0.9e9; + a.fam_ms[P::kDense] = 300; + a.fam_launches[P::kDense] = 2000; + a.gpu_experts = 400, a.staged_experts = 2000, a.cpu_experts = 0; + a.tokens = 2048, a.calls = 2, a.wall_ms = 2600; + r.runs[0].profile = P::Profile{}; + r.runs[0].read = 2048; + r.runs[0].profile.add_call(P::kPrompt, 0, true, a); + const auto d = B::diagnose(r); + bool found = false; + for (const auto& g : d) + if (g.phase.rfind("prompt", 0) == 0) { + found = true; + CHECK(g.hit_rate > 0.16 && g.hit_rate < 0.17); // 400 of 2,400 a visit from VRAM + CHECK(g.verdict.rfind("launch-bound", 0) != 0); + std::fprintf(stderr, " prompt diagnosis: %s\n", g.verdict.c_str()); + } + CHECK(found); +} + +} // namespace + +int main() { + test_profile(); + test_settings(); + test_scrub(); + test_explain(); + test_report_privacy(); + test_scrub_values_only(); + test_diagnosis_launch_bound(); + test_diagnosis_rx9070xt_measured(); + test_diagnosis_bandwidth_and_hidden_launches(); + test_diagnosis_prompt(); + if (failed) { + std::fprintf(stderr, "bench_report_test: %d checks failed\n", failed); + return 1; + } + std::printf("bench_report_test: ok\n"); + return 0; +} diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 35005b37e..1ee5c453d 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -848,6 +848,421 @@ struct Engine::Swap { bool wait_freed = false; }; +// ---- the event profiler (profile.hpp) ---- +// +// The stream's events of each call, kept until the stream is past them (flush()), then turned into the families' +// times. No event goes into a recording: a split token launches its kernels one by one (run()), and a replay in a +// split call is one family (launch_graph()), so the replays every token makes are as they were. +#if !defined(STRATA_GPU_METAL) +// The kernel nodes of a recording (the profiler counts a replay's as launches). +static uint64_t graph_kernels(cudaGraph_t g) { + size_t n = 0; + if (cudaGraphGetNodes(g, nullptr, &n) != cudaSuccess || n == 0) { + (void) cudaGetLastError(); + return 0; + } +#if defined(STRATA_USE_HIP) + std::vector nodes(n); +#else + std::vector nodes(n); +#endif + if (cudaGraphGetNodes(g, nodes.data(), &n) != cudaSuccess) { + (void) cudaGetLastError(); + return 0; + } + uint64_t k = 0; + for (size_t i = 0; i < n; ++i) { +#if defined(STRATA_USE_HIP) + hipGraphNodeType t{}; + if (hipGraphNodeGetType(nodes[i], &t) == hipSuccess && t == hipGraphNodeTypeKernel) ++k; +#else + cudaGraphNodeType t{}; + if (cudaGraphNodeGetType(nodes[i], &t) == cudaSuccess && t == cudaGraphNodeTypeKernel) ++k; +#endif + } + (void) cudaGetLastError(); + return k; +} + +struct Engine::Timeline { + struct Mark { + cudaEvent_t ev; + int fam; + bool pooled; ///< the pool's, given back once read + uint64_t launches; ///< prof::launch_counter() when it was recorded + uint64_t nodes; ///< prof::graph_node_counter() then + }; + struct Side { + cudaEvent_t a = nullptr, b = nullptr; + double bytes = 0; + }; + struct Call { + int phase = prof::kPrompt; + int64_t pos = 0; + int n = 0; + bool split = false, gap = false; + std::vector marks; + std::vector sides; + Clock::time_point t0, t1; + Stats s0, s1; + double bytes = 0; + double dense_b = 0, router_b = 0, kv_b = 0, gpu_b = 0, cpu_b = 0; ///< the byte model's (prof_bytes_of()) + }; + std::mutex mu; + std::vector pool; + std::unordered_map kernels_of; ///< a recording's kernel nodes, counted as it is made + std::deque pending; + std::unique_ptr cur; + int depth = 0; + cudaEvent_t last = nullptr; ///< the last call's end, for the gap to the next one + Clock::time_point last_t; + bool next_gap = false; ///< the next call goes on from the last one in the same request + int phase = prof::kPrompt; + int64_t decode_calls = 0; + prof::Profile prof; + + ~Timeline() { + for (cudaEvent_t e : pool) (void) cudaEventDestroy(e); + for (const Call& c : pending) { + for (const Mark& m : c.marks) + if (m.pooled) (void) cudaEventDestroy(m.ev); + for (const Side& s : c.sides) { + if (s.a) (void) cudaEventDestroy(s.a); + if (s.b) (void) cudaEventDestroy(s.b); + } + } + if (cur) + for (const Mark& m : cur->marks) + if (m.pooled) (void) cudaEventDestroy(m.ev); + if (last) (void) cudaEventDestroy(last); + } + cudaEvent_t take() { + if (pool.empty()) { + cudaEvent_t e = nullptr; + ck(cudaEventCreate(&e), "the profiler's events"); + return e; + } + cudaEvent_t e = pool.back(); + pool.pop_back(); + return e; + } + void give(cudaEvent_t e) { + if (e) pool.push_back(e); + } + // An event's own answers (not ready, not recorded) are taken off the error state; any other error is a launch's, + // and stays for the engine's next ck() to report. +#if defined(STRATA_USE_HIP) + static constexpr cudaError_t kEventNotRecorded = hipErrorInvalidResourceHandle; +#else + static constexpr cudaError_t kEventNotRecorded = cudaErrorInvalidResourceHandle; +#endif + static void forget(cudaError_t e) { + if (e != cudaSuccess && cudaPeekAtLastError() == e && + (e == cudaErrorNotReady || e == kEventNotRecorded)) + (void) cudaGetLastError(); + } + static float between(cudaEvent_t a, cudaEvent_t b) { + float ms = 0.f; + const cudaError_t e = cudaEventElapsedTime(&ms, a, b); + if (e != cudaSuccess) { + forget(e); + return 0.f; + } + return std::max(ms, 0.f); + } + static bool done(cudaEvent_t e, bool wait) { + const cudaError_t q = wait ? cudaEventSynchronize(e) : cudaEventQuery(e); + if (q == cudaSuccess) return true; + forget(q); + return false; + } + /// The calls the stream is past (all of them with `wait`) into prof. + void flush(bool wait) { + while (!pending.empty()) { + Call& c = pending.front(); + bool ready = done(c.marks.back().ev, wait); + for (const Side& s : c.sides) ready = ready && (!s.b || done(s.b, wait)); + if (!ready) return; + prof::Acc a; + for (size_t i = 0; i + 1 < c.marks.size(); ++i) { + a.fam_ms[c.marks[i].fam] += between(c.marks[i].ev, c.marks[i + 1].ev); + a.fam_launches[c.marks[i].fam] += (double) (c.marks[i + 1].launches - c.marks[i].launches); + a.fam_graph_nodes[c.marks[i].fam] += (double) (c.marks[i + 1].nodes - c.marks[i].nodes); + } + if (c.gap && last) { + a.fam_ms[prof::kHostGap] += between(last, c.marks.front().ev); + a.wall_ms += std::chrono::duration(c.t0 - last_t).count(); + } + a.wall_ms += std::chrono::duration(c.t1 - c.t0).count(); + a.tokens = c.n; + a.calls = 1; + a.cpu_ms = c.s1.cpu_ms - c.s0.cpu_ms; + a.route_wait_ms = c.s1.route_wait_ms - c.s0.route_wait_ms; + a.route_waits = (double) (c.s1.route_waits - c.s0.route_waits); + // a prompt batch counts its experts once a layer visit (Stats::batch_*): what it found in VRAM against + // what it copied in or left to the CPU + a.cpu_experts = c.s1.cpu_experts - c.s0.cpu_experts + c.s1.batch_cpu_experts - c.s0.batch_cpu_experts; + a.gpu_experts = c.s1.gpu_experts - c.s0.gpu_experts + c.s1.batch_hit_experts - c.s0.batch_hit_experts; + a.staged_experts = (double) (c.s1.batch_staged_experts - c.s0.batch_staged_experts); + a.upload_bytes = c.bytes; + a.fam_bytes[prof::kDense] += c.dense_b; + a.fam_bytes[prof::kRouting] += c.router_b; + a.fam_bytes[prof::kAttention] += c.kv_b; + a.fam_bytes[prof::kExpertsGpu] += c.gpu_b; + a.cpu_expert_bytes = c.cpu_b; + for (const Side& s : c.sides) + if (s.a && s.b) { + a.side_ms += between(s.a, s.b); + a.side_bytes += s.bytes; + } + prof.add_call(c.phase, c.pos, c.split, a); + // the call's last event stays, for the gap to the next call; it is the pool's (prof_end_on()) + for (size_t i = 0; i + 1 < c.marks.size(); ++i) + if (c.marks[i].pooled) give(c.marks[i].ev); + give(last); + last = c.marks.back().ev; + last_t = c.t1; + for (const Side& s : c.sides) give(s.a), give(s.b); + pending.pop_front(); + } + } + /// A mark of the call under way, on stream st (an event of the pool). + void mark(int f, void* st) { + if (!cur->marks.empty() && cur->marks.back().fam == f) return; // the same family goes on + cudaEvent_t e = take(); + ck(cudaEventRecord(e, cs(st)), "the profiler's events"); + cur->marks.push_back({e, f, true, prof::launch_counter(), prof::graph_node_counter()}); + } +}; + +void Engine::enable_profile(int every) { + prof_prepare(); + if (!tl_) tl_ = std::make_unique(); + prof::launch_counting().store(true, std::memory_order_relaxed); + tl_->prof.every = std::max(every, 1); +} + +void Engine::prof_phase(int phase, bool request) { + if (!tl_) return; + std::lock_guard l(tl_->mu); + tl_->phase = phase == prof::kDecode ? prof::kDecode : prof::kPrompt; + if (request) { + tl_->next_gap = false; + ++tl_->prof.requests; + } +} + +const prof::Profile* Engine::profile() { + if (!tl_) return nullptr; + OnCard here(device_, split_); + ck(cudaStreamSynchronize(cs(st_)), "the profile"); + if (up_) ck(cudaStreamSynchronize(cs(up_)), "the profile"); + std::lock_guard l(tl_->mu); + tl_->flush(true); + return &tl_->prof; +} + +void Engine::profile_reset() { + if (!profile()) return; + std::lock_guard l(tl_->mu); + tl_->prof.reset(); + tl_->next_gap = false; +} + +void Engine::prof_begin_on(int n) { + Timeline& t = *tl_; + std::lock_guard l(t.mu); + if (t.depth++ > 0) return; + t.flush(false); + t.cur = std::make_unique(); + Timeline::Call& c = *t.cur; + c.phase = t.phase; + c.pos = pos_; + c.n = n; + // (a call of no tokens, keep()'s, is never split and does not count for the sampling) + c.split = n > 0 && (t.phase == prof::kPrompt || t.decode_calls++ % t.prof.every == 0); + c.gap = t.next_gap; + c.t0 = Clock::now(); + c.s0 = stats(); + t.mark(c.split ? prof::kCopyH2D : prof::kUnsplit, st_); +} + +void Engine::prof_end_on() { + Timeline& t = *tl_; + std::lock_guard l(t.mu); + if (t.depth == 0 || --t.depth > 0) return; + Timeline::Call& c = *t.cur; + // the end is always a fresh event of the pool: the next call's gap is measured from it + cudaEvent_t e = t.take(); + ck(cudaEventRecord(e, cs(st_)), "the profiler's events"); + c.marks.push_back({e, prof::kHostGap, true, prof::launch_counter(), prof::graph_node_counter()}); + c.t1 = Clock::now(); + c.s1 = stats(); + const CallBytes cb = prof_bytes_of(c.pos, c.n, c.s0, c.s1); + c.dense_b = cb.dense, c.router_b = cb.router, c.kv_b = cb.kv, c.gpu_b = cb.gpu, c.cpu_b = cb.cpu; + t.pending.push_back(std::move(c)); + t.cur.reset(); + t.next_gap = true; +} + +void Engine::pmark_on(int f) { + Timeline& t = *tl_; + std::lock_guard l(t.mu); + if (!t.cur || !t.cur->split) return; + if (recording_) return; // a recording is replayed by later tokens: it has no events (launch_graph() marks it) + t.mark(f, st_); +} + +bool Engine::prof_split() const { return tl_ && tl_->cur && tl_->cur->split; } + +void Engine::prof_unsplit() { + if (!tl_) return; + std::lock_guard l(tl_->mu); + if (!tl_->cur || !tl_->cur->split) return; + tl_->mark(prof::kUnsplit, st_); + tl_->cur->split = false; +} + +void Engine::launch_graph(void* exec, int fam, const char* what) { + if (tl_) { + Timeline& t = *tl_; + std::lock_guard l(t.mu); + if (t.cur && t.cur->split) t.mark(fam, st_); + // a replay hands the card its recording's kernels: they count as launches of the family it is marked as + const auto it = t.kernels_of.find(exec); + if (it != t.kernels_of.end()) { + prof::launch_count().fetch_add(it->second, std::memory_order_relaxed); + prof::graph_node_count().fetch_add(it->second, std::memory_order_relaxed); + } + } + ck(cudaGraphLaunch((cudaGraphExec_t) exec, cs(st_)), what); +} + +int Engine::pside_begin(void* stream) { + if (!tl_) return -1; + Timeline& t = *tl_; + std::lock_guard l(t.mu); + if (!t.cur || !t.cur->split) return -1; + Timeline::Side s; + s.a = t.take(); + ck(cudaEventRecord(s.a, cs(stream)), "the profiler's events"); + t.cur->sides.push_back(s); + return (int) t.cur->sides.size() - 1; +} + +void Engine::pside_end(int id, void* stream, double bytes) { + if (!tl_ || id < 0) return; + Timeline& t = *tl_; + std::lock_guard l(t.mu); + if (!t.cur || id >= (int) t.cur->sides.size()) return; + Timeline::Side& s = t.cur->sides[(size_t) id]; + s.b = t.take(); + ck(cudaEventRecord(s.b, cs(stream)), "the profiler's events"); + s.bytes = bytes; +} + +void Engine::prof_bytes(double bytes) { + if (!tl_) return; + std::lock_guard l(tl_->mu); + if (tl_->cur) tl_->cur->bytes += bytes; +} + +void Engine::prof_kept(int n) { + if (!tl_) return; + std::lock_guard l(tl_->mu); + if (!tl_->pending.empty() && !tl_->cur) tl_->pending.back().n = std::min(tl_->pending.back().n, n); +} +#else // Metal: no profiler (enable_profile() says so); the launches are as they were +struct Engine::Timeline {}; +void Engine::enable_profile(int) { + std::fprintf(stderr, "strata-poly: the event profiler (STRATA_PROFILE) is not built for Metal\n"); +} +void Engine::prof_phase(int, bool) {} +const prof::Profile* Engine::profile() { return nullptr; } +void Engine::profile_reset() {} +void Engine::prof_begin_on(int) {} +void Engine::prof_end_on() {} +void Engine::pmark_on(int) {} +bool Engine::prof_split() const { return false; } +void Engine::prof_unsplit() {} +void Engine::launch_graph(void* exec, int, const char* what) { ck(cudaGraphLaunch((cudaGraphExec_t) exec, cs(st_)), what); } +int Engine::pside_begin(void*) { return -1; } +void Engine::pside_end(int, void*, double) {} +void Engine::prof_bytes(double) {} +void Engine::prof_kept(int) {} +#endif + +// The profiler's byte model: the dense matrices the engine uploads, by layer ("blk.N." in the name) or not (the output +// head, the norms), so that a call's dense reads are each layer's bytes once a visit of it, and the rest once. +void Engine::note_dense(const std::string& name, size_t bytes) { + int il = -1; + if (name.rfind("blk.", 0) == 0) il = std::atoi(name.c_str() + 4); + if (il < 0 || il > 100000) { + dense_other_b_ += (double) bytes; + return; + } + std::vector& to = name.find("ffn_gate_inp") != std::string::npos ? router_layer_b_ : dense_layer_b_; + if ((int) to.size() <= il) to.resize((size_t) il + 1, 0.0); + to[(size_t) il] += (double) bytes; +} + +void Engine::prof_prepare() { + if (prof_visits_ >= 0) return; + prof_visits_ = prof_moe_visits_ = 0; + prof_dense_call_ = dense_other_b_; + prof_router_call_ = 0; + for (int il = lo_; il < hi_; il = next_layer(il)) { // (a full walk: a looped core's pass is back at 0 after it) + ++prof_visits_; + if (layers_[(size_t) il].moe) ++prof_moe_visits_; + if (il < (int) dense_layer_b_.size()) prof_dense_call_ += dense_layer_b_[(size_t) il]; + if (il < (int) router_layer_b_.size()) prof_router_call_ += router_layer_b_[(size_t) il]; + } + // an expert's bytes: the mean over the MoE layers (a file may quantize layers apart) + double sum = 0; + int n = 0; + for (const Layer& L : layers_) + if (L.moe) sum += (double) (L.gu_bytes + L.u_bytes + L.d_bytes), ++n; + prof_expert_b_ = n ? sum / n : 0.0; + (void) kv_read_bytes(0, 0); // the architecture's own visits, now (Inkling2::kv_read_bytes()) +} + +// A call of n tokens from pos: the dense weights it reads (each matrix once a visit, whatever n is; the router's apart), +// the KV rows its attention reads (kv_read_bytes()), and the routed experts on the card and on the CPU: an expert a +// token and visit for a few tokens, each of a visit's experts once for a prompt batch (Stats::batch_*). +Engine::CallBytes Engine::prof_bytes_of(int64_t pos, int n, const Stats& s0, const Stats& s1) { + CallBytes c; + if (n <= 0 || prof_visits_ < 0) return c; + c.dense = prof_dense_call_; + c.router = prof_router_call_; + c.kv = kv_read_bytes(pos, n); + const double gpu = (double) (s1.gpu_experts - s0.gpu_experts + s1.batch_hit_experts - s0.batch_hit_experts + + s1.batch_staged_experts - s0.batch_staged_experts); + const double cpu = (double) (s1.cpu_experts - s0.cpu_experts + s1.batch_cpu_experts - s0.batch_cpu_experts); + c.gpu = gpu * prof_expert_b_; + c.cpu = cpu * prof_expert_b_; + return c; +} + +Engine::ExpertShape Engine::expert_shape() const { + ExpertShape x; + for (const Layer& L : layers_) { + if (!L.moe) continue; + x.gu_type = (int) L.gu_type; + x.u_type = (int) L.u_type; + x.d_type = (int) L.d_type; + x.gu_bytes = L.gu_bytes; + x.u_bytes = L.u_bytes; + x.d_bytes = L.d_bytes; + break; + } + x.n_embd = n_embd_; + x.n_ff = n_ff_exp_; + x.n_used = n_used_; + x.n_expert = n_expert_; + x.n_moe = n_moe_; + return x; +} + Engine::Engine() = default; Engine::~Engine() { @@ -884,6 +1299,7 @@ Engine::~Engine() { aside_.reset(); workers_.reset(); mmq_.reset(); + tl_.reset(); // the profiler's events (some of them recorded in graphs, which go below) #if defined(STRATA_GPU_METAL) // Metal recordings retain their resources. Retire them before releasing the allocation owners. for (void* g : graphs_) cudaGraphExecDestroy((cudaGraphExec_t) g); @@ -1825,6 +2241,11 @@ int64_t Engine::meta_u(const char* key, int64_t fallback) const { return v && v->is_num() ? (int64_t) v->u : fallback; } +std::string Engine::meta_s(const char* key) const { + const MetaValue* v = gg_ ? gg_->get(key) : nullptr; + return v && !v->is_num() ? v->s : std::string(); +} + // A layer's tensor, under any of its names. The draft block's are in the file it comes from. const TensorInfo* Engine::tensor(int il, const char* name) const { const Shards& g = block_ && il >= n_layer_ ? *block_ : *gg_; @@ -2196,6 +2617,7 @@ Dev Engine::upload_as(const TensorInfo* t, const std::string& name, int64_t n_in : strata::quant::quantize_q4_0_ref; dense_at_ += pad(out) + kTail; if (!dense_) return d; + note_dense(t->name, out); if (dense_at_ > dense_bytes_) throw std::logic_error("the dense arena is too small for " + t->name); // a few thousand rows at a time, to floats and to Q4_0, on threads of their own: the engine's are not // started yet @@ -2227,6 +2649,7 @@ Dev Engine::upload_as(const TensorInfo* t, const std::string& name, int64_t n_in const Dev d{dense_ ? dense_ + dense_at_ : nullptr, type, (int) n_in, (int) n_out}; dense_at_ += pad(out) + kTail; if (!dense_) return d; + note_dense(t->name, out); if (dense_at_ > dense_bytes_) throw std::logic_error("the dense arena is too small for " + t->name); if (as_is) { h2d(d.p, home(*t).data(*t), bytes); @@ -4475,6 +4898,10 @@ const Stats& Engine::stats() const { all_stats_.ahead_used += s.ahead_used; all_stats_.cpu_ms += s.cpu_ms; all_stats_.route_wait_ms += s.route_wait_ms; + all_stats_.route_waits += s.route_waits; + all_stats_.batch_hit_experts += s.batch_hit_experts; + all_stats_.batch_staged_experts += s.batch_staged_experts; + all_stats_.batch_cpu_experts += s.batch_cpu_experts; } return all_stats_; } @@ -4644,6 +5071,7 @@ int Engine::card_rows() const { // The router's scores, and the copies of them and of the experts' input to the host. void Engine::moe_router(const Layer& L, int n) { + pmark(prof::kRouting); const size_t ne = (size_t) n_expert_; int j = (int) (&L - layers_.data()) + 1; // the next MoE layer, whose router on this layer's input guesses ahead while (j < n_layer_ && !layers_[(size_t) j].moe) ++j; @@ -4775,10 +5203,12 @@ void Engine::vram_ahead(int j, int n, size_t part) { staged_il_ = -1; // the staging buffer holds other experts now ck(cudaStreamWaitEvent(cs(up_), (cudaEvent_t) g.read, 0), "upload ahead"); uint8_t* at = stage_ + (size_t) me * ahead_slots_ * ahead_stride_; + const int side = pside_begin(up_); for (int i = 0; i < g.n; ++i, at += ahead_stride_) { ck(cudaMemcpyAsync(at, mirror(j, g.e[i]), L.gu2() + L.d_bytes, cudaMemcpyHostToDevice, cs(up_)), "upload ahead"); ck(cudaEventRecord((cudaEvent_t) g.arrived[i], cs(up_)), "upload ahead"); // usable on its own } + pside_end(side, up_, (double) g.n * (double) (L.gu2() + L.d_bytes)); ck(cudaEventRecord((cudaEvent_t) g.up, cs(up_)), "upload ahead"); up_last_ = g.up; g.here = 0; @@ -5171,9 +5601,11 @@ void Engine::pool_read(const Layer& L, PoolRead& r) { // thread that hands the cached experts to the card and ahead of them. bool Engine::moe(Layer& L, int il, int n, const std::function* first) { const size_t e_row = (size_t) n_embd_; + pmark(prof::kRouting); // to the experts' launches: the router's copy, and the stream idle while the host routes Clock::time_point t0 = Clock::now(); ck(cudaEventSynchronize((cudaEvent_t) ev_), "router"); stats_.route_wait_ms += ms_since(t0); + ++stats_.route_waits; // a host round trip: the card's scores to the host, its experts back if (block_pass_) route_block(il, h_rl_, n); if (pool_ && prompt_rows_ >= 4096 && !block_pass_) { rekeep(); @@ -5367,12 +5799,15 @@ bool Engine::moe(Layer& L, int il, int n, const std::function* first) { const std::function launch = [&] { if (split_) cudaSetDevice(device_); // one of the experts' threads, which every card's engine shares if (first && at == 0) (*first)(); + pmark(prof::kExpertsGpu); if (own >= 0) { // the miss this call took for the card, up before its experts run const Ahead& g = ahead_[kAheadGroups]; ck(cudaStreamWaitEvent(cs(up_), (cudaEvent_t) g.read, 0), "upload ahead"); + const int side = pside_begin(up_); ck(cudaMemcpyAsync(stage_ + (size_t) kAheadGroups * ahead_slots_ * ahead_stride_, mirror(il, own), L.gu2() + L.d_bytes, cudaMemcpyHostToDevice, cs(up_)), "upload ahead"); + pside_end(side, up_, (double) (L.gu2() + L.d_bytes)); ck(cudaEventRecord((cudaEvent_t) g.up, cs(up_)), "upload ahead"); up_last_ = g.up; } @@ -5389,8 +5824,11 @@ bool Engine::moe(Layer& L, int il, int n, const std::function* first) { for (int i0 = 0, m; i0 < n_cached; i0 += m) { // nor past the end of add_scaled()'s rows: d_'s rows from the start are the ones not added yet m = std::min({per, (i0 < own_at ? own_at : n_cached) - i0, kSumRows - i0 % kSumRows}); - if (i0 == own_at) + if (i0 == own_at) { + pmark(prof::kWaitUpload); ck(cudaStreamWaitEvent(cs(st_), (cudaEvent_t) ahead_[kAheadGroups].up, 0), "upload ahead"); + pmark(prof::kExpertsGpu); + } kernels::MmvqSlots gate_up{}, up{}, down{}; gate_up.lanes = up.lanes = down.lanes = lane_slots_; for (int j = 0; j < m; ++j) { @@ -5441,6 +5879,7 @@ bool Engine::moe(Layer& L, int il, int n, const std::function* first) { #endif // the next layer's guesses, up while the CPU computes this layer's experts if (ahead_j >= 0 && at == 0) vram_ahead(ahead_j, n, ahead_part); + if (n_host > 0) pmark(prof::kWaitCpu); // the stream's next work is the CPU's experts' sum }; // The next layer's router wait is what makes h_cpu_ free to write again. @@ -5520,7 +5959,10 @@ bool Engine::moe(Layer& L, int il, int n, const std::function* first) { } // The CPU's experts of n tokens into the routed experts' sum. -void Engine::moe_add(int n) { axpy(h_cpu_, 1.f, fo_, n * n_embd_, true, st_); } +void Engine::moe_add(int n) { + pmark(prof::kCopyH2D); // the kernel reads the CPU's sums from pinned memory + axpy(h_cpu_, 1.f, fo_, n * n_embd_, true, st_); +} // With every routed expert in VRAM, a few tokens' experts are routed on the card and found there by its picks // (moe_card()), so a layer never waits for the host. The cache's slots go to the card again when they changed. @@ -5582,6 +6024,7 @@ bool Engine::card_moe(int n) { // on the host, or its formats have no kernel for picks on the card. bool Engine::moe_card(Layer& L, int il, int n) { if (L.card == 0) return false; + pmark(prof::kRouting); if (!kernels::native_mmvq_ids_supported((int) L.gu_type) || !kernels::native_mmvq_ids_supported((int) L.u_type) || !kernels::native_mmvq_ids_supported((int) L.d_type) || !route_card(il, n, d_ids_, d_wts_)) { L.card = 0; @@ -5598,6 +6041,7 @@ bool Engine::moe_card(Layer& L, int il, int n) { h_bell_, d_bell_seq_, st_); table = d_zslots_ + (size_t) il * n_expert_; } else if (!all_cached()) { // card_far_: the experts it lacks, from the mirror into the staging buffer first + pmark(prof::kWaitUpload); far_plan(table, d_far_ + (size_t) il * n_expert_, d_ids_, rr, n_expert_, stage_, ahead_stride_, d_tab_, d_fetch_, d_nfetch_, st_); far_pull(d_fetch_, d_nfetch_, rr, (L.gu2() + L.d_bytes + 15) / 16 * 16, st_); @@ -5606,6 +6050,7 @@ bool Engine::moe_card(Layer& L, int il, int n) { } #endif const size_t xq_row = kernels::native_q8_1_bytes(n_embd_), ff = (size_t) n_ff_exp_; + pmark(prof::kExpertsGpu); // a mixed layer's gate and up are each a matrix of n_ff rows of its own type, up's into the second half const kernels::MmvqIds gate_up{table, d_ids_, 0, xq_, xq_row, n_used_, g_, 2 * ff, lane_slots_}; kernels::native_mmvq_ids((int) L.gu_type, gate_up, rr, n_embd_, L.mixed() ? n_ff_exp_ : 2 * n_ff_exp_, st_); @@ -5628,7 +6073,10 @@ bool Engine::moe_card(Layer& L, int il, int n) { if (moe_sum_later(n)) moe_left_ = true; else moe_sum(d_, d_wts_, fo_, n_embd_, n_used_, n, st_); #if !defined(STRATA_GPU_METAL) - if (rings) bell_add(h_bell_, d_bell_seq_, h_cpu_, fo_, n_embd_, st_); // (bells(): no sum later then) + if (rings) { // (bells(): no sum later then) + pmark(prof::kWaitCpu); // the card waits in it for the host's experts, then adds them + bell_add(h_bell_, d_bell_seq_, h_cpu_, fo_, n_embd_, st_); + } #endif return true; } @@ -5700,12 +6148,33 @@ void Engine::bell_job() { // downs after them. The two pinned buffers take turns, so the workers fill one while the other uploads. `alone`: // stagers_ fill them, while the workers compute experts. void Engine::stage(const Layer& L, const int32_t* experts, int m, void* stream, bool alone) { + // the profiler: on st_ the stream waits for these copies (and for the host that stages them); on another stream + // they go beside the work + const double prof_b = (double) m * (double) (L.gu_step + L.d_bytes); + if (stream == st_) { + pmark(prof::kWaitUpload); + prof_bytes(prof_b); + } staged_il_ = -1; // whatever the buffer held for (Ahead& g : ahead_) { // vram_ahead()'s groups go, once the calls that read them are done if (g.il < 0) continue; ck(cudaStreamWaitEvent(cs(stream), (cudaEvent_t) g.read, 0), "expert staging"); g.il = -1; } + // the side copy's span from here, after the waits: the copies and, without the mirror, the host's staging between + // its chunks (the span's rate is that of the whole staging, not of the link alone) + struct Side { + Engine& e; + void* s; + int id; + double b; + ~Side() { + try { + e.pside_end(id, s, b); + } catch (...) { + } + } + } prof_side{*this, stream, stream == st_ ? -1 : pside_begin(stream), prof_b}; const size_t step = L.gu_step, down_at = pad((size_t) m * step); #if !defined(STRATA_GPU_METAL) if (!mirror_of_.empty()) { @@ -6319,6 +6788,7 @@ void Engine::moe_rows(Layer& L, int il, int n) { // STRATA_POLY_STAGED_TILES: per size class and round, the staged experts' first rows (tb), and the same counted // from the round's first row (tb + n_tile * tile_row) int32_t* tb = cb + kClasses * ((size_t) n_expert_ + 1); + pmark(prof::kRouting); router_scores(L, n); // Routed on the card, a batch hands the host its picks: the host took longer to route a batch of 1,024 tokens // than the card took for its experts. @@ -6334,7 +6804,9 @@ void Engine::moe_rows(Layer& L, int il, int n) { } ck(cudaEventRecord((cudaEvent_t) ev_, cs(st_)), "router"); + pmark(prof::kDense); moe_shared(L, il, n); + pmark(prof::kRouting); // the stream idle while the host routes, up to the tables' copy // read() takes a layer's calls one after the other, so the buffer may hold this layer's experts from the // call before (staged_). The ones copied ahead do not depend on the routing and are this call's too. A @@ -6356,7 +6828,7 @@ void Engine::moe_rows(Layer& L, int il, int n) { const Clock::time_point t = Clock::now(); // the buffer is free once the layer before has read it ck(cudaStreamWaitEvent(cs(up_), (cudaEvent_t) ev_free_, 0), "expert staging"); - stage(L, L.ahead.data(), n_ahead, up_); + stage(L, L.ahead.data(), n_ahead, up_); // (its time and bytes: the profiler's side copies) ck(cudaEventRecord((cudaEvent_t) ev_ahead_, cs(up_)), "expert staging"); if (!freeze_experts_) { // the measured times are the machine's, not the request's: keep them out of a freeze ahead_ms_ = ms_since(t); @@ -6369,6 +6841,7 @@ void Engine::moe_rows(Layer& L, int il, int n) { ck(cudaEventSynchronize((cudaEvent_t) ev_), "router"); if (ahead && !early && !freeze_experts_) route_ms_ = ms_since(t0); stats_.route_wait_ms += ms_since(t0); + ++stats_.route_waits; const size_t cb_row = (size_t) n_expert_ + 1; const int32_t* d_tok = tab_; @@ -6537,6 +7010,7 @@ void Engine::moe_rows(Layer& L, int il, int n) { const int n_ex = (es.gate || es.up) && rg > 0 ? rg : 0; // A read of several calls copies each layer's experts outside the cache ahead (up_), and a copy of the tables // would wait behind them: there a kernel reads them from pinned memory. A call alone keeps the copy. + pmark(prof::kCopyH2D); if (kernel_tables_ && opt_.stage_ahead > 0 && shared_ahead_) { copy2(h_tab_, tab_, (int) n_tab, h_ex_, d_ex_, n_ex, st_); } else { @@ -6548,6 +7022,9 @@ void Engine::moe_rows(Layer& L, int il, int n) { const int rc = bounds[n_cached]; // the rows of the cached experts stats_.batch_cached += rc; + stats_.batch_hit_experts += n_cached; + stats_.batch_staged_experts += n_group - n_cached; + stats_.batch_cpu_experts += n_cpu; stats_.batch_staged += rg - rc; const float limit = clamp_exp_[(size_t) il]; @@ -6610,6 +7087,7 @@ void Engine::moe_rows(Layer& L, int il, int n) { int holds = -1; // the round in the buffer when this call is done // The card's part. With the CPU's beside it, the rows of its experts' places are left at nothing. const auto card = [&] { + pmark(prof::kExpertsGpu); if (n_cpu > 0) ck(cudaMemsetAsync(dx_, 0, (size_t) rr * n_embd_ * sizeof(float), cs(st_)), "expert rows"); if (rg > 0) Mmq::quantize(xn_, tok_of ? nullptr : d_tok, mq_, gt, n_embd_, n_embd_, q_rows, st_); if (rg > 0 && L.mixed()) Mmq::quantize(xn_, tok_of ? nullptr : d_tok, mqu_, ut, n_embd_, n_embd_, q_rows, st_); @@ -6695,11 +7173,13 @@ void Engine::moe_rows(Layer& L, int il, int n) { if (r == kept) { // the buffer has it } else if (r == 0 && early) { + pmark(prof::kWaitUpload); ck(cudaStreamWaitEvent(cs(st_), (cudaEvent_t) ev_ahead_, 0), "expert staging"); } else if (rows > 0) { - stage(L, group_.data() + g0, m, st_, n_cpu > 0); + stage(L, group_.data() + g0, m, st_, n_cpu > 0); // (a wait_upload of its own) holds = r; } + pmark(prof::kExpertsGpu); if (rows == 0) continue; // nothing routed to the experts that go ahead int most = 0; for (int g = g0; g < g0 + m; ++g) most = std::max(most, rows_of(g)); @@ -6740,6 +7220,7 @@ void Engine::moe_rows(Layer& L, int il, int n) { if (guard) scale_rows(dx_, n_embd_, n_embd_, rows, d_place + r0, hf_ + r0, false, st_); } ck(cudaEventRecord((cudaEvent_t) ev_free_, cs(st_)), "expert staging"); + if (n_cpu > 0) pmark(prof::kWaitCpu); // the experts' sum waits for the CPU's }; if (n_cpu == 0) { card(); @@ -6767,6 +7248,7 @@ void Engine::moe_rows(Layer& L, int il, int n) { share_[size] = std::clamp(0.5 * share_[size] + 0.5 * g / (c + g), 0.05, 0.95); } } + pmark(prof::kExpertsGpu); moe_sum(dx_, d_w, fo_, n_embd_, n_used_, n, st_); if (n_cpu > 0) moe_add(n); if (ahead && holds >= 0) { @@ -6811,9 +7293,18 @@ void* Engine::record(F&& work) { exec = nullptr; made = cudaGraphInstantiateWithFlags(&exec, g, 0); } +#if !defined(STRATA_GPU_METAL) + const uint64_t kernels = tl_ ? graph_kernels(g) : 0; +#endif cudaGraphDestroy(g); ck(made, "cudaGraphInstantiate"); graphs_.push_back(exec); +#if !defined(STRATA_GPU_METAL) + if (tl_) { + std::lock_guard l(tl_->mu); + tl_->kernels_of[(void*) exec] = kernels; + } +#endif return exec; } @@ -6835,7 +7326,7 @@ bool Engine::step_replay(std::map, void*>& in, const std::vecto ++step_unrecorded_; return false; } - ck(cudaGraphLaunch((cudaGraphExec_t) g, cs(st_)), "layer graph"); + launch_graph(g, prof::kGraph, "layer graph"); step_used_[g] = step_no_; return true; } @@ -6883,6 +7374,9 @@ void* Engine::record_step(const std::function& work) { exec = nullptr; made = forced ? cudaErrorMemoryAllocation : cudaGraphInstantiateWithFlags(&exec, g, 0); } +#if !defined(STRATA_GPU_METAL) + const uint64_t kernels = tl_ && made == cudaSuccess ? graph_kernels(g) : 0; +#endif cudaGraphDestroy(g); if (made == cudaErrorMemoryAllocation) { cudaGetLastError(); @@ -6897,6 +7391,12 @@ void* Engine::record_step(const std::function& work) { graphs_.push_back(exec); step_used_[exec] = step_no_; ++step_made_; +#if !defined(STRATA_GPU_METAL) + if (tl_) { // the profiler counts a replay's kernels (launch_graph()) + std::lock_guard l(tl_->mu); + tl_->kernels_of[(void*) exec] = kernels; + } +#endif if (step_used_.size() > step_cap_) trim_step_graphs(step_cap_ / 4 * 3, false); if (step_dropped_ == 0 && step_used_.size() >= 2 * std::max(step_logged_, 128)) { // the size, for the cap step_logged_ = step_used_.size(); @@ -6931,6 +7431,12 @@ void Engine::trim_step_graphs(size_t keep, bool all) { drop(step_passes_); graphs_.erase(std::remove_if(graphs_.begin(), graphs_.end(), [&](void* g) { return gone.count(g) > 0; }), graphs_.end()); +#if !defined(STRATA_GPU_METAL) + if (tl_) { // (a later recording may take a dropped one's address) + std::lock_guard l(tl_->mu); + for (void* g : gone) tl_->kernels_of.erase(g); + } +#endif for (void* g : gone) { ck(cudaGraphExecDestroy((cudaGraphExec_t) g), "a step's recording"); step_used_.erase(g); @@ -6990,7 +7496,7 @@ void Engine::run(const int32_t* tokens, int n) { const auto replayed = [&](std::vector& made, size_t key, auto&& work) { if (made.size() <= key) made.resize(key + 1, nullptr); if (!made[key]) made[key] = record(work); - ck(cudaGraphLaunch((cudaGraphExec_t) made[key], cs(st_)), "layer graph"); + launch_graph(made[key], prof::kGraph, "layer graph"); }; if (replay) { // a pair a token: a window's tokens may go one by one, each from its own for (int t = 0; t < n; ++t) { @@ -7008,16 +7514,19 @@ void Engine::run(const int32_t* tokens, int n) { Layer& L = layers_[(size_t) il]; prefetch_layer(il, m); const size_t head = (size_t) head_key(il, m) * recs + rec; + pmark(prof::kAttention); if (replay && L.fixed) replayed(L.heads, head, [&] { layer_head(L, il, m); }); else layer_head(L, il, m); if (!L.moe || batched(L, m)) return; ck(cudaEventRecord((cudaEvent_t) ev_, cs(st_)), "router"); + pmark(prof::kDense); if (replay && shared_recorded()) replayed(L.shared, rec, [&] { moe_shared(L, il, m); }); else moe_shared(L, il, m); }; const auto tail = [&](int il, int m, size_t rec) { Layer& L = layers_[(size_t) il]; dbg("ffn", il, fo_, n_embd_); + pmark(prof::kNorms); if (replay && L.fixed) replayed(L.tail, (size_t) tail_key(il, m) * recs + rec, [&] { layer_tail(L, il, m); }); else layer_tail(L, il, m); }; @@ -7037,6 +7546,7 @@ void Engine::run(const int32_t* tokens, int n) { // A half's launches are the ones its tokens have in a call of their own, at their rows of the buffers // (shift_rows()), so each token comes out as it would alone. if (n > 1 && windowed_ && !card_routes() && halves_) { + prof_unsplit(); // two threads hand the stream the halves' launches: their families interleave const int first[3] = {0, (n + 1) / 2, n}; // half k is the tokens [first[k], first[k + 1]) const unsigned bits = snap_bits_; // the window's tokens that leave the recurrent state int at = 0; @@ -7130,6 +7640,10 @@ void Engine::run(const int32_t* tokens, int n) { const Layer& L = layers_[(size_t) il]; whole = L.fixed && (!L.moe || L.card == 1); } + // The profiler's split token (prof_split()): its launches one by one, layer by layer, as the first tokens' are + // before anything is recorded, so that its families have events between them (a recording has none). A block + // of guesses is recorded whole or not at all: it stays unsplit. + if (prof_split() && !block_pass_) whole = replay = false; // A block of guesses is recorded whole or not at all: a layer's own recordings are a window's, of other kernels. if (block_pass_ && !whole) replay = false; if (whole) { @@ -7150,10 +7664,13 @@ void Engine::run(const int32_t* tokens, int n) { whole_pdl_scope() = whole_pdl(); for (int done = 0; il < hi_ && done < count; il = next_layer(il), ++done) { Layer& L = layers_[(size_t) il]; + pmark(prof::kAttention); layer_head(L, il, n); if (!L.moe) continue; + pmark(prof::kDense); moe_shared(L, il, n); moe_card(L, il, n); + pmark(prof::kNorms); layer_tail(L, il, n); } }; @@ -7177,7 +7694,7 @@ void Engine::run(const int32_t* tokens, int n) { for (int c = 0;; ++c) { const auto it = passes_.find(part(c)); if (it == passes_.end()) break; - ck(cudaGraphLaunch((cudaGraphExec_t) it->second, cs(st_)), "layer graph"); + launch_graph(it->second, prof::kGraph, "layer graph"); ck(gpu::metal::submit(static_cast(st_)), "layer graph"); } runs_done(); @@ -7192,8 +7709,8 @@ void Engine::run(const int32_t* tokens, int n) { pass = record(layers(rest ? first : INT_MAX)); if (rest) *rest = record(layers(INT_MAX)); } - ck(cudaGraphLaunch((cudaGraphExec_t) pass, cs(st_)), "layer graph"); - if (rest) ck(cudaGraphLaunch((cudaGraphExec_t) *rest, cs(st_)), "layer graph"); + launch_graph(pass, prof::kGraph, "layer graph"); + if (rest) launch_graph(*rest, prof::kGraph, "layer graph"); runs_done(); if (bell_) bell_serve(); return; @@ -7243,6 +7760,7 @@ void Engine::step(const int* seqs, const int32_t* tokens, int n, const int32_t* if (guesses && !steps_guesses()) throw std::logic_error("step: guesses need --batch-mtp, a draft block and one card"); if (!step_seqs_.empty()) throw std::logic_error("step: the rows of the step before are not kept yet (keep_step())"); OnCard here(device_, split_); + const ProfCall prof_call(*this, n); // (rows fed: a step's guesses count as tokens) end_read(); const int home = bound_; const auto use = [&](int s) { hold(s); }; @@ -7298,7 +7816,7 @@ void Engine::step(const int* seqs, const int32_t* tokens, int n, const int32_t* const auto replayed = [&](std::vector& made, size_t key, auto&& work) { if (made.size() <= key) made.resize(key + 1, nullptr); if (!made[key]) made[key] = record(work); - ck(cudaGraphLaunch((cudaGraphExec_t) made[key], cs(st_)), "layer graph"); + launch_graph(made[key], prof::kGraph, "layer graph"); }; // A step of one row rings the doorbell as run() rings it for a token (bell_on(): card_moe() routes such a row on // the card for it): its misses go to this thread's workers from inside the launches, which bell_serve() answers @@ -7396,7 +7914,7 @@ void Engine::step(const int* seqs, const int32_t* tokens, int n, const int32_t* } else { void*& pass = step_passes_[wkey]; if (!pass) pass = record(whole_work); - ck(cudaGraphLaunch((cudaGraphExec_t) pass, cs(st_)), "layer graph"); + launch_graph(pass, prof::kGraph, "layer graph"); } for (int il = lo_; il < hi_; il = next_layer(il)) stats_.gpu_experts += layers_[(size_t) il].moe ? R * n_used_ : 0; @@ -7443,7 +7961,7 @@ void Engine::step(const int* seqs, const int32_t* tokens, int n, const int32_t* if (replay && L.fixed) { void*& made = L.rows_heads[hkey]; if (!made) made = record([&] { layer_head(L, il, m); }); - ck(cudaGraphLaunch((cudaGraphExec_t) made, cs(st_)), "layer graph"); + launch_graph(made, prof::kGraph, "layer graph"); } else { layer_head(L, il, m); } @@ -7533,7 +8051,7 @@ void Engine::step(const int* seqs, const int32_t* tokens, int n, const int32_t* } else if (replay && L.fixed) { void*& made = L.rows_heads[key]; if (!made) made = record([&] { layer_head(L, il, R); }); - ck(cudaGraphLaunch((cudaGraphExec_t) made, cs(st_)), "layer graph"); + launch_graph(made, prof::kGraph, "layer graph"); } else { layer_head(L, il, R); } @@ -7838,6 +8356,7 @@ void Engine::carry_in(int64_t from, int n) { void Engine::eval(const int32_t* tokens, int n, bool want_logits) { OnCard here(device_, split_); + const ProfCall prof_call(*this, n); run(tokens, n); if (next_) { hand_on(pos_, n, pass_rows(n)); @@ -7859,6 +8378,7 @@ void Engine::eval(const int32_t* tokens, int n, bool want_logits) { if (!want_logits) return; lin(output_, h + (size_t) (m - 1) * n_embd_, logits_, 1); finish_logits(logits_, 1); + pmark(prof::kCopyD2H); if (picks) { // the lowest id of the largest score, as most_likely() picks it likeliest(logits_, n_vocab_, d_picks_, st_); ck(cudaMemcpyAsync(h_picks_, d_picks_, sizeof(Likeliest), cudaMemcpyDeviceToHost, cs(st_)), "logits"); @@ -7868,10 +8388,11 @@ void Engine::eval(const int32_t* tokens, int n, bool want_logits) { cs(st_)), "logits"); }; + pmark(prof::kDense); if (replay) { void*& graph = picks ? tail_picks_ : tail_; if (!graph) graph = record(tail); - ck(cudaGraphLaunch((cudaGraphExec_t) graph, cs(st_)), "logits graph"); + launch_graph(graph, prof::kDense, "logits graph"); } else { tail(); } @@ -7886,15 +8407,18 @@ void Engine::eval(const int32_t* tokens, int n, bool want_logits) { // A layer for n tokens, as run() hands it to the card when nothing is replayed or printed. void Engine::layer(int il, int n) { Layer& L = layers_[(size_t) il]; + pmark(prof::kAttention); layer_head(L, il, n); if (!L.moe) return; if (batched(L, n)) { moe_rows(L, il, n); } else { ck(cudaEventRecord((cudaEvent_t) ev_, cs(st_)), "router"); + pmark(prof::kDense); moe_shared(L, il, n); if (moe(L, il, n)) moe_add(n); } + pmark(prof::kNorms); layer_tail(L, il, n); } @@ -7914,6 +8438,7 @@ void Engine::layer_pack(int il, const Pack& p, float* rows) { pos_ = call.pos - by; shift_rows(by); tok_ = call.tok; + pmark(prof::kAttention); layer_head(L, il, call.m); tok_ = nullptr; shift_rows(-by); @@ -7927,9 +8452,11 @@ void Engine::layer_pack(int il, const Pack& p, float* rows) { moe_rows(L, il, p.m); } else { ck(cudaEventRecord((cudaEvent_t) ev_, cs(st_)), "router"); + pmark(prof::kDense); moe_shared(L, il, p.m); if (moe(L, il, p.m)) moe_add(p.m); } + pmark(prof::kNorms); layer_tail(L, il, p.m); } tok_ = last.tok; @@ -7964,6 +8491,11 @@ bool Engine::read(const int32_t* tokens, int n, const Mark* marks, int n_marks, all += co[j].n; } if (n_co > 0 && !co_reads()) throw std::logic_error("read: co-reads are one card's, where a read is several calls"); + OnCard prof_card(device_, split_); // the profiler's events go on this card's stream + const ProfCall prof_call(*this, n); + // the host's setup before the read's first launch (the attention caches' growth, the prompt's buffers and staging + // taken back from the expert cache): the stream idles meanwhile, so it is not the copies' time + pmark(prof::kHostSetup); // (a read of no tokens of its own takes co-reads: a request whose prompt the conversation holds but its last token) if (n < (n_co > 0 ? 0 : 1) || all > read_rows_) throw std::logic_error("read takes 1 to max_read() tokens, co-reads among them"); @@ -8056,6 +8588,7 @@ bool Engine::read(const int32_t* tokens, int n, const Mark* marks, int n_marks, if (n_co == 0 && (n_calls == 1 || !mmq_ || all_cached() || all < opt_.stage_ahead || !(reads_by_layer() || groups))) { turn = share_to(n_layer_); // eval() takes the calls through the cards after this one + pmark(prof::kCopyH2D); // the first call's embeddings, as a call's own start marks them // On several cards the next one takes a call on a thread of its own, while this one runs the call after // it. Each card runs the calls as eval() does, in the same order. Behind behind; @@ -8125,7 +8658,10 @@ bool Engine::read(const int32_t* tokens, int n, const Mark* marks, int n_marks, ck(cudaStreamSynchronize(cs(st_)), "read"); lock_settle(); if (n_swap_ > 0) follow(0); - if (groups) return read_groups(marks, n_marks, turn, n); + if (groups) { + pmark(prof::kCopyH2D); + return read_groups(marks, n_marks, turn, n); + } const size_t e_row = (size_t) n_embd_, r_row = (size_t) streams() * e_row, r_bytes = r_row * sizeof(float); const size_t part = (size_t) std::max(streams(), draft_ ? 3 : 1) * rows_ * e_row; // a call's rows of r_ float* const r0 = r_; @@ -8137,6 +8673,7 @@ bool Engine::read(const int32_t* tokens, int n, const Mark* marks, int n_marks, h_res_rows_ = std::min(read_rows_, (all + 4095) / 4096 * 4096); h_res_ = (float*) hmalloc((size_t) h_res_rows_ * r_bytes, "pinned memory"); } + pmark(prof::kCopyH2D); const auto home = [&](int p) { return h_res_ + (size_t) packs_[(size_t) p].at * r_row; }; const auto half = [&](int p) { return r0 + (size_t) (host ? p % 2 : p) * part; }; // pack p's rows back into its half of r_, behind whatever the stream has there of the half's last pack @@ -8433,6 +8970,7 @@ unsigned Engine::snap_tokens(int t) const { void Engine::window(const int32_t* tokens, int t) { if (t < 1 || t > opt_.window) throw std::logic_error("a window takes 1 to max_window() tokens"); OnCard here(device_, split_); + const ProfCall prof_call(*this, t); end_read(); // the two ways are a choice only with experts on the CPU; a call that records launches says nothing of them const bool timed = t > 1 && !card_routes(); @@ -8510,6 +9048,8 @@ void Engine::took_way(int t, double ms) { void Engine::keep(int n) { if (n < 1 || n > win_) throw std::logic_error("keep takes 1 to the window's tokens"); OnCard here(device_, split_); + prof_kept(n); // the window's call counts the tokens kept, not the guesses fed with them + const ProfCall prof_call(*this, 0); // The next card reads the window's rows again for the tokens it puts through its layers again: a right token's // row is the same, whatever came after it. if (n < win_) { diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index ab0e27454..2ca2112d3 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -15,6 +15,7 @@ #pragma once #include "cpu_experts.hpp" +#include "profile.hpp" #include "strata/poly/kernels.hpp" #include @@ -218,6 +219,9 @@ struct Stats { int64_t tail_experts = 0; ///< a token's experts left out by Options::tail_skip int64_t ahead_sent = 0, ahead_used = 0; ///< experts uploaded ahead of their layer (vram_ahead()), and run so double cpu_ms = 0, route_wait_ms = 0; + int64_t route_waits = 0; ///< the host's waits for a router's scores (a round trip each) + /// a prompt batch's experts, each counted once a layer visit: in VRAM already, copied in for the batch, on the CPU + int64_t batch_hit_experts = 0, batch_staged_experts = 0, batch_cpu_experts = 0; }; /// The most likely token of n logits: the first of the largest. @@ -274,6 +278,8 @@ class Engine { double numa_share() const { return node_share_; } int64_t pos() const { return pos_; } int64_t meta_u(const char* key, int64_t fallback) const; + /// A string of the metadata (general.architecture, general.name, ...); "" when the file has none. + std::string meta_s(const char* key) const; /// The mapped bytes of each of the model's files, the one with the metadata first; {nullptr, 0} for a file /// without tensors. std::vector> model_views() const; @@ -473,6 +479,23 @@ class Engine { /// Sequence `to` becomes what sequence `from` is: its position, state, rows and pictures, copied on the card. void copy_seq(int from, int to); + /// The event profiler (STRATA_PROFILE=1, --bench-report; profile.hpp says what it records): on from here, an + /// answer's tokens split one in `every`. Off (the default), the engine records nothing and launches as before. + void enable_profile(int every); + bool profiling() const { return tl_ != nullptr; } + /// The calls so far are a prompt's (prof::kPrompt) or an answer's (prof::kDecode); `request`: a new request + /// starts, so the time since the last call is not the stream's gap. + void prof_phase(int phase, bool request); + /// The figures so far, once the stream is done with the calls made (it waits for them); null when off. + const prof::Profile* profile(); + void profile_reset(); + /// The routed experts' shape, for the CPU probe of --bench-report: the first MoE layer's types and sizes. + struct ExpertShape { + int gu_type = -1, u_type = -1, d_type = -1, n_embd = 0, n_ff = 0, n_used = 0, n_expert = 0, n_moe = 0; + size_t gu_bytes = 0, u_bytes = 0, d_bytes = 0; ///< one expert's gate, up and down + }; + ExpertShape expert_shape() const; + protected: // ---- what an architecture supplies ---- /// The model's shape from its metadata: load_shape() for what every architecture has, then its own. @@ -974,6 +997,63 @@ class Engine { long long* at_ = nullptr; ///< on the card: {pos(), turn(pos())}, and the same for a window's later tokens long long* h_at_ = nullptr; ///< pinned bool recording_ = false; ///< a layer's launches are being recorded: positions are read from at_ + // ---- the event profiler (profile.hpp); tl_ null: off ---- + struct Timeline; + std::unique_ptr tl_; + /// From here the stream's work is family f (prof::Fam), in a call that is split. + void pmark(int f) { + if (tl_) pmark_on(f); + } + void pmark_on(int f); + /// A call into the engine starts (n tokens) and ends; calls inside calls count as the outer one. + void prof_begin(int n) { + if (tl_) prof_begin_on(n); + } + void prof_end() { + if (tl_) prof_end_on(); + } + void prof_begin_on(int n); + void prof_end_on(); + struct ProfCall { ///< prof_begin() and prof_end() around a call into the engine + Engine& e; + ProfCall(Engine& engine, int n) : e(engine) { e.prof_begin(n); } + ~ProfCall() { + try { + e.prof_end(); + } catch (...) { + } + } + }; + /// The call under way is split (its families are recorded), and a way to stop that (threads that share the stream). + bool prof_split() const; + void prof_unsplit(); + /// cudaGraphLaunch, with a mark of family `fam` before it in a split call. + void launch_graph(void* exec, int fam, const char* what); + /// A copy on another stream than st_ (the upload stream): its time and bytes, beside the work. + int pside_begin(void* stream); + void pside_end(int id, void* stream, double bytes); + /// Bytes of experts copied into VRAM in the stream in the call under way. + void prof_bytes(double bytes); + /// keep(): the window just called keeps n of the tokens it was fed. + void prof_kept(int n); + // the byte model (prof_bytes_of()) + std::vector dense_layer_b_, router_layer_b_; + double dense_other_b_ = 0, prof_dense_call_ = 0, prof_router_call_ = 0, prof_expert_b_ = 0; + int prof_visits_ = -1, prof_moe_visits_ = 0; + void note_dense(const std::string& name, size_t bytes); + /// The visits of a call and the bytes of each, once, between calls (enable_profile()): next_layer() moves a + /// looped architecture's pass, so it is never walked while a call is under way. + void prof_prepare(); + struct CallBytes { + double dense = 0, router = 0, kv = 0, gpu = 0, cpu = 0; + }; + CallBytes prof_bytes_of(int64_t pos, int n, const Stats& s0, const Stats& s1); + /// The attention caches' bytes a call of n tokens from pos reads (its keys and values), for the profiler's byte + /// model; 0 where the architecture does not say. + virtual double kv_read_bytes(int64_t pos, int n) { + (void) pos, (void) n; + return 0; + } bool recorded_ = false; ///< took_record() // geometry diff --git a/engine/src/poly/inkling2.cpp b/engine/src/poly/inkling2.cpp index c20d37404..ce3b73d8a 100644 --- a/engine/src/poly/inkling2.cpp +++ b/engine/src/poly/inkling2.cpp @@ -1208,6 +1208,7 @@ void Inkling2::layer_head(Layer& L, int il, int n) { #else const bool rows_launch = per_row && n > 1; #endif + pmark(prof::kNorms); // the profiler's families (profile.hpp): the mixes, controls and norms first // the tokens' embeddings, normed (a picture's rows are not: whole(); step()'s rows have none) if (il == 0 && (per_row || !image_at(pos_))) { @@ -1291,6 +1292,7 @@ void Inkling2::layer_head(Layer& L, int il, int n) { // the stream that it joins after them. gemv_bf16() is lin()'s launch for them. Not on Metal: a recording there // is the capturing stream's alone, so the branch's launches ran once as it was made and never in its replays (the // sink and the taps stayed the recording token's), and each event committed a command buffer. + pmark(prof::kDense); const auto plain_bf16 = [](const Dev& d) { return !d.p || (d.type == kTypeBF16 && d.scale == 1.0f); }; #if defined(STRATA_GPU_METAL) constexpr bool kBranch = false; @@ -1328,6 +1330,7 @@ void Inkling2::layer_head(Layer& L, int il, int n) { } const float alpha = B.swa ? 0.f : log_alpha_; const long long* at = recording_ ? at_ : nullptr; // a recorded launch: the tokens' positions from what at_ holds + pmark(prof::kKvStore); // one launch for all of it, the same bits (step()'s rows: a launch a row; load_geometry() takes no other heads) if ((n == 1 || per_row) && head_dim_ <= 128 && n_rel_ <= 128) { for (int i = 0; i < each; ++i) { @@ -1423,6 +1426,7 @@ void Inkling2::layer_head(Layer& L, int il, int n) { c.kvq8 = kvq8_; ink_clips(c, st_); } + pmark(prof::kAttention); InkAttn a; a.q = q_; a.r = rr_; @@ -1520,7 +1524,9 @@ void Inkling2::layer_head(Layer& L, int il, int n) { if (n == 1) a.q8 = xqo_; // and the output quantized for wo ink_attend(a, st_); } + pmark(prof::kDense); lin(B.wo, att_, aoraw_, n, n == 1 && n < kStageRows ? xqo_ : nullptr); + pmark(prof::kNorms); // the first layer of a block starts a new stream from the attention's output; the one it had joins the mixes if (n == 1 || per_row) { // the convolution and the stream's update in one launch (a launch a row of step()'s) const int mode = il % blk_ != 0 ? 0 : il == core_start_ && looped ? 2 : 1; @@ -1587,6 +1593,7 @@ void Inkling2::layer_tail(Layer&, int il, int n) { } void Inkling2::tail_rows(int il, int n) { + pmark(prof::kNorms); const Slot& S = slots_[(size_t) slot_of(il, pass_of(il))]; if (n == 1 && std::exchange(moe_left_, false)) { // moe_card() left the experts' sum here ink_moe_conv_add(d_, d_wts_, moe_left_scale_, d_ids_, n_used_, fo_, past_f(run_slot(il, 0)), @@ -1636,6 +1643,21 @@ int Inkling2::next_layer(int il) { } // A layer's recordings: one a pass of the core, and for a full layer one a size of the rows it reads. +// The profiler's byte model: each visit reads its own slot's keys and values, every row so far on a full layer and the +// window's on a window layer, for each of the call's tokens (counted at the call's middle row). +double Inkling2::kv_read_bytes(int64_t pos, int n) { + if (prof_full_visits_ < 0) { // (Engine::prof_prepare(), between calls: next_layer() moves pass_) + prof_full_visits_ = 0; + for (int il = lo_; il < hi_; il = next_layer(il)) ++(blocks_[(size_t) il].swa ? prof_swa_visits_ : prof_full_visits_); + } + if (n <= 0) return 0; + const double rows = (double) pos + 0.5 * (double) n; + const double win = std::min(rows, (double) std::max(window_, 1)); + // a token alone reads every row; a batch's attention reads the rows once a tile of queries (64), not a query + const double reads = n == 1 ? 1.0 : std::ceil((double) n / 64.0); + return reads * 2.0 * (double) kv_row() * (prof_full_visits_ * rows + prof_swa_visits_ * win); +} + int Inkling2::head_key(int il, int n) const { return pass_of(il) * 32 + (blocks_[(size_t) il].swa ? 0 : room_key(n)); } diff --git a/engine/src/poly/inkling2.hpp b/engine/src/poly/inkling2.hpp index 9b3b44293..111a76422 100644 --- a/engine/src/poly/inkling2.hpp +++ b/engine/src/poly/inkling2.hpp @@ -193,6 +193,8 @@ class Inkling2 final : public Engine { bool kv8_ = false; ///< the attention caches in FP8 E4M3 (load_geometry()); else fp16 bool kvq8_ = false; ///< the attention caches in Q8_0 (load_geometry(), --kv q8_0) bool int8_dot_ = false; ///< STRATA_KV_INT8: long rows' scores by __dp4a on the Q8_0 caches (InkAttn::int8_dot) + double kv_read_bytes(int64_t pos, int n) override; + int prof_full_visits_ = -1, prof_swa_visits_ = 0; size_t kv_row() const { return kv8_ ? ink_kv8_row(n_kv_, head_dim_) : kvq8_ ? ink_kvq8_row(n_kv_, head_dim_) diff --git a/engine/src/poly/launch_count.cpp b/engine/src/poly/launch_count.cpp new file mode 100644 index 000000000..2942098bd --- /dev/null +++ b/engine/src/poly/launch_count.cpp @@ -0,0 +1,37 @@ +// src/poly/launch_count.cpp - the profiler's launch counter (profile.hpp launch_count()): the runtime's kernel launch +// calls wrapped at link time (-Wl,--wrap=..., Linux only; engine/cmake/strata_poly.cmake), so every launch the +// engine's own code makes adds one while the profiler is on. With the profiler off the wrapper only reads a flag and +// calls the runtime. The calls a BLAS library makes inside itself do not come through here. +#include "profile.hpp" + +#include + +namespace { +const bool linked = (strata::poly::prof::launch_wrapper_linked().store(true), true); + +inline void count() { + if (strata::poly::prof::launch_counting().load(std::memory_order_relaxed)) + strata::poly::prof::launch_count().fetch_add(1, std::memory_order_relaxed); +} +} // namespace + +extern "C" { +#if defined(STRATA_USE_HIP) +hipError_t __real_hipLaunchKernel(const void* f, dim3 grid, dim3 block, void** args, size_t shared, hipStream_t s); +hipError_t __wrap_hipLaunchKernel(const void* f, dim3 grid, dim3 block, void** args, size_t shared, hipStream_t s) { + count(); + return __real_hipLaunchKernel(f, grid, block, args, shared, s); +} +#else +cudaError_t __real_cudaLaunchKernel(const void* f, dim3 grid, dim3 block, void** args, size_t shared, cudaStream_t s); +cudaError_t __wrap_cudaLaunchKernel(const void* f, dim3 grid, dim3 block, void** args, size_t shared, cudaStream_t s) { + count(); + return __real_cudaLaunchKernel(f, grid, block, args, shared, s); +} +cudaError_t __real_cudaLaunchKernelExC(const cudaLaunchConfig_t* c, const void* f, void** args); +cudaError_t __wrap_cudaLaunchKernelExC(const cudaLaunchConfig_t* c, const void* f, void** args) { + count(); + return __real_cudaLaunchKernelExC(c, f, args); +} +#endif +} diff --git a/engine/src/poly/main.cpp b/engine/src/poly/main.cpp index e7eff913c..b1d4f7750 100644 --- a/engine/src/poly/main.cpp +++ b/engine/src/poly/main.cpp @@ -7,6 +7,10 @@ // STOP and QUIT in, and RESUME, PP, T, DONE and ERR out. #include "conversations.hpp" #include "engine.hpp" +#if !defined(STRATA_GPU_METAL) +#include "bench_report.hpp" +#include "strata/quant/types.hpp" +#endif #include "guesses.hpp" #include "strata/core/conversation_file.hpp" #include "strata/core/conversation_memory.hpp" @@ -46,6 +50,9 @@ #include #undef far // a word of this file's #endif +#if !defined(_WIN32) +extern char** environ; +#endif #ifndef STRATA_VERSION #define STRATA_VERSION "dev" @@ -387,6 +394,7 @@ struct Session { std::string pinned; // --pinned-session: the file serve() pins before its first request std::vector co_read; // BCO: prompts for generate()'s first read() to take along bool co_done = false; // and that read took them + std::function after_request; // STRATA_PROFILE=1: the profile written after each request Session(Engine& e, std::vector eos_ids, const CacheFlags& f, int lookup) : engine(e), eos(std::move(eos_ids)), flags(f), kept(e, with_floor(f)), @@ -423,6 +431,7 @@ struct Session { OnProgress on_progress, const std::function* between = nullptr) { Result r; const int64_t n = (int64_t) ids.size(); + engine.prof_phase(strata::poly::prof::kPrompt, true); Clock::time_point t0 = Clock::now(), shown = t0; // bringing a parked conversation back is prompt time engine.images(pictures.at.data(), (int) pictures.at.size()); r.resume = kept.resume(ids); @@ -522,6 +531,7 @@ struct Session { r.prompt_ms = ms_since(t0); if (std::strcmp(r.finish, "cancel") == 0) return r; + engine.prof_phase(strata::poly::prof::kDecode, false); t0 = Clock::now(); std::vector history = kept.seq(); std::replace_if(history.begin(), history.end(), [](int32_t t) { return t < 0; }, pad); @@ -1383,6 +1393,7 @@ int serve(Session& ss) { r.prompt_ms, r.decode_ms, r.finish, (long long) r.guessed_right, (long long) r.guessed, (long long) r.resume, hits, hits + misses, (long long) r.read); std::fflush(stdout); + if (ss.after_request) ss.after_request(); engine.trim(); ss.kept.release(); if (admit >= 0) { @@ -1496,6 +1507,7 @@ int once(Session& ss, const std::vector& ids, const Pictures& pictures, st.route_wait_ms / (double) std::max(st.tokens, 1), (long long) st.swapped_experts, (long long) st.ahead_sent, (long long) st.ahead_used, (long long) st.tail_experts, (long long) r.guessed_right, (long long) r.guessed); + if (ss.after_request) ss.after_request(); return 0; } @@ -1628,6 +1640,227 @@ int check_batch(Engine& engine, const std::vector& ids, int k, long lon return rc; } +#if !defined(STRATA_GPU_METAL) +namespace bench = strata::poly::bench; +namespace prof = strata::poly::prof; + +// The report's header: the card, the CPU, the model and the settings (no probes), for --bench-report and the +// STRATA_PROFILE=1 session file. +bench::Report report_base(Engine& engine, const Options& o, const std::vector& args, + const std::vector>& env) { + bench::Report r; + r.engine_version = STRATA_VERSION; + r.commit = bench::build_commit(); + r.settings = bench::clean_args(args); + r.env = env; + r.gpu = bench::gpu_info(0); + r.host = bench::host_info(); + r.host.engine_threads = engine.threads(); + const Engine::ExpertShape x = engine.expert_shape(); + std::string name = engine.meta_s("general.name"); + if (name.empty()) name = std::filesystem::path(o.model).stem().string(); + r.model.name = name; + r.model.arch = engine.meta_s("general.architecture"); + const auto type_name = [](int t) { + const strata::quant::TypeInfo* ti = t >= 0 ? strata::quant::type_info(t) : nullptr; + return std::string(ti ? ti->name : "?"); + }; + r.model.file_type = x.gu_type < 0 ? "none" : type_name(x.gu_type) + (x.u_type != x.gu_type ? "/" + type_name(x.u_type) : "") + + "/" + type_name(x.d_type); + double bytes = 0; + for (const auto& v : engine.model_views()) bytes += (double) v.second; + r.model.size_gib = bytes / (double) (1ull << 30); + r.model.n_expert = x.n_expert; + r.model.n_used = x.n_used; + r.model.n_moe = x.n_moe; + r.model.expert_mib = (double) (x.gu_bytes + x.u_bytes + x.d_bytes) / 1048576.0; + r.cached_experts = engine.cached_experts(); + r.total_experts = engine.total_experts(); + r.cached_gib = engine.cached_gib(); + r.max_context = engine.max_context(); + return r; +} + +// An environment variable's text, "" when it is not set. +std::string env_text(const char* name) { + const char* v = std::getenv(name); + return v ? std::string(v) : std::string(); +} + +// The prompts: random tokens from a fixed seed, among the vocabulary's first 32,000 past its first 1,000 (where the +// special tokens of most vocabularies are), never an end-of-reply token. The same on every PC for the same file. +std::vector synthetic_tokens(size_t n, uint64_t seed, int n_vocab, const std::vector& eos) { + int lo = std::min(1000, n_vocab / 10), hi = std::min(n_vocab, 32000); + if (hi - lo < 100) lo = 0, hi = n_vocab; + std::vector out; + out.reserve(n); + uint64_t x = seed * 0x9E3779B97F4A7C15ull + 1; + while (out.size() < n) { + uint64_t z = (x += 0x9E3779B97F4A7C15ull); // splitmix64 + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + z ^= z >> 31; + const int32_t t = lo + (int32_t) (z % (uint64_t) (hi - lo)); + if (std::find(eos.begin(), eos.end(), t) == eos.end()) out.push_back(t); + } + return out; +} + +// --bench-report: probes (before the load, in main()), a warm-up, the quick tier and, with --long, one long +// conversation read in chunks with an answer at each checkpoint. Greedy; no answer stops early. +int bench_report(Session& ss, bench::Report& rep, bool long_tier, const std::string& out, + const Clock::time_point started, const std::vector& text) { + Engine& engine = ss.engine; + const std::vector eos = ss.eos; + ss.eos.clear(); // every answer as long as asked + Sampling greedy; + greedy.temperature = 0.f; + std::atomic stop{false}; + const int ctx = engine.max_context(); + std::vector said; + const int most = ss.most; + const bool look = ss.look; + // `single`: one token a call (no guesses), whatever the settings: what the card, the link and the CPU do for a + // token, apart from how often the guesses are right + const auto one = [&](const std::string& name, const std::vector& ids, long long max_new, bool single) { + std::fprintf(stderr, "strata-poly: bench %s: %zu prompt tokens, %lld to write\n", name.c_str(), ids.size(), max_new); + engine.profile_reset(); + said.clear(); + ss.most = single ? 1 : most; + ss.look = single ? false : look; + const Session::Result r = ss.generate(ids, Pictures{}, -1, -1, max_new, greedy, stop, + [&](int32_t t) { said.push_back(t); }, + [](int64_t, int64_t, double, bool) {}); + ss.most = most; + ss.look = look; + bench::Run run; + run.name = name; + run.single = single; + run.prompt_tokens = (int64_t) ids.size(); + run.reused = r.resume; + run.read = r.read; + run.prompt_ms = r.prompt_ms; + run.produced = r.produced; + run.decode_ms = r.decode_ms; + run.guessed = r.guessed; + run.guessed_right = r.guessed_right; + run.context_end = engine.pos(); + if (const prof::Profile* p = engine.profile()) run.profile = *p; + std::fprintf(stderr, "strata-poly: bench %s: %lld prompt tokens read at %.0f tok/s (%lld from the conversation), " + "%lld generated at %.1f tok/s\n", name.c_str(), (long long) run.read, run.prompt_tok_s(), + (long long) run.reused, (long long) run.produced, run.decode_tok_s()); + return run; + }; + const int vocab = engine.n_vocab(); + // the prompts: pieces of --bench-text one after the other (no two start alike, so none goes on from another), or + // random tokens where none was given + size_t text_at = 0; + int seed = 10; + const auto take = [&](size_t n) { + if (text.empty()) return synthetic_tokens(n, (uint64_t) seed++, vocab, eos); + if (text_at + n > text.size()) text_at = 0; + std::vector v(text.begin() + (ptrdiff_t) text_at, text.begin() + (ptrdiff_t) std::min(text.size(), text_at + n)); + text_at += n; + return v; + }; + Clock::time_point t = Clock::now(); + one("warm-up", take(302), 32, false); + rep.warm_s = ms_since(t) / 1000.0; + t = Clock::now(); + const long long decode = 128; + for (const int n : {302, 2048, 8192}) { + if (n + 2 * decode + 8 > ctx) { + std::fprintf(stderr, "strata-poly: bench: the %d-token prompt does not fit the context (%d): left out\n", n, ctx); + continue; + } + const std::vector ids = take((size_t) n); + rep.runs.push_back(one("prompt " + std::to_string(n), ids, decode, false)); + // the same prompt again (the conversation holds it: one token is read) and its answer a token a call + rep.runs.push_back(one("prompt " + std::to_string(n) + ", one token a call", ids, decode, true)); + } + rep.quick_s = ms_since(t) / 1000.0; + std::string base = out; + if (base.size() > 5 && base.compare(base.size() - 5, 5, ".json") == 0) base.resize(base.size() - 5); + const auto write = [&] { + rep.total_s = ms_since(started) / 1000.0; + const std::string json = bench::to_json(rep), md = bench::to_markdown(rep); + for (const auto& [path, body] : {std::pair{base + ".json", &json}, + std::pair{base + ".md", &md}}) { + std::ofstream f(path, std::ios::binary); + f << *body; + if (!f) { + std::fprintf(stderr, "strata-poly: bench: cannot write %s\n", path.c_str()); + return false; + } + } + return true; + }; + // the quick tier's report first: a long tier that runs out of memory or is stopped leaves it written + if (!write()) return 1; + if (long_tier) { + t = Clock::now(); + std::vector points; + const int cap = ctx - 256; + for (const int c : {8192, 32768, 65536, 131072}) + if (c <= cap) points.push_back(c); + if (cap > 8192 && (points.empty() || cap > points.back() + 4096) && cap <= 131072) points.push_back(cap); + // one conversation: each checkpoint's prompt is the one before, its answer, and more of the same random text + // (the text from its start again where the quick tier's pieces were: other requests, the same text) + std::vector conv; + const std::vector more_text = + text.empty() ? synthetic_tokens(points.empty() ? 0 : (size_t) points.back(), 99, vocab, eos) : text; + size_t used = text.empty() ? 0 : std::min(text_at, more_text.size()); + for (const int c : points) { + const size_t more = (size_t) c > conv.size() ? (size_t) c - conv.size() : 0; + if (used + more > more_text.size()) used = 0; + conv.insert(conv.end(), more_text.begin() + (ptrdiff_t) used, + more_text.begin() + (ptrdiff_t) std::min(more_text.size(), used + more)); + used = std::min(more_text.size(), used + more); + // the answer at each checkpoint a token a call: how decode slows with the context, guesses aside + try { + rep.long_points.push_back(one("long " + std::to_string(c / 1024) + "K", conv, 64, true)); + } catch (const std::exception& e) { // (out of VRAM at a long context, say): the points so far stay + rep.long_error = "stopped at " + std::to_string(c / 1024) + "K: " + e.what(); + std::fprintf(stderr, "strata-poly: bench: the long tier %s\n", rep.long_error.c_str()); + break; + } + conv.insert(conv.end(), said.begin(), said.end()); + rep.long_s = ms_since(t) / 1000.0; + if (!write()) return 1; + } + rep.long_s = ms_since(t) / 1000.0; + } + ss.eos = eos; + if (!write()) return 1; + std::fprintf(stderr, "strata-poly: bench report written: %s.json and %s.md (%.0f s); attach both to a " + "\"[Benchmark] bench report\" issue\n", base.c_str(), base.c_str(), rep.total_s); + return 0; +} + +// STRATA_PROFILE=1 in normal use: after every request the session's profile so far goes to a file +// (STRATA_PROFILE_OUT, default strata-profile.json in the working folder), and a line to the log. +void write_session_profile(Engine& engine, const bench::Report& base, const std::string& path) { + const prof::Profile* p = engine.profile(); + if (!p) return; + const prof::Acc& a = p->all[prof::kPrompt]; + const prof::Acc& d = p->all[prof::kDecode]; + const prof::Acc& ds = p->split[prof::kDecode]; + const prof::Acc& as = p->split[prof::kPrompt]; + const auto sh = [](const prof::Acc& x, int f) { return x.timeline_ms() > 0 ? 100.0 * x.fam_ms[f] / x.timeline_ms() : 0.0; }; + std::fprintf(stderr, "strata-poly: profile: prompt %lld tokens %.0f tok/s (uploads %.0f%%, CPU experts %.0f%%, " + "host gaps %.0f%%); decode %lld tokens %.1f tok/s (CPU experts %.0f%%, uploads %.0f%%, host " + "gaps %.0f%%, GPU work %.0f%%)\n", + (long long) a.tokens, a.wall_ms > 0 ? 1000.0 * a.tokens / a.wall_ms : 0.0, sh(as, prof::kWaitUpload), + sh(as, prof::kWaitCpu), sh(as, prof::kHostGap), (long long) d.tokens, + d.wall_ms > 0 ? 1000.0 * d.tokens / d.wall_ms : 0.0, sh(ds, prof::kWaitCpu), sh(ds, prof::kWaitUpload), + sh(ds, prof::kHostGap), + 100.0 - sh(ds, prof::kWaitCpu) - sh(ds, prof::kWaitUpload) - sh(ds, prof::kHostGap)); + std::ofstream f(path, std::ios::binary); + f << bench::session_json(base, *p); + if (!f) std::fprintf(stderr, "strata-poly: profile: cannot write %s\n", path.c_str()); +} +#endif + void usage() { #if defined(STRATA_GPU_METAL) std::fprintf(stderr, "Metal defaults: optimized expert overlap and compact MMQ (disable: --no-metal-optimize), " @@ -1737,6 +1970,16 @@ void usage() { " --check-stagger with --check-batch: prompts of different lengths (the first n >> 3 (K-1-j)\n" " tokens), read while the others write, and answers of different lengths\n" " --eos-ids ID,ID,... tokens that end a reply (default: the GGUF's eos, eot and eom)\n" + " --bench-report FILE in place of --serve or --tokens: probe the card, the PCIe link, the RAM and the\n" + " CPU experts' kernel, then read prompts of 302, 2,048 and 8,192 tokens of\n" + " --bench-text (random tokens without it)\n" + " and answer 128 tokens after each, greedy, with the other options as given;\n" + " writes FILE.json and FILE.md with the speeds, the event profile and what\n" + " they say against the probes, and nothing that names the PC or its user\n" + " --long with --bench-report: then one conversation read in chunks to 8K, 32K, 64K\n" + " and 128K tokens (as far as --max-context goes), 64 answered at each\n" + " --bench-text IDS[@NAME] with --bench-report: the prompts are pieces of this file of token ids (the\n" + " text polystrata.py bench-report makes and tokenizes), not random tokens\n" " --temperature F --top-k N --top-p F --min-p F --seed N sampling for --tokens (default greedy)\n" " --images FILE with --tokens: the prompt's pictures, as strata-vision writes them\n" " --image-pad ID the token whose runs in --tokens are the pictures' places, a token a row\n" @@ -1770,6 +2013,10 @@ void usage() { " comes a few at a time; the weights stay the router's own: fewer\n" " experts on the CPU, and the answers move (default 0 = off)\n" "environment: STRATA_ROUTE_TAIL_SKIP=N in place of --tail-skip (0 turns it off)\n" + "environment: STRATA_PROFILE=1 the event profiler: after every request the GPU's time by kernel\n" + " family and its waits, prompt and decode apart and by context, go to\n" + " STRATA_PROFILE_OUT (default strata-profile.json) and a line to the log;\n" + " STRATA_PROFILE_EVERY=N splits one decode token in N (default 16)\n" "environment: STRATA_FREEZE_EXPERTS=1 hold the split of the routed experts between the card\n" " and the CPU still, so the same request gives the same greedy answer\n" " bit for bit; with guesses on, add --window 1 for a repeat everywhere\n"); @@ -1811,6 +2058,16 @@ void on_terminate() { int main(int argc, char** argv) { std::set_terminate(on_terminate); no_power_throttling(); + const Clock::time_point started = Clock::now(); +#if !defined(STRATA_GPU_METAL) + // for --bench-report and STRATA_PROFILE's file: the settings as given, before this process sets any of its own +#if defined(_WIN32) + const auto env_given = strata::poly::bench::clean_env(_environ); +#else + const auto env_given = strata::poly::bench::clean_env(environ); +#endif + const std::vector args_given(argv + 1, argv + argc); +#endif #if !defined(STRATA_GPU_METAL) && !defined(STRATA_USE_HIP) // The cached experts' warp kernel and 32 of them a launch (native_mmvq_slots_wide()), the HIP build's default, // here too unless STRATA_SLOTS_WARP says otherwise: the same bits, and on lab-pro6000 (RTX PRO 6000) Qwen3.6 @@ -1830,7 +2087,9 @@ int main(int argc, char** argv) { long long max_new = 32; int top_probs = 0, lookup = 3, image_pad = -1, check = 0; bool stagger = false; // --check-stagger - std::string images, pinned; + std::string images, pinned, bench_out, bench_text_name; + bool bench_long = false; + std::vector bench_text; std::vector ids, eos, follow; for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; @@ -1908,6 +2167,25 @@ int main(int argc, char** argv) { else if (a == "--batch-mtp") o.batch_mtp = true; else if (a == "--check-batch") check = std::atoi(val()); else if (a == "--check-stagger") stagger = true; + else if (a == "--bench-report") bench_out = val(); + else if (a == "--long") bench_long = true; + else if (a == "--bench-text") { // IDS@NAME: a file of token ids, and the text's name for the report + std::string v = val(); + const size_t at = v.rfind('@'); + bench_text_name = at == std::string::npos ? "a text given as token ids" : v.substr(at + 1); + if (at != std::string::npos) v.resize(at); + std::ifstream f(v, std::ios::binary); + std::string ids_s((std::istreambuf_iterator(f)), std::istreambuf_iterator()); + while (!ids_s.empty() && (ids_s.back() == '\n' || ids_s.back() == '\r' || ids_s.back() == ' ')) ids_s.pop_back(); + if (!f.good() && ids_s.empty()) { + std::fprintf(stderr, "strata-poly: --bench-text: cannot read %s\n", v.c_str()); + return 2; + } + if (!parse_ids(ids_s.c_str(), bench_text)) { + std::fprintf(stderr, "strata-poly: --bench-text takes a file of token ids separated by commas\n"); + return 2; + } + } else if (a == "--draft-vocab") o.draft_vocab = std::atoi(val()); else if (a == "--prompt-batch") o.prompt_batch = std::atoi(val()); else if (a == "--stage-mib") o.stage_mib = std::atoi(val()); @@ -1952,10 +2230,38 @@ int main(int argc, char** argv) { return 2; } } - if (o.model.empty() || (!want_serve && ids.empty()) || max_new < 1) { + if (o.model.empty() || (!want_serve && ids.empty() && bench_out.empty()) || max_new < 1) { usage(); return 2; } + if (!bench_out.empty() && (want_serve || !ids.empty() || check > 0)) { + std::fprintf(stderr, "strata-poly: --bench-report runs on its own: not with --serve, --tokens or --check-batch\n"); + return 2; + } + if (bench_long && bench_out.empty()) { + std::fprintf(stderr, "strata-poly: --long goes with --bench-report\n"); + return 2; + } +#if defined(STRATA_GPU_METAL) + if (!bench_out.empty()) { + std::fprintf(stderr, "strata-poly: --bench-report is not built for Metal\n"); + return 2; + } +#else + // the probes, before the model takes the card's memory and the RAM's bandwidth + strata::poly::bench::Probes probes; + if (!bench_out.empty()) { + std::fprintf(stderr, "strata-poly: bench: probing the hardware (a few seconds)\n"); + strata::poly::bench::probe_hardware(probes, 0, [](const char* what) { + std::fprintf(stderr, "strata-poly: bench: %s\n", what); + }); + strata::poly::bench::probe_kernels(probes, 0); + std::fprintf(stderr, "strata-poly: bench: probe kernels done: launch %.1f us, a replayed node %.1f us, read %.0f GB/s, " + "small kernel %.1f us (replayed %.1f, card-wide %.1f), round trip %.1f us, copy+wait %.1f us, fp32 %.0f GFLOP/s\n", + probes.launch_us, probes.graph_node_us, probes.read_gbs, probes.small_us, probes.small_node_us, + probes.wide_node_us, probes.sync_us, probes.copy_sync_us, probes.fma_gflops); + } +#endif if (o.batch < 0 || o.batch > 16 || check < 0 || check > o.batch || (check > 0 && (int) ids.size() <= check)) { std::fprintf(stderr, "strata-poly: --batch takes 0 to 16, and --check-batch at most --batch prompts, each " "with tokens left of --tokens\n"); @@ -1996,6 +2302,7 @@ int main(int argc, char** argv) { const Clock::time_point t0 = Clock::now(); loaded = Engine::open(o); Engine& engine = *loaded; + [[maybe_unused]] const double load_s = ms_since(t0) / 1000.0; std::fprintf(stderr, "strata-poly: loaded in %.1f s; %d of %d routed experts in VRAM (%.1f GiB), %d CPU threads\n", ms_since(t0) / 1000.0, engine.cached_experts(), engine.total_experts(), engine.cached_gib(), engine.threads()); @@ -2052,6 +2359,45 @@ int main(int argc, char** argv) { Session ss(engine, eos, cache, lookup); ss.pinned = pinned; int rc = 0; +#if !defined(STRATA_GPU_METAL) + // the event profiler (profile.hpp): STRATA_PROFILE=1 in normal use, and --bench-report + const char* prof_env = std::getenv("STRATA_PROFILE"); + const std::string prof_v = prof_env ? prof_env : ""; + const bool passive = prof_v == "1" || prof_v == "on" || prof_v == "true"; + if (passive || !bench_out.empty()) { + const char* every = std::getenv("STRATA_PROFILE_EVERY"); + engine.enable_profile(every ? std::max(1, std::atoi(every)) : 16); + } + strata::poly::bench::Report base; + std::string prof_file; + if (passive || !bench_out.empty()) base = report_base(engine, o, args_given, env_given); + if (passive && bench_out.empty()) { + prof_file = env_text("STRATA_PROFILE_OUT"); // a file name + prof_file = prof_file.empty() ? std::string("strata-profile.json") : prof_file; + std::fprintf(stderr, "strata-poly: STRATA_PROFILE=1: the event profile goes to %s after every request\n", + prof_file.c_str()); + ss.after_request = [&] { write_session_profile(engine, base, prof_file); }; + } + if (!bench_out.empty()) { + base.probes = probes; + base.probe_s = probes.seconds; + base.load_s = load_s; + base.tier = bench_long ? "long" : "quick"; + base.launches_wrapped = strata::poly::prof::launches_wrapped(); + std::vector> types; + const Engine::ExpertShape x = engine.expert_shape(); + if (x.gu_type >= 0) types = {{x.gu_type, x.n_embd}, {x.d_type, x.n_ff}}; + const Clock::time_point t = Clock::now(); + strata::poly::bench::probe_dots(base.probes, types, engine.threads()); + base.probe_s += ms_since(t) / 1000.0; + for (const auto& d : base.probes.dots) + std::fprintf(stderr, "strata-poly: bench: CPU dot %s (%s): %.1f GB/s on %d threads, %.1f on one\n", + d.type.c_str(), d.kernel.c_str(), d.gbs_all, d.threads, d.gbs_one); + base.prompt_source = bench_text.empty() ? "random tokens of the vocabulary (no --bench-text)" : bench_text_name; + rc = bench_report(ss, base, bench_long, bench_out, started, bench_text); + return rc; // the random prompts' expert counts are not saved into --expert-profile + } +#endif if (want_serve) { rc = serve(ss); } else if ((long long) ids.size() + max_new > engine.max_context()) { diff --git a/engine/src/poly/profile.hpp b/engine/src/poly/profile.hpp new file mode 100644 index 000000000..a3609c369 --- /dev/null +++ b/engine/src/poly/profile.hpp @@ -0,0 +1,339 @@ +// src/poly/profile.hpp - the event profiler's figures (STRATA_PROFILE=1, --bench-report): what the card's stream did +// during a request's prompt and its answer, family by family, and what the host did meanwhile. +// +// The engine records an event on its stream each time the stream's work changes family (Engine::pmark()), and the +// time from one event to the next is that family's. So a family's time is the stream's time from its first launch to +// the next family's first launch: the card's work on it, plus any wait for the host before the next launch reaches +// the card. The waits have families of their own where the engine knows why it waits (wait_upload: the experts' +// copies into VRAM; wait_cpu: the CPU's experts; host_gap: the host's own work between two calls). The events of a +// call follow one another on one stream, so the families add up to the stream's whole time, and with the gaps between +// calls to the phase's wall time. +// +// A prompt's every call is split. An answer's tokens are split one in `every` (STRATA_PROFILE_EVERY, default 16): +// the others record two events, the call's start and end ("unsplit"). A split token is launched kernel by kernel, +// layer by layer, as the first tokens are before anything is recorded (a recording has no events in it): the same +// answers, and that one token a little slower. No event goes into a recording, so the replays are as they were. +// +// With --layer-split the profile is the first card's: its stream and its calls (the later cards' engines record +// nothing). The answer's tokens count as the window keeps them (Engine::keep()), not as fed with their guesses; a +// batch's step() counts its rows. +// +// This header has no GPU code: the aggregation and the JSON are tested on their own (bench_report_test.cpp). +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace strata::poly::prof { + +enum Fam : int { + kAttention = 0, ///< attention scores, softmax and values (and a family's attention block it does not split) + kKvStore, ///< the keys' and values' convolutions, clips and stores into the caches + kDense, ///< dense products: attention projections, shared experts, controllers, the output head + kNorms, ///< norms, mixes, convolutions and residual sums + kRouting, ///< the router's product, its copy to the host and the host's routing + kExpertsGpu, ///< routed experts on the card, and their sum + kCopyH2D, ///< copies to the card in the stream: embeddings, tables, the CPU experts' sums + kCopyD2H, ///< copies to the host in the stream: the logits + kWaitUpload, ///< the stream waits for experts on their way into VRAM (and the host's staging of them) + kWaitCpu, ///< the stream waits for the CPU's experts + kHostGap, ///< the stream has nothing to do: the host's work between two calls + kHostSetup, ///< the stream idles while the host sets a read up (caches grown, staging taken back, buffers) + kGraph, ///< a recording replayed inside a split call (a batch step's, a block of guesses'): not split + kUnsplit, ///< an answer's token between its start and end events, not split (see above) + kFams +}; + +enum Phase : int { kPrompt = 0, kDecode = 1, kPhases }; + +inline const char* fam_key(int f) { + static const char* const k[kFams] = {"attention", "kv_store", "dense", "norms", "routing", + "experts_gpu", "copy_h2d", "copy_d2h", "wait_upload", "wait_cpu", + "host_gap", "host_setup", "graph", "unsplit"}; + return f >= 0 && f < kFams ? k[f] : "?"; +} + +inline const char* fam_title(int f) { + static const char* const t[kFams] = {"attention", + "KV store and clips", + "dense products", + "norms, mixes, convolutions", + "routing", + "experts on the GPU", + "copies to the GPU", + "copies to the host", + "GPU waits for expert uploads", + "GPU waits for CPU experts", + "GPU idle, host between calls", + "GPU idle, host setting up a read", + "recorded launches, not split", + "not split (sampled out)"}; + return f >= 0 && f < kFams ? t[f] : "?"; +} + +/// The families that are the card waiting, not working. +inline bool fam_idle(int f) { return f == kWaitUpload || f == kWaitCpu || f == kHostGap || f == kHostSetup; } + +inline const char* phase_key(int p) { return p == kPrompt ? "prompt" : "decode"; } + +/// A set of calls' figures. +struct Acc { + double fam_ms[kFams] = {}; + double fam_launches[kFams] = {}; ///< kernel launches in each family (see launch_counter()) + double fam_graph_nodes[kFams] = {}; ///< of them, kernels of replayed recordings (the rest: direct launches) + double fam_bytes[kFams] = {}; ///< bytes the family reads, by the engine's byte model (dense weights, KV + ///< rows, experts on the card); 0 where it has none + double cpu_expert_bytes = 0; ///< the CPU experts' weights read from RAM + double wall_ms = 0; ///< host clock from each call's start to its end, and the gaps between calls + int64_t tokens = 0, calls = 0; + double cpu_ms = 0; ///< CPU experts (Stats::cpu_ms) + double route_wait_ms = 0; ///< the host waiting for the router's copy (Stats::route_wait_ms) + double route_waits = 0; ///< how many times (a host round trip each: the scores to the host, the experts back) + int64_t cpu_experts = 0, gpu_experts = 0; + double staged_experts = 0; ///< a prompt batch's experts copied into VRAM for it (once a visit) + double upload_bytes = 0; ///< experts copied into VRAM in the stream (wait_upload's bytes) + double side_ms = 0, side_bytes = 0; ///< copies of experts on the upload stream, beside the work + + double timeline_ms() const { + double s = 0; + for (double v : fam_ms) s += v; + return s; + } + double launches() const { + double s = 0; + for (double v : fam_launches) s += v; + return s; + } + void add(const Acc& o) { + for (int f = 0; f < kFams; ++f) { + fam_ms[f] += o.fam_ms[f], fam_launches[f] += o.fam_launches[f]; + fam_graph_nodes[f] += o.fam_graph_nodes[f], fam_bytes[f] += o.fam_bytes[f]; + } + cpu_expert_bytes += o.cpu_expert_bytes; + wall_ms += o.wall_ms; + tokens += o.tokens; + calls += o.calls; + cpu_ms += o.cpu_ms; + route_wait_ms += o.route_wait_ms; + route_waits += o.route_waits; + cpu_experts += o.cpu_experts; + staged_experts += o.staged_experts; + gpu_experts += o.gpu_experts; + upload_bytes += o.upload_bytes; + side_ms += o.side_ms; + side_bytes += o.side_bytes; + } +}; + +/// Launch counting: every kernel launch the engine's own code makes, and every kernel node of a recording it replays. +/// The direct launches are counted where the build wraps the runtime's launch call (Linux: launch_count.cpp, linked +/// with --wrap); elsewhere only the recordings' nodes are. A BLAS library's own launches inside one call are not +/// counted. launch_counter() is 0 when counting is off. +inline std::atomic& launch_count() { + static std::atomic n{0}; + return n; +} +/// The profiler is on (Engine::enable_profile()): only then does the wrapper count. +inline std::atomic& launch_counting() { + static std::atomic on{false}; + return on; +} +/// launch_count.cpp's wrapper is linked into this program (it says so at start-up). +inline std::atomic& launch_wrapper_linked() { + static std::atomic on{false}; + return on; +} +/// Of launch_count(), the nodes of replayed recordings. +inline std::atomic& graph_node_count() { + static std::atomic n{0}; + return n; +} +inline uint64_t launch_counter() { return launch_count().load(std::memory_order_relaxed); } +inline uint64_t graph_node_counter() { return graph_node_count().load(std::memory_order_relaxed); } +/// True where direct launches are counted (the wrapper is linked), false where only recordings' nodes are. +inline bool launches_wrapped() { return launch_wrapper_linked().load(std::memory_order_relaxed); } + +/// The context lengths the figures are kept apart by: a call counts at the context it starts from. +inline const std::vector& bucket_edges() { + static const std::vector e{0, 2048, 8192, 32768, 65536, 131072, 262144}; + return e; +} + +inline int bucket_of(int64_t pos) { + const auto& e = bucket_edges(); + int b = 0; + while (b + 1 < (int) e.size() && pos >= e[(size_t) b + 1]) ++b; + return b; +} + +inline std::string bucket_name(int b) { + const auto& e = bucket_edges(); + const auto k = [](int64_t v) { return std::to_string(v / 1024) + "K"; }; + if (b + 1 >= (int) e.size()) return k(e[(size_t) b]) + "+"; + return k(e[(size_t) b]) + "-" + k(e[(size_t) b + 1]); +} + +/// A run's figures: every call (all), and the calls that were split (split), by phase and by context. +struct Profile { + Acc all[kPhases], split[kPhases]; + std::vector by_ctx_all[kPhases], by_ctx_split[kPhases]; + int every = 16; + int64_t requests = 0; + + void reset() { + const int e = every; + *this = Profile{}; + every = e; + } + void add_call(int phase, int64_t pos, bool is_split, const Acc& a) { + const size_t b = (size_t) bucket_of(pos); + auto grow = [&](std::vector& v) { + if (v.size() <= b) v.resize(b + 1); + }; + all[phase].add(a); + grow(by_ctx_all[phase]); + by_ctx_all[phase][b].add(a); + if (is_split) { + split[phase].add(a); + grow(by_ctx_split[phase]); + by_ctx_split[phase][b].add(a); + } + } +}; + +/// A small JSON writer: values in the order they are given, numbers rounded to `digits` decimals. +class Json { +public: + std::string s; + /// Applied to every string value (not to the keys) before it is escaped: the bench report's privacy scrub. + std::string (*filter)(const std::string&) = nullptr; + void open(const char* key = nullptr) { sep(key), s += '{', first_ = true; } + void close() { s += '}', first_ = false; } + void open_list(const char* key = nullptr) { sep(key), s += '[', first_ = true; } + void close_list() { s += ']', first_ = false; } + void str(const char* key, const std::string& v) { sep(key), quote(filter ? filter(v) : v); } + void num(const char* key, double v, int digits = 3) { + sep(key); + if (!std::isfinite(v)) { + s += "null"; + return; + } + char b[64]; + std::snprintf(b, sizeof b, "%.*f", digits, v); + // drop the zeros a whole number does not need: 12.500 -> 12.5, 3.000 -> 3 + std::string t = b; + if (t.find('.') != std::string::npos) { + while (t.back() == '0') t.pop_back(); + if (t.back() == '.') t.pop_back(); + } + if (t == "-0") t = "0"; + s += t; + } + void integer(const char* key, int64_t v) { sep(key), s += std::to_string(v); } + void boolean(const char* key, bool v) { sep(key), s += v ? "true" : "false"; } + void null(const char* key) { sep(key), s += "null"; } + +private: + bool first_ = true; + void sep(const char* key) { + if (!first_) s += ','; + first_ = false; + if (key) quote(key), s += ':'; + } + void quote(const std::string& v) { + s += '"'; + for (const unsigned char c : v) { + if (c == '"' || c == '\\') s += '\\', s += (char) c; + else if (c == '\n') s += "\\n"; + else if (c < 0x20) { + char b[8]; + std::snprintf(b, sizeof b, "\\u%04x", c); + s += b; + } else s += (char) c; + } + s += '"'; + } +}; + +/// One Acc as JSON: per token where it has tokens, and the families' shares of the stream's time. +inline void acc_json(Json& j, const char* key, const Acc& a) { + j.open(key); + const double tok = (double) std::max(a.tokens, 1); + const double tl = a.timeline_ms(); + j.integer("calls", a.calls); + j.integer("tokens", a.tokens); + j.num("wall_ms", a.wall_ms, 2); + j.num("timeline_ms", tl, 2); + j.num("tok_s", a.wall_ms > 0 ? 1000.0 * (double) a.tokens / a.wall_ms : 0.0, 2); + j.num("cpu_experts_ms", a.cpu_ms, 2); + j.num("router_wait_ms", a.route_wait_ms, 2); + j.num("host_round_trips", a.route_waits, 0); + j.integer("cpu_experts", a.cpu_experts); + j.integer("gpu_experts", a.gpu_experts); + j.num("upload_gb", a.upload_bytes / 1e9, 4); + // the upload stream's copies beside the work: their span, from the first copy to the last (with the host's + // staging between them where there is no pinned mirror), not the link's time alone + j.num("side_upload_span_ms", a.side_ms, 2); + j.num("side_upload_gb", a.side_bytes / 1e9, 4); + j.num("launches", a.launches(), 0); + j.num("launches_per_token", a.launches() / tok, 1); + j.open("ms"); + for (int f = 0; f < kFams; ++f) + if (a.fam_ms[f] > 0) j.num(fam_key(f), a.fam_ms[f], 3); + j.close(); + j.open("launches_by_family"); + for (int f = 0; f < kFams; ++f) + if (a.fam_launches[f] > 0) j.num(fam_key(f), a.fam_launches[f], 0); + j.close(); + j.open("graph_nodes_by_family"); + for (int f = 0; f < kFams; ++f) + if (a.fam_graph_nodes[f] > 0) j.num(fam_key(f), a.fam_graph_nodes[f], 0); + j.close(); + j.open("gb_by_family"); + for (int f = 0; f < kFams; ++f) + if (a.fam_bytes[f] > 0) j.num(fam_key(f), a.fam_bytes[f] / 1e9, 4); + j.close(); + j.num("cpu_expert_gb", a.cpu_expert_bytes / 1e9, 4); + j.open("ms_per_token"); + for (int f = 0; f < kFams; ++f) + if (a.fam_ms[f] > 0) j.num(fam_key(f), a.fam_ms[f] / tok, 4); + j.close(); + j.open("share"); + for (int f = 0; f < kFams; ++f) + if (a.fam_ms[f] > 0 && tl > 0) j.num(fam_key(f), a.fam_ms[f] / tl, 4); + j.close(); + j.close(); +} + +/// The whole profile as one JSON object (under `key`). +inline void profile_json(Json& j, const char* key, const Profile& p) { + j.open(key); + j.integer("split_every", p.every); + j.str("launch_counting", launches_wrapped() ? "direct launches and recordings' nodes" : "recordings' nodes only"); + j.integer("requests", p.requests); + for (int ph = 0; ph < kPhases; ++ph) { + j.open(phase_key(ph)); + acc_json(j, "all", p.all[ph]); + acc_json(j, "split", p.split[ph]); + j.open_list("by_context"); + for (size_t b = 0; b < p.by_ctx_all[ph].size(); ++b) { + if (p.by_ctx_all[ph][b].calls == 0) continue; + j.open(); + j.str("context", bucket_name((int) b)); + acc_json(j, "all", p.by_ctx_all[ph][b]); + if (b < p.by_ctx_split[ph].size() && p.by_ctx_split[ph][b].calls > 0) + acc_json(j, "split", p.by_ctx_split[ph][b]); + j.close(); + } + j.close_list(); + j.close(); + } + j.close(); +} + +} // namespace strata::poly::prof diff --git a/terminal/data/settings-register.json b/terminal/data/settings-register.json index 1b115a170..1b3c485da 100644 --- a/terminal/data/settings-register.json +++ b/terminal/data/settings-register.json @@ -37881,6 +37881,109 @@ "retire_after": "", "retired_in": "" }, + { + "name": "STRATA_PROFILE", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "engine/src/poly/main.cpp", + "line": 2359, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "flag", + "default_state": null, + "code_default": null, + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [ + "docs/COMMUNITY_BENCHMARKS.md:271" + ], + "first_commit": null, + "first_date": null, + "since": null, + "last_commit": null, + "last_date": null, + "status": "opt-in", + "owner": "poly/profile", + "note": "strata-poly: 1 turns the event profiler on in normal use (profile.hpp): after every request the GPU time by kernel family, its waits and the CPU experts, prompt and decode apart and by context, go to STRATA_PROFILE_OUT and a line to the log", + "retire_after": "", + "retired_in": "" + }, + { + "name": "STRATA_PROFILE_EVERY", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "engine/src/poly/main.cpp", + "line": 2363, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "int", + "default_state": null, + "code_default": "16", + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [], + "first_commit": null, + "first_date": null, + "since": null, + "last_commit": null, + "last_date": null, + "status": "opt-in", + "owner": "poly/profile", + "note": "strata-poly: with STRATA_PROFILE=1 or --bench-report, one decode token in N is split into families (default 16); the others record only their start and end", + "retire_after": "", + "retired_in": "" + }, + { + "name": "STRATA_PROFILE_OUT", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "engine/src/poly/main.cpp", + "line": 2370, + "backend": "cuda-hip", + "fn": "env_text" + } + ], + "parse": "string", + "default_state": null, + "code_default": null, + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [ + "docs/COMMUNITY_BENCHMARKS.md:273" + ], + "first_commit": null, + "first_date": null, + "since": null, + "last_commit": null, + "last_date": null, + "status": "opt-in", + "owner": "poly/profile", + "note": "strata-poly: with STRATA_PROFILE=1, the file the session profile is written to after every request (default strata-profile.json in the working folder)", + "retire_after": "", + "retired_in": "" + }, { "name": "STRATA_PROFILE_PRIOR_ENTRIES", "backends": [ diff --git a/terminal/polystrata.py b/terminal/polystrata.py index e5756b229..83e277338 100644 --- a/terminal/polystrata.py +++ b/terminal/polystrata.py @@ -4,6 +4,8 @@ python polystrata.py --list-models python polystrata.py --model chat with it; /model in the chat changes it python polystrata.py benchmark --model speeds, memory and cache figures, as a table and as JSON + python polystrata.py bench-report --model the engine's own report to post: probes, speeds, where the + GPU's time goes (strata-poly models; the server stopped) A model is one that setup installed (its run config, strata-.json, is beside this file). One model is in memory at a time. With a server already running on the port, --model switches that server to the model; without @@ -200,9 +202,67 @@ def benchmark(a) -> int: return 0 +def bench_report(a) -> int: + """strata-poly --bench-report with the model's own settings (its run config, as the server starts it).""" + entry = entry_of(a.model) + cfg = json.loads(Path(entry["config"]).read_text(encoding="utf-8-sig")) + from serve import server as srv + if not srv.poly_engine(cfg): + raise SystemExit(f"polystrata: {entry['id']} runs on the Strata project's engine: bench-report is strata-poly's") + port = port_of(entry, a.port) + code, _ = terminal.api(f"http://127.0.0.1:{port}", "/health", None, a.api_key, timeout=3) + if code: + raise SystemExit(f"polystrata: a server answers on port {port}: stop it first, the report needs the GPU to itself") + exe = srv._component_exe(cfg["exe"], cfg) if srv.engine_component.is_reference(cfg["exe"]) else srv.engine_exe(cfg) + args = [x for x in srv.engine_args(cfg, exe, announce=False) if x != "--serve"] + out = os.path.abspath(a.out or "bench-report") + cmd = [exe, *args, "--bench-report", out] + (["--long"] if a.long else []) + # the prompts: bench_text's fixed English, in the model's own tokens (random token ids where there is no tokenizer) + import tempfile + import bench_text + tok = srv.load_tokenizer(Path(cfg["tokenizer"])) if cfg.get("tokenizer") else None + ids_file = None + if tok is None: + print("(no tokenizer in the run config: the prompts are random tokens, which route unlike real text)") + else: + ctx = int(args[args.index("--max-context") + 1]) if "--max-context" in args else 8192 + need = 12000 + (ctx if a.long else 0) + if a.text == "docs": + # real prose and code from this checkout's own docs: it routes to the experts the way a chat does (the + # synthetic text keeps to fewer of them, so the cache's misses look cheaper than they are) + docs = [ROOT.parent / "README.md"] + sorted((ROOT.parent / "docs").glob("*.md")) + body = "\n\n".join(p.read_text(encoding="utf-8", errors="replace") for p in docs if p.is_file()) + ids = tok.encode(body) + while ids and len(ids) < need: + ids = ids + ids + name = "this checkout's README and docs (real text)" + else: + ids = bench_text.tokens(tok, need) + name = f"bench_text v{bench_text.VERSION} (synthetic English, fixed seed)" + fd, ids_file = tempfile.mkstemp(prefix="bench-text-", suffix=".ids") + with os.fdopen(fd, "w", encoding="ascii") as f: + f.write(",".join(map(str, ids))) + cmd += ["--bench-text", f"{ids_file}@{name}"] + if a.dry_run: + print(" ".join(cmd)) + if ids_file: + os.unlink(ids_file) + return 0 + print(f"bench report of {entry['id']} with its own settings: about a minute after the model loads on an RTX 2070 Super, more on a slower card" + + (", and the long conversation after that" if a.long else ""), flush=True) + try: + rc = subprocess.call(cmd, env=srv.child_env(cfg), cwd=cfg.get("cwd") or None) + finally: + if ids_file: + os.unlink(ids_file) + if rc == 0: + print(f"written: {out}.json and {out}.md; post them with the \"Bench report\" issue form") + return rc + + def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("command", nargs="?", choices=["chat", "benchmark"], default="chat") + ap.add_argument("command", nargs="?", choices=["chat", "benchmark", "bench-report"], default="chat") ap.add_argument("--list-models", action="store_true", help="the installed models, and which is in memory") ap.add_argument("--model", help="a model's name, as --list-models shows it (a part of it is enough when only " "one name has it)") @@ -213,6 +273,12 @@ def main() -> int: ap.add_argument("--prompt-tokens", type=lambda s: [int(x) for x in s.split(",")], default=[2000, 8000], help="benchmark: the long prompts' sizes in tokens, roughly (default 2000,8000)") ap.add_argument("--json", help="benchmark: also write the figures to this file") + ap.add_argument("--out", help="bench-report: the files' name without .json / .md (default: bench-report here)") + ap.add_argument("--long", action="store_true", help="bench-report: add one long conversation read in chunks") + ap.add_argument("--text", choices=["synthetic", "docs"], default="synthetic", + help="bench-report: the prompts' text: synthetic (the same everywhere; the default) or docs (this " + "checkout's own README and docs: real text, which routes to the experts as a chat does)") + ap.add_argument("--dry-run", action="store_true", help="bench-report: print the engine's command, run nothing") a = ap.parse_args() if a.list_models: return list_models(a.port, a.api_key) @@ -221,6 +287,8 @@ def main() -> int: if a.command == "benchmark": a.max_tokens = a.max_tokens or 256 return benchmark(a) + if a.command == "bench-report": + return bench_report(a) entry = entry_of(a.model) srv = Server(entry, port_of(entry, a.port), a.api_key) try: diff --git a/terminal/tools/bench_text.py b/terminal/tools/bench_text.py new file mode 100644 index 000000000..83151f9e5 --- /dev/null +++ b/terminal/tools/bench_text.py @@ -0,0 +1,109 @@ +"""The bench report's prompt text (strata-poly --bench-report --bench-text): plain English sentences made from fixed +word lists with a fixed seed, the same on every PC and every version of this file's VERSION. No user data, nothing +from the PC. A text that reads like prose routes a mixture-of-experts model's tokens to as many experts as a real +prompt does; random token ids route to far fewer, and their answers repeat themselves. + + python terminal/tools/bench_text.py 2000 the first 2,000 words, to look at +""" +from __future__ import annotations + +import random +import sys + +VERSION = 2 # change it with the lists or the generator: a report says which text it read + +# Plain words, several hundred of them, so that a prompt has about as many different tokens as real prose (version 1's +# few phrases had 198 different tokens in 2,048; an English article about 670). +NOUNS = """account airport answer apple area argument army arrival article artist attention aunt autumn baby balance +ball band bank basket battery beach bean bear bed bell bicycle bird birthday blanket boat body bone book border bottle +bowl box brain branch bread breakfast brick bridge brother brush budget building bus butter cabin cake camera camp +candle captain car card carpet castle cat ceiling chair chapter cheese chest chicken child chimney church circle city +class clock cloud coast coat coffee coin collar college colour corner cottage country cousin cow crowd cup curtain +customer dance daughter desk diary dinner doctor dog door drawer dream dress driver drum dust eagle earth egg +election engine envelope evening factory family farm feather fence field film finger fire fish flag floor flower fog +forest fork fountain friend fruit garden gate gift glass glove goat government grandfather grass guitar hall hammer +harbour hat health heart hill history holiday honey horse hospital hotel house island jacket journey judge kettle key +kitchen knife ladder lake lamp language lawyer leaf lesson letter library lighthouse lion lock machine magazine map +market meadow meeting message metal minute mirror moon morning mountain mouse museum music needle neighbour +newspaper night notebook ocean office onion orange orchard painting palace paper parcel parent park passenger path +pencil pepper piano picture pillow planet plate pocket poem pond potato prison problem question rabbit radio railway +rain recipe river road roof room rope sailor salt sand school science season shadow sheep shelf shell ship shirt shoe +shop shoulder silver sister skirt sky snow soldier song soup spoon spring square stairs star station stone storm +story street student sugar summer sun supper surface sweater table teacher telephone tent theatre ticket tiger +tomato tongue tool tooth tower town toy tractor train tree truck tunnel umbrella uncle valley village violin voice +wagon wall wallet watch water weather wheel window wing winter wire wood wool world year""".split() +VERBS = """accepted admired allowed answered arranged asked attacked avoided baked balanced borrowed brought built +buried burned called carried caught changed chased checked cleaned climbed closed collected copied counted covered +crossed delivered described designed destroyed discovered divided dropped earned emptied entered escaped examined +explained fetched filled finished fixed folded followed forgot found gathered guarded guessed handed heard helped +hid hunted imagined improved invited joined kept kicked knocked learned left lifted listened locked lost loved made +marked measured mended met moved noticed obeyed offered opened ordered owned packed painted passed picked placed +planned planted played pointed polished poured praised prepared pressed printed promised protected pulled pushed +questioned reached read received recorded remembered repaired replaced rescued returned rolled ruled sailed saved +searched sent served shared showed signed sold sorted spilled spotted started stopped studied supported surprised +taught tested thanked threw tied touched traced traded trained translated trusted turned visited waited walked +warned washed watched welcomed whispered wrapped wrote""".split() +ADJECTIVES = """ancient angry anxious bitter black blue bold brave bright broad broken busy calm careful cheap cheerful +clean clever cloudy cold colourful comfortable common cool crowded curious damp dark deep delicate dirty distant dry +dusty eager early empty enormous famous fast fierce flat foolish foreign fresh friendly gentle giant glad golden +graceful green grey happy hard heavy helpful hidden high hollow honest huge hungry icy important kind large late lazy +light little lonely long loud lovely low lucky modern narrow nervous new noisy odd old orange patient plain pleasant +polite poor proud purple quick quiet rare red rich rough round rusty sad safe salty sharp shiny short shy silent +simple slow small smooth soft sour square steep sticky strange strong sudden sweet tall tame thick thin tidy tiny +tired twisted ugly unusual useful warm weak wet white wide wild wise wooden yellow young""".split() +ADVERBS = """afterwards almost always angrily badly bravely briefly calmly carefully certainly clearly closely +easily eventually finally firmly gently gladly gradually happily honestly immediately kindly lately loudly luckily +nearly neatly never often patiently politely proudly quickly quietly rarely really recently regularly roughly sadly +safely seldom slowly smoothly softly sometimes soon suddenly surely tightly today tomorrow warmly wisely yesterday""".split() +PREPS = "above across after against along among around behind below beside between beyond by during inside near over through under within".split() +LINKS = ("Later,", "Meanwhile,", "Afterwards,", "In the end,", "At first,", "However,", "For that reason,", "Then", + "Some time later,", "On the other hand,", "Of course,", "Even so,", "Before long,", "Luckily,") + + +def _sentence(r: random.Random) -> str: + n = lambda: r.choice(NOUNS) # noqa: E731 + a = lambda: r.choice(ADJECTIVES) # noqa: E731 + k = r.randrange(5) + if k == 0: + s = f"the {a()} {n()} {r.choice(VERBS)} a {n()} {r.choice(PREPS)} the {n()}" + elif k == 1: + s = f"my {n()} {r.choice(ADVERBS)} {r.choice(VERBS)} the {a()} {n()} and the {n()}" + elif k == 2: + s = f"{r.choice(PREPS)} the {a()} {n()}, a {n()} {r.choice(VERBS)} {r.choice(ADVERBS)}" + elif k == 3: + s = f"nobody {r.choice(VERBS)} the {n()} of the {a()} {n()} {r.choice(PREPS)} the {n()}" + else: + s = f"the {n()} was {a()}, so the {n()} {r.choice(VERBS)} it {r.choice(PREPS)} a {a()} {n()}" + return s + r.choice((".", ".", ".", "!", "?") if k == 3 else (".", ".", ".", ".")) + + +def words(n: int, seed: int = 1) -> str: + """At least n words of the text for `seed`, in paragraphs.""" + r = random.Random(seed * 1000 + VERSION) + out, count, in_par = [], 0, 0 + while count < n: + s = _sentence(r) + if in_par and r.random() < 0.3: + s = f"{r.choice(LINKS)} {s}" + s = s[0].upper() + s[1:] + out.append(s) + count += len(s.split()) + in_par += 1 + if in_par >= r.randint(4, 8): + out.append("\n\n") + in_par = 0 + return " ".join(out).replace(" \n\n ", "\n\n").strip() + + +def tokens(tokenizer, n_tokens: int, seed: int = 1) -> list[int]: + """At least n_tokens ids of the text, by the model's own tokenizer (its encode()).""" + n_words = max(64, n_tokens * 3 // 4) + while True: + ids = tokenizer.encode(words(n_words, seed)) + if len(ids) >= n_tokens: + return ids + n_words = n_words * 3 // 2 + 64 + + +if __name__ == "__main__": + print(words(int(sys.argv[1]) if len(sys.argv) > 1 else 300)) diff --git a/terminal/tools/test_bench_text.py b/terminal/tools/test_bench_text.py new file mode 100644 index 000000000..dd76bdb21 --- /dev/null +++ b/terminal/tools/test_bench_text.py @@ -0,0 +1,40 @@ +"""terminal/tools/bench_text.py: the bench report's prompt text is the same every time, prose, and long enough.""" +import hashlib +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import bench_text # noqa: E402 + + +class FakeTokenizer: + def encode(self, text): + return [len(w) for w in text.split()] + + +class BenchText(unittest.TestCase): + def test_same_text_every_time(self): + a, b = bench_text.words(3000), bench_text.words(3000) + self.assertEqual(a, b) + self.assertNotEqual(a, bench_text.words(3000, seed=2)) + self.assertGreaterEqual(len(a.split()), 3000) + # the text of VERSION 2: a change to the lists or the generator must change VERSION too + self.assertEqual(bench_text.VERSION, 2) + self.assertEqual(hashlib.sha256(bench_text.words(500).encode()).hexdigest()[:12], "9597a732396f") + + def test_prose(self): + t = bench_text.words(400) + self.assertTrue(t[0].isupper()) + self.assertIn(". ", t) + self.assertIn("\n\n", t) + for bad in ("/", "\\", "@", "http"): + self.assertNotIn(bad, t) + + def test_tokens_long_enough(self): + ids = bench_text.tokens(FakeTokenizer(), 5000) + self.assertGreaterEqual(len(ids), 5000) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/bench_reports.py b/tools/bench_reports.py new file mode 100644 index 000000000..eb9380dc8 --- /dev/null +++ b/tools/bench_reports.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +"""Bench reports side by side: `strata-poly --bench-report` files from several PCs in one table per card, with the +numbers that are far from the same card's other reports flagged. + + python tools/bench_reports.py report1.json report2.json ... a Markdown table per card, and the outliers + python tools/bench_reports.py --json reports/*.json the same as JSON + python tools/bench_reports.py --check-privacy report.json ... exit 1 if a report holds a path, an e-mail + address, a serial or an address on a network + python tools/bench_reports.py --check-privacy --private alice,box report.json ... or one of these words + +A number is flagged when it is under OUTLIER (0.75) of the median of the other reports of the same card and model +(at least two others), or for the probes of the same card whatever the model. The engine writes the reports without +paths, user or host names (engine/src/poly/bench_report.hpp); --check-privacy checks a file before it is posted. +Only the standard library is used. +""" +from __future__ import annotations + +import argparse +import json +import re +import statistics +import sys +from pathlib import Path + +OUTLIER = 0.75 + +# what must never be in a report that is posted +PRIVACY = [ + ("a path", re.compile(r"(?:/home/|/Users/|/root/|/mnt/|/media/|/tmp/|/var/|/work/|/workspace/|/srv/|/data/|/run/user/|/Volumes/|/private/|\b[A-Za-z]:\\|\\\\[A-Za-z]|~/)")), + ("an e-mail address", re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")), + ("a GPU or other UUID", re.compile(r"\b(?:GPU-|MIG-)?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-" + r"[0-9a-fA-F]{12}\b")), + ("a MAC address", re.compile(r"\b(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}\b")), + # (not a version: 6.6.87.2-microsoft-standard-WSL2 is a kernel's release, and Salad's hosts run WSL2) + ("an IP address", re.compile(r"(? list[str]: + """What in `text` names a person or a PC: a list of findings, empty when there is none.""" + out = [] + for what, rx in PRIVACY: + m = rx.search(text) + if m: + out.append(f"{what}: {m.group(0)!r}") + for word in private or []: + if word and len(word) >= 3 and re.search(r"(? dict: + r = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(r, dict) or r.get("kind") not in ("strata-bench-report", "strata-session-profile"): + raise ValueError(f"{path.name}: not a strata-poly bench report") + return r + + +def _d(v) -> dict: + return v if isinstance(v, dict) else {} + + +def _s(v, default="?") -> str: + return v if isinstance(v, str) and v else default + + +def _n(v): + """A number of a report, or None: a posted file is anyone's, so every field is checked for its type.""" + return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else None + + +def _i(v) -> int: + return int(v) if isinstance(v, int) and not isinstance(v, bool) else 0 + + +def run_of(r: dict, name: str) -> dict | None: + runs = r.get("runs") + return next((x for x in runs if isinstance(x, dict) and x.get("name") == name), None) if isinstance(runs, list) else None + + +def figures(r: dict) -> dict: + """The numbers a table row shows, by column.""" + hw = _d(r.get("hardware")) + gpu, cpu = _d(hw.get("gpu")), _d(hw.get("cpu")) + pr, model = _d(r.get("probes")), _d(r.get("model")) + dots = pr.get("cpu_dot") if isinstance(pr.get("cpu_dot"), list) else [] + gen, width = _i(gpu.get("pcie_gen")), _i(gpu.get("pcie_width")) + f = { + "card": _s(gpu.get("name")), + "model": f"{_s(model.get('name'))} ({_s(model.get('expert_types'))})", + "cpu": _s(cpu.get("model")), + "pcie": f"gen{gen} x{width}" if gen > 0 else "?", + "vram_experts": f"{_i(r.get('cached_experts'))}/{_i(r.get('total_experts'))}", + "h2d_pinned_gbs": _n(pr.get("h2d_pinned_gbs")), + "ram_read_gbs": _n(pr.get("ram_read_gbs")), + "gpu_mem_gbs": _n(pr.get("gpu_mem_gbs")), + "cpu_dot_gbs": _n(_d(dots[0]).get("gbs_all_threads")) if dots else None, + } + for n in (302, 2048, 8192): + x = run_of(r, f"prompt {n}") + f[f"prompt_{n}"] = _n(x.get("prompt_tok_s")) if x else None + f[f"decode_{n}"] = _n(x.get("decode_tok_s")) if x else None + for x in r.get("long") if isinstance(r.get("long"), list) else []: + if isinstance(x, dict): + f[f"long_decode_{_i(x.get('context_end')) // 1024}k"] = _n(x.get("decode_tok_s")) + return f + + +def md(v) -> str: + """A table cell: no line or cell breaks, no HTML, headings, images or links from a posted file.""" + t = re.sub(r"[\r\n]+", " ", str(v)) + t = t.replace("<", "<").replace(">", ">") + return re.sub(r"([|#!\[\]`*_\\])", r"\\\1", t) + + +SPEED = ["prompt_2048", "prompt_8192", "decode_302", "decode_2048", "decode_8192"] +PROBES = ["h2d_pinned_gbs", "ram_read_gbs", "gpu_mem_gbs", "cpu_dot_gbs"] + + +def flag_outliers(rows: list[dict]) -> None: + """Each row's `flags`: its numbers under OUTLIER of the median of its peers' (the same card's other rows; for the + speeds, of the same model too).""" + for i, row in enumerate(rows): + row.setdefault("flags", []) + for cols, same in ((SPEED, ("card", "model")), (PROBES, ("card",))): + peers = [o for j, o in enumerate(rows) if j != i and all(o[k] == row[k] for k in same)] + for c in cols: + vals = [o[c] for o in peers if isinstance(o.get(c), (int, float)) and o[c] > 0] + v = row.get(c) + if len(vals) >= 2 and isinstance(v, (int, float)) and v > 0: + med = statistics.median(vals) + if v < OUTLIER * med: + row["flags"].append(f"{c} {v:g} is {v / med:.0%} of its peers' median {med:g}") + + +def table(rows: list[dict]) -> str: + cols = [("source", "Report"), ("model", "Model"), ("cpu", "CPU"), ("pcie", "PCIe"), + ("vram_experts", "Experts in VRAM"), ("h2d_pinned_gbs", "H2D GB/s"), ("ram_read_gbs", "RAM GB/s"), + ("cpu_dot_gbs", "CPU dot GB/s"), ("prompt_2048", "Prompt 2K tok/s"), ("prompt_8192", "Prompt 8K tok/s"), + ("decode_302", "Decode tok/s after 302"), ("decode_8192", "Decode tok/s after 8K")] + out = [] + for card in sorted({r["card"] for r in rows}): + mine = [r for r in rows if r["card"] == card] + out.append(f"### {md(card)} ({len(mine)} report{'s' if len(mine) != 1 else ''})\n") + out.append("| " + " | ".join(t for _, t in cols) + " |") + out.append("| " + " | ".join("---" for _ in cols) + " |") + for r in mine: + cells = [] + for k, _ in cols: + v = r.get(k) + cells.append("-" if v is None else f"{v:g}" if isinstance(v, float) else md(v)) + out.append("| " + " | ".join(cells) + " |") + flagged = [(r["source"], f) for r in mine for f in r["flags"]] + if flagged: + out.append("\nFar from the same card's other reports:\n") + out.extend(f"- {md(s)}: {md(f)}" for s, f in flagged) + out.append("") + return "\n".join(out) + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("reports", nargs="+", type=Path) + ap.add_argument("--json", action="store_true", help="the rows and their flags as JSON") + ap.add_argument("--check-privacy", action="store_true", help="only check the files for private details") + ap.add_argument("--private", default="", help="with --check-privacy: words that must not appear, comma separated") + a = ap.parse_args(argv) + if a.check_privacy: + bad = 0 + words = [w.strip() for w in a.private.split(",") if w.strip()] + for p in a.reports: + problems = privacy_problems(p.read_text(encoding="utf-8", errors="replace"), words) + for x in problems: + print(f"{p.name}: {x}") + bad += bool(problems) + if not bad: + print(f"{len(a.reports)} file(s): nothing private found") + return 1 if bad else 0 + rows = [] + for p in a.reports: + try: + r = load(p) + f = figures(r) + except Exception as e: # one bad file leaves the others' table + print(f"skipped {p.name}: {e}", file=sys.stderr) + continue + f["source"] = p.stem + rows.append(f) + flag_outliers(rows) + if a.json: + print(json.dumps(rows, indent=1)) + else: + print(table(rows)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/test_bench_reports.py b/tools/test_bench_reports.py new file mode 100644 index 000000000..b33410273 --- /dev/null +++ b/tools/test_bench_reports.py @@ -0,0 +1,126 @@ +"""tools/bench_reports.py: the privacy scan, the table per card and the outlier flags; and, where the engine's +poly_bench_report_test is built (BENCH_REPORT_TEST_BIN), the report it writes passes the scan.""" +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import bench_reports as br # noqa: E402 + + +def report(card="NVIDIA GeForce RTX 2070 SUPER", prompt2k=650.0, decode=20.0, h2d=12.0, model="Inkling 2 Mini"): + runs = [{"name": "prompt 302", "prompt_tok_s": 300.0, "decode_tok_s": decode}, + {"name": "prompt 2048", "prompt_tok_s": prompt2k, "decode_tok_s": decode * 0.95}, + {"name": "prompt 8192", "prompt_tok_s": prompt2k * 1.3, "decode_tok_s": decode * 0.9}] + return {"kind": "strata-bench-report", "schema": 1, + "model": {"name": model, "expert_types": "iq4_nl/iq4_nl"}, + "hardware": {"gpu": {"name": card, "pcie_gen": 3, "pcie_width": 16}, "cpu": {"model": "AMD Ryzen 5 3600XT"}}, + "probes": {"h2d_pinned_gbs": h2d, "ram_read_gbs": 38.0, "gpu_mem_gbs": 400.0, + "cpu_dot": [{"gbs_all_threads": 30.0}]}, + "cached_experts": 982, "total_experts": 3072, "runs": runs, "long": []} + + +class Privacy(unittest.TestCase): + def test_clean_text_passes(self): + text = (json.dumps(report()) + " tok/s GB/s gen3 x16 Linux 6.8.0-149-generic driver 580.178.04 sse4.2 q8_0/iq4_nl" + " Linux 6.6.87.2-microsoft-standard-WSL2") + self.assertEqual(br.privacy_problems(text), []) + + def test_each_kind_of_private_detail_is_found(self): + for text in ["/home/alice/models/m.gguf", "C:\\Users\\bob\\m.gguf", "{\"p\": \"D:\\\\models\"}", + "\\\\server\\share", "me@example.com", "GPU-1a2b3c4d-1111-2222-3333-444455556666", + "00:1A:2b:3C:4d:5E", "192.168.11.93", "0000:01:00.0", "sk-abcdefgh1234", "~/models", + "/work/models/m.gguf", "/workspace/x", "/Volumes/disk/m"]: + self.assertTrue(br.privacy_problems(text), text) + + def test_private_words_only_whole(self): + self.assertTrue(br.privacy_problems("ran by alice", ["alice"])) + self.assertEqual(br.privacy_problems("malice and alice_2", ["alice"]), []) + + def test_cli_exit_codes(self): + with tempfile.TemporaryDirectory() as d: + good, bad = Path(d, "good.json"), Path(d, "bad.json") + good.write_text(json.dumps(report()), encoding="utf-8") + r = report() + r["settings"] = {"args": [["--expert-profile", "/home/alice/p.txt"]]} + bad.write_text(json.dumps(r), encoding="utf-8") + self.assertEqual(br.main(["--check-privacy", str(good)]), 0) + self.assertEqual(br.main(["--check-privacy", str(bad)]), 1) + self.assertEqual(br.main(["--check-privacy", "--private", "Ryzen", str(good)]), 1) + + +class Table(unittest.TestCase): + def test_outliers_against_the_same_cards_median(self): + rows = [] + for i, (p, h2d) in enumerate([(650, 12), (640, 12.2), (660, 11.9), (300, 3.0)]): + f = br.figures(report(prompt2k=p, h2d=h2d)) + f["source"] = f"r{i}" + rows.append(f) + other = br.figures(report(card="NVIDIA GeForce RTX 3060", prompt2k=300)) + other["source"] = "r3060" + rows.append(other) + br.flag_outliers(rows) + self.assertEqual([r["source"] for r in rows if r["flags"]], ["r3"]) + self.assertTrue(any("prompt_2048" in f for f in rows[3]["flags"])) + self.assertTrue(any("h2d_pinned_gbs" in f for f in rows[3]["flags"])) + md = br.table(rows) + self.assertIn("### NVIDIA GeForce RTX 2070 SUPER (4 reports)", md) + self.assertIn("### NVIDIA GeForce RTX 3060 (1 report)", md) + self.assertIn("Far from the same card's other reports", md) + + def test_another_model_is_no_peer_for_speeds(self): + a = br.figures(report(prompt2k=650)) + b = br.figures(report(prompt2k=651)) + c = br.figures(report(prompt2k=200, model="Qwen3.6")) + for i, f in enumerate((a, b, c)): + f["source"] = str(i) + br.flag_outliers([a, b, c]) + self.assertEqual(c["flags"], []) + + def test_bad_fields_and_markdown(self): + r = report(card="Evil | # card\n![x](y)") + r["probes"] = {"h2d_pinned_gbs": "fast", "cpu_dot": "nope"} + r["runs"] = [{"name": "prompt 2048", "prompt_tok_s": [1]}, "junk"] + f = br.figures(r) + self.assertIsNone(f["h2d_pinned_gbs"]) + self.assertIsNone(f["prompt_2048"]) + f["source"] = "x" + br.flag_outliers([f]) + t = br.table([f]) + self.assertNotIn("