diff --git a/CMakeLists.txt b/CMakeLists.txt index 90c78a03..26dabf96 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1204,6 +1204,13 @@ if(STRATA_NATIVE_EXPERTS) add_test(NAME iq_avx2_parity COMMAND iq_avx2_parity) add_test(NAME iq_avx2_parity_iq3s_mt1 COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ3S_MT1=1 $) endif() + # the AVX-2 Q8_K activation quantizer against ggml's, byte for byte (--bench: its time) + add_executable(q8k_quant_parity src/kernels/cpu/q8k_quant_parity.cpp) + target_link_libraries(q8k_quant_parity PRIVATE strata_kernels_cpu) + if(STRATA_BUILD_TESTS) + add_test(NAME q8k_quant_parity COMMAND q8k_quant_parity) + add_test(NAME q8k_quant_parity_avx COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_ISA=avx $) + endif() set(_strata_mmq_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) # #296: OrcaRouter Q4_K_S's Q5_0 experts (Q4_K and Q5_1 come with STRATA_MMQ_KQUANTS on CUDA, S5's branch) if(STRATA_ORCA_Q4KS_MMQ) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 9a053278..f1941417 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -621,8 +621,33 @@ The server listens on `http://127.0.0.1:8080` (change with `--port` in setup, or | What the model is doing right now | `GET /status`, `GET /slots` (busy or idle, with `n_prompt_tokens`; one entry per slot with `--batch`) | | Save / restore the conversation to a file (session files, below) | `POST /slots/0?action=save\|restore` | | Everything the Monitor tab shows (engine, live state, last requests, hardware) | `GET /metrics` | +| The same for Prometheus, with vLLM's metric names (asked with `Accept: text/plain` or `?format=prometheus`) | `GET /metrics` | | The MCP servers, their state and tools ([below](#tools-from-mcp-servers)) | `GET /mcp` | +`GET /metrics` answers a Prometheus scrape (`Accept: text/plain` or `application/openmetrics-text`) in the text +format with vLLM's names - `vllm:num_requests_running` / `_waiting`, `vllm:kv_cache_usage_perc`, the token and +request counters, `vllm:prefix_cache_queries_total` / `_hits_total` (prompt tokens read / reused), +`vllm:spec_decode_num_draft_tokens_total` / `_accepted_tokens_total` (the MTP drafts), and the histograms +`vllm:time_to_first_token_seconds`, `vllm:inter_token_latency_seconds` and `vllm:e2e_request_latency_seconds` - so the +dashboards and alerts written for a vLLM server read this one. With an API key, the scraper sends it as a bearer +token. Any other request keeps the JSON. + +The JSON's own facts that vLLM has no name for come in the same scrape under `strata:`, named after their JSON key, +so a Monitor-tab panel and a Grafana panel read the same value: `strata:live_state{state="..."}`, `strata:live_tok_s`, +`strata:live_prefill_tok_s_mean`, `strata:live_prompt_read`, `strata:engine_max_context`, +`strata:totals_prompt_seconds_total` / `strata:totals_decode_seconds_total`, `strata:last_hit_rate` and +`strata:last_decode_tok_s` (the last request's), and the hardware - `strata:gpu_util`, `strata:gpu_mem_used_bytes`, +`strata:gpu_mem_total_bytes`, `strata:gpu_temp_celsius`, `strata:gpu_power_watts` (one sample per card, label +`gpu`), `strata:cpu`, `strata:ram_used_bytes`, `strata:ram_total_bytes`. A value the server does not have (no GPU +telemetry, an older engine) has no sample rather than a zero. + +Ready to use, in `docs/monitoring/`: `prometheus.yml` (a scrape config, the API key as a bearer token), +`servicemonitor.yaml` (the same for the Prometheus Operator) and `grafana-strata.json`, a Grafana dashboard to +import (it asks for the Prometheus data source): requests running and waiting, tokens per second, time to first +token, time between tokens and request duration (p50 / p95), the prompt cache and MTP draft rates, and the engine's +own panels (state, batch slots, rates, expert cache hit rate, GPU and RAM). Its first row uses only vLLM's names, so +it also reads a vLLM server. + `/models` and `/v1/models` list only the loaded model, with its context limit and input modalities. `/props` exposes the original chat template, context limit, configured generation defaults (shared settings take precedence), model path and engine version when available. Context means the full engine context, not the resident KV window. `n_predict: -1` means no fixed output cap. Unconfigured sampling fields are omitted. `/slots` uses llama.cpp's names: `n_ctx` and `n_prompt_tokens` (the running request's prompt size, kept after it ends: what a front-end's context meter divides by `n_ctx`). `total_slots` in `/props` is the number of `--batch` slots (1 without). `autoload` has no effect; an unknown `model` returns 404. These metadata endpoints and `/slots` require the API key when one is configured. They do not load, unload or restart models. `chat_template_caps` uses llama.cpp's field names. Strata checks them when loading the active template by rendering diff --git a/docs/monitoring/grafana-strata.json b/docs/monitoring/grafana-strata.json new file mode 100644 index 00000000..c595bfd9 --- /dev/null +++ b/docs/monitoring/grafana-strata.json @@ -0,0 +1,1033 @@ +{ + "__inputs": [ + { + "name": "DS_PROMETHEUS", + "label": "Prometheus", + "type": "datasource", + "pluginId": "prometheus", + "pluginName": "Prometheus" + } + ], + "title": "Strata (and vLLM)", + "uid": "strata-serving", + "tags": [ + "strata", + "vllm", + "llm" + ], + "timezone": "", + "schemaVersion": 39, + "version": 1, + "refresh": "30s", + "time": { + "from": "now-6h", + "to": "now" + }, + "editable": true, + "templating": { + "list": [ + { + "name": "model", + "label": "Model", + "type": "query", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "refresh": 2, + "includeAll": true, + "multi": true, + "allValue": ".*", + "current": { + "selected": true, + "text": [ + "All" + ], + "value": [ + "$__all" + ] + }, + "query": { + "query": "label_values(vllm:generation_tokens_total, model_name)", + "refId": "model" + }, + "definition": "label_values(vllm:generation_tokens_total, model_name)", + "sort": 1 + }, + { + "name": "instance", + "label": "Instance", + "type": "query", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "refresh": 2, + "includeAll": true, + "multi": true, + "allValue": ".*", + "current": { + "selected": true, + "text": [ + "All" + ], + "value": [ + "$__all" + ] + }, + "query": { + "query": "label_values(vllm:generation_tokens_total{model_name=~\"$model\"}, instance)", + "refId": "instance" + }, + "definition": "label_values(vllm:generation_tokens_total{model_name=~\"$model\"}, instance)", + "sort": 1 + } + ] + }, + "panels": [ + { + "id": 1, + "type": "row", + "title": "Requests and throughput (vLLM names: the same panels read a vLLM server)", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 0 + }, + "panels": [] + }, + { + "id": 2, + "type": "timeseries", + "title": "Requests running / waiting", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 1 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum by (model_name) (vllm:num_requests_running{model_name=~\"$model\",instance=~\"$instance\"})", + "legendFormat": "{{model_name}} running" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum by (model_name) (vllm:num_requests_waiting{model_name=~\"$model\",instance=~\"$instance\"})", + "legendFormat": "{{model_name}} waiting" + } + ], + "fieldConfig": { + "defaults": { + "unit": "none", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 3, + "type": "timeseries", + "title": "Tokens per second", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 1 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum by (model_name) (rate(vllm:generation_tokens_total{model_name=~\"$model\",instance=~\"$instance\"}[1m]))", + "legendFormat": "{{model_name}} generated" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum by (model_name) (rate(vllm:prompt_tokens_total{model_name=~\"$model\",instance=~\"$instance\"}[1m]))", + "legendFormat": "{{model_name}} prompt" + } + ], + "fieldConfig": { + "defaults": { + "unit": "suffix: tok/s", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 4, + "type": "timeseries", + "title": "Time to first token (p50 / p95)", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "histogram_quantile(0.95, sum by (le, model_name) (rate(vllm:time_to_first_token_seconds_bucket{model_name=~\"$model\",instance=~\"$instance\"}[5m])))", + "legendFormat": "{{model_name}} p95" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "histogram_quantile(0.5, sum by (le, model_name) (rate(vllm:time_to_first_token_seconds_bucket{model_name=~\"$model\",instance=~\"$instance\"}[5m])))", + "legendFormat": "{{model_name}} p50" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 5, + "type": "timeseries", + "title": "Time between tokens (p50 / p95)", + "description": "Strata observes the mean gap of each request (the engine reports its decode time, not each token's).", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 8 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "histogram_quantile(0.95, sum by (le, model_name) (rate(vllm:inter_token_latency_seconds_bucket{model_name=~\"$model\",instance=~\"$instance\"}[5m])))", + "legendFormat": "{{model_name}} p95" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "histogram_quantile(0.5, sum by (le, model_name) (rate(vllm:inter_token_latency_seconds_bucket{model_name=~\"$model\",instance=~\"$instance\"}[5m])))", + "legendFormat": "{{model_name}} p50" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 6, + "type": "timeseries", + "title": "Request duration (p50 / p95)", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 15 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "histogram_quantile(0.95, sum by (le, model_name) (rate(vllm:e2e_request_latency_seconds_bucket{model_name=~\"$model\",instance=~\"$instance\"}[5m])))", + "legendFormat": "{{model_name}} p95" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "histogram_quantile(0.5, sum by (le, model_name) (rate(vllm:e2e_request_latency_seconds_bucket{model_name=~\"$model\",instance=~\"$instance\"}[5m])))", + "legendFormat": "{{model_name}} p50" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 7, + "type": "timeseries", + "title": "Speed of one answer", + "description": "1 / the mean time between tokens: what one user sees, against the total above.", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 15 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum by (model_name) (rate(vllm:inter_token_latency_seconds_count{model_name=~\"$model\",instance=~\"$instance\"}[5m])) / sum by (model_name) (rate(vllm:inter_token_latency_seconds_sum{model_name=~\"$model\",instance=~\"$instance\"}[5m]))", + "legendFormat": "{{model_name}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "suffix: tok/s", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 8, + "type": "timeseries", + "title": "Prompt tokens served from the cache", + "description": "Strata: the prompt cache and parked conversations; vLLM: its prefix-cache blocks.", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 22 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum by (model_name) (rate(vllm:prefix_cache_hits_total{model_name=~\"$model\",instance=~\"$instance\"}[15m])) / sum by (model_name) (rate(vllm:prefix_cache_queries_total{model_name=~\"$model\",instance=~\"$instance\"}[15m]))", + "legendFormat": "{{model_name}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 9, + "type": "timeseries", + "title": "MTP drafts accepted", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 22 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum by (model_name) (rate(vllm:spec_decode_num_accepted_tokens_total{model_name=~\"$model\",instance=~\"$instance\"}[15m])) / sum by (model_name) (rate(vllm:spec_decode_num_draft_tokens_total{model_name=~\"$model\",instance=~\"$instance\"}[15m]))", + "legendFormat": "{{model_name}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 10, + "type": "timeseries", + "title": "Requests finished per minute", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 29 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum by (model_name) (rate(vllm:request_success_total{model_name=~\"$model\",instance=~\"$instance\"}[5m])) * 60", + "legendFormat": "{{model_name}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "suffix: req/min", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 11, + "type": "timeseries", + "title": "Context in use", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 29 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "max by (model_name) (vllm:kv_cache_usage_perc{model_name=~\"$model\",instance=~\"$instance\"})", + "legendFormat": "{{model_name}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 12, + "type": "row", + "title": "Strata engine (strata: names, after the /metrics JSON keys)", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 36 + }, + "panels": [] + }, + { + "id": 13, + "type": "timeseries", + "title": "Engine state", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 37 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "max by (state) (strata:live_state{model_name=~\"$model\",instance=~\"$instance\"}) > 0", + "legendFormat": "{{state}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "none", + "custom": { + "fillOpacity": 60, + "showPoints": "never", + "stacking": { + "mode": "normal" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 14, + "type": "timeseries", + "title": "Batch slots by state", + "description": "\"parallel\": N / --batch only.", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 37 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum by (state) (strata:live_slots{model_name=~\"$model\",instance=~\"$instance\"})", + "legendFormat": "{{state}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "none", + "custom": { + "fillOpacity": 60, + "showPoints": "never", + "stacking": { + "mode": "normal" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 15, + "type": "timeseries", + "title": "Engine rates", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 44 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "max(strata:live_tok_s{model_name=~\"$model\",instance=~\"$instance\"})", + "legendFormat": "decode tok/s" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "max(strata:live_prefill_tok_s_mean{model_name=~\"$model\",instance=~\"$instance\"})", + "legendFormat": "prompt tok/s" + } + ], + "fieldConfig": { + "defaults": { + "unit": "suffix: tok/s", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 16, + "type": "timeseries", + "title": "Expert cache hit rate (last request)", + "description": "Experts found in VRAM. Below ~90 % the CPU and the PCIe link compute the rest and decode slows down.", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 44 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "max(strata:last_hit_rate{model_name=~\"$model\",instance=~\"$instance\"})", + "legendFormat": "hit rate" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 17, + "type": "timeseries", + "title": "Engine time: prompts / decoding", + "description": "Seconds of work per second: 1 = busy all the time (more with requests running together).", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 51 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum(rate(strata:totals_prompt_seconds_total{model_name=~\"$model\",instance=~\"$instance\"}[5m]))", + "legendFormat": "reading prompts" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "sum(rate(strata:totals_decode_seconds_total{model_name=~\"$model\",instance=~\"$instance\"}[5m]))", + "legendFormat": "decoding" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "custom": { + "fillOpacity": 60, + "showPoints": "never", + "stacking": { + "mode": "normal" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 18, + "type": "timeseries", + "title": "GPU busy, per card", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 51 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "max by (gpu) (strata:gpu_util{model_name=~\"$model\",instance=~\"$instance\"})", + "legendFormat": "GPU {{gpu}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percent", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 19, + "type": "timeseries", + "title": "GPU memory, per card", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 58 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "max by (gpu) (strata:gpu_mem_used_bytes{model_name=~\"$model\",instance=~\"$instance\"})", + "legendFormat": "GPU {{gpu}} used" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "max by (gpu) (strata:gpu_mem_total_bytes{model_name=~\"$model\",instance=~\"$instance\"})", + "legendFormat": "GPU {{gpu}} total" + } + ], + "fieldConfig": { + "defaults": { + "unit": "bytes", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + }, + { + "id": 20, + "type": "timeseries", + "title": "Host RAM", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 58 + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "max(strata:ram_used_bytes{model_name=~\"$model\",instance=~\"$instance\"})", + "legendFormat": "used" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "expr": "max(strata:ram_total_bytes{model_name=~\"$model\",instance=~\"$instance\"})", + "legendFormat": "total" + } + ], + "fieldConfig": { + "defaults": { + "unit": "bytes", + "custom": { + "fillOpacity": 10, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + } + } + ] +} diff --git a/docs/monitoring/prometheus.yml b/docs/monitoring/prometheus.yml new file mode 100644 index 00000000..a87634d2 --- /dev/null +++ b/docs/monitoring/prometheus.yml @@ -0,0 +1,12 @@ +# Scrape a Strata server's GET /metrics (Prometheus text, vLLM's names; docs/DETAILS.md). +# Prometheus asks for text/plain, so it gets the text format; the Monitor tab keeps the JSON. +scrape_configs: + - job_name: strata + metrics_path: /metrics + scrape_interval: 15s + # with an API key (strata-.json "api_key" or --api-key): sent as a bearer token + authorization: + type: Bearer + credentials_file: /etc/prometheus/strata-api-key + static_configs: + - targets: ["127.0.0.1:8080"] diff --git a/docs/monitoring/servicemonitor.yaml b/docs/monitoring/servicemonitor.yaml new file mode 100644 index 00000000..256bca44 --- /dev/null +++ b/docs/monitoring/servicemonitor.yaml @@ -0,0 +1,21 @@ +# Kubernetes (Prometheus Operator): Strata behind a Service whose port is named "http". +# The API key lives in a Secret (key "key"), sent as a bearer token. +apiVersion: monitoring.coreos.com/v1 +kind: ServiceMonitor +metadata: + name: strata + labels: + release: kube-prometheus-stack # whatever your Prometheus selects ServiceMonitors by +spec: + selector: + matchLabels: + app: strata + endpoints: + - port: http + path: /metrics + interval: 15s + authorization: + type: Bearer + credentials: + name: strata-api-key + key: key diff --git a/include/strata/kernels/cpu/iq_avx2.hpp b/include/strata/kernels/cpu/iq_avx2.hpp index 0a8876bb..519efa2c 100644 --- a/include/strata/kernels/cpu/iq_avx2.hpp +++ b/include/strata/kernels/cpu/iq_avx2.hpp @@ -33,6 +33,9 @@ void iq256_gu_rows_v(int variant, int ggml_type, const uint8_t* blob, size_t gu_ void iq256_rows_v(int variant, int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out, int r0, int r1); +/// ggml's quantize_row_q8_K (x86 runs the scalar reference), byte-identical, in AVX-2: n values -> n/256 block_q8_K. +void q8k_quant_avx2(const float* x, void* y, int64_t n); + /// out[t][r] = w_r . h[t] for IQ4_NL (type 20) rows against Q8_0 activations (ggml's block_q8_0). /// IQ4_NL is a 32-value-block format, so this does not go through iq256_rows (QK_K blocks, Q8_K acts). void iq4nl256_down_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt, diff --git a/serve/prometheus.py b/serve/prometheus.py new file mode 100644 index 00000000..7c09192c --- /dev/null +++ b/serve/prometheus.py @@ -0,0 +1,160 @@ +"""GET /metrics in the Prometheus text format, with vLLM's metric names, so the dashboards and alerts written for a +vLLM server read a Strata server unchanged. Everything comes from the server's own record (Service.metrics(), the +same dict the JSON /metrics returns) plus three latency histograms observed when a request finishes. + +What vLLM has no name for is the JSON's own facts under `strata:`, named after the JSON's keys (live.tok_s -> +strata:live_tok_s, totals.decode_ms -> strata:totals_decode_seconds_total, hardware.gpu_util -> strata:gpu_util), so +the two formats say the same thing and a panel can be moved from the Monitor tab to Grafana by its key.""" +import threading + +# vLLM's buckets for the request latencies (seconds) +BUCKETS = (0.001, 0.005, 0.01, 0.02, 0.04, 0.06, 0.08, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0, 20.0, 40.0, + 80.0, 160.0, 640.0, 2560.0) +CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8" + + +def wants_prometheus(accept: str, query: str) -> bool: + """Prometheus asks with Accept: text/plain or application/openmetrics-text; a person can add ?format=prometheus. + Anything else (the Monitor tab, curl without a header) keeps the JSON.""" + return "format=prometheus" in (query or "") or "openmetrics" in (accept or "") or "text/plain" in (accept or "") + + +class Histogram: + def __init__(self): + self.counts = [0] * len(BUCKETS) + self.sum = 0.0 + self.n = 0 + + def observe(self, v: float, times: int = 1): + if v is None or times <= 0: + return + for i, b in enumerate(BUCKETS): + if v <= b: + self.counts[i] += times + self.sum += v * times + self.n += times + + +class Latencies: + """Time to first token, the time between tokens and the whole request, per finished request.""" + + def __init__(self): + self.lock = threading.Lock() + self.ttft, self.itl, self.e2e = Histogram(), Histogram(), Histogram() + + def observe(self, ttft_s, output_tokens, decode_s, total_s): + with self.lock: + self.ttft.observe(ttft_s) + if output_tokens and output_tokens > 1 and decode_s: + # the mean gap, once per gap: the engine reports the decode time, not each token's + self.itl.observe(decode_s / (output_tokens - 1), output_tokens - 1) + self.e2e.observe(total_s) + + def snapshot(self): + with self.lock: + return {k: (list(h.counts), h.sum, h.n) for k, h in + (("ttft", self.ttft), ("itl", self.itl), ("e2e", self.e2e))} + + +def _num(v, default=0): + return v if isinstance(v, (int, float)) and not isinstance(v, bool) else default + + +def render(m: dict, lat: dict) -> str: + """The text for one scrape. `m` is Service.metrics(), `lat` Latencies.snapshot().""" + model = str((m.get("engine") or {}).get("model") or "strata").replace("\\", "\\\\").replace('"', '\\"') + lab = f'model_name="{model}"' + live, totals = m.get("live") or {}, m.get("totals") or {} + out = [] + + def metric(name, kind, help_, value): + out.append(f"# HELP {name} {help_}\n# TYPE {name} {kind}\n{name}{{{lab}}} {value}") + + busy = live.get("state") in ("reading", "generating") + ctx = _num((m.get("engine") or {}).get("max_context"), 0) + used = _num(live.get("prompt_tokens")) + _num(live.get("generated")) if busy else 0 + # "parallel": live.running / live.waiting count the requests together (waiting: for a slot or the control lines) + metric("vllm:num_requests_running", "gauge", "Requests reading their prompt or generating.", + _num(live.get("running"), int(busy))) + metric("vllm:num_requests_waiting", "gauge", "Requests waiting for their turn.", + _num(live.get("queued")) + _num(live.get("waiting"))) + metric("vllm:kv_cache_usage_perc", "gauge", "The running request's share of the context (1 = full).", + round(min(1.0, used / ctx), 4) if ctx else 0) + metric("vllm:prompt_tokens_total", "counter", "Prompt tokens of the finished requests.", + _num(totals.get("prompt_tokens"))) + metric("vllm:generation_tokens_total", "counter", "Generated tokens.", _num(totals.get("output_tokens"))) + metric("vllm:request_success_total", "counter", "Finished requests.", _num(totals.get("requests"))) + metric("vllm:prefix_cache_queries_total", "counter", "Prompt tokens looked up in the prompt cache.", + _num(totals.get("prompt_tokens"))) + metric("vllm:prefix_cache_hits_total", "counter", "Prompt tokens the prompt cache already held.", + _num(totals.get("reused"))) + metric("vllm:spec_decode_num_draft_tokens_total", "counter", "MTP draft tokens offered.", + _num(totals.get("drafts_offered"))) + metric("vllm:spec_decode_num_accepted_tokens_total", "counter", "MTP draft tokens accepted.", + _num(totals.get("drafts_accepted"))) + metric("vllm:num_preemptions_total", "counter", "Preempted requests (Strata does not preempt).", 0) + for name, key, help_ in (("vllm:time_to_first_token_seconds", "ttft", "Time to the first token."), + ("vllm:inter_token_latency_seconds", "itl", "Time between two tokens."), + ("vllm:e2e_request_latency_seconds", "e2e", "A request from start to end.")): + counts, total, n = lat[key] + out.append(f"# HELP {name} {help_}\n# TYPE {name} histogram") + for b, c in zip(BUCKETS, counts): + out.append(f'{name}_bucket{{{lab},le="{b}"}} {c}') + out.append(f'{name}_bucket{{{lab},le="+Inf"}} {n}') + out.append(f"{name}_sum{{{lab}}} {round(total, 6)}\n{name}_count{{{lab}}} {n}") + strata(m, out, lab) + return "\n".join(out) + "\n" + + +def strata(m: dict, out: list, lab: str): + """The JSON's facts vLLM has no name for, under `strata:` and the JSON's key.""" + live, totals = m.get("live") or {}, m.get("totals") or {} + hw, eng = m.get("hardware") or {}, m.get("engine") or {} + reqs = m.get("requests") or [] + + typed = set() + + def metric(name, kind, help_, value, labels=""): + if not isinstance(value, (int, float)) or isinstance(value, bool): + return # unknown here (no GPU telemetry, an older engine): no sample + if name not in typed: # one HELP / TYPE per family, before its first sample + typed.add(name) + out.append(f"# HELP strata:{name} {help_}\n# TYPE strata:{name} {kind}") + out.append(f"strata:{name}{{{lab}{labels}}} {value}") + + for state in ("unloaded", "idle", "reading", "generating"): + metric("live_state", "gauge", "1 for what the engine is doing (live.state).", int(live.get("state") == state), + f',state="{state}"') + metric("live_tok_s", "gauge", "Decode rate over the last seconds (live.tok_s).", live.get("tok_s") or 0) + metric("live_prefill_tok_s_mean", "gauge", "Prompt reading rate of the running request (live.prefill_tok_s_mean).", + live.get("prefill_tok_s_mean") or 0) + metric("live_prompt_read", "gauge", "Prompt tokens read so far by the running request (live.prompt_read).", + live.get("prompt_read") or 0) + for state in ("idle", "reading", "generating"): + slots = live.get("slots") + if isinstance(slots, list) and slots: + metric("live_slots", "gauge", "The batch slots in each state (live.slots).", + sum(1 for x in slots if isinstance(x, dict) and x.get("state") == state), f',state="{state}"') + metric("engine_max_context", "gauge", "The engine's context (engine.max_context).", eng.get("max_context")) + metric("totals_prompt_seconds_total", "counter", "Time spent reading prompts (totals.prompt_ms).", + round((totals.get("prompt_ms") or 0) / 1000, 3)) + metric("totals_decode_seconds_total", "counter", "Time spent generating (totals.decode_ms).", + round((totals.get("decode_ms") or 0) / 1000, 3)) + last = reqs[0] if reqs else {} + metric("last_hit_rate", "gauge", "The last request's expert cache hit rate (requests[0].hit_rate).", + last.get("hit_rate")) + metric("last_decode_tok_s", "gauge", "The last request's decode rate (requests[0].decode_tok_s).", + last.get("decode_tok_s")) + gpus = hw.get("gpus") or ([{"index": 0, "util": hw.get("gpu_util"), "mem_used": hw.get("gpu_mem_used"), + "mem_total": hw.get("gpu_mem_total"), "temp": hw.get("gpu_temp"), + "power": hw.get("gpu_power")}] if hw.get("gpu_util") is not None else []) + for name, key, help_ in (("gpu_util", "util", "GPU busy, percent (hardware.gpu_util)."), + ("gpu_mem_used_bytes", "mem_used", "GPU memory in use (hardware.gpu_mem_used)."), + ("gpu_mem_total_bytes", "mem_total", "GPU memory (hardware.gpu_mem_total)."), + ("gpu_temp_celsius", "temp", "GPU temperature (hardware.gpu_temp)."), + ("gpu_power_watts", "power", "GPU power draw (hardware.gpu_power).")): + for g in gpus: # a family's samples together, one per card + metric(name, "gauge", help_, g.get(key), f',gpu="{g.get("index")}"') + metric("cpu", "gauge", "CPU busy, percent (hardware.cpu).", hw.get("cpu")) + metric("ram_used_bytes", "gauge", "RAM in use (hardware.ram_used).", hw.get("ram_used")) + metric("ram_total_bytes", "gauge", "RAM (hardware.ram_total).", hw.get("ram_total")) diff --git a/serve/server.py b/serve/server.py index da973350..bd8f0a3a 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2334,6 +2334,8 @@ class Service: "prompt_ms": 0.0, "decode_ms": 0.0, "drafts_offered": 0, "drafts_accepted": 0} # #457: the MTP drafts, summed where reported self.last_timings = None # the last finished request's, llama.cpp's names (/v1/status) + from serve.prometheus import Latencies + self.latencies = Latencies() # GET /metrics in Prometheus text: the latency histograms self.last_request_at = None # when a request last started or finished self.started_at = time.time() self.status_lock = threading.Lock() @@ -3324,6 +3326,9 @@ class Service: t["decode_ms"] += last.get("decode_ms") or 0.0 t["drafts_offered"] += last.get("drafts_offered") or 0 t["drafts_accepted"] += last.get("drafts_accepted") or 0 + ft0 = st.get("first_token") # this request's own (#465: one per request) + self.latencies.observe(ft0 - started if ft0 else None, n, + (last.get("decode_ms") or 0.0) / 1000, time.time() - started) fresh = getattr(self.engine, "last", None) if fresh is not None and fresh is not before: # the engine's clock for THIS request timings = request_timings(seen, n, last) @@ -4070,6 +4075,16 @@ def make_handler(svc: Service): self.wfile.write(body) return if path == "/metrics": + from serve import prometheus + if prometheus.wants_prometheus(self.headers.get("Accept", ""), urlsplit(self.path).query): + if self._authorized(): # a scraper: the text format, vLLM's names (serve/prometheus.py) + body = prometheus.render(svc.metrics(), svc.latencies.snapshot()).encode() + self.send_response(200) + self.send_header("Content-Type", prometheus.CONTENT_TYPE) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return if self._authorized(): # the last 12 requests; `?requests=all` every one kept (the Monitor's "Show all", issue #35) self._json(200, svc.metrics(all_requests="requests=all" in self.path)) diff --git a/serve/test_prometheus.py b/serve/test_prometheus.py new file mode 100644 index 00000000..c9f2d089 --- /dev/null +++ b/serve/test_prometheus.py @@ -0,0 +1,181 @@ +"""serve/test_prometheus.py - GET /metrics in the Prometheus text format (vLLM's names), against the mock engine. + + python -m unittest serve.test_prometheus -v +""" +from __future__ import annotations + +import json +import re +import sys +import threading +import time +import unittest +import urllib.request +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from serve.frontend import ChatTemplate # noqa: E402 +from serve.prometheus import BUCKETS, Latencies, render, wants_prometheus # noqa: E402 +from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] + + +def parse(text): + """{(name, labels): value} for every sample line; checks each family has HELP and TYPE first.""" + out, typed = {}, set() + for line in text.splitlines(): + if line.startswith("# TYPE "): + assert line.split()[2] not in typed, f"two # TYPE lines for {line.split()[2]}" + typed.add(line.split()[2]) + continue + if line.startswith("#") or not line: + continue + m = re.fullmatch(r'([a-z0-9_:]+)\{([^}]*)\} (\S+)', line) + assert m, f"not a sample line: {line!r}" + name, labels, value = m.groups() + family = re.sub(r"_(bucket|sum|count)$", "", name) + assert name in typed or family in typed, f"{name} has no # TYPE" + out[(name, labels)] = float(value) + return out + + +class Units(unittest.TestCase): + def test_who_gets_the_text(self): + self.assertTrue(wants_prometheus("text/plain;version=0.0.4", "")) + self.assertTrue(wants_prometheus("application/openmetrics-text;version=1.0.0", "")) + self.assertTrue(wants_prometheus("", "format=prometheus")) + self.assertFalse(wants_prometheus("application/json", "")) + self.assertFalse(wants_prometheus("*/*", "requests=all")) + + def test_histograms_are_cumulative(self): + lat = Latencies() + lat.observe(0.3, 11, 1.0, 1.5) # 10 gaps of 0.1 s + lat.observe(None, 1, 0.0, 0.2) # no first token, one token: no gap + s = lat.snapshot() + counts, total, n = s["itl"] + self.assertEqual(n, 10) + self.assertAlmostEqual(total, 1.0) + self.assertEqual(counts[BUCKETS.index(0.1)], 10) + self.assertEqual(counts[BUCKETS.index(0.08)], 0) + self.assertEqual(s["ttft"][2], 1) + self.assertEqual(s["e2e"][2], 2) + self.assertEqual(counts, sorted(counts)) + + def test_render_reads_the_server_record(self): + m = {"engine": {"model": 'a "b"', "max_context": 1000}, + "live": {"state": "generating", "queued": 2, "prompt_tokens": 400, "generated": 100}, + "totals": {"requests": 3, "prompt_tokens": 900, "reused": 600, "output_tokens": 50, + "drafts_offered": 40, "drafts_accepted": 30}} + got = parse(render(m, Latencies().snapshot())) + lab = 'model_name="a \\"b\\""' + self.assertEqual(got[("vllm:num_requests_running", lab)], 1) + self.assertEqual(got[("vllm:num_requests_waiting", lab)], 2) + self.assertEqual(got[("vllm:kv_cache_usage_perc", lab)], 0.5) + self.assertEqual(got[("vllm:prefix_cache_hits_total", lab)], 600) + self.assertEqual(got[("vllm:spec_decode_num_accepted_tokens_total", lab)], 30) + self.assertEqual(got[("vllm:time_to_first_token_seconds_count", lab)], 0) + + def test_strata_names_follow_the_json(self): + m = {"engine": {"model": "m", "max_context": 1000}, + "live": {"state": "reading", "queued": 0, "prompt_read": 300, "prefill_tok_s_mean": 2500.0}, + "totals": {"requests": 1, "prompt_ms": 1500.0, "decode_ms": 2000.0}, + "requests": [{"hit_rate": 0.97, "decode_tok_s": 101.5}], + "hardware": {"gpu_util": 40.0, "gpus": [{"index": 0, "util": 30.0, "mem_used": 1 << 30, "temp": 60}, + {"index": 1, "util": 50.0, "mem_used": 2 << 30, "temp": 65}], + "cpu": 12.5, "ram_used": 8 << 30, "ram_total": 64 << 30}} + got = parse(render(m, Latencies().snapshot())) + lab = 'model_name="m"' + self.assertEqual(got[("strata:live_state", lab + ',state="reading"')], 1) + self.assertEqual(got[("strata:live_state", lab + ',state="generating"')], 0) + self.assertEqual(got[("strata:live_prompt_read", lab)], 300) + self.assertEqual(got[("strata:totals_decode_seconds_total", lab)], 2.0) + self.assertEqual(got[("strata:last_hit_rate", lab)], 0.97) + self.assertEqual(got[("strata:gpu_util", lab + ',gpu="1"')], 50) + self.assertEqual(got[("strata:gpu_mem_used_bytes", lab + ',gpu="0"')], 1 << 30) + self.assertNotIn(("strata:gpu_power_watts", lab + ',gpu="0"'), got) # not measured: no sample + self.assertEqual(got[("strata:ram_total_bytes", lab)], 64 << 30) + + +class Endpoint(unittest.TestCase): + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.svc = Service(MockEngine(tok, "\n\nhello there", max_context=4096), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def get(self, path, accept): + req = urllib.request.Request(self.base + path, headers={"Accept": accept}) + with urllib.request.urlopen(req, timeout=30) as r: + return r.headers.get("Content-Type"), r.read().decode() + + def test_a_request_shows_in_both_formats(self): + body = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 32}).encode() + req = urllib.request.Request(self.base + "/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + usage = json.loads(r.read())["usage"] + ctype, text = self.get("/metrics", "text/plain") + self.assertTrue(ctype.startswith("text/plain")) + got = {k[0]: v for k, v in parse(text).items()} + self.assertGreaterEqual(got["vllm:request_success_total"], 1) + self.assertGreaterEqual(got["vllm:generation_tokens_total"], usage["completion_tokens"]) + self.assertGreaterEqual(got["vllm:e2e_request_latency_seconds_count"], 1) + ctype, text = self.get("/metrics", "application/json") + self.assertTrue(ctype.startswith("application/json")) + self.assertGreaterEqual(json.loads(text)["totals"]["requests"], 1) + ctype, _ = self.get("/metrics?format=prometheus", "*/*") + self.assertTrue(ctype.startswith("text/plain")) + + +class BatchEngine(MockEngine): + """--batch as the server sees it: several requests generate at once, none waits for the control lines.""" + batch, waiting = 4, 0 + + +class Batched(unittest.TestCase): + def test_every_concurrent_request_is_counted(self): + tok = ByteTokenizer() + svc = Service(BatchEngine(tok, "\n\n" + "y" * 40, max_context=4096, delay_s=0.02), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + body = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}], + "max_tokens": 64}).encode() + + def ask(): + req = urllib.request.Request(base + "/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=60) as r: + r.read() + + threads = [threading.Thread(target=ask) for _ in range(3)] + [t.start() for t in threads] + time.sleep(0.4) # the three are generating + req = urllib.request.Request(base + "/metrics", headers={"Accept": "text/plain"}) + with urllib.request.urlopen(req, timeout=30) as r: + during = {k[0]: v for k, v in parse(r.read().decode()).items()} + [t.join() for t in threads] + with urllib.request.urlopen(req, timeout=30) as r: + after = {k[0]: v for k, v in parse(r.read().decode()).items()} + finally: + httpd.shutdown() + httpd.server_close() + self.assertEqual(during["vllm:num_requests_running"], 3) + self.assertEqual(after["vllm:num_requests_running"], 0) + self.assertEqual(after["vllm:request_success_total"], 3) # each one, not only the last to finish + self.assertEqual(after["vllm:e2e_request_latency_seconds_count"], 3) + self.assertEqual(after["vllm:time_to_first_token_seconds_count"], 3) + self.assertEqual(svc.metrics()["totals"]["requests"], 3) # the JSON agrees + + +if __name__ == "__main__": + unittest.main() diff --git a/src/kernels/cpu/iq_avx2.cpp b/src/kernels/cpu/iq_avx2.cpp index 333e0c45..da15e003 100644 --- a/src/kernels/cpu/iq_avx2.cpp +++ b/src/kernels/cpu/iq_avx2.cpp @@ -324,6 +324,75 @@ bool vnni_on() { return STRATA_AVXVNNI && cpu_avxvnni_ok(); } } // namespace +// ggml's quantize_row_q8_K_ref (ggml-quants.c), which is also what ggml-cpu runs on x86 (no SIMD version there), +// in AVX-2: the same per-value arithmetic - one IEEE multiply by the same iscale, the same 1.5*2^23 rounding add, +// the same clamp - so the bytes are identical (q8k_quant_parity checks it). The block's sign-carrying max is the +// FIRST value of the largest magnitude, as in the scalar loop; NaNs are skipped as there (`ax > amax` is false for +// them, and max_ps returns its second operand for a NaN first one). A zero block leaves bsums as the reference +// does. A verify window quantizes up to 6 tokens per layer on the host before the pool can start. +void q8k_quant_avx2(const float* x, void* vy, int64_t k) { + block_q8_K* y = (block_q8_K*) vy; + const int64_t nb = k / QK_K; + const __m256 absm = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff)); + const __m256 magic = _mm256_set1_ps(12582912.f); + const __m256i mant = _mm256_set1_epi32(0x007fffff), off = _mm256_set1_epi32(0x00400000); + const __m256i c127 = _mm256_set1_epi32(127); + const __m256i perm = _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7); + for (int64_t i = 0; i < nb; ++i, x += QK_K) { + __m256 m = _mm256_setzero_ps(); + for (int j = 0; j < QK_K; j += 8) m = _mm256_max_ps(_mm256_and_ps(_mm256_loadu_ps(x + j), absm), m); + __m128 h = _mm_max_ps(_mm256_castps256_ps128(m), _mm256_extractf128_ps(m, 1)); + h = _mm_max_ps(h, _mm_movehl_ps(h, h)); + h = _mm_max_ss(h, _mm_movehdup_ps(h)); + const float amax = _mm_cvtss_f32(h); + if (!amax) { + y[i].d = 0; + std::memset(y[i].qs, 0, QK_K); + continue; + } + float mx = 0.f; + const __m256 va = _mm256_set1_ps(amax); + for (int j = 0; j < QK_K; j += 8) { + const int msk = _mm256_movemask_ps(_mm256_cmp_ps(_mm256_and_ps(_mm256_loadu_ps(x + j), absm), va, _CMP_EQ_OQ)); + if (msk) { + int b = 0; + while (!((msk >> b) & 1)) ++b; + mx = x[j + b]; + break; + } + } + const float iscale = -127.f / mx; + const __m256 vis = _mm256_set1_ps(iscale); + for (int j = 0; j < QK_K; j += 32) { + __m256i v[4]; + for (int q = 0; q < 4; ++q) { + __m256 p = _mm256_mul_ps(vis, _mm256_loadu_ps(x + j + 8 * q)); +#if defined(__GNUC__) && !defined(__clang__) + // GCC fuses a multiply and an add into an FMA by default (-ffp-contract=fast); the reference rounds + // the product before the add, so the product must stay a separate value + __asm__("" : "+x"(p)); +#endif + const __m256 t = _mm256_add_ps(p, magic); + v[q] = _mm256_min_epi32(_mm256_sub_epi32(_mm256_and_si256(_mm256_castps_si256(t), mant), off), c127); + // the reference stores MIN(127, v) into an int8 (keeps the low byte), and its bsums add those bytes: + // the same here, so even a degenerate block (iscale overflowing to inf) gives the same bytes + v[q] = _mm256_srai_epi32(_mm256_slli_epi32(v[q], 24), 24); + } + for (int q = 0; q < 2; ++q) { // two 16-value sums + const __m256i s = _mm256_add_epi32(v[2 * q], v[2 * q + 1]); + __m128i s4 = _mm_add_epi32(_mm256_castsi256_si128(s), _mm256_extracti128_si256(s, 1)); + s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0x4E)); + s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0xB1)); + y[i].bsums[j / 16 + q] = (int16_t) _mm_cvtsi128_si32(s4); + } + const __m256i p16a = _mm256_packs_epi32(v[0], v[1]), p16b = _mm256_packs_epi32(v[2], v[3]); + const __m256i p8 = _mm256_permutevar8x32_epi32(_mm256_packs_epi16(p16a, p16b), perm); + _mm256_storeu_si256((__m256i*) (y[i].qs + j), p8); + } + y[i].d = 1 / iscale; + } +} + bool iq256_supported(int type) noexcept { return type == 16 || type == 17 || type == 18 || type == 21 || type == 22 || type == 23; } diff --git a/src/kernels/cpu/native_expert.cpp b/src/kernels/cpu/native_expert.cpp index c381ddc5..066afe0d 100644 --- a/src/kernels/cpu/native_expert.cpp +++ b/src/kernels/cpu/native_expert.cpp @@ -68,11 +68,24 @@ bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt return true; } +namespace { +// Q8_K (the activations of every i-quant row): ggml-cpu's x86 quantizer is the scalar reference, ~3 us per token +// and layer on the host before the pool can start; q8k_quant_avx2 writes the same bytes. cpu_avx2_ok() too: +// iq_avx2.cpp is compiled for AVX2 (an AVX-only CPU, or STRATA_FORCE_ISA=avx, keeps ggml's). STRATA_NO_Q8K_AVX2=1: +// ggml's on any CPU. +bool q8k_avx2(int type) { + static const bool on = cpu_avx2_ok() && std::getenv("STRATA_NO_Q8K_AVX2") == nullptr; + return on && type == (int) GGML_TYPE_Q8_K; +} +} // namespace + void native_quant_act(const NativeFmt& f, const float* x, void* dst) { + if (q8k_avx2(f.gu_act)) { q8k_quant_avx2(x, dst, f.n_embd); return; } traits(f.gu_act)->from_float(x, dst, f.n_embd); } void native_quant_h(const NativeFmt& f, const float* h, void* dst) { + if (q8k_avx2(f.d_act)) { q8k_quant_avx2(h, dst, f.n_ff); return; } traits(f.d_act)->from_float(h, dst, f.n_ff); } diff --git a/src/kernels/cpu/q8k_quant_parity.cpp b/src/kernels/cpu/q8k_quant_parity.cpp new file mode 100644 index 00000000..535b1881 --- /dev/null +++ b/src/kernels/cpu/q8k_quant_parity.cpp @@ -0,0 +1,144 @@ +// src/kernels/cpu/q8k_quant_parity.cpp - the AVX-2 Q8_K activation quantizer (q8k_quant_avx2, iq_avx2.cpp) against +// ggml's, byte for byte: the reference (ggml-base's from_float_ref) and what ggml-cpu runs (its from_float), over +// rows of random, scaled, sparse and degenerate values; then the same through native_quant_act / native_quant_h with +// an IQ3_S expert's format, which is what the engine calls. No GPU, no model. +// +// q8k_quant_parity (STRATA_FORCE_ISA=avx: the AVX-2 copy is skipped, native_quant_* must equal ggml's) +// q8k_quant_parity --bench ns per 2560-value row, ggml-cpu's and the AVX-2 copy +#include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/iq_avx2.hpp" +#include "strata/kernels/cpu/native_expert.hpp" + +#include "ggml.h" +#include "ggml-cpu.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace cpu = strata::kernels::cpu; + +// ggml-quants.h (ggml-base): the scalar reference, which ggml-cpu's x86 quantize_row_q8_K calls. Q8_K has no +// from_float_ref in ggml's type traits, so it is declared here (block_q8_K* in ggml; the bytes are all this reads). +extern "C" void quantize_row_q8_K_ref(const float* x, void* y, int64_t k); + +namespace { + +constexpr int kQK = 256; + +std::vector> cases(int n) { + std::mt19937 rng(11); + std::normal_distribution nd(0.f, 1.f); + std::uniform_real_distribution ud(-100.f, 100.f); + std::vector> c; + auto add = [&](auto fill) { + std::vector x((size_t) n); + for (int j = 0; j < n; ++j) x[(size_t) j] = fill(j); + c.push_back(std::move(x)); + }; + add([&](int) { return nd(rng); }); + add([&](int) { return nd(rng) * 1e-3f; }); + add([&](int) { return nd(rng) * 1e4f; }); + add([&](int) { return ud(rng); }); + add([&](int) { return 0.f; }); // every block zero + add([&](int j) { return (j / kQK) % 2 ? nd(rng) : 0.f; }); // zero blocks between random ones + add([&](int j) { return j % kQK == 77 ? nd(rng) : 0.f; }); // one value per block + add([&](int j) { // the largest magnitude twice, the + const int k = j % kQK; // FIRST one's sign wins + return k == 3 ? -5.f : k == 100 ? 5.f : nd(rng); + }); + add([&](int j) { + const int k = j % kQK; + return k == 3 ? 5.f : k == 100 ? -5.f : nd(rng); + }); + add([&](int j) { return j % kQK == 9 ? 3e38f : nd(rng); }); // extremes beside ordinary values + add([&](int j) { return j % kQK == 9 ? -3e38f : nd(rng) * 1e30f; }); + add([&](int) { return nd(rng) * 1e-40f; }); // denormals + add([&](int j) { return (float) ((j % 255) - 127) / 127.f; }); // the grid itself, and its ties + add([&](int j) { return ((float) ((j * 37) % 509) - 254.f) / 508.f; }); + add([&](int j) { return j % kQK == 5 ? std::numeric_limits::quiet_NaN() : nd(rng); }); + add([&](int j) { return j % kQK == 5 ? std::numeric_limits::infinity() : nd(rng); }); + return c; +} + +// both outputs prefilled alike: a zero block leaves bsums unwritten in the reference, and so must the copy +bool same(const char* tag, int n, int ci, ggml_from_float_t a, void (*b)(const float*, void*, int64_t), + const std::vector& x, size_t bytes) { + std::vector ya(bytes, 0xAB), yb(bytes, 0xAB); + a(x.data(), ya.data(), n); + b(x.data(), yb.data(), n); + if (std::memcmp(ya.data(), yb.data(), bytes) == 0) return true; + size_t at = 0; + while (ya[at] == yb[at]) ++at; + std::printf(" %s n=%d case %d: MISMATCH at byte %zu of %zu\n", tag, n, ci, at, bytes); + return false; +} + +const cpu::NativeFmt* g_fmt = nullptr; +void via_act(const float* x, void* y, int64_t) { cpu::native_quant_act(*g_fmt, x, y); } +void via_h(const float* x, void* y, int64_t) { cpu::native_quant_h(*g_fmt, x, y); } + +} // namespace + +int main(int argc, char** argv) { + const bool bench = argc > 1 && std::string(argv[1]) == "--bench"; + ggml_cpu_init(); + const ggml_from_float_t ref = quantize_row_q8_K_ref; + const ggml_from_float_t gcpu = ggml_get_type_traits_cpu(GGML_TYPE_Q8_K)->from_float; + const bool avx2 = cpu::cpu_avx2_ok(); + int failures = 0, checked = 0; + for (const int n : {256, 512, 2560, 6144}) { + const size_t bytes = ggml_row_size(GGML_TYPE_Q8_K, n); + const auto cs = cases(n); + for (int ci = 0; ci < (int) cs.size(); ++ci) { + failures += !same("ggml-cpu vs reference", n, ci, ref, gcpu, cs[(size_t) ci], bytes); + if (avx2) failures += !same("AVX-2 vs reference", n, ci, ref, cpu::q8k_quant_avx2, cs[(size_t) ci], bytes); + ++checked; + } + } + // the engine's entry points: an IQ3_S expert (type 21) quantizes both of its activations to Q8_K + cpu::NativeFmt f; + std::string err; + if (!cpu::native_fmt(21, 21, 2560, 512, f, err)) { + std::printf("native_fmt: %s\n", err.c_str()); + return 1; + } + g_fmt = &f; + for (const auto& x : cases(2560)) + failures += !same("native_quant_act", 2560, 0, ref, via_act, x, ggml_row_size(GGML_TYPE_Q8_K, 2560)); + for (const auto& x : cases(512)) + failures += !same("native_quant_h", 512, 0, ref, via_h, x, ggml_row_size(GGML_TYPE_Q8_K, 512)); + std::printf("q8k_quant_parity: %d rows x 4 sizes, AVX-2 copy %s: %s\n", checked / 4, + avx2 ? "checked" : "skipped (no AVX2, or STRATA_FORCE_ISA)", failures ? "FAILED" : "identical"); + if (bench && avx2) { + std::mt19937 rng(3); + std::normal_distribution nd(0.f, 1.f); + const int n = 2560, rows = 4096; + std::vector x((size_t) n * rows); + for (auto& v : x) v = nd(rng); + const size_t bytes = ggml_row_size(GGML_TYPE_Q8_K, n); + std::vector y(bytes * rows); + auto time = [&](const char* tag, auto fn) { + double best = 1e30; + for (int rep = 0; rep < 5; ++rep) { + const auto t0 = std::chrono::steady_clock::now(); + for (int r = 0; r < rows; ++r) fn(x.data() + (size_t) r * n, y.data() + bytes * r, n); + const double ns = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + best = std::min(best, ns / rows); + } + std::printf(" %-10s %7.0f ns per %d-value row\n", tag, best, n); + return best; + }; + const double a = time("ggml-cpu", gcpu); + const double b = time("AVX-2", cpu::q8k_quant_avx2); + std::printf(" %.1fx\n", a / b); + } + return failures ? 1 : 0; +} diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index f757f225..8499a36f 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -96,6 +96,14 @@ constexpr int64_t C = 10240, ZV = 6144, HV = 48; inline int64_t MAXBLOB() { return (int64_t) strata::kernels::cpu::expert_layout().max_blob; } constexpr int STAGE = 8; // host->device expert staging ring (chunks below stream_all_min()) constexpr int kSplitHelpRing = 48; // layer split help: the helper stage's ring slots it streams through (at most) +// STRATA_PREFILL_STREAM_AHEAD=0 keeps the previous routed-only upload schedule (A/B). +inline bool stream_ahead_enabled() { + static const bool on = [] { + const char* v = std::getenv("STRATA_PREFILL_STREAM_AHEAD"); + return v == nullptr || std::atoi(v) != 0; + }(); + return on; +} // Step 3: from this chunk size on, every non-resident expert of every layer streams in a fixed order through a // ring_slots()-slot ring (nearly all 512 are routed at such a chunk), so the copy engine keeps working through the // attention halves instead of waiting for each layer's routing. @@ -2498,13 +2506,20 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err, 0, m.mixed_bf_lo)) return false; route(m.logits, m.ids, m.w, T, m.g->n_expert, m.cs); // the shared expert and its scalar gate - if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false; - if (!native_proj(m.gemm, wsu, m.mixed_h, m.sup, T, v.name("ffn_up_shexp.weight"), err)) return false; - swiglu_pair(m.sgate, m.sup, m.sh_h, T, m.cs); - if (!native_proj(m.gemm, wsd, m.sh_h, m.shared, T, v.name("ffn_down_shexp.weight"), err)) return false; - if (wgi->kind != core::WeightKind::Bf16InF32) { err = "prefill: shared gate is not BF16"; return false; } - m.gemm.bf16(m.mixed_bf, (const uint16_t*) wgi->data, m.sg, T, 1, N); - if (m.mixed_bf_lo) m.gemm.bf16(m.mixed_bf_lo, (const uint16_t*) wgi->data, m.sg, T, 1, N, 0, 1.0f); + auto shared_expert = [&]() -> bool { + if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false; + if (!native_proj(m.gemm, wsu, m.mixed_h, m.sup, T, v.name("ffn_up_shexp.weight"), err)) return false; + swiglu_pair(m.sgate, m.sup, m.sh_h, T, m.cs); + if (!native_proj(m.gemm, wsd, m.sh_h, m.shared, T, v.name("ffn_down_shexp.weight"), err)) return false; + if (wgi->kind != core::WeightKind::Bf16InF32) { err = "prefill: shared gate is not BF16"; return false; } + m.gemm.bf16(m.mixed_bf, (const uint16_t*) wgi->data, m.sg, T, 1, N); + if (m.mixed_bf_lo) m.gemm.bf16(m.mixed_bf_lo, (const uint16_t*) wgi->data, m.sg, T, 1, N, 0, 1.0f); + return true; + }; + // Only the router needs to finish before readback. Queue the shared expert afterwards + // so it can overlap CPU grouping and the routed-only path's initial expert uploads. + const bool defer_shared = !stream_all && stream_ahead_enabled(); + if (!defer_shared && !shared_expert()) return false; // #136: STRATA_PF_FUSED=1 - the Q2_0 pack's experts on the fused int8 kernels (moe_fused.hpp), // grouped on the GPU: no host sync. Only where every expert's place is known before the routing - // the streamed walk, in which every non-resident expert of the layer comes through the ring in id @@ -2616,6 +2631,11 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (pe.on) { // the peer's marks so far are done: the primary waited for its last rows int pd = 0; cudaGetDevice(&pd); cudaSetDevice(pe.dev); cudaStreamSynchronize(m.pp->s); pe.fold(); cudaSetDevice(pd); } + if (defer_shared) { + pt.mark(kPfRouter, cs); // keep the existing router+shared timing attribution + if (!shared_expert()) return false; + pt.mark(kPfHostGroup, cs); + } std::fill(m.cnt.begin(), m.cnt.end(), 0); for (int64_t i = 0; i < T * K; ++i) { const int32_t e = ids_h[(size_t) i]; @@ -3073,10 +3093,15 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri }; if (!stream_all) { size_t staged = 0; + size_t pending = 0; + const bool stream_ahead = stream_ahead_enabled(); const size_t lookahead = STAGE - 1; for (size_t j = 0; j < order.size(); ++j) { - while (staged < order.size() && staged <= j + lookahead) { + // Resident experts occupy no staging slot. Keep STAGE actual transfers ahead, + // rather than STAGE positions in the mixed resident/streamed order. + while (staged < order.size() && (stream_ahead ? pending < STAGE : staged <= j + lookahead)) { if (!stage_one(staged)) return false; + if (stage_of[staged] >= 0) ++pending; ++staged; } const int32_t e = order[j]; @@ -3087,6 +3112,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri pt.mark(kPfWaitCopy, cs); cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0); if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j])) return false; + --pending; // compute recorded the slot's release event before any reuse } } } else { diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 9aba23fd..ea797f36 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -647,6 +647,9 @@ void usage() { " --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" + " --gpu LIST run on these GPUs, comma-separated nvidia-smi/PCI indices (default: every\n" + " visible one); sets CUDA_VISIBLE_DEVICES/CUDA_DEVICE_ORDER inside the engine,\n" + " so a caller never has to export environment variables\n" " --ple-gguf PATH required PLE table (original second GGUF shard); with --native, the model's\n" " shard that holds per_layer_token_embd.weight when not given\n" " --no-ple explicit diagnostic ablation of the PLE layer\n" @@ -1530,6 +1533,29 @@ int main(int argc, char** argv) { setenv("CUDA_MODULE_LOADING", "EAGER", 0); #endif } + // --gpu LIST pins the visible GPUs (nvidia-smi/PCI order) from the command line instead of the caller's + // environment: CUDA_VISIBLE_DEVICES is read at the first CUDA call, so this has to happen here, before + // anything else. The value itself is consumed again by the option loop below. + for (int i = 1; i + 1 < argc; ++i) { + if (std::string(argv[i]) != "--gpu") continue; + // The caller's own environment is overridden, so say so (a stale CUDA_VISIBLE_DEVICES from a launcher + // would otherwise silently lose to the flag). + const char* envname = "CUDA_VISIBLE_DEVICES"; +#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) + envname = "HIP_VISIBLE_DEVICES"; // the AMD runtime ignores CUDA_VISIBLE_DEVICES (serve/server.py sets this one) +#endif + const char* prev = std::getenv(envname); + if (prev && prev[0] && std::string(prev) != argv[i + 1]) + std::fprintf(stderr, "warning: --gpu %s overrides %s=%s from the environment\n", argv[i + 1], envname, prev); +#if defined(_WIN32) + _putenv_s("CUDA_DEVICE_ORDER", "PCI_BUS_ID"); + _putenv_s(envname, argv[i + 1]); +#else + setenv("CUDA_DEVICE_ORDER", "PCI_BUS_ID", 1); + setenv(envname, argv[i + 1], 1); +#endif + break; + } Options o; bool have_tokens = false; bool have_logits_stride = false; @@ -1541,6 +1567,7 @@ int main(int argc, char** argv) { }; bool parsed = true; if (a == "--help" || a == "-h") { usage(); return 0; } + else if (a == "--gpu") { (void) next("--gpu"); } // applied at startup, before any CUDA call 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; }