mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-04 07:18:50 +00:00
The engine now runs unsloth's Qwen3.8-Flash-Next quants (UD-IQ1_S up to UD-Q6_K_XL and Q8_0) as native packs, besides the ISTA-DASLab files. - Split models: --native takes the first shard and finds the others by name (gguf_split_paths, GgufModel). The expert arena is filled from the shards by tensor name and checked against native_experts.txt, whose lines no longer carry shard-1 offsets. The native head and embedding are found in any shard, and --ple-gguf defaults to the shard that holds per_layer_token_embd. - GPU kernels: expert dot products and dequantizers for Q4_K, Q5_K, Q6_K, Q5_1, Q8_0, IQ1_S and IQ4_XS (llama.cpp's), one dispatch list for all formats, and a startup check that every layer's formats have kernels. The Q5_1 min and IQ1_S delta terms use the quantized activation sums, as ggml-cpu does: 1.1% instead of 1.9% relative error per expert. - PLE: the table may be IQ4_NL or Q8_0 and may share its shard with other tensors; the native PLE key may be any native MMVQ type (Q8_0 here). - tools/iq_pack.py: all shards of a split model, and every float tensor in the form the engine takes. The files' F32 router, SSM gate and injection tensors hold BF16 values (exact); their Q8_0 hyper-connection and PLE value weights are re-rounded to BF16. - native_expert_parity: split models, a --synthetic mode for formats with no model file at hand, and a check of the GPU dequantizers. - README: the unsloth files, their RAM needs and how to pack them. UD-Q4_K_XL on an RTX 3090 (160 GB RAM): prompts 529-594 tok/s, generation 49-57 tok/s. Greedy tokens equal llama.cpp's argmax on the same GGUF at 98.2% (code) and 95.6% (thinking) of positions.
2953 lines
179 KiB
C++
2953 lines
179 KiB
C++
// src/program/generate.cpp - P2.S6: `strata generate`.
|
|
//
|
|
// THE DRIVER, and the first program in this project that answers a question. Everything below it is a
|
|
// component; this is the thing that composes them into a token:
|
|
//
|
|
// embed_row(token) -> 48 captured layer graphs (the CPU expert pool behind the doorbell) ->
|
|
// lm_head(R) -> sample -> embed_row(next) -> ...
|
|
//
|
|
// WHAT IT IS NOT. There is no tokenizer here. `pack/full/tokenizer/` and `tools/strata_tokenizer.py` exist,
|
|
// and a C++ BPE is Phase 1's deliverable rather than this program's, so the prompt arrives as IDS via
|
|
// `--tokens`. That is not a placeholder: it is exactly what Gate C1 needs, because C1 compares logits against
|
|
// llama.cpp on the SAME ids, and a tokenizer on only one side of that comparison is a second variable.
|
|
//
|
|
// AND IT IS PHASE 2, so hit rate is `h = 0` and the number it prints is slow on purpose
|
|
// (`phase-2-correct-engine.md:5-9`). What it is FOR is the honest tok/s figure and the logit dump.
|
|
|
|
#include "strata/artifact/gguf_split.hpp"
|
|
#include "strata/core/expert_cache.hpp"
|
|
#include "strata/core/expert_source.hpp"
|
|
#include "strata/core/layer.hpp"
|
|
#include "strata/core/layout.hpp"
|
|
#include "strata/core/session.hpp"
|
|
#include "strata/core/weights.hpp"
|
|
#include "strata/kernels/cpu/expert.hpp"
|
|
#include "strata/kernels/cpu/pool.hpp"
|
|
#include "strata/kernels/cpu/expert_layout.hpp"
|
|
#include "strata/kernels/ngram.hpp"
|
|
#include "strata/kernels/s2_expert_grouped.hpp"
|
|
#include "strata/kernels/sampler.hpp"
|
|
#include "strata/kernels/shared_expert.hpp"
|
|
#include "strata/kernels/iq_kernels.hpp"
|
|
#include "strata/kernels/native_moe.hpp"
|
|
#include "strata/kernels/native_mmvq.hpp"
|
|
#include "strata/kernels/native_gdn.hpp"
|
|
#include "strata/kernels/native_router.hpp"
|
|
#include "strata/kernels/native_qsa.hpp"
|
|
#include "strata/kernels/native_qsa_indexer.hpp"
|
|
#include "strata/kernels/native_rope.hpp"
|
|
#include "strata/kernels/mrope.hpp"
|
|
#include "strata/kernels/qsa.hpp"
|
|
#include "strata/core/native_head.hpp"
|
|
#include "strata/core/verify.hpp"
|
|
#include "strata/core/mtp.hpp"
|
|
#include "strata/core/prompt_cache.hpp"
|
|
#include "strata/prefill/prefill.hpp"
|
|
#include "strata/core/native_dense.hpp"
|
|
#include "strata/program/logits_selection.hpp"
|
|
|
|
#include <cuda_runtime.h>
|
|
|
|
#include <chrono>
|
|
#include <algorithm>
|
|
#include <iostream>
|
|
#include <thread>
|
|
#include <charconv>
|
|
#include <cmath>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
#include <fstream>
|
|
#include <sstream>
|
|
#include <string>
|
|
#include <set>
|
|
#include <vector>
|
|
|
|
namespace {
|
|
|
|
using Clock = std::chrono::steady_clock;
|
|
|
|
struct Options {
|
|
std::string pack = "pack/full";
|
|
std::vector<int64_t> tokens; // the prompt, PRE-TOKENIZED
|
|
int64_t max_new = 16;
|
|
int64_t max_context = 4096;
|
|
bool greedy = true;
|
|
uint64_t seed = 0;
|
|
int top_k = 20;
|
|
float top_p = 0.95f;
|
|
float temperature = 1.0f;
|
|
std::string dump_logits; // one line of logits per generated position
|
|
int64_t logits_stride = 1; // storage selection; all prompt tokens remain conditioned
|
|
/// **THE RESIDUAL, SO THE HEAD CAN BE CHECKED WITHOUT THE LAYERS.**
|
|
///
|
|
/// C1 fails (LEDGER L116) and the pipeline is `embed -> 48 layers -> head`. Dumping `R` splits it in half:
|
|
/// the head is one norm, two bf16 projections and one 794 MB GEMV, all of which can be recomputed in Python
|
|
/// from the manifest. If Python agrees with the engine on the same `R`, the head is right and the layers
|
|
/// are wrong; if it disagrees, the head is wrong. Nothing else in the engine can be split that cheaply.
|
|
std::string ple_gguf; // the ORIGINAL second GGUF shard: the PLE table is not in the pack
|
|
bool no_ple = false; // explicit diagnostic ablation; never a normal inference default
|
|
bool stream_token = false; // R2.6 experiment: ordered work on the session stream
|
|
bool check_logits = false; // optional full-vocabulary finite scan
|
|
bool gr_fp32_activations = false; // pinned CUDA single-token BF16 activation contract
|
|
bool gr_native_mmvf = false; // pinned projection reduction tree as well as FP32 inputs
|
|
bool native_bf16 = false; // SSM gates, router and indexer projections only
|
|
bool native_bf16_extra = false; // PLE value and shared expert scalar gate
|
|
bool native_ple_key = false; // unchanged Q2_0 key and CUDA Q8_1 activations
|
|
bool native_moe_combine = false; // pinned fused CUDA weighted reduction
|
|
bool native_gdn = false; // pinned CUDA recurrence and preprocessing
|
|
bool native_flash_attn_short = false; // diagnostic pinned attention, context <=256
|
|
bool native_qsa_indexer = false; // pinned F16 key cache and F32 pooling
|
|
bool native_qsa = false; // pinned F32 QSA norms and gate
|
|
bool native_rope = false; // pinned text-only CUDA rotary arithmetic
|
|
bool native_ple_postops = false; // pinned PLE postprojection arithmetic
|
|
bool native_router = false; // pinned fused 512-expert top-10 router
|
|
bool cpu_oracle_q8_0 = false; // pinned x86 activation scales/codes at both expert stages
|
|
std::string native_head_gguf; // native output.weight experiment; same model shard as the pack
|
|
std::vector<std::string> native_dense_gguf; // repeat for native GDN/QSA projection shards
|
|
/// Plan v0.3 P1: the whole native arithmetic set as ONE switch (model shard 1). It enables exactly the
|
|
/// combination recorded in bench/results/2026-09-23-attention-ple plus the native indexer, and never the
|
|
/// <=256-token attention adapter. It becomes the default once P0 shows it is not slower.
|
|
std::string native_preset;
|
|
/// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM.
|
|
std::string ple_io = "direct";
|
|
int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables
|
|
int ple_inflight = 64;
|
|
double ple_delay_us = 0; ///< fault injection: every row read completes no earlier than this
|
|
bool ple_sync_submit = false; ///< A/B arm: submit reads on the token thread, no I/O worker
|
|
std::string kv = "fp16"; ///< plan v0.3 P7: KV storage, fp16 (default) or int8 (half the VRAM)
|
|
std::string dump_residual;
|
|
/// The head input, `bb.mixed`. It exists so the head can be SPLIT: steps 1-4 (the per-stream norm, the two
|
|
/// bf16 projections and the stream mean) recompute cheaply in Python, and only the 794 MB GEMV does not.
|
|
std::string dump_mixed;
|
|
/// One residual snapshot per layer per position: `n_layers * hc * n_embd` floats per position, appended in
|
|
/// position order. This is the C1 BISECTION LADDER - it is what `llama-debug --tensor-filter l_last` prints
|
|
/// for the reference, so the first layer whose `sum` diverges is the layer that holds the bug. It needs the
|
|
/// captured path (the expert pool only exists there), so it is refused with `--no-capture`.
|
|
std::string dump_layers;
|
|
/// `2 * n_embd + 2 * hc` floats per layer per position: the attention half's block output, the MoE half's,
|
|
/// and the two injection vectors. It separates `linear_attn_out-<l>` from `ffn_out-<l>`, which the residual
|
|
/// ladder cannot. **CAPTURED INTO THE LAYER GRAPHS**, so it must be armed before `session_capture`.
|
|
std::string dump_halves;
|
|
/// P0.S8's routing trace, and a prerequisite the Phase 3 plan names explicitly. One record per layer per
|
|
/// position: `int32 layer, int32 k, k int32 ids, k float weights`. It is what a hit-rate curve for a
|
|
/// candidate VRAM expert cache is computed from, and it needs no new kernels - the doorbell already
|
|
/// publishes exactly this much to pinned memory.
|
|
std::string dump_routing;
|
|
bool no_capture = false; // run the layers directly instead of replaying graphs
|
|
bool no_pool = false; // skip the CPU expert pool: the GPU-only floor
|
|
bool sync_every_layer = false;
|
|
/// Per-stage CUDA-event timings inside the layer halves. `--no-capture` only: an event recorded inside a
|
|
/// stream capture is silently dropped, so the captured path cannot carry this.
|
|
bool stage_timing = false;
|
|
/// Launch the 48 captured `pre` graphs back to back with no host work between them and report the pure GPU
|
|
/// time per token. This is the only measurement that separates host-bound from GPU-bound, because the
|
|
/// stage events include every gap where the GPU waited for the host.
|
|
bool graph_only = false;
|
|
bool gpu_only_full = false; ///< R0.3: pre + post + head, the true per-token GPU floor
|
|
int pool_workers = 0; ///< R2.2: 0 = "all physical cores minus the host's"; >0 overrides
|
|
/// R2.2's first half, as an A/B arm. **ON by default**, because the measurement that justifies it is the
|
|
/// pool's own drain: 33.7 GB/s against 5/6 x 44.14 = 36.8 for five workers, on a machine whose sixth core
|
|
/// is reserved for a host thread that has nothing to do while the drain runs.
|
|
bool no_host_worker = false;
|
|
bool mmap_experts = false; ///< R2.1: opt OUT of the resident arena, back to MapViewOfFile
|
|
/// R4: slots of VRAM-resident experts. **0 = off, and off is the default.**
|
|
/// **THE COMMENT THAT USED TO BE HERE WAS FALSE AND ROUND 328 MEASURED IT.** It said "the cache has no
|
|
/// consumer yet - `moe_hit_grouped_s2` does not exist - so switching it on costs the fill traffic and
|
|
/// saves nothing". The kernel exists (`src/kernels/cuda/s2_expert_grouped.cu`), it is wired at line ~660
|
|
/// via `expert_hit_run`, and switching the cache on **does** move work off the CPU pool: the drain fell
|
|
/// **19.076 -> 10.312 ms/token** at 4096 per-layer slots, for **-2.7 ms/token** end to end. What was
|
|
/// true is that the ADMISSION POLICY gave every slot to the first position, which is why the earlier
|
|
/// measurement found nothing - see `expert_cache_per_layer`.
|
|
int expert_cache = 0;
|
|
bool expert_cache_cpu_order = false;
|
|
/// **R4.2g. ROUND 328 MEASURED THAT THE GLOBAL ADMISSION POLICY CANNOT WORK, AND THIS IS THE FIX.**
|
|
/// The default policy hands out slots in arrival order from one counter shared by all 48 layers, so the
|
|
/// first `n_slots` distinct pairs - about 26 LAYERS OF POSITION 0 - take every slot and hits are confined
|
|
/// to them. Measured at 256 slots: **1781 of 60000 = 2.97%**, against **21.4%** for 8 slots per layer and
|
|
/// **70.4%** for 64, from `Memory/cache_allocation.py` on the same run's routing. Off by default.
|
|
bool expert_cache_per_layer = false;
|
|
/// The PLE gather's prefetch, as an A/B arm. The gather measured 2.10-2.61 ms/token because its sixteen
|
|
/// row reads are sixteen SEPARATE page faults into a 26.8 GB mapping; see `ple_prefetch_enable`.
|
|
bool no_ple_prefetch = false;
|
|
/// R4.2e: a `profile.bin` from `tools/make_profile.py`. **When given, it decides residency instead of the
|
|
/// compulsory-miss policy**, which is the whole point: a profile ranked by routing frequency over a whole
|
|
/// trace is what the plan's `h = 0.6447` refers to, and compulsory-miss measured 0.4864 because it fills
|
|
/// with whatever the prompt touched FIRST. Empty means no profile.
|
|
std::string expert_profile;
|
|
/// R4.2d: **ON by default**, because the measurement is unambiguous and the alternative is known-broken.
|
|
/// Without it, 17 of 10,562 layers had the hit work done when the pool returned; with it, 9,190. The
|
|
/// A/B arm is `--no-hit-poke`.
|
|
bool no_hit_poke = false;
|
|
/// R0.9: capture each layer as THREE graphs and time them from outside the capture, which is the only
|
|
/// valid way to get a per-stage table on the real graph. Prints and exits; it is a measurement, not a run.
|
|
bool gpu_stages = false;
|
|
bool stats = false;
|
|
bool shared_late = false; ///< plan v0.3 P3 A/B: shared expert inside post[l] (old order)
|
|
bool keep_canonical = false; ///< plan v0.3 P1 A/B: load canonical copies of natively served tensors
|
|
bool no_token_graph = false; ///< plan v0.3 P3 A/B: two graphs per layer instead of one per token
|
|
bool no_fused_gr = false; ///< plan v0.3 P3 A/B: the six-kernel native gr_read + separate gr_write
|
|
bool no_fast_attn = false; ///< plan v0.3 P3 A/B: gather + one-block-per-head QSA attention
|
|
bool no_publish_kernel = false; ///< plan v0.3 P3 A/B: memcpy nodes for the doorbell and QSA step
|
|
bool no_fused_gdn = false; ///< plan v0.3 P3 A/B: llama.cpp-layout GDN step + separate out norm
|
|
bool no_fast_select = false; ///< plan v0.3 P7 A/B: FP64 row scores + bit-serial cell top-k
|
|
/// Plan v0.3 P4: `--expert-cache auto` sizes the VRAM tier from what is free after the weights, the session
|
|
/// and the KV state, minus this reserve for the graphs, the hit scratch and the head.
|
|
int vram_reserve_mib = 700;
|
|
/// Plan v0.3 P5: batched prompt processing in chunks of this many tokens (0 = the token path).
|
|
int64_t prefill_chunk = 0;
|
|
bool no_split_rows = false; ///< plan v0.3 P4 A/B: one whole expert per pool thread
|
|
/// Plan v0.3 P5: the prompt path borrows the top expert-cache slots for its buffers and refills them after
|
|
/// the prompt (default); `--no-prefill-borrow` reserves the buffers' VRAM for the whole session instead.
|
|
bool no_prefill_borrow = false;
|
|
/// Plan v0.3 P5 validation: batch only positions [0, P) and run the rest of the prompt through the token path
|
|
/// (teacher-forced), so the logits of positions >= P - which depend on the batched state - can be scored
|
|
/// against the oracle at many positions. 0 = the whole prompt but the last position.
|
|
int64_t prefill_until = 0;
|
|
/// Plan v0.3 P6: after every processed position, append the residual after the last layer (hc x n_embd
|
|
/// floats, the MTP draft head's input) to this file. Token path only.
|
|
std::string dump_final_r;
|
|
/// Plan v0.3 P6: speculative decoding with a verify window of this many tokens (the last accepted token and
|
|
/// spec-1 drafts); 0 = plain decode. `spec_oracle` drafts from a token file (the expected continuation, for
|
|
/// the exactness test); `spec_corrupt` N > 0 replaces every Nth draft with a wrong token.
|
|
int spec = 0;
|
|
std::string spec_oracle;
|
|
int spec_corrupt = 0;
|
|
/// Plan v0.3 P6: the MTP draft layer's runtime directory (tools/mtp_rt.py); drafts come from it.
|
|
std::string mtp;
|
|
int64_t mtp_window = 32768; ///< the draft layer attends to the last N cells (0 = every cell)
|
|
/// Plan v0.3 P6: the share (0..1) of each layer's distinct missed experts the GPU reads over PCIe from the
|
|
/// pinned arena while the CPU computes the rest (verify windows).
|
|
double pcie_frac = -1.0; ///< < 0: the model's default (0.2 direct for the Q2_0 pack, 0.55 DMA for native packs)
|
|
std::string pcie_mode = "auto"; ///< auto | dma | kernel | direct
|
|
/// Plan v0.3 P6: every `adapt_every` rounds, swap up to `adapt_swaps` of the most-routed missing experts into
|
|
/// the VRAM tier in place of the least-routed resident ones (decayed counts). 0 = static residency.
|
|
int adapt_every = 4;
|
|
/// Plan v0.3 P6: a draft enters the verify window only while every draft before it (and itself) has at least
|
|
/// this probability under the draft layer; 0 = always --spec-1 drafts.
|
|
double spec_min_p = 0.0;
|
|
/// Stop when the model emits an end-of-turn token (<|endoftext|> 248044, <|im_end|> 248046, or --eos-ids).
|
|
bool stop_eos = false;
|
|
std::vector<int64_t> eos_ids = {248044, 248046};
|
|
bool spec_split = false; ///< opt-in split verify window (the overlap study: exact, ~7% slower)
|
|
/// Plan v0.3 P8: stay resident and take requests on stdin (see the --serve block in main).
|
|
bool serve = false;
|
|
/// The vision path: keep a per-cell (t, h, w) rotary position table so --serve can take GENI requests.
|
|
bool vision = false;
|
|
/// --serve prompt cache: checkpoints of the sequence state kept in host memory (0 = every request starts
|
|
/// from an empty sequence). A request continues from the longest prefix the session or a checkpoint holds.
|
|
int prompt_cache = 16;
|
|
/// Host memory for sequences the live one replaced (their K/V cells), in MiB.
|
|
int64_t cache_ram_mib = 16384;
|
|
/// Checkpoint interval inside long prompts (positions that are multiples of it).
|
|
int64_t cache_every = 16384;
|
|
/// Prompt remainders of up to this many tokens go through verify windows instead of the batched prompt path,
|
|
/// which lends and refills expert-cache slots on every call.
|
|
int64_t feed_max = 256;
|
|
int adapt_swaps = 96;
|
|
};
|
|
|
|
void usage() {
|
|
std::fprintf(stderr,
|
|
"strata generate --pack DIR --tokens \"1,2,3\" [options]\n"
|
|
"\n"
|
|
" --pack DIR the pack directory (default pack/full)\n"
|
|
" --tokens LIST the prompt as comma-separated token IDS (required)\n"
|
|
" --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n"
|
|
" --ple-gguf PATH the PLE table: the model shard holding per_layer_token_embd (with --native,\n"
|
|
" the --native model's shard that holds it by default)\n"
|
|
" --no-ple explicit diagnostic ablation of the PLE layer\n"
|
|
" --ple-io direct|mmap n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n"
|
|
" reads, the table never enters RAM or the file cache; mmap: A/B arm\n"
|
|
" --ple-row-cache N bounded cache of fetched rows, 90 B each (default 1048576; 0 = off)\n"
|
|
" --ple-inflight N outstanding SSD reads (default 64)\n"
|
|
" --ple-delay-us U fault injection: each row read completes no earlier than U us\n"
|
|
" --ple-sync-submit A/B arm: submit table reads on the token thread (default: an I/O thread)\n"
|
|
" --kv fp16|int8 KV storage (plan v0.3 P7): int8 codes + fp16 scale per 64 values, half the\n"
|
|
" VRAM; default fp16 until gate G-C accepts int8\n"
|
|
" --stream-token enqueue token work on the session stream (experimental)\n"
|
|
" --check-logits copy and check all logits in the stream-token path\n"
|
|
" --gr-fp32-activations experimental CUDA-oracle GR activation precision\n"
|
|
" --gr-native-mmvf experimental pinned GR norm/projections; implies FP32 activations\n"
|
|
" --native-bf16 experimental CUDA-oracle SSM/router/indexer BF16 projections\n"
|
|
" --native-bf16-extra experimental CUDA-oracle PLE/shared gate BF16 projections\n"
|
|
" --native-ple-key experimental native PLE key; requires --native-dense-gguf\n"
|
|
" --native-moe-combine experimental pinned CUDA routed/shared combination\n"
|
|
" --native-gdn experimental pinned CUDA GDN norms/gates/recurrence\n"
|
|
" --native-flash-attn-short diagnostic pinned vector attention; --max-context <=256\n"
|
|
" --native-qsa-indexer experimental pinned indexer key cache and pooling\n"
|
|
" --native-qsa experimental pinned QSA normalization and output gate\n"
|
|
" --native-rope experimental pinned text-only CUDA rotary arithmetic\n"
|
|
" --native-ple-postops experimental pinned PLE postprojection arithmetic\n"
|
|
" --native-router experimental pinned CUDA 512-expert top-10 routing\n"
|
|
" --cpu-oracle-q8-0 experimental pinned CPU expert quantization and dot reduction\n"
|
|
" --native SHARD1 the model's first GGUF shard (the others of a split model are found by\n"
|
|
" name) and every full-context native path at once (plan v0.3 P1): stream-token,\n"
|
|
" GR MMVF, BF16, head, dense + PLE key, MoE combine, GDN, router, QSA,\n"
|
|
" indexer, RoPE, PLE postops, and the CPU q8_0 contract unless the\n"
|
|
" expert cache is on. Individual --native-* flags stay for A/B.\n"
|
|
" --native-head-gguf PATH native head from the model with this first shard; requires --stream-token\n"
|
|
" --native-dense-gguf PATH native GDN/QSA/shared projections; repeat for each source model shard\n"
|
|
" --expert-cache-cpu-order experimental GPU expert reduction matching CPU order\n"
|
|
" --max-new N tokens to generate (default 16)\n"
|
|
" --max-context N KV/state capacity (default 4096)\n"
|
|
" --greedy argmax (the default)\n"
|
|
" --seed S enable sampling with this Philox seed\n"
|
|
" --top-k N --top-p F --temperature F\n"
|
|
" --dump-logits PATH write one line of raw logits per position\n"
|
|
" --logits-stride N store every Nth row plus final input (default 1); N>1 requires --max-new 1\n"
|
|
" --dump-residual PATH write the final R (hc x n_embd, f32) for head bisection\n"
|
|
" --dump-layers PATH write R after EVERY layer, per position: the C1 bisection ladder\n"
|
|
" --dump-halves PATH write both halves' block_out and inject per layer: the half bisection\n"
|
|
" --dump-routing PATH write the routed expert ids and weights per layer per position (P0.S8)\n"
|
|
" --no-capture run the layers directly instead of replaying graphs\n"
|
|
" --shared-late A/B: shared expert after the CPU pool (default: overlapped with it)\n"
|
|
" --keep-canonical A/B: also load canonical copies of natively served tensors (more VRAM)\n"
|
|
" --vision --serve takes images too (GENI requests; embeddings from strata-vision)\n"
|
|
" --prompt-cache N --serve: keep N checkpoints of the sequence state in host memory and\n"
|
|
" continue each request from the longest cached prefix (default 16;\n"
|
|
" 0 = every request starts from an empty sequence)\n"
|
|
" --cache-every N checkpoint interval inside long prompts (default 16384)\n"
|
|
" --cache-ram MIB --serve: host memory for the K/V cells of sequences a request replaced,\n"
|
|
" so switching back to them continues where they were (default 16384)\n"
|
|
" --feed-max N --serve: prompt remainders up to N tokens run through verify windows\n"
|
|
" instead of the batched prompt path (default 256)\n"
|
|
" --no-token-graph A/B: two graphs per layer (the host launches each) instead of one per token\n"
|
|
" --no-fused-gr A/B: the six-kernel hyper-connection read and a separate write (native)\n"
|
|
" --prefill CHUNK batched prompt processing in chunks of CHUNK tokens (needs --native)\n"
|
|
" --no-pool skip the CPU expert pool (the GPU-only floor)\n"
|
|
" --sync-every-layer debug: synchronise after every layer\n"
|
|
" --dump-mixed PATH write the post-attention residual (n_embd, f32)\n"
|
|
" --stage-timing per-stage KERNEL-COUNT shares. NOT a time profile: an uncaptured\n"
|
|
" event interval includes host gaps, so run with --gpu-only-full first\n"
|
|
" --graph-only MEASURE: replay the 48 `pre` graphs only. OMITS the 48 `post` graphs\n"
|
|
" and the LM head, so it is NOT the GPU floor (R0.3, Memory/ERRORS.md A4)\n"
|
|
" --gpu-only-full MEASURE: replay pre+post for all 48 layers plus the LM head, no pool.\n"
|
|
" THE TRUE PER-TOKEN GPU FLOOR. Quote this one, not --graph-only.\n"
|
|
" --stats print the per-stage breakdown\n"
|
|
" --gpu-stages R0.9: capture the layer as three graphs (mixer / ffn+router / post)\n"
|
|
" and time them from OUTSIDE the capture. The per-stage table on the\n"
|
|
" real graph that --stage-timing cannot give. Prints and exits.\n"
|
|
" --expert-profile P R4.2e: pre-load the VRAM tier from a `profile.bin` (see\n"
|
|
" tools/make_profile.py) instead of admitting on first use.\n"
|
|
" --no-hit-poke R4.2d's A/B arm. The hit path pokes the driver once right after its\n"
|
|
" launch so the GPU starts while the CPU pool runs; without it the work\n"
|
|
" waits for the next driver entry and does not overlap at all.\n"
|
|
" --no-ple-prefetch A/B arm: read the PLE table's sixteen rows one at a time, instead of\n"
|
|
" issuing them in one PrefetchVirtualMemory call.\n"
|
|
" --expert-cache N R4: keep N expert blobs resident in VRAM and compute their rows on the\n"
|
|
" GPU via `moe_hit_grouped_s2`. DEFAULT 0. Measured at 4096 slots\n"
|
|
" with --expert-cache-per-layer: 54.4%% hits, CPU pool drain 19.1 -> 10.3\n"
|
|
" ms/token, -2.7 ms/token end to end.\n"
|
|
" --expert-cache-per-layer R4.2g: give each layer its OWN slots instead of letting the first\n"
|
|
" position take all of them. The default policy fills in arrival order\n"
|
|
" from one shared counter, so 256 slots went to ~26 layers of position 0\n"
|
|
" and measured **2.97%%**. Per-layer, the same routing gives 21.4%% at 8\n"
|
|
" slots/layer and 70.4%% at 64.\n"
|
|
" --no-host-worker R2.2: the A/B arm. By default the HOST THREAD joins the drain, so the\n"
|
|
" pool is six threads on six cores instead of five plus an idle core;\n"
|
|
" this flag restores the five-worker form for comparison on `pool phases`.\n"
|
|
" --pool-workers N R2.2: CPU expert pool worker count. Default 0 = every physical core\n"
|
|
" except the one the host loop spins on. A sweep is how the pool's\n"
|
|
" deviation from `cpu_s2` is attributed.\n"
|
|
" --mmap-experts R2.1: opt OUT of the resident expert arena, back to MapViewOfFile.\n"
|
|
" The A/B arm: the mmap's rate depends on the OS page cache holding\n"
|
|
" 34 GB, and measured 71.97 vs 34.78 ms/token cold vs warm.\n");
|
|
}
|
|
|
|
bool parse_i64_list(const char* s, std::vector<int64_t>& out, std::string& err) {
|
|
out.clear();
|
|
std::string text(s);
|
|
for (char& c : text) if (c == ',') c = ' ';
|
|
std::istringstream input(text);
|
|
std::string token;
|
|
while (input >> token) {
|
|
int32_t id = 0;
|
|
const auto parsed = std::from_chars(token.data(), token.data() + token.size(), id);
|
|
if (parsed.ec != std::errc{} || parsed.ptr != token.data() + token.size() || id < 0) {
|
|
err = "invalid token id: expected an integer in [0, 2147483647]";
|
|
out.clear();
|
|
return false;
|
|
}
|
|
out.push_back(id);
|
|
}
|
|
if (out.empty()) { err = "token list was empty"; return false; }
|
|
return true;
|
|
}
|
|
|
|
/// The pool's adapter plus the wall-clock it spent, so the report can say how much of the token was the CPU.
|
|
struct Drive {
|
|
strata::core::ExpertDispatch d;
|
|
double cpu_ms = 0;
|
|
int64_t calls = 0;
|
|
/// THE ROUTING TRACE, which is P0.S8 and a stated prerequisite of Phase 3. `drive_pool` is called once
|
|
/// per layer from the main loop - the workers live inside `expert_pool_dispatch` - so a single FILE* here
|
|
/// needs no locking. `d.layers` is the CURRENT layer on entry (the adapter increments it as it walks the
|
|
/// blob), which is why the layer index comes from there rather than from a counter of our own.
|
|
std::FILE* routing = nullptr;
|
|
};
|
|
|
|
void drive_pool(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd, int64_t k,
|
|
float* out) {
|
|
Drive* t = (Drive*) user;
|
|
const Clock::time_point a = Clock::now();
|
|
strata::core::expert_pool_dispatch(&t->d, x_f, ids, weights, n_embd, k, out);
|
|
t->cpu_ms += std::chrono::duration<double, std::milli>(Clock::now() - a).count();
|
|
++t->calls;
|
|
// THE ROUTING TRACE. Written AFTER the dispatch so the layer index is still this layer's: `d.layers` is
|
|
// advanced by the adapter as it consumes the blob, and reading it after the call is the same value the
|
|
// dispatch used. Record = int32 layer, int32 k, k int32 ids, k float weights.
|
|
if (t->routing != nullptr) {
|
|
// **`d.layers` HAS ALREADY BEEN ADVANCED BY THE TIME THIS RUNS, AND THE FIRST TRACE WAS OFF BY ONE
|
|
// BECAUSE OF IT.** The adapter walks the blob by incrementing `d.layers` as it consumes each layer's
|
|
// experts, so after the dispatch it holds the NEXT layer's index. `tools/make_profile.py` caught it
|
|
// with a bounds check when the trace turned out to span 1..48 instead of 0..47. The hit-rate CURVE was
|
|
// unaffected - it is a per-layer split, and shifting every layer by one preserves both metrics - but
|
|
// anything keyed on the layer index, which is exactly what a cache profile is, would have been wrong.
|
|
const int32_t layer_idx = (int32_t) (t->d.layers - 1);
|
|
if (layer_idx < 0 || layer_idx >= 48) {
|
|
std::fprintf(stderr, "strata generate: the routing trace saw layer %d, outside 0..47\n", layer_idx);
|
|
return;
|
|
}
|
|
const int32_t rec[2] = {layer_idx, (int32_t) k};
|
|
std::fwrite(rec, sizeof rec, 1, t->routing);
|
|
std::fwrite(ids, sizeof(int32_t), (size_t) k, t->routing);
|
|
std::fwrite(weights, sizeof(float), (size_t) k, t->routing);
|
|
}
|
|
}
|
|
|
|
/// Plan v0.3 P6: the pool for a verify window.
|
|
void drive_pool_multi(void* user, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, float* out,
|
|
int64_t layer) {
|
|
Drive* t = (Drive*) user;
|
|
t->d.layers = layer;
|
|
const Clock::time_point a = Clock::now();
|
|
strata::core::expert_pool_dispatch_multi(t->d, x_f, ids, n_tok, k, out);
|
|
t->cpu_ms += std::chrono::duration<double, std::milli>(Clock::now() - a).count();
|
|
++t->calls;
|
|
}
|
|
|
|
int argmax(const std::vector<float>& v) {
|
|
int best = 0;
|
|
for (size_t i = 1; i < v.size(); ++i)
|
|
if (v[i] > v[best]) best = (int) i;
|
|
return best;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
int main(int argc, char** argv) {
|
|
// **UNBUFFERED, BECAUSE THE INTERESTING OUTPUT IS THE OUTPUT BEFORE A CRASH.** `stdout` redirected to a
|
|
// pipe or a file is block-buffered, so a program that dies loses every line it had already printed - which
|
|
// turns "it crashed at step 7" into "it crashed somewhere", and the difference is a debugging session.
|
|
std::setvbuf(stdout, nullptr, _IONBF, 0);
|
|
Options o;
|
|
bool have_tokens = false;
|
|
bool have_logits_stride = false;
|
|
for (int i = 1; i < argc; ++i) {
|
|
const std::string a = argv[i];
|
|
auto next = [&](const char* what) -> const char* {
|
|
if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", what); std::exit(2); }
|
|
return argv[++i];
|
|
};
|
|
if (a == "--help" || a == "-h") { usage(); return 0; }
|
|
else if (a == "--pack") o.pack = next("--pack");
|
|
else if (a == "--tokens") {
|
|
if (have_tokens) { std::fprintf(stderr, "supply one token input only\n"); return 2; }
|
|
std::string e;
|
|
if (!parse_i64_list(next("--tokens"), o.tokens, e)) { std::fprintf(stderr, "%s\n", e.c_str()); return 2; }
|
|
have_tokens = true;
|
|
}
|
|
else if (a == "--tokens-file") {
|
|
if (have_tokens) { std::fprintf(stderr, "supply one token input only\n"); return 2; }
|
|
std::ifstream input(next("--tokens-file"));
|
|
if (!input) { std::fprintf(stderr, "cannot open token file\n"); return 2; }
|
|
std::string text((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());
|
|
if (input.bad()) { std::fprintf(stderr, "cannot read token file\n"); return 2; }
|
|
std::string error;
|
|
if (text.find('\0') != std::string::npos || !parse_i64_list(text.c_str(), o.tokens, error)) {
|
|
std::fprintf(stderr, "malformed token file: %s\n", error.c_str()); return 2;
|
|
}
|
|
have_tokens = true;
|
|
}
|
|
else if (a == "--max-new") o.max_new = std::atoll(next("--max-new"));
|
|
else if (a == "--max-context") o.max_context = std::atoll(next("--max-context"));
|
|
else if (a == "--greedy") o.greedy = true;
|
|
else if (a == "--seed") { o.seed = (uint64_t) std::atoll(next("--seed")); o.greedy = false; }
|
|
else if (a == "--top-k") o.top_k = std::atoi(next("--top-k"));
|
|
else if (a == "--top-p") o.top_p = (float) std::atof(next("--top-p"));
|
|
else if (a == "--temperature") o.temperature = (float) std::atof(next("--temperature"));
|
|
else if (a == "--dump-logits") o.dump_logits = next("--dump-logits");
|
|
else if (a == "--logits-stride") {
|
|
if (have_logits_stride) { std::fprintf(stderr, "--logits-stride must be supplied only once\n"); return 2; }
|
|
if (!strata::program::logits_selection::parse_stride(next("--logits-stride"), o.logits_stride)) {
|
|
std::fprintf(stderr, "--logits-stride requires a positive decimal int64\n"); return 2;
|
|
}
|
|
have_logits_stride = true;
|
|
}
|
|
else if (a == "--dump-residual") o.dump_residual = next("--dump-residual");
|
|
else if (a == "--dump-mixed") o.dump_mixed = next("--dump-mixed");
|
|
else if (a == "--dump-layers") o.dump_layers = next("--dump-layers");
|
|
else if (a == "--dump-halves") o.dump_halves = next("--dump-halves");
|
|
else if (a == "--dump-routing") o.dump_routing = next("--dump-routing");
|
|
else if (a == "--ple-gguf") o.ple_gguf = next("--ple-gguf");
|
|
else if (a == "--no-ple") o.no_ple = true;
|
|
else if (a == "--ple-io") o.ple_io = next("--ple-io");
|
|
else if (a == "--ple-row-cache") o.ple_row_cache = std::atoll(next("--ple-row-cache"));
|
|
else if (a == "--ple-inflight") o.ple_inflight = std::atoi(next("--ple-inflight"));
|
|
else if (a == "--ple-delay-us") o.ple_delay_us = std::atof(next("--ple-delay-us"));
|
|
else if (a == "--ple-sync-submit") o.ple_sync_submit = true;
|
|
else if (a == "--kv") o.kv = next("--kv");
|
|
else if (a == "--stream-token") o.stream_token = true;
|
|
else if (a == "--check-logits") o.check_logits = true;
|
|
else if (a == "--gr-fp32-activations") o.gr_fp32_activations = true;
|
|
else if (a == "--gr-native-mmvf") o.gr_native_mmvf = true;
|
|
else if (a == "--native-bf16") o.native_bf16 = true;
|
|
else if (a == "--native-bf16-extra") o.native_bf16_extra = true;
|
|
else if (a == "--native-ple-key") o.native_ple_key = true;
|
|
else if (a == "--native-moe-combine") o.native_moe_combine = true;
|
|
else if (a == "--native-gdn") o.native_gdn = true;
|
|
else if (a == "--native-flash-attn-short") o.native_flash_attn_short = true;
|
|
else if (a == "--native-qsa-indexer") o.native_qsa_indexer = true;
|
|
else if (a == "--native-qsa") o.native_qsa = true;
|
|
else if (a == "--native-rope") o.native_rope = true;
|
|
else if (a == "--native-ple-postops") o.native_ple_postops = true;
|
|
else if (a == "--native-router") o.native_router = true;
|
|
else if (a == "--cpu-oracle-q8-0") o.cpu_oracle_q8_0 = true;
|
|
else if (a == "--native") o.native_preset = next("--native");
|
|
else if (a == "--native-head-gguf") o.native_head_gguf = next("--native-head-gguf");
|
|
else if (a == "--native-dense-gguf") o.native_dense_gguf.push_back(next("--native-dense-gguf"));
|
|
else if (a == "--no-capture") o.no_capture = true;
|
|
else if (a == "--no-pool") o.no_pool = true;
|
|
else if (a == "--sync-every-layer") o.sync_every_layer = true;
|
|
else if (a == "--stage-timing") o.stage_timing = true;
|
|
else if (a == "--graph-only") o.graph_only = true;
|
|
else if (a == "--gpu-only-full") o.gpu_only_full = true;
|
|
else if (a == "--pool-workers") o.pool_workers = std::atoi(next("--pool-workers"));
|
|
else if (a == "--no-host-worker") o.no_host_worker = true;
|
|
else if (a == "--no-ple-prefetch") o.no_ple_prefetch = true;
|
|
else if (a == "--expert-cache") {
|
|
const std::string v = next("--expert-cache");
|
|
o.expert_cache = (v == "auto") ? -1 : std::atoi(v.c_str());
|
|
}
|
|
else if (a == "--vram-reserve-mib") o.vram_reserve_mib = std::atoi(next("--vram-reserve-mib"));
|
|
else if (a == "--prefill") o.prefill_chunk = std::atoll(next("--prefill"));
|
|
else if (a == "--no-split-rows") o.no_split_rows = true;
|
|
else if (a == "--no-prefill-borrow") o.no_prefill_borrow = true;
|
|
else if (a == "--prefill-until") o.prefill_until = std::atoll(next("--prefill-until"));
|
|
else if (a == "--dump-final-r") o.dump_final_r = next("--dump-final-r");
|
|
else if (a == "--spec") o.spec = std::atoi(next("--spec"));
|
|
else if (a == "--spec-oracle") o.spec_oracle = next("--spec-oracle");
|
|
else if (a == "--spec-corrupt") o.spec_corrupt = std::atoi(next("--spec-corrupt"));
|
|
else if (a == "--mtp") o.mtp = next("--mtp");
|
|
else if (a == "--mtp-window") o.mtp_window = std::atoll(next("--mtp-window"));
|
|
else if (a == "--pcie-frac") o.pcie_frac = std::atof(next("--pcie-frac"));
|
|
else if (a == "--adapt-every") o.adapt_every = std::atoi(next("--adapt-every"));
|
|
else if (a == "--spec-min-p") o.spec_min_p = std::atof(next("--spec-min-p"));
|
|
else if (a == "--stop-eos") o.stop_eos = true;
|
|
else if (a == "--spec-split") o.spec_split = true;
|
|
else if (a == "--pcie-mode") o.pcie_mode = next("--pcie-mode");
|
|
else if (a == "--serve") o.serve = true;
|
|
else if (a == "--vision") o.vision = true;
|
|
else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache")));
|
|
else if (a == "--cache-every") o.cache_every = std::max<int64_t>(1, std::atoll(next("--cache-every")));
|
|
else if (a == "--cache-ram") o.cache_ram_mib = std::max<int64_t>(0, std::atoll(next("--cache-ram")));
|
|
else if (a == "--feed-max") o.feed_max = std::max<int64_t>(0, std::atoll(next("--feed-max")));
|
|
else if (a == "--no-spec-split") o.spec_split = false;
|
|
else if (a == "--eos-ids") {
|
|
std::string e;
|
|
if (!parse_i64_list(next("--eos-ids"), o.eos_ids, e)) { std::fprintf(stderr, "--eos-ids: %s\n", e.c_str()); return 2; }
|
|
o.stop_eos = true;
|
|
}
|
|
else if (a == "--adapt-swaps") o.adapt_swaps = std::atoi(next("--adapt-swaps"));
|
|
else if (a == "--expert-cache-cpu-order") o.expert_cache_cpu_order = true;
|
|
else if (a == "--expert-cache-per-layer") o.expert_cache_per_layer = true;
|
|
else if (a == "--no-hit-poke") o.no_hit_poke = true;
|
|
else if (a == "--expert-profile") o.expert_profile = next("--expert-profile");
|
|
else if (a == "--gpu-stages") o.gpu_stages = true;
|
|
else if (a == "--mmap-experts") o.mmap_experts = true;
|
|
else if (a == "--stats") o.stats = true;
|
|
else if (a == "--shared-late") o.shared_late = true;
|
|
else if (a == "--keep-canonical") o.keep_canonical = true;
|
|
else if (a == "--no-token-graph") o.no_token_graph = true;
|
|
else if (a == "--no-fused-gr") o.no_fused_gr = true;
|
|
else if (a == "--no-fast-attn") o.no_fast_attn = true;
|
|
else if (a == "--no-publish-kernel") o.no_publish_kernel = true;
|
|
else if (a == "--no-fused-gdn") o.no_fused_gdn = true;
|
|
else if (a == "--no-fast-select") o.no_fast_select = true;
|
|
else {
|
|
// An unknown flag is an ERROR and not a warning: a typo'd `--max-neww` that silently generated 16
|
|
// tokens would look like a working run.
|
|
std::fprintf(stderr, "unknown argument: %s\n", a.c_str());
|
|
usage();
|
|
return 2;
|
|
}
|
|
}
|
|
if (!have_tokens && o.serve) { // plan v0.3 P8: requests bring their own tokens
|
|
o.tokens = {248045};
|
|
o.max_new = 1;
|
|
have_tokens = true;
|
|
o.stop_eos = true;
|
|
}
|
|
if (!have_tokens) {
|
|
std::fprintf(stderr, "strata generate: --tokens is required (this build has no tokenizer; see the "
|
|
"header of src/program/generate.cpp)\n");
|
|
usage();
|
|
return 2;
|
|
}
|
|
|
|
if ((o.ple_io != "direct" && o.ple_io != "mmap") || o.ple_row_cache < 0 || o.ple_inflight < 1 ||
|
|
o.ple_inflight > 1024 || !(o.ple_delay_us >= 0)) {
|
|
std::fprintf(stderr, "strata generate: invalid --ple-io/--ple-row-cache/--ple-inflight/--ple-delay-us\n");
|
|
return 2;
|
|
}
|
|
if (o.kv != "fp16" && o.kv != "int8") {
|
|
std::fprintf(stderr, "strata generate: --kv must be fp16 or int8\n");
|
|
return 2;
|
|
}
|
|
strata::core::qsa_set_kv_int8(o.kv == "int8");
|
|
strata::core::layer_set_shared_early(!o.shared_late);
|
|
std::vector<std::string> native_shards; // the --native model's GGUF shards
|
|
if (!o.native_preset.empty()) {
|
|
if (o.no_ple) {
|
|
std::fprintf(stderr, "strata generate: --native requires the PLE (the PLE key is native too)\n");
|
|
return 2;
|
|
}
|
|
try {
|
|
native_shards = strata::gguf_split_paths(o.native_preset);
|
|
} catch (const std::exception& e) {
|
|
std::fprintf(stderr, "strata generate: --native: %s\n", e.what());
|
|
return 2;
|
|
}
|
|
if (o.ple_gguf.empty()) o.ple_gguf = strata::kernels::ple_table_shard(native_shards);
|
|
if (o.ple_gguf.empty()) {
|
|
std::fprintf(stderr, "strata generate: no shard of the --native model holds per_layer_token_embd; "
|
|
"name the file with --ple-gguf\n");
|
|
return 2;
|
|
}
|
|
o.stream_token = true;
|
|
o.gr_native_mmvf = true;
|
|
o.native_bf16 = o.native_bf16_extra = true;
|
|
o.native_ple_key = o.native_moe_combine = o.native_gdn = o.native_router = true;
|
|
o.native_qsa = o.native_qsa_indexer = o.native_rope = o.native_ple_postops = true;
|
|
if (o.native_head_gguf.empty()) o.native_head_gguf = o.native_preset;
|
|
if (o.native_dense_gguf.empty()) {
|
|
o.native_dense_gguf = native_shards;
|
|
if (std::find(native_shards.begin(), native_shards.end(), o.ple_gguf) == native_shards.end())
|
|
o.native_dense_gguf.push_back(o.ple_gguf);
|
|
}
|
|
// Plan v0.3 (24 Sep): the CPU experts stay on the VNNI kernel. The llama.cpp-CPU-exact q8_0 contract
|
|
// cost 27.0 vs 17.2 ms/token of pool time and G-C does not need it; `--cpu-oracle-q8-0` still selects it.
|
|
}
|
|
if (o.logits_stride > 1 && (o.max_new != 1 || o.dump_logits.empty())) {
|
|
std::fprintf(stderr, "strata generate: --logits-stride > 1 requires --max-new 1 and --dump-logits\n");
|
|
return 2;
|
|
}
|
|
if (o.no_ple && !o.ple_gguf.empty()) {
|
|
std::fprintf(stderr, "strata generate: --no-ple and --ple-gguf are mutually exclusive\n");
|
|
return 2;
|
|
}
|
|
if (o.native_ple_postops && o.no_ple) {
|
|
std::fprintf(stderr, "strata generate: --native-ple-postops requires PLE enabled\n");
|
|
return 2;
|
|
}
|
|
if (!o.no_ple && o.ple_gguf.empty()) {
|
|
std::fprintf(stderr, "strata generate: --ple-gguf is required; --no-ple explicitly enables a diagnostic ablation\n");
|
|
return 2;
|
|
}
|
|
// P7 audit: positions, cells and pooled-block indices are cast to int32 on the device path.
|
|
if (o.max_context > 2147483647LL - 8) {
|
|
std::fprintf(stderr, "strata generate: --max-context must be below 2^31\n");
|
|
return 2;
|
|
}
|
|
if (o.max_new <= 0 || o.max_context <= 0 || o.max_new > o.max_context ||
|
|
o.tokens.size() > (size_t) (o.max_context - o.max_new)) {
|
|
std::fprintf(stderr, "strata generate: positive --max-new and --max-context must fit the prompt and generation\n");
|
|
return 2;
|
|
}
|
|
if (!std::isfinite(o.temperature) || o.temperature < 0 || !std::isfinite(o.top_p) ||
|
|
o.top_p <= 0 || o.top_p > 1 || o.top_k < 0 || o.expert_cache < -1 || o.pool_workers < 0) {
|
|
std::fprintf(stderr, "strata generate: invalid sampling or resource parameter\n");
|
|
return 2;
|
|
}
|
|
|
|
if (o.native_flash_attn_short && o.max_context > 256) {
|
|
std::fprintf(stderr, "strata generate: --native-flash-attn-short requires --max-context <=256\n");
|
|
return 2;
|
|
}
|
|
if (o.native_flash_attn_short && (o.gpu_only_full || o.graph_only || o.gpu_stages)) {
|
|
std::fprintf(stderr, "strata generate: --native-flash-attn-short requires the normal decode loop for status validation\n");
|
|
return 2;
|
|
}
|
|
if (o.native_ple_key && (o.native_dense_gguf.empty() || o.no_ple)) {
|
|
std::fprintf(stderr, "strata generate: --native-ple-key requires PLE and --native-dense-gguf\n");
|
|
return 2;
|
|
}
|
|
if (o.cpu_oracle_q8_0 && (o.expert_cache != 0 || !o.expert_profile.empty())) {
|
|
std::fprintf(stderr, "strata generate: --cpu-oracle-q8-0 cannot be combined with --expert-cache or --expert-profile until the GPU expert contract matches\n");
|
|
return 2;
|
|
}
|
|
|
|
// **BEFORE ANYTHING ELSE.** The CPU expert kernel is AVX-512 (VNNI + VBMI) and its translation unit is
|
|
// compiled `/arch:AVX512`, so on a CPU without those features it does not fail - it executes an illegal
|
|
// instruction at some unpredictable token. Refusing at second zero is the whole point of P2.S3's check.
|
|
strata::kernels::cpu::expert_set_oracle_q8_0(o.cpu_oracle_q8_0);
|
|
|
|
std::string err;
|
|
if (!o.native_head_gguf.empty() && !o.stream_token) {
|
|
std::fprintf(stderr, "--native-head-gguf requires --stream-token\n");
|
|
return 2;
|
|
}
|
|
// Plan v0.3 P6: where the experts live. A native pack (tools/iq_pack.py: the IQ2_XS / IQ3_XXS files) keeps
|
|
// every quantized tensor in its GGUF form, so it needs --native (the dense projections, head and embedding
|
|
// come from the model file) and runs its experts in verify windows only (--spec).
|
|
{
|
|
const strata::core::ModelGeometry g0;
|
|
if (!strata::kernels::cpu::expert_layout_load(o.pack, g0.n_layers, g0.n_expert, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
}
|
|
const bool native_pack = strata::kernels::cpu::expert_layout().native;
|
|
if (native_pack)
|
|
for (int64_t l = 0; l < strata::kernels::cpu::expert_layout().n_layers; ++l) {
|
|
const auto& f = strata::kernels::cpu::expert_layout().fmt[(size_t) l];
|
|
if (!strata::kernels::native_expert_supported(f.gu_type, f.d_type, f.n_embd, f.n_ff)) {
|
|
std::fprintf(stderr, "strata generate: layer %lld's experts (GGML types %d / %d) have no GPU kernels\n",
|
|
(long long) l, f.gu_type, f.d_type);
|
|
return 1;
|
|
}
|
|
}
|
|
// plan v0.3 P6: the PCIe share of the missed experts, measured per kind of pack (the paper, finding on PCIe)
|
|
if (o.pcie_frac < 0.0) o.pcie_frac = native_pack ? 0.55 : 0.2;
|
|
// the canonical Q2_0 pack's CPU kernels are AVX-512 only; a native pack runs on AVX2 CPUs as well
|
|
if (!native_pack) strata::kernels::cpu::cpu_require_expert_support();
|
|
else if (!strata::kernels::cpu::cpu_avx512_ok())
|
|
std::fprintf(stderr, "strata generate: this CPU has no AVX-512: the expert kernels run on AVX2\n");
|
|
strata::core::NativeEmbed native_embed;
|
|
if (native_pack) {
|
|
if (o.native_preset.empty() || o.spec < 2 || o.keep_canonical ||
|
|
(o.prefill_chunk <= 0 && o.tokens.size() > 1)) {
|
|
std::fprintf(stderr, "strata generate: %s is a native (IQ) pack: it needs --native SHARD1, --spec T (T >= 2) "
|
|
"and --prefill CHUNK\n", o.pack.c_str());
|
|
return 2;
|
|
}
|
|
const strata::core::ModelGeometry g0;
|
|
if (!native_embed.load(native_shards, g0.n_embd, 248320, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
strata::core::set_native_embed(&native_embed);
|
|
std::fprintf(stderr, "strata generate: native pack: %s experts (largest blob %.2f MB), token embedding "
|
|
"type %d in mapped host memory (%.0f MiB)\n",
|
|
o.pack.c_str(), (double) strata::kernels::cpu::expert_layout().max_blob / 1e6,
|
|
native_embed.type(), (double) native_embed.bytes() / 1048576.0);
|
|
}
|
|
// Plan v0.3 P1: tensors served in native form are not also loaded in canonical form (~2.7 GB of VRAM back
|
|
// to the expert cache with --native). `--keep-canonical` loads both, as before.
|
|
std::set<std::string> skip;
|
|
if (!o.keep_canonical) {
|
|
if (!o.native_dense_gguf.empty() &&
|
|
!strata::core::NativeDense::served_names(o.native_dense_gguf, o.native_ple_key, skip, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
if (!o.native_head_gguf.empty()) skip.insert("output.weight");
|
|
// the PLE module validates its canonical key at construction (8 MB); a native pack has none to load
|
|
if (!native_pack) skip.erase("blk.1.ple_key.weight");
|
|
if (native_pack) skip.insert("token_embd.weight");
|
|
}
|
|
uint64_t pool_bytes = 0;
|
|
if (!strata::core::WeightTable::pool_bytes(o.pack, pool_bytes, err, skip.empty() ? nullptr : &skip)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
void* arena = nullptr;
|
|
if (cudaMalloc(&arena, pool_bytes) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: cudaMalloc(%llu) for the weight arena failed\n",
|
|
(unsigned long long) pool_bytes);
|
|
return 1;
|
|
}
|
|
strata::core::WeightTable wt;
|
|
if (!wt.load(o.pack, arena, pool_bytes, err, skip.empty() ? nullptr : &skip)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
std::fprintf(stderr, "strata generate: %llu MiB of weights loaded from %s (%zu canonical tensors skipped: "
|
|
"served natively)\n",
|
|
(unsigned long long) (pool_bytes >> 20), o.pack.c_str(), skip.size());
|
|
|
|
strata::core::NativeDense native_dense;
|
|
if (!o.native_dense_gguf.empty()) {
|
|
if (!native_dense.load(o.native_dense_gguf, wt, err, o.native_ple_key)) {
|
|
std::fprintf(stderr, "strata generate: native dense projections: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
std::fprintf(stderr, "strata generate: %zu native projection matrices, %.2f MiB of weights\n",
|
|
native_dense.tensor_count(), (double) native_dense.weight_bytes() / (1024.0 * 1024.0));
|
|
}
|
|
|
|
strata::kernels::gr_set_fp32_activations(o.gr_fp32_activations);
|
|
strata::kernels::gr_set_native_mmvf(o.gr_native_mmvf);
|
|
// Plan v0.3 P3: the fused hyper-connection read rides the native (FP32-activation) contract; the per-stage
|
|
// and dump measurements need the unfused layout of R, so they keep the old kernels.
|
|
strata::core::layer_set_fast_attn(!o.no_fast_attn);
|
|
strata::core::layer_set_publish_kernel(!o.no_publish_kernel);
|
|
strata::core::layer_set_fused_gdn(!o.no_fused_gdn);
|
|
strata::core::layer_set_fast_select(!o.no_fast_select);
|
|
strata::core::layer_set_fused_gr(o.gr_native_mmvf && !o.no_fused_gr && !o.gpu_stages && o.dump_layers.empty() &&
|
|
o.dump_halves.empty() && !o.stage_timing);
|
|
strata::core::layer_set_native_bf16(o.native_bf16);
|
|
strata::core::layer_set_native_flash_attn_short(o.native_flash_attn_short);
|
|
strata::kernels::ple_set_native_bf16(o.native_bf16_extra);
|
|
strata::kernels::shared_expert_set_native_bf16(o.native_bf16_extra);
|
|
strata::kernels::native_moe_combine_set_enabled(o.native_moe_combine);
|
|
strata::kernels::native_gdn_set_enabled(o.native_gdn);
|
|
strata::kernels::native_router_set_enabled(o.native_router);
|
|
strata::kernels::native_qsa_set_enabled(o.native_qsa);
|
|
strata::kernels::native_qsa_indexer_set_enabled(o.native_qsa_indexer);
|
|
strata::kernels::native_rope_set_enabled(o.native_rope);
|
|
// The vision path: every rope kernel reads a cell's (t, h, w) from this table (strata/kernels/mrope.hpp). It is
|
|
// the identity until an image request, and it is set here, before any CUDA graph captures a rope kernel.
|
|
int32_t* d_mrope = nullptr;
|
|
std::vector<int32_t> mrope_host;
|
|
if (o.vision) {
|
|
const int64_t cells = o.max_context + 64;
|
|
mrope_host.resize((size_t) cells * 3);
|
|
for (int64_t c = 0; c < cells; ++c)
|
|
mrope_host[(size_t) c * 3] = mrope_host[(size_t) c * 3 + 1] = mrope_host[(size_t) c * 3 + 2] = (int32_t) c;
|
|
if (cudaMalloc(&d_mrope, mrope_host.size() * sizeof(int32_t)) != cudaSuccess ||
|
|
cudaMemcpy(d_mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), cudaMemcpyHostToDevice) !=
|
|
cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: cannot allocate the image position table\n");
|
|
return 1;
|
|
}
|
|
strata::kernels::mrope_table_set(d_mrope);
|
|
}
|
|
strata::kernels::ple_set_native_postops(o.native_ple_postops);
|
|
const strata::core::ModelGeometry g;
|
|
const int64_t K = 10;
|
|
if (o.max_context < (int64_t) o.tokens.size() + o.max_new) {
|
|
std::fprintf(stderr, "strata generate: --max-context %lld cannot hold %zu prompt + %lld new tokens\n",
|
|
(long long) o.max_context, o.tokens.size(), (long long) o.max_new);
|
|
return 2;
|
|
}
|
|
|
|
void* sbuf = nullptr;
|
|
if (cudaMalloc(&sbuf, strata::core::session_bytes(g, o.max_context, K)) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: session state allocation failed\n");
|
|
return 1;
|
|
}
|
|
strata::core::SessionState ss;
|
|
// **THE ENGINE RAN ON THE LEGACY DEFAULT STREAM, WHICH ON WDDM IS THE SLOW PATH.** All four session
|
|
// calls - `session_capture`, `session_replay`, `session_token` and `session_loop` - were handed `nullptr`,
|
|
// i.e. stream 0. `bench/micro/kernel_costs.cu` measures what that costs: EVERY kernel it launches through
|
|
// a wrapper comes back at 28-31 us REGARDLESS OF SIZE, `scale_inplace` on 2,048 floats and `silu_inplace`
|
|
// on 10,240 floats being indistinguishable, which is a fixed per-launch cost and not execution.
|
|
// `bench/micro/graph_node_cost.cu` measures the same kernels on a real stream at 3.63 us ungrapped and
|
|
// 0.805 us inside a graph. **That is an ~8x penalty on every launch in the engine.**
|
|
cudaStream_t main_stream = nullptr;
|
|
if (cudaStreamCreateWithFlags(&main_stream, cudaStreamNonBlocking) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: cannot create the main stream\n");
|
|
return 1;
|
|
}
|
|
void* const main_cs = (void*) main_stream;
|
|
if (strata::core::session_init(g, o.max_context, K, sbuf, ss) == 0) {
|
|
std::fprintf(stderr, "strata generate: session_init failed\n");
|
|
return 1;
|
|
}
|
|
|
|
// ---- **THE HALF-LEVEL DUMP HAS TO BE ARMED BEFORE `session_capture`, AND THE LADDER MUST NOT BE.** The
|
|
// half copies are issued from inside `block_layer_pre`/`block_layer_post`, so they are only ever enqueued
|
|
// while a graph is being CAPTURED - arming `ss.block.dump` afterwards would produce a file of zeros that
|
|
// reads exactly like a wrong answer. The ladder is the opposite: `session_loop` enqueues it per token on
|
|
// the replay stream, so it must be armed after capture to stay out of the graph.
|
|
const uint64_t half_stride = (uint64_t) 2 * g.n_embd + (uint64_t) 2 * g.hc +
|
|
(uint64_t) g.n_head * g.head_dim +
|
|
(uint64_t) 5 * g.n_head_kv * g.head_dim + 8;
|
|
std::FILE* half_dump = nullptr;
|
|
float* half_stage = nullptr;
|
|
if (!o.dump_halves.empty()) {
|
|
half_dump = std::fopen(o.dump_halves.c_str(), "wb");
|
|
if (half_dump == nullptr) {
|
|
std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_halves.c_str());
|
|
return 1;
|
|
}
|
|
const size_t n = (size_t) g.n_layers * (size_t) half_stride;
|
|
if (cudaHostAlloc((void**) &half_stage, n * sizeof(float), cudaHostAllocDefault) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: cannot pin the half-dump staging buffer\n");
|
|
return 1;
|
|
}
|
|
ss.block.dump = half_stage;
|
|
}
|
|
|
|
strata::core::Doorbell db;
|
|
if (strata::core::doorbell_init(g, K, db) == 0) {
|
|
std::fprintf(stderr, "strata generate: doorbell_init failed\n");
|
|
return 1;
|
|
}
|
|
ss.db = &db;
|
|
|
|
// ================================ THE PLE ================================
|
|
//
|
|
// **ITS ABSENCE IS WHY GATE C1 FAILED** (LEDGER L123): layer 1 carries six `blk.1.ple_*` tensors, the whole
|
|
// module was built and parity-tested, and nothing called it. Everything below is construction - the table
|
|
// is a mapping of the ORIGINAL second GGUF shard, the six weights are already loaded in the arena, and the
|
|
// three buffers are the only allocation.
|
|
strata::kernels::PleTable ple_table;
|
|
std::vector<float> ple_emb_host((size_t) strata::kernels::NG_N_EMBD);
|
|
float* ple_emb_dev = nullptr;
|
|
float* ple_scratch = nullptr;
|
|
if (!o.ple_gguf.empty()) {
|
|
strata::kernels::PleIoOptions pio;
|
|
pio.mode = o.ple_io == "mmap" ? strata::kernels::PleIo::Mmap : strata::kernels::PleIo::Direct;
|
|
pio.max_inflight = (uint32_t) o.ple_inflight;
|
|
pio.cache_rows = (uint64_t) o.ple_row_cache;
|
|
pio.io_thread = !o.ple_sync_submit;
|
|
if (!ple_table.open(o.ple_gguf, err, pio)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
const strata::core::WeightRef* wk = wt.find("blk.1.ple_key.weight");
|
|
const strata::core::WeightRef* wv = wt.find("blk.1.ple_value.weight");
|
|
const strata::core::WeightRef* wnk = wt.find("blk.1.ple_norm_key.weight");
|
|
const strata::core::WeightRef* wnq = wt.find("blk.1.ple_norm_query.weight");
|
|
const strata::core::WeightRef* wnc = wt.find("blk.1.ple_norm_conv.weight");
|
|
const strata::core::WeightRef* wc = wt.find("blk.1.ple_conv1d.weight");
|
|
if (!wk || !wv || !wnk || !wnq || !wnc || !wc) {
|
|
std::fprintf(stderr, "strata generate: the pack has no blk.1.ple_* tensors, so the PLE cannot be "
|
|
"wired - and running without it is a DIFFERENT MODEL (LEDGER L123)\n");
|
|
return 1;
|
|
}
|
|
// `ple_key` is S2 and the loader has already widened its scales to f32, so the two planes are located
|
|
// by the sizes the `WeightRef` records rather than re-derived - the same rule `plane_ptrs` follows.
|
|
if (!wk->quantized()) {
|
|
// plan v0.3 P6: the IQ model files' BF16 key (the pack's extra.bin, raw BF16)
|
|
ss.ple.w.key_bf16 = (const uint16_t*) wk->data;
|
|
} else if (wk->data != nullptr) {
|
|
ss.ple.w.key_codes = (const uint8_t*) wk->data;
|
|
ss.ple.w.key_scales = (const float*) ((const uint8_t*) wk->data + wk->codes_bytes);
|
|
}
|
|
if (o.native_ple_key && wk->quantized()) {
|
|
// Q2_0 in the Q2_0 file, Q8_0 in UD-Q4_K_XL
|
|
if (!wk->native_data || !strata::kernels::native_mmvq_supported(wk->native_type) || !wk->native_q8_1) {
|
|
std::fprintf(stderr, "strata generate: native PLE key is absent or incompatible\n");
|
|
return 1;
|
|
}
|
|
ss.ple.w.key_native_data = wk->native_data;
|
|
ss.ple.w.key_native_type = wk->native_type;
|
|
ss.ple.w.key_native_q8_1 = wk->native_q8_1;
|
|
}
|
|
ss.ple.w.value_bf16 = (const uint16_t*) wv->data;
|
|
ss.ple.w.norm_key = (const float*) wnk->data;
|
|
ss.ple.w.norm_query = (const float*) wnq->data;
|
|
ss.ple.w.norm_conv = (const float*) wnc->data;
|
|
ss.ple.w.conv1d_f16 = (const uint16_t*) wc->data;
|
|
ss.ple.consts = strata::kernels::ple_artifact_consts();
|
|
if (o.ple_delay_us > 0) ple_table.set_injected_delay_us(o.ple_delay_us);
|
|
ss.ple.table = &ple_table;
|
|
ss.ple.token = &ss.ple_token;
|
|
ss.ple.prev = ss.ple_prev;
|
|
ss.ple.hist = ss.ple_hist;
|
|
ss.ple.emb_host = ple_emb_host.data();
|
|
if (cudaMalloc((void**) &ple_emb_dev, (size_t) strata::kernels::NG_N_EMBD * 4) != cudaSuccess ||
|
|
cudaMalloc((void**) &ple_scratch, strata::core::ple_run_scratch_bytes()) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: the PLE buffers failed\n");
|
|
return 1;
|
|
}
|
|
ss.ple.emb_dev = ple_emb_dev;
|
|
ss.ple.scratch = ple_scratch;
|
|
if (!ss.ple.ready()) {
|
|
std::fprintf(stderr, "strata generate: the PLE run is not ready after construction\n");
|
|
return 1;
|
|
}
|
|
std::fprintf(stderr, "strata generate: PLE on, table %llu rows of %s\n",
|
|
(unsigned long long) ple_table.rows(), o.ple_gguf.c_str());
|
|
} else {
|
|
std::fprintf(stderr,
|
|
"strata generate: PLE OFF by explicit --no-ple diagnostic request.\n"
|
|
" The tokens below are NOT this model's; this is only useful for A/B measurement.\n");
|
|
}
|
|
|
|
float* d_parts = nullptr;
|
|
if (cudaMalloc(&d_parts, (size_t) K * g.n_embd * 4) != cudaSuccess ||
|
|
cudaMemset(d_parts, 0, (size_t) K * g.n_embd * 4) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: the parts buffer failed\n");
|
|
return 1;
|
|
}
|
|
|
|
// ---- the CPU expert pool
|
|
//
|
|
// R2.1: the experts are loaded into a RESIDENT ARENA by default. The mmap path is kept behind
|
|
// `--mmap-experts` because it is the A/B arm, not because it is competitive.
|
|
//
|
|
// The reasoning is the review's C1 and it is now measured on both sides. `FileExpertSource` maps the 34 GB
|
|
// file, and mapped file pages are the first thing the OS reclaims; the engine's rate then depends on whether
|
|
// the standby list happens to hold `experts.bin`, which is why two consecutive runs of the SAME BINARY with
|
|
// the SAME FLAGS measured 71.97 and 34.78 ms/token in the pool (7.54 vs 12.18 tok/s). The arena is
|
|
// anonymous memory the engine owns, and the pool runs at 19.41 ms/token - 1.79x better than the warm mmap
|
|
// and 3.7x better than the cold one.
|
|
//
|
|
// IT IS NOT PINNED, and that is reported rather than hidden: `cudaHostRegister` on 31.64 GiB fails with
|
|
// "out of memory" (you cannot pin 34 of 63 GB) and the arena falls back to 4 KB anonymous pages. That is
|
|
// fine for the CPU pool - which is all that exists today - and NOT fine for Phase 3, whose cache fills and
|
|
// CPU/PCIe miss split need the GPU to DMA out of this arena. Read `note()` when that lands.
|
|
//
|
|
// The earlier "the arena does not fit" conclusion was WRONG and is worth recording: the failure was a stale
|
|
// CUDA error left set by the failed `cudaHostRegister` and read later by `gr_read`'s launch check. See the
|
|
// note in `pinned.cu`.
|
|
strata::core::FileExpertSource src;
|
|
strata::core::ArenaExpertSource arena_src;
|
|
strata::core::ExpertSource* srcp = nullptr;
|
|
if (o.mmap_experts) {
|
|
if (!src.open(o.pack, g.n_layers, g.n_expert, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
std::fprintf(stderr, "strata generate: experts via mmap (--mmap-experts; the A/B arm of R2.1)\n");
|
|
srcp = &src;
|
|
} else {
|
|
arena_src.set_gguf(native_shards); // plan v0.3 P6: a native pack may take its experts from the GGUF
|
|
if (!arena_src.open(o.pack, g.n_layers, g.n_expert, /*threads=*/6, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
std::fprintf(stderr, "strata generate: expert arena: %s\n", arena_src.note().c_str());
|
|
std::fprintf(stderr, "strata generate: loaded %.2f GiB at %.2f GiB/s\n",
|
|
(double) strata::kernels::cpu::expert_layout().total / (1024.0 * 1024 * 1024),
|
|
arena_src.load_gib_per_second());
|
|
srcp = &arena_src;
|
|
}
|
|
// Plan v0.3 P6: the MTP draft layer, loaded before the VRAM expert tier is sized from what is left.
|
|
strata::core::MtpDrafter mtp;
|
|
if (!o.mtp.empty()) {
|
|
if (o.spec < 2) {
|
|
std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n");
|
|
o.mtp.clear();
|
|
}
|
|
if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size());
|
|
if (!o.mtp.empty() && !mtp.load(o.mtp, g, ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }
|
|
}
|
|
strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker);
|
|
if (o.no_ple_prefetch) strata::kernels::ple_prefetch_enable(false);
|
|
// ---- R4's slot storage. Allocated AFTER the weights and the session, so `cudaMemGetInfo` inside `open`
|
|
// sees the memory this process actually has left rather than the card's idle figure - and refuses with both
|
|
// numbers if the slots do not fit, instead of handing back a cache smaller than it was asked for.
|
|
strata::core::ExpertCache xcache;
|
|
std::vector<std::pair<int32_t, int32_t>> profile;
|
|
if (!o.expert_profile.empty()) {
|
|
int64_t pslots = 0;
|
|
if (!strata::core::read_expert_profile(o.expert_profile, g.n_layers, g.n_expert, profile, pslots, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
// The profile knows how many slots it was built for. `--expert-cache 0` means "take the profile's";
|
|
// an explicit smaller number is allowed and simply truncates the ranked list, which is the right
|
|
// behaviour for asking "what would 2,000 slots give" without rebuilding the file.
|
|
if (o.expert_cache == 0) o.expert_cache = (int) pslots;
|
|
std::fprintf(stderr, "strata generate: profile %s: %zu ranked pairs, built for %lld slots\n",
|
|
o.expert_profile.c_str(), profile.size(), (long long) pslots);
|
|
}
|
|
if (o.expert_cache < 0) {
|
|
size_t free_b = 0, total_b = 0;
|
|
cudaMemGetInfo(&free_b, &total_b);
|
|
// Plan v0.3 P5: the batched prompt path's chunk buffers are allocated later, so they are reserved here -
|
|
// under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls.
|
|
// (with borrowing - the default with a profile - the prompt path lends cache slots instead)
|
|
const bool borrow = !o.no_prefill_borrow && !o.expert_profile.empty();
|
|
const int64_t prefill_mib = (o.prefill_chunk > 0 && !borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0;
|
|
const int64_t reserve = ((int64_t) o.vram_reserve_mib + prefill_mib) << 20;
|
|
int64_t slots = ((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob;
|
|
if (!profile.empty()) slots = std::min<int64_t>(slots, (int64_t) profile.size());
|
|
o.expert_cache = (int) std::max<int64_t>(slots, 0);
|
|
std::fprintf(stderr, "strata generate: expert cache auto: %.2f GiB free, %d MiB reserved -> %d slots\n",
|
|
(double) free_b / 1073741824.0, o.vram_reserve_mib, o.expert_cache);
|
|
}
|
|
// plan v0.3 P6: a native pack's blobs differ per layer, so with a profile its slots are sized per pair: the
|
|
// same VRAM holds ~30% more IQ3_XXS experts than slots of the largest blob would
|
|
std::vector<int64_t> sized_slots;
|
|
if (native_pack && o.expert_cache > 0 && !profile.empty()) {
|
|
size_t free_b = 0, total_b = 0;
|
|
cudaMemGetInfo(&free_b, &total_b);
|
|
const auto& lay = strata::kernels::cpu::expert_layout();
|
|
const uint64_t budget = (uint64_t) o.expert_cache * lay.max_blob; // what the uniform sizing granted
|
|
uint64_t used = 0;
|
|
size_t free_room = free_b > ((size_t) o.vram_reserve_mib << 20) ? free_b - ((size_t) o.vram_reserve_mib << 20) : 0;
|
|
const uint64_t cap = std::min<uint64_t>(budget, (uint64_t) free_room);
|
|
for (const auto& pr : profile) {
|
|
const uint64_t b = (lay.blob_bytes(pr.first) + 255) / 256 * 256;
|
|
if (used + b > cap) break;
|
|
used += b;
|
|
sized_slots.push_back((int64_t) lay.blob_bytes(pr.first));
|
|
}
|
|
o.expert_cache = (int) sized_slots.size();
|
|
}
|
|
if (o.expert_cache > 0) {
|
|
const bool ok = sized_slots.empty()
|
|
? xcache.open(o.expert_cache, g.n_layers, g.n_expert, (int64_t) strata::kernels::cpu::expert_layout().max_blob, err)
|
|
: xcache.open_sized(sized_slots, g.n_layers, g.n_expert, err);
|
|
if (!ok) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
std::fprintf(stderr, "strata generate: expert cache %lld slots, %.2f GiB of VRAM; policy is\n",
|
|
(long long) xcache.slots(), xcache.gib());
|
|
xcache.set_per_layer_admission(o.expert_cache_per_layer);
|
|
// **ROUND 328: THE HIT PATH IS PROVABLY WRONG, AND THIS SAYS SO OUT LOUD RATHER THAN LETTING IT
|
|
// CORRUPT A RUN QUIETLY.** With the cache on, the generated tokens DIVERGE from the cache-off run:
|
|
// at 256 global slots (2.97% hits) the first difference is at **token 40**; at 4096 per-layer slots
|
|
// (54.4% hits) it is at **token 0**. The cache-off run is deterministic across repeated runs, so
|
|
// this is a real fault in `moe_hit_grouped_s2`'s inputs or the fill - not noise. It also explains
|
|
// what R4 recorded as "a better profile makes the token worse": more hits means more wrong rows, so
|
|
// the payoff is non-monotone BY CONSTRUCTION rather than by any memory-system effect.
|
|
// The cache stays opt-in and this warning is not a refusal, because the divergence IS the diagnostic.
|
|
std::fprintf(stderr,
|
|
"strata generate: *** WARNING: --expert-cache is enabled and the GPU hit path is NOT\n"
|
|
" CORRECT. The generated tokens diverge from a cache-off run (measured:\n"
|
|
" first difference at token 40 at 2.97%% hits, token 0 at 54.4%%). Any\n"
|
|
" timing from this run is real; any OUTPUT from it is not. ***\n");
|
|
if (o.expert_cache_per_layer) {
|
|
int64_t lo = 0, hi = 0;
|
|
xcache.layer_slot_range(0, lo, hi);
|
|
std::fprintf(stderr, " R4.2g PER-LAYER: each layer owns %lld slots (%lld..%lld).\n",
|
|
(long long) (hi - lo), (long long) lo, (long long) (hi - 1));
|
|
} else if (profile.empty()) {
|
|
std::fprintf(stderr, " compulsory-miss (fills with whatever the run routes first).\n");
|
|
} else {
|
|
std::fprintf(stderr, " PROFILE, ranked by routing frequency, no eviction.\n");
|
|
}
|
|
}
|
|
// ---- R4.2e: fill the tier from the profile. This is the only place the plan is applied, and it runs
|
|
// ONCE: with `slots` pairs and `slots` slots the cache is full when this returns, so the decode-time
|
|
// admission finds no room and every non-profiled expert stays a CPU miss. That is what makes the profile
|
|
// the policy rather than a hint.
|
|
int64_t prefilled = 0;
|
|
if (!profile.empty() && srcp != nullptr) {
|
|
const int64_t want = std::min<int64_t>((int64_t) profile.size(), xcache.slots());
|
|
for (int64_t i = 0; i < want; ++i) {
|
|
const int32_t slot = xcache.admit(profile[(size_t) i].first, profile[(size_t) i].second);
|
|
if (slot == strata::core::kNotResident) break;
|
|
const uint8_t* b = srcp->blob(profile[(size_t) i].first, profile[(size_t) i].second);
|
|
if (b == nullptr || !xcache.fill_slot_blocking(slot, b, err,
|
|
(int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first))) {
|
|
std::fprintf(stderr, "strata generate: the profile fill failed at pair %lld: %s\n",
|
|
(long long) i, err.c_str());
|
|
return 1;
|
|
}
|
|
++prefilled;
|
|
}
|
|
// **AND ONE SLOT IS READ BACK AND COMPARED.** A residency table that is right about indices and wrong
|
|
// about bytes produces a plausible token, which is this project's most expensive failure mode; the
|
|
// cache's own `verify_slot` is the check and it costs one 1.38 MB D2H at startup.
|
|
if (!xcache.verify_slot(xcache.slot_of(profile[0].first, profile[0].second),
|
|
srcp->blob(profile[0].first, profile[0].second), err,
|
|
(int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[0].first))) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
std::fprintf(stderr, "strata generate: pre-filled %lld of %lld slots from the profile; slot 0 verified\n",
|
|
(long long) prefilled, (long long) want);
|
|
}
|
|
|
|
Drive drive;
|
|
drive.d.hit_cpu_order = o.expert_cache_cpu_order;
|
|
drive.d.split_rows = !o.no_split_rows;
|
|
drive.d.pool = &pool;
|
|
drive.d.src = srcp;
|
|
drive.d.n_expert = g.n_expert;
|
|
drive.d.jobs.resize((size_t) K);
|
|
// ---- R4.2c: THE HIT PATH. Every one of these is required for `hits_ready()`, which is all-or-nothing on
|
|
// purpose: a half-configured hit path would compute some experts twice and others not at all, and a token
|
|
// built on that is wrong rather than refused.
|
|
void* hit_scratch = nullptr;
|
|
int32_t* d_hit_slot = nullptr;
|
|
int32_t* d_hit_dst = nullptr;
|
|
uint8_t* d_hit_q8 = nullptr;
|
|
float* d_hit_q8_scale = nullptr; ///< R4.2h: the fp32 activation scales the CPU path also uses
|
|
float* d_hit_out = nullptr;
|
|
if (o.expert_cache > 0 && !o.no_pool) {
|
|
const uint64_t sb = strata::kernels::moe_hit_grouped_scratch_bytes(K, g.n_embd, strata::kernels::cpu::FF);
|
|
if (cudaMalloc(&hit_scratch, (size_t) sb) != cudaSuccess ||
|
|
cudaMalloc((void**) &d_hit_slot, (size_t) K * sizeof(int32_t)) != cudaSuccess ||
|
|
cudaMalloc((void**) &d_hit_dst, (size_t) K * sizeof(int32_t)) != cudaSuccess ||
|
|
cudaMalloc((void**) &d_hit_q8, (size_t) (g.n_embd / 32) * 34) != cudaSuccess ||
|
|
// R4.2h: the fp32 activation scales. Without this the GPU's hits use the block's fp16 `d`
|
|
// while the CPU's misses use `ActQ::scale`, which is fp32 - a 4.761e-04 relative disagreement on
|
|
// every chunk, and the reason enabling the cache changed the tokens.
|
|
cudaMalloc((void**) &d_hit_q8_scale, (size_t) (g.n_embd / 32) * sizeof(float)) != cudaSuccess ||
|
|
cudaMalloc((void**) &d_hit_out, (size_t) K * g.n_embd * 4) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: the R4 hit path could not allocate its device buffers\n");
|
|
return 1;
|
|
}
|
|
drive.d.cache = &xcache;
|
|
drive.d.cache_stream = main_cs;
|
|
drive.d.cache_base = (const uint8_t*) xcache.device_slot(0);
|
|
drive.d.cache_blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
|
|
drive.d.cache_slot_off = xcache.slot_offsets();
|
|
drive.d.hit_scratch = hit_scratch;
|
|
drive.d.parts_out = d_parts;
|
|
drive.d.hit_out = d_hit_out;
|
|
drive.d.parts_elems = K * g.n_embd;
|
|
drive.d.mixed = ss.block.mixed;
|
|
drive.d.x_q8_0_hit = d_hit_q8;
|
|
drive.d.x_q8_0_hit_scale = d_hit_q8_scale;
|
|
drive.d.d_slot = d_hit_slot;
|
|
drive.d.d_dst = d_hit_dst;
|
|
drive.d.h_slot.resize((size_t) K);
|
|
cudaEvent_t hit_done = nullptr;
|
|
if (cudaEventCreate(&hit_done) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: the hit path could not create its probe event\n");
|
|
return 1;
|
|
}
|
|
drive.d.hit_done = (void*) hit_done;
|
|
drive.d.hit_poke = !o.no_hit_poke;
|
|
drive.d.h_dst.resize((size_t) K);
|
|
std::fprintf(stderr, "strata generate: R4 hit path ON - resident experts are computed on the GPU\n");
|
|
}
|
|
// ---- P0.S8: the routing trace. Only meaningful with the pool running, because the ids arrive through
|
|
// the doorbell that the pool consumes - so `--no-pool` is refused rather than silently producing an empty
|
|
// file that would read as "the router selected nothing".
|
|
// ---- PER-STAGE TIMING. `--no-capture` only: an event recorded inside a stream capture is silently
|
|
// dropped, so a captured graph cannot carry these events and the numbers would be zeros that read as
|
|
// "every stage is free". Refusing is the fix.
|
|
if (o.stage_timing) {
|
|
if (!o.no_capture) {
|
|
std::fprintf(stderr, "strata generate: --stage-timing records CUDA events inside the layer path, "
|
|
"and an event record inside a stream capture is silently dropped. Pass "
|
|
"--no-capture as well.\n");
|
|
return 2;
|
|
}
|
|
if (!strata::core::stage_timing_enable()) {
|
|
std::fprintf(stderr, "strata generate: stage_timing_enable failed\n");
|
|
return 1;
|
|
}
|
|
strata::core::stage_timing_name(0, "gr_read (attn)");
|
|
strata::core::stage_timing_name(1, "attention block");
|
|
strata::core::stage_timing_name(2, "gr_write (attn)");
|
|
strata::core::stage_timing_name(3, "gr_read (ffn)");
|
|
strata::core::stage_timing_name(4, "moe_route");
|
|
strata::core::stage_timing_name(5, "moe_finish");
|
|
strata::core::stage_timing_name(6, "gr_write (ffn)");
|
|
// The GDN block's internals. It is 36 of the 48 layers, 0.96 ms each, and its entire weight traffic
|
|
// is ~26 MB - so ~0.11 ms at the measured read rate. ~13 tiny latency-bound launches live in it and
|
|
// a single "attention block" number cannot say which one costs anything.
|
|
strata::core::stage_timing_name(8, " gdn: quantize x");
|
|
strata::core::stage_timing_name(9, " gdn: qkv gemv");
|
|
strata::core::stage_timing_name(10, " gdn: conv+silu");
|
|
strata::core::stage_timing_name(11, " gdn: l2 norms");
|
|
strata::core::stage_timing_name(12, " gdn: alpha/beta/gate");
|
|
strata::core::stage_timing_name(13, " gdn: gdn_step");
|
|
strata::core::stage_timing_name(14, " gdn: z + out_norm");
|
|
strata::core::stage_timing_name(15, " gdn: out gemv");
|
|
}
|
|
std::FILE* routing = nullptr;
|
|
if (!o.dump_routing.empty()) {
|
|
if (o.no_pool) {
|
|
std::fprintf(stderr, "strata generate: --dump-routing needs the expert pool; the routed ids reach "
|
|
"the host through the doorbell the pool reads. Drop --no-pool.\n");
|
|
return 2;
|
|
}
|
|
routing = std::fopen(o.dump_routing.c_str(), "wb");
|
|
if (routing == nullptr) {
|
|
std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_routing.c_str());
|
|
return 1;
|
|
}
|
|
drive.routing = routing;
|
|
}
|
|
strata::core::PoolFn pool_fn = o.no_pool ? nullptr : &drive_pool;
|
|
// The hit hook rides the same switch as the pool: with no pool there is no `parts` staging to
|
|
// write into, and a hit path with nowhere to write is a wrong token rather than an error.
|
|
strata::core::HitFn hit_fn =
|
|
(o.no_pool || o.expert_cache <= 0) ? nullptr : &strata::core::expert_hit_run;
|
|
void* pool_user = o.no_pool ? nullptr : (void*) &drive;
|
|
std::fprintf(stderr, "strata generate: %d expert-pool workers%s%s\n", pool.workers(),
|
|
pool.host_works() ? " + the host thread" : "",
|
|
o.no_pool ? " (UNUSED: --no-pool)" : "");
|
|
|
|
// **THE MISALIGNMENT WARNING THAT STOOD HERE IS GONE, BECAUSE THE MISALIGNMENT IS FIXED.**
|
|
//
|
|
// It said the tokens were not the model's, and it was true: `session_loop` handed layer `l`'s expert
|
|
// outputs to layer `l+1`, which multiplied them by layer `l+1`'s router weights (LEDGER L100). The loop
|
|
// now runs a captured PAIR per layer - `pre[l]` ending with the router and the doorbell, then the CPU
|
|
// pool, then `post[l]` which combines those experts with THAT layer's weights - so layer `l`'s experts meet
|
|
// layer `l`'s routing. The generated ids changed the moment it landed, which is what a correctness fix
|
|
// looks like from the outside.
|
|
//
|
|
// The cost is real and is recorded rather than hidden: the window for the CPU pool is now whatever GPU
|
|
// work follows the ring inside `pre[l]`, which is the shared expert and nothing else - 0.038 ms against
|
|
// 0.514 ms of CPU work per layer. A per-layer CPU expert pool cannot be hidden behind a strictly serial
|
|
// residual chain; the CPU term is answered by Phase 3's VRAM expert cache, not by this pipeline.
|
|
|
|
// ---- the graphs
|
|
strata::core::SessionGraphs gr;
|
|
if (!o.no_capture && !native_pack) { // plan v0.3 P6: a native pack runs verify windows only
|
|
if (!strata::core::session_capture(wt, g, ss, d_parts, gr, err, /*split=*/o.gpu_stages)) {
|
|
std::fprintf(stderr, "strata generate: session_capture: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
// **`--no-capture` AND THE EXPERTS ARE MUTUALLY EXCLUSIVE, AND SILENTLY SO.**
|
|
//
|
|
// The CPU expert pool is wired into `session_loop` - the host loop around the captured graphs - and
|
|
// `session_token` has no pool hook at all. So `--no-capture` did not merely change HOW the layers were
|
|
// launched: it ran the whole model with `parts` left at whatever the buffer held, which is ZERO, and the
|
|
// only symptom was `expert blobs 0` in a stats line nobody had to read. A run that silently omits the
|
|
// routed experts is not a slow measurement of this model, it is a measurement of a different model.
|
|
//
|
|
// Refusing is the fix. `--no-pool` is the explicit way to say "I want the GPU-only floor".
|
|
if (o.no_capture && !o.no_pool) {
|
|
std::fprintf(stderr,
|
|
"strata generate: --no-capture runs `session_token`, which has NO CPU expert pool hook, so "
|
|
"the routed experts would silently contribute nothing. Pass --no-pool as well if the "
|
|
"GPU-only floor is what you want.\n");
|
|
return 2;
|
|
}
|
|
// The ladder is written by `session_loop`, and `session_token` does not touch the staging buffer at all - so
|
|
// accepting the flag there would produce a file of uninitialised memory, which reads as a wrong answer rather
|
|
// than as a mistake. `--no-capture` without `--no-pool` is already refused above, so this catches the pair.
|
|
if (o.no_capture && !o.dump_layers.empty()) {
|
|
std::fprintf(stderr,
|
|
"strata generate: --dump-layers is written by `session_loop`; `--no-capture` runs "
|
|
"`session_token` instead, which never fills the staging buffer. Drop one of the two.\n");
|
|
return 2;
|
|
}
|
|
if (o.no_capture && !o.dump_halves.empty()) {
|
|
std::fprintf(stderr,
|
|
"strata generate: --dump-halves is CAPTURED into the layer graphs, so it needs the "
|
|
"captured path; `--no-capture` never records it. Drop one of the two.\n");
|
|
return 2;
|
|
}
|
|
|
|
std::fprintf(stderr, "strata generate: session is up; locating the head\n");
|
|
const strata::core::WeightRef* wo = wt.find("output.weight");
|
|
if (wo == nullptr) { std::fprintf(stderr, "strata generate: output.weight is missing\n"); return 1; }
|
|
const int64_t n_vocab = wo->ne1;
|
|
strata::core::NativeHead native_head;
|
|
if (!o.native_head_gguf.empty()) {
|
|
std::vector<std::string> head_shards;
|
|
try {
|
|
head_shards = strata::gguf_split_paths(o.native_head_gguf);
|
|
} catch (const std::exception& e) {
|
|
std::fprintf(stderr, "strata generate: native head: %s\n", e.what());
|
|
return 1;
|
|
}
|
|
if (!native_head.load(head_shards, g.n_embd, n_vocab, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
std::fprintf(stderr, "strata generate: native head, type %d, %llu bytes\n", native_head.type(),
|
|
(unsigned long long) native_head.weight_bytes());
|
|
}
|
|
std::vector<float> logits((size_t) n_vocab);
|
|
float* d_logits = nullptr;
|
|
if (cudaMalloc(&d_logits, (size_t) n_vocab * 4) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: the logits buffer failed\n");
|
|
return 1;
|
|
}
|
|
auto run_head = [&](void* stream) -> bool {
|
|
if (!native_head.loaded())
|
|
return strata::core::lm_head(wt, g, ss.block, d_logits, stream, err);
|
|
return strata::core::lm_head_mix(wt, g, ss.block, stream, err) &&
|
|
native_head.run(ss.block.mixed, d_logits, stream, err);
|
|
};
|
|
float* d_emb = nullptr;
|
|
if (cudaMalloc(&d_emb, (size_t) g.n_embd * 4) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: the embedding buffer failed\n");
|
|
return 1;
|
|
}
|
|
// **`sample_tokens` TAKES DEVICE POINTERS.** It is a kernel launch; `logits` and `out` are both read and
|
|
// written on the device. Passing `logits.data()` - the host vector - faults inside the kernel and the
|
|
// error surfaces at the NEXT synchronising call, which here was the next token's `embed_row`, reporting an
|
|
// illegal access on a weight plane. Nothing in the parameter names said device.
|
|
int* d_next = nullptr;
|
|
if (cudaMalloc(&d_next, sizeof(int)) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: the sampler output buffer failed\n");
|
|
return 1;
|
|
}
|
|
|
|
// **`R` IS BOTH THE INPUT AND THE OUTPUT, SO THE NEW TOKEN'S EMBEDDING HAS TO REPLACE THE OLD RESIDUAL.**
|
|
// At `pos == 0` that is `session_zero`, which is the reference's own initial condition - the embedding
|
|
// broadcast to all `hc` streams. After that `session_zero` would also wipe the recurrence, so the
|
|
// broadcast is done directly. Getting this wrong is invisible for exactly one token.
|
|
void* token_stream = o.stream_token ? main_cs : nullptr;
|
|
auto put_input = [&](int64_t tok, int64_t pos) -> bool {
|
|
if (!strata::core::embed_row(wt, g, tok, d_emb, token_stream, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return false;
|
|
}
|
|
if (pos == 0) {
|
|
strata::core::session_zero(ss, g, d_emb, token_stream);
|
|
} else {
|
|
for (int64_t c = 0; c < g.hc; ++c)
|
|
if (cudaMemcpyAsync(ss.R + (size_t) c * g.n_embd, d_emb, (size_t) g.n_embd * 4,
|
|
cudaMemcpyDeviceToDevice, (cudaStream_t) token_stream) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: the residual broadcast failed\n");
|
|
return false;
|
|
}
|
|
}
|
|
return o.stream_token || cudaDeviceSynchronize() == cudaSuccess;
|
|
};
|
|
|
|
strata::kernels::SamplerParams sp;
|
|
sp.greedy = o.greedy;
|
|
sp.seed = o.seed;
|
|
sp.top_k = o.top_k;
|
|
sp.top_p = o.top_p;
|
|
sp.temperature = o.temperature;
|
|
|
|
std::FILE* dump = nullptr;
|
|
const int64_t dump_positions = (int64_t) o.tokens.size() - 1 + o.max_new;
|
|
if (!o.dump_logits.empty()) {
|
|
if (dump_positions > INT32_MAX || n_vocab > INT32_MAX) {
|
|
std::fprintf(stderr, "strata generate: logits dump dimensions exceed int32\n");
|
|
return 2;
|
|
}
|
|
dump = std::fopen(o.dump_logits.c_str(), "wb");
|
|
if (dump == nullptr) {
|
|
std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_logits.c_str());
|
|
return 1;
|
|
}
|
|
// **THE COUNT IS `n_prompt - 1 + max_new`, NOT `n_prompt + max_new`.** The loop writes one row per
|
|
// position from 0, and it stops once `produced` holds `max_new` tokens - and `produced` only starts
|
|
// receiving at position `n_prompt - 1`. So a 5-token prompt with `--max-new 6` writes 10 rows, and the
|
|
// header used to claim 11. A header that describes a different file from the one written is the same
|
|
// class of defect as a self-check that verifies the wrong invariant: anything reading the count instead
|
|
// of the size gets a wrong answer that looks authoritative. `tools/logits_identical.py` caught it by
|
|
// parsing the header and refusing the file.
|
|
const int32_t n_rows = (int32_t) strata::program::logits_selection::row_count(dump_positions, o.logits_stride);
|
|
const int32_t hdr[2] = {(int32_t) n_vocab, n_rows};
|
|
if (std::fwrite(hdr, sizeof hdr, 1, dump) != 1) {
|
|
std::fprintf(stderr, "strata generate: cannot write logits header\n");
|
|
std::fclose(dump);
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
// ---- THE C1 ORACLE: ONE RESIDUAL SNAPSHOT PER LAYER PER POSITION, so the engine can be bisected against
|
|
// `llama-debug`'s `l_last-<il>` node instead of against a single end-to-end perplexity. The buffer is
|
|
// PINNED because `session_loop` enqueues a device-to-host copy into it after every layer and the transfer
|
|
// would otherwise be staged through a pageable bounce buffer on the critical path.
|
|
std::FILE* layer_dump = nullptr;
|
|
float* layer_stage = nullptr;
|
|
const size_t layer_floats = (size_t) (g.n_layers + 1) * (size_t) g.hc * (size_t) g.n_embd;
|
|
if (!o.dump_layers.empty()) {
|
|
layer_dump = std::fopen(o.dump_layers.c_str(), "wb");
|
|
if (layer_dump == nullptr) {
|
|
std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_layers.c_str());
|
|
return 1;
|
|
}
|
|
if (cudaHostAlloc((void**) &layer_stage, layer_floats * sizeof(float), cudaHostAllocDefault) !=
|
|
cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: cannot pin the layer-dump staging buffer\n");
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
// ---- prefill is the DECODE PATH ONE TOKEN AT A TIME, which `phase-2-correct-engine.md:12-13` says is
|
|
// fine here: "process the prompt through the decode-style graphs in small batches; a 19K-token prompt will
|
|
// take minutes". A real batched prefill is P2.S6's other half and is not this.
|
|
//
|
|
// **THE LOOP IS `feed -> 48 layers -> head -> sample -> feed`, AND THE FIRST GENERATED TOKEN COMES FROM THE
|
|
// LAST *PROMPT* POSITION.** The first version sampled only on the decode positions, so `produced` was
|
|
// still empty when the first generated position asked for `produced.back()` - an out-of-bounds read on an
|
|
// empty vector. Teacher forcing below is what makes the distinction unnecessary to special-case: for every
|
|
// position before the last prompt one, the next input is the PROMPT's next token, and after that it is the
|
|
// sampled one.
|
|
std::vector<int64_t> produced;
|
|
double total_ms = 0;
|
|
double prefill_ms = 0; // positions 0 .. n_prompt-2: prompt tokens that only condition
|
|
const Clock::time_point t_start = Clock::now();
|
|
double ttft_ms = 0;
|
|
const int64_t n_prompt = (int64_t) o.tokens.size();
|
|
int64_t tok = o.tokens[0];
|
|
|
|
// ---- THE PURE-GPU MEASUREMENT. `session_replay` launches all 48 `pre` graphs back to back on one stream
|
|
// with NO host work between them - no doorbell poll, no pool, no parts copy - so what it times is the GPU
|
|
// executing the layer sequence and nothing else. It had been declared, defined and never called since the
|
|
// day it was written.
|
|
//
|
|
// **THIS IS THE MEASUREMENT THAT SAYS WHETHER THE ENGINE IS HOST-BOUND OR GPU-BOUND**, and the stage table
|
|
// cannot answer it: those events measure the interval between two marks on a stream, which includes every
|
|
// gap where the GPU sat idle waiting for the host to enqueue the next kernel. In `--no-capture` those gaps
|
|
// are the host's launch latency and they are proportional to the KERNEL COUNT rather than to any work, so
|
|
// the no-capture stage shares are shares of kernel count - which is why the attention block, with the most
|
|
// kernels, looks like 55% of the token there.
|
|
// ---- R0.9: THE PER-STAGE TABLE ON THE CAPTURED GRAPH.
|
|
if (o.gpu_stages) {
|
|
strata::core::doorbell_reset(db);
|
|
double mix = 0, ffn = 0, post = 0;
|
|
if (!strata::core::session_replay_stages(g, 0, 0, ss, gr, main_cs, mix, ffn, post, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
const int reps = 20;
|
|
double t_mix = 0, t_ffn = 0, t_post = 0;
|
|
for (int r = 0; r < reps; ++r) {
|
|
if (!strata::core::session_replay_stages(g, 0, 0, ss, gr, main_cs, mix, ffn, post, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
t_mix += mix;
|
|
t_ffn += ffn;
|
|
t_post += post;
|
|
}
|
|
const double tot = t_mix + t_ffn + t_post;
|
|
std::printf("\nper-stage GPU time on the CAPTURED graph, one token over %lld layers\n",
|
|
(long long) g.n_layers);
|
|
std::printf(" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n", "mixer (gr_read+attn+gr_write)",
|
|
t_mix / reps, t_mix / reps / (double) g.n_layers, 100.0 * t_mix / tot);
|
|
std::printf(" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n", "ffn front + router",
|
|
t_ffn / reps, t_ffn / reps / (double) g.n_layers, 100.0 * t_ffn / tot);
|
|
std::printf(" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n", "post (moe_finish+gr_write)",
|
|
t_post / reps, t_post / reps / (double) g.n_layers, 100.0 * t_post / tot);
|
|
std::printf(" %-22s %9.3f ms/token\n", "sum of the three", tot / reps);
|
|
|
|
// ---- AND THE MIXER BY LAYER KIND, because 36 of the 48 are GDN and 12 are QSA and a total cannot
|
|
// separate them. Round 309's uncaptured table put GDN at 10.88 ms for 36 layers against QSA's 4.56 for
|
|
// 12, which would make the recurrence the largest single R3 target - and that table had `moe_finish`
|
|
// wrong by 4x, so the ratio is re-derived here from the captured graph rather than inherited.
|
|
{
|
|
// **ACCUMULATED OVER `reps`, NOT MEASURED ONCE AND THEN DIVIDED.** The first version called the
|
|
// per-layer replay a single time and printed `gdn / reps`, which reported GDN at 0.480 ms/token
|
|
// against a mixer total of 14.039 - a factor of exactly `reps`, and the tell was that
|
|
// 0.480 + 0.220 = 0.700 = 14.039 / 20.
|
|
std::vector<double> acc((size_t) g.n_layers, 0.0), per;
|
|
double f2 = 0, p2 = 0;
|
|
for (int r = 0; r < reps; ++r) {
|
|
if (!strata::core::session_replay_stages_per_layer(g, 0, 0, ss, gr, main_cs, per, f2, p2, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
for (int64_t l = 0; l < g.n_layers; ++l) acc[(size_t) l] += per[(size_t) l];
|
|
}
|
|
double gdn = 0, qsa = 0, worst = 0;
|
|
int64_t ng = 0, nq = 0, worst_l = 0;
|
|
for (int64_t l = 0; l < g.n_layers; ++l) {
|
|
const double v = acc[(size_t) l] / reps;
|
|
if (strata::core::is_qsa_layer(g, l)) { qsa += v; ++nq; }
|
|
else { gdn += v; ++ng; }
|
|
if (v > worst) { worst = v; worst_l = l; }
|
|
}
|
|
std::printf("\n the mixer by layer kind, averaged over %d runs\n", reps);
|
|
std::printf(" %-22s %9.3f ms/token %8.3f ms/layer (%lld layers)\n", "GDN layers",
|
|
gdn, ng ? gdn / (double) ng : 0.0, (long long) ng);
|
|
std::printf(" %-22s %9.3f ms/token %8.3f ms/layer (%lld layers)\n", "QSA layers",
|
|
qsa, nq ? qsa / (double) nq : 0.0, (long long) nq);
|
|
std::printf(" %-22s layer %lld at %.3f ms\n", "worst mixer layer", (long long) worst_l, worst);
|
|
std::printf(" %-22s %9.3f ms/token (must equal the mixer above)\n", "GDN + QSA", gdn + qsa);
|
|
}
|
|
|
|
// ================================ R0.11: THE FIVE STAGES SEPARATELY ================================
|
|
//
|
|
// Prefixes 1..5 are replayed per layer with the residual restored between them, and consecutive
|
|
// differences are the per-stage times. **THE CHECK IS THAT THE FIVE SUM TO THE THREE-GRAPH TOTAL** -
|
|
// the same independent-restatement test that caught round 320's divide-by-reps bug, and it is the only
|
|
// reason to believe a table built out of differences.
|
|
{
|
|
std::vector<double> acc5(5, 0.0), per, s5;
|
|
for (int r = 0; r < reps; ++r) {
|
|
if (!strata::core::session_replay_stage_prefixes(g, 0, 0, ss, gr, main_cs, s5, per, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
for (int k = 0; k < 5; ++k) acc5[(size_t) k] += s5[(size_t) k];
|
|
}
|
|
static const char* sn[5] = {"0 gr_read (attn)", "1 attention", "2 gr_write (attn)",
|
|
"3 gr_read (ffn)", "4 moe_route (router)"};
|
|
const char* kind[5] = {"GR", "ATTN", "GR", "GR", "ROUTER"};
|
|
double tot5 = 0, gr_ms = 0;
|
|
std::printf("\n the five stages separately, by differencing prefixes\n");
|
|
std::printf(" %-24s %-8s %10s %10s %8s\n", "stage", "kind", "ms/token", "ms/layer", "share");
|
|
for (int k = 0; k < 5; ++k) {
|
|
const double v = acc5[(size_t) k] / reps;
|
|
tot5 += v;
|
|
if (k != 1 && k != 4) gr_ms += v;
|
|
std::printf(" %-24s %-8s %10.3f %10.4f %7.1f%%\n", sn[k], kind[k], v,
|
|
v / (double) g.n_layers, 0.0);
|
|
}
|
|
for (int k = 0; k < 5; ++k) {
|
|
const double v = acc5[(size_t) k] / reps;
|
|
(void) v;
|
|
}
|
|
std::printf(" %-24s %-8s %10.3f\n", "sum of the five", "", tot5);
|
|
std::printf(" %-24s %-8s %10.3f <- R3.3's target is <= 3 ms for all four passes\n",
|
|
"GR passes (0,2,3)", "GR", gr_ms);
|
|
std::printf("\n the three-graph total above was %.3f ms/token; the five must account for it.\n",
|
|
tot / reps);
|
|
|
|
// ================================ R3.5c: THE SAME TABLE, A DIFFERENT WAY ================================
|
|
//
|
|
// The differencing table above mixes five graphs per layer, so stage 4's interval carries the launch
|
|
// of the FULL five-stage graph while stage 3's carries a four-stage one. This sweep launches ONE
|
|
// graph type per layer and nothing else, so that bias cannot exist. **If the two disagree, the
|
|
// difference IS the bias and this one is right** - and stage 4 is the router, so it is exactly the
|
|
// number that must not be wrong.
|
|
{
|
|
double sweep[6] = {0, 0, 0, 0, 0, 0};
|
|
for (int k = 1; k <= 5; ++k) {
|
|
double acc = 0, one = 0;
|
|
for (int r = 0; r < reps; ++r) {
|
|
if (!strata::core::session_replay_stage_sweep(g, 0, 0, ss, gr, main_cs, k, one, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
acc += one;
|
|
}
|
|
sweep[k] = acc / reps;
|
|
}
|
|
std::printf("\n the same five stages, by SWEEPING each prefix back to back (no graph switching)\n");
|
|
std::printf(" %-24s %10s %10s %12s\n", "stage", "prefix sweep", "difference", "bias");
|
|
static const char* sn2[5] = {"0 gr_read (attn)", "1 attention", "2 gr_write (attn)",
|
|
"3 gr_read (ffn)", "4 moe_route (router)"};
|
|
for (int k = 0; k < 5; ++k) {
|
|
const double sw = sweep[k + 1] - sweep[k];
|
|
const double df = acc5[(size_t) k] / reps;
|
|
std::printf(" %-24s %10.3f %10.3f %11.1f%%\n", sn2[k], sw, df,
|
|
sw != 0.0 ? 100.0 * (df / sw - 1.0) : 0.0);
|
|
}
|
|
std::printf(" %-24s %10.3f (full pre, 48 layers)\n", "prefix 5 total", sweep[5]);
|
|
}
|
|
}
|
|
std::printf("\n compare `--gpu-only-full`, which replays the same work as TWO graphs per layer. The\n");
|
|
std::printf(" three sum slightly above it because each launch carries the driver's gap.\n");
|
|
strata::core::session_graphs_free(gr);
|
|
strata::core::doorbell_free(db);
|
|
cudaFree(d_next);
|
|
return 0;
|
|
}
|
|
|
|
if (o.graph_only) {
|
|
strata::core::doorbell_reset(db);
|
|
// one warm pass so the first launch does not pay for page mapping
|
|
if (!strata::core::session_replay(g, 0, 0, ss, gr, main_cs, err)) {
|
|
std::fprintf(stderr, "strata generate: session_replay warm: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
if (cudaDeviceSynchronize() != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: session_replay warm faulted\n");
|
|
return 1;
|
|
}
|
|
const int reps = 20;
|
|
const Clock::time_point t0 = Clock::now();
|
|
for (int r = 0; r < reps; ++r) {
|
|
if (!strata::core::session_replay(g, 0, 0, ss, gr, main_cs, err)) {
|
|
std::fprintf(stderr, "strata generate: session_replay: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
}
|
|
if (cudaDeviceSynchronize() != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: session_replay faulted: %s\n", cudaGetErrorString(cudaGetLastError()));
|
|
return 1;
|
|
}
|
|
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - t0).count() / (double) reps;
|
|
std::printf("pre graphs only %8.2f ms per token over %lld layers -> %.2f tok/s of GPU work\n", ms,
|
|
(long long) g.n_layers, ms > 0 ? 1000.0 / ms : 0.0);
|
|
std::printf(" %8.3f ms per layer\n", ms / (double) g.n_layers);
|
|
return 0;
|
|
}
|
|
|
|
// ---- R0.3: THE TRUE PER-TOKEN GPU FLOOR.
|
|
//
|
|
// `--graph-only` above launches ONLY `gr.execs[l]`, the `pre` graphs. It omits the 48 `post` graphs - the
|
|
// shared expert, the combine and the second `gr_write` - and the LM head. Everything this project published
|
|
// as "39.8 ms pure GPU" came from that loop while being described as the whole GPU, which also made the
|
|
// "host's share = 49.4 - 39.8 = 9.6 ms" figure wrong by however much the missing work costs. See
|
|
// Memory/ERRORS.md A4/A5.
|
|
//
|
|
// This flag is what "pure GPU" has to mean, and it replaces that number everywhere. No pool runs, so
|
|
// `parts` keeps whatever the buffer holds and the timing is GPU work alone.
|
|
if (o.gpu_only_full) {
|
|
strata::core::doorbell_reset(db);
|
|
const int reps = 20;
|
|
double ms_layers = 0, ms_head = 0;
|
|
for (int r = -1; r < reps; ++r) { // r == -1 is the warm pass, not counted
|
|
const Clock::time_point t0 = Clock::now();
|
|
if (!strata::core::session_replay_full(g, 0, 0, ss, gr, main_cs, err)) {
|
|
std::fprintf(stderr, "strata generate: session_replay_full: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
// The sync is INSIDE the interval on purpose: it is the wait for the GPU, so t1 - t0 is GPU time.
|
|
if (cudaStreamSynchronize((cudaStream_t) main_cs) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: gpu-only-full layers faulted: %s\n",
|
|
cudaGetErrorString(cudaGetLastError()));
|
|
return 1;
|
|
}
|
|
const Clock::time_point t1 = Clock::now();
|
|
if (!run_head(main_cs)) {
|
|
std::fprintf(stderr, "strata generate: gpu-only-full lm_head: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
if (cudaStreamSynchronize((cudaStream_t) main_cs) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: gpu-only-full head faulted: %s\n",
|
|
cudaGetErrorString(cudaGetLastError()));
|
|
return 1;
|
|
}
|
|
const Clock::time_point t2 = Clock::now();
|
|
if (r < 0) continue;
|
|
ms_layers += std::chrono::duration<double, std::milli>(t1 - t0).count();
|
|
ms_head += std::chrono::duration<double, std::milli>(t2 - t1).count();
|
|
}
|
|
ms_layers /= (double) reps;
|
|
ms_head /= (double) reps;
|
|
const double ms = ms_layers + ms_head;
|
|
std::printf("GPU floor pre+post+head %7.2f ms per token -> %.2f tok/s of GPU work\n", ms,
|
|
ms > 0 ? 1000.0 / ms : 0.0);
|
|
std::printf(" %8.3f ms layers (%lld x pre+post)\n", ms_layers, (long long) g.n_layers);
|
|
std::printf(" %8.3f ms per layer\n", ms_layers / (double) g.n_layers);
|
|
std::printf(" %8.3f ms LM head\n", ms_head);
|
|
return 0;
|
|
}
|
|
|
|
// ---- **THE TOKEN PATH ALLOCATES NOTHING (P2.T10, review finding H3).**
|
|
//
|
|
// `session_loop` used to allocate its pinned staging buffer, its probe event and its host pin ON EVERY
|
|
// TOKEN, and `cudaFreeHost` at the end of each call implicitly synchronises the device - so every token
|
|
// finished with a device-wide sync nobody asked for. The scratch is created once here and reused; it also
|
|
// owns the host pin for the whole session rather than taking and releasing it per token.
|
|
strata::core::SessionLoopScratch loop_scratch;
|
|
struct ScratchFree {
|
|
strata::core::SessionLoopScratch* p;
|
|
~ScratchFree() { if (p != nullptr) p->free(); }
|
|
} scratch_free{&loop_scratch};
|
|
// Initialised unconditionally, including under --no-pool: the loop validates the scratch it is handed, so
|
|
// passing a default-constructed one is an error rather than a fallback. (It was, and the guard caught it -
|
|
// which is the point of the guard.) One allocation at setup either way.
|
|
if (!loop_scratch.init((size_t) K * g.n_embd * 4, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
// Plan v0.3 P3: the whole token as ONE graph whenever nothing needs a host step between the ring and post[l]
|
|
// (the VRAM expert tier and the per-layer dumps do). `--no-token-graph` keeps two graphs per layer.
|
|
strata::core::TokenGraph tgraph;
|
|
struct TokenGraphFree {
|
|
strata::core::TokenGraph* p;
|
|
~TokenGraphFree() { strata::core::token_graph_free(*p); }
|
|
} tgraph_free{&tgraph};
|
|
// Plan v0.3 P4: with a PROFILE-filled cache the residency is static, so the hit decision moves onto the
|
|
// device and the token graph keeps it. (A cache filled on demand still needs the per-layer host path.)
|
|
std::vector<int32_t> host_res;
|
|
int32_t* d_res = nullptr;
|
|
int32_t* d_hit_count = nullptr;
|
|
strata::core::TokenHits thits;
|
|
const bool graph_hits = hit_fn != nullptr && !profile.empty() && !o.no_pool;
|
|
if (graph_hits && !o.no_capture && !o.no_token_graph && layer_dump == nullptr && half_dump == nullptr) {
|
|
host_res.assign((size_t) (g.n_layers * g.n_expert), strata::core::kNotResident);
|
|
int64_t resident = 0;
|
|
for (int64_t l = 0; l < g.n_layers; ++l)
|
|
for (int64_t e = 0; e < g.n_expert; ++e) {
|
|
const int32_t slot = xcache.slot_of(l, e);
|
|
host_res[(size_t) (l * g.n_expert + e)] = slot;
|
|
if (slot != strata::core::kNotResident) ++resident;
|
|
}
|
|
if (cudaMalloc((void**) &d_res, host_res.size() * sizeof(int32_t)) != cudaSuccess ||
|
|
cudaMalloc((void**) &d_hit_count, sizeof(int32_t)) != cudaSuccess ||
|
|
cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: the device residency table could not be staged\n");
|
|
return 1;
|
|
}
|
|
thits.d_res = d_res;
|
|
thits.n_expert = g.n_expert;
|
|
thits.cache_base = drive.d.cache_base;
|
|
thits.blob = drive.d.cache_blob;
|
|
thits.d_slot = drive.d.d_slot;
|
|
thits.d_dst = drive.d.d_dst;
|
|
thits.d_count = d_hit_count;
|
|
thits.x_q8 = drive.d.x_q8_0_hit;
|
|
thits.x_scale = drive.d.x_q8_0_hit_scale;
|
|
thits.scratch = drive.d.hit_scratch;
|
|
thits.hit_out = drive.d.hit_out;
|
|
drive.d.host_res = host_res.data();
|
|
std::fprintf(stderr, "strata generate: token graph hit path: %lld resident experts, decided on the device\n",
|
|
(long long) resident);
|
|
}
|
|
if (!o.no_capture && !o.no_token_graph && layer_dump == nullptr && half_dump == nullptr &&
|
|
(hit_fn == nullptr || thits.on()) && !native_pack) {
|
|
if (!strata::core::session_capture_token(wt, g, ss, d_parts, loop_scratch.y_miss, loop_scratch.parts_bytes,
|
|
tgraph, err, thits.on() ? &thits : nullptr)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
std::fprintf(stderr, "strata generate: token graph captured (48 layers, one launch per token)\n");
|
|
}
|
|
|
|
// ================================ WHERE THE HOST TERM GOES, PER TOKEN ================================
|
|
//
|
|
// **`--gpu-only-full` MEASURES THE 48 LAYER GRAPHS AND THE LM HEAD AND NOTHING ELSE.** It never enters
|
|
// this loop, so it does not run `ple_stage_token`, `embed_row`, the whole-vocabulary logits readback, the
|
|
// NaN scan or the sampler - and `--no-pool --stats` against that floor was being read as "the per-layer
|
|
// round trip costs 12.4 ms" when an unknown part of it is per TOKEN, not per layer. That is the same error
|
|
// the review catalogued as A4/A5, one level down: a difference between two measurements attributed to a
|
|
// mechanism that neither of them isolates.
|
|
//
|
|
// Six accumulators, because the six have different fixes. Reported in `--stats` as ms/token. **The
|
|
// boundary after the layer loop is the one that matters**: without it the head's interval swallows all 48
|
|
// layers and the report reads as "head = 50 ms", which is not a thing that can happen to 1.4 ms of GPU
|
|
// work. That is not hypothetical - it is what the first version of this printed.
|
|
double ms_ple = 0, ms_embed = 0, ms_layers = 0, ms_head = 0, ms_readback = 0, ms_sample = 0;
|
|
int64_t phase_tokens = 0;
|
|
|
|
// ================================ plan v0.3 P8: THE PERSISTENT ENGINE (--serve) ================================
|
|
//
|
|
// The weights, the expert arena and the VRAM tier load once; then requests arrive on stdin, one per line,
|
|
//
|
|
// GEN <max_new> <id,id,...>
|
|
//
|
|
// and each generated token is written to stdout as `T <id>` as soon as its verify window is done, followed by
|
|
//
|
|
// DONE <generated> <prompt_tokens> <prompt_ms> <decode_ms> <stop|length>
|
|
//
|
|
// (`ERR <message>` instead when a request cannot run; `QUIT` ends the process). Every request starts from an
|
|
// empty sequence (`session_zero`): the prompt goes through the batched prompt path and its last token through
|
|
// the first verify window - the path all three model files share. Decoding is greedy.
|
|
if (o.serve) {
|
|
if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 || thits.d_res == nullptr || host_res.empty()) {
|
|
std::fprintf(stderr, "strata serve: needs --spec T, --mtp DIR, --prefill CHUNK, --expert-profile P and "
|
|
"--expert-cache\n");
|
|
return 2;
|
|
}
|
|
strata::prefill::Prefill sp;
|
|
void* borrow = nullptr;
|
|
uint64_t borrow_bytes = 0;
|
|
int32_t lend_first = -1;
|
|
if (!o.no_prefill_borrow && d_res != nullptr) {
|
|
const uint64_t need = strata::prefill::Prefill::bytes_needed(g, ss, o.prefill_chunk);
|
|
const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
|
|
int64_t k = (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob);
|
|
if (xcache.slot_offsets() != nullptr) {
|
|
k = 0;
|
|
while (k < xcache.slots() &&
|
|
(uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[xcache.slots() - k]) < need) ++k;
|
|
}
|
|
if (k + 128 <= xcache.slots()) {
|
|
lend_first = (int32_t) (xcache.slots() - k);
|
|
borrow = xcache.device_slot(lend_first);
|
|
borrow_bytes = xcache.slot_offsets() ? (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[lend_first])
|
|
: (uint64_t) k * (uint64_t) blob;
|
|
}
|
|
}
|
|
if (!sp.init(wt, g, ss, srcp, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) {
|
|
std::fprintf(stderr, "strata serve: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
strata::core::Verifier ver;
|
|
strata::core::VerifyHits vh;
|
|
vh.d_res = thits.d_res;
|
|
vh.cache_base = thits.cache_base;
|
|
vh.blob = thits.blob;
|
|
if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err) ||
|
|
!mtp.bind(wt, &native_head, ver.final_R_all(), err)) {
|
|
std::fprintf(stderr, "strata serve: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
ver.set_split(o.spec_split);
|
|
ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : o.pcie_mode == "kernel" ? 2
|
|
: native_pack ? 0 : 2); // auto: DMA for the native packs, the copy kernel for Q2_0
|
|
std::vector<int64_t> cur;
|
|
sp.on_chunk = [&](const float* R_rows, int64_t T, int64_t p0, std::string& e) -> bool {
|
|
std::vector<int32_t> nxt((size_t) T);
|
|
for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) cur[(size_t) (p0 + t + 1)];
|
|
return mtp.prefill(R_rows, nxt.data(), T, p0, e);
|
|
};
|
|
drive.d.plan = ver.plan_sink();
|
|
drive.d.pcie_num = std::max(0, std::min(256, (int) (o.pcie_frac * 256.0 + 0.5)));
|
|
if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f);
|
|
cudaStream_t adapt_stream = nullptr;
|
|
if (cudaStreamCreateWithFlags(&adapt_stream, cudaStreamNonBlocking) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata serve: cannot create the refill stream\n");
|
|
return 1;
|
|
}
|
|
// plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completed
|
|
std::vector<std::pair<int32_t, int32_t>> pending;
|
|
cudaEvent_t adapt_ev = nullptr;
|
|
cudaEventCreateWithFlags(&adapt_ev, cudaEventDisableTiming);
|
|
auto apply_pending = [&](bool wait) {
|
|
if (pending.empty()) return;
|
|
if (wait) cudaEventSynchronize(adapt_ev);
|
|
else if (cudaEventQuery(adapt_ev) != cudaSuccess) return;
|
|
for (const auto& [i, slot] : pending) host_res[(size_t) i] = slot;
|
|
pending.clear();
|
|
if (d_res != nullptr)
|
|
cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
|
|
};
|
|
// the VRAM tier follows the conversation (the same rule as the speculative loop below)
|
|
auto adapt = [&]() -> bool {
|
|
if (!pending.empty()) return true; // the previous swaps are still in flight
|
|
struct Swap { float gain; int32_t layer, in, out; };
|
|
std::vector<Swap> swaps;
|
|
std::vector<std::pair<float, int32_t>> cand, vict;
|
|
for (int64_t l = 0; l < g.n_layers; ++l) {
|
|
cand.clear();
|
|
vict.clear();
|
|
const float* u = drive.d.usage.data() + l * g.n_expert;
|
|
const int32_t* r = host_res.data() + l * g.n_expert;
|
|
for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) {
|
|
if (r[e] < 0) { if (u[e] >= 2.0f) cand.emplace_back(u[e], e); }
|
|
else vict.emplace_back(u[e], e);
|
|
}
|
|
if (cand.empty() || vict.empty()) continue;
|
|
std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; });
|
|
const size_t nc = std::min(cand.size(), vict.size());
|
|
std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(),
|
|
[](auto& a, auto& b) { return a.first < b.first; });
|
|
for (size_t i = 0; i < nc; ++i) {
|
|
if (cand[i].first < vict[i].first + 1.5f) break;
|
|
swaps.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second});
|
|
}
|
|
}
|
|
std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; });
|
|
if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps);
|
|
for (const Swap& s : swaps) {
|
|
const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out;
|
|
const int32_t slot = host_res[out];
|
|
const uint8_t* b = srcp->blob(s.layer, s.in);
|
|
if (slot < 0 || b == nullptr ||
|
|
cudaMemcpyAsync(xcache.device_slot(slot), b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer),
|
|
cudaMemcpyHostToDevice, adapt_stream) != cudaSuccess)
|
|
return false;
|
|
host_res[out] = strata::core::kNotResident; // evicted now: the CPU computes it meanwhile
|
|
pending.emplace_back((int32_t) in, slot); // resident once the copy has landed
|
|
}
|
|
if (!swaps.empty()) cudaEventRecord(adapt_ev, adapt_stream);
|
|
for (float& v : drive.d.usage) v *= 0.7f;
|
|
return true;
|
|
};
|
|
// ---- the prompt cache (strata/core/prompt_cache.hpp)
|
|
std::vector<strata::core::QsaState*> kv_states;
|
|
for (int64_t i = 0; i < g.n_qsa_layers(); ++i) kv_states.push_back(&ss.qsa_states[i]);
|
|
kv_states.push_back(&mtp.kv_state());
|
|
strata::core::PromptCache pcache(g, ss, kv_states, main_cs, o.prompt_cache, (uint64_t) o.cache_ram_mib << 20);
|
|
if (pcache.enabled())
|
|
std::fprintf(stderr, "strata serve: prompt cache on: up to %d checkpoints of %.1f MiB, %lld MiB for stashed "
|
|
"sequences\n", o.prompt_cache, (double) pcache.ckpt_bytes() / 1048576.0,
|
|
(long long) o.cache_ram_mib);
|
|
std::printf("READY %lld\n", (long long) o.max_context);
|
|
std::fflush(stdout);
|
|
std::string line;
|
|
int64_t rounds = 0;
|
|
const int S = o.spec;
|
|
constexpr int64_t kImStart = 248045; // <|im_start|>: a new turn begins here
|
|
// The vision path (--vision): GENI <max_new> <embeddings file> <id,id,...> carries images. The file is one
|
|
// or more strata-vision records (int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats) in prompt order;
|
|
// each image's rows go to its run of <|image_pad|> tokens, whose M-RoPE positions are mtmd's: t = p,
|
|
// h = p + y, w = p + x, and the text after the image continues at p + max(nx, ny).
|
|
constexpr int64_t kImagePad = 248056; // qwen4exp.ple.image_token_id: the PLE hash reads it for image cells
|
|
bool mrope_identity = true;
|
|
std::vector<float> img_rows;
|
|
std::vector<const float*> row_ptr;
|
|
while (std::getline(std::cin, line)) {
|
|
if (!line.empty() && line.back() == '\r') line.pop_back();
|
|
if (line == "QUIT") break;
|
|
const bool geni = line.rfind("GENI ", 0) == 0;
|
|
if (!geni && line.rfind("GEN ", 0) != 0) {
|
|
std::printf("ERR expected: GEN <max_new> <id,id,...> or GENI <max_new> <file> <id,id,...>\n");
|
|
continue;
|
|
}
|
|
char* endp = nullptr;
|
|
const long long max_new = std::strtoll(line.c_str() + (geni ? 5 : 4), &endp, 10);
|
|
std::string emb_path;
|
|
if (geni && endp != nullptr) {
|
|
while (*endp == ' ') ++endp;
|
|
char* gap = std::strchr(endp, ' ');
|
|
if (gap != nullptr) { emb_path.assign(endp, (size_t) (gap - endp)); endp = gap; }
|
|
}
|
|
std::vector<int64_t> ids;
|
|
std::string pe;
|
|
if (max_new < 1 || endp == nullptr || (geni && emb_path.empty()) || !parse_i64_list(endp, ids, pe)) {
|
|
std::printf("ERR bad request: %s\n", pe.empty() ? "max_new" : pe.c_str());
|
|
continue;
|
|
}
|
|
const int64_t n = (int64_t) ids.size();
|
|
if (geni && !o.vision) { std::printf("ERR this engine was started without --vision\n"); continue; }
|
|
if (geni || !mrope_identity) {
|
|
// positions for every cell this request can reach; the identity again for a text request
|
|
std::string ve;
|
|
row_ptr.assign((size_t) n, nullptr);
|
|
const int64_t cells = (int64_t) mrope_host.size() / 3;
|
|
auto put = [&](int64_t c, int64_t t, int64_t h, int64_t w) {
|
|
mrope_host[(size_t) c * 3] = (int32_t) t;
|
|
mrope_host[(size_t) c * 3 + 1] = (int32_t) h;
|
|
mrope_host[(size_t) c * 3 + 2] = (int32_t) w;
|
|
};
|
|
if (!geni) {
|
|
for (int64_t c = 0; c < cells; ++c) put(c, c, c, c);
|
|
} else {
|
|
struct Img { int64_t n, nx, ny; size_t off; };
|
|
std::vector<Img> imgs;
|
|
img_rows.clear();
|
|
std::FILE* f = std::fopen(emb_path.c_str(), "rb");
|
|
if (!f) ve = "cannot open " + emb_path;
|
|
while (f && ve.empty()) {
|
|
int32_t hdr[5];
|
|
const size_t got = std::fread(hdr, sizeof(int32_t), 5, f);
|
|
if (got == 0) break;
|
|
if (got != 5 || hdr[0] != 0x31455653 || hdr[1] < 1 || hdr[2] < 1 || hdr[3] < 1 ||
|
|
(int64_t) hdr[2] * hdr[3] != hdr[1] || hdr[4] != (int32_t) g.n_embd) {
|
|
ve = "bad embeddings file (expected strata-vision records of width " +
|
|
std::to_string((long long) g.n_embd) + ")";
|
|
break;
|
|
}
|
|
const size_t off = img_rows.size(), cnt = (size_t) hdr[1] * (size_t) hdr[4];
|
|
img_rows.resize(off + cnt);
|
|
if (std::fread(img_rows.data() + off, sizeof(float), cnt, f) != cnt) { ve = "short embeddings file"; break; }
|
|
imgs.push_back({hdr[1], hdr[2], hdr[3], off});
|
|
}
|
|
if (f) std::fclose(f);
|
|
int64_t p = 0, i = 0;
|
|
size_t k = 0;
|
|
while (ve.empty() && i < n) {
|
|
if (ids[(size_t) i] != kImagePad) { put(i, p, p, p); ++p; ++i; continue; }
|
|
if (k >= imgs.size()) { ve = "the prompt has more images than the embeddings file"; break; }
|
|
const Img& im = imgs[k++];
|
|
for (int64_t j = 0; j < im.n && ve.empty(); ++j)
|
|
if (i + j >= n || ids[(size_t) (i + j)] != kImagePad)
|
|
ve = "image " + std::to_string(k) + " has " + std::to_string((long long) im.n) +
|
|
" rows but fewer <|image_pad|> tokens";
|
|
for (int64_t j = 0; j < im.n && ve.empty(); ++j) {
|
|
const int64_t y = j / im.nx, x = j % im.nx;
|
|
put(i + j, p, p + y, p + x);
|
|
row_ptr[(size_t) (i + j)] = img_rows.data() + im.off + (size_t) j * (size_t) g.n_embd;
|
|
}
|
|
i += im.n;
|
|
p += std::max(im.nx, im.ny);
|
|
}
|
|
if (ve.empty() && k != imgs.size()) ve = "the embeddings file has more images than the prompt";
|
|
if (ve.empty() && n > 0 && ids[(size_t) (n - 1)] == kImagePad) ve = "the prompt cannot end in an image";
|
|
for (int64_t c = n; ve.empty() && c < cells; ++c) put(c, p + (c - n), p + (c - n), p + (c - n));
|
|
}
|
|
cudaDeviceSynchronize();
|
|
if (ve.empty() && cudaMemcpy(d_mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t),
|
|
cudaMemcpyHostToDevice) != cudaSuccess)
|
|
ve = "the image position upload failed";
|
|
if (!ve.empty()) {
|
|
// leave the table as the identity so the next text request is untouched
|
|
for (int64_t c = 0; c < cells; ++c) put(c, c, c, c);
|
|
cudaMemcpy(d_mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
|
|
mrope_identity = true;
|
|
std::printf("ERR %s\n", ve.c_str());
|
|
std::fflush(stdout);
|
|
continue;
|
|
}
|
|
mrope_identity = !geni;
|
|
}
|
|
sp.embd_rows = geni ? row_ptr.data() : nullptr;
|
|
if (n + max_new + 8 > o.max_context) {
|
|
std::printf("ERR prompt (%lld tokens) + max_new (%lld) exceeds the context (%lld)\n", (long long) n,
|
|
(long long) max_new, (long long) o.max_context);
|
|
continue;
|
|
}
|
|
bool bad = false;
|
|
for (int64_t t : ids) bad = bad || t < 0 || t >= n_vocab;
|
|
if (bad) { std::printf("ERR a token id is outside the vocabulary\n"); continue; }
|
|
cur = ids;
|
|
const Clock::time_point r0 = Clock::now();
|
|
auto report = [&](const std::string& e) {
|
|
std::fprintf(stderr, "strata serve: %s\n", e.c_str());
|
|
std::printf("ERR %s\n", e.c_str());
|
|
};
|
|
// ---- the prompt cache: continue from the longest prefix it holds (or start from an empty sequence).
|
|
// Image requests are not cached: their cells are not identified by the token ids alone.
|
|
const bool track = pcache.enabled() && !geni;
|
|
const int64_t reuse = pcache.begin(ids, !geni);
|
|
mtp.set_prompt_len(n);
|
|
std::vector<int32_t> drafts((size_t) S, 0), window((size_t) S), outv((size_t) S);
|
|
std::vector<float> dprob((size_t) S, 0.0f);
|
|
// ---- the rest of the prompt, [reuse, n - 1). A turn usually shares everything before its prompt's
|
|
// last <|im_start|> with the next one (chat templates re-render the answer, e.g. without its
|
|
// reasoning), so that position gets a checkpoint, and so do the prompt's end (a regenerated answer)
|
|
// and every `cache_every` cells of a long prompt. A short remainder goes through verify windows.
|
|
int64_t q = 0;
|
|
if (track)
|
|
for (int64_t i = n - 2; i > reuse; --i)
|
|
if (ids[(size_t) i] == kImStart) { q = i; break; }
|
|
int64_t batched_end = reuse; // [reuse, batched_end) through the batched prompt path
|
|
if (n - 1 - reuse > o.feed_max) batched_end = (q > reuse && n - 1 - q <= o.feed_max) ? q : n - 1;
|
|
if (batched_end > reuse) {
|
|
std::vector<std::pair<int32_t, int32_t>> lent_now;
|
|
apply_pending(true);
|
|
if (lend_first >= 0) {
|
|
for (size_t i = 0; i < host_res.size(); ++i)
|
|
if (host_res[i] >= lend_first) {
|
|
lent_now.emplace_back((int32_t) i, host_res[i]);
|
|
host_res[i] = strata::core::kNotResident;
|
|
}
|
|
cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
|
|
}
|
|
for (int64_t a0 = reuse; a0 < batched_end;) {
|
|
const int64_t b0 = track ? std::min(batched_end, (a0 / o.cache_every + 1) * o.cache_every)
|
|
: batched_end;
|
|
if (!sp.run(ids.data() + a0, b0 - a0, a0, err)) { report(err); return 1; }
|
|
if (track) {
|
|
pcache.set(a0, ids.data() + a0, b0 - a0);
|
|
if (b0 % o.cache_every == 0 || b0 == q || b0 == n - 1) pcache.checkpoint(b0);
|
|
}
|
|
a0 = b0;
|
|
}
|
|
for (const auto& [i, slot] : lent_now) {
|
|
const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert);
|
|
if (b == nullptr || !xcache.fill_slot_blocking(slot, b, err,
|
|
(int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert))) {
|
|
std::printf("ERR refilling a lent slot failed: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
host_res[(size_t) i] = slot;
|
|
}
|
|
if (!lent_now.empty())
|
|
cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
|
|
}
|
|
// prompt tokens through verify windows: each window is committed whole, and the draft layer catches up
|
|
// on the same cells (its drafts are not used)
|
|
auto feed = [&](int64_t from, int64_t to) -> bool {
|
|
for (int64_t j = from; j < to;) {
|
|
const int T = (int) std::min<int64_t>(S, to - j);
|
|
for (int i = 0; i < T; ++i) window[(size_t) i] = (int32_t) ids[(size_t) (j + i)];
|
|
drive.d.layers = 0;
|
|
drive.d.experts = 0;
|
|
drive.d.failed = false;
|
|
apply_pending(false);
|
|
if (!ver.run(T, window.data(), j, &drive_pool_multi, &drive, outv.data(), err) || drive.d.failed) {
|
|
if (drive.d.failed && drive.d.fail) err = drive.d.fail;
|
|
return false;
|
|
}
|
|
if (!ver.commit(T, err)) return false;
|
|
for (int i = 0; i < T; ++i) outv[(size_t) i] = (int32_t) ids[(size_t) (j + i + 1)];
|
|
if (!mtp.draft(T, outv.data(), j, T - 1, drafts.data(), err, dprob.data(), (float) o.spec_min_p))
|
|
return false;
|
|
if (track) pcache.set(j, ids.data() + j, T);
|
|
j += T;
|
|
}
|
|
return true;
|
|
};
|
|
const int64_t split = q > batched_end ? q : batched_end;
|
|
if (!feed(batched_end, split)) { report(err); return 1; }
|
|
if (track && split == q) pcache.checkpoint(q);
|
|
if (!feed(split, n - 1)) { report(err); return 1; }
|
|
if (track) pcache.checkpoint(n - 1);
|
|
const double prompt_ms = std::chrono::duration<double, std::milli>(Clock::now() - r0).count();
|
|
// the verify windows: the first holds the last prompt token alone
|
|
int64_t p = n - 1;
|
|
int32_t x = (int32_t) ids[(size_t) (n - 1)];
|
|
bool first_window = true;
|
|
int64_t produced_n = 0;
|
|
const char* finish = "length";
|
|
const Clock::time_point d0 = Clock::now();
|
|
while (produced_n < max_new) {
|
|
int T = S;
|
|
if (o.spec_min_p > 0.0) {
|
|
T = 1;
|
|
while (T < S && dprob[(size_t) T - 1] >= (float) o.spec_min_p) ++T;
|
|
}
|
|
if (first_window) T = 1;
|
|
// Never verify past what this request emits: the committed cells then hold exactly the tokens the
|
|
// client saw, so its next turn continues from them. So the window stops at the output limit and
|
|
// at a drafted end-of-turn token.
|
|
T = (int) std::min<int64_t>(T, max_new - produced_n);
|
|
for (int i = 1; i < T; ++i)
|
|
if (std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) drafts[(size_t) i - 1]) != o.eos_ids.end()) {
|
|
T = i + 1;
|
|
break;
|
|
}
|
|
if (p + T > o.max_context) break;
|
|
window[0] = x;
|
|
for (int i = 1; i < T; ++i) window[(size_t) i] = drafts[(size_t) i - 1];
|
|
drive.d.layers = 0;
|
|
drive.d.experts = 0;
|
|
drive.d.failed = false;
|
|
apply_pending(false);
|
|
if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err) || drive.d.failed) {
|
|
std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str());
|
|
return 1;
|
|
}
|
|
int a = 0;
|
|
while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a;
|
|
std::thread adapt_thr; // the adaptive tier beside the commit and the draft (as in generate)
|
|
bool adapt_ok = true;
|
|
if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0)
|
|
adapt_thr = std::thread([&] { adapt_ok = adapt(); });
|
|
if (!ver.commit(a + 1, err)) {
|
|
if (adapt_thr.joinable()) adapt_thr.join();
|
|
std::printf("ERR %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
if (track) pcache.set(p, window.data(), a + 1); // the committed cells p .. p + a
|
|
first_window = false;
|
|
bool eos = false;
|
|
for (int i = 0; i <= a && produced_n < max_new && !eos; ++i) {
|
|
std::printf("T %d\n", (int) outv[(size_t) i]);
|
|
++produced_n;
|
|
eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end();
|
|
}
|
|
std::fflush(stdout);
|
|
++rounds;
|
|
const bool drafted = eos || produced_n >= max_new ||
|
|
mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) o.spec_min_p);
|
|
if (adapt_thr.joinable()) adapt_thr.join();
|
|
if (!adapt_ok) {
|
|
std::printf("ERR an adaptive refill failed\n");
|
|
return 1;
|
|
}
|
|
if (!drafted) {
|
|
std::printf("ERR %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
if (eos) { finish = "stop"; break; }
|
|
x = outv[(size_t) a];
|
|
p += a + 1;
|
|
}
|
|
const double decode_ms = std::chrono::duration<double, std::milli>(Clock::now() - d0).count();
|
|
std::printf("DONE %lld %lld %.1f %.1f %s %lld\n", (long long) produced_n, (long long) n, prompt_ms, decode_ms,
|
|
finish, (long long) reuse);
|
|
std::fflush(stdout);
|
|
const int64_t fresh = n - reuse;
|
|
std::fprintf(stderr, "strata serve: %lld prompt tokens (%lld cached) in %.0f ms (%.1f tok/s), %lld generated "
|
|
"in %.0f ms (%.1f tok/s)\n", (long long) n, (long long) reuse, prompt_ms,
|
|
prompt_ms > 0 ? 1000.0 * fresh / prompt_ms : 0.0, (long long) produced_n, decode_ms,
|
|
decode_ms > 0 ? 1000.0 * produced_n / decode_ms : 0.0);
|
|
if (pcache.enabled()) std::fprintf(stderr, "strata serve: prompt cache: %s\n", pcache.summary().c_str());
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
// ---- plan v0.3 P5: the prompt's conditioning positions [0, n_prompt - 1) in batched chunks. The token loop
|
|
// then starts at the last prompt position, whose prediction is the first generated token.
|
|
int64_t pos_start = 0;
|
|
int64_t spec_pos = 0; // plan v0.3 P6: where the speculative loop starts (0 = not used)
|
|
strata::prefill::Prefill prefill;
|
|
double prefill_batched_ms = 0;
|
|
std::FILE* final_r = o.dump_final_r.empty() ? nullptr : std::fopen(o.dump_final_r.c_str(), "wb");
|
|
std::vector<float> final_r_host(final_r ? (size_t) (g.hc * g.n_embd) : 0);
|
|
std::vector<std::pair<int32_t, int32_t>> lent; // (residency index, slot) lent to the prompt path
|
|
if (o.prefill_chunk > 0 && n_prompt > 1) {
|
|
void* borrow = nullptr;
|
|
uint64_t borrow_bytes = 0;
|
|
if (!o.no_prefill_borrow && !host_res.empty() && d_res != nullptr) {
|
|
const uint64_t need = strata::prefill::Prefill::bytes_needed(g, ss, o.prefill_chunk);
|
|
const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
|
|
int64_t k = (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob);
|
|
if (xcache.slot_offsets() != nullptr) { // sized slots: take slots from the end until they hold `need`
|
|
k = 0;
|
|
while (k < xcache.slots() &&
|
|
(uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[xcache.slots() - k]) < need) ++k;
|
|
}
|
|
if (k + 128 <= xcache.slots()) { // the lent slots are refilled after the prompt
|
|
const int32_t first = (int32_t) (xcache.slots() - k);
|
|
for (size_t i = 0; i < host_res.size(); ++i)
|
|
if (host_res[i] >= first) {
|
|
lent.emplace_back((int32_t) i, host_res[i]);
|
|
host_res[i] = strata::core::kNotResident;
|
|
}
|
|
cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
|
|
borrow = xcache.device_slot(first);
|
|
borrow_bytes = xcache.slot_offsets() ? (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[first])
|
|
: (uint64_t) k * (uint64_t) blob;
|
|
std::fprintf(stderr, "strata generate: prompt path borrows %lld cache slots (%.2f GiB)\n", (long long) k,
|
|
(double) borrow_bytes / 1073741824.0);
|
|
}
|
|
}
|
|
if (borrow == nullptr)
|
|
std::fprintf(stderr, "strata generate: prompt path allocates its own buffers (no cache slots to borrow)\n");
|
|
if (!prefill.init(wt, g, ss, srcp, o.expert_cache > 0 ? &xcache : nullptr,
|
|
host_res.empty() ? nullptr : host_res.data(), o.prefill_chunk, main_cs, err, borrow,
|
|
borrow_bytes)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
if (!o.mtp.empty()) {
|
|
if (!mtp.bind(wt, &native_head, nullptr, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
prefill.on_chunk = [&](const float* R_rows, int64_t T, int64_t p0, std::string& e) -> bool {
|
|
// cell i pairs R_i with the token at i + 1 (every such token is in the prompt)
|
|
std::vector<int32_t> nxt((size_t) T);
|
|
for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) o.tokens[(size_t) (p0 + t + 1)];
|
|
return mtp.prefill(R_rows, nxt.data(), T, p0, e);
|
|
};
|
|
}
|
|
const Clock::time_point tp0 = Clock::now();
|
|
const int64_t n_batched = (o.prefill_until > 0 && o.prefill_until < n_prompt - 1) ? o.prefill_until : n_prompt - 1;
|
|
if (!prefill.run(o.tokens.data(), n_batched, 0, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
// refill the lent slots from the arena and give them back to the decode tier
|
|
if (!lent.empty()) {
|
|
const Clock::time_point tr = Clock::now();
|
|
for (const auto& [i, slot] : lent) {
|
|
const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert);
|
|
if (b == nullptr || !xcache.fill_slot_blocking(slot, b, err,
|
|
(int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert))) {
|
|
std::fprintf(stderr, "strata generate: refilling a lent slot failed: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
host_res[(size_t) i] = slot;
|
|
}
|
|
cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
|
|
std::fprintf(stderr, "strata generate: %zu lent slots refilled in %.1f ms\n", lent.size(),
|
|
std::chrono::duration<double, std::milli>(Clock::now() - tr).count());
|
|
}
|
|
prefill_batched_ms = std::chrono::duration<double, std::milli>(Clock::now() - tp0).count();
|
|
prefill_ms += prefill_batched_ms;
|
|
pos_start = n_batched;
|
|
tok = o.tokens[(size_t) pos_start];
|
|
// the PLE window of the token path: the two tokens before `pos_start`
|
|
ss.ple_prev[0] = pos_start >= 2 ? (int32_t) o.tokens[(size_t) (pos_start - 2)] : -1;
|
|
ss.ple_prev[1] = pos_start >= 1 ? (int32_t) o.tokens[(size_t) (pos_start - 1)] : -1;
|
|
const strata::prefill::PrefillStats& ps = prefill.stats();
|
|
std::fprintf(stderr, "strata generate: prefill %lld tokens in %lld chunks, %.1f ms (%.1f tok/s); experts "
|
|
"streamed %lld (%lld by DMA, host %.1f ms), resident %lld; PLE %.1f ms\n",
|
|
(long long) ps.tokens, (long long) ps.chunks, ps.ms_total,
|
|
ps.ms_total > 0 ? 1000.0 * (double) ps.tokens / ps.ms_total : 0.0, (long long) ps.experts_streamed,
|
|
(long long) ps.experts_dma, ps.ms_experts_host, (long long) ps.experts_resident, ps.ms_ple);
|
|
}
|
|
|
|
for (int64_t pos = pos_start;; ++pos) {
|
|
// plan v0.3 P6: a native pack's last prompt token is the first verify window (T = 1)
|
|
if (native_pack) { spec_pos = pos; break; }
|
|
if (pos >= o.max_context) {
|
|
std::fprintf(stderr, "strata generate: ran out of context at position %lld\n", (long long) pos);
|
|
return 2;
|
|
}
|
|
// **THE TOKEN TIMER STARTS HERE, BEFORE ANY OF THE TOKEN'S WORK (A7).** It used to start after
|
|
// `put_input`/`embed_row`, which excluded the embedding and the PLE window advance from the reported
|
|
// rate, and it stopped before the NaN scan, the logits dump and the sampler. The published tok/s
|
|
// figure is a WALL-CLOCK rate: everything one token costs, PLE advance to sampled id. A rate that
|
|
// excludes real per-token work is not a rate anyone can plan against.
|
|
const Clock::time_point t0 = Clock::now();
|
|
// **THE PLE'S TOKEN WINDOW ADVANCES HERE, ONCE PER TOKEN, AND `ple_stage_token` RUNS OUTSIDE THE
|
|
// CAPTURE.** Both are the driver's job: `ngram_rows` is a host hash over the last three tokens and the
|
|
// table gather is a host read, so either one inside a captured graph would run once at capture time and
|
|
// replay forever. `ple_prev` is OLDEST FIRST and `-1` means "no predecessor", which `ngram_rows`
|
|
// treats as the EOS cut - a sequence boundary.
|
|
ss.ple_token = (int32_t) tok;
|
|
Clock::time_point tp = Clock::now();
|
|
// Plan v0.3 P2: the 16 SSD reads start here and complete while the embedding is staged; `ms_ple` is
|
|
// the issue plus the time still spent WAITING afterwards, i.e. the part the embedding did not hide.
|
|
if (ss.ple.ready() && !strata::core::ple_issue_token(ss.ple, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
{
|
|
const Clock::time_point n = Clock::now();
|
|
ms_ple += std::chrono::duration<double, std::milli>(n - tp).count();
|
|
tp = n;
|
|
}
|
|
if (!put_input(tok, pos)) return 1;
|
|
{
|
|
const Clock::time_point n = Clock::now();
|
|
ms_embed += std::chrono::duration<double, std::milli>(n - tp).count();
|
|
tp = n;
|
|
}
|
|
if (ss.ple.ready() && !strata::core::ple_finish_token(ss.ple, token_stream, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
{
|
|
const Clock::time_point n = Clock::now();
|
|
ms_ple += std::chrono::duration<double, std::milli>(n - tp).count();
|
|
tp = n;
|
|
}
|
|
|
|
if (pos % 256 == 0 || pos + 1 >= n_prompt - 1)
|
|
std::fprintf(stderr, "strata generate: position %lld, token %lld%s\n", (long long) pos, (long long) tok,
|
|
pos < n_prompt ? " (prompt)" : "");
|
|
// **`d.layers` IS THE BLOB'S LAYER AXIS, NOT A COUNTER.** The adapter uses it to index
|
|
// `experts.bin` as `layer * n_expert + expert`, so it MUST restart at 0 for every token. Leaving it
|
|
// running across tokens asks for layer 48 of a 48-layer file on the second token - which
|
|
// `FileExpertSource` REFUSES rather than wrapping into layer 0's experts, and that refusal is the only
|
|
// reason this was a clean error instead of a silently wrong second token.
|
|
drive.d.layers = 0;
|
|
drive.d.experts = 0;
|
|
drive.d.failed = false;
|
|
err.clear();
|
|
if (o.no_capture) {
|
|
if (!strata::core::session_token(wt, g, pos, /*pos_base=*/0, ss, d_parts, main_cs,
|
|
o.sync_every_layer, err)) {
|
|
std::fprintf(stderr, "strata generate: session_token: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
} else {
|
|
strata::core::doorbell_reset(db);
|
|
if (tgraph.captured) {
|
|
if (!strata::core::session_run_token(g, pos, /*pos_base=*/0, ss, tgraph, pool_fn, pool_user,
|
|
loop_scratch.y_miss, main_cs, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
} else if (!strata::core::session_loop(g, pos, /*pos_base=*/0, ss, gr, pool_fn, hit_fn, pool_user, /*overlap=*/true, main_cs,
|
|
err, layer_stage, &loop_scratch)) {
|
|
std::fprintf(stderr, "strata generate: session_loop: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
}
|
|
if (final_r != nullptr) {
|
|
cudaMemcpy(final_r_host.data(), ss.R, final_r_host.size() * sizeof(float), cudaMemcpyDeviceToHost);
|
|
const int64_t posrec[2] = {pos, tok};
|
|
std::fwrite(posrec, sizeof posrec, 1, final_r);
|
|
std::fwrite(final_r_host.data(), sizeof(float), final_r_host.size(), final_r);
|
|
}
|
|
if (drive.d.failed) {
|
|
std::fprintf(stderr, "strata generate: the expert pool failed at layer %lld expert %lld: %s\n",
|
|
(long long) drive.d.fail_layer, (long long) drive.d.fail_expert,
|
|
drive.d.fail ? drive.d.fail : "(no message)");
|
|
return 1;
|
|
}
|
|
{
|
|
// **THE LAYER LOOP ITSELF, WHICH IS WHAT `--gpu-only-full` HAS TO BE COMPARED AGAINST.**
|
|
const Clock::time_point n = Clock::now();
|
|
ms_layers += std::chrono::duration<double, std::milli>(n - tp).count();
|
|
tp = n;
|
|
}
|
|
// ---- the ladder for THIS position, in the order `session_loop` filled it: layer 0 first.
|
|
if (layer_dump != nullptr) std::fwrite(layer_stage, sizeof(float), layer_floats, layer_dump);
|
|
if (half_dump != nullptr) {
|
|
std::fwrite(half_stage, sizeof(float), (size_t) g.n_layers * (size_t) half_stride, half_dump);
|
|
}
|
|
if (!run_head(token_stream)) {
|
|
std::fprintf(stderr, "strata generate: lm_head: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
// **A CHECKPOINT AFTER THE HEAD, BECAUSE AN ASYNC FAULT IS STICKY AND LIES ABOUT WHERE IT HAPPENED.**
|
|
// Measured, and it cost an hour: without this, `embed_row`'s D2H on the NEXT token reported "an illegal
|
|
// memory access" at a plane offset that has nothing to do with the fault, and the layer that actually
|
|
// faulted had completed its own error checks successfully - because its kernels had not run yet. A
|
|
// sticky error surfaces at the next SYNCHRONISING call, which is whatever happens to come next.
|
|
if (!o.stream_token && cudaDeviceSynchronize() != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: the device faulted in lm_head at position %lld: %s\n",
|
|
(long long) pos, cudaGetErrorString(cudaGetLastError()));
|
|
return 1;
|
|
}
|
|
{
|
|
const Clock::time_point n = Clock::now();
|
|
ms_head += std::chrono::duration<double, std::milli>(n - tp).count();
|
|
tp = n;
|
|
}
|
|
const bool emit_logits = dump != nullptr &&
|
|
strata::program::logits_selection::selected(pos, dump_positions, o.logits_stride);
|
|
const bool read_logits = !o.stream_token || o.check_logits || emit_logits;
|
|
if (read_logits && (cudaMemcpyAsync(logits.data(), d_logits, (size_t) n_vocab * 4,
|
|
cudaMemcpyDeviceToHost, (cudaStream_t) token_stream) != cudaSuccess ||
|
|
cudaStreamSynchronize((cudaStream_t) token_stream) != cudaSuccess)) {
|
|
std::fprintf(stderr, "strata generate: reading the logits back failed\n");
|
|
return 1;
|
|
}
|
|
int bad = 0;
|
|
if (read_logits) for (float v : logits) if (!std::isfinite(v)) ++bad;
|
|
if (bad != 0) {
|
|
std::fprintf(stderr, "strata generate: %d of %lld logits are not finite at position %lld\n", bad,
|
|
(long long) n_vocab, (long long) pos);
|
|
return 1;
|
|
}
|
|
if (emit_logits && std::fwrite(logits.data(), sizeof(float), (size_t) n_vocab, dump) != (size_t) n_vocab) {
|
|
std::fprintf(stderr, "strata generate: cannot write logits at position %lld\n", (long long) pos);
|
|
std::fclose(dump);
|
|
return 1;
|
|
}
|
|
{
|
|
// **993 KB OF SYNCHRONOUS D2H AND A 248,320-FLOAT HOST SCAN, EVERY TOKEN.** (The review's notes
|
|
// say 151,936 floats; the artifact's `output.weight` is 248,320 rows, so the real figure is 1.6x
|
|
// that - a number nobody had checked because nothing measured this term.) R2.6 asks for the dump
|
|
// and the scan to be behind flags; round 36 did exactly that and measured it SLOWER, because on
|
|
// this driver a large blocking readback is also what flushes the pipeline for the sampler that
|
|
// follows. Timed so the claim can be re-checked rather than remembered.
|
|
const Clock::time_point n = Clock::now();
|
|
ms_readback += std::chrono::duration<double, std::milli>(n - tp).count();
|
|
tp = n;
|
|
}
|
|
|
|
int next = 0;
|
|
// Teacher-forced prompt rows consume no generation draws.
|
|
sp.counter = (uint64_t) produced.size();
|
|
strata::kernels::sample_tokens(d_logits, 1, (int) n_vocab, nullptr, 0, sp, d_next, token_stream);
|
|
if (cudaMemcpyAsync(&next, d_next, sizeof(int), cudaMemcpyDeviceToHost,
|
|
(cudaStream_t) token_stream) != cudaSuccess ||
|
|
cudaStreamSynchronize((cudaStream_t) token_stream) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: reading the sampled token back failed: %s\n",
|
|
cudaGetErrorString(cudaGetLastError()));
|
|
return 1;
|
|
}
|
|
// The sampled-token synchronization also completes every captured QSA
|
|
// status readback. Retain one status per layer so a later layer cannot
|
|
// hide an earlier failure; no extra synchronization or token allocation.
|
|
if (o.native_flash_attn_short) for (int64_t i = 0; i < g.n_qsa_layers(); ++i) {
|
|
const int32_t status = ss.qsa_states[i].host_step[strata::kernels::kStepCount];
|
|
if (status != 0) {
|
|
std::fprintf(stderr, "strata generate: native attention status %d at QSA layer %lld, position %lld\n",
|
|
status, (long long) i, (long long) pos);
|
|
return 1;
|
|
}
|
|
}
|
|
if (next < 0 || next >= n_vocab) {
|
|
std::fprintf(stderr, "strata generate: the sampler returned %d, outside 0..%lld\n", next,
|
|
(long long) (n_vocab - 1));
|
|
return 1;
|
|
}
|
|
{
|
|
// **TWO DEVICE-WIDE SYNCS FOR FOUR BYTES.** `sample_tokens(nullptr)` ends in
|
|
// `cudaDeviceSynchronize()` (`sampler.cu:245`) and the blocking 4-byte read below is the second.
|
|
const Clock::time_point n = Clock::now();
|
|
ms_sample += std::chrono::duration<double, std::milli>(n - tp).count();
|
|
++phase_tokens;
|
|
}
|
|
// CHARGED HERE, AFTER THE SAMPLER, so the wall-clock rate covers the whole token including the embedding,
|
|
// the NaN scan, the logits readback and the sample (A7). Only DECODE positions count; prefill is
|
|
// measured separately.
|
|
if (pos >= n_prompt - 1) total_ms += std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
|
|
else prefill_ms += std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
|
|
if (pos == n_prompt - 1) ttft_ms = std::chrono::duration<double, std::milli>(Clock::now() - t_start).count();
|
|
// **THE PREDICTION AT THE LAST PROMPT POSITION *IS* THE FIRST GENERATED TOKEN.** Sampling on every
|
|
// position and recording only from `n_prompt - 1` onward is what keeps the two cases from needing
|
|
// separate handling - and the version that "obviously" only samples after the prompt loses exactly one
|
|
// token's worth of conditioning.
|
|
if (pos >= n_prompt - 1) produced.push_back(next);
|
|
if ((int64_t) produced.size() >= o.max_new) break;
|
|
if (o.stop_eos && pos >= n_prompt - 1 &&
|
|
std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) next) != o.eos_ids.end()) break;
|
|
// TEACHER FORCING while the prompt lasts: the next input is the prompt's own next token, not the
|
|
// model's guess. Feeding the guess would make the run depend on the model's own errors from position
|
|
// 1, which is a different (and worse) measurement of the same prompt.
|
|
// and the window advances: the token just decoded becomes the newest predecessor.
|
|
ss.ple_prev[0] = ss.ple_prev[1];
|
|
ss.ple_prev[1] = (int32_t) tok;
|
|
tok = (pos + 1 < n_prompt) ? o.tokens[(size_t) (pos + 1)] : next;
|
|
// Plan v0.3 P6: from the first generated token on, the speculative loop below takes over.
|
|
if (o.spec > 0 && pos >= n_prompt - 1) { spec_pos = pos + 1; break; }
|
|
}
|
|
|
|
// ================================ plan v0.3 P6: SPECULATIVE DECODING ================================
|
|
//
|
|
// Each round verifies [the last emitted token, drafts...] in one window; the window's argmax after token t
|
|
// is exactly what greedy decode would emit there, so the first draft that differs ends the round and the
|
|
// round emits (accepted drafts + 1) tokens. `commit` keeps the state of the tokens that were emitted.
|
|
const bool ended = o.stop_eos && !produced.empty() &&
|
|
std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) produced.back()) != o.eos_ids.end();
|
|
if (spec_pos > 0 && (int64_t) produced.size() < o.max_new && !ended) {
|
|
std::vector<int64_t> oracle;
|
|
if (!o.spec_oracle.empty()) {
|
|
std::ifstream in(o.spec_oracle);
|
|
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
|
std::string e;
|
|
if (!in || !parse_i64_list(text.c_str(), oracle, e)) {
|
|
std::fprintf(stderr, "strata generate: cannot read --spec-oracle %s\n", o.spec_oracle.c_str());
|
|
return 2;
|
|
}
|
|
}
|
|
if (thits.d_res == nullptr) {
|
|
std::fprintf(stderr, "strata generate: --spec needs the device residency table (--expert-profile, "
|
|
"--expert-cache and the token graph)\n");
|
|
return 2;
|
|
}
|
|
strata::core::Verifier ver;
|
|
strata::core::VerifyHits vh;
|
|
vh.d_res = thits.d_res;
|
|
vh.cache_base = thits.cache_base;
|
|
vh.blob = thits.blob;
|
|
if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
const bool use_mtp = !o.mtp.empty();
|
|
if (use_mtp && !mtp.bind(wt, &native_head, ver.final_R_all(), err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
ver.set_split(o.spec_split);
|
|
ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : o.pcie_mode == "kernel" ? 2
|
|
: native_pack ? 0 : 2); // auto: DMA for the native packs, the copy kernel for Q2_0
|
|
drive.d.plan = ver.plan_sink();
|
|
drive.d.pcie_num = (int) (o.pcie_frac * 256.0 + 0.5);
|
|
if (drive.d.pcie_num < 0) drive.d.pcie_num = 0;
|
|
if (drive.d.pcie_num > 256) drive.d.pcie_num = 256;
|
|
const int64_t pcie0 = drive.d.pcie_experts;
|
|
if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f);
|
|
int64_t swaps_total = 0;
|
|
double ms_adapt = 0;
|
|
cudaStream_t adapt_stream = nullptr;
|
|
if (!drive.d.usage.empty() && cudaStreamCreateWithFlags(&adapt_stream, cudaStreamNonBlocking) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: cannot create the refill stream\n");
|
|
return 1;
|
|
}
|
|
// plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completed
|
|
std::vector<std::pair<int32_t, int32_t>> pending;
|
|
cudaEvent_t adapt_ev = nullptr;
|
|
cudaEventCreateWithFlags(&adapt_ev, cudaEventDisableTiming);
|
|
auto apply_pending = [&](bool wait) {
|
|
if (pending.empty()) return;
|
|
if (wait) cudaEventSynchronize(adapt_ev);
|
|
else if (cudaEventQuery(adapt_ev) != cudaSuccess) return;
|
|
for (const auto& [i, slot] : pending) host_res[(size_t) i] = slot;
|
|
pending.clear();
|
|
if (d_res != nullptr)
|
|
cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
|
|
};
|
|
// Plan v0.3 P6: the VRAM tier follows the conversation. Candidates are missing experts routed at least
|
|
// twice (decayed); each is paired with its layer's least-routed resident expert and swapped when it was
|
|
// routed clearly more often. Copies run between rounds, when the GPU is idle.
|
|
auto adapt = [&]() -> bool {
|
|
const Clock::time_point ta = Clock::now();
|
|
if (!pending.empty()) return true; // the previous swaps are still in flight
|
|
struct Swap { float gain; int32_t layer, in, out; };
|
|
std::vector<Swap> swaps;
|
|
std::vector<std::pair<float, int32_t>> cand, vict;
|
|
for (int64_t l = 0; l < g.n_layers; ++l) {
|
|
cand.clear();
|
|
vict.clear();
|
|
const float* u = drive.d.usage.data() + l * g.n_expert;
|
|
const int32_t* r = host_res.data() + l * g.n_expert;
|
|
for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) {
|
|
if (r[e] < 0) { if (u[e] >= 2.0f) cand.emplace_back(u[e], e); }
|
|
else vict.emplace_back(u[e], e);
|
|
}
|
|
if (cand.empty() || vict.empty()) continue;
|
|
std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; });
|
|
const size_t nc = std::min(cand.size(), vict.size());
|
|
std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(),
|
|
[](auto& a, auto& b) { return a.first < b.first; });
|
|
for (size_t i = 0; i < nc; ++i) {
|
|
if (cand[i].first < vict[i].first + 1.5f) break;
|
|
swaps.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second});
|
|
}
|
|
}
|
|
std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; });
|
|
if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps);
|
|
for (const Swap& s : swaps) {
|
|
const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out;
|
|
const int32_t slot = host_res[out];
|
|
const uint8_t* b = srcp->blob(s.layer, s.in);
|
|
// asynchronous: the copies run while the MTP drafts; the next window waits for them
|
|
if (slot < 0 || b == nullptr ||
|
|
cudaMemcpyAsync(xcache.device_slot(slot), b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer),
|
|
cudaMemcpyHostToDevice, adapt_stream) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: an adaptive refill failed\n");
|
|
return false;
|
|
}
|
|
host_res[out] = strata::core::kNotResident; // evicted now: the CPU computes it meanwhile
|
|
pending.emplace_back((int32_t) in, slot); // resident once the copy has landed
|
|
}
|
|
if (!swaps.empty()) cudaEventRecord(adapt_ev, adapt_stream);
|
|
for (float& v : drive.d.usage) v *= 0.7f;
|
|
swaps_total += (int64_t) swaps.size();
|
|
ms_adapt += std::chrono::duration<double, std::milli>(Clock::now() - ta).count();
|
|
return true;
|
|
};
|
|
int64_t p = spec_pos;
|
|
int32_t x = (int32_t) tok;
|
|
std::vector<int32_t> drafts((size_t) o.spec, 0);
|
|
std::vector<float> dprob((size_t) o.spec, 1.0f);
|
|
std::vector<int64_t> window_hist((size_t) o.spec + 1, 0);
|
|
// plan v0.3 P6: with a native pack the first window is the last prompt token alone (it produces the first
|
|
// generated token and the MTP's first cell); otherwise the token loop already did that.
|
|
bool first_window = native_pack;
|
|
if (use_mtp && !first_window &&
|
|
!mtp.draft_first(o.spec, ss.R, x, p - 1, drafts.data(), err, dprob.data(), (float) o.spec_min_p)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
std::vector<int32_t> window((size_t) o.spec), outv((size_t) o.spec);
|
|
std::vector<int64_t> accepted_hist((size_t) o.spec, 0);
|
|
int64_t rounds = 0, drafts_total = 0, drafts_ok = 0, corrupt_counter = 0;
|
|
const double pool_ms0 = drive.cpu_ms;
|
|
const int64_t misses0 = drive.d.multi_misses, entries0 = drive.d.multi_entries;
|
|
while ((int64_t) produced.size() < o.max_new) {
|
|
const Clock::time_point t0 = Clock::now();
|
|
int T = o.spec;
|
|
if (use_mtp && o.spec_min_p > 0.0) {
|
|
T = 1;
|
|
while (T < o.spec && dprob[(size_t) T - 1] >= (float) o.spec_min_p) ++T;
|
|
}
|
|
if (first_window) T = 1;
|
|
++window_hist[(size_t) T];
|
|
if (p + T > o.max_context) {
|
|
std::fprintf(stderr, "strata generate: ran out of context at position %lld\n", (long long) p);
|
|
return 2;
|
|
}
|
|
window[0] = x;
|
|
for (int i = 1; i < T; ++i) {
|
|
const size_t at = produced.size() - 1 + (size_t) i;
|
|
int32_t d = use_mtp ? drafts[(size_t) i - 1] : at < oracle.size() ? (int32_t) oracle[at] : 0;
|
|
if (o.spec_corrupt > 0 && (++corrupt_counter % o.spec_corrupt) == 0) d = (d + 1) % (int32_t) n_vocab;
|
|
window[(size_t) i] = d;
|
|
}
|
|
drive.d.layers = 0;
|
|
drive.d.experts = 0;
|
|
drive.d.failed = false;
|
|
apply_pending(false);
|
|
if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err)) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
if (drive.d.failed) {
|
|
std::fprintf(stderr, "strata generate: the expert pool failed at layer %lld expert %lld: %s\n",
|
|
(long long) drive.d.fail_layer, (long long) drive.d.fail_expert,
|
|
drive.d.fail ? drive.d.fail : "(no message)");
|
|
return 1;
|
|
}
|
|
int a = 0;
|
|
while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a;
|
|
if (first_window) {
|
|
first_window = false;
|
|
ttft_ms = std::chrono::duration<double, std::milli>(Clock::now() - t_start).count();
|
|
}
|
|
// plan v0.3 P6: the adaptive tier's host work (ranking, copy submission) runs on its own thread while the
|
|
// GPU commits and drafts; it touches only the residency tables, which nothing reads until the next window
|
|
std::thread adapt_thr;
|
|
bool adapt_ok = true;
|
|
if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0)
|
|
adapt_thr = std::thread([&] { adapt_ok = adapt(); });
|
|
if (!ver.commit(a + 1, err)) {
|
|
if (adapt_thr.joinable()) adapt_thr.join();
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
++rounds;
|
|
drafts_total += T - 1;
|
|
drafts_ok += a;
|
|
++accepted_hist[(size_t) a];
|
|
bool eos = false;
|
|
for (int i = 0; i <= a && (int64_t) produced.size() < o.max_new && !eos; ++i) {
|
|
produced.push_back(outv[(size_t) i]);
|
|
eos = o.stop_eos && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end();
|
|
}
|
|
if (eos) {
|
|
if (adapt_thr.joinable()) adapt_thr.join();
|
|
total_ms += std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
|
|
break;
|
|
}
|
|
const bool drafted = !use_mtp || (int64_t) produced.size() >= o.max_new ||
|
|
mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) o.spec_min_p);
|
|
if (adapt_thr.joinable()) adapt_thr.join();
|
|
if (!adapt_ok) return 1;
|
|
if (!drafted) {
|
|
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
|
|
return 1;
|
|
}
|
|
x = outv[(size_t) a];
|
|
p += a + 1;
|
|
total_ms += std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
|
|
if (rounds % 64 == 0)
|
|
std::fprintf(stderr, "strata generate: position %lld, %lld tokens, %lld rounds\n", (long long) p,
|
|
(long long) produced.size(), (long long) rounds);
|
|
}
|
|
std::printf("%-24s %lld rounds of %d, drafts accepted %lld of %lld (%.3f), %.2f tokens per round\n",
|
|
"speculation", (long long) rounds, o.spec, (long long) drafts_ok, (long long) drafts_total,
|
|
drafts_total > 0 ? (double) drafts_ok / (double) drafts_total : 0.0,
|
|
rounds > 0 ? (double) (drafts_ok + rounds) / (double) rounds : 0.0);
|
|
if (o.spec_min_p > 0.0) {
|
|
std::printf("%-24s", "window sizes");
|
|
for (size_t i = 1; i < window_hist.size(); ++i) std::printf(" T%zu:%lld", i, (long long) window_hist[i]);
|
|
std::printf(" (min draft probability %.2f)\n", o.spec_min_p);
|
|
}
|
|
std::printf("%-24s", "accepted per round");
|
|
for (size_t i = 0; i < accepted_hist.size(); ++i) std::printf(" %zu:%lld", i, (long long) accepted_hist[i]);
|
|
std::printf("\n");
|
|
if (rounds > 0)
|
|
std::printf("%-24s wait for rings %.3f pool %.3f host %.3f commit %.3f ms/round; CPU experts %.2f "
|
|
"distinct / %.2f routed per layer\n",
|
|
"verify window", ver.ms_wait / rounds, ver.ms_pool / rounds, ver.ms_host / rounds,
|
|
ver.ms_commit / rounds,
|
|
(double) (drive.d.multi_misses - misses0) / (double) (rounds * g.n_layers),
|
|
(double) (drive.d.multi_entries - entries0) / (double) (rounds * g.n_layers));
|
|
if (rounds > 0)
|
|
std::printf("%-24s gate/up %.3f quantize %.3f down %.3f ms/round; %.1f GB/s over the rows phases; "
|
|
"CPU pool call %.3f ms/round\n", "pool multi", pool.ms_multi_gu / rounds,
|
|
pool.ms_multi_q / rounds, pool.ms_multi_down / rounds,
|
|
(double) pool.multi_bytes / 1e6 / std::max(1e-9, pool.ms_multi_gu + pool.ms_multi_down),
|
|
(drive.cpu_ms - pool_ms0) / rounds);
|
|
if (rounds > 0)
|
|
std::printf("%-24s plan %.3f activation quantize %.3f jobs %.3f run %.3f ms/round\n", "dispatch",
|
|
drive.d.ms_plan / rounds, drive.d.ms_actq / rounds, drive.d.ms_jobs / rounds,
|
|
drive.d.ms_run / rounds);
|
|
if (rounds > 0 && !drive.d.usage.empty())
|
|
std::printf("%-24s %lld experts swapped into the VRAM tier (every %d rounds, %.3f ms/round)\n", "adaptive tier",
|
|
(long long) swaps_total, o.adapt_every, ms_adapt / rounds);
|
|
if (rounds > 0 && drive.d.pcie_num > 0)
|
|
std::printf("%-24s %.2f distinct experts per layer read over PCIe (share %d/256 of the misses)\n",
|
|
"pcie experts", (double) (drive.d.pcie_experts - pcie0) / (double) (rounds * g.n_layers),
|
|
drive.d.pcie_num);
|
|
(void) pool_ms0;
|
|
if (use_mtp && rounds > 0)
|
|
std::printf("%-24s %.3f ms/round drafting (%lld rounds), MTP prompt %.1f ms, %.0f MiB of VRAM\n", "mtp",
|
|
mtp.ms_draft / (double) mtp.rounds, (long long) mtp.rounds, mtp.ms_prefill,
|
|
(double) mtp.vram_bytes() / 1048576.0);
|
|
}
|
|
|
|
if (dump != nullptr && std::fclose(dump) != 0) {
|
|
std::fprintf(stderr, "strata generate: cannot finish logits dump\n");
|
|
return 1;
|
|
}
|
|
if (layer_dump != nullptr) {
|
|
std::fclose(layer_dump);
|
|
cudaFreeHost(layer_stage);
|
|
std::printf("%-24s %s (%lld layers + the input x %d streams x %lld per position)\n", "layers dumped",
|
|
o.dump_layers.c_str(), (long long) g.n_layers, (int) g.hc, (long long) g.n_embd);
|
|
}
|
|
if (half_dump != nullptr) {
|
|
std::fclose(half_dump);
|
|
cudaFreeHost(half_stage);
|
|
std::printf("%-24s %s (%lld layers x %llu per position)\n", "halves dumped", o.dump_halves.c_str(),
|
|
(long long) g.n_layers, (unsigned long long) half_stride);
|
|
}
|
|
if (routing != nullptr) {
|
|
std::fclose(routing);
|
|
drive.routing = nullptr;
|
|
std::printf("%-24s %s (%lld records of layer, k, ids, weights)\n", "routing dumped",
|
|
o.dump_routing.c_str(), (long long) drive.calls);
|
|
}
|
|
if (o.stage_timing) strata::core::stage_timing_report(g.n_layers);
|
|
|
|
const int64_t decoded = (int64_t) produced.size();
|
|
std::printf("prompt :");
|
|
for (int64_t t : o.tokens) std::printf(" %lld", (long long) t);
|
|
std::printf("\noutput :");
|
|
for (int64_t t : produced) std::printf(" %lld", (long long) t);
|
|
std::printf("\n");
|
|
const double decode_ms = decoded > 0 ? total_ms / (double) decoded : 0.0;
|
|
std::printf("%-24s %lld tokens in %.1f ms -> %.2f tok/s\n", "decode", (long long) decoded, total_ms,
|
|
decode_ms > 0.0 ? 1000.0 / decode_ms : 0.0);
|
|
if (n_prompt > 1)
|
|
std::printf("%-24s %lld tokens in %.1f ms -> %.2f tok/s (time to first token %.1f ms)\n", "prefill",
|
|
(long long) (n_prompt - 1), prefill_ms,
|
|
prefill_ms > 0 ? 1000.0 * (double) (n_prompt - 1) / prefill_ms : 0.0, ttft_ms);
|
|
if (!o.dump_mixed.empty()) {
|
|
std::vector<float> mx((size_t) g.n_embd);
|
|
if (cudaMemcpy(mx.data(), ss.block.mixed, mx.size() * sizeof(float), cudaMemcpyDeviceToHost) !=
|
|
cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: reading mixed back failed\n");
|
|
return 1;
|
|
}
|
|
std::FILE* mf = std::fopen(o.dump_mixed.c_str(), "wb");
|
|
if (mf == nullptr) {
|
|
std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_mixed.c_str());
|
|
return 1;
|
|
}
|
|
std::fwrite(mx.data(), sizeof(float), mx.size(), mf);
|
|
std::fclose(mf);
|
|
double s2 = 0, mag = 0;
|
|
for (float v : mx) { s2 += (double) v * (double) v; mag += std::fabs((double) v); }
|
|
std::printf("%-24s %s (n_embd %lld, rms %.5g, mean|.| %.5g)\n", "mixed dumped", o.dump_mixed.c_str(),
|
|
(long long) g.n_embd, std::sqrt(s2 / (double) mx.size()), mag / (double) mx.size());
|
|
}
|
|
|
|
// ---- the residual, for bisecting the head against the layers (see `dump_residual`'s note)
|
|
if (!o.dump_residual.empty()) {
|
|
std::vector<float> R((size_t) g.hc * g.n_embd);
|
|
if (cudaMemcpy(R.data(), ss.R, R.size() * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) {
|
|
std::fprintf(stderr, "strata generate: reading R back failed\n");
|
|
return 1;
|
|
}
|
|
std::FILE* rf = std::fopen(o.dump_residual.c_str(), "wb");
|
|
if (rf == nullptr) {
|
|
std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_residual.c_str());
|
|
return 1;
|
|
}
|
|
const int32_t hdr[2] = {(int32_t) g.hc, (int32_t) g.n_embd};
|
|
std::fwrite(hdr, sizeof hdr, 1, rf);
|
|
std::fwrite(R.data(), sizeof(float), R.size(), rf);
|
|
std::fclose(rf);
|
|
double mag = 0, mx = 0;
|
|
int bad = 0;
|
|
for (float v : R) {
|
|
if (!std::isfinite(v)) ++bad;
|
|
else { mag += std::fabs((double) v); mx = std::max(mx, (double) std::fabs((double) v)); }
|
|
}
|
|
std::printf("%-24s %s (%d x %lld, nonfinite %d, mean|.| %.4g, max|.| %.4g)\n", "residual dumped",
|
|
o.dump_residual.c_str(), (int) g.hc, (long long) g.n_embd, bad, mag / (double) R.size(), mx);
|
|
}
|
|
|
|
if (o.stats) {
|
|
std::printf("%-24s %.3f ms/token (WALL CLOCK: embed, layers, head, sample)\n", " per token", decode_ms);
|
|
// **THE PER-TOKEN HOST TERM, WHICH `--gpu-only-full` CANNOT SEE.** That measurement never enters the
|
|
// token loop, so it excludes all six of these. On the 78-token fixture + 200 generated tokens the six
|
|
// sum to ~9 ms of non-layer work against ~1.5 ms of actual head GPU work - 16% of the token, and it is
|
|
// not the pool.
|
|
if (phase_tokens > 0) {
|
|
const double pt = (double) phase_tokens;
|
|
std::printf("%-24s PLE %.3f embed %.3f LAYERS %.3f head %.3f readback %.3f sample %.3f "
|
|
"(sum %.3f of %.3f ms)\n",
|
|
" token host phases", ms_ple / pt, ms_embed / pt, ms_layers / pt, ms_head / pt,
|
|
ms_readback / pt, ms_sample / pt,
|
|
(ms_ple + ms_embed + ms_layers + ms_head + ms_readback + ms_sample) / pt, decode_ms);
|
|
}
|
|
if (const std::string io = ple_table.io_report(); !io.empty()) std::printf(" %s\n", io.c_str());
|
|
// **THE DENOMINATOR IS THE POSITIONS THE POOL ACTUALLY RAN ON, NOT THE DECODED TOKENS (A6).**
|
|
// `drive_pool` is called once per layer per position and PREFILL runs the loop too, so accumulating
|
|
// `cpu_ms` over prefill and then dividing by `decoded` inflates this figure. `drive.calls / n_layers`
|
|
// is the number of positions - the same correction the ring counters below already received, which is
|
|
// why they print "of 192" rather than "240 of 192".
|
|
const double pool_positions = g.n_layers > 0 ? (double) drive.calls / (double) g.n_layers : 0.0;
|
|
std::printf("%-24s %.3f ms/token over %lld layers (%.0f positions, %lld dispatches)\n",
|
|
" the CPU expert pool", pool_positions > 0.0 ? drive.cpu_ms / pool_positions : 0.0,
|
|
(long long) g.n_layers, pool_positions, (long long) drive.calls);
|
|
// **AND WHERE INSIDE `run()` IT WENT.** Three phases per layer and they were one number, which cannot
|
|
// tell a pool that is slow at the WORK from one that is slow at the SYNCHRONISATION - opposite fixes.
|
|
// Wait-for-park is expected to be ~0 (the workers re-parked at the end of the previous layer); the
|
|
// question is whether the time is in the drain or in the re-park barrier.
|
|
if (pool_positions > 0.0) {
|
|
double wp = 0, dr = 0, rp = 0;
|
|
pool.phase_ms(wp, dr, rp);
|
|
const double per = pool_positions;
|
|
std::printf("%-24s wait-park %.3f drain %.3f re-park %.3f ms/token\n",
|
|
" pool phases", wp / per, dr / per, rp / per);
|
|
}
|
|
std::printf("%-24s %lld blobs read\n", " expert blobs", (long long) srcp->reads());
|
|
// ---- **R4's DISPATCH MEASUREMENT: h, ON THE ENGINE'S OWN ROUTING.** No offline trace, no corpus
|
|
// question, no k-fold - these are the ids the router actually produced on this run. Reported as
|
|
// hits/lookups so it can be read directly as the h the cache would deliver, and alongside `refused`
|
|
// so a full cache is visible rather than silently capping the rate.
|
|
if (o.expert_cache > 0) {
|
|
const int64_t look = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused;
|
|
const int64_t hl = drive.d.hit_ready + drive.d.hit_late;
|
|
std::printf("%-24s %lld of %lld layers the hit work was DONE when the pool returned\n",
|
|
" R4 overlap", (long long) drive.d.hit_ready, (long long) hl);
|
|
std::printf("%-24s %lld of %lld = %.4f (%lld admitted, %lld refused, cache %.4f%% full)\n",
|
|
" R4 expert-cache hits", (long long) drive.d.cache_hits, (long long) look,
|
|
look > 0 ? (double) drive.d.cache_hits / (double) look : 0.0,
|
|
(long long) drive.d.cache_admitted, (long long) drive.d.cache_refused,
|
|
100.0 * (double) (drive.d.cache_admitted + drive.d.cache_hits > 0
|
|
? (double) xcache.resident() / (double) xcache.slots()
|
|
: 0.0));
|
|
}
|
|
if (tgraph.captured && tgraph.calls > 0) {
|
|
const double per = (double) tgraph.calls;
|
|
std::printf("%-24s wait for rings %.3f pool %.3f ms/token (%lld flushes over %lld positions)\n",
|
|
" token graph", tgraph.ms_wait / per, tgraph.ms_pool / per, (long long) tgraph.flushes,
|
|
(long long) tgraph.calls);
|
|
}
|
|
if (gr.captured && gr.calls_total > 0) {
|
|
// The counters are CUMULATIVE over every `session_loop` call, and PREFILL runs the loop too - so
|
|
// the denominator is the number of positions, not the number of generated tokens. Dividing by
|
|
// `n_layers * decoded` printed "240 of 192", which is a reporting bug that looks like a ring
|
|
// firing more often than it should.
|
|
const int64_t positions = gr.calls_total;
|
|
std::printf("%-24s %lld of %lld over %lld positions\n", " rings seen MID-GRAPH",
|
|
(long long) gr.rings_mid_graph, (long long) (g.n_layers * positions),
|
|
(long long) positions);
|
|
std::printf("%-24s %.3f ms of a %.3f ms layer\n", " ring latency",
|
|
gr.ms_to_ring / (double) (g.n_layers * positions), decode_ms / (double) g.n_layers);
|
|
// **THE ROUND TRIP, SPLIT AT THE RING.** `ring latency` is the first half and stops when the ring
|
|
// is seen; this is the second half - the driver calls after it, during which the GPU is IDLE
|
|
// because `post[l]` has not been launched yet. `--no-pool` is the arm that isolates it: 38.73
|
|
// ms/token against a 26.32 ms pure-GPU floor is 12.4 ms of round trip with no expert work at all.
|
|
//
|
|
// Same denominator as the pool line above (the positions the loop actually ran on), so the two can
|
|
// be added without one of them being inflated by prefill.
|
|
const double perlap = (double) (g.n_layers * positions);
|
|
std::printf("%-24s %.3f ms/token over %.0f positions (%.3f ms/layer, after the ring)\n",
|
|
" host after ring", pool_positions > 0.0 ? gr.ms_host / pool_positions : 0.0,
|
|
pool_positions, gr.ms_host / perlap);
|
|
}
|
|
}
|
|
|
|
if (dump != nullptr) std::printf("%-24s %s\n", "logits dumped", o.dump_logits.c_str());
|
|
|
|
strata::core::session_graphs_free(gr);
|
|
strata::core::doorbell_free(db);
|
|
cudaFree(d_next);
|
|
cudaFree(d_logits);
|
|
cudaFree(d_emb);
|
|
cudaFree(d_parts);
|
|
cudaFree(sbuf);
|
|
cudaFree(arena);
|
|
return 0;
|
|
}
|