add tools
Browse files- tools/moe_routed_experts/Makefile +39 -0
- tools/moe_routed_experts/README.md +330 -0
- tools/moe_routed_experts/requirements.txt +1 -0
- tools/moe_routed_experts/scripts/compare_routes.py +631 -0
- tools/moe_routed_experts/scripts/generate_decode_routes.py +204 -0
- tools/moe_routed_experts/scripts/prefill_routes.py +159 -0
- tools/moe_routed_experts/scripts/routed_common.py +224 -0
- tools/vllm_worker_verify_pipeline/README.md +164 -0
- tools/vllm_worker_verify_pipeline/analyze_vllm_worker_verify.py +1047 -0
- tools/vllm_worker_verify_pipeline/benchmark_worker_verifier_latency.py +436 -0
- tools/vllm_worker_verify_pipeline/calibrate_vllm_worker_verify_params.py +609 -0
- tools/vllm_worker_verify_pipeline/collect_vllm_worker_evidence.py +203 -0
- tools/vllm_worker_verify_pipeline/generate_prompts.py +246 -0
- tools/vllm_worker_verify_pipeline/pipeline_common.py +392 -0
- tools/vllm_worker_verify_pipeline/run_vllm_worker_verify.py +558 -0
- tools/vllm_worker_verify_pipeline/summarize_worker_verify.py +255 -0
- tools/vllm_worker_verify_pipeline/verify_vllm_worker_evidence.py +337 -0
- tools/worker_logits_verify/README.md +348 -0
- tools/worker_logits_verify/configs/variants.example.json +55 -0
- tools/worker_logits_verify/examples/tiny_challenger/metadata.json +5 -0
- tools/worker_logits_verify/examples/tiny_challenger/trace.jsonl +2 -0
- tools/worker_logits_verify/examples/tiny_left/metadata.json +5 -0
- tools/worker_logits_verify/examples/tiny_left/trace.jsonl +2 -0
- tools/worker_logits_verify/examples/tiny_right/metadata.json +5 -0
- tools/worker_logits_verify/examples/tiny_right/trace.jsonl +2 -0
- tools/worker_logits_verify/pyproject.toml +35 -0
- tools/worker_logits_verify/scripts/run_h100_6000_profile.sh +93 -0
- tools/worker_logits_verify/scripts/verifier_verifiy.py +329 -0
- tools/worker_logits_verify/scripts/vllm_openai_api.py +845 -0
- tools/worker_logits_verify/scripts/worker_inference.py +499 -0
- tools/worker_logits_verify/src/worker_logits_verify/__init__.py +3 -0
- tools/worker_logits_verify/src/worker_logits_verify/analyze_depth_effect.py +311 -0
- tools/worker_logits_verify/src/worker_logits_verify/calibrate_profile.py +174 -0
- tools/worker_logits_verify/src/worker_logits_verify/collect_trace.py +408 -0
- tools/worker_logits_verify/src/worker_logits_verify/collect_vllm_worker_evidence.py +201 -0
- tools/worker_logits_verify/src/worker_logits_verify/compare_traces.py +468 -0
- tools/worker_logits_verify/src/worker_logits_verify/dense_bf16_verifier.py +470 -0
- tools/worker_logits_verify/src/worker_logits_verify/estimate_sample_size.py +721 -0
- tools/worker_logits_verify/src/worker_logits_verify/generate_anchor_outputs.py +228 -0
- tools/worker_logits_verify/src/worker_logits_verify/generate_prompts.py +245 -0
- tools/worker_logits_verify/src/worker_logits_verify/metrics.py +137 -0
- tools/worker_logits_verify/src/worker_logits_verify/run_vllm_worker_verify.py +546 -0
- tools/worker_logits_verify/src/worker_logits_verify/schema.py +180 -0
- tools/worker_logits_verify/src/worker_logits_verify/summarize_worker_verify.py +254 -0
- tools/worker_logits_verify/src/worker_logits_verify/tokenizer_utils.py +81 -0
- tools/worker_logits_verify/src/worker_logits_verify/verify_comparison.py +231 -0
- tools/worker_logits_verify/src/worker_logits_verify/verify_vllm_worker_evidence.py +330 -0
- tools/worker_logits_verify/src/worker_logits_verify/vllm_utils.py +137 -0
tools/moe_routed_experts/Makefile
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
BASE_URL ?= http://localhost:8000
|
| 2 |
+
MODEL ?=
|
| 3 |
+
PROMPTS ?= ../data/qwen3_32b_identity_v1/prompts.jsonl
|
| 4 |
+
OUT_DIR ?= data
|
| 5 |
+
REPORT_DIR ?= reports
|
| 6 |
+
MAX_TOKENS ?= 128
|
| 7 |
+
TEMPERATURE ?= 0
|
| 8 |
+
SEED ?= 0
|
| 9 |
+
PYTHON ?= python3
|
| 10 |
+
LIMIT ?= 0
|
| 11 |
+
|
| 12 |
+
.PHONY: generate prefill compare guard-model
|
| 13 |
+
|
| 14 |
+
guard-model:
|
| 15 |
+
@test -n "$(MODEL)" || { echo "Set MODEL=<MODEL> when running this target." >&2; exit 2; }
|
| 16 |
+
|
| 17 |
+
generate: guard-model
|
| 18 |
+
$(PYTHON) scripts/generate_decode_routes.py \
|
| 19 |
+
--base-url "$(BASE_URL)" \
|
| 20 |
+
--model "$(MODEL)" \
|
| 21 |
+
--prompts-file "$(PROMPTS)" \
|
| 22 |
+
--output "$(OUT_DIR)/generated_routes.jsonl" \
|
| 23 |
+
--max-tokens "$(MAX_TOKENS)" \
|
| 24 |
+
--temperature "$(TEMPERATURE)" \
|
| 25 |
+
--seed "$(SEED)" \
|
| 26 |
+
--limit "$(LIMIT)"
|
| 27 |
+
|
| 28 |
+
prefill:
|
| 29 |
+
$(PYTHON) scripts/prefill_routes.py \
|
| 30 |
+
--base-url "$(BASE_URL)" \
|
| 31 |
+
--model "$(MODEL)" \
|
| 32 |
+
--input "$(OUT_DIR)/generated_routes.jsonl" \
|
| 33 |
+
--output "$(OUT_DIR)/prefill_routes.jsonl"
|
| 34 |
+
|
| 35 |
+
compare:
|
| 36 |
+
$(PYTHON) scripts/compare_routes.py \
|
| 37 |
+
--generated "$(OUT_DIR)/generated_routes.jsonl" \
|
| 38 |
+
--prefill "$(OUT_DIR)/prefill_routes.jsonl" \
|
| 39 |
+
--output-dir "$(REPORT_DIR)"
|
tools/moe_routed_experts/README.md
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 6 |
+
Start vLLM with routed experts enabled:
|
| 7 |
+
|
| 8 |
+
```bash
|
| 9 |
+
vllm serve <MODEL> --enable-return-routed-experts
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
Only this flag is required for these scripts:
|
| 13 |
+
|
| 14 |
+
```text
|
| 15 |
+
--enable-return-routed-experts
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
These scripts do not use trace replay, so this flag is not required:
|
| 19 |
+
|
| 20 |
+
```text
|
| 21 |
+
--enable-trace-replay
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
The HTTP requests also use these vLLM extra parameters:
|
| 25 |
+
|
| 26 |
+
```json
|
| 27 |
+
{
|
| 28 |
+
"return_token_ids": true
|
| 29 |
+
}
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
`return_token_ids` lets the generation step save the exact output token ids.
|
| 33 |
+
The prefill step additionally sends:
|
| 34 |
+
|
| 35 |
+
```json
|
| 36 |
+
{
|
| 37 |
+
"routed_experts_prompt_start": "len(input_token_ids)"
|
| 38 |
+
}
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
`routed_experts_prompt_start` asks vLLM to skip early prompt route entries. vLLM
|
| 42 |
+
requires this value to be strictly smaller than the prompt length. During prefill
|
| 43 |
+
the prompt is `input_token_ids + output_token_ids`, so `len(input_token_ids)` is
|
| 44 |
+
valid when the output is non-empty.
|
| 45 |
+
|
| 46 |
+
Do not set `routed_experts_prompt_start` to exactly `len(input_token_ids)` during
|
| 47 |
+
normal generation, because the generation prompt contains only the input tokens
|
| 48 |
+
and some vLLM versions hit this assertion:
|
| 49 |
+
|
| 50 |
+
```text
|
| 51 |
+
assert prompt_start < request.num_prompt_tokens
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
If your vLLM build rejects either field, check the installed vLLM version and the
|
| 55 |
+
OpenAI-compatible server's extra parameter support.
|
| 56 |
+
|
| 57 |
+
Install the tiny local dependency used to decode base64 `.npy` route payloads:
|
| 58 |
+
|
| 59 |
+
```bash
|
| 60 |
+
cd tools/moe_routed_experts
|
| 61 |
+
python3 -m pip install -r requirements.txt
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
For the cleanest comparison, avoid prefix-cache reuse while debugging. Some vLLM
|
| 65 |
+
versions can return `-1` sentinel values for cached prompt routes; the compare
|
| 66 |
+
script ignores `-1` by default.
|
| 67 |
+
|
| 68 |
+
If same-model prefill comparison unexpectedly returns many `-1` entries or a
|
| 69 |
+
large route mismatch, rerun once with prefix caching disabled. The exact CLI
|
| 70 |
+
spelling can vary by vLLM version, so confirm it with:
|
| 71 |
+
|
| 72 |
+
```bash
|
| 73 |
+
vllm serve --help | grep -i prefix
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
## Input Format
|
| 77 |
+
|
| 78 |
+
The default input is the existing `worker_logits_verify` prompt file:
|
| 79 |
+
|
| 80 |
+
```text
|
| 81 |
+
../data/qwen3_32b_identity_v1/prompts.jsonl
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
Expected row shape:
|
| 85 |
+
|
| 86 |
+
```json
|
| 87 |
+
{"sample_id":"7a613643598c07a5fd54","input_text":"...","category":"math_numeric","target_input_tokens":32,"metadata":{},"tokenizations":{}}
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
The scripts use `input_text` as the prompt and preserve `category`,
|
| 91 |
+
`target_input_tokens`, `anchor_variant`, `metadata`, and `tokenizations` in the
|
| 92 |
+
generated evidence rows.
|
| 93 |
+
|
| 94 |
+
## Command 1: Normal Prompt Generation
|
| 95 |
+
|
| 96 |
+
Generate output text, output token ids, and decode routed experts:
|
| 97 |
+
|
| 98 |
+
```bash
|
| 99 |
+
cd tools/moe_routed_experts
|
| 100 |
+
make generate MODEL=<MODEL> BASE_URL=http://localhost:8000
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
To test only the first `N` prompt rows:
|
| 104 |
+
|
| 105 |
+
```bash
|
| 106 |
+
make generate MODEL=<MODEL> BASE_URL=http://localhost:8000 LIMIT=10
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
Equivalent direct command:
|
| 110 |
+
|
| 111 |
+
```bash
|
| 112 |
+
python3 scripts/generate_decode_routes.py \
|
| 113 |
+
--base-url http://localhost:8000 \
|
| 114 |
+
--model <MODEL> \
|
| 115 |
+
--prompts-file ../data/qwen3_32b_identity_v1/prompts.jsonl \
|
| 116 |
+
--output data/generated_routes.jsonl \
|
| 117 |
+
--max-tokens 128 \
|
| 118 |
+
--temperature 0 \
|
| 119 |
+
--seed 0 \
|
| 120 |
+
--limit 10
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
Output:
|
| 124 |
+
|
| 125 |
+
```text
|
| 126 |
+
data/generated_routes.jsonl
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
Each row contains `input_token_ids`, `output_token_ids`, `output_text`, and
|
| 130 |
+
`routed_experts`. The generation request does not pass
|
| 131 |
+
`routed_experts_prompt_start`; it records the route window returned by vLLM and
|
| 132 |
+
saves `route_prompt_start = 0` for alignment.
|
| 133 |
+
|
| 134 |
+
## Command 2: Prefill Routes From Generated Output Tokens
|
| 135 |
+
|
| 136 |
+
Use the generated `output_token_ids` as the suffix of a full prompt and collect
|
| 137 |
+
prefill routed experts:
|
| 138 |
+
|
| 139 |
+
```bash
|
| 140 |
+
cd tools/moe_routed_experts
|
| 141 |
+
make prefill MODEL=<MODEL> BASE_URL=http://localhost:8000
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
Equivalent direct command:
|
| 145 |
+
|
| 146 |
+
```bash
|
| 147 |
+
python3 scripts/prefill_routes.py \
|
| 148 |
+
--base-url http://localhost:8000 \
|
| 149 |
+
--model <MODEL> \
|
| 150 |
+
--input data/generated_routes.jsonl \
|
| 151 |
+
--output data/prefill_routes.jsonl
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
Internally this sends:
|
| 155 |
+
|
| 156 |
+
```text
|
| 157 |
+
prompt = input_token_ids + output_token_ids
|
| 158 |
+
max_tokens = 0
|
| 159 |
+
echo = true
|
| 160 |
+
routed_experts_prompt_start = len(input_token_ids)
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
Output:
|
| 164 |
+
|
| 165 |
+
```text
|
| 166 |
+
data/prefill_routes.jsonl
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
## Command 3: Compare Decode Routes vs Prefill Routes
|
| 170 |
+
|
| 171 |
+
Compute route mismatch statistics:
|
| 172 |
+
|
| 173 |
+
```bash
|
| 174 |
+
cd tools/moe_routed_experts
|
| 175 |
+
make compare
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
Equivalent direct command:
|
| 179 |
+
|
| 180 |
+
```bash
|
| 181 |
+
python3 scripts/compare_routes.py \
|
| 182 |
+
--generated data/generated_routes.jsonl \
|
| 183 |
+
--prefill data/prefill_routes.jsonl \
|
| 184 |
+
--output-dir reports
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
To compare only selected MoE layers, add `--layers`. The value can be a single
|
| 188 |
+
layer, a range, or a comma-separated mix:
|
| 189 |
+
|
| 190 |
+
```bash
|
| 191 |
+
python3 scripts/compare_routes.py \
|
| 192 |
+
--generated data/generated_routes.jsonl \
|
| 193 |
+
--prefill data/prefill_routes.jsonl \
|
| 194 |
+
--output-dir reports/layers_0_4 \
|
| 195 |
+
--layers 0-4
|
| 196 |
+
```
|
| 197 |
+
|
| 198 |
+
Examples:
|
| 199 |
+
|
| 200 |
+
```text
|
| 201 |
+
--layers 0
|
| 202 |
+
--layers 0-4
|
| 203 |
+
--layers 0-4,7,12-15
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
Outputs:
|
| 207 |
+
|
| 208 |
+
```text
|
| 209 |
+
reports/route_diff_by_sample.csv
|
| 210 |
+
reports/route_diff_by_sample_layer.csv
|
| 211 |
+
reports/route_diff_by_layer.csv
|
| 212 |
+
reports/route_diff_summary.json
|
| 213 |
+
reports/route_diff_summary.md
|
| 214 |
+
```
|
| 215 |
+
|
| 216 |
+
Key metrics:
|
| 217 |
+
|
| 218 |
+
- `entry_mismatch_rate`: order-sensitive mismatch over token, MoE layer, top-k slot.
|
| 219 |
+
- `token_layer_set_match_rate`: order-insensitive exact top-k expert set match for each token/layer.
|
| 220 |
+
- `token_match_rate`: fraction of output route positions whose full layer/top-k route matches.
|
| 221 |
+
- `topk_overlap_mean`: order-insensitive top-k expert overlap per token/layer.
|
| 222 |
+
- `topk_jaccard_mean`: order-insensitive Jaccard similarity for top-k expert sets.
|
| 223 |
+
- `gen_tail_ignored` and `prefill_tail_ignored`: suffix lengths ignored because decode and prefill can expose one different final route position.
|
| 224 |
+
- `shape_mismatch_sample_count`: samples whose aligned route shape does not match the shape inferred from `input_token_ids` and `output_token_ids`.
|
| 225 |
+
- `raw_shape_mismatch_sample_count`: samples whose raw generation and prefill route arrays have different shapes. This can be expected because generation usually returns `input + output - 1` positions while prefill returns the output suffix.
|
| 226 |
+
|
| 227 |
+
`route_diff_by_sample.csv` is the sample-level report. It includes category,
|
| 228 |
+
input/output token counts, route alignment offsets, and every metric above for
|
| 229 |
+
each `sample_id`. The JSON/Markdown summary also includes sample-level
|
| 230 |
+
mean/min/p50/p90/max so one bad sample is not hidden by a global weighted average.
|
| 231 |
+
|
| 232 |
+
`route_diff_by_layer.csv` aggregates the same metrics by MoE layer index, which
|
| 233 |
+
is the most direct report for checking whether the same token's per-layer top-k
|
| 234 |
+
experts differ between normal generation and prefill.
|
| 235 |
+
|
| 236 |
+
## One-Vs-Rest Verification
|
| 237 |
+
|
| 238 |
+
The final identity test should generate worker traces from every candidate
|
| 239 |
+
source model, then prefill those same `input + output_token_ids` sequences with
|
| 240 |
+
each verifier model.
|
| 241 |
+
|
| 242 |
+
Example with `M1` and `M2`:
|
| 243 |
+
|
| 244 |
+
```bash
|
| 245 |
+
# 1. Generate claimed-source traces.
|
| 246 |
+
python3 scripts/generate_decode_routes.py \
|
| 247 |
+
--base-url http://localhost:8000 \
|
| 248 |
+
--model M1 \
|
| 249 |
+
--prompts-file ../data/qwen3.6_35b_a3b_identity_v1/prompts.jsonl \
|
| 250 |
+
--limit 5 \
|
| 251 |
+
--output data/generated_routes_m1.jsonl \
|
| 252 |
+
--max-tokens 128 \
|
| 253 |
+
--temperature 0
|
| 254 |
+
|
| 255 |
+
python3 scripts/generate_decode_routes.py \
|
| 256 |
+
--base-url http://localhost:8000 \
|
| 257 |
+
--model M2 \
|
| 258 |
+
--prompts-file ../data/qwen3.6_35b_a3b_identity_v1/prompts.jsonl \
|
| 259 |
+
--limit 5 \
|
| 260 |
+
--output data/generated_routes_m2.jsonl \
|
| 261 |
+
--max-tokens 128 \
|
| 262 |
+
--temperature 0
|
| 263 |
+
|
| 264 |
+
# 2. Use M1 as verifier against M1 and non-M1 outputs.
|
| 265 |
+
python3 scripts/prefill_routes.py \
|
| 266 |
+
--base-url http://localhost:8000 \
|
| 267 |
+
--model M1 \
|
| 268 |
+
--input data/generated_routes_m1.jsonl \
|
| 269 |
+
--output data/prefill_m1_generated_by_m1.jsonl
|
| 270 |
+
|
| 271 |
+
python3 scripts/prefill_routes.py \
|
| 272 |
+
--base-url http://localhost:8000 \
|
| 273 |
+
--model M1 \
|
| 274 |
+
--input data/generated_routes_m2.jsonl \
|
| 275 |
+
--output data/prefill_m1_generated_by_m2.jsonl
|
| 276 |
+
|
| 277 |
+
# 3. Use M2 as verifier against M2 and non-M2 outputs.
|
| 278 |
+
python3 scripts/prefill_routes.py \
|
| 279 |
+
--base-url http://localhost:8000 \
|
| 280 |
+
--model M2 \
|
| 281 |
+
--input data/generated_routes_m2.jsonl \
|
| 282 |
+
--output data/prefill_m2_generated_by_m2.jsonl
|
| 283 |
+
|
| 284 |
+
python3 scripts/prefill_routes.py \
|
| 285 |
+
--base-url http://localhost:8000 \
|
| 286 |
+
--model M2 \
|
| 287 |
+
--input data/generated_routes_m1.jsonl \
|
| 288 |
+
--output data/prefill_m2_generated_by_m1.jsonl
|
| 289 |
+
```
|
| 290 |
+
|
| 291 |
+
Then compare the positive and negative baselines:
|
| 292 |
+
|
| 293 |
+
```bash
|
| 294 |
+
# Positive for M1.
|
| 295 |
+
python3 scripts/compare_routes.py \
|
| 296 |
+
--generated data/generated_routes_m1.jsonl \
|
| 297 |
+
--prefill data/prefill_m1_generated_by_m1.jsonl \
|
| 298 |
+
--output-dir reports/m1_positive
|
| 299 |
+
|
| 300 |
+
# Negative for M1.
|
| 301 |
+
python3 scripts/compare_routes.py \
|
| 302 |
+
--generated data/generated_routes_m2.jsonl \
|
| 303 |
+
--prefill data/prefill_m1_generated_by_m2.jsonl \
|
| 304 |
+
--output-dir reports/m1_negative_m2
|
| 305 |
+
|
| 306 |
+
# Positive for M2.
|
| 307 |
+
python3 scripts/compare_routes.py \
|
| 308 |
+
--generated data/generated_routes_m2.jsonl \
|
| 309 |
+
--prefill data/prefill_m2_generated_by_m2.jsonl \
|
| 310 |
+
--output-dir reports/m2_positive
|
| 311 |
+
|
| 312 |
+
# Negative for M2.
|
| 313 |
+
python3 scripts/compare_routes.py \
|
| 314 |
+
--generated data/generated_routes_m1.jsonl \
|
| 315 |
+
--prefill data/prefill_m2_generated_by_m1.jsonl \
|
| 316 |
+
--output-dir reports/m2_negative_m1
|
| 317 |
+
```
|
| 318 |
+
|
| 319 |
+
For each verifier, the positive distribution should separate from the negative
|
| 320 |
+
distribution. For example, M1 is useful as a verifier only if `reports/m1_positive`
|
| 321 |
+
has much higher `topk_overlap_mean` / `token_layer_set_match_rate` and much lower
|
| 322 |
+
`entry_mismatch_rate` than `reports/m1_negative_m2`.
|
| 323 |
+
|
| 324 |
+
## Notes
|
| 325 |
+
|
| 326 |
+
- This path does not use trace replay. It compares normal decode generation
|
| 327 |
+
against a teacher-forcing prefill pass.
|
| 328 |
+
- If same-model mismatch is high, first check token alignment, prefix cache,
|
| 329 |
+
vLLM version, MoE kernel differences, and whether the server actually returns
|
| 330 |
+
output-only routes after `routed_experts_prompt_start`.
|
tools/moe_routed_experts/requirements.txt
ADDED
|
@@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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import csv
|
| 6 |
+
import json
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
| 10 |
+
|
| 11 |
+
from routed_common import (
|
| 12 |
+
decode_routed_experts,
|
| 13 |
+
normalize_route_array,
|
| 14 |
+
print_progress,
|
| 15 |
+
read_jsonl,
|
| 16 |
+
require_numpy,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def route_array(row: Dict[str, Any]) -> Optional[np.ndarray]:
|
| 21 |
+
arr = decode_routed_experts(row.get("routed_experts"))
|
| 22 |
+
if arr is None:
|
| 23 |
+
return None
|
| 24 |
+
return normalize_route_array(arr)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def load_by_sample(path: Path) -> Dict[str, Dict[str, Any]]:
|
| 28 |
+
rows = {}
|
| 29 |
+
for row in read_jsonl(path):
|
| 30 |
+
sample_id = str(row.get("sample_id"))
|
| 31 |
+
rows[sample_id] = row
|
| 32 |
+
return rows
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def safe_div(numer: float, denom: float) -> Optional[float]:
|
| 36 |
+
if denom == 0:
|
| 37 |
+
return None
|
| 38 |
+
return numer / denom
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def parse_layer_spec(raw: Optional[str]) -> Optional[List[int]]:
|
| 42 |
+
if raw is None or raw.strip() == "":
|
| 43 |
+
return None
|
| 44 |
+
layers = []
|
| 45 |
+
for part in raw.split(","):
|
| 46 |
+
part = part.strip()
|
| 47 |
+
if not part:
|
| 48 |
+
continue
|
| 49 |
+
if "-" in part:
|
| 50 |
+
start_raw, end_raw = part.split("-", 1)
|
| 51 |
+
start = int(start_raw)
|
| 52 |
+
end = int(end_raw)
|
| 53 |
+
if end < start:
|
| 54 |
+
raise ValueError(f"Invalid layer range: {part}")
|
| 55 |
+
layers.extend(range(start, end + 1))
|
| 56 |
+
else:
|
| 57 |
+
layers.append(int(part))
|
| 58 |
+
out = sorted(set(layers))
|
| 59 |
+
if any(layer < 0 for layer in out):
|
| 60 |
+
raise ValueError(f"Layer indices must be non-negative: {raw}")
|
| 61 |
+
return out
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def topk_set_stats(a: np.ndarray, b: np.ndarray, mask: np.ndarray) -> Dict[str, Any]:
|
| 65 |
+
np = require_numpy()
|
| 66 |
+
overlaps = []
|
| 67 |
+
jaccards = []
|
| 68 |
+
set_match_count = 0
|
| 69 |
+
for token_idx in range(a.shape[0]):
|
| 70 |
+
for layer_idx in range(a.shape[1]):
|
| 71 |
+
if not mask[token_idx, layer_idx].any():
|
| 72 |
+
continue
|
| 73 |
+
left = set(int(x) for x in a[token_idx, layer_idx][mask[token_idx, layer_idx]])
|
| 74 |
+
right = set(int(x) for x in b[token_idx, layer_idx][mask[token_idx, layer_idx]])
|
| 75 |
+
intersection = left.intersection(right)
|
| 76 |
+
union = left.union(right)
|
| 77 |
+
denom = max(len(left), len(right), 1)
|
| 78 |
+
overlaps.append(len(intersection) / denom)
|
| 79 |
+
jaccards.append(len(intersection) / len(union) if union else 1.0)
|
| 80 |
+
if left == right:
|
| 81 |
+
set_match_count += 1
|
| 82 |
+
count = len(overlaps)
|
| 83 |
+
return {
|
| 84 |
+
"token_layer_set_count": count,
|
| 85 |
+
"token_layer_set_match_count": set_match_count,
|
| 86 |
+
"token_layer_set_match_rate": safe_div(set_match_count, count),
|
| 87 |
+
"topk_overlap_sum": float(sum(overlaps)),
|
| 88 |
+
"topk_overlap_mean": float(np.mean(overlaps)) if overlaps else None,
|
| 89 |
+
"topk_jaccard_sum": float(sum(jaccards)),
|
| 90 |
+
"topk_jaccard_mean": float(np.mean(jaccards)) if jaccards else None,
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def infer_shape_status(meta: Dict[str, Any], gen_shape: List[int], prefill_shape: List[int]) -> Dict[str, Any]:
|
| 95 |
+
input_len = int(meta.get("input_token_count") or 0)
|
| 96 |
+
output_len = int(meta.get("output_token_count") or 0)
|
| 97 |
+
gen_start = int(meta.get("gen_route_start") or 0)
|
| 98 |
+
pre_start = int(meta.get("prefill_route_start") or 0)
|
| 99 |
+
|
| 100 |
+
expected_gen_positions = max(0, input_len + output_len - 1)
|
| 101 |
+
expected_prefill_positions = input_len + output_len
|
| 102 |
+
expected_gen_len = max(0, expected_gen_positions - gen_start)
|
| 103 |
+
expected_prefill_len = max(0, expected_prefill_positions - pre_start)
|
| 104 |
+
expected_overlap_start = max(gen_start, pre_start)
|
| 105 |
+
expected_overlap_end = min(expected_gen_positions, expected_prefill_positions)
|
| 106 |
+
expected_overlap_len = max(0, expected_overlap_end - expected_overlap_start)
|
| 107 |
+
|
| 108 |
+
gen_len = int(gen_shape[0]) if gen_shape else 0
|
| 109 |
+
prefill_len = int(prefill_shape[0]) if prefill_shape else 0
|
| 110 |
+
gen_layers = int(gen_shape[1]) if len(gen_shape) > 1 else 0
|
| 111 |
+
prefill_layers = int(prefill_shape[1]) if len(prefill_shape) > 1 else 0
|
| 112 |
+
gen_topk = int(gen_shape[2]) if len(gen_shape) > 2 else 0
|
| 113 |
+
prefill_topk = int(prefill_shape[2]) if len(prefill_shape) > 2 else 0
|
| 114 |
+
|
| 115 |
+
layer_topk_match = gen_layers == prefill_layers and gen_topk == prefill_topk
|
| 116 |
+
expected_length_match = (
|
| 117 |
+
gen_len == expected_gen_len
|
| 118 |
+
and prefill_len == expected_prefill_len
|
| 119 |
+
and int(meta.get("common_len") or 0) == expected_overlap_len
|
| 120 |
+
)
|
| 121 |
+
inferred_shape_match = layer_topk_match and expected_length_match
|
| 122 |
+
|
| 123 |
+
return {
|
| 124 |
+
"raw_shape_match": gen_shape == prefill_shape,
|
| 125 |
+
"expected_gen_route_len": expected_gen_len,
|
| 126 |
+
"expected_prefill_route_len": expected_prefill_len,
|
| 127 |
+
"expected_overlap_len": expected_overlap_len,
|
| 128 |
+
"expected_length_match": expected_length_match,
|
| 129 |
+
"layer_topk_shape_match": layer_topk_match,
|
| 130 |
+
"inferred_shape_match": inferred_shape_match,
|
| 131 |
+
"shape_status": "expected_aligned_shape" if inferred_shape_match else "unexpected_shape",
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def aligned_route_window(gen_row: Dict[str, Any],
|
| 136 |
+
prefill_row: Dict[str, Any],
|
| 137 |
+
*,
|
| 138 |
+
ignore_value: Optional[int],
|
| 139 |
+
layer_indices: Optional[List[int]]) -> Tuple[Dict[str, Any], Any, Any, Any]:
|
| 140 |
+
np = require_numpy()
|
| 141 |
+
sample_id = str(gen_row.get("sample_id"))
|
| 142 |
+
gen = route_array(gen_row)
|
| 143 |
+
pre = route_array(prefill_row)
|
| 144 |
+
if gen is None or pre is None:
|
| 145 |
+
return {"sample_id": sample_id, "status": "missing_routes"}, None, None, None
|
| 146 |
+
|
| 147 |
+
gen_start = int(gen_row.get("route_prompt_start", 0) or 0)
|
| 148 |
+
pre_start = int(prefill_row.get("route_prompt_start", 0) or 0)
|
| 149 |
+
gen_request = gen_row.get("request") or {}
|
| 150 |
+
source_model = str(gen_request.get("model") or prefill_row.get("source_model") or "")
|
| 151 |
+
verifier_model = str(prefill_row.get("verifier_model") or "")
|
| 152 |
+
gen_len, pre_len = int(gen.shape[0]), int(pre.shape[0])
|
| 153 |
+
overlap_start = max(gen_start, pre_start)
|
| 154 |
+
overlap_end = min(gen_start + gen_len, pre_start + pre_len)
|
| 155 |
+
common_len = max(0, overlap_end - overlap_start)
|
| 156 |
+
common_layers = min(int(gen.shape[1]), int(pre.shape[1]))
|
| 157 |
+
common_topk = min(int(gen.shape[2]), int(pre.shape[2]))
|
| 158 |
+
meta = {
|
| 159 |
+
"sample_id": sample_id,
|
| 160 |
+
"source_model": source_model,
|
| 161 |
+
"verifier_model": verifier_model,
|
| 162 |
+
"comparison_kind": (
|
| 163 |
+
"same_model"
|
| 164 |
+
if source_model and verifier_model and source_model == verifier_model
|
| 165 |
+
else "cross_model"
|
| 166 |
+
),
|
| 167 |
+
"category": gen_row.get("category", prefill_row.get("category", "")),
|
| 168 |
+
"target_input_tokens": gen_row.get(
|
| 169 |
+
"target_input_tokens",
|
| 170 |
+
prefill_row.get("target_input_tokens"),
|
| 171 |
+
),
|
| 172 |
+
"input_token_count": len(gen_row.get("input_token_ids") or []),
|
| 173 |
+
"output_token_count": len(gen_row.get("output_token_ids") or []),
|
| 174 |
+
"gen_shape": list(gen.shape),
|
| 175 |
+
"prefill_shape": list(pre.shape),
|
| 176 |
+
"gen_route_start": gen_start,
|
| 177 |
+
"prefill_route_start": pre_start,
|
| 178 |
+
"overlap_start": overlap_start,
|
| 179 |
+
"overlap_end": overlap_end,
|
| 180 |
+
}
|
| 181 |
+
if common_len == 0 or common_layers == 0 or common_topk == 0:
|
| 182 |
+
meta.update(infer_shape_status(meta, list(gen.shape), list(pre.shape)))
|
| 183 |
+
meta["status"] = "empty_common_window"
|
| 184 |
+
return meta, None, None, None
|
| 185 |
+
|
| 186 |
+
gen_offset = overlap_start - gen_start
|
| 187 |
+
pre_offset = overlap_start - pre_start
|
| 188 |
+
raw_common_layers = common_layers
|
| 189 |
+
selected_layer_indices = (
|
| 190 |
+
[layer for layer in layer_indices if layer < common_layers]
|
| 191 |
+
if layer_indices is not None
|
| 192 |
+
else list(range(common_layers))
|
| 193 |
+
)
|
| 194 |
+
if not selected_layer_indices:
|
| 195 |
+
meta.update(infer_shape_status(meta, list(gen.shape), list(pre.shape)))
|
| 196 |
+
meta["status"] = "no_selected_layers"
|
| 197 |
+
meta["requested_layers"] = layer_indices
|
| 198 |
+
return meta, None, None, None
|
| 199 |
+
gen_cmp = gen[gen_offset:gen_offset + common_len, :common_layers, :common_topk]
|
| 200 |
+
pre_cmp = pre[pre_offset:pre_offset + common_len, :common_layers, :common_topk]
|
| 201 |
+
gen_cmp = gen_cmp[:, selected_layer_indices, :]
|
| 202 |
+
pre_cmp = pre_cmp[:, selected_layer_indices, :]
|
| 203 |
+
valid = np.ones(gen_cmp.shape, dtype=bool)
|
| 204 |
+
if ignore_value is not None:
|
| 205 |
+
valid &= gen_cmp != ignore_value
|
| 206 |
+
valid &= pre_cmp != ignore_value
|
| 207 |
+
|
| 208 |
+
meta.update({
|
| 209 |
+
"status": "ok",
|
| 210 |
+
"gen_overlap_offset": gen_offset,
|
| 211 |
+
"prefill_overlap_offset": pre_offset,
|
| 212 |
+
"common_len": common_len,
|
| 213 |
+
"common_layers": len(selected_layer_indices),
|
| 214 |
+
"raw_common_layers": raw_common_layers,
|
| 215 |
+
"selected_layers": ",".join(str(layer) for layer in selected_layer_indices),
|
| 216 |
+
"common_topk": common_topk,
|
| 217 |
+
"gen_prefix_ignored": gen_offset,
|
| 218 |
+
"prefill_prefix_ignored": pre_offset,
|
| 219 |
+
"gen_tail_ignored": max(0, gen_len - gen_offset - common_len),
|
| 220 |
+
"prefill_tail_ignored": max(0, pre_len - pre_offset - common_len),
|
| 221 |
+
})
|
| 222 |
+
meta.update(infer_shape_status(meta, list(gen.shape), list(pre.shape)))
|
| 223 |
+
return meta, gen_cmp, pre_cmp, valid
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def compare_one(gen_row: Dict[str, Any],
|
| 227 |
+
prefill_row: Dict[str, Any],
|
| 228 |
+
*,
|
| 229 |
+
ignore_value: Optional[int],
|
| 230 |
+
layer_indices: Optional[List[int]]) -> Dict[str, Any]:
|
| 231 |
+
np = require_numpy()
|
| 232 |
+
meta, gen_cmp, pre_cmp, valid = aligned_route_window(
|
| 233 |
+
gen_row,
|
| 234 |
+
prefill_row,
|
| 235 |
+
ignore_value=ignore_value,
|
| 236 |
+
layer_indices=layer_indices,
|
| 237 |
+
)
|
| 238 |
+
if meta.get("status") != "ok":
|
| 239 |
+
return meta
|
| 240 |
+
|
| 241 |
+
compared_entries = int(valid.sum())
|
| 242 |
+
entry_matches = int(((gen_cmp == pre_cmp) & valid).sum())
|
| 243 |
+
entry_mismatches = compared_entries - entry_matches
|
| 244 |
+
|
| 245 |
+
token_layer_valid = valid.any(axis=2)
|
| 246 |
+
token_layer_exact = ((gen_cmp == pre_cmp) | ~valid).all(axis=2) & token_layer_valid
|
| 247 |
+
token_layer_count = int(token_layer_valid.sum())
|
| 248 |
+
token_layer_match_count = int(token_layer_exact.sum())
|
| 249 |
+
|
| 250 |
+
token_valid = token_layer_valid.any(axis=1)
|
| 251 |
+
token_exact = ((gen_cmp == pre_cmp) | ~valid).all(axis=(1, 2)) & token_valid
|
| 252 |
+
token_count = int(token_valid.sum())
|
| 253 |
+
token_match_count = int(token_exact.sum())
|
| 254 |
+
set_stats = topk_set_stats(gen_cmp, pre_cmp, valid)
|
| 255 |
+
|
| 256 |
+
meta.update({
|
| 257 |
+
"compared_entries": compared_entries,
|
| 258 |
+
"entry_match_count": entry_matches,
|
| 259 |
+
"entry_mismatch_count": entry_mismatches,
|
| 260 |
+
"entry_match_rate": safe_div(entry_matches, compared_entries),
|
| 261 |
+
"entry_mismatch_rate": safe_div(entry_mismatches, compared_entries),
|
| 262 |
+
"token_layer_count": token_layer_count,
|
| 263 |
+
"token_layer_match_count": token_layer_match_count,
|
| 264 |
+
"token_layer_match_rate": safe_div(token_layer_match_count, token_layer_count),
|
| 265 |
+
"token_count": token_count,
|
| 266 |
+
"token_match_count": token_match_count,
|
| 267 |
+
"token_match_rate": safe_div(token_match_count, token_count),
|
| 268 |
+
**set_stats,
|
| 269 |
+
})
|
| 270 |
+
return meta
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def compare_layer_rows(gen_row: Dict[str, Any],
|
| 274 |
+
prefill_row: Dict[str, Any],
|
| 275 |
+
*,
|
| 276 |
+
ignore_value: Optional[int],
|
| 277 |
+
layer_indices: Optional[List[int]]) -> List[Dict[str, Any]]:
|
| 278 |
+
np = require_numpy()
|
| 279 |
+
meta, gen_cmp, pre_cmp, valid = aligned_route_window(
|
| 280 |
+
gen_row,
|
| 281 |
+
prefill_row,
|
| 282 |
+
ignore_value=ignore_value,
|
| 283 |
+
layer_indices=layer_indices,
|
| 284 |
+
)
|
| 285 |
+
if meta.get("status") != "ok":
|
| 286 |
+
return []
|
| 287 |
+
|
| 288 |
+
rows = []
|
| 289 |
+
selected_layer_indices = [
|
| 290 |
+
int(layer)
|
| 291 |
+
for layer in str(meta.get("selected_layers", "")).split(",")
|
| 292 |
+
if layer != ""
|
| 293 |
+
]
|
| 294 |
+
for local_layer_idx, original_layer_idx in enumerate(selected_layer_indices):
|
| 295 |
+
layer_gen = gen_cmp[:, local_layer_idx:local_layer_idx + 1, :]
|
| 296 |
+
layer_pre = pre_cmp[:, local_layer_idx:local_layer_idx + 1, :]
|
| 297 |
+
layer_valid = valid[:, local_layer_idx:local_layer_idx + 1, :]
|
| 298 |
+
compared_entries = int(layer_valid.sum())
|
| 299 |
+
entry_matches = int(((layer_gen == layer_pre) & layer_valid).sum())
|
| 300 |
+
token_layer_valid = layer_valid.any(axis=2)
|
| 301 |
+
token_layer_exact = ((layer_gen == layer_pre) | ~layer_valid).all(axis=2) & token_layer_valid
|
| 302 |
+
token_layer_count = int(token_layer_valid.sum())
|
| 303 |
+
token_layer_match_count = int(token_layer_exact.sum())
|
| 304 |
+
set_stats = topk_set_stats(layer_gen, layer_pre, layer_valid)
|
| 305 |
+
rows.append({
|
| 306 |
+
"sample_id": meta["sample_id"],
|
| 307 |
+
"layer_idx": original_layer_idx,
|
| 308 |
+
"common_len": meta["common_len"],
|
| 309 |
+
"common_topk": meta["common_topk"],
|
| 310 |
+
"compared_entries": compared_entries,
|
| 311 |
+
"entry_match_count": entry_matches,
|
| 312 |
+
"entry_mismatch_count": compared_entries - entry_matches,
|
| 313 |
+
"entry_match_rate": safe_div(entry_matches, compared_entries),
|
| 314 |
+
"entry_mismatch_rate": safe_div(compared_entries - entry_matches, compared_entries),
|
| 315 |
+
"token_layer_count": token_layer_count,
|
| 316 |
+
"token_layer_match_count": token_layer_match_count,
|
| 317 |
+
"token_layer_match_rate": safe_div(token_layer_match_count, token_layer_count),
|
| 318 |
+
**set_stats,
|
| 319 |
+
})
|
| 320 |
+
return rows
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def summarize(rows: Iterable[Dict[str, Any]]) -> Dict[str, Any]:
|
| 324 |
+
np = require_numpy()
|
| 325 |
+
rows = list(rows)
|
| 326 |
+
ok_rows = [row for row in rows if row.get("status") == "ok"]
|
| 327 |
+
selected_layers = sorted({
|
| 328 |
+
str(row.get("selected_layers"))
|
| 329 |
+
for row in ok_rows
|
| 330 |
+
if row.get("selected_layers") is not None
|
| 331 |
+
})
|
| 332 |
+
selected_layer_counts = sorted({
|
| 333 |
+
int(row.get("common_layers") or 0)
|
| 334 |
+
for row in ok_rows
|
| 335 |
+
if row.get("common_layers") is not None
|
| 336 |
+
})
|
| 337 |
+
compared_entries = sum(int(row.get("compared_entries") or 0) for row in ok_rows)
|
| 338 |
+
entry_matches = sum(int(row.get("entry_match_count") or 0) for row in ok_rows)
|
| 339 |
+
token_count = sum(int(row.get("token_count") or 0) for row in ok_rows)
|
| 340 |
+
token_matches = sum(int(row.get("token_match_count") or 0) for row in ok_rows)
|
| 341 |
+
token_layer_set_count = sum(int(row.get("token_layer_set_count") or 0) for row in ok_rows)
|
| 342 |
+
token_layer_set_matches = sum(
|
| 343 |
+
int(row.get("token_layer_set_match_count") or 0)
|
| 344 |
+
for row in ok_rows
|
| 345 |
+
)
|
| 346 |
+
topk_values = [
|
| 347 |
+
float(row["topk_overlap_mean"])
|
| 348 |
+
for row in ok_rows
|
| 349 |
+
if row.get("topk_overlap_mean") is not None
|
| 350 |
+
]
|
| 351 |
+
topk_jaccard_values = [
|
| 352 |
+
float(row["topk_jaccard_mean"])
|
| 353 |
+
for row in ok_rows
|
| 354 |
+
if row.get("topk_jaccard_mean") is not None
|
| 355 |
+
]
|
| 356 |
+
sample_metric_summary = summarize_sample_metrics(ok_rows)
|
| 357 |
+
return {
|
| 358 |
+
"sample_count": len(rows),
|
| 359 |
+
"ok_sample_count": len(ok_rows),
|
| 360 |
+
"non_ok_sample_count": len(rows) - len(ok_rows),
|
| 361 |
+
"source_models": sorted({
|
| 362 |
+
str(row.get("source_model"))
|
| 363 |
+
for row in ok_rows
|
| 364 |
+
if row.get("source_model")
|
| 365 |
+
}),
|
| 366 |
+
"verifier_models": sorted({
|
| 367 |
+
str(row.get("verifier_model"))
|
| 368 |
+
for row in ok_rows
|
| 369 |
+
if row.get("verifier_model")
|
| 370 |
+
}),
|
| 371 |
+
"comparison_kind_counts": {
|
| 372 |
+
"same_model": sum(1 for row in ok_rows if row.get("comparison_kind") == "same_model"),
|
| 373 |
+
"cross_model": sum(1 for row in ok_rows if row.get("comparison_kind") == "cross_model"),
|
| 374 |
+
},
|
| 375 |
+
"selected_layers": selected_layers,
|
| 376 |
+
"selected_layer_counts": selected_layer_counts,
|
| 377 |
+
"weighted_entry_match_rate": safe_div(entry_matches, compared_entries),
|
| 378 |
+
"weighted_entry_mismatch_rate": safe_div(compared_entries - entry_matches, compared_entries),
|
| 379 |
+
"weighted_token_match_rate": safe_div(token_matches, token_count),
|
| 380 |
+
"weighted_token_layer_set_match_rate": safe_div(
|
| 381 |
+
token_layer_set_matches,
|
| 382 |
+
token_layer_set_count,
|
| 383 |
+
),
|
| 384 |
+
"mean_sample_entry_mismatch_rate": (
|
| 385 |
+
float(np.mean([row["entry_mismatch_rate"] for row in ok_rows if row.get("entry_mismatch_rate") is not None]))
|
| 386 |
+
if ok_rows else None
|
| 387 |
+
),
|
| 388 |
+
"mean_topk_overlap": float(np.mean(topk_values)) if topk_values else None,
|
| 389 |
+
"mean_topk_jaccard": float(np.mean(topk_jaccard_values)) if topk_jaccard_values else None,
|
| 390 |
+
"sample_metric_summary": sample_metric_summary,
|
| 391 |
+
"total_compared_entries": compared_entries,
|
| 392 |
+
"total_compared_tokens": token_count,
|
| 393 |
+
"total_compared_token_layers": token_layer_set_count,
|
| 394 |
+
"raw_shape_mismatch_sample_count": sum(
|
| 395 |
+
1 for row in ok_rows if not row.get("raw_shape_match")
|
| 396 |
+
),
|
| 397 |
+
"expected_length_mismatch_sample_count": sum(
|
| 398 |
+
1 for row in ok_rows if not row.get("expected_length_match")
|
| 399 |
+
),
|
| 400 |
+
"layer_topk_shape_mismatch_sample_count": sum(
|
| 401 |
+
1 for row in ok_rows if not row.get("layer_topk_shape_match")
|
| 402 |
+
),
|
| 403 |
+
"shape_mismatch_sample_count": sum(
|
| 404 |
+
1 for row in ok_rows if not row.get("inferred_shape_match")
|
| 405 |
+
),
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def summarize_sample_metrics(rows: Iterable[Dict[str, Any]]) -> Dict[str, Dict[str, Optional[float]]]:
|
| 410 |
+
np = require_numpy()
|
| 411 |
+
metric_names = (
|
| 412 |
+
"entry_mismatch_rate",
|
| 413 |
+
"token_layer_match_rate",
|
| 414 |
+
"token_layer_set_match_rate",
|
| 415 |
+
"token_match_rate",
|
| 416 |
+
"topk_overlap_mean",
|
| 417 |
+
"topk_jaccard_mean",
|
| 418 |
+
)
|
| 419 |
+
summary: Dict[str, Dict[str, Optional[float]]] = {}
|
| 420 |
+
for metric_name in metric_names:
|
| 421 |
+
values = [
|
| 422 |
+
float(row[metric_name])
|
| 423 |
+
for row in rows
|
| 424 |
+
if row.get(metric_name) is not None
|
| 425 |
+
]
|
| 426 |
+
if not values:
|
| 427 |
+
summary[metric_name] = {
|
| 428 |
+
"count": 0,
|
| 429 |
+
"mean": None,
|
| 430 |
+
"min": None,
|
| 431 |
+
"p50": None,
|
| 432 |
+
"p90": None,
|
| 433 |
+
"max": None,
|
| 434 |
+
}
|
| 435 |
+
continue
|
| 436 |
+
arr = np.asarray(values, dtype=float)
|
| 437 |
+
summary[metric_name] = {
|
| 438 |
+
"count": int(arr.size),
|
| 439 |
+
"mean": float(np.mean(arr)),
|
| 440 |
+
"min": float(np.min(arr)),
|
| 441 |
+
"p50": float(np.percentile(arr, 50)),
|
| 442 |
+
"p90": float(np.percentile(arr, 90)),
|
| 443 |
+
"max": float(np.max(arr)),
|
| 444 |
+
}
|
| 445 |
+
return summary
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def summarize_layer_rows(rows: Iterable[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 449 |
+
groups = defaultdict(lambda: {
|
| 450 |
+
"sample_layer_count": 0,
|
| 451 |
+
"compared_entries": 0,
|
| 452 |
+
"entry_match_count": 0,
|
| 453 |
+
"token_layer_count": 0,
|
| 454 |
+
"token_layer_match_count": 0,
|
| 455 |
+
"token_layer_set_count": 0,
|
| 456 |
+
"token_layer_set_match_count": 0,
|
| 457 |
+
"topk_overlap_sum": 0.0,
|
| 458 |
+
"topk_jaccard_sum": 0.0,
|
| 459 |
+
})
|
| 460 |
+
for row in rows:
|
| 461 |
+
group = groups[int(row["layer_idx"])]
|
| 462 |
+
group["sample_layer_count"] += 1
|
| 463 |
+
for key in (
|
| 464 |
+
"compared_entries",
|
| 465 |
+
"entry_match_count",
|
| 466 |
+
"token_layer_count",
|
| 467 |
+
"token_layer_match_count",
|
| 468 |
+
"token_layer_set_count",
|
| 469 |
+
"token_layer_set_match_count",
|
| 470 |
+
):
|
| 471 |
+
group[key] += int(row.get(key) or 0)
|
| 472 |
+
group["topk_overlap_sum"] += float(row.get("topk_overlap_sum") or 0.0)
|
| 473 |
+
group["topk_jaccard_sum"] += float(row.get("topk_jaccard_sum") or 0.0)
|
| 474 |
+
|
| 475 |
+
out = []
|
| 476 |
+
for layer_idx in sorted(groups):
|
| 477 |
+
group = groups[layer_idx]
|
| 478 |
+
compared_entries = group["compared_entries"]
|
| 479 |
+
entry_matches = group["entry_match_count"]
|
| 480 |
+
token_layer_count = group["token_layer_count"]
|
| 481 |
+
token_layer_matches = group["token_layer_match_count"]
|
| 482 |
+
set_count = group["token_layer_set_count"]
|
| 483 |
+
set_matches = group["token_layer_set_match_count"]
|
| 484 |
+
out.append({
|
| 485 |
+
"layer_idx": layer_idx,
|
| 486 |
+
"sample_layer_count": group["sample_layer_count"],
|
| 487 |
+
"compared_entries": compared_entries,
|
| 488 |
+
"entry_match_count": entry_matches,
|
| 489 |
+
"entry_mismatch_count": compared_entries - entry_matches,
|
| 490 |
+
"entry_match_rate": safe_div(entry_matches, compared_entries),
|
| 491 |
+
"entry_mismatch_rate": safe_div(compared_entries - entry_matches, compared_entries),
|
| 492 |
+
"token_layer_count": token_layer_count,
|
| 493 |
+
"token_layer_match_count": token_layer_matches,
|
| 494 |
+
"token_layer_match_rate": safe_div(token_layer_matches, token_layer_count),
|
| 495 |
+
"token_layer_set_count": set_count,
|
| 496 |
+
"token_layer_set_match_count": set_matches,
|
| 497 |
+
"token_layer_set_match_rate": safe_div(set_matches, set_count),
|
| 498 |
+
"topk_overlap_mean": safe_div(group["topk_overlap_sum"], set_count),
|
| 499 |
+
"topk_jaccard_mean": safe_div(group["topk_jaccard_sum"], set_count),
|
| 500 |
+
})
|
| 501 |
+
return out
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def write_summary_md(path: Path, summary: Dict[str, Any]) -> None:
|
| 505 |
+
lines = [
|
| 506 |
+
"# Routed Experts Diff Summary",
|
| 507 |
+
"",
|
| 508 |
+
f"- samples: {summary['sample_count']}",
|
| 509 |
+
f"- ok samples: {summary['ok_sample_count']}",
|
| 510 |
+
f"- selected layers: {summary.get('selected_layers')}",
|
| 511 |
+
f"- selected layer counts: {summary.get('selected_layer_counts')}",
|
| 512 |
+
f"- weighted entry mismatch rate: {summary['weighted_entry_mismatch_rate']}",
|
| 513 |
+
f"- weighted token match rate: {summary['weighted_token_match_rate']}",
|
| 514 |
+
f"- weighted token-layer set match rate: {summary['weighted_token_layer_set_match_rate']}",
|
| 515 |
+
f"- mean top-k overlap: {summary['mean_topk_overlap']}",
|
| 516 |
+
f"- mean top-k jaccard: {summary['mean_topk_jaccard']}",
|
| 517 |
+
f"- total compared entries: {summary['total_compared_entries']}",
|
| 518 |
+
f"- total compared token-layers: {summary['total_compared_token_layers']}",
|
| 519 |
+
f"- shape mismatch samples: {summary['shape_mismatch_sample_count']}",
|
| 520 |
+
f"- raw shape mismatch samples: {summary['raw_shape_mismatch_sample_count']}",
|
| 521 |
+
f"- expected length mismatch samples: {summary['expected_length_mismatch_sample_count']}",
|
| 522 |
+
f"- layer/top-k shape mismatch samples: {summary['layer_topk_shape_mismatch_sample_count']}",
|
| 523 |
+
"",
|
| 524 |
+
]
|
| 525 |
+
sample_summary = summary.get("sample_metric_summary") or {}
|
| 526 |
+
if sample_summary:
|
| 527 |
+
lines.extend([
|
| 528 |
+
"## Sample Metric Summary",
|
| 529 |
+
"",
|
| 530 |
+
"| metric | count | mean | min | p50 | p90 | max |",
|
| 531 |
+
"| --- | ---: | ---: | ---: | ---: | ---: | ---: |",
|
| 532 |
+
])
|
| 533 |
+
for metric_name, stats in sample_summary.items():
|
| 534 |
+
lines.append(
|
| 535 |
+
f"| {metric_name} | {stats.get('count')} | "
|
| 536 |
+
f"{stats.get('mean')} | {stats.get('min')} | "
|
| 537 |
+
f"{stats.get('p50')} | {stats.get('p90')} | {stats.get('max')} |"
|
| 538 |
+
)
|
| 539 |
+
lines.append("")
|
| 540 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def main() -> int:
|
| 544 |
+
parser = argparse.ArgumentParser(
|
| 545 |
+
description="Compare generated routed_experts with prefill routed_experts."
|
| 546 |
+
)
|
| 547 |
+
parser.add_argument("--generated", default="data/generated_routes.jsonl")
|
| 548 |
+
parser.add_argument("--prefill", default="data/prefill_routes.jsonl")
|
| 549 |
+
parser.add_argument("--output-dir", default="reports")
|
| 550 |
+
parser.add_argument("--ignore-value", type=int, default=-1)
|
| 551 |
+
parser.add_argument(
|
| 552 |
+
"--layers",
|
| 553 |
+
default=None,
|
| 554 |
+
help="Optional layer subset, for example '0', '0-4', or '0-4,7,12-15'.",
|
| 555 |
+
)
|
| 556 |
+
parser.add_argument(
|
| 557 |
+
"--do-not-ignore-sentinel",
|
| 558 |
+
action="store_true",
|
| 559 |
+
help="Compare -1 sentinel entries instead of ignoring them.",
|
| 560 |
+
)
|
| 561 |
+
args = parser.parse_args()
|
| 562 |
+
|
| 563 |
+
generated = load_by_sample(Path(args.generated))
|
| 564 |
+
prefill = load_by_sample(Path(args.prefill))
|
| 565 |
+
sample_ids = sorted(set(generated).intersection(prefill))
|
| 566 |
+
if not sample_ids:
|
| 567 |
+
raise SystemExit("No overlapping sample_id values between generated and prefill files.")
|
| 568 |
+
|
| 569 |
+
ignore_value = None if args.do_not_ignore_sentinel else args.ignore_value
|
| 570 |
+
layer_indices = parse_layer_spec(args.layers)
|
| 571 |
+
rows = [
|
| 572 |
+
compare_one(
|
| 573 |
+
generated[sample_id],
|
| 574 |
+
prefill[sample_id],
|
| 575 |
+
ignore_value=ignore_value,
|
| 576 |
+
layer_indices=layer_indices,
|
| 577 |
+
)
|
| 578 |
+
for sample_id in sample_ids
|
| 579 |
+
]
|
| 580 |
+
layer_rows = []
|
| 581 |
+
for sample_id in sample_ids:
|
| 582 |
+
layer_rows.extend(compare_layer_rows(
|
| 583 |
+
generated[sample_id],
|
| 584 |
+
prefill[sample_id],
|
| 585 |
+
ignore_value=ignore_value,
|
| 586 |
+
layer_indices=layer_indices,
|
| 587 |
+
))
|
| 588 |
+
summary = summarize(rows)
|
| 589 |
+
layer_summary_rows = summarize_layer_rows(layer_rows)
|
| 590 |
+
|
| 591 |
+
output_dir = Path(args.output_dir)
|
| 592 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 593 |
+
csv_path = output_dir / "route_diff_by_sample.csv"
|
| 594 |
+
layer_csv_path = output_dir / "route_diff_by_sample_layer.csv"
|
| 595 |
+
layer_summary_csv_path = output_dir / "route_diff_by_layer.csv"
|
| 596 |
+
json_path = output_dir / "route_diff_summary.json"
|
| 597 |
+
md_path = output_dir / "route_diff_summary.md"
|
| 598 |
+
|
| 599 |
+
fieldnames = sorted({key for row in rows for key in row.keys()})
|
| 600 |
+
with csv_path.open("w", encoding="utf-8", newline="") as handle:
|
| 601 |
+
writer = csv.DictWriter(handle, fieldnames=fieldnames)
|
| 602 |
+
writer.writeheader()
|
| 603 |
+
writer.writerows(rows)
|
| 604 |
+
if layer_rows:
|
| 605 |
+
layer_fieldnames = sorted({key for row in layer_rows for key in row.keys()})
|
| 606 |
+
with layer_csv_path.open("w", encoding="utf-8", newline="") as handle:
|
| 607 |
+
writer = csv.DictWriter(handle, fieldnames=layer_fieldnames)
|
| 608 |
+
writer.writeheader()
|
| 609 |
+
writer.writerows(layer_rows)
|
| 610 |
+
if layer_summary_rows:
|
| 611 |
+
layer_summary_fieldnames = sorted({key for row in layer_summary_rows for key in row.keys()})
|
| 612 |
+
with layer_summary_csv_path.open("w", encoding="utf-8", newline="") as handle:
|
| 613 |
+
writer = csv.DictWriter(handle, fieldnames=layer_summary_fieldnames)
|
| 614 |
+
writer.writeheader()
|
| 615 |
+
writer.writerows(layer_summary_rows)
|
| 616 |
+
json_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
|
| 617 |
+
write_summary_md(md_path, summary)
|
| 618 |
+
|
| 619 |
+
print_progress(f"Wrote {csv_path}")
|
| 620 |
+
if layer_rows:
|
| 621 |
+
print_progress(f"Wrote {layer_csv_path}")
|
| 622 |
+
if layer_summary_rows:
|
| 623 |
+
print_progress(f"Wrote {layer_summary_csv_path}")
|
| 624 |
+
print_progress(f"Wrote {json_path}")
|
| 625 |
+
print_progress(f"Wrote {md_path}")
|
| 626 |
+
print(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True))
|
| 627 |
+
return 0
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
if __name__ == "__main__":
|
| 631 |
+
raise SystemExit(main())
|
tools/moe_routed_experts/scripts/generate_decode_routes.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any, Dict, Iterable, Optional
|
| 9 |
+
|
| 10 |
+
from routed_common import (
|
| 11 |
+
api_key_from_args,
|
| 12 |
+
completions_url,
|
| 13 |
+
extract_choice,
|
| 14 |
+
extract_prompt_token_ids,
|
| 15 |
+
extract_token_ids,
|
| 16 |
+
now_ms,
|
| 17 |
+
post_json,
|
| 18 |
+
print_progress,
|
| 19 |
+
prompt_from_row,
|
| 20 |
+
read_jsonl,
|
| 21 |
+
route_field_from_choice,
|
| 22 |
+
route_summary,
|
| 23 |
+
tokenize_prompt,
|
| 24 |
+
write_jsonl_row,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def iter_input_rows(args: argparse.Namespace) -> Iterable[Dict[str, Any]]:
|
| 29 |
+
if args.prompt is not None:
|
| 30 |
+
yield {"sample_id": "prompt_000001", "prompt": args.prompt}
|
| 31 |
+
return
|
| 32 |
+
if args.prompts_file is None:
|
| 33 |
+
raise SystemExit("Pass --prompt or --prompts-file")
|
| 34 |
+
for index, row in enumerate(read_jsonl(Path(args.prompts_file)), start=1):
|
| 35 |
+
if args.limit and index > args.limit:
|
| 36 |
+
break
|
| 37 |
+
yield row
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def load_extra_json(raw: Optional[str]) -> Dict[str, Any]:
|
| 41 |
+
if not raw:
|
| 42 |
+
return {}
|
| 43 |
+
payload = json.loads(raw)
|
| 44 |
+
if not isinstance(payload, dict):
|
| 45 |
+
raise ValueError("--extra-json must decode to a JSON object")
|
| 46 |
+
return payload
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def build_request(args: argparse.Namespace,
|
| 50 |
+
prompt: Any,
|
| 51 |
+
prompt_token_ids: Optional[list[int]]) -> Dict[str, Any]:
|
| 52 |
+
payload: Dict[str, Any] = {
|
| 53 |
+
"model": args.model,
|
| 54 |
+
"prompt": prompt,
|
| 55 |
+
"max_tokens": args.max_tokens,
|
| 56 |
+
"temperature": args.temperature,
|
| 57 |
+
"top_p": args.top_p,
|
| 58 |
+
"stream": False,
|
| 59 |
+
"n": 1,
|
| 60 |
+
"return_token_ids": True,
|
| 61 |
+
}
|
| 62 |
+
if args.top_k is not None:
|
| 63 |
+
payload["top_k"] = args.top_k
|
| 64 |
+
if args.seed is not None:
|
| 65 |
+
payload["seed"] = args.seed
|
| 66 |
+
if args.logprobs is not None:
|
| 67 |
+
payload["logprobs"] = args.logprobs
|
| 68 |
+
if args.routed_experts_prompt_start is not None:
|
| 69 |
+
payload["routed_experts_prompt_start"] = args.routed_experts_prompt_start
|
| 70 |
+
payload.update(load_extra_json(args.extra_json))
|
| 71 |
+
return payload
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def main() -> int:
|
| 75 |
+
parser = argparse.ArgumentParser(
|
| 76 |
+
description="Run normal vLLM generation and save output token ids plus routed_experts."
|
| 77 |
+
)
|
| 78 |
+
parser.add_argument("--base-url", default="http://localhost:8000")
|
| 79 |
+
parser.add_argument("--api-key", default=None)
|
| 80 |
+
parser.add_argument("--model", required=True)
|
| 81 |
+
parser.add_argument("--prompt", default=None)
|
| 82 |
+
parser.add_argument("--prompts-file", default=None)
|
| 83 |
+
parser.add_argument("--output", default="data/generated_routes.jsonl")
|
| 84 |
+
parser.add_argument("--max-tokens", type=int, default=128)
|
| 85 |
+
parser.add_argument("--temperature", type=float, default=0.0)
|
| 86 |
+
parser.add_argument("--top-p", type=float, default=1.0)
|
| 87 |
+
parser.add_argument("--top-k", type=int, default=None)
|
| 88 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 89 |
+
parser.add_argument("--logprobs", type=int, default=None)
|
| 90 |
+
parser.add_argument("--extra-json", default=None, help="Extra JSON object merged into the request.")
|
| 91 |
+
parser.add_argument("--timeout", type=float, default=600.0)
|
| 92 |
+
parser.add_argument(
|
| 93 |
+
"--limit",
|
| 94 |
+
type=int,
|
| 95 |
+
default=0,
|
| 96 |
+
help="Only run the first N prompts from --prompts-file. 0 means all prompts.",
|
| 97 |
+
)
|
| 98 |
+
parser.add_argument(
|
| 99 |
+
"--routed-experts-prompt-start",
|
| 100 |
+
type=int,
|
| 101 |
+
default=None,
|
| 102 |
+
help=(
|
| 103 |
+
"Advanced: pass routed_experts_prompt_start to vLLM. "
|
| 104 |
+
"By default the generation request omits it to avoid vLLM versions "
|
| 105 |
+
"that assert when the value reaches the prompt length."
|
| 106 |
+
),
|
| 107 |
+
)
|
| 108 |
+
args = parser.parse_args()
|
| 109 |
+
|
| 110 |
+
api_key = api_key_from_args(args.api_key)
|
| 111 |
+
output_path = Path(args.output)
|
| 112 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 113 |
+
count = 0
|
| 114 |
+
|
| 115 |
+
with output_path.open("w", encoding="utf-8") as handle:
|
| 116 |
+
for row_index, row in enumerate(iter_input_rows(args), start=1):
|
| 117 |
+
sample_id, prompt, prompt_token_ids = prompt_from_row(row, row_index)
|
| 118 |
+
if prompt_token_ids is None:
|
| 119 |
+
prompt_token_ids = tokenize_prompt(
|
| 120 |
+
args.base_url,
|
| 121 |
+
args.model,
|
| 122 |
+
prompt,
|
| 123 |
+
api_key=api_key,
|
| 124 |
+
timeout=args.timeout,
|
| 125 |
+
)
|
| 126 |
+
request_payload = build_request(args, prompt, prompt_token_ids)
|
| 127 |
+
start_ms = now_ms()
|
| 128 |
+
response = post_json(
|
| 129 |
+
completions_url(args.base_url),
|
| 130 |
+
request_payload,
|
| 131 |
+
api_key=api_key,
|
| 132 |
+
timeout=args.timeout,
|
| 133 |
+
)
|
| 134 |
+
elapsed_ms = now_ms() - start_ms
|
| 135 |
+
choice = extract_choice(response)
|
| 136 |
+
output_token_ids = extract_token_ids(choice)
|
| 137 |
+
if output_token_ids is None:
|
| 138 |
+
raise RuntimeError(
|
| 139 |
+
"Could not find generated token ids in the response. "
|
| 140 |
+
"Check that your vLLM version supports return_token_ids."
|
| 141 |
+
)
|
| 142 |
+
response_prompt_ids = extract_prompt_token_ids(response, choice)
|
| 143 |
+
routed_experts = route_field_from_choice(choice)
|
| 144 |
+
if routed_experts is None:
|
| 145 |
+
raise RuntimeError(
|
| 146 |
+
"Response did not contain routed_experts. "
|
| 147 |
+
"Start vLLM with --enable-return-routed-experts."
|
| 148 |
+
)
|
| 149 |
+
record = {
|
| 150 |
+
"sample_id": sample_id,
|
| 151 |
+
"input_text": prompt if isinstance(prompt, str) else row.get("input_text"),
|
| 152 |
+
"input_token_ids": response_prompt_ids or prompt_token_ids,
|
| 153 |
+
"output_text": choice.get("text", ""),
|
| 154 |
+
"output_token_ids": output_token_ids,
|
| 155 |
+
"category": row.get("category", ""),
|
| 156 |
+
"target_input_tokens": row.get("target_input_tokens"),
|
| 157 |
+
"anchor_variant": row.get("anchor_variant", ""),
|
| 158 |
+
"source_prompt_metadata": row.get("metadata", {}),
|
| 159 |
+
"source_prompt_decode_config": row.get("decode_config"),
|
| 160 |
+
"source_prompt_tokenizations": row.get("tokenizations", {}),
|
| 161 |
+
"routed_experts": routed_experts,
|
| 162 |
+
"routed_experts_summary": route_summary(routed_experts),
|
| 163 |
+
"route_scope": (
|
| 164 |
+
"custom_prompt_start_requested"
|
| 165 |
+
if "routed_experts_prompt_start" in request_payload
|
| 166 |
+
else "default_full_route_window"
|
| 167 |
+
),
|
| 168 |
+
"route_prompt_start": request_payload.get("routed_experts_prompt_start", 0),
|
| 169 |
+
"route_alignment_note": (
|
| 170 |
+
"Custom routed_experts_prompt_start was passed through to vLLM."
|
| 171 |
+
if "routed_experts_prompt_start" in request_payload
|
| 172 |
+
else "Generation omits routed_experts_prompt_start; vLLM default start is 0."
|
| 173 |
+
),
|
| 174 |
+
"request": {
|
| 175 |
+
"base_url": args.base_url,
|
| 176 |
+
"model": args.model,
|
| 177 |
+
"max_tokens": args.max_tokens,
|
| 178 |
+
"temperature": args.temperature,
|
| 179 |
+
"top_p": args.top_p,
|
| 180 |
+
"top_k": args.top_k,
|
| 181 |
+
"seed": args.seed,
|
| 182 |
+
"logprobs": args.logprobs,
|
| 183 |
+
"routed_experts_prompt_start": request_payload.get("routed_experts_prompt_start"),
|
| 184 |
+
"extra_json": load_extra_json(args.extra_json),
|
| 185 |
+
},
|
| 186 |
+
"usage": response.get("usage"),
|
| 187 |
+
"response_id": response.get("id"),
|
| 188 |
+
"created": response.get("created"),
|
| 189 |
+
"elapsed_ms": elapsed_ms,
|
| 190 |
+
}
|
| 191 |
+
write_jsonl_row(handle, record)
|
| 192 |
+
count += 1
|
| 193 |
+
print_progress(
|
| 194 |
+
f"[generate] {sample_id}: input_tokens={len(record['input_token_ids'])} "
|
| 195 |
+
f"output_tokens={len(output_token_ids)} "
|
| 196 |
+
f"route_shape={record['routed_experts_summary'].get('shape')}"
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
print_progress(f"Wrote {count} rows to {output_path}")
|
| 200 |
+
return 0
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
if __name__ == "__main__":
|
| 204 |
+
raise SystemExit(main())
|
tools/moe_routed_experts/scripts/prefill_routes.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Dict, Optional
|
| 8 |
+
|
| 9 |
+
from routed_common import (
|
| 10 |
+
api_key_from_args,
|
| 11 |
+
completions_url,
|
| 12 |
+
extract_choice,
|
| 13 |
+
now_ms,
|
| 14 |
+
post_json,
|
| 15 |
+
print_progress,
|
| 16 |
+
read_jsonl,
|
| 17 |
+
route_field_from_choice,
|
| 18 |
+
route_summary,
|
| 19 |
+
write_jsonl_row,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def load_extra_json(raw: Optional[str]) -> Dict[str, Any]:
|
| 24 |
+
if not raw:
|
| 25 |
+
return {}
|
| 26 |
+
payload = json.loads(raw)
|
| 27 |
+
if not isinstance(payload, dict):
|
| 28 |
+
raise ValueError("--extra-json must decode to a JSON object")
|
| 29 |
+
return payload
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def model_for_row(args: argparse.Namespace, row: Dict[str, Any]) -> str:
|
| 33 |
+
if args.model:
|
| 34 |
+
return args.model
|
| 35 |
+
request = row.get("request") or {}
|
| 36 |
+
model = request.get("model")
|
| 37 |
+
if not model:
|
| 38 |
+
raise RuntimeError(
|
| 39 |
+
f"Row {row.get('sample_id')} has no request.model; pass --model explicitly."
|
| 40 |
+
)
|
| 41 |
+
return str(model)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def build_prefill_request(args: argparse.Namespace,
|
| 45 |
+
model: str,
|
| 46 |
+
input_ids: list[int],
|
| 47 |
+
output_ids: list[int]) -> Dict[str, Any]:
|
| 48 |
+
route_prompt_start = len(input_ids) if output_ids else max(0, len(input_ids) - 1)
|
| 49 |
+
payload: Dict[str, Any] = {
|
| 50 |
+
"model": model,
|
| 51 |
+
"prompt": input_ids + output_ids,
|
| 52 |
+
"max_tokens": 0,
|
| 53 |
+
"echo": True,
|
| 54 |
+
"temperature": 0.0,
|
| 55 |
+
"stream": False,
|
| 56 |
+
"n": 1,
|
| 57 |
+
"return_token_ids": True,
|
| 58 |
+
"routed_experts_prompt_start": route_prompt_start,
|
| 59 |
+
}
|
| 60 |
+
if args.logprobs is not None:
|
| 61 |
+
payload["logprobs"] = args.logprobs
|
| 62 |
+
if args.prompt_logprobs is not None:
|
| 63 |
+
payload["prompt_logprobs"] = args.prompt_logprobs
|
| 64 |
+
payload.update(load_extra_json(args.extra_json))
|
| 65 |
+
return payload
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def main() -> int:
|
| 69 |
+
parser = argparse.ArgumentParser(
|
| 70 |
+
description="Replay generated output as prompt/prefill and save routed_experts."
|
| 71 |
+
)
|
| 72 |
+
parser.add_argument("--base-url", default="http://localhost:8000")
|
| 73 |
+
parser.add_argument("--api-key", default=None)
|
| 74 |
+
parser.add_argument("--model", default=None, help="Verifier model. Defaults to each row's request.model.")
|
| 75 |
+
parser.add_argument("--input", default="data/generated_routes.jsonl")
|
| 76 |
+
parser.add_argument("--output", default="data/prefill_routes.jsonl")
|
| 77 |
+
parser.add_argument("--logprobs", type=int, default=None)
|
| 78 |
+
parser.add_argument("--prompt-logprobs", type=int, default=None)
|
| 79 |
+
parser.add_argument("--extra-json", default=None, help="Extra JSON object merged into the request.")
|
| 80 |
+
parser.add_argument("--timeout", type=float, default=600.0)
|
| 81 |
+
args = parser.parse_args()
|
| 82 |
+
|
| 83 |
+
api_key = api_key_from_args(args.api_key)
|
| 84 |
+
output_path = Path(args.output)
|
| 85 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 86 |
+
rows = list(read_jsonl(Path(args.input)))
|
| 87 |
+
count = 0
|
| 88 |
+
|
| 89 |
+
with output_path.open("w", encoding="utf-8") as handle:
|
| 90 |
+
for row in rows:
|
| 91 |
+
sample_id = str(row.get("sample_id"))
|
| 92 |
+
input_ids = [int(token_id) for token_id in row["input_token_ids"]]
|
| 93 |
+
output_ids = [int(token_id) for token_id in row["output_token_ids"]]
|
| 94 |
+
model = model_for_row(args, row)
|
| 95 |
+
request_payload = build_prefill_request(args, model, input_ids, output_ids)
|
| 96 |
+
start_ms = now_ms()
|
| 97 |
+
response = post_json(
|
| 98 |
+
completions_url(args.base_url),
|
| 99 |
+
request_payload,
|
| 100 |
+
api_key=api_key,
|
| 101 |
+
timeout=args.timeout,
|
| 102 |
+
)
|
| 103 |
+
elapsed_ms = now_ms() - start_ms
|
| 104 |
+
choice = extract_choice(response)
|
| 105 |
+
routed_experts = route_field_from_choice(choice)
|
| 106 |
+
if routed_experts is None:
|
| 107 |
+
raise RuntimeError(
|
| 108 |
+
"Prefill response did not contain routed_experts. "
|
| 109 |
+
"Start vLLM with --enable-return-routed-experts."
|
| 110 |
+
)
|
| 111 |
+
record = {
|
| 112 |
+
"sample_id": sample_id,
|
| 113 |
+
"source_model": (row.get("request") or {}).get("model"),
|
| 114 |
+
"verifier_model": model,
|
| 115 |
+
"category": row.get("category", ""),
|
| 116 |
+
"target_input_tokens": row.get("target_input_tokens"),
|
| 117 |
+
"anchor_variant": row.get("anchor_variant", ""),
|
| 118 |
+
"source_prompt_metadata": row.get("source_prompt_metadata", {}),
|
| 119 |
+
"input_token_ids": input_ids,
|
| 120 |
+
"output_token_ids": output_ids,
|
| 121 |
+
"prefill_prompt_token_ids": input_ids + output_ids,
|
| 122 |
+
"routed_experts": routed_experts,
|
| 123 |
+
"routed_experts_summary": route_summary(routed_experts),
|
| 124 |
+
"route_scope": "output_prompt_suffix_requested",
|
| 125 |
+
"route_prompt_start": request_payload.get("routed_experts_prompt_start", 0),
|
| 126 |
+
"route_alignment_note": (
|
| 127 |
+
"Uses input_len because prefill prompt is input_ids + output_ids; "
|
| 128 |
+
"therefore input_len is inside the full prompt when output_ids is non-empty."
|
| 129 |
+
),
|
| 130 |
+
"request": {
|
| 131 |
+
"base_url": args.base_url,
|
| 132 |
+
"model": model,
|
| 133 |
+
"max_tokens": 0,
|
| 134 |
+
"echo": True,
|
| 135 |
+
"temperature": 0.0,
|
| 136 |
+
"routed_experts_prompt_start": request_payload.get("routed_experts_prompt_start"),
|
| 137 |
+
"logprobs": args.logprobs,
|
| 138 |
+
"prompt_logprobs": args.prompt_logprobs,
|
| 139 |
+
"extra_json": load_extra_json(args.extra_json),
|
| 140 |
+
},
|
| 141 |
+
"usage": response.get("usage"),
|
| 142 |
+
"response_id": response.get("id"),
|
| 143 |
+
"created": response.get("created"),
|
| 144 |
+
"elapsed_ms": elapsed_ms,
|
| 145 |
+
}
|
| 146 |
+
write_jsonl_row(handle, record)
|
| 147 |
+
count += 1
|
| 148 |
+
print_progress(
|
| 149 |
+
f"[prefill] {sample_id}: input_tokens={len(input_ids)} "
|
| 150 |
+
f"output_tokens={len(output_ids)} "
|
| 151 |
+
f"route_shape={record['routed_experts_summary'].get('shape')}"
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
print_progress(f"Wrote {count} rows to {output_path}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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import base64
|
| 5 |
+
import io
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
import urllib.error
|
| 11 |
+
import urllib.request
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
import numpy as np
|
| 17 |
+
except ModuleNotFoundError:
|
| 18 |
+
np = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def now_ms() -> int:
|
| 22 |
+
return int(time.time() * 1000)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def normalize_base_url(base_url: str) -> str:
|
| 26 |
+
base = base_url.rstrip("/")
|
| 27 |
+
if base.endswith("/v1"):
|
| 28 |
+
base = base[:-3]
|
| 29 |
+
return base
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def completions_url(base_url: str) -> str:
|
| 33 |
+
return f"{normalize_base_url(base_url)}/v1/completions"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def tokenize_url(base_url: str) -> str:
|
| 37 |
+
return f"{normalize_base_url(base_url)}/tokenize"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def api_key_from_args(api_key: Optional[str]) -> Optional[str]:
|
| 41 |
+
return api_key or os.environ.get("VLLM_API_KEY") or os.environ.get("OPENAI_API_KEY")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def post_json(url: str,
|
| 45 |
+
payload: Dict[str, Any],
|
| 46 |
+
*,
|
| 47 |
+
api_key: Optional[str] = None,
|
| 48 |
+
timeout: float = 600.0) -> Dict[str, Any]:
|
| 49 |
+
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
| 50 |
+
headers = {"Content-Type": "application/json"}
|
| 51 |
+
if api_key:
|
| 52 |
+
headers["Authorization"] = f"Bearer {api_key}"
|
| 53 |
+
request = urllib.request.Request(url, data=data, headers=headers, method="POST")
|
| 54 |
+
try:
|
| 55 |
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
| 56 |
+
body = response.read().decode("utf-8")
|
| 57 |
+
except urllib.error.HTTPError as exc:
|
| 58 |
+
body = exc.read().decode("utf-8", errors="replace")
|
| 59 |
+
raise RuntimeError(f"HTTP {exc.code} from {url}: {body}") from exc
|
| 60 |
+
except urllib.error.URLError as exc:
|
| 61 |
+
raise RuntimeError(f"Could not reach {url}: {exc}") from exc
|
| 62 |
+
return json.loads(body)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def read_jsonl(path: Path) -> Iterable[Dict[str, Any]]:
|
| 66 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 67 |
+
for line_number, line in enumerate(handle, start=1):
|
| 68 |
+
line = line.strip()
|
| 69 |
+
if not line or line.startswith("#"):
|
| 70 |
+
continue
|
| 71 |
+
try:
|
| 72 |
+
payload = json.loads(line)
|
| 73 |
+
except json.JSONDecodeError as exc:
|
| 74 |
+
raise ValueError(f"{path}:{line_number}: invalid JSONL row") from exc
|
| 75 |
+
if isinstance(payload, str):
|
| 76 |
+
yield {"sample_id": f"row_{line_number:06d}", "prompt": payload}
|
| 77 |
+
elif isinstance(payload, dict):
|
| 78 |
+
yield payload
|
| 79 |
+
else:
|
| 80 |
+
raise ValueError(f"{path}:{line_number}: row must be a JSON object or string")
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def write_jsonl_row(handle: Any, payload: Dict[str, Any]) -> None:
|
| 84 |
+
handle.write(json.dumps(payload, ensure_ascii=False, sort_keys=True))
|
| 85 |
+
handle.write("\n")
|
| 86 |
+
handle.flush()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def prompt_from_row(row: Dict[str, Any], row_index: int) -> Tuple[str, Any, Optional[List[int]]]:
|
| 90 |
+
sample_id = str(row.get("sample_id") or row.get("id") or f"sample_{row_index:06d}")
|
| 91 |
+
token_ids = row.get("prompt_token_ids") or row.get("input_token_ids") or row.get("input_ids")
|
| 92 |
+
if token_ids is not None:
|
| 93 |
+
return sample_id, [int(token_id) for token_id in token_ids], [int(token_id) for token_id in token_ids]
|
| 94 |
+
for key in ("prompt", "input", "input_text", "text"):
|
| 95 |
+
if key in row:
|
| 96 |
+
return sample_id, str(row[key]), None
|
| 97 |
+
raise ValueError(f"Row {sample_id} has no prompt/input/input_text/text or token ids")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def extract_choice(response: Dict[str, Any]) -> Dict[str, Any]:
|
| 101 |
+
choices = response.get("choices") or []
|
| 102 |
+
if not choices:
|
| 103 |
+
raise RuntimeError(f"Response has no choices: {response}")
|
| 104 |
+
return choices[0]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def first_int_list(value: Any) -> Optional[List[int]]:
|
| 108 |
+
if isinstance(value, list) and all(isinstance(item, int) for item in value):
|
| 109 |
+
return [int(item) for item in value]
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def extract_token_ids(payload: Dict[str, Any]) -> Optional[List[int]]:
|
| 114 |
+
for key in (
|
| 115 |
+
"token_ids",
|
| 116 |
+
"prompt_token_ids",
|
| 117 |
+
"output_token_ids",
|
| 118 |
+
"input_ids",
|
| 119 |
+
"tokens",
|
| 120 |
+
):
|
| 121 |
+
token_ids = first_int_list(payload.get(key))
|
| 122 |
+
if token_ids is not None:
|
| 123 |
+
return token_ids
|
| 124 |
+
logprobs = payload.get("logprobs")
|
| 125 |
+
if isinstance(logprobs, dict):
|
| 126 |
+
token_ids = first_int_list(logprobs.get("token_ids"))
|
| 127 |
+
if token_ids is not None:
|
| 128 |
+
return token_ids
|
| 129 |
+
return None
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def extract_prompt_token_ids(response: Dict[str, Any], choice: Dict[str, Any]) -> Optional[List[int]]:
|
| 133 |
+
for source in (choice, response):
|
| 134 |
+
token_ids = source.get("prompt_token_ids")
|
| 135 |
+
if first_int_list(token_ids) is not None:
|
| 136 |
+
return [int(token_id) for token_id in token_ids]
|
| 137 |
+
return None
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def tokenize_prompt(base_url: str,
|
| 141 |
+
model: str,
|
| 142 |
+
prompt: Any,
|
| 143 |
+
*,
|
| 144 |
+
api_key: Optional[str],
|
| 145 |
+
timeout: float) -> List[int]:
|
| 146 |
+
if isinstance(prompt, list):
|
| 147 |
+
return [int(token_id) for token_id in prompt]
|
| 148 |
+
response = post_json(
|
| 149 |
+
tokenize_url(base_url),
|
| 150 |
+
{"model": model, "prompt": prompt},
|
| 151 |
+
api_key=api_key,
|
| 152 |
+
timeout=timeout,
|
| 153 |
+
)
|
| 154 |
+
token_ids = extract_token_ids(response)
|
| 155 |
+
if token_ids is None:
|
| 156 |
+
raise RuntimeError(f"Could not find token ids in /tokenize response: {response}")
|
| 157 |
+
return token_ids
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def route_field_from_choice(choice: Dict[str, Any]) -> Any:
|
| 161 |
+
for key in ("routed_experts", "prompt_routed_experts"):
|
| 162 |
+
if key in choice and choice[key] is not None:
|
| 163 |
+
return choice[key]
|
| 164 |
+
return None
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def decode_routed_experts(value: Any) -> Optional[np.ndarray]:
|
| 168 |
+
np_module = require_numpy()
|
| 169 |
+
if value is None:
|
| 170 |
+
return None
|
| 171 |
+
if isinstance(value, str):
|
| 172 |
+
raw = base64.b64decode(value)
|
| 173 |
+
return np_module.load(io.BytesIO(raw), allow_pickle=False)
|
| 174 |
+
if isinstance(value, list):
|
| 175 |
+
return np_module.asarray(value)
|
| 176 |
+
if isinstance(value, dict):
|
| 177 |
+
for key in ("data", "array", "routed_experts", "prompt_routed_experts"):
|
| 178 |
+
if key in value:
|
| 179 |
+
return decode_routed_experts(value[key])
|
| 180 |
+
raise TypeError(f"Unsupported routed_experts payload type: {type(value).__name__}")
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def route_summary(value: Any) -> Dict[str, Any]:
|
| 184 |
+
if value is None:
|
| 185 |
+
return {"present": False}
|
| 186 |
+
try:
|
| 187 |
+
arr = decode_routed_experts(value)
|
| 188 |
+
except RuntimeError as exc:
|
| 189 |
+
return {"present": True, "decoded": False, "error": str(exc)}
|
| 190 |
+
if arr is None:
|
| 191 |
+
return {"present": False}
|
| 192 |
+
return {
|
| 193 |
+
"present": True,
|
| 194 |
+
"shape": [int(dim) for dim in arr.shape],
|
| 195 |
+
"dtype": str(arr.dtype),
|
| 196 |
+
"num_entries": int(arr.size),
|
| 197 |
+
"min": int(arr.min()) if arr.size else None,
|
| 198 |
+
"max": int(arr.max()) if arr.size else None,
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def normalize_route_array(arr: np.ndarray) -> np.ndarray:
|
| 203 |
+
np_module = require_numpy()
|
| 204 |
+
arr = np_module.asarray(arr)
|
| 205 |
+
if arr.ndim == 1:
|
| 206 |
+
arr = arr.reshape((arr.shape[0], 1, 1))
|
| 207 |
+
elif arr.ndim == 2:
|
| 208 |
+
arr = arr.reshape((arr.shape[0], arr.shape[1], 1))
|
| 209 |
+
elif arr.ndim != 3:
|
| 210 |
+
raise ValueError(f"Expected routed_experts rank 1/2/3, got shape {arr.shape}")
|
| 211 |
+
return arr.astype(np_module.int64, copy=False)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def require_numpy() -> Any:
|
| 215 |
+
if np is None:
|
| 216 |
+
raise RuntimeError(
|
| 217 |
+
"numpy is required to decode and compare routed_experts. "
|
| 218 |
+
"Install it with: python3 -m pip install -r requirements.txt"
|
| 219 |
+
)
|
| 220 |
+
return np
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def print_progress(message: str) -> None:
|
| 224 |
+
print(message, file=sys.stderr, flush=True)
|
tools/vllm_worker_verify_pipeline/README.md
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# vLLM Worker Verify Pipeline
|
| 2 |
+
|
| 3 |
+
This folder holds the standalone pipeline scripts. The main script chains together the local implementations in the same directory:
|
| 4 |
+
|
| 5 |
+
1. `generate_prompts.py`
|
| 6 |
+
2. `collect_vllm_worker_evidence.py`
|
| 7 |
+
3. `verify_vllm_worker_evidence.py`
|
| 8 |
+
4. `summarize_worker_verify.py`
|
| 9 |
+
|
| 10 |
+
When running the vLLM stages, the current Python environment still needs `transformers`, `vllm`, and the GPU runtime required by the model.
|
| 11 |
+
|
| 12 |
+
```bash
|
| 13 |
+
python3 -m pip install transformers vllm
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
Then run:
|
| 17 |
+
|
| 18 |
+
```bash
|
| 19 |
+
./run_vllm_worker_verify.py \
|
| 20 |
+
--baseline-model /models/Qwen3-32B \
|
| 21 |
+
--comparison-model /models/Qwen3-32B-FP8 \
|
| 22 |
+
--baseline-variant-id qwen3-32b-bf16-worker \
|
| 23 |
+
--comparison-variant-id qwen3-32b-fp8-verifier \
|
| 24 |
+
--baseline-dtype bfloat16 \
|
| 25 |
+
--comparison-quantization fp8 \
|
| 26 |
+
--comparison-dtype auto \
|
| 27 |
+
--trust-remote-code
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
Common options:
|
| 31 |
+
|
| 32 |
+
- `--dry-run`: only print the commands, don't write any output.
|
| 33 |
+
- `--prompts path/to/prompts.jsonl`: reuse existing prompts and skip prompt generation.
|
| 34 |
+
- `--resume`: reuse existing stage artifacts.
|
| 35 |
+
- `--force`: overwrite existing stage artifacts.
|
| 36 |
+
- `--python /path/to/python`: specify the Python interpreter used by the local sub-scripts.
|
| 37 |
+
|
| 38 |
+
By default, output goes under the current directory:
|
| 39 |
+
|
| 40 |
+
```text
|
| 41 |
+
results/vllm_worker_verify_runs/<run-id>/
|
| 42 |
+
data/prompts.jsonl
|
| 43 |
+
data/worker_evidence.<baseline>.jsonl
|
| 44 |
+
worker_verify/<baseline>_worker_vs_<comparison>_verifier/
|
| 45 |
+
worker_vs_verifier_depth_metrics.csv
|
| 46 |
+
summary.md
|
| 47 |
+
distribution/summary.md
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
## Parameter Calibration and Statistical Analysis
|
| 51 |
+
|
| 52 |
+
The recommended workflow has three steps:
|
| 53 |
+
|
| 54 |
+
1. `run_vllm_worker_verify.py` generates the base / challenger experiment data.
|
| 55 |
+
2. `calibrate_vllm_worker_verify_params.py` automatically derives recommended parameters from the experiment data.
|
| 56 |
+
3. `analyze_vllm_worker_verify.py` uses the parameters from step 2 to verify whether the base model can be distinguished from other models.
|
| 57 |
+
|
| 58 |
+
### 2. Automatic Parameter Calibration
|
| 59 |
+
|
| 60 |
+
Based on the `worker_vs_verifier_depth_metrics.csv` of the base model and challenger models, automatically derive the PASS / REJECT boundaries for each metric:
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
./calibrate_vllm_worker_verify_params.py \
|
| 64 |
+
--input results/vllm_worker_verify_runs \
|
| 65 |
+
--base-model Qwen/Qwen3-32B \
|
| 66 |
+
--output-dir calibration
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
Output files:
|
| 70 |
+
|
| 71 |
+
```text
|
| 72 |
+
calibration/
|
| 73 |
+
recommended_thresholds.json # recommended parameters, can be fed directly to analyze
|
| 74 |
+
metric_calibration.csv # per-metric base/other distribution, recommended boundaries, separation
|
| 75 |
+
group_verdicts.csv # model-level verdict stats after replaying with the recommended parameters
|
| 76 |
+
sample_verdicts.csv # sample-level verdicts after replaying with the recommended parameters
|
| 77 |
+
summary.md # quick report
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
Common calibration strategy options:
|
| 81 |
+
|
| 82 |
+
```bash
|
| 83 |
+
--target-base-pass-rate 0.99 # how many base samples the PASS boundary should cover
|
| 84 |
+
--max-base-false-reject-rate 0.01 # how many base false rejects the REJECT boundary allows
|
| 85 |
+
--pass-safety-multiplier 1.10 # PASS safety margin for upper-bound metrics
|
| 86 |
+
--lower-margin 0.02 # PASS safety margin for lower-bound metrics such as jaccard
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
### 3. Using the Parameters for Statistics / Validation
|
| 90 |
+
|
| 91 |
+
Based on the `recommended_thresholds.json` from step 2, generate the protocol-aligned statistics table:
|
| 92 |
+
|
| 93 |
+
```bash
|
| 94 |
+
./analyze_vllm_worker_verify.py \
|
| 95 |
+
--input results/vllm_worker_verify_runs \
|
| 96 |
+
--base-model Qwen/Qwen3-32B \
|
| 97 |
+
--thresholds calibration/recommended_thresholds.json \
|
| 98 |
+
--output-dir analysis
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
Output files:
|
| 102 |
+
|
| 103 |
+
```text
|
| 104 |
+
analysis/
|
| 105 |
+
run_summary.csv # overall metrics for each run/model
|
| 106 |
+
model_summary.csv # aggregated by verifier model
|
| 107 |
+
sample_summary.csv # per-sample metric summary + PASS/REJECT/INCONCLUSIVE
|
| 108 |
+
by_input_bucket.csv # aggregated by input token bucket
|
| 109 |
+
by_output_depth_bucket.csv # aggregated by generated token depth bucket
|
| 110 |
+
top_outlier_tokens.csv # token-level detail with the largest abs_logprob_diff
|
| 111 |
+
thresholds.json # local analysis thresholds used or derived from base
|
| 112 |
+
summary.md # report for quick reading
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
The statistics script follows `PREFILL_GENERATED_TOKEN_METRICS_V1`, covering the following over all generated output tokens:
|
| 116 |
+
|
| 117 |
+
- `mean_abs_logprob_diff`
|
| 118 |
+
- `abs_logprob_diff_p95 / p99`
|
| 119 |
+
- `rank_delta_nonzero_rate`
|
| 120 |
+
- `topk_jaccard_mean`
|
| 121 |
+
- `union_js_p99`
|
| 122 |
+
- `missing_compared_count`
|
| 123 |
+
|
| 124 |
+
Note: the calibration script outputs recommended parameters derived from experiment data, suitable for the initial profile values and backtesting; the final protocol thresholds should still go into `ProfileState.verification_thresholds` and be confirmed through review / governance.
|
| 125 |
+
|
| 126 |
+
## Worker vs Verifier Time-Cost Benchmark
|
| 127 |
+
|
| 128 |
+
`benchmark_worker_verifier_latency.py` is used to measure and compare the time cost of the two paths in isolation, sweeping the impact of different input / output lengths:
|
| 129 |
+
|
| 130 |
+
- **worker**: normal generation, `prefill(input) + decode(output_len)`, `SamplingParams(max_tokens=output_len, logprobs=K)`.
|
| 131 |
+
- **verifier**: based on the worker's `input_ids + output_ids`, does one prefill to obtain top-k logprobs, `SamplingParams(max_tokens=1, prompt_logprobs=K)`.
|
| 132 |
+
|
| 133 |
+
The two paths **share the same offline `vllm.LLM` instance** (same model, same GPU state, for a fair comparison); the verifier uses the `output_ids` actually generated by the worker. The output length is strictly fixed via `ignore_eos=True` + `min_tokens=max_tokens`, keeping the sweep axis clean. Each grid cell first runs `--warmup` times (not timed) and then `--repeats` times, reporting median / mean / p10 / p90; it also splits out TTFT (≈prefill) and decode from `request_output.metrics`.
|
| 134 |
+
|
| 135 |
+
```bash
|
| 136 |
+
./benchmark_worker_verifier_latency.py \
|
| 137 |
+
--model /models/Qwen3-8B \
|
| 138 |
+
--dtype bfloat16 --trust-remote-code \
|
| 139 |
+
--input-lengths "128 512 1024 2048 4096" \
|
| 140 |
+
--output-lengths "1 16 64 256 1024" \
|
| 141 |
+
--top-k 20 --warmup 2 --repeats 5 \
|
| 142 |
+
--gpu "L4" \
|
| 143 |
+
--output-dir results/worker_verifier_latency/qwen3_8b
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
Common options:
|
| 147 |
+
|
| 148 |
+
- `--input-lengths` / `--output-lengths`: comma- or space-separated sweep grid.
|
| 149 |
+
- `--top-k`: depth of the worker's `logprobs` and the verifier's `prompt_logprobs` (`--max-logprobs` defaults to this value).
|
| 150 |
+
- `--warmup` / `--repeats`: number of warmup and timed iterations.
|
| 151 |
+
- `--skip-verifier` / `--skip-worker`: measure only one of the two paths.
|
| 152 |
+
- `--max-total-tokens`: skip cells where input+output exceeds this value (0 disables).
|
| 153 |
+
|
| 154 |
+
Output (under `--output-dir`):
|
| 155 |
+
|
| 156 |
+
```text
|
| 157 |
+
results/worker_verifier_latency/<name>/
|
| 158 |
+
latency_summary.csv # per-cell median/mean/p10/p90, TTFT, decode, tok/s, worker/verifier ratio
|
| 159 |
+
latency_raw.jsonl # raw data for each timed iteration
|
| 160 |
+
summary.md # Markdown table
|
| 161 |
+
metadata.json # parameters, vLLM version, environment
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
How to read the results: rows with `output_len=1` reflect the growth of pure prefill as input length increases (worker≈verifier); with input fixed and output increasing, the worker's decode grows linearly while the verifier only adds one extra prefill, so `worker_over_verifier_median` widens as output length grows.
|
tools/vllm_worker_verify_pipeline/analyze_vllm_worker_verify.py
ADDED
|
@@ -0,0 +1,1047 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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8 |
+
import platform
|
| 9 |
+
import sys
|
| 10 |
+
import time
|
| 11 |
+
from collections import defaultdict
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
METRICS_FILENAME = "worker_vs_verifier_depth_metrics.csv"
|
| 17 |
+
JUDGMENT_FUNCTION_VERSION = "PREFILL_GENERATED_TOKEN_METRICS_V1"
|
| 18 |
+
FP_SCALE = 1_000_000
|
| 19 |
+
|
| 20 |
+
UPPER_BOUND_METRICS = [
|
| 21 |
+
"missing_compared_count",
|
| 22 |
+
"mean_abs_logprob_diff",
|
| 23 |
+
"abs_logprob_diff_p95",
|
| 24 |
+
"abs_logprob_diff_p99",
|
| 25 |
+
"rank_delta_nonzero_rate",
|
| 26 |
+
"union_js_p99",
|
| 27 |
+
]
|
| 28 |
+
LOWER_BOUND_METRICS = [
|
| 29 |
+
"topk_jaccard_mean",
|
| 30 |
+
]
|
| 31 |
+
SAMPLE_THRESHOLD_METRICS = UPPER_BOUND_METRICS + LOWER_BOUND_METRICS
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def log(message: str) -> None:
|
| 35 |
+
print(message, flush=True)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def runtime_metadata(argv: Sequence[str]) -> Dict[str, Any]:
|
| 39 |
+
return {
|
| 40 |
+
"created_at_unix": time.time(),
|
| 41 |
+
"python": sys.version,
|
| 42 |
+
"platform": platform.platform(),
|
| 43 |
+
"argv": list(argv),
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def read_json(path: Path) -> Optional[Dict[str, Any]]:
|
| 48 |
+
try:
|
| 49 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 50 |
+
payload = json.load(handle)
|
| 51 |
+
return payload if isinstance(payload, dict) else None
|
| 52 |
+
except (OSError, json.JSONDecodeError):
|
| 53 |
+
return None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def write_json(path: Path, payload: Dict[str, Any]) -> None:
|
| 57 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 58 |
+
with path.open("w", encoding="utf-8") as handle:
|
| 59 |
+
json.dump(payload, handle, ensure_ascii=False, indent=2, sort_keys=True)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def safe_float(value: Any, default: float = float("nan")) -> float:
|
| 63 |
+
if value in {"", None}:
|
| 64 |
+
return default
|
| 65 |
+
try:
|
| 66 |
+
return float(value)
|
| 67 |
+
except (TypeError, ValueError):
|
| 68 |
+
return default
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def safe_int(value: Any, default: Optional[int] = None) -> Optional[int]:
|
| 72 |
+
if value in {"", None}:
|
| 73 |
+
return default
|
| 74 |
+
try:
|
| 75 |
+
return int(float(value))
|
| 76 |
+
except (TypeError, ValueError):
|
| 77 |
+
return default
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def is_finite(value: Any) -> bool:
|
| 81 |
+
return math.isfinite(safe_float(value))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def mean(values: Sequence[float]) -> float:
|
| 85 |
+
finite = [value for value in values if math.isfinite(value)]
|
| 86 |
+
return sum(finite) / len(finite) if finite else float("nan")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def quantile(values: Sequence[float], q: float) -> float:
|
| 90 |
+
finite = sorted(value for value in values if math.isfinite(value))
|
| 91 |
+
if not finite:
|
| 92 |
+
return float("nan")
|
| 93 |
+
if len(finite) == 1:
|
| 94 |
+
return finite[0]
|
| 95 |
+
pos = (len(finite) - 1) * q
|
| 96 |
+
low = int(math.floor(pos))
|
| 97 |
+
high = int(math.ceil(pos))
|
| 98 |
+
if low == high:
|
| 99 |
+
return finite[low]
|
| 100 |
+
weight = pos - low
|
| 101 |
+
return finite[low] * (1.0 - weight) + finite[high] * weight
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def fp_1e6(value: Any) -> str:
|
| 105 |
+
number = safe_float(value)
|
| 106 |
+
if not math.isfinite(number):
|
| 107 |
+
return ""
|
| 108 |
+
return str(int(round(number * FP_SCALE)))
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def input_bucket(token_count: int) -> str:
|
| 112 |
+
if token_count <= 128:
|
| 113 |
+
return "00000-00128"
|
| 114 |
+
if token_count <= 512:
|
| 115 |
+
return "00129-00512"
|
| 116 |
+
if token_count <= 2048:
|
| 117 |
+
return "00513-02048"
|
| 118 |
+
if token_count <= 8192:
|
| 119 |
+
return "02049-08192"
|
| 120 |
+
if token_count <= 16384:
|
| 121 |
+
return "08193-16384"
|
| 122 |
+
return "16385+"
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def output_depth_bucket(depth: int) -> str:
|
| 126 |
+
if depth <= 16:
|
| 127 |
+
return "000-016"
|
| 128 |
+
if depth <= 32:
|
| 129 |
+
return "017-032"
|
| 130 |
+
if depth <= 64:
|
| 131 |
+
return "033-064"
|
| 132 |
+
if depth <= 128:
|
| 133 |
+
return "065-128"
|
| 134 |
+
if depth <= 256:
|
| 135 |
+
return "129-256"
|
| 136 |
+
return "257+"
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def resolve_metrics_file(path: Path) -> Optional[Path]:
|
| 140 |
+
if path.is_file() and path.name == METRICS_FILENAME:
|
| 141 |
+
return path
|
| 142 |
+
if path.is_dir():
|
| 143 |
+
candidate = path / METRICS_FILENAME
|
| 144 |
+
if candidate.exists():
|
| 145 |
+
return candidate
|
| 146 |
+
return None
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def resolve_inputs(paths: Sequence[str]) -> List[Path]:
|
| 150 |
+
metrics_files: List[Path] = []
|
| 151 |
+
seen = set()
|
| 152 |
+
for raw in paths:
|
| 153 |
+
path = Path(raw)
|
| 154 |
+
direct = resolve_metrics_file(path)
|
| 155 |
+
if direct is not None:
|
| 156 |
+
resolved = direct.resolve()
|
| 157 |
+
if resolved not in seen:
|
| 158 |
+
metrics_files.append(direct)
|
| 159 |
+
seen.add(resolved)
|
| 160 |
+
continue
|
| 161 |
+
if path.is_dir():
|
| 162 |
+
for found in sorted(path.rglob(METRICS_FILENAME)):
|
| 163 |
+
resolved = found.resolve()
|
| 164 |
+
if resolved not in seen:
|
| 165 |
+
metrics_files.append(found)
|
| 166 |
+
seen.add(resolved)
|
| 167 |
+
continue
|
| 168 |
+
raise FileNotFoundError(f"Cannot find {METRICS_FILENAME} under {path}")
|
| 169 |
+
return metrics_files
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def read_csv_rows(path: Path) -> List[Dict[str, str]]:
|
| 173 |
+
with path.open("r", encoding="utf-8", newline="") as handle:
|
| 174 |
+
return list(csv.DictReader(handle))
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def write_csv(path: Path, rows: Sequence[Dict[str, Any]], fields: Sequence[str]) -> None:
|
| 178 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 179 |
+
with path.open("w", encoding="utf-8", newline="") as handle:
|
| 180 |
+
writer = csv.DictWriter(handle, fieldnames=list(fields))
|
| 181 |
+
writer.writeheader()
|
| 182 |
+
for row in rows:
|
| 183 |
+
writer.writerow({field: row.get(field, "") for field in fields})
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def collect_fields(rows: Sequence[Dict[str, Any]], preferred: Sequence[str]) -> List[str]:
|
| 187 |
+
fields = list(preferred)
|
| 188 |
+
present = set(fields)
|
| 189 |
+
for row in rows:
|
| 190 |
+
for key in row:
|
| 191 |
+
if key not in present:
|
| 192 |
+
fields.append(key)
|
| 193 |
+
present.add(key)
|
| 194 |
+
return fields
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def parse_labels_from_dir(name: str) -> Tuple[str, str]:
|
| 198 |
+
marker = "_worker_vs_"
|
| 199 |
+
suffix = "_verifier"
|
| 200 |
+
if marker not in name:
|
| 201 |
+
return "", ""
|
| 202 |
+
left, right = name.split(marker, 1)
|
| 203 |
+
if right.endswith(suffix):
|
| 204 |
+
right = right[: -len(suffix)]
|
| 205 |
+
return left, right
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def find_pipeline_metadata(metrics_path: Path) -> Optional[Dict[str, Any]]:
|
| 209 |
+
for parent in [metrics_path.parent, *metrics_path.parents]:
|
| 210 |
+
candidate = parent / "pipeline_metadata.json"
|
| 211 |
+
if candidate.exists():
|
| 212 |
+
return read_json(candidate)
|
| 213 |
+
return None
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def run_context(metrics_path: Path) -> Dict[str, str]:
|
| 217 |
+
parent = metrics_path.parent
|
| 218 |
+
verifier_metadata = read_json(parent / "metadata.json") or {}
|
| 219 |
+
pipeline_metadata = find_pipeline_metadata(metrics_path) or {}
|
| 220 |
+
worker_label, verifier_label = parse_labels_from_dir(parent.name)
|
| 221 |
+
|
| 222 |
+
pipeline_args = pipeline_metadata.get("args", {})
|
| 223 |
+
verifier_variant = verifier_metadata.get("verifier_variant", {})
|
| 224 |
+
verifier_args = verifier_metadata.get("args", {})
|
| 225 |
+
|
| 226 |
+
worker_variant_id = str(
|
| 227 |
+
pipeline_metadata.get("baseline_variant_id")
|
| 228 |
+
or worker_label
|
| 229 |
+
or ""
|
| 230 |
+
)
|
| 231 |
+
verifier_variant_id = str(
|
| 232 |
+
pipeline_metadata.get("comparison_variant_id")
|
| 233 |
+
or verifier_variant.get("variant_id")
|
| 234 |
+
or verifier_label
|
| 235 |
+
or ""
|
| 236 |
+
)
|
| 237 |
+
worker_model = str(pipeline_args.get("baseline_model") or "")
|
| 238 |
+
verifier_model = str(
|
| 239 |
+
pipeline_args.get("comparison_model")
|
| 240 |
+
or verifier_variant.get("model")
|
| 241 |
+
or verifier_args.get("model")
|
| 242 |
+
or ""
|
| 243 |
+
)
|
| 244 |
+
run_id = str(pipeline_metadata.get("run_id") or parent.name)
|
| 245 |
+
output_dir = str(parent)
|
| 246 |
+
|
| 247 |
+
return {
|
| 248 |
+
"run_id": run_id,
|
| 249 |
+
"metrics_path": str(metrics_path),
|
| 250 |
+
"output_dir": output_dir,
|
| 251 |
+
"worker_variant_id": worker_variant_id,
|
| 252 |
+
"verifier_variant_id": verifier_variant_id,
|
| 253 |
+
"worker_model": worker_model,
|
| 254 |
+
"verifier_model": verifier_model,
|
| 255 |
+
"verifier_backend": str(verifier_variant.get("backend") or ""),
|
| 256 |
+
"verifier_backend_version": str(verifier_variant.get("backend_version") or ""),
|
| 257 |
+
"verifier_dtype": str(verifier_variant.get("dtype") or verifier_args.get("dtype") or ""),
|
| 258 |
+
"verifier_quantization": str(
|
| 259 |
+
verifier_variant.get("quantization")
|
| 260 |
+
or verifier_args.get("quantization")
|
| 261 |
+
or ""
|
| 262 |
+
),
|
| 263 |
+
"verifier_gpu": str(verifier_variant.get("gpu") or verifier_args.get("gpu") or ""),
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def mark_model_role(context: Dict[str, str], base_runs: Sequence[str],
|
| 268 |
+
base_models: Sequence[str]) -> str:
|
| 269 |
+
haystack = " ".join(
|
| 270 |
+
str(context.get(key, ""))
|
| 271 |
+
for key in [
|
| 272 |
+
"run_id",
|
| 273 |
+
"output_dir",
|
| 274 |
+
"worker_variant_id",
|
| 275 |
+
"verifier_variant_id",
|
| 276 |
+
"worker_model",
|
| 277 |
+
"verifier_model",
|
| 278 |
+
]
|
| 279 |
+
).lower()
|
| 280 |
+
for selector in base_runs:
|
| 281 |
+
if selector.lower() in haystack:
|
| 282 |
+
return "base"
|
| 283 |
+
for selector in base_models:
|
| 284 |
+
if model_selector_matches(selector, str(context.get("verifier_model", ""))):
|
| 285 |
+
return "base"
|
| 286 |
+
if model_selector_matches(selector, str(context.get("verifier_variant_id", ""))):
|
| 287 |
+
return "base"
|
| 288 |
+
worker_model = context.get("worker_model")
|
| 289 |
+
verifier_model = context.get("verifier_model")
|
| 290 |
+
if worker_model and verifier_model and worker_model == verifier_model:
|
| 291 |
+
return "base"
|
| 292 |
+
return "other"
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def model_selector_matches(selector: str, value: str) -> bool:
|
| 296 |
+
selector_l = selector.strip().lower().rstrip("/")
|
| 297 |
+
value_l = value.strip().lower().rstrip("/")
|
| 298 |
+
if not selector_l or not value_l:
|
| 299 |
+
return False
|
| 300 |
+
if selector_l == value_l:
|
| 301 |
+
return True
|
| 302 |
+
selector_name = Path(selector_l).name
|
| 303 |
+
value_name = Path(value_l).name
|
| 304 |
+
return bool(selector_name and selector_name == value_name)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def missing_selected(row: Dict[str, str]) -> bool:
|
| 308 |
+
return (
|
| 309 |
+
not is_finite(row.get("worker_selected_logprob"))
|
| 310 |
+
or not is_finite(row.get("verifier_selected_logprob"))
|
| 311 |
+
or not is_finite(row.get("abs_logprob_diff"))
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def summarize_token_rows(rows: Sequence[Dict[str, str]], label: str) -> Dict[str, Any]:
|
| 316 |
+
abs_values = [safe_float(row.get("abs_logprob_diff")) for row in rows]
|
| 317 |
+
abs_values = [value for value in abs_values if math.isfinite(value)]
|
| 318 |
+
rank_deltas = [
|
| 319 |
+
safe_float(row.get("rank_delta_verifier_minus_worker"))
|
| 320 |
+
for row in rows
|
| 321 |
+
]
|
| 322 |
+
rank_deltas = [value for value in rank_deltas if math.isfinite(value)]
|
| 323 |
+
jaccards = [safe_float(row.get("topk_jaccard")) for row in rows]
|
| 324 |
+
jaccards = [value for value in jaccards if math.isfinite(value)]
|
| 325 |
+
union_js = [safe_float(row.get("union_js_divergence")) for row in rows]
|
| 326 |
+
union_js = [value for value in union_js if math.isfinite(value)]
|
| 327 |
+
common_counts = [safe_float(row.get("common_top_count")) for row in rows]
|
| 328 |
+
common_counts = [value for value in common_counts if math.isfinite(value)]
|
| 329 |
+
union_counts = [safe_float(row.get("union_top_count")) for row in rows]
|
| 330 |
+
union_counts = [value for value in union_counts if math.isfinite(value)]
|
| 331 |
+
input_counts = [
|
| 332 |
+
safe_int(row.get("input_token_count"), 0) or 0
|
| 333 |
+
for row in rows
|
| 334 |
+
]
|
| 335 |
+
output_counts = [
|
| 336 |
+
safe_int(row.get("output_token_count"), 0) or 0
|
| 337 |
+
for row in rows
|
| 338 |
+
]
|
| 339 |
+
sample_ids = {str(row.get("sample_id", "")) for row in rows if row.get("sample_id")}
|
| 340 |
+
|
| 341 |
+
summary: Dict[str, Any] = {
|
| 342 |
+
"group": label,
|
| 343 |
+
"sample_count": len(sample_ids),
|
| 344 |
+
"depth_row_count": len(rows),
|
| 345 |
+
"finite_count": len(abs_values),
|
| 346 |
+
"missing_compared_count": sum(1 for row in rows if missing_selected(row)),
|
| 347 |
+
"mean_abs_logprob_diff": mean(abs_values),
|
| 348 |
+
"abs_logprob_diff_p50": quantile(abs_values, 0.50),
|
| 349 |
+
"abs_logprob_diff_p90": quantile(abs_values, 0.90),
|
| 350 |
+
"abs_logprob_diff_p95": quantile(abs_values, 0.95),
|
| 351 |
+
"abs_logprob_diff_p99": quantile(abs_values, 0.99),
|
| 352 |
+
"abs_logprob_diff_p999": quantile(abs_values, 0.999),
|
| 353 |
+
"max_abs_logprob_diff": max(abs_values, default=float("nan")),
|
| 354 |
+
"compared_rank_count": len(rank_deltas),
|
| 355 |
+
"rank_delta_nonzero_rate": (
|
| 356 |
+
sum(1 for value in rank_deltas if value != 0.0) / len(rank_deltas)
|
| 357 |
+
if rank_deltas else float("nan")
|
| 358 |
+
),
|
| 359 |
+
"compared_topk_count": len(jaccards),
|
| 360 |
+
"topk_jaccard_mean": mean(jaccards),
|
| 361 |
+
"topk_jaccard_p01": quantile(jaccards, 0.01),
|
| 362 |
+
"topk_jaccard_p05": quantile(jaccards, 0.05),
|
| 363 |
+
"topk_jaccard_min": min(jaccards, default=float("nan")),
|
| 364 |
+
"union_js_p95": quantile(union_js, 0.95),
|
| 365 |
+
"union_js_p99": quantile(union_js, 0.99),
|
| 366 |
+
"union_js_max": max(union_js, default=float("nan")),
|
| 367 |
+
"common_top_count_mean": mean(common_counts),
|
| 368 |
+
"union_top_count_mean": mean(union_counts),
|
| 369 |
+
"input_token_count_min": min(input_counts, default=""),
|
| 370 |
+
"input_token_count_max": max(input_counts, default=""),
|
| 371 |
+
"output_token_count_min": min(output_counts, default=""),
|
| 372 |
+
"output_token_count_max": max(output_counts, default=""),
|
| 373 |
+
}
|
| 374 |
+
add_fp_columns(summary)
|
| 375 |
+
return summary
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def add_fp_columns(summary: Dict[str, Any]) -> None:
|
| 379 |
+
for key in [
|
| 380 |
+
"mean_abs_logprob_diff",
|
| 381 |
+
"abs_logprob_diff_p50",
|
| 382 |
+
"abs_logprob_diff_p90",
|
| 383 |
+
"abs_logprob_diff_p95",
|
| 384 |
+
"abs_logprob_diff_p99",
|
| 385 |
+
"abs_logprob_diff_p999",
|
| 386 |
+
"max_abs_logprob_diff",
|
| 387 |
+
"rank_delta_nonzero_rate",
|
| 388 |
+
"topk_jaccard_mean",
|
| 389 |
+
"topk_jaccard_p01",
|
| 390 |
+
"topk_jaccard_p05",
|
| 391 |
+
"topk_jaccard_min",
|
| 392 |
+
"union_js_p95",
|
| 393 |
+
"union_js_p99",
|
| 394 |
+
"union_js_max",
|
| 395 |
+
]:
|
| 396 |
+
summary[f"{key}_fp_1e6"] = fp_1e6(summary.get(key))
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def summarize_by_sample(rows: Sequence[Dict[str, str]],
|
| 400 |
+
context: Dict[str, str]) -> List[Dict[str, Any]]:
|
| 401 |
+
grouped: Dict[str, List[Dict[str, str]]] = defaultdict(list)
|
| 402 |
+
for row in rows:
|
| 403 |
+
grouped[str(row.get("sample_id", ""))].append(row)
|
| 404 |
+
|
| 405 |
+
sample_rows = []
|
| 406 |
+
for sample_id, group_rows in sorted(grouped.items()):
|
| 407 |
+
summary = summarize_token_rows(group_rows, sample_id)
|
| 408 |
+
first = group_rows[0]
|
| 409 |
+
summary.update(context)
|
| 410 |
+
summary.update({
|
| 411 |
+
"sample_id": sample_id,
|
| 412 |
+
"input_token_count": safe_int(first.get("input_token_count"), ""),
|
| 413 |
+
"output_token_count": safe_int(first.get("output_token_count"), ""),
|
| 414 |
+
"input_bucket": input_bucket(safe_int(first.get("input_token_count"), 0) or 0),
|
| 415 |
+
})
|
| 416 |
+
sample_rows.append(summary)
|
| 417 |
+
return sample_rows
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def summarize_grouped_tokens(rows: Sequence[Dict[str, str]], context: Dict[str, str],
|
| 421 |
+
group_name: str) -> List[Dict[str, Any]]:
|
| 422 |
+
grouped: Dict[str, List[Dict[str, str]]] = defaultdict(list)
|
| 423 |
+
for row in rows:
|
| 424 |
+
if group_name == "input_bucket":
|
| 425 |
+
key = input_bucket(safe_int(row.get("input_token_count"), 0) or 0)
|
| 426 |
+
elif group_name == "output_depth_bucket":
|
| 427 |
+
key = output_depth_bucket(safe_int(row.get("depth"), 0) or 0)
|
| 428 |
+
else:
|
| 429 |
+
key = str(row.get(group_name, ""))
|
| 430 |
+
grouped[key].append(row)
|
| 431 |
+
|
| 432 |
+
out = []
|
| 433 |
+
for key, group_rows in sorted(grouped.items()):
|
| 434 |
+
summary = summarize_token_rows(group_rows, key)
|
| 435 |
+
summary.update(context)
|
| 436 |
+
summary[group_name] = key
|
| 437 |
+
out.append(summary)
|
| 438 |
+
return out
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def threshold_key(metric: str, bound: str) -> str:
|
| 442 |
+
return f"{metric}_{bound}"
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def normalize_thresholds(payload: Dict[str, Any]) -> Dict[str, Any]:
|
| 446 |
+
thresholds = {
|
| 447 |
+
"source": payload.get("source", "provided"),
|
| 448 |
+
"judgment_function_version": payload.get(
|
| 449 |
+
"judgment_function_version",
|
| 450 |
+
JUDGMENT_FUNCTION_VERSION,
|
| 451 |
+
),
|
| 452 |
+
"pass": {},
|
| 453 |
+
"reject": {},
|
| 454 |
+
}
|
| 455 |
+
for section in ["pass", "reject"]:
|
| 456 |
+
raw = payload.get(section, {})
|
| 457 |
+
if not isinstance(raw, dict):
|
| 458 |
+
continue
|
| 459 |
+
for key, value in raw.items():
|
| 460 |
+
if value in {"", None}:
|
| 461 |
+
continue
|
| 462 |
+
thresholds[section][str(key)] = value
|
| 463 |
+
return thresholds
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def load_thresholds(path: Path) -> Dict[str, Any]:
|
| 467 |
+
payload = read_json(path)
|
| 468 |
+
if payload is None:
|
| 469 |
+
raise ValueError(f"Invalid thresholds JSON: {path}")
|
| 470 |
+
return normalize_thresholds(payload)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def derive_thresholds_from_base(
|
| 474 |
+
base_samples: Sequence[Dict[str, Any]],
|
| 475 |
+
*,
|
| 476 |
+
pass_quantile: float,
|
| 477 |
+
pass_multiplier: float,
|
| 478 |
+
reject_multiplier: float,
|
| 479 |
+
jaccard_floor_margin: float,
|
| 480 |
+
) -> Dict[str, Any]:
|
| 481 |
+
if not base_samples:
|
| 482 |
+
raise ValueError("No base samples found for threshold derivation")
|
| 483 |
+
|
| 484 |
+
pass_thresholds: Dict[str, Any] = {}
|
| 485 |
+
reject_thresholds: Dict[str, Any] = {}
|
| 486 |
+
for metric in UPPER_BOUND_METRICS:
|
| 487 |
+
values = [safe_float(row.get(metric)) for row in base_samples]
|
| 488 |
+
values = [value for value in values if math.isfinite(value)]
|
| 489 |
+
if not values:
|
| 490 |
+
continue
|
| 491 |
+
if metric == "missing_compared_count":
|
| 492 |
+
pass_value = max(values)
|
| 493 |
+
reject_value = pass_value + 1
|
| 494 |
+
else:
|
| 495 |
+
pass_value = quantile(values, pass_quantile) * pass_multiplier
|
| 496 |
+
reject_value = pass_value * reject_multiplier
|
| 497 |
+
pass_thresholds[threshold_key(metric, "max")] = pass_value
|
| 498 |
+
reject_thresholds[threshold_key(metric, "max")] = reject_value
|
| 499 |
+
|
| 500 |
+
for metric in LOWER_BOUND_METRICS:
|
| 501 |
+
values = [safe_float(row.get(metric)) for row in base_samples]
|
| 502 |
+
values = [value for value in values if math.isfinite(value)]
|
| 503 |
+
if not values:
|
| 504 |
+
continue
|
| 505 |
+
low = quantile(values, 1.0 - pass_quantile)
|
| 506 |
+
pass_value = max(0.0, low - jaccard_floor_margin)
|
| 507 |
+
reject_value = max(0.0, pass_value / reject_multiplier)
|
| 508 |
+
pass_thresholds[threshold_key(metric, "min")] = pass_value
|
| 509 |
+
reject_thresholds[threshold_key(metric, "min")] = reject_value
|
| 510 |
+
|
| 511 |
+
return {
|
| 512 |
+
"source": "derived_from_base_samples",
|
| 513 |
+
"judgment_function_version": JUDGMENT_FUNCTION_VERSION,
|
| 514 |
+
"derivation": {
|
| 515 |
+
"base_sample_count": len(base_samples),
|
| 516 |
+
"pass_quantile": pass_quantile,
|
| 517 |
+
"pass_multiplier": pass_multiplier,
|
| 518 |
+
"reject_multiplier": reject_multiplier,
|
| 519 |
+
"jaccard_floor_margin": jaccard_floor_margin,
|
| 520 |
+
"note": (
|
| 521 |
+
"Exploratory local thresholds. Protocol thresholds must come "
|
| 522 |
+
"from ProfileState.verification_thresholds."
|
| 523 |
+
),
|
| 524 |
+
},
|
| 525 |
+
"pass": pass_thresholds,
|
| 526 |
+
"reject": reject_thresholds,
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def pass_checks(row: Dict[str, Any], thresholds: Dict[str, Any]) -> List[Tuple[str, bool]]:
|
| 531 |
+
checks = []
|
| 532 |
+
pass_thresholds = thresholds.get("pass", {})
|
| 533 |
+
for metric in UPPER_BOUND_METRICS:
|
| 534 |
+
key = threshold_key(metric, "max")
|
| 535 |
+
if key not in pass_thresholds:
|
| 536 |
+
continue
|
| 537 |
+
value = safe_float(row.get(metric))
|
| 538 |
+
limit = safe_float(pass_thresholds.get(key))
|
| 539 |
+
checks.append((key, math.isfinite(value) and value <= limit))
|
| 540 |
+
for metric in LOWER_BOUND_METRICS:
|
| 541 |
+
key = threshold_key(metric, "min")
|
| 542 |
+
if key not in pass_thresholds:
|
| 543 |
+
continue
|
| 544 |
+
value = safe_float(row.get(metric))
|
| 545 |
+
limit = safe_float(pass_thresholds.get(key))
|
| 546 |
+
checks.append((key, math.isfinite(value) and value >= limit))
|
| 547 |
+
return checks
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def reject_checks(row: Dict[str, Any], thresholds: Dict[str, Any]) -> List[Tuple[str, bool]]:
|
| 551 |
+
checks = []
|
| 552 |
+
reject_thresholds = thresholds.get("reject", {})
|
| 553 |
+
for metric in UPPER_BOUND_METRICS:
|
| 554 |
+
key = threshold_key(metric, "max")
|
| 555 |
+
if key not in reject_thresholds:
|
| 556 |
+
continue
|
| 557 |
+
value = safe_float(row.get(metric))
|
| 558 |
+
limit = safe_float(reject_thresholds.get(key))
|
| 559 |
+
checks.append((key, math.isfinite(value) and value > limit))
|
| 560 |
+
for metric in LOWER_BOUND_METRICS:
|
| 561 |
+
key = threshold_key(metric, "min")
|
| 562 |
+
if key not in reject_thresholds:
|
| 563 |
+
continue
|
| 564 |
+
value = safe_float(row.get(metric))
|
| 565 |
+
limit = safe_float(reject_thresholds.get(key))
|
| 566 |
+
checks.append((key, math.isfinite(value) and value < limit))
|
| 567 |
+
return checks
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def evaluate_sample(row: Dict[str, Any], thresholds: Optional[Dict[str, Any]]) -> None:
|
| 571 |
+
if not thresholds:
|
| 572 |
+
row["metric_sample_verdict"] = ""
|
| 573 |
+
row["threshold_breach_count"] = ""
|
| 574 |
+
row["reject_breach_count"] = ""
|
| 575 |
+
return
|
| 576 |
+
|
| 577 |
+
p_checks = pass_checks(row, thresholds)
|
| 578 |
+
r_checks = reject_checks(row, thresholds)
|
| 579 |
+
pass_breaches = [name for name, ok in p_checks if not ok]
|
| 580 |
+
reject_breaches = [name for name, breached in r_checks if breached]
|
| 581 |
+
if p_checks and not pass_breaches:
|
| 582 |
+
verdict = "PASS"
|
| 583 |
+
elif reject_breaches:
|
| 584 |
+
verdict = "REJECT"
|
| 585 |
+
else:
|
| 586 |
+
verdict = "INCONCLUSIVE"
|
| 587 |
+
row["metric_sample_verdict"] = verdict
|
| 588 |
+
row["threshold_breach_count"] = len(pass_breaches)
|
| 589 |
+
row["reject_breach_count"] = len(reject_breaches)
|
| 590 |
+
row["threshold_breaches"] = ";".join(pass_breaches)
|
| 591 |
+
row["reject_breaches"] = ";".join(reject_breaches)
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def add_verdict_counts(summary: Dict[str, Any], samples: Sequence[Dict[str, Any]]) -> None:
|
| 595 |
+
counts = defaultdict(int)
|
| 596 |
+
breach_total = 0
|
| 597 |
+
reject_breach_total = 0
|
| 598 |
+
for row in samples:
|
| 599 |
+
counts[str(row.get("metric_sample_verdict", ""))] += 1
|
| 600 |
+
breach_total += safe_int(row.get("threshold_breach_count"), 0) or 0
|
| 601 |
+
reject_breach_total += safe_int(row.get("reject_breach_count"), 0) or 0
|
| 602 |
+
total = sum(value for key, value in counts.items() if key)
|
| 603 |
+
for verdict in ["PASS", "REJECT", "INCONCLUSIVE"]:
|
| 604 |
+
summary[f"sample_{verdict.lower()}_count"] = counts.get(verdict, 0)
|
| 605 |
+
summary[f"sample_{verdict.lower()}_rate"] = (
|
| 606 |
+
counts.get(verdict, 0) / total if total else ""
|
| 607 |
+
)
|
| 608 |
+
summary["threshold_breach_count"] = breach_total if total else ""
|
| 609 |
+
summary["reject_breach_count"] = reject_breach_total if total else ""
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def process_metrics_file(metrics_path: Path, args: argparse.Namespace) -> Dict[str, Any]:
|
| 613 |
+
rows = read_csv_rows(metrics_path)
|
| 614 |
+
context = run_context(metrics_path)
|
| 615 |
+
context["model_role"] = mark_model_role(context, args.base_run, args.base_model)
|
| 616 |
+
log(f"Loaded {len(rows)} depth rows from {metrics_path}")
|
| 617 |
+
|
| 618 |
+
run_summary = summarize_token_rows(rows, context["run_id"])
|
| 619 |
+
run_summary.update(context)
|
| 620 |
+
sample_rows = summarize_by_sample(rows, context)
|
| 621 |
+
by_input = summarize_grouped_tokens(rows, context, "input_bucket")
|
| 622 |
+
by_depth = summarize_grouped_tokens(rows, context, "output_depth_bucket")
|
| 623 |
+
|
| 624 |
+
top_rows = []
|
| 625 |
+
for row in sorted(
|
| 626 |
+
rows,
|
| 627 |
+
key=lambda item: safe_float(item.get("abs_logprob_diff"), -1.0),
|
| 628 |
+
reverse=True,
|
| 629 |
+
)[: args.top_outliers_per_run]:
|
| 630 |
+
top = dict(context)
|
| 631 |
+
top.update({
|
| 632 |
+
"sample_id": row.get("sample_id", ""),
|
| 633 |
+
"depth": row.get("depth", ""),
|
| 634 |
+
"input_token_count": row.get("input_token_count", ""),
|
| 635 |
+
"output_token_count": row.get("output_token_count", ""),
|
| 636 |
+
"target_token_id": row.get("target_token_id", ""),
|
| 637 |
+
"target_decoded_token": row.get("target_decoded_token", ""),
|
| 638 |
+
"worker_selected_logprob": row.get("worker_selected_logprob", ""),
|
| 639 |
+
"verifier_selected_logprob": row.get("verifier_selected_logprob", ""),
|
| 640 |
+
"abs_logprob_diff": row.get("abs_logprob_diff", ""),
|
| 641 |
+
"rank_delta_verifier_minus_worker": row.get(
|
| 642 |
+
"rank_delta_verifier_minus_worker",
|
| 643 |
+
"",
|
| 644 |
+
),
|
| 645 |
+
"topk_jaccard": row.get("topk_jaccard", ""),
|
| 646 |
+
"union_js_divergence": row.get("union_js_divergence", ""),
|
| 647 |
+
})
|
| 648 |
+
top["abs_logprob_diff_fp_1e6"] = fp_1e6(top["abs_logprob_diff"])
|
| 649 |
+
top_rows.append(top)
|
| 650 |
+
|
| 651 |
+
return {
|
| 652 |
+
"context": context,
|
| 653 |
+
"run_summary": run_summary,
|
| 654 |
+
"sample_rows": sample_rows,
|
| 655 |
+
"by_input": by_input,
|
| 656 |
+
"by_depth": by_depth,
|
| 657 |
+
"top_outliers": top_rows,
|
| 658 |
+
}
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def summarize_sample_rows(rows: Sequence[Dict[str, Any]], label: str) -> Dict[str, Any]:
|
| 662 |
+
summary: Dict[str, Any] = {
|
| 663 |
+
"group": label,
|
| 664 |
+
"run_count": len({row.get("run_id") for row in rows}),
|
| 665 |
+
"sample_count": len(rows),
|
| 666 |
+
"depth_row_count": sum(safe_int(row.get("depth_row_count"), 0) or 0 for row in rows),
|
| 667 |
+
"finite_count": sum(safe_int(row.get("finite_count"), 0) or 0 for row in rows),
|
| 668 |
+
"missing_compared_count": sum(
|
| 669 |
+
safe_int(row.get("missing_compared_count"), 0) or 0
|
| 670 |
+
for row in rows
|
| 671 |
+
),
|
| 672 |
+
}
|
| 673 |
+
for metric in [
|
| 674 |
+
"mean_abs_logprob_diff",
|
| 675 |
+
"abs_logprob_diff_p95",
|
| 676 |
+
"abs_logprob_diff_p99",
|
| 677 |
+
"rank_delta_nonzero_rate",
|
| 678 |
+
"topk_jaccard_mean",
|
| 679 |
+
"union_js_p99",
|
| 680 |
+
]:
|
| 681 |
+
values = [safe_float(row.get(metric)) for row in rows]
|
| 682 |
+
values = [value for value in values if math.isfinite(value)]
|
| 683 |
+
summary[f"{metric}_sample_mean"] = mean(values)
|
| 684 |
+
summary[f"{metric}_sample_p50"] = quantile(values, 0.50)
|
| 685 |
+
summary[f"{metric}_sample_p90"] = quantile(values, 0.90)
|
| 686 |
+
summary[f"{metric}_sample_p99"] = quantile(values, 0.99)
|
| 687 |
+
add_fp_columns(summary)
|
| 688 |
+
add_verdict_counts(summary, rows)
|
| 689 |
+
return summary
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
def build_model_summary(sample_rows: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 693 |
+
grouped: Dict[Tuple[str, str, str], List[Dict[str, Any]]] = defaultdict(list)
|
| 694 |
+
for row in sample_rows:
|
| 695 |
+
key = (
|
| 696 |
+
str(row.get("model_role", "")),
|
| 697 |
+
str(row.get("verifier_variant_id", "")),
|
| 698 |
+
str(row.get("verifier_model", "")),
|
| 699 |
+
)
|
| 700 |
+
grouped[key].append(row)
|
| 701 |
+
|
| 702 |
+
out = []
|
| 703 |
+
for (role, variant, model), rows in sorted(grouped.items()):
|
| 704 |
+
label = variant or model or role
|
| 705 |
+
summary = summarize_sample_rows(rows, label)
|
| 706 |
+
summary.update({
|
| 707 |
+
"model_role": role,
|
| 708 |
+
"verifier_variant_id": variant,
|
| 709 |
+
"verifier_model": model,
|
| 710 |
+
})
|
| 711 |
+
out.append(summary)
|
| 712 |
+
return out
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
def markdown_number(value: Any) -> str:
|
| 716 |
+
number = safe_float(value)
|
| 717 |
+
if not math.isfinite(number):
|
| 718 |
+
return ""
|
| 719 |
+
return f"{number:.6g}"
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
def write_markdown(path: Path, run_rows: Sequence[Dict[str, Any]],
|
| 723 |
+
model_rows: Sequence[Dict[str, Any]],
|
| 724 |
+
thresholds: Optional[Dict[str, Any]]) -> None:
|
| 725 |
+
lines = [
|
| 726 |
+
"# vLLM worker verify metric analysis",
|
| 727 |
+
"",
|
| 728 |
+
f"- judgment_function_version: `{JUDGMENT_FUNCTION_VERSION}`",
|
| 729 |
+
"- token_scope: `ALL_GENERATED_OUTPUT_TOKENS`",
|
| 730 |
+
"- metrics: abs logprob diff, rank delta, top-k Jaccard, union JS",
|
| 731 |
+
"",
|
| 732 |
+
]
|
| 733 |
+
if thresholds:
|
| 734 |
+
lines.extend([
|
| 735 |
+
"## thresholds",
|
| 736 |
+
"",
|
| 737 |
+
f"- source: `{thresholds.get('source', '')}`",
|
| 738 |
+
f"- pass keys: `{', '.join(sorted(thresholds.get('pass', {})))}`",
|
| 739 |
+
f"- reject keys: `{', '.join(sorted(thresholds.get('reject', {})))}`",
|
| 740 |
+
"",
|
| 741 |
+
])
|
| 742 |
+
else:
|
| 743 |
+
lines.extend([
|
| 744 |
+
"## thresholds",
|
| 745 |
+
"",
|
| 746 |
+
"No thresholds were supplied or derived, so verdict columns are left blank.",
|
| 747 |
+
"",
|
| 748 |
+
])
|
| 749 |
+
|
| 750 |
+
lines.extend([
|
| 751 |
+
"## by run",
|
| 752 |
+
"",
|
| 753 |
+
"| role | run | worker | verifier | samples | depth rows | mean_abs | p95 | p99 | rank_delta_rate | jaccard_mean | union_js_p99 | pass/reject/inconclusive |",
|
| 754 |
+
"|---|---|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|",
|
| 755 |
+
])
|
| 756 |
+
for row in run_rows:
|
| 757 |
+
verdict = "{}/{}/{}".format(
|
| 758 |
+
row.get("sample_pass_count", ""),
|
| 759 |
+
row.get("sample_reject_count", ""),
|
| 760 |
+
row.get("sample_inconclusive_count", ""),
|
| 761 |
+
)
|
| 762 |
+
lines.append(
|
| 763 |
+
"| {role} | {run} | {worker} | {verifier} | {samples} | {depth} | {mean} | {p95} | {p99} | {rank} | {jac} | {js} | {verdict} |".format(
|
| 764 |
+
role=row.get("model_role", ""),
|
| 765 |
+
run=row.get("run_id", ""),
|
| 766 |
+
worker=row.get("worker_variant_id", ""),
|
| 767 |
+
verifier=row.get("verifier_variant_id", ""),
|
| 768 |
+
samples=row.get("sample_count", ""),
|
| 769 |
+
depth=row.get("depth_row_count", ""),
|
| 770 |
+
mean=markdown_number(row.get("mean_abs_logprob_diff")),
|
| 771 |
+
p95=markdown_number(row.get("abs_logprob_diff_p95")),
|
| 772 |
+
p99=markdown_number(row.get("abs_logprob_diff_p99")),
|
| 773 |
+
rank=markdown_number(row.get("rank_delta_nonzero_rate")),
|
| 774 |
+
jac=markdown_number(row.get("topk_jaccard_mean")),
|
| 775 |
+
js=markdown_number(row.get("union_js_p99")),
|
| 776 |
+
verdict=verdict,
|
| 777 |
+
)
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
lines.extend([
|
| 781 |
+
"",
|
| 782 |
+
"## by verifier model",
|
| 783 |
+
"",
|
| 784 |
+
"| role | verifier | runs | samples | mean_abs sample mean | p99 sample mean | rank_delta sample mean | jaccard sample mean | pass/reject/inconclusive |",
|
| 785 |
+
"|---|---|---:|---:|---:|---:|---:|---:|---:|",
|
| 786 |
+
])
|
| 787 |
+
for row in model_rows:
|
| 788 |
+
verdict = "{}/{}/{}".format(
|
| 789 |
+
row.get("sample_pass_count", ""),
|
| 790 |
+
row.get("sample_reject_count", ""),
|
| 791 |
+
row.get("sample_inconclusive_count", ""),
|
| 792 |
+
)
|
| 793 |
+
lines.append(
|
| 794 |
+
"| {role} | {verifier} | {runs} | {samples} | {mean} | {p99} | {rank} | {jac} | {verdict} |".format(
|
| 795 |
+
role=row.get("model_role", ""),
|
| 796 |
+
verifier=row.get("verifier_variant_id") or row.get("verifier_model", ""),
|
| 797 |
+
runs=row.get("run_count", ""),
|
| 798 |
+
samples=row.get("sample_count", ""),
|
| 799 |
+
mean=markdown_number(row.get("mean_abs_logprob_diff_sample_mean")),
|
| 800 |
+
p99=markdown_number(row.get("abs_logprob_diff_p99_sample_mean")),
|
| 801 |
+
rank=markdown_number(row.get("rank_delta_nonzero_rate_sample_mean")),
|
| 802 |
+
jac=markdown_number(row.get("topk_jaccard_mean_sample_mean")),
|
| 803 |
+
verdict=verdict,
|
| 804 |
+
)
|
| 805 |
+
)
|
| 806 |
+
lines.append("")
|
| 807 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
def make_parser() -> argparse.ArgumentParser:
|
| 811 |
+
parser = argparse.ArgumentParser(
|
| 812 |
+
description=(
|
| 813 |
+
"Analyze worker_vs_verifier_depth_metrics.csv outputs using "
|
| 814 |
+
"PREFILL_GENERATED_TOKEN_METRICS_V1-style aggregate metrics."
|
| 815 |
+
)
|
| 816 |
+
)
|
| 817 |
+
parser.add_argument(
|
| 818 |
+
"--input",
|
| 819 |
+
action="append",
|
| 820 |
+
default=[],
|
| 821 |
+
help=(
|
| 822 |
+
"Metrics CSV, verifier output dir, or root dir to scan recursively. "
|
| 823 |
+
"Repeat as needed. Defaults to results/vllm_worker_verify_runs."
|
| 824 |
+
),
|
| 825 |
+
)
|
| 826 |
+
parser.add_argument("--output-dir", default="analysis")
|
| 827 |
+
parser.add_argument(
|
| 828 |
+
"--base-run",
|
| 829 |
+
action="append",
|
| 830 |
+
default=[],
|
| 831 |
+
help="Substring marking a run/path/variant as base. Repeat as needed.",
|
| 832 |
+
)
|
| 833 |
+
parser.add_argument(
|
| 834 |
+
"--base-model",
|
| 835 |
+
action="append",
|
| 836 |
+
default=[],
|
| 837 |
+
help="Substring marking a verifier model/variant as base. Repeat as needed.",
|
| 838 |
+
)
|
| 839 |
+
parser.add_argument(
|
| 840 |
+
"--thresholds",
|
| 841 |
+
default=None,
|
| 842 |
+
help="Optional JSON file containing pass/reject thresholds.",
|
| 843 |
+
)
|
| 844 |
+
parser.add_argument(
|
| 845 |
+
"--derive-thresholds-from-base",
|
| 846 |
+
action="store_true",
|
| 847 |
+
help="Derive exploratory thresholds from rows marked as base.",
|
| 848 |
+
)
|
| 849 |
+
parser.add_argument("--base-pass-quantile", type=float, default=0.99)
|
| 850 |
+
parser.add_argument("--base-pass-multiplier", type=float, default=1.25)
|
| 851 |
+
parser.add_argument("--reject-multiplier", type=float, default=3.0)
|
| 852 |
+
parser.add_argument("--jaccard-floor-margin", type=float, default=0.02)
|
| 853 |
+
parser.add_argument("--top-outliers-per-run", type=int, default=100)
|
| 854 |
+
return parser
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 858 |
+
parser = make_parser()
|
| 859 |
+
args = parser.parse_args(argv)
|
| 860 |
+
|
| 861 |
+
input_paths = args.input or ["results/vllm_worker_verify_runs"]
|
| 862 |
+
try:
|
| 863 |
+
metrics_files = resolve_inputs(input_paths)
|
| 864 |
+
except FileNotFoundError as exc:
|
| 865 |
+
parser.error(str(exc))
|
| 866 |
+
if not metrics_files:
|
| 867 |
+
parser.error("No worker_vs_verifier_depth_metrics.csv files found")
|
| 868 |
+
|
| 869 |
+
processed = [process_metrics_file(path, args) for path in metrics_files]
|
| 870 |
+
run_rows = [item["run_summary"] for item in processed]
|
| 871 |
+
sample_rows = [row for item in processed for row in item["sample_rows"]]
|
| 872 |
+
by_input_rows = [row for item in processed for row in item["by_input"]]
|
| 873 |
+
by_depth_rows = [row for item in processed for row in item["by_depth"]]
|
| 874 |
+
top_outliers = [row for item in processed for row in item["top_outliers"]]
|
| 875 |
+
|
| 876 |
+
thresholds: Optional[Dict[str, Any]] = None
|
| 877 |
+
if args.thresholds:
|
| 878 |
+
thresholds = load_thresholds(Path(args.thresholds))
|
| 879 |
+
elif args.derive_thresholds_from_base:
|
| 880 |
+
base_samples = [row for row in sample_rows if row.get("model_role") == "base"]
|
| 881 |
+
thresholds = derive_thresholds_from_base(
|
| 882 |
+
base_samples,
|
| 883 |
+
pass_quantile=args.base_pass_quantile,
|
| 884 |
+
pass_multiplier=args.base_pass_multiplier,
|
| 885 |
+
reject_multiplier=args.reject_multiplier,
|
| 886 |
+
jaccard_floor_margin=args.jaccard_floor_margin,
|
| 887 |
+
)
|
| 888 |
+
|
| 889 |
+
for row in sample_rows:
|
| 890 |
+
evaluate_sample(row, thresholds)
|
| 891 |
+
|
| 892 |
+
samples_by_run: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
|
| 893 |
+
for row in sample_rows:
|
| 894 |
+
samples_by_run[str(row.get("metrics_path", ""))].append(row)
|
| 895 |
+
for row in run_rows:
|
| 896 |
+
add_verdict_counts(row, samples_by_run.get(str(row.get("metrics_path", "")), []))
|
| 897 |
+
|
| 898 |
+
model_rows = build_model_summary(sample_rows)
|
| 899 |
+
|
| 900 |
+
output_dir = Path(args.output_dir)
|
| 901 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 902 |
+
|
| 903 |
+
write_csv(output_dir / "run_summary.csv", run_rows, collect_fields(run_rows, [
|
| 904 |
+
"model_role",
|
| 905 |
+
"run_id",
|
| 906 |
+
"worker_variant_id",
|
| 907 |
+
"verifier_variant_id",
|
| 908 |
+
"worker_model",
|
| 909 |
+
"verifier_model",
|
| 910 |
+
"sample_count",
|
| 911 |
+
"depth_row_count",
|
| 912 |
+
"finite_count",
|
| 913 |
+
"missing_compared_count",
|
| 914 |
+
"mean_abs_logprob_diff",
|
| 915 |
+
"abs_logprob_diff_p95",
|
| 916 |
+
"abs_logprob_diff_p99",
|
| 917 |
+
"rank_delta_nonzero_rate",
|
| 918 |
+
"topk_jaccard_mean",
|
| 919 |
+
"union_js_p99",
|
| 920 |
+
"sample_pass_count",
|
| 921 |
+
"sample_reject_count",
|
| 922 |
+
"sample_inconclusive_count",
|
| 923 |
+
"threshold_breach_count",
|
| 924 |
+
]))
|
| 925 |
+
write_csv(output_dir / "model_summary.csv", model_rows, collect_fields(model_rows, [
|
| 926 |
+
"model_role",
|
| 927 |
+
"verifier_variant_id",
|
| 928 |
+
"verifier_model",
|
| 929 |
+
"run_count",
|
| 930 |
+
"sample_count",
|
| 931 |
+
"depth_row_count",
|
| 932 |
+
"mean_abs_logprob_diff_sample_mean",
|
| 933 |
+
"abs_logprob_diff_p99_sample_mean",
|
| 934 |
+
"rank_delta_nonzero_rate_sample_mean",
|
| 935 |
+
"topk_jaccard_mean_sample_mean",
|
| 936 |
+
"union_js_p99_sample_mean",
|
| 937 |
+
"sample_pass_count",
|
| 938 |
+
"sample_reject_count",
|
| 939 |
+
"sample_inconclusive_count",
|
| 940 |
+
]))
|
| 941 |
+
write_csv(output_dir / "sample_summary.csv", sample_rows, collect_fields(sample_rows, [
|
| 942 |
+
"model_role",
|
| 943 |
+
"run_id",
|
| 944 |
+
"sample_id",
|
| 945 |
+
"worker_variant_id",
|
| 946 |
+
"verifier_variant_id",
|
| 947 |
+
"input_token_count",
|
| 948 |
+
"output_token_count",
|
| 949 |
+
"finite_count",
|
| 950 |
+
"missing_compared_count",
|
| 951 |
+
"mean_abs_logprob_diff",
|
| 952 |
+
"mean_abs_logprob_diff_fp_1e6",
|
| 953 |
+
"abs_logprob_diff_p95",
|
| 954 |
+
"abs_logprob_diff_p95_fp_1e6",
|
| 955 |
+
"abs_logprob_diff_p99",
|
| 956 |
+
"abs_logprob_diff_p99_fp_1e6",
|
| 957 |
+
"rank_delta_nonzero_rate",
|
| 958 |
+
"rank_delta_nonzero_rate_fp_1e6",
|
| 959 |
+
"topk_jaccard_mean",
|
| 960 |
+
"topk_jaccard_mean_fp_1e6",
|
| 961 |
+
"union_js_p99",
|
| 962 |
+
"union_js_p99_fp_1e6",
|
| 963 |
+
"compared_topk_count",
|
| 964 |
+
"compared_rank_count",
|
| 965 |
+
"metric_sample_verdict",
|
| 966 |
+
"threshold_breach_count",
|
| 967 |
+
"reject_breach_count",
|
| 968 |
+
]))
|
| 969 |
+
write_csv(output_dir / "by_input_bucket.csv", by_input_rows, collect_fields(by_input_rows, [
|
| 970 |
+
"model_role",
|
| 971 |
+
"run_id",
|
| 972 |
+
"input_bucket",
|
| 973 |
+
"worker_variant_id",
|
| 974 |
+
"verifier_variant_id",
|
| 975 |
+
"sample_count",
|
| 976 |
+
"depth_row_count",
|
| 977 |
+
"mean_abs_logprob_diff",
|
| 978 |
+
"abs_logprob_diff_p95",
|
| 979 |
+
"abs_logprob_diff_p99",
|
| 980 |
+
"rank_delta_nonzero_rate",
|
| 981 |
+
"topk_jaccard_mean",
|
| 982 |
+
"union_js_p99",
|
| 983 |
+
]))
|
| 984 |
+
write_csv(output_dir / "by_output_depth_bucket.csv", by_depth_rows, collect_fields(by_depth_rows, [
|
| 985 |
+
"model_role",
|
| 986 |
+
"run_id",
|
| 987 |
+
"output_depth_bucket",
|
| 988 |
+
"worker_variant_id",
|
| 989 |
+
"verifier_variant_id",
|
| 990 |
+
"sample_count",
|
| 991 |
+
"depth_row_count",
|
| 992 |
+
"mean_abs_logprob_diff",
|
| 993 |
+
"abs_logprob_diff_p95",
|
| 994 |
+
"abs_logprob_diff_p99",
|
| 995 |
+
"rank_delta_nonzero_rate",
|
| 996 |
+
"topk_jaccard_mean",
|
| 997 |
+
"union_js_p99",
|
| 998 |
+
]))
|
| 999 |
+
write_csv(output_dir / "top_outlier_tokens.csv", top_outliers, collect_fields(top_outliers, [
|
| 1000 |
+
"model_role",
|
| 1001 |
+
"run_id",
|
| 1002 |
+
"worker_variant_id",
|
| 1003 |
+
"verifier_variant_id",
|
| 1004 |
+
"sample_id",
|
| 1005 |
+
"depth",
|
| 1006 |
+
"target_token_id",
|
| 1007 |
+
"target_decoded_token",
|
| 1008 |
+
"abs_logprob_diff",
|
| 1009 |
+
"abs_logprob_diff_fp_1e6",
|
| 1010 |
+
"rank_delta_verifier_minus_worker",
|
| 1011 |
+
"topk_jaccard",
|
| 1012 |
+
"union_js_divergence",
|
| 1013 |
+
]))
|
| 1014 |
+
write_json(output_dir / "thresholds.json", thresholds or {
|
| 1015 |
+
"source": "none",
|
| 1016 |
+
"judgment_function_version": JUDGMENT_FUNCTION_VERSION,
|
| 1017 |
+
"pass": {},
|
| 1018 |
+
"reject": {},
|
| 1019 |
+
})
|
| 1020 |
+
write_json(output_dir / "analysis_metadata.json", {
|
| 1021 |
+
"metadata": runtime_metadata(sys.argv),
|
| 1022 |
+
"judgment_function_version": JUDGMENT_FUNCTION_VERSION,
|
| 1023 |
+
"token_scope": "ALL_GENERATED_OUTPUT_TOKENS",
|
| 1024 |
+
"input_metrics_files": [str(path) for path in metrics_files],
|
| 1025 |
+
"output_files": [
|
| 1026 |
+
"run_summary.csv",
|
| 1027 |
+
"model_summary.csv",
|
| 1028 |
+
"sample_summary.csv",
|
| 1029 |
+
"by_input_bucket.csv",
|
| 1030 |
+
"by_output_depth_bucket.csv",
|
| 1031 |
+
"top_outlier_tokens.csv",
|
| 1032 |
+
"thresholds.json",
|
| 1033 |
+
"summary.md",
|
| 1034 |
+
],
|
| 1035 |
+
"thresholds_source": (thresholds or {}).get("source", "none"),
|
| 1036 |
+
})
|
| 1037 |
+
write_markdown(output_dir / "summary.md", run_rows, model_rows, thresholds)
|
| 1038 |
+
|
| 1039 |
+
log(f"Wrote {output_dir / 'summary.md'}")
|
| 1040 |
+
log(f"Wrote {output_dir / 'run_summary.csv'}")
|
| 1041 |
+
log(f"Wrote {output_dir / 'model_summary.csv'}")
|
| 1042 |
+
log(f"Wrote {output_dir / 'sample_summary.csv'}")
|
| 1043 |
+
return 0
|
| 1044 |
+
|
| 1045 |
+
|
| 1046 |
+
if __name__ == "__main__":
|
| 1047 |
+
raise SystemExit(main())
|
tools/vllm_worker_verify_pipeline/benchmark_worker_verifier_latency.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Benchmark worker vs verifier latency on vLLM across input/output length grid.
|
| 3 |
+
|
| 4 |
+
Two flows share one vLLM instance (same model, same GPU state) so the comparison
|
| 5 |
+
is apples-to-apples:
|
| 6 |
+
|
| 7 |
+
* worker -- normal generation: prefill(input) + decode(output_len tokens),
|
| 8 |
+
SamplingParams(max_tokens=output_len, logprobs=K).
|
| 9 |
+
* verifier -- single prefill over worker's input_ids + output_ids with
|
| 10 |
+
SamplingParams(max_tokens=1, prompt_logprobs=K) to recover top-k
|
| 11 |
+
logprobs at every position.
|
| 12 |
+
|
| 13 |
+
For each (input_len, output_len) cell we run `warmup` unmeasured repeats then
|
| 14 |
+
`repeats` measured repeats, and report median / mean / p10 / p90 wall times plus
|
| 15 |
+
a worker->verifier ratio. Output length is pinned exactly via ignore_eos +
|
| 16 |
+
min_tokens so the sweep axis is clean.
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import csv
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import random
|
| 25 |
+
import statistics
|
| 26 |
+
import sys
|
| 27 |
+
import time
|
| 28 |
+
from dataclasses import dataclass
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
from typing import Dict, List, Optional, Sequence, Tuple
|
| 31 |
+
|
| 32 |
+
from pipeline_common import (
|
| 33 |
+
build_llm_kwargs,
|
| 34 |
+
make_tokens_prompt,
|
| 35 |
+
runtime_metadata,
|
| 36 |
+
write_json,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def log(message: str) -> None:
|
| 41 |
+
print(message, flush=True)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def vllm_version() -> str:
|
| 45 |
+
try:
|
| 46 |
+
import vllm
|
| 47 |
+
|
| 48 |
+
return vllm.__version__
|
| 49 |
+
except Exception:
|
| 50 |
+
return ""
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def parse_int_list(text: str) -> List[int]:
|
| 54 |
+
return [int(chunk) for chunk in text.replace(",", " ").split() if chunk.strip()]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def percentile(values: Sequence[float], q: float) -> float:
|
| 58 |
+
clean = sorted(values)
|
| 59 |
+
if not clean:
|
| 60 |
+
return float("nan")
|
| 61 |
+
if len(clean) == 1:
|
| 62 |
+
return clean[0]
|
| 63 |
+
pos = (len(clean) - 1) * q
|
| 64 |
+
lo = int(pos)
|
| 65 |
+
hi = min(lo + 1, len(clean) - 1)
|
| 66 |
+
frac = pos - lo
|
| 67 |
+
return clean[lo] * (1.0 - frac) + clean[hi] * frac
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def summarize(values: Sequence[float]) -> Dict[str, float]:
|
| 71 |
+
if not values:
|
| 72 |
+
return {"mean": float("nan"), "median": float("nan"),
|
| 73 |
+
"p10": float("nan"), "p90": float("nan"),
|
| 74 |
+
"min": float("nan"), "max": float("nan"), "std": float("nan")}
|
| 75 |
+
return {
|
| 76 |
+
"mean": statistics.fmean(values),
|
| 77 |
+
"median": statistics.median(values),
|
| 78 |
+
"p10": percentile(values, 0.10),
|
| 79 |
+
"p90": percentile(values, 0.90),
|
| 80 |
+
"min": min(values),
|
| 81 |
+
"max": max(values),
|
| 82 |
+
"std": statistics.pstdev(values) if len(values) > 1 else 0.0,
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@dataclass
|
| 87 |
+
class RunTiming:
|
| 88 |
+
total_s: float
|
| 89 |
+
ttft_s: float # prefill proxy (arrival -> first token); nan if unavailable
|
| 90 |
+
decode_s: float # total - ttft; nan if ttft unavailable
|
| 91 |
+
gen_tokens: int
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def make_random_input_ids(rng: random.Random, length: int,
|
| 95 |
+
vocab_size: int, reserved: int) -> List[int]:
|
| 96 |
+
# Sample from a "safe" middle band of the vocab to avoid special / reserved ids.
|
| 97 |
+
lo = reserved
|
| 98 |
+
hi = max(reserved + 1, vocab_size - reserved)
|
| 99 |
+
return [rng.randrange(lo, hi) for _ in range(length)]
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def request_metrics_timing(request_output: object, total_s: float,
|
| 103 |
+
gen_tokens: int) -> RunTiming:
|
| 104 |
+
"""Break total time into prefill(TTFT) vs decode using vLLM request metrics.
|
| 105 |
+
|
| 106 |
+
metrics fields vary across vLLM versions; we defensively pull common ones and
|
| 107 |
+
fall back to nan when unavailable (then only `total_s` is meaningful).
|
| 108 |
+
"""
|
| 109 |
+
metrics = getattr(request_output, "metrics", None)
|
| 110 |
+
ttft = float("nan")
|
| 111 |
+
if metrics is not None:
|
| 112 |
+
arrival = getattr(metrics, "arrival_time", None)
|
| 113 |
+
first_scheduled = getattr(metrics, "first_scheduled_time", None)
|
| 114 |
+
first_token = getattr(metrics, "first_token_time", None)
|
| 115 |
+
start = arrival if arrival is not None else first_scheduled
|
| 116 |
+
if start is not None and first_token is not None:
|
| 117 |
+
ttft = max(0.0, float(first_token) - float(start))
|
| 118 |
+
decode = total_s - ttft if ttft == ttft else float("nan") # nan-safe
|
| 119 |
+
return RunTiming(total_s=total_s, ttft_s=ttft, decode_s=decode,
|
| 120 |
+
gen_tokens=gen_tokens)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def time_worker(llm: object, input_ids: Sequence[int], output_len: int,
|
| 124 |
+
sampling_cls, top_k: int, seed: int) -> RunTiming:
|
| 125 |
+
from vllm import SamplingParams # noqa: F401 (sampling_cls already SamplingParams)
|
| 126 |
+
|
| 127 |
+
params = sampling_cls(
|
| 128 |
+
temperature=0.0,
|
| 129 |
+
top_p=1.0,
|
| 130 |
+
top_k=-1,
|
| 131 |
+
max_tokens=output_len,
|
| 132 |
+
min_tokens=output_len, # pin exact output length ...
|
| 133 |
+
ignore_eos=True, # ... by never stopping at EOS
|
| 134 |
+
logprobs=top_k,
|
| 135 |
+
prompt_logprobs=None,
|
| 136 |
+
seed=seed,
|
| 137 |
+
detokenize=False,
|
| 138 |
+
)
|
| 139 |
+
prompt = make_tokens_prompt(input_ids)
|
| 140 |
+
t0 = time.perf_counter()
|
| 141 |
+
outputs = llm.generate([prompt], params)
|
| 142 |
+
total_s = time.perf_counter() - t0
|
| 143 |
+
completion = outputs[0].outputs[0]
|
| 144 |
+
gen_tokens = len(list(getattr(completion, "token_ids", [])))
|
| 145 |
+
timing = request_metrics_timing(outputs[0], total_s, gen_tokens)
|
| 146 |
+
output_ids = [int(t) for t in getattr(completion, "token_ids", [])]
|
| 147 |
+
return timing, output_ids
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def time_verifier(llm: object, input_ids: Sequence[int],
|
| 151 |
+
output_ids: Sequence[int], sampling_cls,
|
| 152 |
+
top_k: int, seed: int) -> RunTiming:
|
| 153 |
+
params = sampling_cls(
|
| 154 |
+
temperature=0.0,
|
| 155 |
+
top_p=1.0,
|
| 156 |
+
top_k=-1,
|
| 157 |
+
max_tokens=1,
|
| 158 |
+
prompt_logprobs=top_k,
|
| 159 |
+
logprobs=None,
|
| 160 |
+
seed=seed,
|
| 161 |
+
detokenize=False,
|
| 162 |
+
)
|
| 163 |
+
prompt = make_tokens_prompt(list(input_ids) + list(output_ids))
|
| 164 |
+
t0 = time.perf_counter()
|
| 165 |
+
outputs = llm.generate([prompt], params)
|
| 166 |
+
total_s = time.perf_counter() - t0
|
| 167 |
+
# verifier is a single forward: whole thing is "prefill".
|
| 168 |
+
return request_metrics_timing(outputs[0], total_s, gen_tokens=0)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def build_sampling_cls():
|
| 172 |
+
from vllm import SamplingParams
|
| 173 |
+
return SamplingParams
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 177 |
+
parser = argparse.ArgumentParser(
|
| 178 |
+
description="Benchmark worker vs verifier latency across input/output length grid."
|
| 179 |
+
)
|
| 180 |
+
# model / engine
|
| 181 |
+
parser.add_argument("--model", required=True)
|
| 182 |
+
parser.add_argument("--quantization", default="bf16")
|
| 183 |
+
parser.add_argument("--dtype", default="auto")
|
| 184 |
+
parser.add_argument("--trust-remote-code", action="store_true")
|
| 185 |
+
parser.add_argument("--tensor-parallel-size", type=int, default=1)
|
| 186 |
+
parser.add_argument("--gpu-memory-utilization", type=float, default=None)
|
| 187 |
+
parser.add_argument("--max-model-len", type=int, default=None)
|
| 188 |
+
parser.add_argument("--max-num-seqs", type=int, default=None)
|
| 189 |
+
parser.add_argument("--max-num-batched-tokens", type=int, default=None)
|
| 190 |
+
parser.add_argument("--max-logprobs", type=int, default=None,
|
| 191 |
+
help="Must be >= top-k; defaults to top-k when unset.")
|
| 192 |
+
# sweep grid
|
| 193 |
+
parser.add_argument("--input-lengths", default="128 512 1024 2048 4096",
|
| 194 |
+
help="Comma/space separated prefill input token counts.")
|
| 195 |
+
parser.add_argument("--output-lengths", default="1 16 64 256 1024",
|
| 196 |
+
help="Comma/space separated worker generation lengths.")
|
| 197 |
+
parser.add_argument("--top-k", type=int, default=20,
|
| 198 |
+
help="logprobs / prompt_logprobs top-k for both flows.")
|
| 199 |
+
# timing
|
| 200 |
+
parser.add_argument("--warmup", type=int, default=2)
|
| 201 |
+
parser.add_argument("--repeats", type=int, default=5)
|
| 202 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 203 |
+
parser.add_argument("--skip-verifier", action="store_true")
|
| 204 |
+
parser.add_argument("--skip-worker", action="store_true",
|
| 205 |
+
help="Verifier-only mode still needs output_ids; uses random ids.")
|
| 206 |
+
parser.add_argument("--max-total-tokens", type=int, default=0,
|
| 207 |
+
help="Skip a grid cell if input+output exceeds this (0=off).")
|
| 208 |
+
# output
|
| 209 |
+
parser.add_argument("--output-dir", default="results/worker_verifier_latency")
|
| 210 |
+
parser.add_argument("--gpu", default="", help="Free-form GPU label recorded in metadata.")
|
| 211 |
+
args = parser.parse_args(argv)
|
| 212 |
+
|
| 213 |
+
input_lengths = parse_int_list(args.input_lengths)
|
| 214 |
+
output_lengths = parse_int_list(args.output_lengths)
|
| 215 |
+
top_k = args.top_k
|
| 216 |
+
if args.max_logprobs is None:
|
| 217 |
+
args.max_logprobs = top_k
|
| 218 |
+
|
| 219 |
+
from transformers import AutoTokenizer
|
| 220 |
+
from vllm import LLM
|
| 221 |
+
|
| 222 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 223 |
+
args.model, trust_remote_code=args.trust_remote_code
|
| 224 |
+
)
|
| 225 |
+
vocab_size = int(getattr(tokenizer, "vocab_size", 0) or 32000)
|
| 226 |
+
|
| 227 |
+
llm_kwargs = build_llm_kwargs(args)
|
| 228 |
+
log(f"Loading vLLM with kwargs: {llm_kwargs}")
|
| 229 |
+
llm = LLM(**llm_kwargs)
|
| 230 |
+
sampling_cls = build_sampling_cls()
|
| 231 |
+
|
| 232 |
+
rng = random.Random(args.seed)
|
| 233 |
+
reserved = min(256, max(1, vocab_size // 100))
|
| 234 |
+
|
| 235 |
+
raw_rows: List[Dict[str, object]] = []
|
| 236 |
+
agg_rows: List[Dict[str, object]] = []
|
| 237 |
+
|
| 238 |
+
output_dir = Path(args.output_dir)
|
| 239 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 240 |
+
raw_path = output_dir / "latency_raw.jsonl"
|
| 241 |
+
raw_handle = raw_path.open("w", encoding="utf-8")
|
| 242 |
+
|
| 243 |
+
grid: List[Tuple[int, int]] = [
|
| 244 |
+
(i, o) for i in input_lengths for o in output_lengths
|
| 245 |
+
]
|
| 246 |
+
total_start = time.time()
|
| 247 |
+
|
| 248 |
+
for cell_idx, (in_len, out_len) in enumerate(grid, start=1):
|
| 249 |
+
total_tokens = in_len + out_len
|
| 250 |
+
if args.max_total_tokens and total_tokens > args.max_total_tokens:
|
| 251 |
+
log(f"[{cell_idx}/{len(grid)}] skip in={in_len} out={out_len} "
|
| 252 |
+
f"(total {total_tokens} > {args.max_total_tokens})")
|
| 253 |
+
continue
|
| 254 |
+
|
| 255 |
+
log(f"[{cell_idx}/{len(grid)}] input_len={in_len} output_len={out_len} "
|
| 256 |
+
f"warmup={args.warmup} repeats={args.repeats}")
|
| 257 |
+
|
| 258 |
+
worker_total: List[float] = []
|
| 259 |
+
worker_ttft: List[float] = []
|
| 260 |
+
worker_decode: List[float] = []
|
| 261 |
+
verifier_total: List[float] = []
|
| 262 |
+
worker_tok_s: List[float] = []
|
| 263 |
+
verifier_tok_s: List[float] = []
|
| 264 |
+
gen_tokens_seen = 0
|
| 265 |
+
|
| 266 |
+
n_iters = args.warmup + args.repeats
|
| 267 |
+
for it in range(n_iters):
|
| 268 |
+
measured = it >= args.warmup
|
| 269 |
+
iter_seed = args.seed + it
|
| 270 |
+
input_ids = make_random_input_ids(rng, in_len, vocab_size, reserved)
|
| 271 |
+
|
| 272 |
+
output_ids: List[int]
|
| 273 |
+
if not args.skip_worker:
|
| 274 |
+
w_timing, output_ids = time_worker(
|
| 275 |
+
llm, input_ids, out_len, sampling_cls, top_k, iter_seed
|
| 276 |
+
)
|
| 277 |
+
if measured:
|
| 278 |
+
worker_total.append(w_timing.total_s)
|
| 279 |
+
if w_timing.ttft_s == w_timing.ttft_s:
|
| 280 |
+
worker_ttft.append(w_timing.ttft_s)
|
| 281 |
+
worker_decode.append(w_timing.decode_s)
|
| 282 |
+
if w_timing.gen_tokens > 0:
|
| 283 |
+
worker_tok_s.append(w_timing.gen_tokens / w_timing.total_s)
|
| 284 |
+
gen_tokens_seen = w_timing.gen_tokens
|
| 285 |
+
else:
|
| 286 |
+
output_ids = make_random_input_ids(rng, out_len, vocab_size, reserved)
|
| 287 |
+
gen_tokens_seen = out_len
|
| 288 |
+
|
| 289 |
+
if not args.skip_verifier:
|
| 290 |
+
v_timing = time_verifier(
|
| 291 |
+
llm, input_ids, output_ids, sampling_cls, top_k, iter_seed
|
| 292 |
+
)
|
| 293 |
+
if measured:
|
| 294 |
+
verifier_total.append(v_timing.total_s)
|
| 295 |
+
verifier_tok_s.append(total_tokens / v_timing.total_s)
|
| 296 |
+
|
| 297 |
+
if measured:
|
| 298 |
+
raw_row = {
|
| 299 |
+
"input_len": in_len,
|
| 300 |
+
"output_len": out_len,
|
| 301 |
+
"total_tokens": total_tokens,
|
| 302 |
+
"iter": it - args.warmup,
|
| 303 |
+
"worker_total_s": (worker_total[-1] if worker_total and not args.skip_worker else None),
|
| 304 |
+
"verifier_total_s": (verifier_total[-1] if verifier_total and not args.skip_verifier else None),
|
| 305 |
+
}
|
| 306 |
+
raw_handle.write(json.dumps(raw_row, ensure_ascii=False) + "\n")
|
| 307 |
+
raw_handle.flush()
|
| 308 |
+
|
| 309 |
+
w_sum = summarize(worker_total)
|
| 310 |
+
v_sum = summarize(verifier_total)
|
| 311 |
+
ttft_sum = summarize(worker_ttft)
|
| 312 |
+
decode_sum = summarize(worker_decode)
|
| 313 |
+
ratio_median = (
|
| 314 |
+
w_sum["median"] / v_sum["median"]
|
| 315 |
+
if v_sum["median"] == v_sum["median"] and v_sum["median"] > 0
|
| 316 |
+
and w_sum["median"] == w_sum["median"]
|
| 317 |
+
else float("nan")
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
agg = {
|
| 321 |
+
"input_len": in_len,
|
| 322 |
+
"output_len": out_len,
|
| 323 |
+
"total_tokens": total_tokens,
|
| 324 |
+
"gen_tokens": gen_tokens_seen,
|
| 325 |
+
"worker_total_median_s": w_sum["median"],
|
| 326 |
+
"worker_total_mean_s": w_sum["mean"],
|
| 327 |
+
"worker_total_p10_s": w_sum["p10"],
|
| 328 |
+
"worker_total_p90_s": w_sum["p90"],
|
| 329 |
+
"worker_ttft_median_s": ttft_sum["median"],
|
| 330 |
+
"worker_decode_median_s": decode_sum["median"],
|
| 331 |
+
"worker_tok_per_s_median": summarize(worker_tok_s)["median"],
|
| 332 |
+
"verifier_total_median_s": v_sum["median"],
|
| 333 |
+
"verifier_total_mean_s": v_sum["mean"],
|
| 334 |
+
"verifier_total_p10_s": v_sum["p10"],
|
| 335 |
+
"verifier_total_p90_s": v_sum["p90"],
|
| 336 |
+
"verifier_tok_per_s_median": summarize(verifier_tok_s)["median"],
|
| 337 |
+
"worker_over_verifier_median": ratio_median,
|
| 338 |
+
}
|
| 339 |
+
agg_rows.append(agg)
|
| 340 |
+
log(
|
| 341 |
+
f" worker median={w_sum['median']:.4f}s "
|
| 342 |
+
f"(ttft={ttft_sum['median']:.4f}s decode={decode_sum['median']:.4f}s) | "
|
| 343 |
+
f"verifier median={v_sum['median']:.4f}s | "
|
| 344 |
+
f"worker/verifier={ratio_median:.3f}"
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
raw_handle.close()
|
| 348 |
+
|
| 349 |
+
# aggregated CSV
|
| 350 |
+
fields = [
|
| 351 |
+
"input_len", "output_len", "total_tokens", "gen_tokens",
|
| 352 |
+
"worker_total_median_s", "worker_total_mean_s",
|
| 353 |
+
"worker_total_p10_s", "worker_total_p90_s",
|
| 354 |
+
"worker_ttft_median_s", "worker_decode_median_s",
|
| 355 |
+
"worker_tok_per_s_median",
|
| 356 |
+
"verifier_total_median_s", "verifier_total_mean_s",
|
| 357 |
+
"verifier_total_p10_s", "verifier_total_p90_s",
|
| 358 |
+
"verifier_tok_per_s_median",
|
| 359 |
+
"worker_over_verifier_median",
|
| 360 |
+
]
|
| 361 |
+
csv_path = output_dir / "latency_summary.csv"
|
| 362 |
+
with csv_path.open("w", encoding="utf-8", newline="") as handle:
|
| 363 |
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
| 364 |
+
writer.writeheader()
|
| 365 |
+
for row in agg_rows:
|
| 366 |
+
writer.writerow({f: row.get(f, "") for f in fields})
|
| 367 |
+
|
| 368 |
+
write_markdown_summary(output_dir / "summary.md", agg_rows, args, top_k)
|
| 369 |
+
|
| 370 |
+
write_json(output_dir / "metadata.json", {
|
| 371 |
+
"metadata": runtime_metadata(sys.argv),
|
| 372 |
+
"args": vars(args),
|
| 373 |
+
"vllm_version": vllm_version(),
|
| 374 |
+
"vocab_size": vocab_size,
|
| 375 |
+
"cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"),
|
| 376 |
+
"input_lengths": input_lengths,
|
| 377 |
+
"output_lengths": output_lengths,
|
| 378 |
+
"elapsed_seconds": time.time() - total_start,
|
| 379 |
+
"cell_count": len(agg_rows),
|
| 380 |
+
})
|
| 381 |
+
|
| 382 |
+
log(f"Wrote {csv_path}")
|
| 383 |
+
log(f"Wrote {raw_path}")
|
| 384 |
+
log(f"Wrote {output_dir / 'summary.md'}")
|
| 385 |
+
log(f"Done in {time.time() - total_start:.1f}s")
|
| 386 |
+
return 0
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def write_markdown_summary(path: Path, rows: Sequence[Dict[str, object]],
|
| 390 |
+
args: argparse.Namespace, top_k: int) -> None:
|
| 391 |
+
def fmt(x: object) -> str:
|
| 392 |
+
try:
|
| 393 |
+
v = float(x) # type: ignore[arg-type]
|
| 394 |
+
if v != v:
|
| 395 |
+
return "-"
|
| 396 |
+
return f"{v:.4f}"
|
| 397 |
+
except (TypeError, ValueError):
|
| 398 |
+
return "-"
|
| 399 |
+
|
| 400 |
+
lines = [
|
| 401 |
+
"# Worker vs Verifier latency benchmark",
|
| 402 |
+
"",
|
| 403 |
+
f"- model: `{args.model}` (quant={args.quantization}, dtype={args.dtype})",
|
| 404 |
+
f"- top_k logprobs: {top_k}",
|
| 405 |
+
f"- warmup={args.warmup}, repeats={args.repeats}, tp={args.tensor_parallel_size}",
|
| 406 |
+
f"- gpu: {args.gpu or '(unset)'}",
|
| 407 |
+
"",
|
| 408 |
+
"Worker = prefill(input) + decode(output_len). "
|
| 409 |
+
"Verifier = single prefill over input+output for top-k prompt logprobs.",
|
| 410 |
+
"",
|
| 411 |
+
"| input | output | total | worker med (s) | w ttft | w decode | "
|
| 412 |
+
"verifier med (s) | worker/verifier |",
|
| 413 |
+
"|---:|---:|---:|---:|---:|---:|---:|---:|",
|
| 414 |
+
]
|
| 415 |
+
for r in rows:
|
| 416 |
+
lines.append(
|
| 417 |
+
"| {inl} | {outl} | {tot} | {wt} | {ttft} | {dec} | {vt} | {ratio} |".format(
|
| 418 |
+
inl=r["input_len"], outl=r["output_len"], tot=r["total_tokens"],
|
| 419 |
+
wt=fmt(r["worker_total_median_s"]),
|
| 420 |
+
ttft=fmt(r["worker_ttft_median_s"]),
|
| 421 |
+
dec=fmt(r["worker_decode_median_s"]),
|
| 422 |
+
vt=fmt(r["verifier_total_median_s"]),
|
| 423 |
+
ratio=fmt(r["worker_over_verifier_median"]),
|
| 424 |
+
)
|
| 425 |
+
)
|
| 426 |
+
lines.append("")
|
| 427 |
+
lines.append("Notes:")
|
| 428 |
+
lines.append("- `worker/verifier` > 1 means the worker (generation) is slower "
|
| 429 |
+
"than the verifier (single prefill) for that cell.")
|
| 430 |
+
lines.append("- ttft/decode split comes from vLLM request metrics; shown as `-` "
|
| 431 |
+
"when the running vLLM version does not expose them.")
|
| 432 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
if __name__ == "__main__":
|
| 436 |
+
raise SystemExit(main())
|
tools/vllm_worker_verify_pipeline/calibrate_vllm_worker_verify_params.py
ADDED
|
@@ -0,0 +1,609 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import csv
|
| 6 |
+
import json
|
| 7 |
+
import math
|
| 8 |
+
import platform
|
| 9 |
+
import sys
|
| 10 |
+
import time
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from types import SimpleNamespace
|
| 13 |
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
| 14 |
+
|
| 15 |
+
from analyze_vllm_worker_verify import (
|
| 16 |
+
FP_SCALE,
|
| 17 |
+
JUDGMENT_FUNCTION_VERSION,
|
| 18 |
+
LOWER_BOUND_METRICS,
|
| 19 |
+
METRICS_FILENAME,
|
| 20 |
+
SAMPLE_THRESHOLD_METRICS,
|
| 21 |
+
UPPER_BOUND_METRICS,
|
| 22 |
+
collect_fields,
|
| 23 |
+
evaluate_sample,
|
| 24 |
+
fp_1e6,
|
| 25 |
+
mean,
|
| 26 |
+
model_selector_matches,
|
| 27 |
+
quantile,
|
| 28 |
+
resolve_inputs,
|
| 29 |
+
safe_float,
|
| 30 |
+
safe_int,
|
| 31 |
+
summarize_sample_rows,
|
| 32 |
+
process_metrics_file,
|
| 33 |
+
write_csv,
|
| 34 |
+
write_json,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def log(message: str) -> None:
|
| 39 |
+
print(message, flush=True)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def runtime_metadata(argv: Sequence[str]) -> Dict[str, Any]:
|
| 43 |
+
return {
|
| 44 |
+
"created_at_unix": time.time(),
|
| 45 |
+
"python": sys.version,
|
| 46 |
+
"platform": platform.platform(),
|
| 47 |
+
"argv": list(argv),
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def finite_values(rows: Sequence[Dict[str, Any]], metric: str) -> List[float]:
|
| 52 |
+
return [
|
| 53 |
+
value
|
| 54 |
+
for value in (safe_float(row.get(metric)) for row in rows)
|
| 55 |
+
if math.isfinite(value)
|
| 56 |
+
]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def metric_direction(metric: str) -> str:
|
| 60 |
+
if metric in UPPER_BOUND_METRICS:
|
| 61 |
+
return "upper_is_worse"
|
| 62 |
+
if metric in LOWER_BOUND_METRICS:
|
| 63 |
+
return "lower_is_worse"
|
| 64 |
+
raise ValueError(f"Unknown metric: {metric}")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def threshold_key(metric: str, bound: str) -> str:
|
| 68 |
+
return f"{metric}_{bound}"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def metric_stats(values: Sequence[float]) -> Dict[str, Any]:
|
| 72 |
+
finite = [value for value in values if math.isfinite(value)]
|
| 73 |
+
return {
|
| 74 |
+
"count": len(finite),
|
| 75 |
+
"min": min(finite, default=float("nan")),
|
| 76 |
+
"p01": quantile(finite, 0.01),
|
| 77 |
+
"p05": quantile(finite, 0.05),
|
| 78 |
+
"p50": quantile(finite, 0.50),
|
| 79 |
+
"p90": quantile(finite, 0.90),
|
| 80 |
+
"p95": quantile(finite, 0.95),
|
| 81 |
+
"p99": quantile(finite, 0.99),
|
| 82 |
+
"max": max(finite, default=float("nan")),
|
| 83 |
+
"mean": mean(finite),
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def pass_rate(values: Sequence[float], metric: str, bound: float) -> float:
|
| 88 |
+
finite = [value for value in values if math.isfinite(value)]
|
| 89 |
+
if not finite or not math.isfinite(bound):
|
| 90 |
+
return float("nan")
|
| 91 |
+
if metric in UPPER_BOUND_METRICS:
|
| 92 |
+
return sum(1 for value in finite if value <= bound) / len(finite)
|
| 93 |
+
return sum(1 for value in finite if value >= bound) / len(finite)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def reject_rate(values: Sequence[float], metric: str, bound: float) -> float:
|
| 97 |
+
finite = [value for value in values if math.isfinite(value)]
|
| 98 |
+
if not finite or not math.isfinite(bound):
|
| 99 |
+
return float("nan")
|
| 100 |
+
if metric in UPPER_BOUND_METRICS:
|
| 101 |
+
return sum(1 for value in finite if value > bound) / len(finite)
|
| 102 |
+
return sum(1 for value in finite if value < bound) / len(finite)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def midpoint_candidates(values: Sequence[float]) -> List[float]:
|
| 106 |
+
finite = sorted(set(value for value in values if math.isfinite(value)))
|
| 107 |
+
if not finite:
|
| 108 |
+
return []
|
| 109 |
+
if len(finite) == 1:
|
| 110 |
+
return finite
|
| 111 |
+
candidates = [finite[0]]
|
| 112 |
+
for left, right in zip(finite, finite[1:]):
|
| 113 |
+
candidates.append((left + right) / 2.0)
|
| 114 |
+
candidates.append(finite[-1])
|
| 115 |
+
return candidates
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def optimize_reject_bound(
|
| 119 |
+
base_values: Sequence[float],
|
| 120 |
+
challenger_values: Sequence[float],
|
| 121 |
+
metric: str,
|
| 122 |
+
*,
|
| 123 |
+
max_base_reject_rate: float,
|
| 124 |
+
) -> Tuple[float, float, float, float]:
|
| 125 |
+
candidates = midpoint_candidates([*base_values, *challenger_values])
|
| 126 |
+
if not candidates:
|
| 127 |
+
return float("nan"), float("nan"), float("nan"), float("nan")
|
| 128 |
+
|
| 129 |
+
best: Optional[Tuple[float, float, float, float]] = None
|
| 130 |
+
for candidate in candidates:
|
| 131 |
+
base_fp = reject_rate(base_values, metric, candidate)
|
| 132 |
+
challenger_tp = reject_rate(challenger_values, metric, candidate)
|
| 133 |
+
if not math.isfinite(base_fp) or not math.isfinite(challenger_tp):
|
| 134 |
+
continue
|
| 135 |
+
if base_fp > max_base_reject_rate:
|
| 136 |
+
continue
|
| 137 |
+
youden = challenger_tp - base_fp
|
| 138 |
+
score = (youden, challenger_tp, -base_fp)
|
| 139 |
+
if best is None or score > (best[3], best[2], -best[1]):
|
| 140 |
+
best = (candidate, base_fp, challenger_tp, youden)
|
| 141 |
+
if best is not None:
|
| 142 |
+
return best
|
| 143 |
+
|
| 144 |
+
# Fallback: no candidate satisfies the base false reject constraint.
|
| 145 |
+
if metric in UPPER_BOUND_METRICS:
|
| 146 |
+
candidate = quantile(base_values, 1.0 - max_base_reject_rate)
|
| 147 |
+
else:
|
| 148 |
+
candidate = quantile(base_values, max_base_reject_rate)
|
| 149 |
+
base_fp = reject_rate(base_values, metric, candidate)
|
| 150 |
+
challenger_tp = reject_rate(challenger_values, metric, candidate)
|
| 151 |
+
return candidate, base_fp, challenger_tp, challenger_tp - base_fp
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def calibrated_pass_bound(base_values: Sequence[float], metric: str,
|
| 155 |
+
target_base_pass_rate: float,
|
| 156 |
+
safety_multiplier: float,
|
| 157 |
+
lower_margin: float) -> float:
|
| 158 |
+
if metric == "missing_compared_count":
|
| 159 |
+
return max(base_values, default=0.0)
|
| 160 |
+
if metric in UPPER_BOUND_METRICS:
|
| 161 |
+
value = quantile(base_values, target_base_pass_rate)
|
| 162 |
+
return value * safety_multiplier if value >= 0.0 else value / safety_multiplier
|
| 163 |
+
value = quantile(base_values, 1.0 - target_base_pass_rate)
|
| 164 |
+
return max(0.0, value - lower_margin)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def calibrated_reject_bound(base_values: Sequence[float],
|
| 168 |
+
challenger_values: Sequence[float],
|
| 169 |
+
metric: str,
|
| 170 |
+
*,
|
| 171 |
+
max_base_reject_rate: float,
|
| 172 |
+
pass_bound: float) -> Tuple[float, float, float, float]:
|
| 173 |
+
if metric == "missing_compared_count":
|
| 174 |
+
bound = pass_bound + 1
|
| 175 |
+
return (
|
| 176 |
+
bound,
|
| 177 |
+
reject_rate(base_values, metric, bound),
|
| 178 |
+
reject_rate(challenger_values, metric, bound),
|
| 179 |
+
reject_rate(challenger_values, metric, bound) - reject_rate(base_values, metric, bound),
|
| 180 |
+
)
|
| 181 |
+
optimized, base_fp, challenger_tp, youden = optimize_reject_bound(
|
| 182 |
+
base_values,
|
| 183 |
+
challenger_values,
|
| 184 |
+
metric,
|
| 185 |
+
max_base_reject_rate=max_base_reject_rate,
|
| 186 |
+
)
|
| 187 |
+
if not math.isfinite(optimized):
|
| 188 |
+
return optimized, base_fp, challenger_tp, youden
|
| 189 |
+
if metric in UPPER_BOUND_METRICS:
|
| 190 |
+
optimized = max(optimized, pass_bound)
|
| 191 |
+
else:
|
| 192 |
+
optimized = min(optimized, pass_bound)
|
| 193 |
+
return (
|
| 194 |
+
optimized,
|
| 195 |
+
reject_rate(base_values, metric, optimized),
|
| 196 |
+
reject_rate(challenger_values, metric, optimized),
|
| 197 |
+
reject_rate(challenger_values, metric, optimized) - reject_rate(base_values, metric, optimized),
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def separation_gap(base_stats: Dict[str, Any],
|
| 202 |
+
challenger_stats: Dict[str, Any],
|
| 203 |
+
metric: str) -> float:
|
| 204 |
+
if metric in UPPER_BOUND_METRICS:
|
| 205 |
+
return safe_float(challenger_stats.get("p50")) - safe_float(base_stats.get("p99"))
|
| 206 |
+
return safe_float(base_stats.get("p01")) - safe_float(challenger_stats.get("p50"))
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def calibrate_metric(
|
| 210 |
+
metric: str,
|
| 211 |
+
base_samples: Sequence[Dict[str, Any]],
|
| 212 |
+
challenger_samples: Sequence[Dict[str, Any]],
|
| 213 |
+
args: argparse.Namespace,
|
| 214 |
+
) -> Dict[str, Any]:
|
| 215 |
+
base_values = finite_values(base_samples, metric)
|
| 216 |
+
challenger_values = finite_values(challenger_samples, metric)
|
| 217 |
+
base_stats = metric_stats(base_values)
|
| 218 |
+
challenger_stats = metric_stats(challenger_values)
|
| 219 |
+
pass_bound = calibrated_pass_bound(
|
| 220 |
+
base_values,
|
| 221 |
+
metric,
|
| 222 |
+
args.target_base_pass_rate,
|
| 223 |
+
args.pass_safety_multiplier,
|
| 224 |
+
args.lower_margin,
|
| 225 |
+
)
|
| 226 |
+
reject_bound, base_false_reject_rate, challenger_reject_rate, youden = calibrated_reject_bound(
|
| 227 |
+
base_values,
|
| 228 |
+
challenger_values,
|
| 229 |
+
metric,
|
| 230 |
+
max_base_reject_rate=args.max_base_false_reject_rate,
|
| 231 |
+
pass_bound=pass_bound,
|
| 232 |
+
)
|
| 233 |
+
bound_type = "max" if metric in UPPER_BOUND_METRICS else "min"
|
| 234 |
+
row: Dict[str, Any] = {
|
| 235 |
+
"metric": metric,
|
| 236 |
+
"direction": metric_direction(metric),
|
| 237 |
+
"threshold_key": threshold_key(metric, bound_type),
|
| 238 |
+
"pass_bound": pass_bound,
|
| 239 |
+
"pass_bound_fp_1e6": fp_1e6(pass_bound),
|
| 240 |
+
"reject_bound": reject_bound,
|
| 241 |
+
"reject_bound_fp_1e6": fp_1e6(reject_bound),
|
| 242 |
+
"base_count": len(base_values),
|
| 243 |
+
"challenger_count": len(challenger_values),
|
| 244 |
+
"base_pass_rate_at_pass_bound": pass_rate(base_values, metric, pass_bound),
|
| 245 |
+
"challenger_pass_rate_at_pass_bound": pass_rate(challenger_values, metric, pass_bound),
|
| 246 |
+
"base_false_reject_rate_at_reject_bound": base_false_reject_rate,
|
| 247 |
+
"challenger_reject_rate_at_reject_bound": challenger_reject_rate,
|
| 248 |
+
"youden_at_reject_bound": youden,
|
| 249 |
+
"separation_gap": separation_gap(base_stats, challenger_stats, metric),
|
| 250 |
+
"base_min": base_stats["min"],
|
| 251 |
+
"base_p50": base_stats["p50"],
|
| 252 |
+
"base_p95": base_stats["p95"],
|
| 253 |
+
"base_p99": base_stats["p99"],
|
| 254 |
+
"base_max": base_stats["max"],
|
| 255 |
+
"challenger_min": challenger_stats["min"],
|
| 256 |
+
"challenger_p50": challenger_stats["p50"],
|
| 257 |
+
"challenger_p95": challenger_stats["p95"],
|
| 258 |
+
"challenger_p99": challenger_stats["p99"],
|
| 259 |
+
"challenger_max": challenger_stats["max"],
|
| 260 |
+
}
|
| 261 |
+
return row
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def thresholds_from_calibration(metric_rows: Sequence[Dict[str, Any]],
|
| 265 |
+
args: argparse.Namespace) -> Dict[str, Any]:
|
| 266 |
+
pass_thresholds: Dict[str, Any] = {}
|
| 267 |
+
reject_thresholds: Dict[str, Any] = {}
|
| 268 |
+
pass_fp_1e6: Dict[str, Any] = {}
|
| 269 |
+
reject_fp_1e6: Dict[str, Any] = {}
|
| 270 |
+
for row in metric_rows:
|
| 271 |
+
key = str(row["threshold_key"])
|
| 272 |
+
pass_thresholds[key] = safe_float(row.get("pass_bound"))
|
| 273 |
+
reject_thresholds[key] = safe_float(row.get("reject_bound"))
|
| 274 |
+
pass_fp_1e6[key] = safe_int(row.get("pass_bound_fp_1e6"), "")
|
| 275 |
+
reject_fp_1e6[key] = safe_int(row.get("reject_bound_fp_1e6"), "")
|
| 276 |
+
return {
|
| 277 |
+
"source": "calibrated_from_experiment_data",
|
| 278 |
+
"judgment_function_version": JUDGMENT_FUNCTION_VERSION,
|
| 279 |
+
"token_scope": "ALL_GENERATED_OUTPUT_TOKENS",
|
| 280 |
+
"pass": pass_thresholds,
|
| 281 |
+
"reject": reject_thresholds,
|
| 282 |
+
"pass_fp_1e6": pass_fp_1e6,
|
| 283 |
+
"reject_fp_1e6": reject_fp_1e6,
|
| 284 |
+
"calibration_policy": {
|
| 285 |
+
"target_base_pass_rate_per_metric": args.target_base_pass_rate,
|
| 286 |
+
"max_base_false_reject_rate_per_metric": args.max_base_false_reject_rate,
|
| 287 |
+
"pass_safety_multiplier": args.pass_safety_multiplier,
|
| 288 |
+
"lower_margin": args.lower_margin,
|
| 289 |
+
"reject_bound_selection": (
|
| 290 |
+
"maximize challenger reject rate / Youden subject to base false "
|
| 291 |
+
"reject constraint, then keep reject bound outside pass bound"
|
| 292 |
+
),
|
| 293 |
+
},
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def apply_thresholds(samples: Sequence[Dict[str, Any]], thresholds: Dict[str, Any]) -> None:
|
| 298 |
+
for row in samples:
|
| 299 |
+
evaluate_sample(row, thresholds)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def split_samples(sample_rows: Sequence[Dict[str, Any]],
|
| 303 |
+
args: argparse.Namespace) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
|
| 304 |
+
base = [row for row in sample_rows if row.get("model_role") == "base"]
|
| 305 |
+
challengers = [row for row in sample_rows if row.get("model_role") != "base"]
|
| 306 |
+
if args.challenger_run or args.challenger_model:
|
| 307 |
+
challengers = [
|
| 308 |
+
row for row in challengers
|
| 309 |
+
if challenger_selector_matches(row, args.challenger_run, args.challenger_model)
|
| 310 |
+
]
|
| 311 |
+
return base, challengers
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def challenger_selector_matches(row: Dict[str, Any],
|
| 315 |
+
challenger_runs: Sequence[str],
|
| 316 |
+
challenger_models: Sequence[str]) -> bool:
|
| 317 |
+
haystack = " ".join(
|
| 318 |
+
str(row.get(key, ""))
|
| 319 |
+
for key in [
|
| 320 |
+
"run_id",
|
| 321 |
+
"worker_variant_id",
|
| 322 |
+
"verifier_variant_id",
|
| 323 |
+
"worker_model",
|
| 324 |
+
"verifier_model",
|
| 325 |
+
"metrics_path",
|
| 326 |
+
]
|
| 327 |
+
).lower()
|
| 328 |
+
for selector in challenger_runs:
|
| 329 |
+
if selector.lower() in haystack:
|
| 330 |
+
return True
|
| 331 |
+
for selector in challenger_models:
|
| 332 |
+
if model_selector_matches(selector, str(row.get("verifier_model", ""))):
|
| 333 |
+
return True
|
| 334 |
+
if model_selector_matches(selector, str(row.get("verifier_variant_id", ""))):
|
| 335 |
+
return True
|
| 336 |
+
return False
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def verdict_counts(samples: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
|
| 340 |
+
counts = {"PASS": 0, "REJECT": 0, "INCONCLUSIVE": 0}
|
| 341 |
+
for row in samples:
|
| 342 |
+
verdict = str(row.get("metric_sample_verdict", ""))
|
| 343 |
+
if verdict in counts:
|
| 344 |
+
counts[verdict] += 1
|
| 345 |
+
total = sum(counts.values())
|
| 346 |
+
return {
|
| 347 |
+
"sample_count": total,
|
| 348 |
+
"pass_count": counts["PASS"],
|
| 349 |
+
"reject_count": counts["REJECT"],
|
| 350 |
+
"inconclusive_count": counts["INCONCLUSIVE"],
|
| 351 |
+
"pass_rate": counts["PASS"] / total if total else "",
|
| 352 |
+
"reject_rate": counts["REJECT"] / total if total else "",
|
| 353 |
+
"inconclusive_rate": counts["INCONCLUSIVE"] / total if total else "",
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def build_group_rows(samples: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 358 |
+
grouped: Dict[Tuple[str, str, str], List[Dict[str, Any]]] = {}
|
| 359 |
+
for row in samples:
|
| 360 |
+
key = (
|
| 361 |
+
str(row.get("model_role", "")),
|
| 362 |
+
str(row.get("verifier_variant_id", "")),
|
| 363 |
+
str(row.get("verifier_model", "")),
|
| 364 |
+
)
|
| 365 |
+
grouped.setdefault(key, []).append(row)
|
| 366 |
+
out = []
|
| 367 |
+
for (role, variant, model), rows in sorted(grouped.items()):
|
| 368 |
+
summary = summarize_sample_rows(rows, variant or model or role)
|
| 369 |
+
summary.update({
|
| 370 |
+
"model_role": role,
|
| 371 |
+
"verifier_variant_id": variant,
|
| 372 |
+
"verifier_model": model,
|
| 373 |
+
**verdict_counts(rows),
|
| 374 |
+
})
|
| 375 |
+
out.append(summary)
|
| 376 |
+
return out
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def write_markdown(path: Path,
|
| 380 |
+
metric_rows: Sequence[Dict[str, Any]],
|
| 381 |
+
group_rows: Sequence[Dict[str, Any]],
|
| 382 |
+
thresholds: Dict[str, Any],
|
| 383 |
+
base_count: int,
|
| 384 |
+
challenger_count: int) -> None:
|
| 385 |
+
lines = [
|
| 386 |
+
"# vLLM worker verify parameter calibration",
|
| 387 |
+
"",
|
| 388 |
+
f"- judgment_function_version: `{JUDGMENT_FUNCTION_VERSION}`",
|
| 389 |
+
f"- base samples: {base_count}",
|
| 390 |
+
f"- challenger samples: {challenger_count}",
|
| 391 |
+
f"- threshold output: `recommended_thresholds.json`",
|
| 392 |
+
"",
|
| 393 |
+
"## Recommended Thresholds",
|
| 394 |
+
"",
|
| 395 |
+
"| metric | pass bound | reject bound | base pass | challenger pass | base false reject | challenger reject | separation gap |",
|
| 396 |
+
"|---|---:|---:|---:|---:|---:|---:|---:|",
|
| 397 |
+
]
|
| 398 |
+
for row in metric_rows:
|
| 399 |
+
lines.append(
|
| 400 |
+
"| {metric} | {pass_bound:.8g} | {reject_bound:.8g} | {base_pass:.6g} | {challenger_pass:.6g} | {base_reject:.6g} | {challenger_reject:.6g} | {gap:.8g} |".format(
|
| 401 |
+
metric=row.get("metric", ""),
|
| 402 |
+
pass_bound=safe_float(row.get("pass_bound")),
|
| 403 |
+
reject_bound=safe_float(row.get("reject_bound")),
|
| 404 |
+
base_pass=safe_float(row.get("base_pass_rate_at_pass_bound")),
|
| 405 |
+
challenger_pass=safe_float(row.get("challenger_pass_rate_at_pass_bound")),
|
| 406 |
+
base_reject=safe_float(row.get("base_false_reject_rate_at_reject_bound")),
|
| 407 |
+
challenger_reject=safe_float(row.get("challenger_reject_rate_at_reject_bound")),
|
| 408 |
+
gap=safe_float(row.get("separation_gap")),
|
| 409 |
+
)
|
| 410 |
+
)
|
| 411 |
+
lines.extend([
|
| 412 |
+
"",
|
| 413 |
+
"## Combined Sample Verdicts",
|
| 414 |
+
"",
|
| 415 |
+
"| role | verifier | samples | pass | reject | inconclusive | pass rate | reject rate |",
|
| 416 |
+
"|---|---|---:|---:|---:|---:|---:|---:|",
|
| 417 |
+
])
|
| 418 |
+
for row in group_rows:
|
| 419 |
+
lines.append(
|
| 420 |
+
"| {role} | {verifier} | {samples} | {passed} | {rejected} | {inc} | {pass_rate:.6g} | {reject_rate:.6g} |".format(
|
| 421 |
+
role=row.get("model_role", ""),
|
| 422 |
+
verifier=row.get("verifier_variant_id") or row.get("verifier_model", ""),
|
| 423 |
+
samples=row.get("sample_count", ""),
|
| 424 |
+
passed=row.get("pass_count", ""),
|
| 425 |
+
rejected=row.get("reject_count", ""),
|
| 426 |
+
inc=row.get("inconclusive_count", ""),
|
| 427 |
+
pass_rate=safe_float(row.get("pass_rate")),
|
| 428 |
+
reject_rate=safe_float(row.get("reject_rate")),
|
| 429 |
+
)
|
| 430 |
+
)
|
| 431 |
+
lines.extend([
|
| 432 |
+
"",
|
| 433 |
+
"## Notes",
|
| 434 |
+
"",
|
| 435 |
+
"- PASS bounds are calibrated to retain base samples per metric.",
|
| 436 |
+
"- REJECT bounds are calibrated to reject challengers while respecting the base false-reject constraint.",
|
| 437 |
+
"- This is an experiment-derived recommendation; protocol values still need profile/governance review.",
|
| 438 |
+
"",
|
| 439 |
+
])
|
| 440 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def make_parser() -> argparse.ArgumentParser:
|
| 444 |
+
parser = argparse.ArgumentParser(
|
| 445 |
+
description=(
|
| 446 |
+
"Calibrate PREFILL_GENERATED_TOKEN_METRICS_V1 threshold parameters "
|
| 447 |
+
"from base-model and challenger-model experiment data."
|
| 448 |
+
)
|
| 449 |
+
)
|
| 450 |
+
parser.add_argument(
|
| 451 |
+
"--input",
|
| 452 |
+
action="append",
|
| 453 |
+
default=[],
|
| 454 |
+
help=(
|
| 455 |
+
"Metrics CSV, verifier output dir, or root dir to scan recursively. "
|
| 456 |
+
"Repeat as needed. Defaults to results/vllm_worker_verify_runs."
|
| 457 |
+
),
|
| 458 |
+
)
|
| 459 |
+
parser.add_argument("--output-dir", default="calibration")
|
| 460 |
+
parser.add_argument(
|
| 461 |
+
"--base-run",
|
| 462 |
+
action="append",
|
| 463 |
+
default=[],
|
| 464 |
+
help="Substring marking a run/path/variant as base. Repeat as needed.",
|
| 465 |
+
)
|
| 466 |
+
parser.add_argument(
|
| 467 |
+
"--base-model",
|
| 468 |
+
action="append",
|
| 469 |
+
default=[],
|
| 470 |
+
help="Exact model name or path basename marking a verifier model as base.",
|
| 471 |
+
)
|
| 472 |
+
parser.add_argument(
|
| 473 |
+
"--challenger-run",
|
| 474 |
+
action="append",
|
| 475 |
+
default=[],
|
| 476 |
+
help="Optional substring filter for challenger runs. Repeat as needed.",
|
| 477 |
+
)
|
| 478 |
+
parser.add_argument(
|
| 479 |
+
"--challenger-model",
|
| 480 |
+
action="append",
|
| 481 |
+
default=[],
|
| 482 |
+
help="Optional exact model name/path basename filter for challenger models.",
|
| 483 |
+
)
|
| 484 |
+
parser.add_argument("--target-base-pass-rate", type=float, default=0.99)
|
| 485 |
+
parser.add_argument("--max-base-false-reject-rate", type=float, default=0.01)
|
| 486 |
+
parser.add_argument("--pass-safety-multiplier", type=float, default=1.10)
|
| 487 |
+
parser.add_argument("--lower-margin", type=float, default=0.02)
|
| 488 |
+
return parser
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 492 |
+
parser = make_parser()
|
| 493 |
+
args = parser.parse_args(argv)
|
| 494 |
+
input_paths = args.input or ["results/vllm_worker_verify_runs"]
|
| 495 |
+
metrics_files = resolve_inputs(input_paths)
|
| 496 |
+
if not metrics_files:
|
| 497 |
+
parser.error(f"No {METRICS_FILENAME} files found")
|
| 498 |
+
if not args.base_run and not args.base_model:
|
| 499 |
+
parser.error("At least one --base-run or --base-model selector is required")
|
| 500 |
+
|
| 501 |
+
process_args = SimpleNamespace(
|
| 502 |
+
base_run=args.base_run,
|
| 503 |
+
base_model=args.base_model,
|
| 504 |
+
top_outliers_per_run=0,
|
| 505 |
+
)
|
| 506 |
+
processed = [process_metrics_file(path, process_args) for path in metrics_files]
|
| 507 |
+
sample_rows = [row for item in processed for row in item["sample_rows"]]
|
| 508 |
+
base_samples, challenger_samples = split_samples(sample_rows, args)
|
| 509 |
+
if not base_samples:
|
| 510 |
+
parser.error("No base samples matched. Check --base-run / --base-model.")
|
| 511 |
+
if not challenger_samples:
|
| 512 |
+
parser.error("No challenger samples matched. Check inputs or challenger filters.")
|
| 513 |
+
|
| 514 |
+
metric_rows = [
|
| 515 |
+
calibrate_metric(metric, base_samples, challenger_samples, args)
|
| 516 |
+
for metric in SAMPLE_THRESHOLD_METRICS
|
| 517 |
+
]
|
| 518 |
+
thresholds = thresholds_from_calibration(metric_rows, args)
|
| 519 |
+
apply_thresholds(sample_rows, thresholds)
|
| 520 |
+
group_rows = build_group_rows(sample_rows)
|
| 521 |
+
|
| 522 |
+
output_dir = Path(args.output_dir)
|
| 523 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 524 |
+
write_json(output_dir / "recommended_thresholds.json", thresholds)
|
| 525 |
+
write_csv(output_dir / "metric_calibration.csv", metric_rows, collect_fields(metric_rows, [
|
| 526 |
+
"metric",
|
| 527 |
+
"direction",
|
| 528 |
+
"threshold_key",
|
| 529 |
+
"pass_bound",
|
| 530 |
+
"pass_bound_fp_1e6",
|
| 531 |
+
"reject_bound",
|
| 532 |
+
"reject_bound_fp_1e6",
|
| 533 |
+
"base_count",
|
| 534 |
+
"challenger_count",
|
| 535 |
+
"base_pass_rate_at_pass_bound",
|
| 536 |
+
"challenger_pass_rate_at_pass_bound",
|
| 537 |
+
"base_false_reject_rate_at_reject_bound",
|
| 538 |
+
"challenger_reject_rate_at_reject_bound",
|
| 539 |
+
"youden_at_reject_bound",
|
| 540 |
+
"separation_gap",
|
| 541 |
+
]))
|
| 542 |
+
write_csv(output_dir / "group_verdicts.csv", group_rows, collect_fields(group_rows, [
|
| 543 |
+
"model_role",
|
| 544 |
+
"verifier_variant_id",
|
| 545 |
+
"verifier_model",
|
| 546 |
+
"run_count",
|
| 547 |
+
"sample_count",
|
| 548 |
+
"pass_count",
|
| 549 |
+
"reject_count",
|
| 550 |
+
"inconclusive_count",
|
| 551 |
+
"pass_rate",
|
| 552 |
+
"reject_rate",
|
| 553 |
+
"inconclusive_rate",
|
| 554 |
+
"mean_abs_logprob_diff_sample_mean",
|
| 555 |
+
"abs_logprob_diff_p99_sample_mean",
|
| 556 |
+
"rank_delta_nonzero_rate_sample_mean",
|
| 557 |
+
"topk_jaccard_mean_sample_mean",
|
| 558 |
+
"union_js_p99_sample_mean",
|
| 559 |
+
]))
|
| 560 |
+
write_csv(output_dir / "sample_verdicts.csv", sample_rows, collect_fields(sample_rows, [
|
| 561 |
+
"model_role",
|
| 562 |
+
"run_id",
|
| 563 |
+
"sample_id",
|
| 564 |
+
"worker_variant_id",
|
| 565 |
+
"verifier_variant_id",
|
| 566 |
+
"verifier_model",
|
| 567 |
+
"mean_abs_logprob_diff",
|
| 568 |
+
"abs_logprob_diff_p95",
|
| 569 |
+
"abs_logprob_diff_p99",
|
| 570 |
+
"rank_delta_nonzero_rate",
|
| 571 |
+
"topk_jaccard_mean",
|
| 572 |
+
"union_js_p99",
|
| 573 |
+
"metric_sample_verdict",
|
| 574 |
+
"threshold_breach_count",
|
| 575 |
+
"reject_breach_count",
|
| 576 |
+
"threshold_breaches",
|
| 577 |
+
"reject_breaches",
|
| 578 |
+
]))
|
| 579 |
+
write_json(output_dir / "calibration_metadata.json", {
|
| 580 |
+
"metadata": runtime_metadata(sys.argv),
|
| 581 |
+
"judgment_function_version": JUDGMENT_FUNCTION_VERSION,
|
| 582 |
+
"input_metrics_files": [str(path) for path in metrics_files],
|
| 583 |
+
"base_sample_count": len(base_samples),
|
| 584 |
+
"challenger_sample_count": len(challenger_samples),
|
| 585 |
+
"output_files": [
|
| 586 |
+
"recommended_thresholds.json",
|
| 587 |
+
"metric_calibration.csv",
|
| 588 |
+
"group_verdicts.csv",
|
| 589 |
+
"sample_verdicts.csv",
|
| 590 |
+
"summary.md",
|
| 591 |
+
],
|
| 592 |
+
})
|
| 593 |
+
write_markdown(
|
| 594 |
+
output_dir / "summary.md",
|
| 595 |
+
metric_rows,
|
| 596 |
+
group_rows,
|
| 597 |
+
thresholds,
|
| 598 |
+
len(base_samples),
|
| 599 |
+
len(challenger_samples),
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
log(f"Wrote {output_dir / 'recommended_thresholds.json'}")
|
| 603 |
+
log(f"Wrote {output_dir / 'metric_calibration.csv'}")
|
| 604 |
+
log(f"Wrote {output_dir / 'summary.md'}")
|
| 605 |
+
return 0
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
if __name__ == "__main__":
|
| 609 |
+
raise SystemExit(main())
|
tools/vllm_worker_verify_pipeline/collect_vllm_worker_evidence.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import List, Optional, Sequence
|
| 10 |
+
|
| 11 |
+
from pipeline_common import (
|
| 12 |
+
DecodeConfig,
|
| 13 |
+
VariantInfo,
|
| 14 |
+
build_llm_kwargs,
|
| 15 |
+
build_sampling_params,
|
| 16 |
+
dataclass_to_dict,
|
| 17 |
+
decode_tokens,
|
| 18 |
+
encode_text,
|
| 19 |
+
logprob_for_token,
|
| 20 |
+
normalize_logprob_dict,
|
| 21 |
+
parse_worker_sample,
|
| 22 |
+
rank_for_token,
|
| 23 |
+
read_jsonl,
|
| 24 |
+
runtime_metadata,
|
| 25 |
+
sorted_top_logprobs,
|
| 26 |
+
tokenizer_hash,
|
| 27 |
+
tokenizer_name,
|
| 28 |
+
write_json,
|
| 29 |
+
write_jsonl_row,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def log(message: str) -> None:
|
| 34 |
+
print(message, flush=True)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def vllm_version() -> str:
|
| 38 |
+
try:
|
| 39 |
+
import vllm
|
| 40 |
+
|
| 41 |
+
return vllm.__version__
|
| 42 |
+
except Exception:
|
| 43 |
+
return ""
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def make_variant(args: argparse.Namespace, tokenizer: object) -> VariantInfo:
|
| 47 |
+
tok_hash = tokenizer_hash(tokenizer)
|
| 48 |
+
return VariantInfo(
|
| 49 |
+
variant_id=args.variant_id,
|
| 50 |
+
model=args.model,
|
| 51 |
+
tokenizer_hash=tok_hash,
|
| 52 |
+
tokenizer_name=tokenizer_name(tokenizer),
|
| 53 |
+
quantization=args.quantization,
|
| 54 |
+
gpu=args.gpu,
|
| 55 |
+
backend="vllm",
|
| 56 |
+
backend_version=vllm_version(),
|
| 57 |
+
dtype=args.dtype,
|
| 58 |
+
extra={
|
| 59 |
+
"cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"),
|
| 60 |
+
"tensor_parallel_size": args.tensor_parallel_size,
|
| 61 |
+
"gpu_memory_utilization": args.gpu_memory_utilization,
|
| 62 |
+
"max_model_len": args.max_model_len,
|
| 63 |
+
"max_num_seqs": args.max_num_seqs,
|
| 64 |
+
"max_num_batched_tokens": args.max_num_batched_tokens,
|
| 65 |
+
"max_logprobs": args.max_logprobs,
|
| 66 |
+
},
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def trace_from_completion(completion: object,
|
| 71 |
+
tokenizer: object,
|
| 72 |
+
output_ids: Sequence[int]) -> List[dict]:
|
| 73 |
+
logprob_steps = list(getattr(completion, "logprobs", []) or [])
|
| 74 |
+
rows = []
|
| 75 |
+
for depth, token_id in enumerate(output_ids):
|
| 76 |
+
step_logprobs = (
|
| 77 |
+
normalize_logprob_dict(logprob_steps[depth])
|
| 78 |
+
if depth < len(logprob_steps) else {}
|
| 79 |
+
)
|
| 80 |
+
selected_logprob = logprob_for_token(step_logprobs, int(token_id))
|
| 81 |
+
selected_rank = rank_for_token(step_logprobs, int(token_id))
|
| 82 |
+
rows.append({
|
| 83 |
+
"depth": depth,
|
| 84 |
+
"target_token_id": int(token_id),
|
| 85 |
+
"target_decoded_token": tokenizer.decode([int(token_id)], skip_special_tokens=False),
|
| 86 |
+
"selected_logprob": selected_logprob,
|
| 87 |
+
"selected_rank": selected_rank,
|
| 88 |
+
"top_logprobs": sorted_top_logprobs(step_logprobs),
|
| 89 |
+
})
|
| 90 |
+
return rows
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 94 |
+
parser = argparse.ArgumentParser(
|
| 95 |
+
description="Generate vLLM worker evidence: input, output, and decode-time logprob trace."
|
| 96 |
+
)
|
| 97 |
+
parser.add_argument("--input", default="data/prompts.jsonl")
|
| 98 |
+
parser.add_argument("--output", default="data/worker_evidence.jsonl")
|
| 99 |
+
parser.add_argument("--model", required=True)
|
| 100 |
+
parser.add_argument("--variant-id", required=True)
|
| 101 |
+
parser.add_argument("--gpu", default="")
|
| 102 |
+
parser.add_argument("--quantization", default="bf16")
|
| 103 |
+
parser.add_argument("--dtype", default="auto")
|
| 104 |
+
parser.add_argument("--trust-remote-code", action="store_true")
|
| 105 |
+
parser.add_argument("--tensor-parallel-size", type=int, default=1)
|
| 106 |
+
parser.add_argument("--gpu-memory-utilization", type=float, default=None)
|
| 107 |
+
parser.add_argument("--max-model-len", type=int, default=None)
|
| 108 |
+
parser.add_argument("--max-num-seqs", type=int, default=None)
|
| 109 |
+
parser.add_argument("--max-num-batched-tokens", type=int, default=None)
|
| 110 |
+
parser.add_argument("--max-logprobs", type=int, default=None)
|
| 111 |
+
parser.add_argument("--max-new-tokens", type=int, default=128)
|
| 112 |
+
parser.add_argument("--logprobs", type=int, default=64)
|
| 113 |
+
parser.add_argument("--temperature", type=float, default=0.0)
|
| 114 |
+
parser.add_argument("--top-p", type=float, default=1.0)
|
| 115 |
+
parser.add_argument("--top-k", type=int, default=0)
|
| 116 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 117 |
+
parser.add_argument("--batch-size", type=int, default=8)
|
| 118 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 119 |
+
args = parser.parse_args(argv)
|
| 120 |
+
|
| 121 |
+
from transformers import AutoTokenizer
|
| 122 |
+
from vllm import LLM
|
| 123 |
+
|
| 124 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 125 |
+
args.model,
|
| 126 |
+
trust_remote_code=args.trust_remote_code,
|
| 127 |
+
)
|
| 128 |
+
variant = make_variant(args, tokenizer)
|
| 129 |
+
llm_kwargs = build_llm_kwargs(args)
|
| 130 |
+
log(f"Loading vLLM with kwargs: {llm_kwargs}")
|
| 131 |
+
llm = LLM(**llm_kwargs)
|
| 132 |
+
sampling_params = build_sampling_params(
|
| 133 |
+
args,
|
| 134 |
+
max_tokens=args.max_new_tokens,
|
| 135 |
+
logprobs=args.logprobs,
|
| 136 |
+
prompt_logprobs=None,
|
| 137 |
+
detokenize=False,
|
| 138 |
+
)
|
| 139 |
+
config = DecodeConfig(
|
| 140 |
+
max_new_tokens=args.max_new_tokens,
|
| 141 |
+
temperature=args.temperature,
|
| 142 |
+
top_p=args.top_p,
|
| 143 |
+
top_k=args.top_k,
|
| 144 |
+
seed=args.seed,
|
| 145 |
+
do_sample=args.temperature > 0.0,
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
samples = []
|
| 149 |
+
for index, payload in enumerate(read_jsonl(Path(args.input)), start=1):
|
| 150 |
+
if args.limit and index > args.limit:
|
| 151 |
+
break
|
| 152 |
+
samples.append((index, parse_worker_sample(payload)))
|
| 153 |
+
|
| 154 |
+
output_path = Path(args.output)
|
| 155 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 156 |
+
total_start = time.time()
|
| 157 |
+
count = 0
|
| 158 |
+
with output_path.open("w", encoding="utf-8") as handle:
|
| 159 |
+
for batch_start in range(0, len(samples), args.batch_size):
|
| 160 |
+
batch = samples[batch_start:batch_start + args.batch_size]
|
| 161 |
+
prompts = [sample.input_text for _, sample in batch]
|
| 162 |
+
log(f"Generating worker evidence batch {batch_start // args.batch_size + 1}, size={len(batch)}")
|
| 163 |
+
outputs = llm.generate(prompts, sampling_params)
|
| 164 |
+
if len(outputs) != len(batch):
|
| 165 |
+
raise RuntimeError(f"vLLM returned {len(outputs)} outputs for {len(batch)} prompts")
|
| 166 |
+
for (index, sample), request_output in zip(batch, outputs):
|
| 167 |
+
completion = request_output.outputs[0] if request_output.outputs else None
|
| 168 |
+
if completion is None:
|
| 169 |
+
raise RuntimeError(f"No completion for sample {sample.sample_id}")
|
| 170 |
+
input_ids = encode_text(tokenizer, sample.input_text)
|
| 171 |
+
output_ids = [int(token_id) for token_id in list(getattr(completion, "token_ids", []))]
|
| 172 |
+
row = {
|
| 173 |
+
"sample_id": sample.sample_id,
|
| 174 |
+
"input_text": sample.input_text,
|
| 175 |
+
"input_ids": input_ids,
|
| 176 |
+
"output_text": decode_tokens(tokenizer, output_ids),
|
| 177 |
+
"output_ids": output_ids,
|
| 178 |
+
"category": sample.category,
|
| 179 |
+
"target_input_tokens": sample.target_input_tokens,
|
| 180 |
+
"worker_variant": dataclass_to_dict(variant),
|
| 181 |
+
"decode_config": dataclass_to_dict(config),
|
| 182 |
+
"worker_trace_mode": "vllm_decode_generate",
|
| 183 |
+
"worker_trace": trace_from_completion(completion, tokenizer, output_ids),
|
| 184 |
+
}
|
| 185 |
+
write_jsonl_row(handle, row)
|
| 186 |
+
count += 1
|
| 187 |
+
log(
|
| 188 |
+
f"[{index}] sample={sample.sample_id} "
|
| 189 |
+
f"input_tokens={len(input_ids)} output_tokens={len(output_ids)}"
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
write_json(output_path.with_suffix(output_path.suffix + ".metadata.json"), {
|
| 193 |
+
"metadata": runtime_metadata(sys.argv),
|
| 194 |
+
"args": vars(args),
|
| 195 |
+
"worker_variant": dataclass_to_dict(variant),
|
| 196 |
+
"sample_count": count,
|
| 197 |
+
})
|
| 198 |
+
log(f"Wrote {count} worker evidence rows to {output_path} in {time.time() - total_start:.1f}s")
|
| 199 |
+
return 0
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
if __name__ == "__main__":
|
| 203 |
+
raise SystemExit(main())
|
tools/vllm_worker_verify_pipeline/generate_prompts.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import random
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Dict, List, Optional, Sequence
|
| 9 |
+
|
| 10 |
+
from pipeline_common import runtime_metadata, stable_json_hash, write_json, write_jsonl
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
CATEGORIES = [
|
| 14 |
+
"short_qa",
|
| 15 |
+
"code",
|
| 16 |
+
"math_numeric",
|
| 17 |
+
"json_structured",
|
| 18 |
+
"mixed_language",
|
| 19 |
+
"summarization",
|
| 20 |
+
"logs",
|
| 21 |
+
"chat",
|
| 22 |
+
"needle",
|
| 23 |
+
"low_margin",
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
BASE_SNIPPETS = {
|
| 28 |
+
"short_qa": [
|
| 29 |
+
"Question: What is the operational risk of silently accepting a wrong model worker? Answer carefully.",
|
| 30 |
+
"Explain why deterministic verification should separate input evidence from output evidence.",
|
| 31 |
+
"Give a concise answer about why top-k support changes matter in logits verification.",
|
| 32 |
+
],
|
| 33 |
+
"code": [
|
| 34 |
+
"Review this Python function and continue with a corrected version:\n\n"
|
| 35 |
+
"def merge_counts(left, right):\n"
|
| 36 |
+
" out = left\n"
|
| 37 |
+
" for key, value in right.items():\n"
|
| 38 |
+
" out[key] = out.get(key, 0) + value\n"
|
| 39 |
+
" return out\n\n",
|
| 40 |
+
"Write a TypeScript helper that normalizes a worker trace row before saving it.",
|
| 41 |
+
"Explain this shell failure and propose a robust command sequence: CUDA out of memory while loading shard 19.",
|
| 42 |
+
],
|
| 43 |
+
"math_numeric": [
|
| 44 |
+
"Solve step by step, then give the final integer only: 173 * 29 - 418.",
|
| 45 |
+
"A service processes 384 requests per second per GPU. Estimate throughput for 7 GPUs after a 12% overhead.",
|
| 46 |
+
"Compare the numeric stability of accumulating 1024 small deltas in fp16, bf16, and fp32.",
|
| 47 |
+
],
|
| 48 |
+
"json_structured": [
|
| 49 |
+
"Return a JSON object with keys sample_id, verdict, confidence, and notes for a worker verification event.",
|
| 50 |
+
"Convert the following policy into YAML with exactly three top-level keys: identity, drift, action.",
|
| 51 |
+
"Produce a compact JSONL example for two token-depth trace rows.",
|
| 52 |
+
],
|
| 53 |
+
"mixed_language": [
|
| 54 |
+
"用中文解释为什么同上下文 teacher-forced replay 可以避免生成分叉带来的干扰。",
|
| 55 |
+
"Translate and summarize: 数值漂移需要按 token depth 分桶统计, because accumulated error is not uniform.",
|
| 56 |
+
"写一个中英混合的 incident note,主题是 worker 返回了错误量化版本的输出。",
|
| 57 |
+
],
|
| 58 |
+
"summarization": [
|
| 59 |
+
"Summarize the incident: a deployment silently switched one worker from BF16 to AWQ; latency improved, but verification drift increased.",
|
| 60 |
+
"Condense the following design note into bullet points while preserving the main constraints.",
|
| 61 |
+
"Write an executive summary of a GPU drift calibration experiment.",
|
| 62 |
+
],
|
| 63 |
+
"logs": [
|
| 64 |
+
"Analyze these logs and identify the likely failure: rank=0 loaded qwen shard, rank=1 timeout, verifier reported top-k fingerprint mismatch.",
|
| 65 |
+
"Given a trace with depth, selected_logprob, rank, and margin columns, describe what anomaly to look for.",
|
| 66 |
+
"Explain this monitoring alert: cumulative_nll_delta_p99 exceeded profile envelope for bucket 257-1024.",
|
| 67 |
+
],
|
| 68 |
+
"chat": [
|
| 69 |
+
"User: My worker output verifies on H100 but fails on 6000. Assistant:",
|
| 70 |
+
"System: You are a careful verification service.\nUser: Decide whether this trace belongs to Qwen3-32B BF16.",
|
| 71 |
+
"User: Why is output text equality insufficient for model identity verification?\nAssistant:",
|
| 72 |
+
],
|
| 73 |
+
"needle": [
|
| 74 |
+
"Remember this verifier nonce: TRACE-ANCHOR-73491. Later, state the nonce and explain its purpose.",
|
| 75 |
+
"The important token is hidden in the context: delta_margin_bucket=low_0.05_0.25. Use it in the final answer.",
|
| 76 |
+
"Store the key phrase 'same context, not same branch' and use it in a short explanation.",
|
| 77 |
+
],
|
| 78 |
+
"low_margin": [
|
| 79 |
+
"Choose the most plausible next word between two close alternatives and explain uncertainty.",
|
| 80 |
+
"Complete the sentence with one token if possible: The result is either valid or",
|
| 81 |
+
"Rank the next action when the verifier is almost tied between accept and reject.",
|
| 82 |
+
],
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
FILLERS = [
|
| 87 |
+
"The verifier records depth, selected token rank, top-k support, and cumulative negative log-likelihood.",
|
| 88 |
+
"A worker is accepted only when its fingerprint fits the calibrated same-weight cross-GPU envelope.",
|
| 89 |
+
"Low-margin positions are useful because small numerical changes can alter the argmax there.",
|
| 90 |
+
"Quantized models may preserve text quality while changing the local probability distribution.",
|
| 91 |
+
"The experiment freezes the canonical output so later comparisons stay on the same context path.",
|
| 92 |
+
"A trace row should be compact enough to store, but rich enough to explain failures.",
|
| 93 |
+
"Structured outputs, code, numbers, Chinese text, and log-like data exercise different tokenizer regions.",
|
| 94 |
+
"The profile should report percentiles by depth bucket instead of averaging over all positions.",
|
| 95 |
+
"Probe tokens make it harder for a non-anchor model to mimic only the selected output path.",
|
| 96 |
+
"The result is an identity-style fingerprint, not merely an output plausibility score.",
|
| 97 |
+
]
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def try_load_tokenizer(model: Optional[str], trust_remote_code: bool) -> Optional[object]:
|
| 101 |
+
if not model:
|
| 102 |
+
return None
|
| 103 |
+
try:
|
| 104 |
+
from transformers import AutoTokenizer
|
| 105 |
+
except Exception:
|
| 106 |
+
return None
|
| 107 |
+
return AutoTokenizer.from_pretrained(model, trust_remote_code=trust_remote_code)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def token_count(tokenizer: Optional[object], text: str) -> int:
|
| 111 |
+
if tokenizer is None:
|
| 112 |
+
return max(1, len(text.split()))
|
| 113 |
+
return len(tokenizer.encode(text, add_special_tokens=False))
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def build_prompt(category: str,
|
| 117 |
+
target_tokens: int,
|
| 118 |
+
index: int,
|
| 119 |
+
rng: random.Random,
|
| 120 |
+
tokenizer: Optional[object]) -> str:
|
| 121 |
+
base = rng.choice(BASE_SNIPPETS[category])
|
| 122 |
+
header = (
|
| 123 |
+
f"Calibration sample {index}. Category: {category}. "
|
| 124 |
+
"Respond as the model would during a worker verification benchmark.\n\n"
|
| 125 |
+
)
|
| 126 |
+
parts = [header, base]
|
| 127 |
+
loops = 0
|
| 128 |
+
while token_count(tokenizer, "\n".join(parts)) < target_tokens:
|
| 129 |
+
loops += 1
|
| 130 |
+
filler = rng.choice(FILLERS)
|
| 131 |
+
if category == "json_structured":
|
| 132 |
+
filler = (
|
| 133 |
+
'{"depth": %d, "metric": "selected_logprob", '
|
| 134 |
+
'"note": "stable schema matters"}' % loops
|
| 135 |
+
)
|
| 136 |
+
elif category == "code":
|
| 137 |
+
filler = (
|
| 138 |
+
"def trace_step_%d(row):\n"
|
| 139 |
+
" return row.get('selected_logprob'), row.get('selected_rank')\n" % loops
|
| 140 |
+
)
|
| 141 |
+
elif category == "logs":
|
| 142 |
+
filler = (
|
| 143 |
+
"2026-06-25T12:%02d:00Z worker=%02d level=INFO "
|
| 144 |
+
"event=trace_depth depth=%d margin=0.%03d\n"
|
| 145 |
+
% (loops % 60, index % 32, loops * 17, rng.randint(10, 999))
|
| 146 |
+
)
|
| 147 |
+
elif category == "mixed_language":
|
| 148 |
+
filler = "同一个上下文路径用于比较漂移; the output path is frozen for replay."
|
| 149 |
+
elif category == "needle" and loops == 3:
|
| 150 |
+
filler = f"The hidden checksum for this sample is CHECK-{index:05d}-{target_tokens}."
|
| 151 |
+
parts.append(filler)
|
| 152 |
+
if loops > target_tokens * 4:
|
| 153 |
+
break
|
| 154 |
+
|
| 155 |
+
text = "\n".join(parts)
|
| 156 |
+
current = token_count(tokenizer, text)
|
| 157 |
+
if tokenizer is None or current <= int(target_tokens * 1.25):
|
| 158 |
+
return text
|
| 159 |
+
|
| 160 |
+
token_ids = tokenizer.encode(text, add_special_tokens=False)[:target_tokens]
|
| 161 |
+
return tokenizer.decode(token_ids, skip_special_tokens=False)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def parse_buckets(raw: str) -> List[int]:
|
| 165 |
+
buckets = []
|
| 166 |
+
for item in raw.split(","):
|
| 167 |
+
item = item.strip()
|
| 168 |
+
if item:
|
| 169 |
+
buckets.append(int(item))
|
| 170 |
+
if not buckets:
|
| 171 |
+
raise ValueError("At least one bucket is required")
|
| 172 |
+
return buckets
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def rows_for_dataset(buckets: Sequence[int],
|
| 176 |
+
per_bucket: int,
|
| 177 |
+
tokenizer: Optional[object],
|
| 178 |
+
seed: int) -> List[Dict[str, object]]:
|
| 179 |
+
rng = random.Random(seed)
|
| 180 |
+
rows: List[Dict[str, object]] = []
|
| 181 |
+
for bucket in buckets:
|
| 182 |
+
for index in range(per_bucket):
|
| 183 |
+
category = CATEGORIES[(index + bucket) % len(CATEGORIES)]
|
| 184 |
+
prompt = build_prompt(category, bucket, index, rng, tokenizer)
|
| 185 |
+
actual_tokens = token_count(tokenizer, prompt)
|
| 186 |
+
sample_id = stable_json_hash({
|
| 187 |
+
"bucket": bucket,
|
| 188 |
+
"index": index,
|
| 189 |
+
"category": category,
|
| 190 |
+
"input_text": prompt,
|
| 191 |
+
}, length=20)
|
| 192 |
+
rows.append({
|
| 193 |
+
"sample_id": sample_id,
|
| 194 |
+
"input_text": prompt,
|
| 195 |
+
"canonical_output_text": "",
|
| 196 |
+
"category": category,
|
| 197 |
+
"target_input_tokens": bucket,
|
| 198 |
+
"anchor_variant": "",
|
| 199 |
+
"decode_config": None,
|
| 200 |
+
"tokenizations": {},
|
| 201 |
+
"metadata": {
|
| 202 |
+
"generator": "vllm_worker_verify_pipeline.generate_prompts",
|
| 203 |
+
"bucket_input_tokens": bucket,
|
| 204 |
+
"actual_input_tokens": actual_tokens,
|
| 205 |
+
"bucket_index": index,
|
| 206 |
+
},
|
| 207 |
+
})
|
| 208 |
+
return rows
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 212 |
+
parser = argparse.ArgumentParser(
|
| 213 |
+
description="Generate a calibration input dataset across token-length buckets."
|
| 214 |
+
)
|
| 215 |
+
parser.add_argument("--output", default="data/prompts.jsonl")
|
| 216 |
+
parser.add_argument("--model", default=None,
|
| 217 |
+
help="Optional tokenizer model used to measure token lengths.")
|
| 218 |
+
parser.add_argument("--trust-remote-code", action="store_true")
|
| 219 |
+
parser.add_argument("--buckets", default="32,128,512,2048,8192,16384")
|
| 220 |
+
parser.add_argument("--per-bucket", type=int, default=50)
|
| 221 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 222 |
+
args = parser.parse_args(argv)
|
| 223 |
+
|
| 224 |
+
tokenizer = try_load_tokenizer(args.model, args.trust_remote_code)
|
| 225 |
+
buckets = parse_buckets(args.buckets)
|
| 226 |
+
rows = rows_for_dataset(
|
| 227 |
+
buckets=buckets,
|
| 228 |
+
per_bucket=args.per_bucket,
|
| 229 |
+
tokenizer=tokenizer,
|
| 230 |
+
seed=args.seed,
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
output_path = Path(args.output)
|
| 234 |
+
write_jsonl(output_path, rows)
|
| 235 |
+
write_json(output_path.with_suffix(output_path.suffix + ".metadata.json"), {
|
| 236 |
+
"metadata": runtime_metadata(sys.argv),
|
| 237 |
+
"args": vars(args),
|
| 238 |
+
"sample_count": len(rows),
|
| 239 |
+
"buckets": buckets,
|
| 240 |
+
})
|
| 241 |
+
print(f"Wrote {len(rows)} samples to {output_path}")
|
| 242 |
+
return 0
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
if __name__ == "__main__":
|
| 246 |
+
raise SystemExit(main())
|
tools/vllm_worker_verify_pipeline/pipeline_common.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import inspect
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import platform
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
from dataclasses import asdict, dataclass, field
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
JSONDict = Dict[str, Any]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass
|
| 19 |
+
class DecodeConfig:
|
| 20 |
+
max_new_tokens: int = 128
|
| 21 |
+
temperature: float = 0.0
|
| 22 |
+
top_p: float = 1.0
|
| 23 |
+
top_k: int = 0
|
| 24 |
+
seed: int = 0
|
| 25 |
+
do_sample: bool = False
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class VariantInfo:
|
| 30 |
+
variant_id: str
|
| 31 |
+
model: str
|
| 32 |
+
tokenizer_hash: str
|
| 33 |
+
tokenizer_name: str = ""
|
| 34 |
+
quantization: str = "bf16"
|
| 35 |
+
gpu: str = ""
|
| 36 |
+
backend: str = "vllm"
|
| 37 |
+
backend_version: str = ""
|
| 38 |
+
dtype: str = ""
|
| 39 |
+
extra: JSONDict = field(default_factory=dict)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
class Tokenization:
|
| 44 |
+
tokenizer_hash: str
|
| 45 |
+
tokenizer_name: str
|
| 46 |
+
input_ids: List[int]
|
| 47 |
+
output_ids: List[int]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclass
|
| 51 |
+
class WorkerSample:
|
| 52 |
+
sample_id: str
|
| 53 |
+
input_text: str
|
| 54 |
+
canonical_output_text: str = ""
|
| 55 |
+
category: str = ""
|
| 56 |
+
target_input_tokens: Optional[int] = None
|
| 57 |
+
anchor_variant: str = ""
|
| 58 |
+
decode_config: Optional[DecodeConfig] = None
|
| 59 |
+
tokenizations: Dict[str, Tokenization] = field(default_factory=dict)
|
| 60 |
+
metadata: JSONDict = field(default_factory=dict)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def runtime_metadata(argv: Sequence[str]) -> JSONDict:
|
| 64 |
+
return {
|
| 65 |
+
"created_at_unix": time.time(),
|
| 66 |
+
"python": sys.version,
|
| 67 |
+
"platform": platform.platform(),
|
| 68 |
+
"argv": list(argv),
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def stable_json_hash(payload: Any, length: int = 16) -> str:
|
| 73 |
+
encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")
|
| 74 |
+
return hashlib.sha256(encoded).hexdigest()[:length]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def dataclass_to_dict(value: Any) -> JSONDict:
|
| 78 |
+
return asdict(value)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def read_jsonl(path: Path) -> Iterator[JSONDict]:
|
| 82 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 83 |
+
for line_number, line in enumerate(handle, start=1):
|
| 84 |
+
line = line.strip()
|
| 85 |
+
if not line:
|
| 86 |
+
continue
|
| 87 |
+
try:
|
| 88 |
+
yield json.loads(line)
|
| 89 |
+
except json.JSONDecodeError as exc:
|
| 90 |
+
raise ValueError(f"{path}:{line_number}: invalid JSONL row") from exc
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def write_jsonl(path: Path, rows: Iterable[JSONDict]) -> None:
|
| 94 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 95 |
+
with path.open("w", encoding="utf-8") as handle:
|
| 96 |
+
for row in rows:
|
| 97 |
+
handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True))
|
| 98 |
+
handle.write("\n")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def write_json(path: Path, payload: JSONDict) -> None:
|
| 102 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 103 |
+
with path.open("w", encoding="utf-8") as handle:
|
| 104 |
+
json.dump(payload, handle, ensure_ascii=False, indent=2, sort_keys=True)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def parse_decode_config(payload: Optional[JSONDict]) -> Optional[DecodeConfig]:
|
| 108 |
+
if payload is None:
|
| 109 |
+
return None
|
| 110 |
+
return DecodeConfig(**payload)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def parse_tokenizations(payload: Optional[JSONDict]) -> Dict[str, Tokenization]:
|
| 114 |
+
if not payload:
|
| 115 |
+
return {}
|
| 116 |
+
return {
|
| 117 |
+
str(key): Tokenization(**value)
|
| 118 |
+
for key, value in payload.items()
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def parse_worker_sample(payload: JSONDict) -> WorkerSample:
|
| 123 |
+
data = dict(payload)
|
| 124 |
+
data["decode_config"] = parse_decode_config(data.get("decode_config"))
|
| 125 |
+
data["tokenizations"] = parse_tokenizations(data.get("tokenizations"))
|
| 126 |
+
return WorkerSample(**data)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def safe_float(value: object, default: float = float("nan")) -> float:
|
| 130 |
+
try:
|
| 131 |
+
return float(value)
|
| 132 |
+
except (TypeError, ValueError):
|
| 133 |
+
return default
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def sorted_token_ids(token_ids: Iterable[str]) -> List[str]:
|
| 137 |
+
return sorted((str(token_id) for token_id in token_ids), key=lambda item: int(item))
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def normalize_logprobs(logprobs: Sequence[float]) -> List[float]:
|
| 141 |
+
if not logprobs:
|
| 142 |
+
return []
|
| 143 |
+
max_logprob = max(logprobs)
|
| 144 |
+
if not math.isfinite(max_logprob):
|
| 145 |
+
return [float("nan") for _ in logprobs]
|
| 146 |
+
weights = [math.exp(value - max_logprob) for value in logprobs]
|
| 147 |
+
total = sum(weights)
|
| 148 |
+
if total <= 0.0 or not math.isfinite(total):
|
| 149 |
+
return [float("nan") for _ in logprobs]
|
| 150 |
+
return [value / total for value in weights]
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def cosine(left: Sequence[float], right: Sequence[float]) -> float:
|
| 154 |
+
if not left or not right or len(left) != len(right):
|
| 155 |
+
return float("nan")
|
| 156 |
+
dot = sum(a * b for a, b in zip(left, right))
|
| 157 |
+
left_norm = math.sqrt(sum(a * a for a in left))
|
| 158 |
+
right_norm = math.sqrt(sum(b * b for b in right))
|
| 159 |
+
if left_norm == 0.0 or right_norm == 0.0:
|
| 160 |
+
return float("nan")
|
| 161 |
+
return dot / (left_norm * right_norm)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def kl_divergence(p: Sequence[float], q: Sequence[float]) -> float:
|
| 165 |
+
if not p or not q or len(p) != len(q):
|
| 166 |
+
return float("nan")
|
| 167 |
+
total = 0.0
|
| 168 |
+
for p_value, q_value in zip(p, q):
|
| 169 |
+
if p_value <= 0.0:
|
| 170 |
+
continue
|
| 171 |
+
if q_value <= 0.0:
|
| 172 |
+
return float("inf")
|
| 173 |
+
total += p_value * math.log(p_value / q_value)
|
| 174 |
+
return total
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def js_divergence(p: Sequence[float], q: Sequence[float]) -> float:
|
| 178 |
+
if not p or not q or len(p) != len(q):
|
| 179 |
+
return float("nan")
|
| 180 |
+
middle = [(p_value + q_value) / 2.0 for p_value, q_value in zip(p, q)]
|
| 181 |
+
return 0.5 * kl_divergence(p, middle) + 0.5 * kl_divergence(q, middle)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def logprob_value(logprobs: Mapping[str, Mapping[str, object]],
|
| 185 |
+
token_id: str,
|
| 186 |
+
missing_logprob: float) -> float:
|
| 187 |
+
if token_id not in logprobs:
|
| 188 |
+
return missing_logprob
|
| 189 |
+
return safe_float(logprobs[token_id].get("logprob"))
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def probability_metrics(left: Mapping[str, Mapping[str, object]],
|
| 193 |
+
right: Mapping[str, Mapping[str, object]],
|
| 194 |
+
token_ids: Sequence[str],
|
| 195 |
+
missing_logprob: float) -> Dict[str, float]:
|
| 196 |
+
left_logprobs = [
|
| 197 |
+
logprob_value(left, token_id, missing_logprob)
|
| 198 |
+
for token_id in token_ids
|
| 199 |
+
]
|
| 200 |
+
right_logprobs = [
|
| 201 |
+
logprob_value(right, token_id, missing_logprob)
|
| 202 |
+
for token_id in token_ids
|
| 203 |
+
]
|
| 204 |
+
left_probs = normalize_logprobs(left_logprobs)
|
| 205 |
+
right_probs = normalize_logprobs(right_logprobs)
|
| 206 |
+
return {
|
| 207 |
+
"prob_cosine": cosine(left_probs, right_probs),
|
| 208 |
+
"kl_left_to_right": kl_divergence(left_probs, right_probs),
|
| 209 |
+
"kl_right_to_left": kl_divergence(right_probs, left_probs),
|
| 210 |
+
"js_divergence": js_divergence(left_probs, right_probs),
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def quantile(values: Sequence[float], q: float) -> float:
|
| 215 |
+
clean = sorted(value for value in values if math.isfinite(value))
|
| 216 |
+
if not clean:
|
| 217 |
+
return float("nan")
|
| 218 |
+
if len(clean) == 1:
|
| 219 |
+
return clean[0]
|
| 220 |
+
position = (len(clean) - 1) * q
|
| 221 |
+
lower = int(math.floor(position))
|
| 222 |
+
upper = int(math.ceil(position))
|
| 223 |
+
if lower == upper:
|
| 224 |
+
return clean[lower]
|
| 225 |
+
frac = position - lower
|
| 226 |
+
return clean[lower] * (1.0 - frac) + clean[upper] * frac
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def tokenizer_hash(tokenizer: Any, length: int = 16) -> str:
|
| 230 |
+
parts = {
|
| 231 |
+
"class": tokenizer.__class__.__name__,
|
| 232 |
+
"name_or_path": str(getattr(tokenizer, "name_or_path", "")),
|
| 233 |
+
"vocab_size": int(getattr(tokenizer, "vocab_size", 0) or 0),
|
| 234 |
+
"bos_token_id": getattr(tokenizer, "bos_token_id", None),
|
| 235 |
+
"eos_token_id": getattr(tokenizer, "eos_token_id", None),
|
| 236 |
+
"pad_token_id": getattr(tokenizer, "pad_token_id", None),
|
| 237 |
+
"unk_token_id": getattr(tokenizer, "unk_token_id", None),
|
| 238 |
+
"chat_template": getattr(tokenizer, "chat_template", None),
|
| 239 |
+
}
|
| 240 |
+
backend = getattr(tokenizer, "backend_tokenizer", None)
|
| 241 |
+
if backend is not None and hasattr(backend, "to_str"):
|
| 242 |
+
parts["backend_sha256"] = hashlib.sha256(
|
| 243 |
+
backend.to_str().encode("utf-8")
|
| 244 |
+
).hexdigest()
|
| 245 |
+
else:
|
| 246 |
+
try:
|
| 247 |
+
vocab_items = sorted(tokenizer.get_vocab().items())
|
| 248 |
+
except Exception:
|
| 249 |
+
vocab_items = []
|
| 250 |
+
parts["vocab_sha256"] = hashlib.sha256(
|
| 251 |
+
json.dumps(vocab_items, sort_keys=True).encode("utf-8")
|
| 252 |
+
).hexdigest()
|
| 253 |
+
encoded = json.dumps(parts, ensure_ascii=False, sort_keys=True).encode("utf-8")
|
| 254 |
+
return hashlib.sha256(encoded).hexdigest()[:length]
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def tokenizer_name(tokenizer: Any) -> str:
|
| 258 |
+
return str(getattr(tokenizer, "name_or_path", "") or tokenizer.__class__.__name__)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def encode_text(tokenizer: Any, text: str) -> List[int]:
|
| 262 |
+
return list(tokenizer.encode(text, add_special_tokens=False))
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def decode_tokens(tokenizer: Any, token_ids: Sequence[int]) -> str:
|
| 266 |
+
return tokenizer.decode(list(token_ids), skip_special_tokens=False)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def normalize_logprob_value(value: Any) -> Dict[str, Any]:
|
| 270 |
+
if hasattr(value, "logprob"):
|
| 271 |
+
return {
|
| 272 |
+
"logprob": float(value.logprob),
|
| 273 |
+
"rank": getattr(value, "rank", None),
|
| 274 |
+
"decoded_token": getattr(value, "decoded_token", None),
|
| 275 |
+
}
|
| 276 |
+
if isinstance(value, dict):
|
| 277 |
+
logprob = value.get("logprob", value.get("value"))
|
| 278 |
+
return {
|
| 279 |
+
"logprob": float(logprob),
|
| 280 |
+
"rank": value.get("rank"),
|
| 281 |
+
"decoded_token": value.get("decoded_token"),
|
| 282 |
+
}
|
| 283 |
+
return {"logprob": float(value), "rank": None, "decoded_token": None}
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def normalize_logprob_dict(raw: Any) -> Dict[str, Dict[str, Any]]:
|
| 287 |
+
if raw is None:
|
| 288 |
+
return {}
|
| 289 |
+
out: Dict[str, Dict[str, Any]] = {}
|
| 290 |
+
for token_id, value in dict(raw).items():
|
| 291 |
+
out[str(int(token_id))] = normalize_logprob_value(value)
|
| 292 |
+
return out
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def sorted_top_logprobs(logprobs: Dict[str, Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 296 |
+
def sort_key(item: tuple) -> tuple:
|
| 297 |
+
token_id, token_info = item
|
| 298 |
+
rank = token_info.get("rank")
|
| 299 |
+
rank_key = float("inf") if rank is None else safe_float(rank, float("inf"))
|
| 300 |
+
return rank_key, -safe_float(token_info.get("logprob")), int(token_id)
|
| 301 |
+
|
| 302 |
+
rows = []
|
| 303 |
+
for position, (token_id, token_info) in enumerate(
|
| 304 |
+
sorted(logprobs.items(), key=sort_key),
|
| 305 |
+
start=1,
|
| 306 |
+
):
|
| 307 |
+
rows.append({
|
| 308 |
+
"position": position,
|
| 309 |
+
"token_id": int(token_id),
|
| 310 |
+
"logprob": safe_float(token_info.get("logprob")),
|
| 311 |
+
"rank": token_info.get("rank"),
|
| 312 |
+
"decoded_token": token_info.get("decoded_token"),
|
| 313 |
+
})
|
| 314 |
+
return rows
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def logprob_for_token(logprobs: Dict[str, Dict[str, Any]], token_id: int) -> Optional[float]:
|
| 318 |
+
item = logprobs.get(str(int(token_id)))
|
| 319 |
+
if item is None:
|
| 320 |
+
return None
|
| 321 |
+
return safe_float(item.get("logprob"))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def rank_for_token(logprobs: Dict[str, Dict[str, Any]], token_id: int) -> Optional[int]:
|
| 325 |
+
item = logprobs.get(str(int(token_id)))
|
| 326 |
+
if item is None:
|
| 327 |
+
return None
|
| 328 |
+
rank = item.get("rank")
|
| 329 |
+
if rank is None:
|
| 330 |
+
return None
|
| 331 |
+
return int(rank)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def make_tokens_prompt(token_ids: Sequence[int]) -> Any:
|
| 335 |
+
ids = [int(token_id) for token_id in token_ids]
|
| 336 |
+
try:
|
| 337 |
+
from vllm.inputs import TokensPrompt
|
| 338 |
+
|
| 339 |
+
return TokensPrompt(prompt_token_ids=ids)
|
| 340 |
+
except Exception:
|
| 341 |
+
return {"prompt_token_ids": ids}
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def build_llm_kwargs(args: Any) -> Dict[str, Any]:
|
| 345 |
+
kwargs = {
|
| 346 |
+
"model": args.model,
|
| 347 |
+
"dtype": args.dtype,
|
| 348 |
+
"trust_remote_code": args.trust_remote_code,
|
| 349 |
+
"tensor_parallel_size": args.tensor_parallel_size,
|
| 350 |
+
"gpu_memory_utilization": args.gpu_memory_utilization,
|
| 351 |
+
"max_model_len": args.max_model_len,
|
| 352 |
+
"max_num_seqs": getattr(args, "max_num_seqs", None),
|
| 353 |
+
"max_num_batched_tokens": getattr(args, "max_num_batched_tokens", None),
|
| 354 |
+
"max_logprobs": args.max_logprobs,
|
| 355 |
+
"quantization": None if args.quantization == "bf16" else args.quantization,
|
| 356 |
+
}
|
| 357 |
+
return {key: value for key, value in kwargs.items() if value is not None}
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def build_sampling_params(args: Any,
|
| 361 |
+
*,
|
| 362 |
+
max_tokens: int,
|
| 363 |
+
logprobs: Optional[int] = None,
|
| 364 |
+
prompt_logprobs: Optional[int] = None,
|
| 365 |
+
detokenize: bool = False) -> Any:
|
| 366 |
+
from vllm import SamplingParams
|
| 367 |
+
|
| 368 |
+
kwargs = {
|
| 369 |
+
"temperature": args.temperature,
|
| 370 |
+
"top_p": args.top_p,
|
| 371 |
+
"top_k": args.top_k if args.top_k > 0 else -1,
|
| 372 |
+
"max_tokens": max_tokens,
|
| 373 |
+
"logprobs": logprobs,
|
| 374 |
+
"prompt_logprobs": prompt_logprobs,
|
| 375 |
+
"seed": args.seed,
|
| 376 |
+
"detokenize": detokenize,
|
| 377 |
+
}
|
| 378 |
+
supported = set()
|
| 379 |
+
try:
|
| 380 |
+
supported = set(inspect.signature(SamplingParams).parameters)
|
| 381 |
+
except (TypeError, ValueError):
|
| 382 |
+
pass
|
| 383 |
+
if supported:
|
| 384 |
+
kwargs = {key: value for key, value in kwargs.items() if key in supported}
|
| 385 |
+
return SamplingParams(**kwargs)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def write_jsonl_row(handle: Any, payload: Dict[str, Any], flush: bool = True) -> None:
|
| 389 |
+
handle.write(json.dumps(payload, ensure_ascii=False, sort_keys=True))
|
| 390 |
+
handle.write("\n")
|
| 391 |
+
if flush:
|
| 392 |
+
handle.flush()
|
tools/vllm_worker_verify_pipeline/run_vllm_worker_verify.py
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import platform
|
| 7 |
+
import shlex
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import time
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any, Dict, List, Optional, Sequence
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def log(message: str) -> None:
|
| 16 |
+
print(message, flush=True)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def runtime_metadata(argv: Sequence[str]) -> Dict[str, Any]:
|
| 20 |
+
return {
|
| 21 |
+
"created_at_unix": time.time(),
|
| 22 |
+
"python": sys.version,
|
| 23 |
+
"platform": platform.platform(),
|
| 24 |
+
"argv": list(argv),
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def write_json(path: Path, payload: Dict[str, Any]) -> None:
|
| 29 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 30 |
+
with path.open("w", encoding="utf-8") as handle:
|
| 31 |
+
json.dump(payload, handle, ensure_ascii=False, indent=2, sort_keys=True)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def slugify(value: str, default: str = "model") -> str:
|
| 35 |
+
raw = value.rstrip("/")
|
| 36 |
+
name = Path(raw).name if raw else ""
|
| 37 |
+
if not name:
|
| 38 |
+
name = raw or default
|
| 39 |
+
chars = []
|
| 40 |
+
for char in name.lower():
|
| 41 |
+
if char.isalnum():
|
| 42 |
+
chars.append(char)
|
| 43 |
+
elif char in {"-", "_", "."}:
|
| 44 |
+
chars.append(char)
|
| 45 |
+
else:
|
| 46 |
+
chars.append("-")
|
| 47 |
+
slug = "".join(chars).strip("-_.")
|
| 48 |
+
while "--" in slug:
|
| 49 |
+
slug = slug.replace("--", "-")
|
| 50 |
+
return slug or default
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def default_run_id(baseline_model: str, comparison_model: str) -> str:
|
| 54 |
+
timestamp = time.strftime("%Y%m%d-%H%M%S")
|
| 55 |
+
return (
|
| 56 |
+
f"{timestamp}_"
|
| 57 |
+
f"{slugify(baseline_model, 'baseline')}_vs_"
|
| 58 |
+
f"{slugify(comparison_model, 'comparison')}"
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def validate_run_id(parser: argparse.ArgumentParser, run_id: str) -> None:
|
| 63 |
+
path = Path(run_id)
|
| 64 |
+
if path.is_absolute() or any(part == ".." for part in path.parts):
|
| 65 |
+
parser.error("--run-id must be a relative path and must not contain '..'")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def add_value(command: List[str], flag: str, value: Any, *, include_empty: bool = False) -> None:
|
| 69 |
+
if value is None:
|
| 70 |
+
return
|
| 71 |
+
if value == "" and not include_empty:
|
| 72 |
+
return
|
| 73 |
+
command.extend([flag, str(value)])
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def add_positive_int(command: List[str], flag: str, value: Optional[int]) -> None:
|
| 77 |
+
if value is not None and value > 0:
|
| 78 |
+
command.extend([flag, str(value)])
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def add_float(command: List[str], flag: str, value: Optional[float]) -> None:
|
| 82 |
+
if value is not None:
|
| 83 |
+
command.extend([flag, str(value)])
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def add_common_vllm_args(
|
| 87 |
+
command: List[str],
|
| 88 |
+
args: argparse.Namespace,
|
| 89 |
+
*,
|
| 90 |
+
role: str,
|
| 91 |
+
) -> None:
|
| 92 |
+
tensor_parallel_size = (
|
| 93 |
+
getattr(args, f"{role}_tensor_parallel_size")
|
| 94 |
+
or args.tensor_parallel_size
|
| 95 |
+
)
|
| 96 |
+
gpu_memory_utilization = (
|
| 97 |
+
getattr(args, f"{role}_gpu_memory_utilization")
|
| 98 |
+
if getattr(args, f"{role}_gpu_memory_utilization") is not None
|
| 99 |
+
else args.gpu_memory_utilization
|
| 100 |
+
)
|
| 101 |
+
max_model_len = (
|
| 102 |
+
getattr(args, f"{role}_max_model_len")
|
| 103 |
+
or args.max_model_len
|
| 104 |
+
)
|
| 105 |
+
max_num_seqs = (
|
| 106 |
+
getattr(args, f"{role}_max_num_seqs")
|
| 107 |
+
or args.max_num_seqs
|
| 108 |
+
)
|
| 109 |
+
max_num_batched_tokens = (
|
| 110 |
+
getattr(args, f"{role}_max_num_batched_tokens")
|
| 111 |
+
or args.max_num_batched_tokens
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
add_value(command, "--tensor-parallel-size", tensor_parallel_size)
|
| 115 |
+
add_float(command, "--gpu-memory-utilization", gpu_memory_utilization)
|
| 116 |
+
add_positive_int(command, "--max-model-len", max_model_len)
|
| 117 |
+
add_positive_int(command, "--max-num-seqs", max_num_seqs)
|
| 118 |
+
add_positive_int(command, "--max-num-batched-tokens", max_num_batched_tokens)
|
| 119 |
+
add_positive_int(command, "--max-logprobs", args.max_logprobs)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def script_dir() -> Path:
|
| 123 |
+
return Path(__file__).resolve().parent
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def base_command(args: argparse.Namespace, local_script: str) -> List[str]:
|
| 127 |
+
return [args.python, str(script_dir() / local_script)]
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def build_generate_prompts_command(
|
| 131 |
+
args: argparse.Namespace,
|
| 132 |
+
prompts_path: Path,
|
| 133 |
+
) -> List[str]:
|
| 134 |
+
command = base_command(
|
| 135 |
+
args,
|
| 136 |
+
"generate_prompts.py",
|
| 137 |
+
)
|
| 138 |
+
command.extend([
|
| 139 |
+
"--model",
|
| 140 |
+
args.prompt_tokenizer_model or args.baseline_model,
|
| 141 |
+
"--buckets",
|
| 142 |
+
args.buckets,
|
| 143 |
+
"--per-bucket",
|
| 144 |
+
str(args.per_bucket),
|
| 145 |
+
"--output",
|
| 146 |
+
str(prompts_path),
|
| 147 |
+
"--seed",
|
| 148 |
+
str(args.prompt_seed),
|
| 149 |
+
])
|
| 150 |
+
if args.trust_remote_code:
|
| 151 |
+
command.append("--trust-remote-code")
|
| 152 |
+
command.extend(args.generate_extra_arg)
|
| 153 |
+
return command
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def build_collect_evidence_command(
|
| 157 |
+
args: argparse.Namespace,
|
| 158 |
+
prompts_path: Path,
|
| 159 |
+
evidence_path: Path,
|
| 160 |
+
baseline_variant_id: str,
|
| 161 |
+
) -> List[str]:
|
| 162 |
+
command = base_command(
|
| 163 |
+
args,
|
| 164 |
+
"collect_vllm_worker_evidence.py",
|
| 165 |
+
)
|
| 166 |
+
command.extend([
|
| 167 |
+
"--input",
|
| 168 |
+
str(prompts_path),
|
| 169 |
+
"--output",
|
| 170 |
+
str(evidence_path),
|
| 171 |
+
"--model",
|
| 172 |
+
args.baseline_model,
|
| 173 |
+
"--variant-id",
|
| 174 |
+
baseline_variant_id,
|
| 175 |
+
"--quantization",
|
| 176 |
+
args.baseline_quantization,
|
| 177 |
+
"--dtype",
|
| 178 |
+
args.baseline_dtype,
|
| 179 |
+
"--max-new-tokens",
|
| 180 |
+
str(args.max_new_tokens),
|
| 181 |
+
"--logprobs",
|
| 182 |
+
str(args.logprobs),
|
| 183 |
+
"--temperature",
|
| 184 |
+
str(args.temperature),
|
| 185 |
+
"--top-p",
|
| 186 |
+
str(args.top_p),
|
| 187 |
+
"--top-k",
|
| 188 |
+
str(args.top_k),
|
| 189 |
+
"--seed",
|
| 190 |
+
str(args.seed),
|
| 191 |
+
"--batch-size",
|
| 192 |
+
str(args.worker_batch_size),
|
| 193 |
+
])
|
| 194 |
+
add_value(command, "--gpu", args.baseline_gpu)
|
| 195 |
+
if args.trust_remote_code:
|
| 196 |
+
command.append("--trust-remote-code")
|
| 197 |
+
add_common_vllm_args(command, args, role="baseline")
|
| 198 |
+
add_positive_int(command, "--limit", args.limit)
|
| 199 |
+
command.extend(args.worker_extra_arg)
|
| 200 |
+
return command
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def build_verify_evidence_command(
|
| 204 |
+
args: argparse.Namespace,
|
| 205 |
+
evidence_path: Path,
|
| 206 |
+
output_dir: Path,
|
| 207 |
+
comparison_variant_id: str,
|
| 208 |
+
) -> List[str]:
|
| 209 |
+
command = base_command(
|
| 210 |
+
args,
|
| 211 |
+
"verify_vllm_worker_evidence.py",
|
| 212 |
+
)
|
| 213 |
+
command.extend([
|
| 214 |
+
"--evidence",
|
| 215 |
+
str(evidence_path),
|
| 216 |
+
"--output-dir",
|
| 217 |
+
str(output_dir),
|
| 218 |
+
"--model",
|
| 219 |
+
args.comparison_model,
|
| 220 |
+
"--variant-id",
|
| 221 |
+
comparison_variant_id,
|
| 222 |
+
"--quantization",
|
| 223 |
+
args.comparison_quantization,
|
| 224 |
+
"--dtype",
|
| 225 |
+
args.comparison_dtype,
|
| 226 |
+
"--prompt-logprobs",
|
| 227 |
+
str(args.prompt_logprobs),
|
| 228 |
+
"--temperature",
|
| 229 |
+
str(args.temperature),
|
| 230 |
+
"--top-p",
|
| 231 |
+
str(args.top_p),
|
| 232 |
+
"--top-k",
|
| 233 |
+
str(args.top_k),
|
| 234 |
+
"--seed",
|
| 235 |
+
str(args.seed),
|
| 236 |
+
"--batch-size",
|
| 237 |
+
str(args.verifier_batch_size),
|
| 238 |
+
"--missing-logprob",
|
| 239 |
+
str(args.missing_logprob),
|
| 240 |
+
])
|
| 241 |
+
add_value(command, "--gpu", args.comparison_gpu)
|
| 242 |
+
if args.trust_remote_code:
|
| 243 |
+
command.append("--trust-remote-code")
|
| 244 |
+
add_common_vllm_args(command, args, role="comparison")
|
| 245 |
+
add_positive_int(command, "--limit", args.limit)
|
| 246 |
+
add_positive_int(command, "--max-total-tokens", args.max_total_tokens)
|
| 247 |
+
command.extend(args.verifier_extra_arg)
|
| 248 |
+
return command
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def build_summarize_command(args: argparse.Namespace, verifier_output_dir: Path) -> List[str]:
|
| 252 |
+
command = base_command(
|
| 253 |
+
args,
|
| 254 |
+
"summarize_worker_verify.py",
|
| 255 |
+
)
|
| 256 |
+
command.extend([
|
| 257 |
+
"--metrics",
|
| 258 |
+
str(verifier_output_dir),
|
| 259 |
+
"--output-dir",
|
| 260 |
+
str(verifier_output_dir / "distribution"),
|
| 261 |
+
])
|
| 262 |
+
command.extend(args.summarize_extra_arg)
|
| 263 |
+
return command
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def path_exists(path: Path, *, is_dir: bool = False) -> bool:
|
| 267 |
+
return path.is_dir() if is_dir else path.exists()
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def decide_step_status(
|
| 271 |
+
output_path: Path,
|
| 272 |
+
args: argparse.Namespace,
|
| 273 |
+
*,
|
| 274 |
+
is_dir: bool = False,
|
| 275 |
+
) -> str:
|
| 276 |
+
if args.dry_run:
|
| 277 |
+
return "run"
|
| 278 |
+
if path_exists(output_path, is_dir=is_dir):
|
| 279 |
+
if args.force:
|
| 280 |
+
return "run"
|
| 281 |
+
if args.resume:
|
| 282 |
+
return "skip"
|
| 283 |
+
kind = "directory" if is_dir else "file"
|
| 284 |
+
raise FileExistsError(
|
| 285 |
+
f"Refusing to overwrite existing {kind}: {output_path}. "
|
| 286 |
+
"Use --force to overwrite it or --resume to reuse completed outputs."
|
| 287 |
+
)
|
| 288 |
+
return "run"
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def run_step(step: Dict[str, Any], *, dry_run: bool) -> None:
|
| 292 |
+
command = step["command"]
|
| 293 |
+
log("")
|
| 294 |
+
log(f"==> {step['name']}")
|
| 295 |
+
log(f"$ {shlex.join(command)}")
|
| 296 |
+
if dry_run:
|
| 297 |
+
step["status"] = "dry_run"
|
| 298 |
+
return
|
| 299 |
+
start = time.time()
|
| 300 |
+
try:
|
| 301 |
+
subprocess.run(command, check=True)
|
| 302 |
+
except subprocess.CalledProcessError as exc:
|
| 303 |
+
step["status"] = "failed"
|
| 304 |
+
step["returncode"] = exc.returncode
|
| 305 |
+
step["elapsed_seconds"] = time.time() - start
|
| 306 |
+
raise
|
| 307 |
+
step["status"] = "completed"
|
| 308 |
+
step["elapsed_seconds"] = time.time() - start
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def serializable_args(args: argparse.Namespace) -> Dict[str, Any]:
|
| 312 |
+
return {key: value for key, value in sorted(vars(args).items())}
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def write_pipeline_metadata(path: Path, payload: Dict[str, Any]) -> None:
|
| 316 |
+
write_json(path, payload)
|
| 317 |
+
log(f"Wrote {path}")
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def make_parser() -> argparse.ArgumentParser:
|
| 321 |
+
parser = argparse.ArgumentParser(
|
| 322 |
+
description=(
|
| 323 |
+
"Run the vLLM worker evidence pipeline: generate prompts, collect "
|
| 324 |
+
"baseline worker evidence, verify it with a comparison model, and "
|
| 325 |
+
"summarize the final metrics."
|
| 326 |
+
)
|
| 327 |
+
)
|
| 328 |
+
parser.add_argument("--baseline-model", "--worker-model", required=True,
|
| 329 |
+
help="Model repo/path used to generate worker evidence.")
|
| 330 |
+
parser.add_argument("--comparison-model", "--verifier-model", required=True,
|
| 331 |
+
help="Model repo/path used to recompute verifier prompt logprobs.")
|
| 332 |
+
parser.add_argument("--output-root", default="results/vllm_worker_verify_runs")
|
| 333 |
+
parser.add_argument("--run-id", default=None,
|
| 334 |
+
help="Relative run directory name under --output-root.")
|
| 335 |
+
parser.add_argument("--prompts", default=None,
|
| 336 |
+
help="Existing prompts.jsonl to reuse. If omitted, prompts are generated.")
|
| 337 |
+
parser.add_argument("--prompt-tokenizer-model", default=None,
|
| 338 |
+
help="Tokenizer model for prompt length measurement. Defaults to --baseline-model.")
|
| 339 |
+
parser.add_argument("--buckets", default="32,128,512,2048,8192,16384")
|
| 340 |
+
parser.add_argument("--per-bucket", type=int, default=50)
|
| 341 |
+
parser.add_argument("--prompt-seed", type=int, default=0)
|
| 342 |
+
|
| 343 |
+
parser.add_argument("--baseline-variant-id", default=None)
|
| 344 |
+
parser.add_argument("--comparison-variant-id", default=None)
|
| 345 |
+
parser.add_argument("--baseline-gpu", default="")
|
| 346 |
+
parser.add_argument("--comparison-gpu", default="")
|
| 347 |
+
parser.add_argument("--baseline-quantization", default="bf16")
|
| 348 |
+
parser.add_argument("--comparison-quantization", default="bf16")
|
| 349 |
+
parser.add_argument("--baseline-dtype", default="auto")
|
| 350 |
+
parser.add_argument("--comparison-dtype", default="auto")
|
| 351 |
+
|
| 352 |
+
parser.add_argument("--max-new-tokens", type=int, default=128)
|
| 353 |
+
parser.add_argument("--logprobs", type=int, default=64)
|
| 354 |
+
parser.add_argument("--prompt-logprobs", type=int, default=64)
|
| 355 |
+
parser.add_argument("--max-logprobs", type=int, default=64)
|
| 356 |
+
parser.add_argument("--worker-batch-size", type=int, default=8)
|
| 357 |
+
parser.add_argument("--verifier-batch-size", type=int, default=4)
|
| 358 |
+
parser.add_argument("--temperature", type=float, default=0.0)
|
| 359 |
+
parser.add_argument("--top-p", type=float, default=1.0)
|
| 360 |
+
parser.add_argument("--top-k", type=int, default=0)
|
| 361 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 362 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 363 |
+
parser.add_argument("--missing-logprob", type=float, default=-100.0)
|
| 364 |
+
parser.add_argument("--max-total-tokens", type=int, default=0)
|
| 365 |
+
|
| 366 |
+
parser.add_argument("--trust-remote-code", action="store_true")
|
| 367 |
+
parser.add_argument("--tensor-parallel-size", type=int, default=1,
|
| 368 |
+
help="Default tensor parallel size for both vLLM stages.")
|
| 369 |
+
parser.add_argument("--baseline-tensor-parallel-size", type=int, default=None)
|
| 370 |
+
parser.add_argument("--comparison-tensor-parallel-size", type=int, default=None)
|
| 371 |
+
parser.add_argument("--gpu-memory-utilization", type=float, default=None)
|
| 372 |
+
parser.add_argument("--baseline-gpu-memory-utilization", type=float, default=None)
|
| 373 |
+
parser.add_argument("--comparison-gpu-memory-utilization", type=float, default=None)
|
| 374 |
+
parser.add_argument("--max-model-len", type=int, default=None)
|
| 375 |
+
parser.add_argument("--baseline-max-model-len", type=int, default=None)
|
| 376 |
+
parser.add_argument("--comparison-max-model-len", type=int, default=None)
|
| 377 |
+
parser.add_argument("--max-num-seqs", type=int, default=None)
|
| 378 |
+
parser.add_argument("--baseline-max-num-seqs", type=int, default=None)
|
| 379 |
+
parser.add_argument("--comparison-max-num-seqs", type=int, default=None)
|
| 380 |
+
parser.add_argument("--max-num-batched-tokens", type=int, default=None)
|
| 381 |
+
parser.add_argument("--baseline-max-num-batched-tokens", type=int, default=None)
|
| 382 |
+
parser.add_argument("--comparison-max-num-batched-tokens", type=int, default=None)
|
| 383 |
+
|
| 384 |
+
parser.add_argument("--skip-distribution-summary", action="store_true",
|
| 385 |
+
help="Do not run summarize_worker_verify.py after verification.")
|
| 386 |
+
parser.add_argument("--resume", action="store_true",
|
| 387 |
+
help="Reuse already completed step outputs.")
|
| 388 |
+
parser.add_argument("--force", action="store_true",
|
| 389 |
+
help="Overwrite existing step outputs.")
|
| 390 |
+
parser.add_argument("--dry-run", action="store_true",
|
| 391 |
+
help="Print the planned commands without executing them.")
|
| 392 |
+
parser.add_argument("--python", default=sys.executable,
|
| 393 |
+
help="Python executable used for local subprocesses.")
|
| 394 |
+
parser.add_argument("--generate-extra-arg", action="append", default=[],
|
| 395 |
+
help="Extra argument passed to prompt generation. Repeat as needed.")
|
| 396 |
+
parser.add_argument("--worker-extra-arg", action="append", default=[],
|
| 397 |
+
help="Extra argument passed to worker evidence collection. Repeat as needed.")
|
| 398 |
+
parser.add_argument("--verifier-extra-arg", action="append", default=[],
|
| 399 |
+
help="Extra argument passed to verifier evidence comparison. Repeat as needed.")
|
| 400 |
+
parser.add_argument("--summarize-extra-arg", action="append", default=[],
|
| 401 |
+
help="Extra argument passed to distribution summarization. Repeat as needed.")
|
| 402 |
+
return parser
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 406 |
+
parser = make_parser()
|
| 407 |
+
args = parser.parse_args(argv)
|
| 408 |
+
|
| 409 |
+
if args.force and args.resume:
|
| 410 |
+
parser.error("--force and --resume cannot be used together")
|
| 411 |
+
|
| 412 |
+
run_id = args.run_id or default_run_id(args.baseline_model, args.comparison_model)
|
| 413 |
+
validate_run_id(parser, run_id)
|
| 414 |
+
|
| 415 |
+
baseline_variant_id = (
|
| 416 |
+
args.baseline_variant_id
|
| 417 |
+
or f"{slugify(args.baseline_model, 'baseline')}-baseline"
|
| 418 |
+
)
|
| 419 |
+
comparison_variant_id = (
|
| 420 |
+
args.comparison_variant_id
|
| 421 |
+
or f"{slugify(args.comparison_model, 'comparison')}-comparison"
|
| 422 |
+
)
|
| 423 |
+
baseline_slug = slugify(baseline_variant_id, "baseline")
|
| 424 |
+
comparison_slug = slugify(comparison_variant_id, "comparison")
|
| 425 |
+
|
| 426 |
+
run_dir = Path(args.output_root) / run_id
|
| 427 |
+
data_dir = run_dir / "data"
|
| 428 |
+
worker_verify_root = run_dir / "worker_verify"
|
| 429 |
+
prompts_path = Path(args.prompts) if args.prompts else data_dir / "prompts.jsonl"
|
| 430 |
+
evidence_path = data_dir / f"worker_evidence.{baseline_slug}.jsonl"
|
| 431 |
+
verifier_output_dir = (
|
| 432 |
+
worker_verify_root
|
| 433 |
+
/ f"{baseline_slug}_worker_vs_{comparison_slug}_verifier"
|
| 434 |
+
)
|
| 435 |
+
pipeline_metadata_path = run_dir / "pipeline_metadata.json"
|
| 436 |
+
|
| 437 |
+
if args.prompts and not args.dry_run and not prompts_path.exists():
|
| 438 |
+
parser.error(f"--prompts does not exist: {prompts_path}")
|
| 439 |
+
|
| 440 |
+
if not args.dry_run:
|
| 441 |
+
data_dir.mkdir(parents=True, exist_ok=True)
|
| 442 |
+
worker_verify_root.mkdir(parents=True, exist_ok=True)
|
| 443 |
+
|
| 444 |
+
steps: List[Dict[str, Any]] = []
|
| 445 |
+
if args.prompts:
|
| 446 |
+
steps.append({
|
| 447 |
+
"name": "reuse prompts",
|
| 448 |
+
"status": "skipped",
|
| 449 |
+
"reason": "--prompts was provided",
|
| 450 |
+
"output": str(prompts_path),
|
| 451 |
+
})
|
| 452 |
+
else:
|
| 453 |
+
steps.append({
|
| 454 |
+
"name": "generate prompts",
|
| 455 |
+
"command": build_generate_prompts_command(args, prompts_path),
|
| 456 |
+
"output": str(prompts_path),
|
| 457 |
+
"status": "planned",
|
| 458 |
+
})
|
| 459 |
+
|
| 460 |
+
steps.extend([
|
| 461 |
+
{
|
| 462 |
+
"name": "collect worker evidence",
|
| 463 |
+
"command": build_collect_evidence_command(
|
| 464 |
+
args,
|
| 465 |
+
prompts_path,
|
| 466 |
+
evidence_path,
|
| 467 |
+
baseline_variant_id,
|
| 468 |
+
),
|
| 469 |
+
"output": str(evidence_path),
|
| 470 |
+
"status": "planned",
|
| 471 |
+
},
|
| 472 |
+
{
|
| 473 |
+
"name": "verify worker evidence",
|
| 474 |
+
"command": build_verify_evidence_command(
|
| 475 |
+
args,
|
| 476 |
+
evidence_path,
|
| 477 |
+
verifier_output_dir,
|
| 478 |
+
comparison_variant_id,
|
| 479 |
+
),
|
| 480 |
+
"output": str(verifier_output_dir),
|
| 481 |
+
"status": "planned",
|
| 482 |
+
},
|
| 483 |
+
])
|
| 484 |
+
if not args.skip_distribution_summary:
|
| 485 |
+
steps.append({
|
| 486 |
+
"name": "summarize verifier metrics",
|
| 487 |
+
"command": build_summarize_command(args, verifier_output_dir),
|
| 488 |
+
"output": str(verifier_output_dir / "distribution"),
|
| 489 |
+
"status": "planned",
|
| 490 |
+
})
|
| 491 |
+
|
| 492 |
+
payload: Dict[str, Any] = {
|
| 493 |
+
"metadata": runtime_metadata(sys.argv),
|
| 494 |
+
"args": serializable_args(args),
|
| 495 |
+
"run_id": run_id,
|
| 496 |
+
"run_dir": str(run_dir),
|
| 497 |
+
"baseline_variant_id": baseline_variant_id,
|
| 498 |
+
"comparison_variant_id": comparison_variant_id,
|
| 499 |
+
"paths": {
|
| 500 |
+
"prompts": str(prompts_path),
|
| 501 |
+
"worker_evidence": str(evidence_path),
|
| 502 |
+
"verifier_output_dir": str(verifier_output_dir),
|
| 503 |
+
"depth_metrics": str(verifier_output_dir / "worker_vs_verifier_depth_metrics.csv"),
|
| 504 |
+
"summary": str(verifier_output_dir / "summary.md"),
|
| 505 |
+
"distribution_summary": str(verifier_output_dir / "distribution" / "summary.md"),
|
| 506 |
+
},
|
| 507 |
+
"steps": steps,
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
try:
|
| 511 |
+
for step in steps:
|
| 512 |
+
if "command" not in step:
|
| 513 |
+
log(f"Skipping {step['name']}: {step.get('reason', '')}")
|
| 514 |
+
continue
|
| 515 |
+
if step["name"] == "verify worker evidence":
|
| 516 |
+
status = decide_step_status(
|
| 517 |
+
verifier_output_dir / "worker_vs_verifier_depth_metrics.csv",
|
| 518 |
+
args,
|
| 519 |
+
)
|
| 520 |
+
elif step["name"] == "summarize verifier metrics":
|
| 521 |
+
status = decide_step_status(
|
| 522 |
+
verifier_output_dir / "distribution" / "summary.md",
|
| 523 |
+
args,
|
| 524 |
+
)
|
| 525 |
+
else:
|
| 526 |
+
status = decide_step_status(Path(step["output"]), args)
|
| 527 |
+
if status == "skip":
|
| 528 |
+
step["status"] = "skipped"
|
| 529 |
+
step["reason"] = "--resume found existing output"
|
| 530 |
+
log(f"Skipping {step['name']}: existing output at {step['output']}")
|
| 531 |
+
continue
|
| 532 |
+
run_step(step, dry_run=args.dry_run)
|
| 533 |
+
except (subprocess.CalledProcessError, FileExistsError) as exc:
|
| 534 |
+
payload["status"] = "failed"
|
| 535 |
+
payload["error"] = str(exc)
|
| 536 |
+
write_pipeline_metadata(pipeline_metadata_path, payload)
|
| 537 |
+
log(str(exc))
|
| 538 |
+
return getattr(exc, "returncode", 1) or 1
|
| 539 |
+
|
| 540 |
+
payload["status"] = "dry_run" if args.dry_run else "completed"
|
| 541 |
+
if args.dry_run:
|
| 542 |
+
log("")
|
| 543 |
+
log(f"Dry run complete; no files were written. Planned metadata path: {pipeline_metadata_path}")
|
| 544 |
+
else:
|
| 545 |
+
write_pipeline_metadata(pipeline_metadata_path, payload)
|
| 546 |
+
log("")
|
| 547 |
+
log("Pipeline outputs:")
|
| 548 |
+
log(f"- prompts: {prompts_path}")
|
| 549 |
+
log(f"- worker evidence: {evidence_path}")
|
| 550 |
+
log(f"- verifier metrics: {verifier_output_dir / 'worker_vs_verifier_depth_metrics.csv'}")
|
| 551 |
+
log(f"- verifier summary: {verifier_output_dir / 'summary.md'}")
|
| 552 |
+
if not args.skip_distribution_summary:
|
| 553 |
+
log(f"- distribution summary: {verifier_output_dir / 'distribution' / 'summary.md'}")
|
| 554 |
+
return 0
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
if __name__ == "__main__":
|
| 558 |
+
raise SystemExit(main())
|
tools/vllm_worker_verify_pipeline/summarize_worker_verify.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import csv
|
| 6 |
+
import math
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Dict, List, Optional, Sequence
|
| 10 |
+
|
| 11 |
+
from pipeline_common import quantile, safe_float
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
QUANTILES = [
|
| 15 |
+
("p50", 0.50),
|
| 16 |
+
("p90", 0.90),
|
| 17 |
+
("p95", 0.95),
|
| 18 |
+
("p99", 0.99),
|
| 19 |
+
("p999", 0.999),
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def read_csv(path: Path) -> List[dict]:
|
| 24 |
+
with path.open("r", encoding="utf-8", newline="") as handle:
|
| 25 |
+
return list(csv.DictReader(handle))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def write_csv(path: Path, rows: Sequence[dict], fields: Sequence[str]) -> None:
|
| 29 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 30 |
+
with path.open("w", encoding="utf-8", newline="") as handle:
|
| 31 |
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
| 32 |
+
writer.writeheader()
|
| 33 |
+
for row in rows:
|
| 34 |
+
writer.writerow({field: row.get(field, "") for field in fields})
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def metrics_path(path: Path) -> Path:
|
| 38 |
+
if path.is_dir():
|
| 39 |
+
return path / "worker_vs_verifier_depth_metrics.csv"
|
| 40 |
+
return path
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def input_bucket(token_count: int) -> str:
|
| 44 |
+
if token_count <= 128:
|
| 45 |
+
return "00000-00128"
|
| 46 |
+
if token_count <= 512:
|
| 47 |
+
return "00129-00512"
|
| 48 |
+
if token_count <= 2048:
|
| 49 |
+
return "00513-02048"
|
| 50 |
+
if token_count <= 8192:
|
| 51 |
+
return "02049-08192"
|
| 52 |
+
if token_count <= 16384:
|
| 53 |
+
return "08193-16384"
|
| 54 |
+
return "16385+"
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def output_depth_bucket(depth: int) -> str:
|
| 58 |
+
if depth <= 16:
|
| 59 |
+
return "000-016"
|
| 60 |
+
if depth <= 32:
|
| 61 |
+
return "017-032"
|
| 62 |
+
if depth <= 64:
|
| 63 |
+
return "033-064"
|
| 64 |
+
if depth <= 128:
|
| 65 |
+
return "065-128"
|
| 66 |
+
if depth <= 256:
|
| 67 |
+
return "129-256"
|
| 68 |
+
return "257+"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def summarize_rows(rows: Sequence[dict], label: str) -> dict:
|
| 72 |
+
values = [safe_float(row.get("abs_logprob_diff")) for row in rows]
|
| 73 |
+
values = [value for value in values if math.isfinite(value)]
|
| 74 |
+
out = {
|
| 75 |
+
"group": label,
|
| 76 |
+
"count": len(rows),
|
| 77 |
+
"finite_count": len(values),
|
| 78 |
+
"missing_selected_count": sum(
|
| 79 |
+
1 for row in rows
|
| 80 |
+
if row.get("verifier_selected_logprob") in {"", None}
|
| 81 |
+
),
|
| 82 |
+
"mean_abs_logprob_diff": (
|
| 83 |
+
sum(values) / len(values) if values else float("nan")
|
| 84 |
+
),
|
| 85 |
+
"max_abs_logprob_diff": max(values, default=float("nan")),
|
| 86 |
+
}
|
| 87 |
+
for name, q in QUANTILES:
|
| 88 |
+
out[f"abs_logprob_diff_{name}"] = quantile(values, q)
|
| 89 |
+
rank_deltas = [
|
| 90 |
+
abs(safe_float(row.get("rank_delta_verifier_minus_worker")))
|
| 91 |
+
for row in rows
|
| 92 |
+
]
|
| 93 |
+
rank_deltas = [value for value in rank_deltas if math.isfinite(value)]
|
| 94 |
+
out["rank_delta_nonzero_rate"] = (
|
| 95 |
+
sum(1 for value in rank_deltas if value != 0.0) / len(rank_deltas)
|
| 96 |
+
if rank_deltas else float("nan")
|
| 97 |
+
)
|
| 98 |
+
jaccards = [safe_float(row.get("topk_jaccard")) for row in rows]
|
| 99 |
+
jaccards = [value for value in jaccards if math.isfinite(value)]
|
| 100 |
+
out["topk_jaccard_p01"] = quantile(jaccards, 0.01)
|
| 101 |
+
out["topk_jaccard_p05"] = quantile(jaccards, 0.05)
|
| 102 |
+
out["topk_jaccard_mean"] = sum(jaccards) / len(jaccards) if jaccards else float("nan")
|
| 103 |
+
union_js = [safe_float(row.get("union_js_divergence")) for row in rows]
|
| 104 |
+
union_js = [value for value in union_js if math.isfinite(value)]
|
| 105 |
+
out["union_js_p95"] = quantile(union_js, 0.95)
|
| 106 |
+
out["union_js_p99"] = quantile(union_js, 0.99)
|
| 107 |
+
out["union_js_max"] = max(union_js, default=float("nan"))
|
| 108 |
+
return out
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def grouped_summary(rows: Sequence[dict], key_name: str) -> List[dict]:
|
| 112 |
+
grouped: Dict[str, List[dict]] = defaultdict(list)
|
| 113 |
+
for row in rows:
|
| 114 |
+
if key_name == "input_bucket":
|
| 115 |
+
key = input_bucket(int(row.get("input_token_count", 0)))
|
| 116 |
+
elif key_name == "output_depth_bucket":
|
| 117 |
+
key = output_depth_bucket(int(row.get("depth", 0)))
|
| 118 |
+
elif key_name == "output_depth":
|
| 119 |
+
key = f"{int(row.get('depth', 0)):03d}"
|
| 120 |
+
elif key_name == "sample_id":
|
| 121 |
+
key = str(row.get("sample_id"))
|
| 122 |
+
else:
|
| 123 |
+
key = str(row.get(key_name, ""))
|
| 124 |
+
grouped[key].append(row)
|
| 125 |
+
return [
|
| 126 |
+
summarize_rows(group_rows, key)
|
| 127 |
+
for key, group_rows in sorted(grouped.items())
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def write_markdown(path: Path, overall: dict, by_input: Sequence[dict],
|
| 132 |
+
by_depth: Sequence[dict],
|
| 133 |
+
by_exact_depth: Sequence[dict]) -> None:
|
| 134 |
+
lines = [
|
| 135 |
+
"# worker verify distribution",
|
| 136 |
+
"",
|
| 137 |
+
"## overall",
|
| 138 |
+
"",
|
| 139 |
+
"| count | mean | p50 | p90 | p95 | p99 | p999 | max | rank_delta_rate |",
|
| 140 |
+
"|---:|---:|---:|---:|---:|---:|---:|---:|---:|",
|
| 141 |
+
"| {count} | {mean:.8g} | {p50:.8g} | {p90:.8g} | {p95:.8g} | {p99:.8g} | {p999:.8g} | {maxv:.8g} | {rank:.8g} |".format(
|
| 142 |
+
count=overall.get("count"),
|
| 143 |
+
mean=safe_float(overall.get("mean_abs_logprob_diff")),
|
| 144 |
+
p50=safe_float(overall.get("abs_logprob_diff_p50")),
|
| 145 |
+
p90=safe_float(overall.get("abs_logprob_diff_p90")),
|
| 146 |
+
p95=safe_float(overall.get("abs_logprob_diff_p95")),
|
| 147 |
+
p99=safe_float(overall.get("abs_logprob_diff_p99")),
|
| 148 |
+
p999=safe_float(overall.get("abs_logprob_diff_p999")),
|
| 149 |
+
maxv=safe_float(overall.get("max_abs_logprob_diff")),
|
| 150 |
+
rank=safe_float(overall.get("rank_delta_nonzero_rate")),
|
| 151 |
+
),
|
| 152 |
+
"",
|
| 153 |
+
"## by input length",
|
| 154 |
+
"",
|
| 155 |
+
"| bucket | count | p90 | p95 | p99 | max | jaccard p05 | union_js p99 |",
|
| 156 |
+
"|---|---:|---:|---:|---:|---:|---:|---:|",
|
| 157 |
+
]
|
| 158 |
+
for row in by_input:
|
| 159 |
+
lines.append(
|
| 160 |
+
"| {group} | {count} | {p90:.8g} | {p95:.8g} | {p99:.8g} | {maxv:.8g} | {jac:.8g} | {js:.8g} |".format(
|
| 161 |
+
group=row.get("group"),
|
| 162 |
+
count=row.get("count"),
|
| 163 |
+
p90=safe_float(row.get("abs_logprob_diff_p90")),
|
| 164 |
+
p95=safe_float(row.get("abs_logprob_diff_p95")),
|
| 165 |
+
p99=safe_float(row.get("abs_logprob_diff_p99")),
|
| 166 |
+
maxv=safe_float(row.get("max_abs_logprob_diff")),
|
| 167 |
+
jac=safe_float(row.get("topk_jaccard_p05")),
|
| 168 |
+
js=safe_float(row.get("union_js_p99")),
|
| 169 |
+
)
|
| 170 |
+
)
|
| 171 |
+
lines.extend([
|
| 172 |
+
"",
|
| 173 |
+
"## by output depth",
|
| 174 |
+
"",
|
| 175 |
+
"| bucket | count | p90 | p95 | p99 | max | jaccard p05 | union_js p99 |",
|
| 176 |
+
"|---|---:|---:|---:|---:|---:|---:|---:|",
|
| 177 |
+
])
|
| 178 |
+
for row in by_depth:
|
| 179 |
+
lines.append(
|
| 180 |
+
"| {group} | {count} | {p90:.8g} | {p95:.8g} | {p99:.8g} | {maxv:.8g} | {jac:.8g} | {js:.8g} |".format(
|
| 181 |
+
group=row.get("group"),
|
| 182 |
+
count=row.get("count"),
|
| 183 |
+
p90=safe_float(row.get("abs_logprob_diff_p90")),
|
| 184 |
+
p95=safe_float(row.get("abs_logprob_diff_p95")),
|
| 185 |
+
p99=safe_float(row.get("abs_logprob_diff_p99")),
|
| 186 |
+
maxv=safe_float(row.get("max_abs_logprob_diff")),
|
| 187 |
+
jac=safe_float(row.get("topk_jaccard_p05")),
|
| 188 |
+
js=safe_float(row.get("union_js_p99")),
|
| 189 |
+
)
|
| 190 |
+
)
|
| 191 |
+
lines.extend([
|
| 192 |
+
"",
|
| 193 |
+
"## by exact output depth",
|
| 194 |
+
"",
|
| 195 |
+
"| depth | count | mean | p50 | p90 | p95 | p99 | max | rank_delta_rate | jaccard p05 | union_js p99 |",
|
| 196 |
+
"|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|",
|
| 197 |
+
])
|
| 198 |
+
for row in by_exact_depth:
|
| 199 |
+
lines.append(
|
| 200 |
+
"| {group} | {count} | {mean:.8g} | {p50:.8g} | {p90:.8g} | {p95:.8g} | {p99:.8g} | {maxv:.8g} | {rank:.8g} | {jac:.8g} | {js:.8g} |".format(
|
| 201 |
+
group=row.get("group"),
|
| 202 |
+
count=row.get("count"),
|
| 203 |
+
mean=safe_float(row.get("mean_abs_logprob_diff")),
|
| 204 |
+
p50=safe_float(row.get("abs_logprob_diff_p50")),
|
| 205 |
+
p90=safe_float(row.get("abs_logprob_diff_p90")),
|
| 206 |
+
p95=safe_float(row.get("abs_logprob_diff_p95")),
|
| 207 |
+
p99=safe_float(row.get("abs_logprob_diff_p99")),
|
| 208 |
+
maxv=safe_float(row.get("max_abs_logprob_diff")),
|
| 209 |
+
rank=safe_float(row.get("rank_delta_nonzero_rate")),
|
| 210 |
+
jac=safe_float(row.get("topk_jaccard_p05")),
|
| 211 |
+
js=safe_float(row.get("union_js_p99")),
|
| 212 |
+
)
|
| 213 |
+
)
|
| 214 |
+
lines.append("")
|
| 215 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 219 |
+
parser = argparse.ArgumentParser(
|
| 220 |
+
description="Summarize worker-vs-verifier abs logprob diff distributions."
|
| 221 |
+
)
|
| 222 |
+
parser.add_argument("--metrics", required=True,
|
| 223 |
+
help="worker_vs_verifier_depth_metrics.csv or its parent dir.")
|
| 224 |
+
parser.add_argument("--output-dir", default=None)
|
| 225 |
+
args = parser.parse_args(argv)
|
| 226 |
+
|
| 227 |
+
path = metrics_path(Path(args.metrics))
|
| 228 |
+
rows = read_csv(path)
|
| 229 |
+
output_dir = Path(args.output_dir) if args.output_dir else path.parent / "distribution"
|
| 230 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 231 |
+
|
| 232 |
+
overall = summarize_rows(rows, "overall")
|
| 233 |
+
by_input = grouped_summary(rows, "input_bucket")
|
| 234 |
+
by_depth = grouped_summary(rows, "output_depth_bucket")
|
| 235 |
+
by_exact_depth = grouped_summary(rows, "output_depth")
|
| 236 |
+
by_sample = grouped_summary(rows, "sample_id")
|
| 237 |
+
|
| 238 |
+
fields = sorted(set(overall) | {field for row in by_input + by_depth + by_exact_depth + by_sample for field in row})
|
| 239 |
+
write_csv(output_dir / "overall.csv", [overall], fields)
|
| 240 |
+
write_csv(output_dir / "by_input_bucket.csv", by_input, fields)
|
| 241 |
+
write_csv(output_dir / "by_output_depth_bucket.csv", by_depth, fields)
|
| 242 |
+
write_csv(output_dir / "by_output_depth.csv", by_exact_depth, fields)
|
| 243 |
+
write_csv(output_dir / "by_sample.csv", by_sample, fields)
|
| 244 |
+
write_markdown(output_dir / "summary.md", overall, by_input, by_depth, by_exact_depth)
|
| 245 |
+
print(f"Wrote {output_dir / 'summary.md'}")
|
| 246 |
+
print(f"Wrote {output_dir / 'overall.csv'}")
|
| 247 |
+
print(f"Wrote {output_dir / 'by_input_bucket.csv'}")
|
| 248 |
+
print(f"Wrote {output_dir / 'by_output_depth_bucket.csv'}")
|
| 249 |
+
print(f"Wrote {output_dir / 'by_output_depth.csv'}")
|
| 250 |
+
print(f"Wrote {output_dir / 'by_sample.csv'}")
|
| 251 |
+
return 0
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
if __name__ == "__main__":
|
| 255 |
+
raise SystemExit(main())
|
tools/vllm_worker_verify_pipeline/verify_vllm_worker_evidence.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import csv
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Dict, List, Optional, Sequence
|
| 12 |
+
|
| 13 |
+
from pipeline_common import (
|
| 14 |
+
VariantInfo,
|
| 15 |
+
build_llm_kwargs,
|
| 16 |
+
build_sampling_params,
|
| 17 |
+
dataclass_to_dict,
|
| 18 |
+
logprob_for_token,
|
| 19 |
+
make_tokens_prompt,
|
| 20 |
+
normalize_logprob_dict,
|
| 21 |
+
probability_metrics,
|
| 22 |
+
rank_for_token,
|
| 23 |
+
read_jsonl,
|
| 24 |
+
runtime_metadata,
|
| 25 |
+
safe_float,
|
| 26 |
+
sorted_token_ids,
|
| 27 |
+
tokenizer_hash,
|
| 28 |
+
tokenizer_name,
|
| 29 |
+
write_json,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def log(message: str) -> None:
|
| 34 |
+
print(message, flush=True)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def vllm_version() -> str:
|
| 38 |
+
try:
|
| 39 |
+
import vllm
|
| 40 |
+
|
| 41 |
+
return vllm.__version__
|
| 42 |
+
except Exception:
|
| 43 |
+
return ""
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def make_variant(args: argparse.Namespace, tokenizer: object) -> VariantInfo:
|
| 47 |
+
tok_hash = tokenizer_hash(tokenizer)
|
| 48 |
+
return VariantInfo(
|
| 49 |
+
variant_id=args.variant_id,
|
| 50 |
+
model=args.model,
|
| 51 |
+
tokenizer_hash=tok_hash,
|
| 52 |
+
tokenizer_name=tokenizer_name(tokenizer),
|
| 53 |
+
quantization=args.quantization,
|
| 54 |
+
gpu=args.gpu,
|
| 55 |
+
backend="vllm",
|
| 56 |
+
backend_version=vllm_version(),
|
| 57 |
+
dtype=args.dtype,
|
| 58 |
+
extra={
|
| 59 |
+
"cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"),
|
| 60 |
+
"tensor_parallel_size": args.tensor_parallel_size,
|
| 61 |
+
"gpu_memory_utilization": args.gpu_memory_utilization,
|
| 62 |
+
"max_model_len": args.max_model_len,
|
| 63 |
+
"max_num_seqs": args.max_num_seqs,
|
| 64 |
+
"max_num_batched_tokens": args.max_num_batched_tokens,
|
| 65 |
+
"max_logprobs": args.max_logprobs,
|
| 66 |
+
},
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def top_map(items: Sequence[dict]) -> Dict[str, Dict[str, object]]:
|
| 71 |
+
return {
|
| 72 |
+
str(int(item["token_id"])): {
|
| 73 |
+
"logprob": item.get("logprob"),
|
| 74 |
+
"rank": item.get("rank"),
|
| 75 |
+
"decoded_token": item.get("decoded_token"),
|
| 76 |
+
}
|
| 77 |
+
for item in items
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def vector_metrics(worker_top: Dict[str, Dict[str, object]],
|
| 82 |
+
verifier_top: Dict[str, Dict[str, object]],
|
| 83 |
+
missing_logprob: float) -> dict:
|
| 84 |
+
worker_tokens = set(worker_top)
|
| 85 |
+
verifier_tokens = set(verifier_top)
|
| 86 |
+
common = sorted_token_ids(worker_tokens & verifier_tokens)
|
| 87 |
+
union = sorted_token_ids(worker_tokens | verifier_tokens)
|
| 88 |
+
common_prob = probability_metrics(worker_top, verifier_top, common, missing_logprob)
|
| 89 |
+
union_prob = probability_metrics(worker_top, verifier_top, union, missing_logprob)
|
| 90 |
+
return {
|
| 91 |
+
"common_top_count": len(common),
|
| 92 |
+
"union_top_count": len(union),
|
| 93 |
+
"topk_jaccard": len(common) / len(union) if union else float("nan"),
|
| 94 |
+
"missing_from_verifier_count": len(worker_tokens - verifier_tokens),
|
| 95 |
+
"extra_in_verifier_count": len(verifier_tokens - worker_tokens),
|
| 96 |
+
"common_js_divergence": common_prob["js_divergence"],
|
| 97 |
+
"union_js_divergence": union_prob["js_divergence"],
|
| 98 |
+
"common_prob_cosine": common_prob["prob_cosine"],
|
| 99 |
+
"union_prob_cosine": union_prob["prob_cosine"],
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def compare_depth(worker_depth: dict,
|
| 104 |
+
verifier_logprobs: Dict[str, Dict[str, object]],
|
| 105 |
+
missing_logprob: float) -> dict:
|
| 106 |
+
target_token_id = int(worker_depth["target_token_id"])
|
| 107 |
+
worker_logprob = worker_depth.get("selected_logprob")
|
| 108 |
+
verifier_logprob = logprob_for_token(verifier_logprobs, target_token_id)
|
| 109 |
+
worker_rank = worker_depth.get("selected_rank")
|
| 110 |
+
verifier_rank = rank_for_token(verifier_logprobs, target_token_id)
|
| 111 |
+
worker_top = top_map(worker_depth.get("top_logprobs", []))
|
| 112 |
+
verifier_top = verifier_logprobs
|
| 113 |
+
lp_diff = (
|
| 114 |
+
safe_float(verifier_logprob) - safe_float(worker_logprob)
|
| 115 |
+
if worker_logprob is not None and verifier_logprob is not None
|
| 116 |
+
else float("nan")
|
| 117 |
+
)
|
| 118 |
+
if worker_rank is not None and verifier_rank is not None:
|
| 119 |
+
rank_delta = int(verifier_rank) - int(worker_rank)
|
| 120 |
+
else:
|
| 121 |
+
rank_delta = ""
|
| 122 |
+
return {
|
| 123 |
+
"depth": worker_depth.get("depth"),
|
| 124 |
+
"target_token_id": target_token_id,
|
| 125 |
+
"target_decoded_token": worker_depth.get("target_decoded_token"),
|
| 126 |
+
"worker_selected_logprob": worker_logprob,
|
| 127 |
+
"verifier_selected_logprob": verifier_logprob,
|
| 128 |
+
"logprob_diff_verifier_minus_worker": lp_diff,
|
| 129 |
+
"abs_logprob_diff": abs(lp_diff) if math.isfinite(lp_diff) else float("nan"),
|
| 130 |
+
"worker_selected_rank": worker_rank,
|
| 131 |
+
"verifier_selected_rank": verifier_rank,
|
| 132 |
+
"rank_delta_verifier_minus_worker": rank_delta,
|
| 133 |
+
**vector_metrics(worker_top, verifier_top, missing_logprob),
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def write_csv(path: Path, rows: Sequence[dict], fields: Sequence[str]) -> None:
|
| 138 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 139 |
+
with path.open("w", encoding="utf-8", newline="") as handle:
|
| 140 |
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
| 141 |
+
writer.writeheader()
|
| 142 |
+
for row in rows:
|
| 143 |
+
writer.writerow({field: row.get(field, "") for field in fields})
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def write_summary(path: Path, rows: Sequence[dict]) -> None:
|
| 147 |
+
finite_abs = [safe_float(row.get("abs_logprob_diff")) for row in rows]
|
| 148 |
+
finite_abs = [value for value in finite_abs if math.isfinite(value)]
|
| 149 |
+
missing_selected = sum(
|
| 150 |
+
1 for row in rows
|
| 151 |
+
if row.get("verifier_selected_logprob") in {"", None}
|
| 152 |
+
)
|
| 153 |
+
max_abs = max(finite_abs, default=float("nan"))
|
| 154 |
+
mean_abs = sum(finite_abs) / len(finite_abs) if finite_abs else float("nan")
|
| 155 |
+
sorted_rows = sorted(
|
| 156 |
+
rows,
|
| 157 |
+
key=lambda row: safe_float(row.get("abs_logprob_diff"), -1.0),
|
| 158 |
+
reverse=True,
|
| 159 |
+
)
|
| 160 |
+
lines = [
|
| 161 |
+
"# vLLM worker evidence verification",
|
| 162 |
+
"",
|
| 163 |
+
f"- depth rows: {len(rows)}",
|
| 164 |
+
f"- missing verifier selected logprob: {missing_selected}",
|
| 165 |
+
f"- max abs logprob diff: {max_abs:.8g}",
|
| 166 |
+
f"- mean abs logprob diff: {mean_abs:.8g}",
|
| 167 |
+
"",
|
| 168 |
+
"| sample | depth | token | worker_lp | verifier_lp | abs_diff | worker/verifier_rank | jaccard | union_js |",
|
| 169 |
+
"|---|---:|---|---:|---:|---:|---:|---:|---:|",
|
| 170 |
+
]
|
| 171 |
+
for row in sorted_rows[:50]:
|
| 172 |
+
lines.append(
|
| 173 |
+
"| {sample} | {depth} | `{token}` | {worker:.8g} | {verifier:.8g} | {diff:.8g} | "
|
| 174 |
+
"{wrank}/{vrank} | {jaccard:.8g} | {js:.8g} |".format(
|
| 175 |
+
sample=row.get("sample_id"),
|
| 176 |
+
depth=row.get("depth"),
|
| 177 |
+
token=str(row.get("target_decoded_token", "")).replace("\n", "\\n"),
|
| 178 |
+
worker=safe_float(row.get("worker_selected_logprob")),
|
| 179 |
+
verifier=safe_float(row.get("verifier_selected_logprob")),
|
| 180 |
+
diff=safe_float(row.get("abs_logprob_diff")),
|
| 181 |
+
wrank=row.get("worker_selected_rank"),
|
| 182 |
+
vrank=row.get("verifier_selected_rank"),
|
| 183 |
+
jaccard=safe_float(row.get("topk_jaccard")),
|
| 184 |
+
js=safe_float(row.get("union_js_divergence")),
|
| 185 |
+
)
|
| 186 |
+
)
|
| 187 |
+
lines.append("")
|
| 188 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 192 |
+
parser = argparse.ArgumentParser(
|
| 193 |
+
description="Recompute vLLM prompt logprobs for worker evidence and compare per output token."
|
| 194 |
+
)
|
| 195 |
+
parser.add_argument("--evidence", required=True)
|
| 196 |
+
parser.add_argument("--output-dir", default="results/vllm_worker_verify")
|
| 197 |
+
parser.add_argument("--model", required=True)
|
| 198 |
+
parser.add_argument("--variant-id", required=True)
|
| 199 |
+
parser.add_argument("--gpu", default="")
|
| 200 |
+
parser.add_argument("--quantization", default="bf16")
|
| 201 |
+
parser.add_argument("--dtype", default="auto")
|
| 202 |
+
parser.add_argument("--trust-remote-code", action="store_true")
|
| 203 |
+
parser.add_argument("--tensor-parallel-size", type=int, default=1)
|
| 204 |
+
parser.add_argument("--gpu-memory-utilization", type=float, default=None)
|
| 205 |
+
parser.add_argument("--max-model-len", type=int, default=None)
|
| 206 |
+
parser.add_argument("--max-num-seqs", type=int, default=None)
|
| 207 |
+
parser.add_argument("--max-num-batched-tokens", type=int, default=None)
|
| 208 |
+
parser.add_argument("--max-logprobs", type=int, default=None)
|
| 209 |
+
parser.add_argument("--prompt-logprobs", type=int, default=64)
|
| 210 |
+
parser.add_argument("--temperature", type=float, default=0.0)
|
| 211 |
+
parser.add_argument("--top-p", type=float, default=1.0)
|
| 212 |
+
parser.add_argument("--top-k", type=int, default=0)
|
| 213 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 214 |
+
parser.add_argument("--batch-size", type=int, default=4)
|
| 215 |
+
parser.add_argument("--missing-logprob", type=float, default=-100.0)
|
| 216 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 217 |
+
parser.add_argument("--max-total-tokens", type=int, default=0,
|
| 218 |
+
help="Skip evidence rows whose input+output token count exceeds this value.")
|
| 219 |
+
args = parser.parse_args(argv)
|
| 220 |
+
|
| 221 |
+
from transformers import AutoTokenizer
|
| 222 |
+
from vllm import LLM
|
| 223 |
+
|
| 224 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 225 |
+
args.model,
|
| 226 |
+
trust_remote_code=args.trust_remote_code,
|
| 227 |
+
)
|
| 228 |
+
variant = make_variant(args, tokenizer)
|
| 229 |
+
llm_kwargs = build_llm_kwargs(args)
|
| 230 |
+
log(f"Loading verifier vLLM with kwargs: {llm_kwargs}")
|
| 231 |
+
llm = LLM(**llm_kwargs)
|
| 232 |
+
sampling_params = build_sampling_params(
|
| 233 |
+
args,
|
| 234 |
+
max_tokens=1,
|
| 235 |
+
logprobs=None,
|
| 236 |
+
prompt_logprobs=args.prompt_logprobs,
|
| 237 |
+
detokenize=False,
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
evidence_rows = []
|
| 241 |
+
skipped_too_long = 0
|
| 242 |
+
for index, row in enumerate(read_jsonl(Path(args.evidence)), start=1):
|
| 243 |
+
if args.limit and index > args.limit:
|
| 244 |
+
break
|
| 245 |
+
total_tokens = len(row.get("input_ids", [])) + len(row.get("output_ids", []))
|
| 246 |
+
if args.max_total_tokens and total_tokens > args.max_total_tokens:
|
| 247 |
+
skipped_too_long += 1
|
| 248 |
+
continue
|
| 249 |
+
evidence_rows.append(row)
|
| 250 |
+
log(
|
| 251 |
+
f"Loaded evidence rows: {len(evidence_rows)} "
|
| 252 |
+
f"(skipped_too_long={skipped_too_long})"
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
output_dir = Path(args.output_dir)
|
| 256 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 257 |
+
metric_rows: List[dict] = []
|
| 258 |
+
total_start = time.time()
|
| 259 |
+
for batch_start in range(0, len(evidence_rows), args.batch_size):
|
| 260 |
+
batch = evidence_rows[batch_start:batch_start + args.batch_size]
|
| 261 |
+
prompts = [
|
| 262 |
+
make_tokens_prompt(row["input_ids"] + row["output_ids"])
|
| 263 |
+
for row in batch
|
| 264 |
+
]
|
| 265 |
+
lengths = [len(row["input_ids"]) + len(row["output_ids"]) for row in batch]
|
| 266 |
+
log(
|
| 267 |
+
f"Verifier prompt_logprobs batch {batch_start // args.batch_size + 1}, "
|
| 268 |
+
f"size={len(batch)}, max_tokens={max(lengths)}, total_tokens={sum(lengths)}"
|
| 269 |
+
)
|
| 270 |
+
outputs = llm.generate(prompts, sampling_params)
|
| 271 |
+
if len(outputs) != len(batch):
|
| 272 |
+
raise RuntimeError(f"vLLM returned {len(outputs)} outputs for {len(batch)} prompts")
|
| 273 |
+
for evidence, request_output in zip(batch, outputs):
|
| 274 |
+
input_len = len(evidence["input_ids"])
|
| 275 |
+
prompt_logprobs = list(getattr(request_output, "prompt_logprobs", []) or [])
|
| 276 |
+
worker_trace = evidence.get("worker_trace", [])
|
| 277 |
+
for worker_depth in worker_trace:
|
| 278 |
+
depth = int(worker_depth["depth"])
|
| 279 |
+
prompt_pos = input_len + depth
|
| 280 |
+
verifier_logprobs = (
|
| 281 |
+
normalize_logprob_dict(prompt_logprobs[prompt_pos])
|
| 282 |
+
if prompt_pos < len(prompt_logprobs) else {}
|
| 283 |
+
)
|
| 284 |
+
row = compare_depth(worker_depth, verifier_logprobs, args.missing_logprob)
|
| 285 |
+
row.update({
|
| 286 |
+
"sample_id": evidence.get("sample_id"),
|
| 287 |
+
"input_token_count": input_len,
|
| 288 |
+
"output_token_count": len(evidence.get("output_ids", [])),
|
| 289 |
+
"worker_trace_mode": evidence.get("worker_trace_mode"),
|
| 290 |
+
"verifier_trace_mode": "vllm_prompt_logprobs_full_prefill",
|
| 291 |
+
})
|
| 292 |
+
metric_rows.append(row)
|
| 293 |
+
|
| 294 |
+
fields = [
|
| 295 |
+
"sample_id",
|
| 296 |
+
"depth",
|
| 297 |
+
"input_token_count",
|
| 298 |
+
"output_token_count",
|
| 299 |
+
"target_token_id",
|
| 300 |
+
"target_decoded_token",
|
| 301 |
+
"worker_trace_mode",
|
| 302 |
+
"verifier_trace_mode",
|
| 303 |
+
"worker_selected_logprob",
|
| 304 |
+
"verifier_selected_logprob",
|
| 305 |
+
"logprob_diff_verifier_minus_worker",
|
| 306 |
+
"abs_logprob_diff",
|
| 307 |
+
"worker_selected_rank",
|
| 308 |
+
"verifier_selected_rank",
|
| 309 |
+
"rank_delta_verifier_minus_worker",
|
| 310 |
+
"common_top_count",
|
| 311 |
+
"union_top_count",
|
| 312 |
+
"topk_jaccard",
|
| 313 |
+
"missing_from_verifier_count",
|
| 314 |
+
"extra_in_verifier_count",
|
| 315 |
+
"common_js_divergence",
|
| 316 |
+
"union_js_divergence",
|
| 317 |
+
"common_prob_cosine",
|
| 318 |
+
"union_prob_cosine",
|
| 319 |
+
]
|
| 320 |
+
write_csv(output_dir / "worker_vs_verifier_depth_metrics.csv", metric_rows, fields)
|
| 321 |
+
write_summary(output_dir / "summary.md", metric_rows)
|
| 322 |
+
write_json(output_dir / "metadata.json", {
|
| 323 |
+
"metadata": runtime_metadata(sys.argv),
|
| 324 |
+
"args": vars(args),
|
| 325 |
+
"verifier_variant": dataclass_to_dict(variant),
|
| 326 |
+
"evidence_count": len(evidence_rows),
|
| 327 |
+
"skipped_too_long": skipped_too_long,
|
| 328 |
+
"depth_row_count": len(metric_rows),
|
| 329 |
+
"elapsed_seconds": time.time() - total_start,
|
| 330 |
+
})
|
| 331 |
+
log(f"Wrote {output_dir / 'worker_vs_verifier_depth_metrics.csv'}")
|
| 332 |
+
log(f"Wrote {output_dir / 'summary.md'}")
|
| 333 |
+
return 0
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
if __name__ == "__main__":
|
| 337 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/README.md
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Worker Logits Verify
|
| 2 |
+
|
| 3 |
+
This project is a redesigned worker-verify experiment that does not rely on the old first-token batch/fork logic. The core goal is to build a **depth-aware logits/logprob fingerprint along the same context path**, used to distinguish:
|
| 4 |
+
|
| 5 |
+
- Should pass: legitimate numerical drift of `Qwen3-32B BF16` between `H100` and `RTX Pro 6000`.
|
| 6 |
+
- Should fail: challenges to `Qwen3-32B BF16` identity from `Qwen3-32B FP8/AWQ`, `Qwen3-14B`, and `Qwen3-8B`.
|
| 7 |
+
|
| 8 |
+
## Experiment definition
|
| 9 |
+
|
| 10 |
+
First, fix a canonical input-output pair:
|
| 11 |
+
|
| 12 |
+
```text
|
| 13 |
+
anchor = Qwen3-32B BF16 on H100
|
| 14 |
+
sample = input_text + canonical_output_text
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
After that, every variant performs a teacher-forced replay:
|
| 18 |
+
|
| 19 |
+
```text
|
| 20 |
+
context_t = input_ids + output_ids[:t]
|
| 21 |
+
target_t = output_ids[t]
|
| 22 |
+
logits_t = model(context_t).logits[-1]
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
This compares the numerical drift along the same output path, not free-generation branching.
|
| 26 |
+
|
| 27 |
+
## Why not use vLLM logprobs
|
| 28 |
+
|
| 29 |
+
The vLLM API usually returns logprobs, i.e. the values after `log_softmax(logits)`, not raw logits. This project's collection backend uses `transformers` first, taking directly from the forward output:
|
| 30 |
+
|
| 31 |
+
- `raw_logits`
|
| 32 |
+
- `logprobs`
|
| 33 |
+
- selected token rank
|
| 34 |
+
- top-k logprob fingerprint
|
| 35 |
+
- probe token logprob fingerprint
|
| 36 |
+
|
| 37 |
+
Raw logits are used for identity fingerprint research; logprob/rank/NLL are used as the main verification metrics.
|
| 38 |
+
|
| 39 |
+
## Data scale
|
| 40 |
+
|
| 41 |
+
By default, 6 input token length buckets are generated:
|
| 42 |
+
|
| 43 |
+
```text
|
| 44 |
+
32, 128, 512, 2048, 8192, 16384
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
50 samples per bucket, 300 total. The default anchor output generates 128 tokens, so the first version is roughly:
|
| 48 |
+
|
| 49 |
+
```text
|
| 50 |
+
300 * 128 = 38,400 depth rows / variant
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
If the H100 vs 6000 envelope is very narrow and the negative samples clearly fail, expand to 100 samples per bucket or a longer output.
|
| 54 |
+
|
| 55 |
+
## Installation
|
| 56 |
+
|
| 57 |
+
```bash
|
| 58 |
+
cd worker_logits_verify
|
| 59 |
+
python3 -m pip install -e ".[transformers]"
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
If you already have a GPU environment, you can also run directly:
|
| 63 |
+
|
| 64 |
+
```bash
|
| 65 |
+
PYTHONPATH=src python3 -m worker_logits_verify.generate_prompts --help
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
## 1. Generate calibration inputs
|
| 69 |
+
|
| 70 |
+
```bash
|
| 71 |
+
worker-logits-generate-prompts \
|
| 72 |
+
--model /models/Qwen3-32B \
|
| 73 |
+
--buckets 32,128,512,2048,8192,16384 \
|
| 74 |
+
--per-bucket 50 \
|
| 75 |
+
--output data/qwen3_32b_identity_v1/prompts.jsonl \
|
| 76 |
+
--trust-remote-code
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
## 2. Generate the canonical output
|
| 80 |
+
|
| 81 |
+
Recommended to fix:
|
| 82 |
+
|
| 83 |
+
```text
|
| 84 |
+
Qwen3-32B BF16 on H100
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
```bash
|
| 88 |
+
worker-logits-generate-anchor \
|
| 89 |
+
--model /models/Qwen3-32B \
|
| 90 |
+
--variant-id qwen3-32b-bf16-h100 \
|
| 91 |
+
--gpu H100 \
|
| 92 |
+
--quantization bf16 \
|
| 93 |
+
--dtype bfloat16 \
|
| 94 |
+
--input data/qwen3_32b_identity_v1/prompts.jsonl \
|
| 95 |
+
--output data/qwen3_32b_identity_v1/anchor_samples.jsonl \
|
| 96 |
+
--max-new-tokens 128 \
|
| 97 |
+
--trust-remote-code
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
## 3. Collect H100 and 6000 traces
|
| 101 |
+
|
| 102 |
+
H100:
|
| 103 |
+
|
| 104 |
+
```bash
|
| 105 |
+
worker-logits-collect-trace \
|
| 106 |
+
--samples data/qwen3_32b_identity_v1/anchor_samples.jsonl \
|
| 107 |
+
--model /models/Qwen3-32B \
|
| 108 |
+
--variant-id qwen3-32b-bf16-h100 \
|
| 109 |
+
--gpu H100 \
|
| 110 |
+
--quantization bf16 \
|
| 111 |
+
--dtype bfloat16 \
|
| 112 |
+
--output-dir results/qwen3_32b_identity_v1/traces/qwen3-32b-bf16-h100 \
|
| 113 |
+
--top-k 64 \
|
| 114 |
+
--trust-remote-code
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
6000:
|
| 118 |
+
|
| 119 |
+
```bash
|
| 120 |
+
worker-logits-collect-trace \
|
| 121 |
+
--samples data/qwen3_32b_identity_v1/anchor_samples.jsonl \
|
| 122 |
+
--model /models/Qwen3-32B \
|
| 123 |
+
--variant-id qwen3-32b-bf16-6000 \
|
| 124 |
+
--gpu RTXPro6000 \
|
| 125 |
+
--quantization bf16 \
|
| 126 |
+
--dtype bfloat16 \
|
| 127 |
+
--output-dir results/qwen3_32b_identity_v1/traces/qwen3-32b-bf16-6000 \
|
| 128 |
+
--top-k 64 \
|
| 129 |
+
--trust-remote-code
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
## 4. Build the legitimate cross-GPU envelope
|
| 133 |
+
|
| 134 |
+
```bash
|
| 135 |
+
worker-logits-compare-traces \
|
| 136 |
+
--left results/qwen3_32b_identity_v1/traces/qwen3-32b-bf16-h100 \
|
| 137 |
+
--right results/qwen3_32b_identity_v1/traces/qwen3-32b-bf16-6000 \
|
| 138 |
+
--left-label H100-BF16 \
|
| 139 |
+
--right-label 6000-BF16 \
|
| 140 |
+
--output-dir results/qwen3_32b_identity_v1/comparisons/h100_vs_6000_bf16
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
First analyze whether token depth actually changes drift:
|
| 144 |
+
|
| 145 |
+
```bash
|
| 146 |
+
worker-logits-analyze-depth-effect \
|
| 147 |
+
--comparison results/qwen3_32b_identity_v1/comparisons/h100_vs_6000_bf16 \
|
| 148 |
+
--output-dir results/qwen3_32b_identity_v1/depth_effect/h100_vs_6000_bf16
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
Focus on:
|
| 152 |
+
|
| 153 |
+
- `depth_bucket_summary.csv`: p50/p95/p99/max per depth bucket.
|
| 154 |
+
- `depth_trends.csv`: slope / Pearson r / R2 of each metric against absolute depth and relative depth.
|
| 155 |
+
- `cumulative_by_sample.csv`: cumulative NLL delta and cumulative abs drift within each sample.
|
| 156 |
+
- `summary.md`: a quick-read summary.
|
| 157 |
+
|
| 158 |
+
If the slope is close to 0 and R2 is very low, depth is not a major factor; if the slope is clearly positive and bucket p95/p99 rise with depth, then depth buckets need to be kept in the profile.
|
| 159 |
+
|
| 160 |
+
Then build the legitimate envelope:
|
| 161 |
+
|
| 162 |
+
```bash
|
| 163 |
+
|
| 164 |
+
worker-logits-calibrate-profile \
|
| 165 |
+
--comparison results/qwen3_32b_identity_v1/comparisons/h100_vs_6000_bf16 \
|
| 166 |
+
--profile-id qwen3-32b-bf16-h100-6000-envelope \
|
| 167 |
+
--variant-pair "Qwen3-32B BF16 H100 vs RTXPro6000" \
|
| 168 |
+
--output-dir results/qwen3_32b_identity_v1/profiles/h100_6000_bf16
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
## 5. Run the negative-sample challenges
|
| 172 |
+
|
| 173 |
+
For example FP8:
|
| 174 |
+
|
| 175 |
+
```bash
|
| 176 |
+
worker-logits-collect-trace \
|
| 177 |
+
--samples data/qwen3_32b_identity_v1/anchor_samples.jsonl \
|
| 178 |
+
--model /models/Qwen3-32B-FP8 \
|
| 179 |
+
--variant-id qwen3-32b-fp8-h100 \
|
| 180 |
+
--gpu H100 \
|
| 181 |
+
--quantization fp8 \
|
| 182 |
+
--dtype auto \
|
| 183 |
+
--output-dir results/qwen3_32b_identity_v1/traces/qwen3-32b-fp8-h100 \
|
| 184 |
+
--top-k 64 \
|
| 185 |
+
--trust-remote-code \
|
| 186 |
+
--allow-retokenize
|
| 187 |
+
|
| 188 |
+
worker-logits-compare-traces \
|
| 189 |
+
--left results/qwen3_32b_identity_v1/traces/qwen3-32b-bf16-h100 \
|
| 190 |
+
--right results/qwen3_32b_identity_v1/traces/qwen3-32b-fp8-h100 \
|
| 191 |
+
--left-label H100-BF16 \
|
| 192 |
+
--right-label H100-FP8 \
|
| 193 |
+
--output-dir results/qwen3_32b_identity_v1/comparisons/bf16_vs_fp8
|
| 194 |
+
|
| 195 |
+
worker-logits-verify-comparison \
|
| 196 |
+
--comparison results/qwen3_32b_identity_v1/comparisons/bf16_vs_fp8 \
|
| 197 |
+
--profile results/qwen3_32b_identity_v1/profiles/h100_6000_bf16/profile.json \
|
| 198 |
+
--output-dir results/qwen3_32b_identity_v1/verifications/bf16_vs_fp8
|
| 199 |
+
```
|
| 200 |
+
|
| 201 |
+
The expected verification verdict for FP8/AWQ/14B/8B is `FAIL`.
|
| 202 |
+
|
| 203 |
+
## Worker Evidence vs Verifier Logprob
|
| 204 |
+
|
| 205 |
+
If you already have `prompts.jsonl` and want to verify directly:
|
| 206 |
+
|
| 207 |
+
```text
|
| 208 |
+
the logprob produced during worker decode
|
| 209 |
+
vs
|
| 210 |
+
the logprob the verifier recomputes for the same input+output
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
you can go through the vLLM evidence pipeline.
|
| 214 |
+
|
| 215 |
+
Step one: generate output in the worker environment, and at the same time save each output token's decode-time logprob/top-k:
|
| 216 |
+
|
| 217 |
+
```bash
|
| 218 |
+
worker-logits-collect-vllm-evidence \
|
| 219 |
+
--input data/qwen3_32b_identity_v1/prompts.jsonl \
|
| 220 |
+
--output data/qwen3_32b_identity_v1/worker_evidence.h100.jsonl \
|
| 221 |
+
--model Qwen/Qwen3-32B \
|
| 222 |
+
--variant-id qwen3-32b-bf16-h100 \
|
| 223 |
+
--gpu H100 \
|
| 224 |
+
--quantization bf16 \
|
| 225 |
+
--dtype bfloat16 \
|
| 226 |
+
--max-new-tokens 128 \
|
| 227 |
+
--logprobs 64 \
|
| 228 |
+
--max-logprobs 64 \
|
| 229 |
+
--batch-size 8 \
|
| 230 |
+
--trust-remote-code
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
+
Step two: in the verifier environment, run vLLM `prompt_logprobs` on the same `input_ids + output_ids`, and compare against the worker evidence token by token:
|
| 234 |
+
|
| 235 |
+
```bash
|
| 236 |
+
worker-logits-verify-vllm-evidence \
|
| 237 |
+
--evidence data/qwen3_32b_identity_v1/worker_evidence.h100.jsonl \
|
| 238 |
+
--output-dir results/qwen3_32b_identity_v1/worker_verify/h100_worker_vs_6000_verifier \
|
| 239 |
+
--model Qwen/Qwen3-32B \
|
| 240 |
+
--variant-id qwen3-32b-bf16-6000-verifier \
|
| 241 |
+
--gpu RTXPro6000 \
|
| 242 |
+
--quantization bf16 \
|
| 243 |
+
--dtype bfloat16 \
|
| 244 |
+
--prompt-logprobs 64 \
|
| 245 |
+
--max-logprobs 64 \
|
| 246 |
+
--batch-size 4 \
|
| 247 |
+
--trust-remote-code
|
| 248 |
+
```
|
| 249 |
+
|
| 250 |
+
You can also use a single-command script to chain prompt generation, worker evidence collection, verifier comparison, and distribution summarization:
|
| 251 |
+
|
| 252 |
+
```bash
|
| 253 |
+
worker-logits-run-vllm-worker-verify \
|
| 254 |
+
--baseline-model /models/Qwen3-32B \
|
| 255 |
+
--comparison-model /models/Qwen3-32B-FP8 \
|
| 256 |
+
--baseline-variant-id qwen3-32b-bf16-worker \
|
| 257 |
+
--comparison-variant-id qwen3-32b-fp8-verifier \
|
| 258 |
+
--baseline-quantization bf16 \
|
| 259 |
+
--comparison-quantization fp8 \
|
| 260 |
+
--baseline-dtype bfloat16 \
|
| 261 |
+
--comparison-dtype auto \
|
| 262 |
+
--buckets 32,128,512,2048,8192,16384 \
|
| 263 |
+
--per-bucket 50 \
|
| 264 |
+
--max-new-tokens 128 \
|
| 265 |
+
--logprobs 64 \
|
| 266 |
+
--prompt-logprobs 64 \
|
| 267 |
+
--max-logprobs 64 \
|
| 268 |
+
--worker-batch-size 8 \
|
| 269 |
+
--verifier-batch-size 4 \
|
| 270 |
+
--output-root results/vllm_worker_verify_runs \
|
| 271 |
+
--trust-remote-code
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
Common helper flags:
|
| 275 |
+
|
| 276 |
+
- `--dry-run`: only print the pipeline commands that would run, to check paths, dtype, quantization, and batch size first.
|
| 277 |
+
- `--prompts path/to/prompts.jsonl`: reuse existing prompts and skip `worker-logits-generate-prompts`.
|
| 278 |
+
- `--resume`: reuse stage artifacts that already exist; `--force`: overwrite stage artifacts.
|
| 279 |
+
- `--baseline-tensor-parallel-size` / `--comparison-tensor-parallel-size`: set separately when the two models need different TP.
|
| 280 |
+
|
| 281 |
+
The default output directory is:
|
| 282 |
+
|
| 283 |
+
```text
|
| 284 |
+
results/vllm_worker_verify_runs/<run-id>/
|
| 285 |
+
data/prompts.jsonl
|
| 286 |
+
data/worker_evidence.<baseline>.jsonl
|
| 287 |
+
worker_verify/<baseline>_worker_vs_<comparison>_verifier/
|
| 288 |
+
worker_vs_verifier_depth_metrics.csv
|
| 289 |
+
summary.md
|
| 290 |
+
distribution/summary.md
|
| 291 |
+
```
|
| 292 |
+
|
| 293 |
+
This output tells you:
|
| 294 |
+
|
| 295 |
+
- `worker_selected_logprob`
|
| 296 |
+
- `verifier_selected_logprob`
|
| 297 |
+
- `abs_logprob_diff`
|
| 298 |
+
- `worker_selected_rank` / `verifier_selected_rank`
|
| 299 |
+
- the overlap / JS / cosine between the worker top-k and the verifier top-k
|
| 300 |
+
|
| 301 |
+
Note that in this pipeline the verifier is `full-prefill prompt_logprobs` while the worker is `decode generate logprobs`. This also lets it measure exactly:
|
| 302 |
+
|
| 303 |
+
```text
|
| 304 |
+
how large the difference is between decode-time worker logprob and full-prefill verifier logprob
|
| 305 |
+
```
|
| 306 |
+
|
| 307 |
+
If this mode delta is large, strict verification requires the verifier to also do a decode replay rather than using a full-prefill approximation.
|
| 308 |
+
|
| 309 |
+
## Core metrics
|
| 310 |
+
|
| 311 |
+
For each depth, record:
|
| 312 |
+
|
| 313 |
+
- selected token raw logit / logprob / rank
|
| 314 |
+
- top1/top2 token and margin
|
| 315 |
+
- top-k token/logprob/raw_logit map
|
| 316 |
+
- top-k mass
|
| 317 |
+
- fixed probe token logprobs
|
| 318 |
+
|
| 319 |
+
When comparing, output:
|
| 320 |
+
|
| 321 |
+
- `selected_abs_logprob_diff`
|
| 322 |
+
- `selected_abs_raw_logit_diff`
|
| 323 |
+
- `selected_abs_rank_delta`
|
| 324 |
+
- `top1_equal`
|
| 325 |
+
- `topk_jaccard`
|
| 326 |
+
- top-k observed common/union cosine, KL, JS
|
| 327 |
+
- probe logprob cosine / max abs diff
|
| 328 |
+
- cumulative NLL delta
|
| 329 |
+
|
| 330 |
+
Note: top-k KL/JS are only engineering metrics over the observed support, not full-vocab KL.
|
| 331 |
+
|
| 332 |
+
## File structure
|
| 333 |
+
|
| 334 |
+
```text
|
| 335 |
+
src/worker_logits_verify/
|
| 336 |
+
generate_prompts.py # generate calibration inputs across input length buckets
|
| 337 |
+
generate_anchor_outputs.py # fix the canonical output using the anchor model
|
| 338 |
+
collect_trace.py # teacher-forced replay to collect the depth trace
|
| 339 |
+
compare_traces.py # same-depth drift comparison between two variants
|
| 340 |
+
calibrate_profile.py # build the accepted envelope from H100 vs 6000
|
| 341 |
+
verify_comparison.py # use the profile to decide whether a negative sample is out of bounds
|
| 342 |
+
analyze_depth_effect.py # specifically analyze whether drift grows with token depth
|
| 343 |
+
collect_vllm_worker_evidence.py
|
| 344 |
+
verify_vllm_worker_evidence.py
|
| 345 |
+
schema.py
|
| 346 |
+
metrics.py
|
| 347 |
+
tokenizer_utils.py
|
| 348 |
+
```
|
tools/worker_logits_verify/configs/variants.example.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"anchor": {
|
| 3 |
+
"variant_id": "qwen3-32b-bf16-h100",
|
| 4 |
+
"model": "/models/Qwen3-32B",
|
| 5 |
+
"gpu": "H100",
|
| 6 |
+
"quantization": "bf16",
|
| 7 |
+
"dtype": "bfloat16"
|
| 8 |
+
},
|
| 9 |
+
"accepted": [
|
| 10 |
+
{
|
| 11 |
+
"variant_id": "qwen3-32b-bf16-h100",
|
| 12 |
+
"model": "/models/Qwen3-32B",
|
| 13 |
+
"gpu": "H100",
|
| 14 |
+
"quantization": "bf16",
|
| 15 |
+
"dtype": "bfloat16"
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"variant_id": "qwen3-32b-bf16-6000",
|
| 19 |
+
"model": "/models/Qwen3-32B",
|
| 20 |
+
"gpu": "RTXPro6000",
|
| 21 |
+
"quantization": "bf16",
|
| 22 |
+
"dtype": "bfloat16"
|
| 23 |
+
}
|
| 24 |
+
],
|
| 25 |
+
"negative_controls": [
|
| 26 |
+
{
|
| 27 |
+
"variant_id": "qwen3-32b-fp8-h100",
|
| 28 |
+
"model": "/models/Qwen3-32B-FP8",
|
| 29 |
+
"gpu": "H100",
|
| 30 |
+
"quantization": "fp8",
|
| 31 |
+
"dtype": "auto"
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"variant_id": "qwen3-32b-awq-h100",
|
| 35 |
+
"model": "/models/Qwen3-32B-AWQ",
|
| 36 |
+
"gpu": "H100",
|
| 37 |
+
"quantization": "awq",
|
| 38 |
+
"dtype": "auto"
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"variant_id": "qwen3-14b-bf16-h100",
|
| 42 |
+
"model": "/models/Qwen3-14B",
|
| 43 |
+
"gpu": "H100",
|
| 44 |
+
"quantization": "bf16",
|
| 45 |
+
"dtype": "bfloat16"
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"variant_id": "qwen3-8b-bf16-h100",
|
| 49 |
+
"model": "/models/Qwen3-8B",
|
| 50 |
+
"gpu": "H100",
|
| 51 |
+
"quantization": "bf16",
|
| 52 |
+
"dtype": "bfloat16"
|
| 53 |
+
}
|
| 54 |
+
]
|
| 55 |
+
}
|
tools/worker_logits_verify/examples/tiny_challenger/metadata.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"variant": {
|
| 3 |
+
"variant_id": "tiny-challenger"
|
| 4 |
+
}
|
| 5 |
+
}
|
tools/worker_logits_verify/examples/tiny_challenger/trace.jsonl
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"depth": 0, "input_token_count": 8, "metadata": {}, "output_token_count": 2, "probe_logprobs": {"1": -0.9, "2": -0.8}, "probe_raw_logits": {"1": 2.9, "2": 3.0}, "sample_id": "tiny-a", "selected_logprob": -0.9, "selected_rank": 2, "selected_raw_logit": 2.9, "target_decoded_token": " yes", "target_token_id": 1, "top1_logprob": -0.8, "top1_raw_logit": 3.0, "top1_token_id": 2, "top1_top2_margin_logprob": 0.1, "top2_logprob": -0.9, "top2_raw_logit": 2.9, "top2_token_id": 1, "top_k_mass": 0.86, "top_logprobs": [{"decoded_token": " no", "logprob": -0.8, "rank": 1, "raw_logit": 3.0, "token_id": 2}, {"decoded_token": " yes", "logprob": -0.9, "rank": 2, "raw_logit": 2.9, "token_id": 1}], "variant_id": "tiny-challenger"}
|
| 2 |
+
{"depth": 1, "input_token_count": 8, "metadata": {}, "output_token_count": 2, "probe_logprobs": {"3": -1.2, "4": -0.5}, "probe_raw_logits": {"3": 2.1, "4": 2.8}, "sample_id": "tiny-a", "selected_logprob": -1.2, "selected_rank": 2, "selected_raw_logit": 2.1, "target_decoded_token": " ok", "target_token_id": 3, "top1_logprob": -0.5, "top1_raw_logit": 2.8, "top1_token_id": 4, "top1_top2_margin_logprob": 0.7, "top2_logprob": -1.2, "top2_raw_logit": 2.1, "top2_token_id": 3, "top_k_mass": 0.9, "top_logprobs": [{"decoded_token": " bad", "logprob": -0.5, "rank": 1, "raw_logit": 2.8, "token_id": 4}, {"decoded_token": " ok", "logprob": -1.2, "rank": 2, "raw_logit": 2.1, "token_id": 3}], "variant_id": "tiny-challenger"}
|
tools/worker_logits_verify/examples/tiny_left/metadata.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"variant": {
|
| 3 |
+
"variant_id": "tiny-left"
|
| 4 |
+
}
|
| 5 |
+
}
|
tools/worker_logits_verify/examples/tiny_left/trace.jsonl
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"depth": 0, "input_token_count": 8, "metadata": {}, "output_token_count": 2, "probe_logprobs": {"1": -0.2, "2": -1.7}, "probe_raw_logits": {"1": 4.0, "2": 2.5}, "sample_id": "tiny-a", "selected_logprob": -0.2, "selected_rank": 1, "selected_raw_logit": 4.0, "target_decoded_token": " yes", "target_token_id": 1, "top1_logprob": -0.2, "top1_raw_logit": 4.0, "top1_token_id": 1, "top1_top2_margin_logprob": 1.5, "top2_logprob": -1.7, "top2_raw_logit": 2.5, "top2_token_id": 2, "top_k_mass": 0.999, "top_logprobs": [{"decoded_token": " yes", "logprob": -0.2, "rank": 1, "raw_logit": 4.0, "token_id": 1}, {"decoded_token": " no", "logprob": -1.7, "rank": 2, "raw_logit": 2.5, "token_id": 2}], "variant_id": "tiny-left"}
|
| 2 |
+
{"depth": 1, "input_token_count": 8, "metadata": {}, "output_token_count": 2, "probe_logprobs": {"3": -0.3, "4": -1.6}, "probe_raw_logits": {"3": 3.9, "4": 2.6}, "sample_id": "tiny-a", "selected_logprob": -0.3, "selected_rank": 1, "selected_raw_logit": 3.9, "target_decoded_token": " ok", "target_token_id": 3, "top1_logprob": -0.3, "top1_raw_logit": 3.9, "top1_token_id": 3, "top1_top2_margin_logprob": 1.3, "top2_logprob": -1.6, "top2_raw_logit": 2.6, "top2_token_id": 4, "top_k_mass": 0.995, "top_logprobs": [{"decoded_token": " ok", "logprob": -0.3, "rank": 1, "raw_logit": 3.9, "token_id": 3}, {"decoded_token": " bad", "logprob": -1.6, "rank": 2, "raw_logit": 2.6, "token_id": 4}], "variant_id": "tiny-left"}
|
tools/worker_logits_verify/examples/tiny_right/metadata.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"variant": {
|
| 3 |
+
"variant_id": "tiny-right"
|
| 4 |
+
}
|
| 5 |
+
}
|
tools/worker_logits_verify/examples/tiny_right/trace.jsonl
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"depth": 0, "input_token_count": 8, "metadata": {}, "output_token_count": 2, "probe_logprobs": {"1": -0.21, "2": -1.69}, "probe_raw_logits": {"1": 4.01, "2": 2.53}, "sample_id": "tiny-a", "selected_logprob": -0.21, "selected_rank": 1, "selected_raw_logit": 4.01, "target_decoded_token": " yes", "target_token_id": 1, "top1_logprob": -0.21, "top1_raw_logit": 4.01, "top1_token_id": 1, "top1_top2_margin_logprob": 1.48, "top2_logprob": -1.69, "top2_raw_logit": 2.53, "top2_token_id": 2, "top_k_mass": 0.998, "top_logprobs": [{"decoded_token": " yes", "logprob": -0.21, "rank": 1, "raw_logit": 4.01, "token_id": 1}, {"decoded_token": " no", "logprob": -1.69, "rank": 2, "raw_logit": 2.53, "token_id": 2}], "variant_id": "tiny-right"}
|
| 2 |
+
{"depth": 1, "input_token_count": 8, "metadata": {}, "output_token_count": 2, "probe_logprobs": {"3": -0.29, "4": -1.62}, "probe_raw_logits": {"3": 3.88, "4": 2.55}, "sample_id": "tiny-a", "selected_logprob": -0.29, "selected_rank": 1, "selected_raw_logit": 3.88, "target_decoded_token": " ok", "target_token_id": 3, "top1_logprob": -0.29, "top1_raw_logit": 3.88, "top1_token_id": 3, "top1_top2_margin_logprob": 1.33, "top2_logprob": -1.62, "top2_raw_logit": 2.55, "top2_token_id": 4, "top_k_mass": 0.996, "top_logprobs": [{"decoded_token": " ok", "logprob": -0.29, "rank": 1, "raw_logit": 3.88, "token_id": 3}, {"decoded_token": " bad", "logprob": -1.62, "rank": 2, "raw_logit": 2.55, "token_id": 4}], "variant_id": "tiny-right"}
|
tools/worker_logits_verify/pyproject.toml
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=61"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "worker-logits-verify"
|
| 7 |
+
version = "0.1.0"
|
| 8 |
+
description = "Depth-aware teacher-forced logits/logprob fingerprinting for worker output verification."
|
| 9 |
+
requires-python = ">=3.9"
|
| 10 |
+
dependencies = []
|
| 11 |
+
|
| 12 |
+
[project.optional-dependencies]
|
| 13 |
+
transformers = [
|
| 14 |
+
"accelerate",
|
| 15 |
+
"torch",
|
| 16 |
+
"transformers",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
[project.scripts]
|
| 20 |
+
worker-logits-generate-prompts = "worker_logits_verify.generate_prompts:main"
|
| 21 |
+
worker-logits-generate-anchor = "worker_logits_verify.generate_anchor_outputs:main"
|
| 22 |
+
worker-logits-collect-trace = "worker_logits_verify.collect_trace:main"
|
| 23 |
+
worker-logits-compare-traces = "worker_logits_verify.compare_traces:main"
|
| 24 |
+
worker-logits-calibrate-profile = "worker_logits_verify.calibrate_profile:main"
|
| 25 |
+
worker-logits-verify-comparison = "worker_logits_verify.verify_comparison:main"
|
| 26 |
+
worker-logits-analyze-depth-effect = "worker_logits_verify.analyze_depth_effect:main"
|
| 27 |
+
worker-logits-collect-vllm-evidence = "worker_logits_verify.collect_vllm_worker_evidence:main"
|
| 28 |
+
worker-logits-verify-vllm-evidence = "worker_logits_verify.verify_vllm_worker_evidence:main"
|
| 29 |
+
worker-logits-run-vllm-worker-verify = "worker_logits_verify.run_vllm_worker_verify:main"
|
| 30 |
+
worker-logits-summarize-worker-verify = "worker_logits_verify.summarize_worker_verify:main"
|
| 31 |
+
worker-logits-dense-bf16-verify = "worker_logits_verify.dense_bf16_verifier:main"
|
| 32 |
+
worker-logits-estimate-sample-size = "worker_logits_verify.estimate_sample_size:main"
|
| 33 |
+
|
| 34 |
+
[tool.setuptools.packages.find]
|
| 35 |
+
where = ["src"]
|
tools/worker_logits_verify/scripts/run_h100_6000_profile.sh
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
# Edit these paths for your machines. Run the collection commands on the matching GPU host,
|
| 5 |
+
# then copy trace directories to one analysis host before compare/profile steps.
|
| 6 |
+
|
| 7 |
+
MODEL_32B_BF16="${MODEL_32B_BF16:-/models/Qwen3-32B}"
|
| 8 |
+
MODEL_32B_FP8="${MODEL_32B_FP8:-/models/Qwen3-32B-FP8}"
|
| 9 |
+
MODEL_32B_AWQ="${MODEL_32B_AWQ:-/models/Qwen3-32B-AWQ}"
|
| 10 |
+
MODEL_14B="${MODEL_14B:-/models/Qwen3-14B}"
|
| 11 |
+
MODEL_8B="${MODEL_8B:-/models/Qwen3-8B}"
|
| 12 |
+
|
| 13 |
+
DATA_ROOT="${DATA_ROOT:-data/qwen3_32b_identity_v1}"
|
| 14 |
+
RESULT_ROOT="${RESULT_ROOT:-results/qwen3_32b_identity_v1}"
|
| 15 |
+
PYTHONPATH="${PYTHONPATH:-src}"
|
| 16 |
+
|
| 17 |
+
mkdir -p "${DATA_ROOT}" "${RESULT_ROOT}"
|
| 18 |
+
|
| 19 |
+
worker-logits-generate-prompts \
|
| 20 |
+
--model "${MODEL_32B_BF16}" \
|
| 21 |
+
--buckets "${BUCKETS:-32,128,512,2048,8192,16384}" \
|
| 22 |
+
--per-bucket "${PER_BUCKET:-50}" \
|
| 23 |
+
--output "${DATA_ROOT}/prompts.jsonl" \
|
| 24 |
+
--trust-remote-code
|
| 25 |
+
|
| 26 |
+
worker-logits-generate-anchor \
|
| 27 |
+
--model "${MODEL_32B_BF16}" \
|
| 28 |
+
--variant-id qwen3-32b-bf16-h100 \
|
| 29 |
+
--gpu H100 \
|
| 30 |
+
--quantization bf16 \
|
| 31 |
+
--dtype bfloat16 \
|
| 32 |
+
--input "${DATA_ROOT}/prompts.jsonl" \
|
| 33 |
+
--output "${DATA_ROOT}/anchor_samples.jsonl" \
|
| 34 |
+
--max-new-tokens "${MAX_NEW_TOKENS:-128}" \
|
| 35 |
+
--trust-remote-code
|
| 36 |
+
|
| 37 |
+
echo
|
| 38 |
+
echo "Now collect traces on each target host. Examples:"
|
| 39 |
+
echo
|
| 40 |
+
cat <<EOF
|
| 41 |
+
worker-logits-collect-trace \\
|
| 42 |
+
--samples ${DATA_ROOT}/anchor_samples.jsonl \\
|
| 43 |
+
--model ${MODEL_32B_BF16} \\
|
| 44 |
+
--variant-id qwen3-32b-bf16-h100 \\
|
| 45 |
+
--gpu H100 \\
|
| 46 |
+
--quantization bf16 \\
|
| 47 |
+
--dtype bfloat16 \\
|
| 48 |
+
--output-dir ${RESULT_ROOT}/traces/qwen3-32b-bf16-h100 \\
|
| 49 |
+
--top-k 64 \\
|
| 50 |
+
--trust-remote-code
|
| 51 |
+
|
| 52 |
+
worker-logits-collect-trace \\
|
| 53 |
+
--samples ${DATA_ROOT}/anchor_samples.jsonl \\
|
| 54 |
+
--model ${MODEL_32B_BF16} \\
|
| 55 |
+
--variant-id qwen3-32b-bf16-6000 \\
|
| 56 |
+
--gpu RTXPro6000 \\
|
| 57 |
+
--quantization bf16 \\
|
| 58 |
+
--dtype bfloat16 \\
|
| 59 |
+
--output-dir ${RESULT_ROOT}/traces/qwen3-32b-bf16-6000 \\
|
| 60 |
+
--top-k 64 \\
|
| 61 |
+
--trust-remote-code
|
| 62 |
+
|
| 63 |
+
# Negative controls, run where they fit:
|
| 64 |
+
worker-logits-collect-trace --samples ${DATA_ROOT}/anchor_samples.jsonl --model ${MODEL_32B_FP8} --variant-id qwen3-32b-fp8-h100 --gpu H100 --quantization fp8 --dtype auto --output-dir ${RESULT_ROOT}/traces/qwen3-32b-fp8-h100 --top-k 64 --trust-remote-code --allow-retokenize
|
| 65 |
+
worker-logits-collect-trace --samples ${DATA_ROOT}/anchor_samples.jsonl --model ${MODEL_32B_AWQ} --variant-id qwen3-32b-awq-h100 --gpu H100 --quantization awq --dtype auto --output-dir ${RESULT_ROOT}/traces/qwen3-32b-awq-h100 --top-k 64 --trust-remote-code --allow-retokenize
|
| 66 |
+
worker-logits-collect-trace --samples ${DATA_ROOT}/anchor_samples.jsonl --model ${MODEL_14B} --variant-id qwen3-14b-bf16-h100 --gpu H100 --quantization bf16 --dtype bfloat16 --output-dir ${RESULT_ROOT}/traces/qwen3-14b-bf16-h100 --top-k 64 --trust-remote-code --allow-retokenize
|
| 67 |
+
worker-logits-collect-trace --samples ${DATA_ROOT}/anchor_samples.jsonl --model ${MODEL_8B} --variant-id qwen3-8b-bf16-h100 --gpu H100 --quantization bf16 --dtype bfloat16 --output-dir ${RESULT_ROOT}/traces/qwen3-8b-bf16-h100 --top-k 64 --trust-remote-code --allow-retokenize
|
| 68 |
+
EOF
|
| 69 |
+
|
| 70 |
+
echo
|
| 71 |
+
echo "After traces are available on this host, run:"
|
| 72 |
+
echo
|
| 73 |
+
cat <<EOF
|
| 74 |
+
worker-logits-compare-traces \\
|
| 75 |
+
--left ${RESULT_ROOT}/traces/qwen3-32b-bf16-h100 \\
|
| 76 |
+
--right ${RESULT_ROOT}/traces/qwen3-32b-bf16-6000 \\
|
| 77 |
+
--left-label H100-BF16 \\
|
| 78 |
+
--right-label 6000-BF16 \\
|
| 79 |
+
--output-dir ${RESULT_ROOT}/comparisons/h100_vs_6000_bf16
|
| 80 |
+
|
| 81 |
+
worker-logits-analyze-depth-effect \\
|
| 82 |
+
--comparison ${RESULT_ROOT}/comparisons/h100_vs_6000_bf16 \\
|
| 83 |
+
--output-dir ${RESULT_ROOT}/depth_effect/h100_vs_6000_bf16
|
| 84 |
+
|
| 85 |
+
worker-logits-calibrate-profile \\
|
| 86 |
+
--comparison ${RESULT_ROOT}/comparisons/h100_vs_6000_bf16 \\
|
| 87 |
+
--profile-id qwen3-32b-bf16-h100-6000-envelope \\
|
| 88 |
+
--variant-pair "Qwen3-32B BF16 H100 vs RTXPro6000" \\
|
| 89 |
+
--output-dir ${RESULT_ROOT}/profiles/h100_6000_bf16
|
| 90 |
+
|
| 91 |
+
worker-logits-compare-traces --left ${RESULT_ROOT}/traces/qwen3-32b-bf16-h100 --right ${RESULT_ROOT}/traces/qwen3-32b-fp8-h100 --left-label H100-BF16 --right-label H100-FP8 --output-dir ${RESULT_ROOT}/comparisons/bf16_vs_fp8
|
| 92 |
+
worker-logits-verify-comparison --comparison ${RESULT_ROOT}/comparisons/bf16_vs_fp8 --profile ${RESULT_ROOT}/profiles/h100_6000_bf16/profile.json --output-dir ${RESULT_ROOT}/verifications/bf16_vs_fp8 --no-fail-on-reject
|
| 93 |
+
EOF
|
tools/worker_logits_verify/scripts/verifier_verifiy.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any, Dict, List, Optional, Sequence
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 14 |
+
SRC_ROOT = PROJECT_ROOT / "src"
|
| 15 |
+
SCRIPT_ROOT = Path(__file__).resolve().parent
|
| 16 |
+
for path in (SRC_ROOT, SCRIPT_ROOT):
|
| 17 |
+
if path.exists():
|
| 18 |
+
sys.path.insert(0, str(path))
|
| 19 |
+
|
| 20 |
+
from worker_inference import ( # noqa: E402
|
| 21 |
+
VLLMOpenAIClient,
|
| 22 |
+
choices_by_index,
|
| 23 |
+
compact_dict,
|
| 24 |
+
load_extra_body,
|
| 25 |
+
log,
|
| 26 |
+
normalize_logprob_mapping,
|
| 27 |
+
)
|
| 28 |
+
from worker_logits_verify.schema import ( # noqa: E402
|
| 29 |
+
VariantInfo,
|
| 30 |
+
dataclass_to_dict,
|
| 31 |
+
read_jsonl,
|
| 32 |
+
runtime_metadata,
|
| 33 |
+
write_json,
|
| 34 |
+
)
|
| 35 |
+
from worker_logits_verify.verify_vllm_worker_evidence import ( # noqa: E402
|
| 36 |
+
compare_depth,
|
| 37 |
+
write_csv,
|
| 38 |
+
write_summary,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
JSONDict = Dict[str, Any]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def make_variant(args: argparse.Namespace) -> VariantInfo:
|
| 46 |
+
return VariantInfo(
|
| 47 |
+
variant_id=args.variant_id,
|
| 48 |
+
model=args.model,
|
| 49 |
+
tokenizer_hash=args.tokenizer_hash,
|
| 50 |
+
tokenizer_name=args.tokenizer_name or args.model,
|
| 51 |
+
quantization=args.quantization,
|
| 52 |
+
gpu=args.gpu,
|
| 53 |
+
backend="vllm-openai-api",
|
| 54 |
+
backend_version=args.backend_version,
|
| 55 |
+
dtype=args.dtype,
|
| 56 |
+
extra={
|
| 57 |
+
"base_url": args.base_url,
|
| 58 |
+
"prompt_logprobs": args.prompt_logprobs,
|
| 59 |
+
"return_token_ids": True,
|
| 60 |
+
"return_tokens_as_token_ids": True,
|
| 61 |
+
},
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def make_verifier_body(args: argparse.Namespace,
|
| 66 |
+
prompts: Sequence[Sequence[int]]) -> JSONDict:
|
| 67 |
+
body: JSONDict = {
|
| 68 |
+
"model": args.model,
|
| 69 |
+
"prompt": [[int(token_id) for token_id in prompt] for prompt in prompts],
|
| 70 |
+
"max_tokens": args.max_tokens,
|
| 71 |
+
"temperature": args.temperature,
|
| 72 |
+
"top_p": args.top_p,
|
| 73 |
+
"prompt_logprobs": args.prompt_logprobs,
|
| 74 |
+
"echo": False,
|
| 75 |
+
"seed": args.seed,
|
| 76 |
+
"stream": False,
|
| 77 |
+
"return_token_ids": True,
|
| 78 |
+
"return_tokens_as_token_ids": True,
|
| 79 |
+
"skip_special_tokens": False,
|
| 80 |
+
}
|
| 81 |
+
if args.top_k > 0:
|
| 82 |
+
body["top_k"] = args.top_k
|
| 83 |
+
body.update(load_extra_body(args.extra_body_json))
|
| 84 |
+
return compact_dict(body)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def extract_prompt_logprobs(choice: JSONDict,
|
| 88 |
+
*,
|
| 89 |
+
strict_token_ids: bool,
|
| 90 |
+
sample_id: str) -> List[Dict[str, Dict[str, Any]]]:
|
| 91 |
+
raw = choice.get("prompt_logprobs")
|
| 92 |
+
if raw is None:
|
| 93 |
+
logprobs = choice.get("logprobs") or {}
|
| 94 |
+
if isinstance(logprobs, dict):
|
| 95 |
+
raw = logprobs.get("prompt_logprobs")
|
| 96 |
+
if raw is None:
|
| 97 |
+
return []
|
| 98 |
+
if not isinstance(raw, list):
|
| 99 |
+
raise TypeError(
|
| 100 |
+
f"sample={sample_id}: prompt_logprobs should be a list, got {type(raw).__name__}"
|
| 101 |
+
)
|
| 102 |
+
return [
|
| 103 |
+
normalize_logprob_mapping(
|
| 104 |
+
item,
|
| 105 |
+
strict_token_ids=strict_token_ids,
|
| 106 |
+
context=f"sample={sample_id} prompt_pos={position}",
|
| 107 |
+
)
|
| 108 |
+
for position, item in enumerate(raw)
|
| 109 |
+
]
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def write_threshold_summary(path: Path,
|
| 113 |
+
metric_rows: Sequence[JSONDict],
|
| 114 |
+
*,
|
| 115 |
+
max_abs_logprob_diff: float,
|
| 116 |
+
max_missing_selected_rate: float) -> str:
|
| 117 |
+
total = len(metric_rows)
|
| 118 |
+
finite_abs = []
|
| 119 |
+
missing_selected = 0
|
| 120 |
+
over_abs = 0
|
| 121 |
+
for row in metric_rows:
|
| 122 |
+
verifier_logprob = row.get("verifier_selected_logprob")
|
| 123 |
+
if verifier_logprob in {"", None}:
|
| 124 |
+
missing_selected += 1
|
| 125 |
+
try:
|
| 126 |
+
abs_diff = float(row.get("abs_logprob_diff"))
|
| 127 |
+
except (TypeError, ValueError):
|
| 128 |
+
abs_diff = float("nan")
|
| 129 |
+
if math.isfinite(abs_diff):
|
| 130 |
+
finite_abs.append(abs_diff)
|
| 131 |
+
if abs_diff > max_abs_logprob_diff:
|
| 132 |
+
over_abs += 1
|
| 133 |
+
missing_rate = missing_selected / total if total else 0.0
|
| 134 |
+
verdict = (
|
| 135 |
+
"PASS"
|
| 136 |
+
if over_abs == 0 and missing_rate <= max_missing_selected_rate
|
| 137 |
+
else "FAIL"
|
| 138 |
+
)
|
| 139 |
+
lines = [
|
| 140 |
+
"# threshold verdict",
|
| 141 |
+
"",
|
| 142 |
+
f"- verdict: {verdict}",
|
| 143 |
+
f"- depth rows: {total}",
|
| 144 |
+
f"- max_abs_logprob_diff_threshold: {max_abs_logprob_diff:.8g}",
|
| 145 |
+
f"- over_abs_threshold_count: {over_abs}",
|
| 146 |
+
f"- missing_selected_rate: {missing_rate:.8g}",
|
| 147 |
+
f"- max_missing_selected_rate: {max_missing_selected_rate:.8g}",
|
| 148 |
+
f"- observed_max_abs_logprob_diff: {max(finite_abs, default=float('nan')):.8g}",
|
| 149 |
+
"",
|
| 150 |
+
]
|
| 151 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 152 |
+
return verdict
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def build_arg_parser() -> argparse.ArgumentParser:
|
| 156 |
+
parser = argparse.ArgumentParser(
|
| 157 |
+
description="Verify worker_inference evidence by recomputing prompt logprobs through the vLLM OpenAI-compatible Completions API."
|
| 158 |
+
)
|
| 159 |
+
parser.add_argument("--evidence", required=True)
|
| 160 |
+
parser.add_argument("--output-dir", default="results/vllm_openai_worker_verify")
|
| 161 |
+
parser.add_argument("--base-url", default=os.environ.get("VLLM_OPENAI_BASE_URL", "http://localhost:8000/v1"))
|
| 162 |
+
parser.add_argument("--api-key", default=os.environ.get("OPENAI_API_KEY", "EMPTY"))
|
| 163 |
+
parser.add_argument("--model", required=True)
|
| 164 |
+
parser.add_argument("--variant-id", required=True)
|
| 165 |
+
parser.add_argument("--gpu", default="")
|
| 166 |
+
parser.add_argument("--quantization", default="bf16")
|
| 167 |
+
parser.add_argument("--dtype", default="auto")
|
| 168 |
+
parser.add_argument("--backend-version", default="")
|
| 169 |
+
parser.add_argument("--tokenizer-name", default="")
|
| 170 |
+
parser.add_argument("--tokenizer-hash", default="")
|
| 171 |
+
parser.add_argument("--prompt-logprobs", type=int, default=32)
|
| 172 |
+
parser.add_argument("--max-tokens", type=int, default=1,
|
| 173 |
+
help="Completion tokens to request while collecting prompt_logprobs; generated token is ignored.")
|
| 174 |
+
parser.add_argument("--temperature", type=float, default=0.0)
|
| 175 |
+
parser.add_argument("--top-p", type=float, default=1.0)
|
| 176 |
+
parser.add_argument("--top-k", type=int, default=0)
|
| 177 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 178 |
+
parser.add_argument("--missing-logprob", type=float, default=-100.0)
|
| 179 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 180 |
+
parser.add_argument("--max-total-tokens", type=int, default=0,
|
| 181 |
+
help="Skip rows whose input_ids + output_ids exceeds this length.")
|
| 182 |
+
parser.add_argument("--timeout", type=float, default=600.0)
|
| 183 |
+
parser.add_argument("--retries", type=int, default=2)
|
| 184 |
+
parser.add_argument("--retry-sleep", type=float, default=2.0)
|
| 185 |
+
parser.add_argument("--extra-body-json", default="",
|
| 186 |
+
help="Extra JSON object or JSON file merged into each /v1/completions request.")
|
| 187 |
+
parser.add_argument("--allow-text-top-logprobs", action="store_true",
|
| 188 |
+
help="Keep running if prompt_logprobs keys are text instead of token ids; unmapped entries are dropped.")
|
| 189 |
+
parser.add_argument("--max-abs-logprob-diff", type=float, default=None,
|
| 190 |
+
help="Optional hard threshold for PASS/FAIL summary.")
|
| 191 |
+
parser.add_argument("--max-missing-selected-rate", type=float, default=0.0,
|
| 192 |
+
help="Allowed selected-token missing rate when --max-abs-logprob-diff is set.")
|
| 193 |
+
return parser
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 197 |
+
parser = build_arg_parser()
|
| 198 |
+
args = parser.parse_args(argv)
|
| 199 |
+
|
| 200 |
+
client = VLLMOpenAIClient(
|
| 201 |
+
base_url=args.base_url,
|
| 202 |
+
api_key=args.api_key,
|
| 203 |
+
timeout=args.timeout,
|
| 204 |
+
retries=args.retries,
|
| 205 |
+
retry_sleep=args.retry_sleep,
|
| 206 |
+
)
|
| 207 |
+
variant = make_variant(args)
|
| 208 |
+
strict_token_ids = not args.allow_text_top_logprobs
|
| 209 |
+
|
| 210 |
+
evidence_rows: List[JSONDict] = []
|
| 211 |
+
skipped_too_long = 0
|
| 212 |
+
for index, row in enumerate(read_jsonl(Path(args.evidence)), start=1):
|
| 213 |
+
if args.limit and index > args.limit:
|
| 214 |
+
break
|
| 215 |
+
total_tokens = len(row.get("input_ids", [])) + len(row.get("output_ids", []))
|
| 216 |
+
if args.max_total_tokens and total_tokens > args.max_total_tokens:
|
| 217 |
+
skipped_too_long += 1
|
| 218 |
+
continue
|
| 219 |
+
evidence_rows.append(row)
|
| 220 |
+
|
| 221 |
+
log(
|
| 222 |
+
f"Loaded evidence rows: {len(evidence_rows)} "
|
| 223 |
+
f"(skipped_too_long={skipped_too_long})"
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
output_dir = Path(args.output_dir)
|
| 227 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 228 |
+
metric_rows: List[JSONDict] = []
|
| 229 |
+
total_start = time.time()
|
| 230 |
+
|
| 231 |
+
for request_index, evidence in enumerate(evidence_rows, start=1):
|
| 232 |
+
full_prompt = [
|
| 233 |
+
int(token_id)
|
| 234 |
+
for token_id in evidence["input_ids"] + evidence["output_ids"]
|
| 235 |
+
]
|
| 236 |
+
log(
|
| 237 |
+
f"Verifier OpenAI prompt_logprobs request {request_index}/{len(evidence_rows)}, "
|
| 238 |
+
f"tokens={len(full_prompt)}"
|
| 239 |
+
)
|
| 240 |
+
response = client.post_json("/completions", make_verifier_body(args, [full_prompt]))
|
| 241 |
+
choice = choices_by_index(response, 1)[0]
|
| 242 |
+
|
| 243 |
+
sample_id = str(evidence.get("sample_id", ""))
|
| 244 |
+
input_len = len(evidence.get("input_ids", []))
|
| 245 |
+
prompt_logprobs = extract_prompt_logprobs(
|
| 246 |
+
choice,
|
| 247 |
+
strict_token_ids=strict_token_ids,
|
| 248 |
+
sample_id=sample_id,
|
| 249 |
+
)
|
| 250 |
+
if not prompt_logprobs:
|
| 251 |
+
raise ValueError(
|
| 252 |
+
"Verifier response did not include prompt_logprobs. "
|
| 253 |
+
"Ensure the vLLM OpenAI server supports the prompt_logprobs request field."
|
| 254 |
+
)
|
| 255 |
+
for worker_depth in evidence.get("worker_trace", []):
|
| 256 |
+
depth = int(worker_depth["depth"])
|
| 257 |
+
prompt_pos = input_len + depth
|
| 258 |
+
verifier_logprobs = (
|
| 259 |
+
prompt_logprobs[prompt_pos]
|
| 260 |
+
if prompt_pos < len(prompt_logprobs) else {}
|
| 261 |
+
)
|
| 262 |
+
row = compare_depth(worker_depth, verifier_logprobs, args.missing_logprob)
|
| 263 |
+
row.update({
|
| 264 |
+
"sample_id": sample_id,
|
| 265 |
+
"input_token_count": input_len,
|
| 266 |
+
"output_token_count": len(evidence.get("output_ids", [])),
|
| 267 |
+
"worker_trace_mode": evidence.get("worker_trace_mode"),
|
| 268 |
+
"verifier_trace_mode": "vllm_openai_prompt_logprobs_full_prefill",
|
| 269 |
+
})
|
| 270 |
+
metric_rows.append(row)
|
| 271 |
+
|
| 272 |
+
fields = [
|
| 273 |
+
"sample_id",
|
| 274 |
+
"depth",
|
| 275 |
+
"input_token_count",
|
| 276 |
+
"output_token_count",
|
| 277 |
+
"target_token_id",
|
| 278 |
+
"target_decoded_token",
|
| 279 |
+
"worker_trace_mode",
|
| 280 |
+
"verifier_trace_mode",
|
| 281 |
+
"worker_selected_logprob",
|
| 282 |
+
"verifier_selected_logprob",
|
| 283 |
+
"logprob_diff_verifier_minus_worker",
|
| 284 |
+
"abs_logprob_diff",
|
| 285 |
+
"worker_selected_rank",
|
| 286 |
+
"verifier_selected_rank",
|
| 287 |
+
"rank_delta_verifier_minus_worker",
|
| 288 |
+
"common_top_count",
|
| 289 |
+
"union_top_count",
|
| 290 |
+
"topk_jaccard",
|
| 291 |
+
"missing_from_verifier_count",
|
| 292 |
+
"extra_in_verifier_count",
|
| 293 |
+
"common_js_divergence",
|
| 294 |
+
"union_js_divergence",
|
| 295 |
+
"common_prob_cosine",
|
| 296 |
+
"union_prob_cosine",
|
| 297 |
+
]
|
| 298 |
+
metrics_path = output_dir / "worker_vs_verifier_depth_metrics.csv"
|
| 299 |
+
write_csv(metrics_path, metric_rows, fields)
|
| 300 |
+
write_summary(output_dir / "summary.md", metric_rows)
|
| 301 |
+
|
| 302 |
+
verdict: Optional[str] = None
|
| 303 |
+
if args.max_abs_logprob_diff is not None:
|
| 304 |
+
verdict = write_threshold_summary(
|
| 305 |
+
output_dir / "threshold_verdict.md",
|
| 306 |
+
metric_rows,
|
| 307 |
+
max_abs_logprob_diff=args.max_abs_logprob_diff,
|
| 308 |
+
max_missing_selected_rate=args.max_missing_selected_rate,
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
write_json(output_dir / "metadata.json", {
|
| 312 |
+
"metadata": runtime_metadata(sys.argv),
|
| 313 |
+
"args": vars(args),
|
| 314 |
+
"verifier_variant": dataclass_to_dict(variant),
|
| 315 |
+
"evidence_count": len(evidence_rows),
|
| 316 |
+
"skipped_too_long": skipped_too_long,
|
| 317 |
+
"depth_row_count": len(metric_rows),
|
| 318 |
+
"elapsed_seconds": time.time() - total_start,
|
| 319 |
+
"verdict": verdict,
|
| 320 |
+
})
|
| 321 |
+
log(f"Wrote {metrics_path}")
|
| 322 |
+
log(f"Wrote {output_dir / 'summary.md'}")
|
| 323 |
+
if verdict is not None:
|
| 324 |
+
log(f"Threshold verdict: {verdict}")
|
| 325 |
+
return 0
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
if __name__ == "__main__":
|
| 329 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/scripts/vllm_openai_api.py
ADDED
|
@@ -0,0 +1,845 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import mimetypes
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
import uuid
|
| 11 |
+
import urllib.error
|
| 12 |
+
import urllib.parse
|
| 13 |
+
import urllib.request
|
| 14 |
+
from dataclasses import dataclass, field
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Union
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
JSONDict = Dict[str, Any]
|
| 20 |
+
JSONLike = Union[JSONDict, List[Any], str, int, float, bool, None]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class VLLMOpenAIError(RuntimeError):
|
| 24 |
+
def __init__(self, message: str, *, status: Optional[int] = None, body: str = "") -> None:
|
| 25 |
+
super().__init__(message)
|
| 26 |
+
self.status = status
|
| 27 |
+
self.body = body
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@dataclass
|
| 31 |
+
class VLLMOpenAIClient:
|
| 32 |
+
"""Small stdlib-only client for vLLM's OpenAI-compatible HTTP server.
|
| 33 |
+
|
| 34 |
+
`base_url` accepts either the server root (`http://127.0.0.1:8000`) or
|
| 35 |
+
the OpenAI-style v1 URL (`http://127.0.0.1:8000/v1`). Wrapper methods use
|
| 36 |
+
explicit paths, so custom vLLM endpoints such as `/tokenize` still work.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
base_url: str = field(default_factory=lambda: os.environ.get("VLLM_BASE_URL", "http://127.0.0.1:8000"))
|
| 40 |
+
api_key: str = field(default_factory=lambda: os.environ.get("OPENAI_API_KEY", "EMPTY"))
|
| 41 |
+
timeout: float = 600.0
|
| 42 |
+
retries: int = 2
|
| 43 |
+
retry_sleep: float = 1.0
|
| 44 |
+
extra_headers: Mapping[str, str] = field(default_factory=dict)
|
| 45 |
+
|
| 46 |
+
def __post_init__(self) -> None:
|
| 47 |
+
self.base_url = self.base_url.rstrip("/")
|
| 48 |
+
self.server_url = self.base_url[:-3] if self.base_url.endswith("/v1") else self.base_url
|
| 49 |
+
|
| 50 |
+
def _url(self, path: str, query: Optional[Mapping[str, Any]] = None) -> str:
|
| 51 |
+
path = "/" + path.lstrip("/")
|
| 52 |
+
url = self.server_url + path
|
| 53 |
+
if query:
|
| 54 |
+
compact = {key: value for key, value in query.items() if value is not None}
|
| 55 |
+
if compact:
|
| 56 |
+
url += "?" + urllib.parse.urlencode(compact, doseq=True)
|
| 57 |
+
return url
|
| 58 |
+
|
| 59 |
+
def _headers(self, extra: Optional[Mapping[str, str]] = None) -> Dict[str, str]:
|
| 60 |
+
headers = {
|
| 61 |
+
"Authorization": f"Bearer {self.api_key}",
|
| 62 |
+
"Accept": "application/json",
|
| 63 |
+
}
|
| 64 |
+
headers.update(dict(self.extra_headers))
|
| 65 |
+
if extra:
|
| 66 |
+
headers.update(dict(extra))
|
| 67 |
+
return headers
|
| 68 |
+
|
| 69 |
+
def request(
|
| 70 |
+
self,
|
| 71 |
+
method: str,
|
| 72 |
+
path: str,
|
| 73 |
+
*,
|
| 74 |
+
json_body: Optional[JSONLike] = None,
|
| 75 |
+
data: Optional[bytes] = None,
|
| 76 |
+
headers: Optional[Mapping[str, str]] = None,
|
| 77 |
+
query: Optional[Mapping[str, Any]] = None,
|
| 78 |
+
stream: bool = False,
|
| 79 |
+
) -> Any:
|
| 80 |
+
request_headers = self._headers(headers)
|
| 81 |
+
if json_body is not None:
|
| 82 |
+
data = json.dumps(json_body, ensure_ascii=False).encode("utf-8")
|
| 83 |
+
request_headers.setdefault("Content-Type", "application/json")
|
| 84 |
+
|
| 85 |
+
request = urllib.request.Request(
|
| 86 |
+
self._url(path, query=query),
|
| 87 |
+
data=data,
|
| 88 |
+
headers=request_headers,
|
| 89 |
+
method=method.upper(),
|
| 90 |
+
)
|
| 91 |
+
return self._open_with_retries(request, path=path, stream=stream)
|
| 92 |
+
|
| 93 |
+
def get_json(self, path: str, *, query: Optional[Mapping[str, Any]] = None) -> Any:
|
| 94 |
+
return self.request("GET", path, query=query)
|
| 95 |
+
|
| 96 |
+
def post_json(self, path: str, payload: JSONLike) -> Any:
|
| 97 |
+
return self.request("POST", path, json_body=payload)
|
| 98 |
+
|
| 99 |
+
def delete_json(self, path: str, payload: Optional[JSONLike] = None) -> Any:
|
| 100 |
+
return self.request("DELETE", path, json_body=payload)
|
| 101 |
+
|
| 102 |
+
def stream_json(self, path: str, payload: JSONDict) -> Iterator[JSONDict]:
|
| 103 |
+
response = self.request("POST", path, json_body={**payload, "stream": True}, stream=True)
|
| 104 |
+
try:
|
| 105 |
+
for raw_line in response:
|
| 106 |
+
line = raw_line.decode("utf-8", errors="replace").strip()
|
| 107 |
+
if not line:
|
| 108 |
+
continue
|
| 109 |
+
if line.startswith("data:"):
|
| 110 |
+
line = line[len("data:"):].strip()
|
| 111 |
+
if line == "[DONE]":
|
| 112 |
+
break
|
| 113 |
+
yield json.loads(line)
|
| 114 |
+
finally:
|
| 115 |
+
response.close()
|
| 116 |
+
|
| 117 |
+
def _open_with_retries(self, request: urllib.request.Request, *, path: str, stream: bool) -> Any:
|
| 118 |
+
last_error: Optional[BaseException] = None
|
| 119 |
+
for attempt in range(self.retries + 1):
|
| 120 |
+
try:
|
| 121 |
+
response = urllib.request.urlopen(request, timeout=self.timeout)
|
| 122 |
+
if stream:
|
| 123 |
+
return response
|
| 124 |
+
with response:
|
| 125 |
+
body = response.read().decode("utf-8")
|
| 126 |
+
if not body:
|
| 127 |
+
return None
|
| 128 |
+
return json.loads(body)
|
| 129 |
+
except urllib.error.HTTPError as exc:
|
| 130 |
+
body = exc.read().decode("utf-8", errors="replace")
|
| 131 |
+
last_error = VLLMOpenAIError(
|
| 132 |
+
f"HTTP {exc.code} from {path}: {body}",
|
| 133 |
+
status=exc.code,
|
| 134 |
+
body=body,
|
| 135 |
+
)
|
| 136 |
+
except urllib.error.URLError as exc:
|
| 137 |
+
last_error = exc
|
| 138 |
+
except json.JSONDecodeError as exc:
|
| 139 |
+
last_error = VLLMOpenAIError(f"Invalid JSON from {path}: {exc}")
|
| 140 |
+
if attempt < self.retries:
|
| 141 |
+
time.sleep(self.retry_sleep)
|
| 142 |
+
assert last_error is not None
|
| 143 |
+
raise last_error
|
| 144 |
+
|
| 145 |
+
# Basic / instrumentation endpoints.
|
| 146 |
+
def health(self) -> Any:
|
| 147 |
+
return self.get_json("/health")
|
| 148 |
+
|
| 149 |
+
def version(self) -> Any:
|
| 150 |
+
return self.get_json("/version")
|
| 151 |
+
|
| 152 |
+
def load(self) -> Any:
|
| 153 |
+
return self.get_json("/load")
|
| 154 |
+
|
| 155 |
+
def metrics(self) -> str:
|
| 156 |
+
response = self.request("GET", "/metrics", headers={"Accept": "text/plain"}, stream=True)
|
| 157 |
+
try:
|
| 158 |
+
return response.read().decode("utf-8")
|
| 159 |
+
finally:
|
| 160 |
+
response.close()
|
| 161 |
+
|
| 162 |
+
def models(self) -> JSONDict:
|
| 163 |
+
return self.get_json("/v1/models")
|
| 164 |
+
|
| 165 |
+
# OpenAI-compatible generation APIs.
|
| 166 |
+
def completions(self, *, model: str, prompt: Any, **params: Any) -> JSONDict:
|
| 167 |
+
return self.post_json("/v1/completions", compact_dict({
|
| 168 |
+
"model": model,
|
| 169 |
+
"prompt": prompt,
|
| 170 |
+
**params,
|
| 171 |
+
}))
|
| 172 |
+
|
| 173 |
+
def stream_completions(self, *, model: str, prompt: Any, **params: Any) -> Iterator[JSONDict]:
|
| 174 |
+
return self.stream_json("/v1/completions", compact_dict({
|
| 175 |
+
"model": model,
|
| 176 |
+
"prompt": prompt,
|
| 177 |
+
**params,
|
| 178 |
+
}))
|
| 179 |
+
|
| 180 |
+
def chat_completions(self, *, model: str, messages: Sequence[Mapping[str, Any]], **params: Any) -> JSONDict:
|
| 181 |
+
return self.post_json("/v1/chat/completions", compact_dict({
|
| 182 |
+
"model": model,
|
| 183 |
+
"messages": list(messages),
|
| 184 |
+
**params,
|
| 185 |
+
}))
|
| 186 |
+
|
| 187 |
+
def stream_chat_completions(self, *, model: str, messages: Sequence[Mapping[str, Any]], **params: Any) -> Iterator[JSONDict]:
|
| 188 |
+
return self.stream_json("/v1/chat/completions", compact_dict({
|
| 189 |
+
"model": model,
|
| 190 |
+
"messages": list(messages),
|
| 191 |
+
**params,
|
| 192 |
+
}))
|
| 193 |
+
|
| 194 |
+
def chat_completions_batch(self, payload: JSONDict) -> JSONDict:
|
| 195 |
+
return self.post_json("/v1/chat/completions/batch", payload)
|
| 196 |
+
|
| 197 |
+
def create_response(self, *, model: str, input: Any, **params: Any) -> JSONDict:
|
| 198 |
+
return self.post_json("/v1/responses", compact_dict({
|
| 199 |
+
"model": model,
|
| 200 |
+
"input": input,
|
| 201 |
+
**params,
|
| 202 |
+
}))
|
| 203 |
+
|
| 204 |
+
def get_response(self, response_id: str) -> JSONDict:
|
| 205 |
+
return self.get_json(f"/v1/responses/{response_id}")
|
| 206 |
+
|
| 207 |
+
def cancel_response(self, response_id: str) -> JSONDict:
|
| 208 |
+
return self.post_json(f"/v1/responses/{response_id}/cancel", {})
|
| 209 |
+
|
| 210 |
+
# Vector / pooling / ranking APIs.
|
| 211 |
+
def embeddings(self, *, model: str, input: Any, **params: Any) -> JSONDict:
|
| 212 |
+
return self.post_json("/v1/embeddings", compact_dict({
|
| 213 |
+
"model": model,
|
| 214 |
+
"input": input,
|
| 215 |
+
**params,
|
| 216 |
+
}))
|
| 217 |
+
|
| 218 |
+
def cohere_embed(self, *, model: str, texts: Sequence[str], **params: Any) -> JSONDict:
|
| 219 |
+
return self.post_json("/v2/embed", compact_dict({
|
| 220 |
+
"model": model,
|
| 221 |
+
"texts": list(texts),
|
| 222 |
+
**params,
|
| 223 |
+
}))
|
| 224 |
+
|
| 225 |
+
def pooling(self, *, model: str, input: Any, **params: Any) -> JSONDict:
|
| 226 |
+
return self.post_json("/pooling", compact_dict({
|
| 227 |
+
"model": model,
|
| 228 |
+
"input": input,
|
| 229 |
+
**params,
|
| 230 |
+
}))
|
| 231 |
+
|
| 232 |
+
def classify(self, *, model: str, input: Any, **params: Any) -> JSONDict:
|
| 233 |
+
return self.post_json("/classify", compact_dict({
|
| 234 |
+
"model": model,
|
| 235 |
+
"input": input,
|
| 236 |
+
**params,
|
| 237 |
+
}))
|
| 238 |
+
|
| 239 |
+
def score(self, *, model: str, text_1: Any, text_2: Any, path: str = "/score", **params: Any) -> JSONDict:
|
| 240 |
+
return self.post_json(path, compact_dict({
|
| 241 |
+
"model": model,
|
| 242 |
+
"text_1": text_1,
|
| 243 |
+
"text_2": text_2,
|
| 244 |
+
**params,
|
| 245 |
+
}))
|
| 246 |
+
|
| 247 |
+
def rerank(self, *, model: str, query: str, documents: Sequence[Any], path: str = "/rerank", **params: Any) -> JSONDict:
|
| 248 |
+
return self.post_json(path, compact_dict({
|
| 249 |
+
"model": model,
|
| 250 |
+
"query": query,
|
| 251 |
+
"documents": list(documents),
|
| 252 |
+
**params,
|
| 253 |
+
}))
|
| 254 |
+
|
| 255 |
+
def generative_scoring(self, *, model: str, prompt: Any, label_token_ids: Sequence[int], **params: Any) -> JSONDict:
|
| 256 |
+
return self.post_json("/generative_scoring", compact_dict({
|
| 257 |
+
"model": model,
|
| 258 |
+
"prompt": prompt,
|
| 259 |
+
"label_token_ids": [int(token_id) for token_id in label_token_ids],
|
| 260 |
+
**params,
|
| 261 |
+
}))
|
| 262 |
+
|
| 263 |
+
# Tokenizer APIs.
|
| 264 |
+
def tokenize(self, *, model: str, prompt: str, add_special_tokens: bool = False, **params: Any) -> JSONDict:
|
| 265 |
+
return self.post_json("/tokenize", compact_dict({
|
| 266 |
+
"model": model,
|
| 267 |
+
"prompt": prompt,
|
| 268 |
+
"add_special_tokens": add_special_tokens,
|
| 269 |
+
**params,
|
| 270 |
+
}))
|
| 271 |
+
|
| 272 |
+
def token_ids(self, *, model: str, prompt: str, add_special_tokens: bool = False, **params: Any) -> List[int]:
|
| 273 |
+
response = self.tokenize(
|
| 274 |
+
model=model,
|
| 275 |
+
prompt=prompt,
|
| 276 |
+
add_special_tokens=add_special_tokens,
|
| 277 |
+
**params,
|
| 278 |
+
)
|
| 279 |
+
token_ids = response.get("token_ids") or response.get("tokens") or response.get("input_ids")
|
| 280 |
+
if not isinstance(token_ids, list):
|
| 281 |
+
raise ValueError(f"/tokenize response did not include token ids: {response}")
|
| 282 |
+
return [int(token_id) for token_id in token_ids]
|
| 283 |
+
|
| 284 |
+
def detokenize(self, *, model: str, tokens: Sequence[int], **params: Any) -> JSONDict:
|
| 285 |
+
return self.post_json("/detokenize", compact_dict({
|
| 286 |
+
"model": model,
|
| 287 |
+
"tokens": [int(token_id) for token_id in tokens],
|
| 288 |
+
**params,
|
| 289 |
+
}))
|
| 290 |
+
|
| 291 |
+
def tokenizer_info(self, *, model: Optional[str] = None) -> JSONDict:
|
| 292 |
+
payload = {"model": model} if model else {}
|
| 293 |
+
return self.post_json("/tokenizer_info", payload)
|
| 294 |
+
|
| 295 |
+
# Anthropic-compatible APIs exposed by recent vLLM versions.
|
| 296 |
+
def messages(self, *, model: str, messages: Sequence[Mapping[str, Any]], **params: Any) -> JSONDict:
|
| 297 |
+
return self.post_json("/v1/messages", compact_dict({
|
| 298 |
+
"model": model,
|
| 299 |
+
"messages": list(messages),
|
| 300 |
+
**params,
|
| 301 |
+
}))
|
| 302 |
+
|
| 303 |
+
def count_message_tokens(self, *, model: str, messages: Sequence[Mapping[str, Any]], **params: Any) -> JSONDict:
|
| 304 |
+
return self.post_json("/v1/messages/count_tokens", compact_dict({
|
| 305 |
+
"model": model,
|
| 306 |
+
"messages": list(messages),
|
| 307 |
+
**params,
|
| 308 |
+
}))
|
| 309 |
+
|
| 310 |
+
# Audio APIs.
|
| 311 |
+
def transcribe(self, *, model: str, file_path: Union[str, Path], **params: Any) -> JSONDict:
|
| 312 |
+
return self._multipart_audio("/v1/audio/transcriptions", model=model, file_path=file_path, params=params)
|
| 313 |
+
|
| 314 |
+
def translate(self, *, model: str, file_path: Union[str, Path], **params: Any) -> JSONDict:
|
| 315 |
+
return self._multipart_audio("/v1/audio/translations", model=model, file_path=file_path, params=params)
|
| 316 |
+
|
| 317 |
+
# LoRA dynamic loading. Use only when you intentionally enabled it server-side.
|
| 318 |
+
def load_lora_adapter(self, *, lora_name: str, lora_path: str) -> JSONDict:
|
| 319 |
+
return self.post_json("/v1/load_lora_adapter", {
|
| 320 |
+
"lora_name": lora_name,
|
| 321 |
+
"lora_path": lora_path,
|
| 322 |
+
})
|
| 323 |
+
|
| 324 |
+
def unload_lora_adapter(self, *, lora_name: str) -> JSONDict:
|
| 325 |
+
return self.post_json("/v1/unload_lora_adapter", {"lora_name": lora_name})
|
| 326 |
+
|
| 327 |
+
def _multipart_audio(
|
| 328 |
+
self,
|
| 329 |
+
path: str,
|
| 330 |
+
*,
|
| 331 |
+
model: str,
|
| 332 |
+
file_path: Union[str, Path],
|
| 333 |
+
params: Mapping[str, Any],
|
| 334 |
+
) -> JSONDict:
|
| 335 |
+
file_path = Path(file_path)
|
| 336 |
+
fields = compact_dict({"model": model, **dict(params)})
|
| 337 |
+
body, content_type = encode_multipart(fields, [("file", file_path)])
|
| 338 |
+
return self.request("POST", path, data=body, headers={"Content-Type": content_type})
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def compact_dict(payload: Mapping[str, Any]) -> JSONDict:
|
| 342 |
+
return {key: value for key, value in payload.items() if value is not None}
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def load_json_arg(raw: str) -> Any:
|
| 346 |
+
if raw == "":
|
| 347 |
+
return None
|
| 348 |
+
if raw.startswith("@"):
|
| 349 |
+
return json.loads(Path(raw[1:]).read_text(encoding="utf-8"))
|
| 350 |
+
path = Path(raw)
|
| 351 |
+
if path.exists():
|
| 352 |
+
return json.loads(path.read_text(encoding="utf-8"))
|
| 353 |
+
return json.loads(raw)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def load_text_arg(raw: str) -> str:
|
| 357 |
+
if raw.startswith("@"):
|
| 358 |
+
return Path(raw[1:]).read_text(encoding="utf-8")
|
| 359 |
+
return raw
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def parse_kv_pairs(items: Sequence[str]) -> JSONDict:
|
| 363 |
+
out: JSONDict = {}
|
| 364 |
+
for item in items:
|
| 365 |
+
if "=" not in item:
|
| 366 |
+
raise ValueError(f"Expected KEY=JSON_VALUE, got {item!r}")
|
| 367 |
+
key, value = item.split("=", 1)
|
| 368 |
+
out[key] = load_json_arg(value)
|
| 369 |
+
return out
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def encode_multipart(fields: Mapping[str, Any], files: Sequence[Tuple[str, Path]]) -> Tuple[bytes, str]:
|
| 373 |
+
boundary = "----vllm-client-" + uuid.uuid4().hex
|
| 374 |
+
chunks: List[bytes] = []
|
| 375 |
+
for name, value in fields.items():
|
| 376 |
+
chunks.extend([
|
| 377 |
+
f"--{boundary}\r\n".encode("utf-8"),
|
| 378 |
+
f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode("utf-8"),
|
| 379 |
+
str(value).encode("utf-8"),
|
| 380 |
+
b"\r\n",
|
| 381 |
+
])
|
| 382 |
+
for field_name, path in files:
|
| 383 |
+
content_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
|
| 384 |
+
chunks.extend([
|
| 385 |
+
f"--{boundary}\r\n".encode("utf-8"),
|
| 386 |
+
(
|
| 387 |
+
f'Content-Disposition: form-data; name="{field_name}"; '
|
| 388 |
+
f'filename="{path.name}"\r\n'
|
| 389 |
+
).encode("utf-8"),
|
| 390 |
+
f"Content-Type: {content_type}\r\n\r\n".encode("utf-8"),
|
| 391 |
+
path.read_bytes(),
|
| 392 |
+
b"\r\n",
|
| 393 |
+
])
|
| 394 |
+
chunks.append(f"--{boundary}--\r\n".encode("utf-8"))
|
| 395 |
+
return b"".join(chunks), f"multipart/form-data; boundary={boundary}"
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def print_json(payload: Any) -> None:
|
| 399 |
+
print(json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True))
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def build_client(args: argparse.Namespace) -> VLLMOpenAIClient:
|
| 403 |
+
return VLLMOpenAIClient(
|
| 404 |
+
base_url=args.base_url,
|
| 405 |
+
api_key=args.api_key,
|
| 406 |
+
timeout=args.timeout,
|
| 407 |
+
retries=args.retries,
|
| 408 |
+
retry_sleep=args.retry_sleep,
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def add_common(parser: argparse.ArgumentParser) -> None:
|
| 413 |
+
parser.add_argument("--base-url", default=os.environ.get("VLLM_OPENAI_BASE_URL", os.environ.get("VLLM_BASE_URL", "http://127.0.0.1:8000")),
|
| 414 |
+
help="vLLM server root or /v1 URL.")
|
| 415 |
+
parser.add_argument("--api-key", default=os.environ.get("OPENAI_API_KEY", "EMPTY"))
|
| 416 |
+
parser.add_argument("--timeout", type=float, default=600.0)
|
| 417 |
+
parser.add_argument("--retries", type=int, default=2)
|
| 418 |
+
parser.add_argument("--retry-sleep", type=float, default=1.0)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def add_model(parser: argparse.ArgumentParser) -> None:
|
| 422 |
+
parser.add_argument("--model", required=True)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def add_extra_params(parser: argparse.ArgumentParser) -> None:
|
| 426 |
+
parser.add_argument("--param", action="append", default=[],
|
| 427 |
+
help="Extra request field as KEY=JSON_VALUE, e.g. --param top_k=20.")
|
| 428 |
+
parser.add_argument("--params-json", default="",
|
| 429 |
+
help="Extra JSON object or @file merged into the request body.")
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def merged_params(args: argparse.Namespace) -> JSONDict:
|
| 433 |
+
out: JSONDict = {}
|
| 434 |
+
if args.params_json:
|
| 435 |
+
loaded = load_json_arg(args.params_json)
|
| 436 |
+
if not isinstance(loaded, dict):
|
| 437 |
+
raise TypeError("--params-json must decode to an object")
|
| 438 |
+
out.update(loaded)
|
| 439 |
+
out.update(parse_kv_pairs(args.param))
|
| 440 |
+
return out
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def cmd_models(args: argparse.Namespace) -> None:
|
| 444 |
+
print_json(build_client(args).models())
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def cmd_health(args: argparse.Namespace) -> None:
|
| 448 |
+
print_json(build_client(args).health())
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def cmd_version(args: argparse.Namespace) -> None:
|
| 452 |
+
print_json(build_client(args).version())
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def cmd_load(args: argparse.Namespace) -> None:
|
| 456 |
+
print_json(build_client(args).load())
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def cmd_metrics(args: argparse.Namespace) -> None:
|
| 460 |
+
print(build_client(args).metrics())
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def cmd_completion(args: argparse.Namespace) -> None:
|
| 464 |
+
client = build_client(args)
|
| 465 |
+
params = merged_params(args)
|
| 466 |
+
response = client.completions(
|
| 467 |
+
model=args.model,
|
| 468 |
+
prompt=load_text_arg(args.prompt),
|
| 469 |
+
max_tokens=args.max_tokens,
|
| 470 |
+
temperature=args.temperature,
|
| 471 |
+
top_p=args.top_p,
|
| 472 |
+
stream=False,
|
| 473 |
+
**params,
|
| 474 |
+
)
|
| 475 |
+
print_json(response)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def cmd_completion_stream(args: argparse.Namespace) -> None:
|
| 479 |
+
client = build_client(args)
|
| 480 |
+
params = merged_params(args)
|
| 481 |
+
for event in client.stream_completions(
|
| 482 |
+
model=args.model,
|
| 483 |
+
prompt=load_text_arg(args.prompt),
|
| 484 |
+
max_tokens=args.max_tokens,
|
| 485 |
+
temperature=args.temperature,
|
| 486 |
+
top_p=args.top_p,
|
| 487 |
+
**params,
|
| 488 |
+
):
|
| 489 |
+
print_json(event)
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
def cmd_chat(args: argparse.Namespace) -> None:
|
| 493 |
+
client = build_client(args)
|
| 494 |
+
messages = load_json_arg(args.messages)
|
| 495 |
+
if not isinstance(messages, list):
|
| 496 |
+
raise TypeError("--messages must be a JSON list")
|
| 497 |
+
response = client.chat_completions(
|
| 498 |
+
model=args.model,
|
| 499 |
+
messages=messages,
|
| 500 |
+
max_tokens=args.max_tokens,
|
| 501 |
+
temperature=args.temperature,
|
| 502 |
+
top_p=args.top_p,
|
| 503 |
+
stream=False,
|
| 504 |
+
**merged_params(args),
|
| 505 |
+
)
|
| 506 |
+
print_json(response)
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def cmd_chat_stream(args: argparse.Namespace) -> None:
|
| 510 |
+
client = build_client(args)
|
| 511 |
+
messages = load_json_arg(args.messages)
|
| 512 |
+
if not isinstance(messages, list):
|
| 513 |
+
raise TypeError("--messages must be a JSON list")
|
| 514 |
+
for event in client.stream_chat_completions(
|
| 515 |
+
model=args.model,
|
| 516 |
+
messages=messages,
|
| 517 |
+
max_tokens=args.max_tokens,
|
| 518 |
+
temperature=args.temperature,
|
| 519 |
+
top_p=args.top_p,
|
| 520 |
+
**merged_params(args),
|
| 521 |
+
):
|
| 522 |
+
print_json(event)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def cmd_response(args: argparse.Namespace) -> None:
|
| 526 |
+
client = build_client(args)
|
| 527 |
+
response = client.create_response(
|
| 528 |
+
model=args.model,
|
| 529 |
+
input=load_text_arg(args.input),
|
| 530 |
+
**merged_params(args),
|
| 531 |
+
)
|
| 532 |
+
print_json(response)
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def cmd_messages(args: argparse.Namespace) -> None:
|
| 536 |
+
client = build_client(args)
|
| 537 |
+
messages = load_json_arg(args.messages)
|
| 538 |
+
if not isinstance(messages, list):
|
| 539 |
+
raise TypeError("--messages must be a JSON list")
|
| 540 |
+
print_json(client.messages(model=args.model, messages=messages, **merged_params(args)))
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def cmd_count_message_tokens(args: argparse.Namespace) -> None:
|
| 544 |
+
client = build_client(args)
|
| 545 |
+
messages = load_json_arg(args.messages)
|
| 546 |
+
if not isinstance(messages, list):
|
| 547 |
+
raise TypeError("--messages must be a JSON list")
|
| 548 |
+
print_json(client.count_message_tokens(model=args.model, messages=messages, **merged_params(args)))
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def cmd_embedding(args: argparse.Namespace) -> None:
|
| 552 |
+
client = build_client(args)
|
| 553 |
+
input_value = load_json_arg(args.input_json) if args.input_json else load_text_arg(args.input)
|
| 554 |
+
print_json(client.embeddings(model=args.model, input=input_value, **merged_params(args)))
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def cmd_cohere_embed(args: argparse.Namespace) -> None:
|
| 558 |
+
texts = load_json_arg(args.texts)
|
| 559 |
+
if not isinstance(texts, list):
|
| 560 |
+
raise TypeError("--texts must be a JSON list of strings")
|
| 561 |
+
print_json(build_client(args).cohere_embed(model=args.model, texts=texts, **merged_params(args)))
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
def cmd_tokenize(args: argparse.Namespace) -> None:
|
| 565 |
+
print_json(build_client(args).tokenize(
|
| 566 |
+
model=args.model,
|
| 567 |
+
prompt=load_text_arg(args.prompt),
|
| 568 |
+
add_special_tokens=args.add_special_tokens,
|
| 569 |
+
**merged_params(args),
|
| 570 |
+
))
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def cmd_detokenize(args: argparse.Namespace) -> None:
|
| 574 |
+
token_ids = load_json_arg(args.tokens)
|
| 575 |
+
if not isinstance(token_ids, list):
|
| 576 |
+
raise TypeError("--tokens must be a JSON list of token ids")
|
| 577 |
+
print_json(build_client(args).detokenize(model=args.model, tokens=token_ids, **merged_params(args)))
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def cmd_tokenizer_info(args: argparse.Namespace) -> None:
|
| 581 |
+
print_json(build_client(args).tokenizer_info(model=args.model))
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def cmd_pooling(args: argparse.Namespace) -> None:
|
| 585 |
+
input_value = load_json_arg(args.input_json) if args.input_json else load_text_arg(args.input)
|
| 586 |
+
print_json(build_client(args).pooling(model=args.model, input=input_value, **merged_params(args)))
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def cmd_classify(args: argparse.Namespace) -> None:
|
| 590 |
+
input_value = load_json_arg(args.input_json) if args.input_json else load_text_arg(args.input)
|
| 591 |
+
print_json(build_client(args).classify(model=args.model, input=input_value, **merged_params(args)))
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def cmd_score(args: argparse.Namespace) -> None:
|
| 595 |
+
print_json(build_client(args).score(
|
| 596 |
+
model=args.model,
|
| 597 |
+
text_1=load_text_arg(args.text_1),
|
| 598 |
+
text_2=load_text_arg(args.text_2),
|
| 599 |
+
path=args.path,
|
| 600 |
+
**merged_params(args),
|
| 601 |
+
))
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def cmd_rerank(args: argparse.Namespace) -> None:
|
| 605 |
+
documents = load_json_arg(args.documents)
|
| 606 |
+
if not isinstance(documents, list):
|
| 607 |
+
raise TypeError("--documents must be a JSON list")
|
| 608 |
+
print_json(build_client(args).rerank(
|
| 609 |
+
model=args.model,
|
| 610 |
+
query=args.query,
|
| 611 |
+
documents=documents,
|
| 612 |
+
path=args.path,
|
| 613 |
+
**merged_params(args),
|
| 614 |
+
))
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
def cmd_generative_scoring(args: argparse.Namespace) -> None:
|
| 618 |
+
token_ids = load_json_arg(args.label_token_ids)
|
| 619 |
+
if not isinstance(token_ids, list):
|
| 620 |
+
raise TypeError("--label-token-ids must be a JSON list of token ids")
|
| 621 |
+
print_json(build_client(args).generative_scoring(
|
| 622 |
+
model=args.model,
|
| 623 |
+
prompt=load_text_arg(args.prompt),
|
| 624 |
+
label_token_ids=token_ids,
|
| 625 |
+
**merged_params(args),
|
| 626 |
+
))
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def cmd_transcribe(args: argparse.Namespace) -> None:
|
| 630 |
+
print_json(build_client(args).transcribe(
|
| 631 |
+
model=args.model,
|
| 632 |
+
file_path=args.file,
|
| 633 |
+
**merged_params(args),
|
| 634 |
+
))
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def cmd_translate(args: argparse.Namespace) -> None:
|
| 638 |
+
print_json(build_client(args).translate(
|
| 639 |
+
model=args.model,
|
| 640 |
+
file_path=args.file,
|
| 641 |
+
**merged_params(args),
|
| 642 |
+
))
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
def cmd_load_lora(args: argparse.Namespace) -> None:
|
| 646 |
+
print_json(build_client(args).load_lora_adapter(
|
| 647 |
+
lora_name=args.lora_name,
|
| 648 |
+
lora_path=args.lora_path,
|
| 649 |
+
))
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
def cmd_unload_lora(args: argparse.Namespace) -> None:
|
| 653 |
+
print_json(build_client(args).unload_lora_adapter(lora_name=args.lora_name))
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def cmd_raw(args: argparse.Namespace) -> None:
|
| 657 |
+
client = build_client(args)
|
| 658 |
+
body = load_json_arg(args.body) if args.body else None
|
| 659 |
+
response = client.request(args.method, args.path, json_body=body)
|
| 660 |
+
print_json(response)
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
def build_parser() -> argparse.ArgumentParser:
|
| 664 |
+
parser = argparse.ArgumentParser(
|
| 665 |
+
description="Stdlib-only wrapper around vLLM's OpenAI-compatible and custom HTTP APIs."
|
| 666 |
+
)
|
| 667 |
+
add_common(parser)
|
| 668 |
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
| 669 |
+
|
| 670 |
+
for name, func in (
|
| 671 |
+
("models", cmd_models),
|
| 672 |
+
("health", cmd_health),
|
| 673 |
+
("version", cmd_version),
|
| 674 |
+
("load", cmd_load),
|
| 675 |
+
("metrics", cmd_metrics),
|
| 676 |
+
):
|
| 677 |
+
child = subparsers.add_parser(name)
|
| 678 |
+
child.set_defaults(func=func)
|
| 679 |
+
|
| 680 |
+
completion = subparsers.add_parser("completion")
|
| 681 |
+
add_model(completion)
|
| 682 |
+
add_extra_params(completion)
|
| 683 |
+
completion.add_argument("--prompt", required=True, help="Prompt text or @file.")
|
| 684 |
+
completion.add_argument("--max-tokens", type=int, default=128)
|
| 685 |
+
completion.add_argument("--temperature", type=float, default=0.0)
|
| 686 |
+
completion.add_argument("--top-p", type=float, default=1.0)
|
| 687 |
+
completion.set_defaults(func=cmd_completion)
|
| 688 |
+
|
| 689 |
+
completion_stream = subparsers.add_parser("completion-stream")
|
| 690 |
+
add_model(completion_stream)
|
| 691 |
+
add_extra_params(completion_stream)
|
| 692 |
+
completion_stream.add_argument("--prompt", required=True, help="Prompt text or @file.")
|
| 693 |
+
completion_stream.add_argument("--max-tokens", type=int, default=128)
|
| 694 |
+
completion_stream.add_argument("--temperature", type=float, default=0.0)
|
| 695 |
+
completion_stream.add_argument("--top-p", type=float, default=1.0)
|
| 696 |
+
completion_stream.set_defaults(func=cmd_completion_stream)
|
| 697 |
+
|
| 698 |
+
chat = subparsers.add_parser("chat")
|
| 699 |
+
add_model(chat)
|
| 700 |
+
add_extra_params(chat)
|
| 701 |
+
chat.add_argument("--messages", required=True, help='JSON list or file path, e.g. \'[{"role":"user","content":"hi"}]\'.')
|
| 702 |
+
chat.add_argument("--max-tokens", type=int, default=128)
|
| 703 |
+
chat.add_argument("--temperature", type=float, default=0.0)
|
| 704 |
+
chat.add_argument("--top-p", type=float, default=1.0)
|
| 705 |
+
chat.set_defaults(func=cmd_chat)
|
| 706 |
+
|
| 707 |
+
chat_stream = subparsers.add_parser("chat-stream")
|
| 708 |
+
add_model(chat_stream)
|
| 709 |
+
add_extra_params(chat_stream)
|
| 710 |
+
chat_stream.add_argument("--messages", required=True)
|
| 711 |
+
chat_stream.add_argument("--max-tokens", type=int, default=128)
|
| 712 |
+
chat_stream.add_argument("--temperature", type=float, default=0.0)
|
| 713 |
+
chat_stream.add_argument("--top-p", type=float, default=1.0)
|
| 714 |
+
chat_stream.set_defaults(func=cmd_chat_stream)
|
| 715 |
+
|
| 716 |
+
response = subparsers.add_parser("response")
|
| 717 |
+
add_model(response)
|
| 718 |
+
add_extra_params(response)
|
| 719 |
+
response.add_argument("--input", required=True, help="Input text or @file.")
|
| 720 |
+
response.set_defaults(func=cmd_response)
|
| 721 |
+
|
| 722 |
+
messages = subparsers.add_parser("messages")
|
| 723 |
+
add_model(messages)
|
| 724 |
+
add_extra_params(messages)
|
| 725 |
+
messages.add_argument("--messages", required=True, help="Anthropic-style JSON message list or @file.")
|
| 726 |
+
messages.set_defaults(func=cmd_messages)
|
| 727 |
+
|
| 728 |
+
count_message_tokens = subparsers.add_parser("count-message-tokens")
|
| 729 |
+
add_model(count_message_tokens)
|
| 730 |
+
add_extra_params(count_message_tokens)
|
| 731 |
+
count_message_tokens.add_argument("--messages", required=True, help="Anthropic-style JSON message list or @file.")
|
| 732 |
+
count_message_tokens.set_defaults(func=cmd_count_message_tokens)
|
| 733 |
+
|
| 734 |
+
embedding = subparsers.add_parser("embedding")
|
| 735 |
+
add_model(embedding)
|
| 736 |
+
add_extra_params(embedding)
|
| 737 |
+
embedding.add_argument("--input", default="", help="Input text or @file.")
|
| 738 |
+
embedding.add_argument("--input-json", default="", help="JSON input, e.g. a list of strings.")
|
| 739 |
+
embedding.set_defaults(func=cmd_embedding)
|
| 740 |
+
|
| 741 |
+
cohere_embed = subparsers.add_parser("cohere-embed")
|
| 742 |
+
add_model(cohere_embed)
|
| 743 |
+
add_extra_params(cohere_embed)
|
| 744 |
+
cohere_embed.add_argument("--texts", required=True, help="JSON list of strings or @file.")
|
| 745 |
+
cohere_embed.set_defaults(func=cmd_cohere_embed)
|
| 746 |
+
|
| 747 |
+
tokenize = subparsers.add_parser("tokenize")
|
| 748 |
+
add_model(tokenize)
|
| 749 |
+
add_extra_params(tokenize)
|
| 750 |
+
tokenize.add_argument("--prompt", required=True, help="Prompt text or @file.")
|
| 751 |
+
tokenize.add_argument("--add-special-tokens", action="store_true")
|
| 752 |
+
tokenize.set_defaults(func=cmd_tokenize)
|
| 753 |
+
|
| 754 |
+
detokenize = subparsers.add_parser("detokenize")
|
| 755 |
+
add_model(detokenize)
|
| 756 |
+
add_extra_params(detokenize)
|
| 757 |
+
detokenize.add_argument("--tokens", required=True, help="JSON list of token ids.")
|
| 758 |
+
detokenize.set_defaults(func=cmd_detokenize)
|
| 759 |
+
|
| 760 |
+
tokenizer_info = subparsers.add_parser("tokenizer-info")
|
| 761 |
+
tokenizer_info.add_argument("--model", default=None)
|
| 762 |
+
tokenizer_info.set_defaults(func=cmd_tokenizer_info)
|
| 763 |
+
|
| 764 |
+
pooling = subparsers.add_parser("pooling")
|
| 765 |
+
add_model(pooling)
|
| 766 |
+
add_extra_params(pooling)
|
| 767 |
+
pooling.add_argument("--input", default="", help="Input text or @file.")
|
| 768 |
+
pooling.add_argument("--input-json", default="", help="JSON input.")
|
| 769 |
+
pooling.set_defaults(func=cmd_pooling)
|
| 770 |
+
|
| 771 |
+
classify = subparsers.add_parser("classify")
|
| 772 |
+
add_model(classify)
|
| 773 |
+
add_extra_params(classify)
|
| 774 |
+
classify.add_argument("--input", default="", help="Input text or @file.")
|
| 775 |
+
classify.add_argument("--input-json", default="", help="JSON input.")
|
| 776 |
+
classify.set_defaults(func=cmd_classify)
|
| 777 |
+
|
| 778 |
+
score = subparsers.add_parser("score")
|
| 779 |
+
add_model(score)
|
| 780 |
+
add_extra_params(score)
|
| 781 |
+
score.add_argument("--text-1", required=True, help="Text or @file.")
|
| 782 |
+
score.add_argument("--text-2", required=True, help="Text or @file.")
|
| 783 |
+
score.add_argument("--path", default="/score", choices=["/score", "/v1/score"])
|
| 784 |
+
score.set_defaults(func=cmd_score)
|
| 785 |
+
|
| 786 |
+
rerank = subparsers.add_parser("rerank")
|
| 787 |
+
add_model(rerank)
|
| 788 |
+
add_extra_params(rerank)
|
| 789 |
+
rerank.add_argument("--query", required=True)
|
| 790 |
+
rerank.add_argument("--documents", required=True, help="JSON list of strings or document objects.")
|
| 791 |
+
rerank.add_argument("--path", default="/rerank", choices=["/rerank", "/v1/rerank", "/v2/rerank"])
|
| 792 |
+
rerank.set_defaults(func=cmd_rerank)
|
| 793 |
+
|
| 794 |
+
generative_scoring = subparsers.add_parser("generative-scoring")
|
| 795 |
+
add_model(generative_scoring)
|
| 796 |
+
add_extra_params(generative_scoring)
|
| 797 |
+
generative_scoring.add_argument("--prompt", required=True, help="Prompt text or @file.")
|
| 798 |
+
generative_scoring.add_argument("--label-token-ids", required=True, help="JSON list of token ids.")
|
| 799 |
+
generative_scoring.set_defaults(func=cmd_generative_scoring)
|
| 800 |
+
|
| 801 |
+
transcribe = subparsers.add_parser("transcribe")
|
| 802 |
+
add_model(transcribe)
|
| 803 |
+
add_extra_params(transcribe)
|
| 804 |
+
transcribe.add_argument("--file", required=True)
|
| 805 |
+
transcribe.set_defaults(func=cmd_transcribe)
|
| 806 |
+
|
| 807 |
+
translate = subparsers.add_parser("translate")
|
| 808 |
+
add_model(translate)
|
| 809 |
+
add_extra_params(translate)
|
| 810 |
+
translate.add_argument("--file", required=True)
|
| 811 |
+
translate.set_defaults(func=cmd_translate)
|
| 812 |
+
|
| 813 |
+
load_lora = subparsers.add_parser("load-lora")
|
| 814 |
+
load_lora.add_argument("--lora-name", required=True)
|
| 815 |
+
load_lora.add_argument("--lora-path", required=True)
|
| 816 |
+
load_lora.set_defaults(func=cmd_load_lora)
|
| 817 |
+
|
| 818 |
+
unload_lora = subparsers.add_parser("unload-lora")
|
| 819 |
+
unload_lora.add_argument("--lora-name", required=True)
|
| 820 |
+
unload_lora.set_defaults(func=cmd_unload_lora)
|
| 821 |
+
|
| 822 |
+
raw = subparsers.add_parser("raw")
|
| 823 |
+
raw.add_argument("--method", default="POST", choices=["GET", "POST", "DELETE"])
|
| 824 |
+
raw.add_argument("--path", required=True)
|
| 825 |
+
raw.add_argument("--body", default="", help="JSON object/array/scalar or file path.")
|
| 826 |
+
raw.set_defaults(func=cmd_raw)
|
| 827 |
+
|
| 828 |
+
return parser
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 832 |
+
parser = build_parser()
|
| 833 |
+
args = parser.parse_args(argv)
|
| 834 |
+
try:
|
| 835 |
+
args.func(args)
|
| 836 |
+
return 0
|
| 837 |
+
except BrokenPipeError:
|
| 838 |
+
return 1
|
| 839 |
+
except Exception as exc:
|
| 840 |
+
print(f"error: {exc}", file=sys.stderr)
|
| 841 |
+
return 2
|
| 842 |
+
|
| 843 |
+
|
| 844 |
+
if __name__ == "__main__":
|
| 845 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/scripts/worker_inference.py
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
+
import urllib.error
|
| 10 |
+
import urllib.request
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 16 |
+
SRC_ROOT = PROJECT_ROOT / "src"
|
| 17 |
+
if SRC_ROOT.exists():
|
| 18 |
+
sys.path.insert(0, str(SRC_ROOT))
|
| 19 |
+
|
| 20 |
+
from worker_logits_verify.schema import ( # noqa: E402
|
| 21 |
+
DecodeConfig,
|
| 22 |
+
VariantInfo,
|
| 23 |
+
dataclass_to_dict,
|
| 24 |
+
parse_worker_sample,
|
| 25 |
+
read_jsonl,
|
| 26 |
+
runtime_metadata,
|
| 27 |
+
write_json,
|
| 28 |
+
)
|
| 29 |
+
from worker_logits_verify.vllm_utils import sorted_top_logprobs, write_jsonl_row # noqa: E402
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
JSONDict = Dict[str, Any]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def log(message: str) -> None:
|
| 36 |
+
print(message, flush=True)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_extra_body(raw: str) -> JSONDict:
|
| 40 |
+
if not raw:
|
| 41 |
+
return {}
|
| 42 |
+
path = Path(raw)
|
| 43 |
+
if path.exists():
|
| 44 |
+
return json.loads(path.read_text(encoding="utf-8"))
|
| 45 |
+
return json.loads(raw)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def compact_dict(payload: JSONDict) -> JSONDict:
|
| 49 |
+
return {key: value for key, value in payload.items() if value is not None}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def endpoint_url(base_url: str, path: str) -> str:
|
| 53 |
+
return f"{base_url.rstrip('/')}/{path.lstrip('/')}"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class VLLMOpenAIClient:
|
| 57 |
+
def __init__(self,
|
| 58 |
+
base_url: str,
|
| 59 |
+
api_key: str,
|
| 60 |
+
timeout: float,
|
| 61 |
+
retries: int,
|
| 62 |
+
retry_sleep: float) -> None:
|
| 63 |
+
self.base_url = base_url.rstrip("/")
|
| 64 |
+
self.api_key = api_key
|
| 65 |
+
self.timeout = timeout
|
| 66 |
+
self.retries = retries
|
| 67 |
+
self.retry_sleep = retry_sleep
|
| 68 |
+
|
| 69 |
+
def post_json(self, path: str, payload: JSONDict) -> JSONDict:
|
| 70 |
+
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
| 71 |
+
request = urllib.request.Request(
|
| 72 |
+
endpoint_url(self.base_url, path),
|
| 73 |
+
data=data,
|
| 74 |
+
headers={
|
| 75 |
+
"Authorization": f"Bearer {self.api_key}",
|
| 76 |
+
"Content-Type": "application/json",
|
| 77 |
+
},
|
| 78 |
+
method="POST",
|
| 79 |
+
)
|
| 80 |
+
last_error: Optional[BaseException] = None
|
| 81 |
+
for attempt in range(self.retries + 1):
|
| 82 |
+
try:
|
| 83 |
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
| 84 |
+
return json.loads(response.read().decode("utf-8"))
|
| 85 |
+
except urllib.error.HTTPError as exc:
|
| 86 |
+
body = exc.read().decode("utf-8", errors="replace")
|
| 87 |
+
last_error = RuntimeError(f"HTTP {exc.code} from {path}: {body}")
|
| 88 |
+
except urllib.error.URLError as exc:
|
| 89 |
+
last_error = exc
|
| 90 |
+
if attempt < self.retries:
|
| 91 |
+
time.sleep(self.retry_sleep)
|
| 92 |
+
assert last_error is not None
|
| 93 |
+
raise last_error
|
| 94 |
+
|
| 95 |
+
def tokenize(self, model: str, text: str) -> List[int]:
|
| 96 |
+
response = self.post_json("/tokenize", {
|
| 97 |
+
"model": model,
|
| 98 |
+
"prompt": text,
|
| 99 |
+
"add_special_tokens": False,
|
| 100 |
+
})
|
| 101 |
+
token_ids = (
|
| 102 |
+
response.get("token_ids")
|
| 103 |
+
or response.get("tokens")
|
| 104 |
+
or response.get("input_ids")
|
| 105 |
+
)
|
| 106 |
+
if not isinstance(token_ids, list):
|
| 107 |
+
raise ValueError(f"/tokenize response did not include token ids: {response}")
|
| 108 |
+
return [int(token_id) for token_id in token_ids]
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def safe_float(value: Any) -> Optional[float]:
|
| 112 |
+
if value is None:
|
| 113 |
+
return None
|
| 114 |
+
try:
|
| 115 |
+
return float(value)
|
| 116 |
+
except (TypeError, ValueError):
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def parse_token_id(value: Any) -> Optional[int]:
|
| 121 |
+
if isinstance(value, int):
|
| 122 |
+
return int(value)
|
| 123 |
+
if isinstance(value, float) and value.is_integer():
|
| 124 |
+
return int(value)
|
| 125 |
+
if not isinstance(value, str):
|
| 126 |
+
return None
|
| 127 |
+
text = value.strip()
|
| 128 |
+
if text.startswith("token_id:"):
|
| 129 |
+
text = text.split(":", 1)[1].strip()
|
| 130 |
+
if text.startswith("<token_id:") and text.endswith(">"):
|
| 131 |
+
text = text[len("<token_id:"):-1].strip()
|
| 132 |
+
if text.isdigit():
|
| 133 |
+
return int(text)
|
| 134 |
+
return None
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def decoded_token_from_key(value: Any, token_id: Optional[int]) -> str:
|
| 138 |
+
if token_id is None and isinstance(value, str):
|
| 139 |
+
return value
|
| 140 |
+
if isinstance(value, str) and not value.strip().startswith("token_id:"):
|
| 141 |
+
return value
|
| 142 |
+
return ""
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def normalize_logprob_mapping(raw: Any,
|
| 146 |
+
*,
|
| 147 |
+
strict_token_ids: bool,
|
| 148 |
+
context: str) -> Dict[str, Dict[str, Any]]:
|
| 149 |
+
if raw is None:
|
| 150 |
+
return {}
|
| 151 |
+
|
| 152 |
+
rows: List[Tuple[int, Dict[str, Any]]] = []
|
| 153 |
+
bad_keys: List[str] = []
|
| 154 |
+
|
| 155 |
+
def add_item(key: Any, value: Any, position: int) -> None:
|
| 156 |
+
token_id = parse_token_id(key)
|
| 157 |
+
decoded_token = decoded_token_from_key(key, token_id)
|
| 158 |
+
rank: Optional[int] = None
|
| 159 |
+
logprob: Optional[float] = None
|
| 160 |
+
|
| 161 |
+
if isinstance(value, dict):
|
| 162 |
+
explicit_token_id = value.get("token_id")
|
| 163 |
+
if explicit_token_id is not None:
|
| 164 |
+
token_id = parse_token_id(explicit_token_id)
|
| 165 |
+
elif token_id is None:
|
| 166 |
+
token_id = parse_token_id(value.get("token"))
|
| 167 |
+
decoded_token = str(
|
| 168 |
+
value.get("decoded_token")
|
| 169 |
+
or value.get("token")
|
| 170 |
+
or decoded_token
|
| 171 |
+
or ""
|
| 172 |
+
)
|
| 173 |
+
rank_value = value.get("rank")
|
| 174 |
+
rank = int(rank_value) if rank_value is not None else None
|
| 175 |
+
logprob = safe_float(value.get("logprob", value.get("value")))
|
| 176 |
+
else:
|
| 177 |
+
logprob = safe_float(value)
|
| 178 |
+
|
| 179 |
+
if token_id is None:
|
| 180 |
+
bad_keys.append(str(key))
|
| 181 |
+
return
|
| 182 |
+
rows.append((
|
| 183 |
+
int(token_id),
|
| 184 |
+
{
|
| 185 |
+
"logprob": logprob,
|
| 186 |
+
"rank": rank if rank is not None else position,
|
| 187 |
+
"decoded_token": decoded_token,
|
| 188 |
+
},
|
| 189 |
+
))
|
| 190 |
+
|
| 191 |
+
if isinstance(raw, dict):
|
| 192 |
+
for position, (key, value) in enumerate(raw.items(), start=1):
|
| 193 |
+
add_item(key, value, position)
|
| 194 |
+
elif isinstance(raw, list):
|
| 195 |
+
for position, item in enumerate(raw, start=1):
|
| 196 |
+
if isinstance(item, dict):
|
| 197 |
+
key = item.get("token_id", item.get("token"))
|
| 198 |
+
add_item(key, item, position)
|
| 199 |
+
else:
|
| 200 |
+
add_item(position, item, position)
|
| 201 |
+
else:
|
| 202 |
+
raise TypeError(f"{context}: unsupported logprob container {type(raw).__name__}")
|
| 203 |
+
|
| 204 |
+
if bad_keys and strict_token_ids:
|
| 205 |
+
preview = ", ".join(repr(key) for key in bad_keys[:5])
|
| 206 |
+
raise ValueError(
|
| 207 |
+
f"{context}: top logprob keys do not expose token ids ({preview}). "
|
| 208 |
+
"Start vLLM OpenAI server with token-id support and keep "
|
| 209 |
+
"`return_token_ids` / `return_tokens_as_token_ids` enabled, "
|
| 210 |
+
"or rerun with --allow-text-top-logprobs to ignore unmapped top-k entries."
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
return {str(token_id): info for token_id, info in rows}
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def extract_completion_token_ids(choice: JSONDict) -> List[int]:
|
| 217 |
+
logprobs = choice.get("logprobs") or {}
|
| 218 |
+
candidates = [
|
| 219 |
+
choice.get("token_ids"),
|
| 220 |
+
choice.get("output_token_ids"),
|
| 221 |
+
logprobs.get("token_ids") if isinstance(logprobs, dict) else None,
|
| 222 |
+
]
|
| 223 |
+
for candidate in candidates:
|
| 224 |
+
if isinstance(candidate, list):
|
| 225 |
+
return [int(token_id) for token_id in candidate]
|
| 226 |
+
|
| 227 |
+
tokens = logprobs.get("tokens") if isinstance(logprobs, dict) else None
|
| 228 |
+
if isinstance(tokens, list):
|
| 229 |
+
parsed = [parse_token_id(token) for token in tokens]
|
| 230 |
+
if all(token_id is not None for token_id in parsed):
|
| 231 |
+
return [int(token_id) for token_id in parsed if token_id is not None]
|
| 232 |
+
return []
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _nested_prompt_ids(value: Any, choice_index: int) -> Optional[List[int]]:
|
| 236 |
+
if not isinstance(value, list):
|
| 237 |
+
return None
|
| 238 |
+
if not value:
|
| 239 |
+
return []
|
| 240 |
+
if all(isinstance(item, int) for item in value):
|
| 241 |
+
return [int(item) for item in value]
|
| 242 |
+
if choice_index < len(value) and isinstance(value[choice_index], list):
|
| 243 |
+
return [int(token_id) for token_id in value[choice_index]]
|
| 244 |
+
return None
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def extract_prompt_token_ids(response: JSONDict,
|
| 248 |
+
choice: JSONDict,
|
| 249 |
+
choice_index: int) -> List[int]:
|
| 250 |
+
logprobs = choice.get("logprobs") or {}
|
| 251 |
+
candidates = [
|
| 252 |
+
choice.get("prompt_token_ids"),
|
| 253 |
+
logprobs.get("prompt_token_ids") if isinstance(logprobs, dict) else None,
|
| 254 |
+
response.get("prompt_token_ids"),
|
| 255 |
+
]
|
| 256 |
+
for candidate in candidates:
|
| 257 |
+
token_ids = _nested_prompt_ids(candidate, choice_index)
|
| 258 |
+
if token_ids is not None:
|
| 259 |
+
return token_ids
|
| 260 |
+
return []
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def selected_rank(top_logprobs: Sequence[JSONDict], token_id: int) -> Optional[int]:
|
| 264 |
+
for item in top_logprobs:
|
| 265 |
+
if int(item["token_id"]) == int(token_id):
|
| 266 |
+
rank = item.get("rank", item.get("position"))
|
| 267 |
+
return int(rank) if rank is not None else None
|
| 268 |
+
return None
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def trace_from_completion_choice(choice: JSONDict,
|
| 272 |
+
output_ids: Sequence[int],
|
| 273 |
+
*,
|
| 274 |
+
strict_token_ids: bool) -> List[JSONDict]:
|
| 275 |
+
logprobs = choice.get("logprobs") or {}
|
| 276 |
+
tokens = logprobs.get("tokens", []) if isinstance(logprobs, dict) else []
|
| 277 |
+
token_logprobs = logprobs.get("token_logprobs", []) if isinstance(logprobs, dict) else []
|
| 278 |
+
top_logprobs = logprobs.get("top_logprobs", []) if isinstance(logprobs, dict) else []
|
| 279 |
+
rows: List[JSONDict] = []
|
| 280 |
+
|
| 281 |
+
for depth, token_id in enumerate(output_ids):
|
| 282 |
+
selected_logprob = (
|
| 283 |
+
safe_float(token_logprobs[depth])
|
| 284 |
+
if depth < len(token_logprobs) else None
|
| 285 |
+
)
|
| 286 |
+
target_token = tokens[depth] if depth < len(tokens) else ""
|
| 287 |
+
raw_top = top_logprobs[depth] if depth < len(top_logprobs) else {}
|
| 288 |
+
top_map = normalize_logprob_mapping(
|
| 289 |
+
raw_top,
|
| 290 |
+
strict_token_ids=strict_token_ids,
|
| 291 |
+
context=f"completion depth={depth}",
|
| 292 |
+
)
|
| 293 |
+
top_rows = sorted_top_logprobs(top_map)
|
| 294 |
+
rows.append({
|
| 295 |
+
"depth": depth,
|
| 296 |
+
"target_token_id": int(token_id),
|
| 297 |
+
"target_decoded_token": decoded_token_from_key(target_token, parse_token_id(target_token)),
|
| 298 |
+
"selected_logprob": selected_logprob,
|
| 299 |
+
"selected_rank": selected_rank(top_rows, int(token_id)),
|
| 300 |
+
"top_logprobs": top_rows,
|
| 301 |
+
})
|
| 302 |
+
return rows
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def make_completion_body(args: argparse.Namespace,
|
| 306 |
+
prompts: Sequence[Any],
|
| 307 |
+
*,
|
| 308 |
+
prompt_logprobs: Optional[int] = None) -> JSONDict:
|
| 309 |
+
body: JSONDict = {
|
| 310 |
+
"model": args.model,
|
| 311 |
+
"prompt": list(prompts),
|
| 312 |
+
"max_tokens": args.max_new_tokens,
|
| 313 |
+
"temperature": args.temperature,
|
| 314 |
+
"top_p": args.top_p,
|
| 315 |
+
"logprobs": args.logprobs if prompt_logprobs is None else None,
|
| 316 |
+
"prompt_logprobs": prompt_logprobs,
|
| 317 |
+
"echo": False,
|
| 318 |
+
"seed": args.seed,
|
| 319 |
+
"stream": False,
|
| 320 |
+
"return_token_ids": True,
|
| 321 |
+
"return_tokens_as_token_ids": True,
|
| 322 |
+
"skip_special_tokens": False,
|
| 323 |
+
}
|
| 324 |
+
if args.top_k > 0:
|
| 325 |
+
body["top_k"] = args.top_k
|
| 326 |
+
body.update(load_extra_body(args.extra_body_json))
|
| 327 |
+
return compact_dict(body)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def choices_by_index(response: JSONDict, expected_count: int) -> List[JSONDict]:
|
| 331 |
+
choices = response.get("choices")
|
| 332 |
+
if not isinstance(choices, list):
|
| 333 |
+
raise ValueError(f"Completion response missing choices: {response}")
|
| 334 |
+
ordered: List[Optional[JSONDict]] = [None] * expected_count
|
| 335 |
+
extras: List[JSONDict] = []
|
| 336 |
+
for position, choice in enumerate(choices):
|
| 337 |
+
if not isinstance(choice, dict):
|
| 338 |
+
continue
|
| 339 |
+
index = choice.get("index", position)
|
| 340 |
+
if isinstance(index, int) and 0 <= index < expected_count and ordered[index] is None:
|
| 341 |
+
ordered[index] = choice
|
| 342 |
+
else:
|
| 343 |
+
extras.append(choice)
|
| 344 |
+
for index in range(expected_count):
|
| 345 |
+
if ordered[index] is None and extras:
|
| 346 |
+
ordered[index] = extras.pop(0)
|
| 347 |
+
if any(choice is None for choice in ordered):
|
| 348 |
+
raise RuntimeError(f"vLLM returned {len(choices)} choices for {expected_count} prompts")
|
| 349 |
+
return [choice for choice in ordered if choice is not None]
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def make_variant(args: argparse.Namespace) -> VariantInfo:
|
| 353 |
+
return VariantInfo(
|
| 354 |
+
variant_id=args.variant_id,
|
| 355 |
+
model=args.model,
|
| 356 |
+
tokenizer_hash=args.tokenizer_hash,
|
| 357 |
+
tokenizer_name=args.tokenizer_name or args.model,
|
| 358 |
+
quantization=args.quantization,
|
| 359 |
+
gpu=args.gpu,
|
| 360 |
+
backend="vllm-openai-api",
|
| 361 |
+
backend_version=args.backend_version,
|
| 362 |
+
dtype=args.dtype,
|
| 363 |
+
extra={
|
| 364 |
+
"base_url": args.base_url,
|
| 365 |
+
"logprobs": args.logprobs,
|
| 366 |
+
"return_token_ids": True,
|
| 367 |
+
"return_tokens_as_token_ids": True,
|
| 368 |
+
},
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def build_arg_parser() -> argparse.ArgumentParser:
|
| 373 |
+
parser = argparse.ArgumentParser(
|
| 374 |
+
description="Run worker inference through the vLLM OpenAI-compatible Completions API and store token-id logprob evidence."
|
| 375 |
+
)
|
| 376 |
+
parser.add_argument("--input", default="data/prompts.jsonl")
|
| 377 |
+
parser.add_argument("--output", default="data/worker_evidence.openai.jsonl")
|
| 378 |
+
parser.add_argument("--base-url", default=os.environ.get("VLLM_OPENAI_BASE_URL", "http://localhost:8000/v1"))
|
| 379 |
+
parser.add_argument("--api-key", default=os.environ.get("OPENAI_API_KEY", "EMPTY"))
|
| 380 |
+
parser.add_argument("--model", required=True)
|
| 381 |
+
parser.add_argument("--variant-id", required=True)
|
| 382 |
+
parser.add_argument("--gpu", default="")
|
| 383 |
+
parser.add_argument("--quantization", default="bf16")
|
| 384 |
+
parser.add_argument("--dtype", default="auto")
|
| 385 |
+
parser.add_argument("--backend-version", default="")
|
| 386 |
+
parser.add_argument("--tokenizer-name", default="")
|
| 387 |
+
parser.add_argument("--tokenizer-hash", default="")
|
| 388 |
+
parser.add_argument("--max-new-tokens", type=int, default=128)
|
| 389 |
+
parser.add_argument("--logprobs", type=int, default=32)
|
| 390 |
+
parser.add_argument("--temperature", type=float, default=0.0)
|
| 391 |
+
parser.add_argument("--top-p", type=float, default=1.0)
|
| 392 |
+
parser.add_argument("--top-k", type=int, default=0)
|
| 393 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 394 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 395 |
+
parser.add_argument("--timeout", type=float, default=600.0)
|
| 396 |
+
parser.add_argument("--retries", type=int, default=2)
|
| 397 |
+
parser.add_argument("--retry-sleep", type=float, default=2.0)
|
| 398 |
+
parser.add_argument("--extra-body-json", default="",
|
| 399 |
+
help="Extra JSON object or JSON file merged into each /v1/completions request.")
|
| 400 |
+
parser.add_argument("--allow-text-top-logprobs", action="store_true",
|
| 401 |
+
help="Keep running if top_logprobs keys are text instead of token ids; unmapped top-k entries are dropped.")
|
| 402 |
+
parser.add_argument("--disable-tokenize-fallback", action="store_true",
|
| 403 |
+
help="Do not call vLLM /tokenize if prompt_token_ids are absent from completion responses.")
|
| 404 |
+
return parser
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 408 |
+
parser = build_arg_parser()
|
| 409 |
+
args = parser.parse_args(argv)
|
| 410 |
+
|
| 411 |
+
client = VLLMOpenAIClient(
|
| 412 |
+
base_url=args.base_url,
|
| 413 |
+
api_key=args.api_key,
|
| 414 |
+
timeout=args.timeout,
|
| 415 |
+
retries=args.retries,
|
| 416 |
+
retry_sleep=args.retry_sleep,
|
| 417 |
+
)
|
| 418 |
+
variant = make_variant(args)
|
| 419 |
+
decode_config = DecodeConfig(
|
| 420 |
+
max_new_tokens=args.max_new_tokens,
|
| 421 |
+
temperature=args.temperature,
|
| 422 |
+
top_p=args.top_p,
|
| 423 |
+
top_k=args.top_k,
|
| 424 |
+
seed=args.seed,
|
| 425 |
+
do_sample=args.temperature > 0.0,
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
samples = []
|
| 429 |
+
for index, payload in enumerate(read_jsonl(Path(args.input)), start=1):
|
| 430 |
+
if args.limit and index > args.limit:
|
| 431 |
+
break
|
| 432 |
+
samples.append((index, parse_worker_sample(payload)))
|
| 433 |
+
|
| 434 |
+
output_path = Path(args.output)
|
| 435 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 436 |
+
strict_token_ids = not args.allow_text_top_logprobs
|
| 437 |
+
total_start = time.time()
|
| 438 |
+
written = 0
|
| 439 |
+
|
| 440 |
+
with output_path.open("w", encoding="utf-8") as handle:
|
| 441 |
+
for request_index, (input_index, sample) in enumerate(samples, start=1):
|
| 442 |
+
prompts = [sample.input_text]
|
| 443 |
+
body = make_completion_body(args, prompts)
|
| 444 |
+
log(f"Worker OpenAI request {request_index}/{len(samples)}")
|
| 445 |
+
response = client.post_json("/completions", body)
|
| 446 |
+
choice = choices_by_index(response, 1)[0]
|
| 447 |
+
input_ids = extract_prompt_token_ids(response, choice, 0)
|
| 448 |
+
if not input_ids and not args.disable_tokenize_fallback:
|
| 449 |
+
input_ids = client.tokenize(args.model, sample.input_text)
|
| 450 |
+
if not input_ids:
|
| 451 |
+
raise ValueError(
|
| 452 |
+
"Could not recover input_ids. Keep return_token_ids enabled "
|
| 453 |
+
"or allow the /tokenize fallback."
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
output_ids = extract_completion_token_ids(choice)
|
| 457 |
+
if not output_ids:
|
| 458 |
+
raise ValueError(
|
| 459 |
+
"Could not recover output_ids from completion response. "
|
| 460 |
+
"Ensure vLLM supports return_token_ids on /v1/completions."
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
row = {
|
| 464 |
+
"sample_id": sample.sample_id,
|
| 465 |
+
"input_text": sample.input_text,
|
| 466 |
+
"input_ids": input_ids,
|
| 467 |
+
"output_text": choice.get("text", ""),
|
| 468 |
+
"output_ids": output_ids,
|
| 469 |
+
"category": sample.category,
|
| 470 |
+
"target_input_tokens": sample.target_input_tokens,
|
| 471 |
+
"worker_variant": dataclass_to_dict(variant),
|
| 472 |
+
"decode_config": dataclass_to_dict(decode_config),
|
| 473 |
+
"worker_trace_mode": "vllm_openai_completions_decode",
|
| 474 |
+
"worker_trace": trace_from_completion_choice(
|
| 475 |
+
choice,
|
| 476 |
+
output_ids,
|
| 477 |
+
strict_token_ids=strict_token_ids,
|
| 478 |
+
),
|
| 479 |
+
}
|
| 480 |
+
write_jsonl_row(handle, row)
|
| 481 |
+
written += 1
|
| 482 |
+
log(
|
| 483 |
+
f"[{input_index}] sample={sample.sample_id} "
|
| 484 |
+
f"input_tokens={len(input_ids)} output_tokens={len(output_ids)}"
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
write_json(output_path.with_suffix(output_path.suffix + ".metadata.json"), {
|
| 488 |
+
"metadata": runtime_metadata(sys.argv),
|
| 489 |
+
"args": vars(args),
|
| 490 |
+
"worker_variant": dataclass_to_dict(variant),
|
| 491 |
+
"sample_count": written,
|
| 492 |
+
"elapsed_seconds": time.time() - total_start,
|
| 493 |
+
})
|
| 494 |
+
log(f"Wrote {written} worker evidence rows to {output_path}")
|
| 495 |
+
return 0
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
if __name__ == "__main__":
|
| 499 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/src/worker_logits_verify/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Depth-aware worker logits verification tools."""
|
| 2 |
+
|
| 3 |
+
__version__ = "0.1.0"
|
tools/worker_logits_verify/src/worker_logits_verify/analyze_depth_effect.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import math
|
| 6 |
+
import sys
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
| 10 |
+
|
| 11 |
+
from .metrics import depth_bucket, quantile, safe_float
|
| 12 |
+
from .schema import runtime_metadata, write_json
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
DEFAULT_METRICS = [
|
| 16 |
+
"selected_abs_logprob_diff",
|
| 17 |
+
"selected_abs_raw_logit_diff",
|
| 18 |
+
"selected_abs_rank_delta",
|
| 19 |
+
"union_js_divergence",
|
| 20 |
+
"union_max_abs_logprob_diff",
|
| 21 |
+
"probe_max_abs_logprob_diff",
|
| 22 |
+
"probe_rms_logprob_diff",
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def read_csv(path: Path) -> List[dict]:
|
| 27 |
+
with path.open("r", encoding="utf-8", newline="") as handle:
|
| 28 |
+
return list(csv.DictReader(handle))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def write_csv(path: Path, rows: Sequence[dict], fields: Sequence[str]) -> None:
|
| 32 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
with path.open("w", encoding="utf-8", newline="") as handle:
|
| 34 |
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
| 35 |
+
writer.writeheader()
|
| 36 |
+
for row in rows:
|
| 37 |
+
writer.writerow({field: row.get(field, "") for field in fields})
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def comparison_path(path: Path) -> Path:
|
| 41 |
+
if path.is_dir():
|
| 42 |
+
return path / "depth_metrics.csv"
|
| 43 |
+
return path
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def parse_metrics(raw: str) -> List[str]:
|
| 47 |
+
if not raw:
|
| 48 |
+
return DEFAULT_METRICS
|
| 49 |
+
return [item.strip() for item in raw.split(",") if item.strip()]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def finite_pairs(xs: Sequence[float], ys: Sequence[float]) -> Tuple[List[float], List[float]]:
|
| 53 |
+
clean_xs: List[float] = []
|
| 54 |
+
clean_ys: List[float] = []
|
| 55 |
+
for x, y in zip(xs, ys):
|
| 56 |
+
if math.isfinite(x) and math.isfinite(y):
|
| 57 |
+
clean_xs.append(x)
|
| 58 |
+
clean_ys.append(y)
|
| 59 |
+
return clean_xs, clean_ys
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def linear_regression(xs: Sequence[float], ys: Sequence[float]) -> dict:
|
| 63 |
+
xs, ys = finite_pairs(xs, ys)
|
| 64 |
+
n = len(xs)
|
| 65 |
+
if n < 2:
|
| 66 |
+
return {
|
| 67 |
+
"count": n,
|
| 68 |
+
"slope": float("nan"),
|
| 69 |
+
"intercept": float("nan"),
|
| 70 |
+
"pearson_r": float("nan"),
|
| 71 |
+
"r_squared": float("nan"),
|
| 72 |
+
}
|
| 73 |
+
mean_x = sum(xs) / n
|
| 74 |
+
mean_y = sum(ys) / n
|
| 75 |
+
sxx = sum((x - mean_x) ** 2 for x in xs)
|
| 76 |
+
syy = sum((y - mean_y) ** 2 for y in ys)
|
| 77 |
+
sxy = sum((x - mean_x) * (y - mean_y) for x, y in zip(xs, ys))
|
| 78 |
+
if sxx == 0.0:
|
| 79 |
+
slope = float("nan")
|
| 80 |
+
intercept = float("nan")
|
| 81 |
+
else:
|
| 82 |
+
slope = sxy / sxx
|
| 83 |
+
intercept = mean_y - slope * mean_x
|
| 84 |
+
if sxx == 0.0 or syy == 0.0:
|
| 85 |
+
pearson = float("nan")
|
| 86 |
+
else:
|
| 87 |
+
pearson = sxy / math.sqrt(sxx * syy)
|
| 88 |
+
return {
|
| 89 |
+
"count": n,
|
| 90 |
+
"slope": slope,
|
| 91 |
+
"intercept": intercept,
|
| 92 |
+
"pearson_r": pearson,
|
| 93 |
+
"r_squared": pearson * pearson if math.isfinite(pearson) else float("nan"),
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def add_relative_depth(rows: Sequence[dict]) -> List[dict]:
|
| 98 |
+
by_sample: Dict[str, List[dict]] = defaultdict(list)
|
| 99 |
+
for row in rows:
|
| 100 |
+
by_sample[str(row.get("sample_id"))].append(dict(row))
|
| 101 |
+
out: List[dict] = []
|
| 102 |
+
for sample_rows in by_sample.values():
|
| 103 |
+
max_depth = max((int(row.get("depth", 0)) for row in sample_rows), default=0)
|
| 104 |
+
denom = max(max_depth, 1)
|
| 105 |
+
for row in sample_rows:
|
| 106 |
+
row["relative_depth"] = int(row.get("depth", 0)) / denom
|
| 107 |
+
out.append(row)
|
| 108 |
+
return out
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def bucket_summary(rows: Sequence[dict], metrics: Sequence[str]) -> List[dict]:
|
| 112 |
+
grouped: Dict[str, List[dict]] = defaultdict(list)
|
| 113 |
+
for row in rows:
|
| 114 |
+
grouped[str(row.get("depth_bucket") or depth_bucket(int(row.get("depth", 0))))].append(row)
|
| 115 |
+
|
| 116 |
+
out = []
|
| 117 |
+
for bucket, bucket_rows in sorted(grouped.items()):
|
| 118 |
+
summary = {
|
| 119 |
+
"depth_bucket": bucket,
|
| 120 |
+
"count": len(bucket_rows),
|
| 121 |
+
"top1_mismatch_rate": (
|
| 122 |
+
sum(1 for row in bucket_rows if str(row.get("top1_equal")) != "True")
|
| 123 |
+
/ len(bucket_rows)
|
| 124 |
+
if bucket_rows else float("nan")
|
| 125 |
+
),
|
| 126 |
+
}
|
| 127 |
+
for metric in metrics:
|
| 128 |
+
values = [safe_float(row.get(metric)) for row in bucket_rows]
|
| 129 |
+
finite = [value for value in values if math.isfinite(value)]
|
| 130 |
+
summary[f"{metric}_mean"] = sum(finite) / len(finite) if finite else float("nan")
|
| 131 |
+
summary[f"{metric}_p50"] = quantile(finite, 0.50)
|
| 132 |
+
summary[f"{metric}_p95"] = quantile(finite, 0.95)
|
| 133 |
+
summary[f"{metric}_p99"] = quantile(finite, 0.99)
|
| 134 |
+
summary[f"{metric}_max"] = max(finite, default=float("nan"))
|
| 135 |
+
out.append(summary)
|
| 136 |
+
return out
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def trend_summary(rows: Sequence[dict], metrics: Sequence[str]) -> List[dict]:
|
| 140 |
+
out = []
|
| 141 |
+
depth_values = [float(int(row.get("depth", 0))) for row in rows]
|
| 142 |
+
relative_depth_values = [safe_float(row.get("relative_depth")) for row in rows]
|
| 143 |
+
for metric in metrics:
|
| 144 |
+
metric_values = [safe_float(row.get(metric)) for row in rows]
|
| 145 |
+
by_depth = linear_regression(depth_values, metric_values)
|
| 146 |
+
by_relative = linear_regression(relative_depth_values, metric_values)
|
| 147 |
+
out.append({
|
| 148 |
+
"metric": metric,
|
| 149 |
+
"count": by_depth["count"],
|
| 150 |
+
"slope_per_token": by_depth["slope"],
|
| 151 |
+
"slope_per_100_tokens": (
|
| 152 |
+
by_depth["slope"] * 100.0
|
| 153 |
+
if math.isfinite(by_depth["slope"]) else float("nan")
|
| 154 |
+
),
|
| 155 |
+
"pearson_r_depth": by_depth["pearson_r"],
|
| 156 |
+
"r_squared_depth": by_depth["r_squared"],
|
| 157 |
+
"slope_per_relative_output": by_relative["slope"],
|
| 158 |
+
"pearson_r_relative_depth": by_relative["pearson_r"],
|
| 159 |
+
"r_squared_relative_depth": by_relative["r_squared"],
|
| 160 |
+
})
|
| 161 |
+
return out
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def cumulative_by_sample(rows: Sequence[dict]) -> List[dict]:
|
| 165 |
+
grouped: Dict[str, List[dict]] = defaultdict(list)
|
| 166 |
+
for row in rows:
|
| 167 |
+
grouped[str(row.get("sample_id"))].append(row)
|
| 168 |
+
out = []
|
| 169 |
+
for sample_id, sample_rows in grouped.items():
|
| 170 |
+
sample_rows = sorted(sample_rows, key=lambda row: int(row.get("depth", 0)))
|
| 171 |
+
cumulative_abs_lp = 0.0
|
| 172 |
+
cumulative_signed_nll_delta = 0.0
|
| 173 |
+
max_abs_lp = 0.0
|
| 174 |
+
max_abs_raw = 0.0
|
| 175 |
+
for row in sample_rows:
|
| 176 |
+
depth = int(row.get("depth", 0))
|
| 177 |
+
lp_diff = safe_float(row.get("selected_logprob_diff_right_minus_left"), 0.0)
|
| 178 |
+
abs_lp = safe_float(row.get("selected_abs_logprob_diff"), 0.0)
|
| 179 |
+
abs_raw = safe_float(row.get("selected_abs_raw_logit_diff"), 0.0)
|
| 180 |
+
cumulative_abs_lp += abs_lp
|
| 181 |
+
# NLL = -logprob, so right-left NLL delta is -logprob_diff.
|
| 182 |
+
cumulative_signed_nll_delta += -lp_diff
|
| 183 |
+
max_abs_lp = max(max_abs_lp, abs_lp)
|
| 184 |
+
max_abs_raw = max(max_abs_raw, abs_raw)
|
| 185 |
+
out.append({
|
| 186 |
+
"sample_id": sample_id,
|
| 187 |
+
"depth": depth,
|
| 188 |
+
"depth_bucket": row.get("depth_bucket"),
|
| 189 |
+
"relative_depth": row.get("relative_depth"),
|
| 190 |
+
"cumulative_abs_selected_logprob_diff": cumulative_abs_lp,
|
| 191 |
+
"cumulative_nll_delta_right_minus_left": cumulative_signed_nll_delta,
|
| 192 |
+
"cumulative_abs_nll_delta": abs(cumulative_signed_nll_delta),
|
| 193 |
+
"max_selected_abs_logprob_diff_so_far": max_abs_lp,
|
| 194 |
+
"max_selected_abs_raw_logit_diff_so_far": max_abs_raw,
|
| 195 |
+
})
|
| 196 |
+
return out
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def write_markdown(path: Path,
|
| 200 |
+
comparison: str,
|
| 201 |
+
bucket_rows: Sequence[dict],
|
| 202 |
+
trend_rows: Sequence[dict]) -> None:
|
| 203 |
+
lines = [
|
| 204 |
+
"# depth effect analysis",
|
| 205 |
+
"",
|
| 206 |
+
f"- source: `{comparison}`",
|
| 207 |
+
"",
|
| 208 |
+
"## trend",
|
| 209 |
+
"",
|
| 210 |
+
"| metric | slope / 100 tokens | pearson_r | r2 | relative slope | relative_r |",
|
| 211 |
+
"|---|---:|---:|---:|---:|---:|",
|
| 212 |
+
]
|
| 213 |
+
for row in trend_rows:
|
| 214 |
+
lines.append(
|
| 215 |
+
"| {metric} | {slope:.8g} | {r:.8g} | {r2:.8g} | {rel_slope:.8g} | {rel_r:.8g} |".format(
|
| 216 |
+
metric=row.get("metric"),
|
| 217 |
+
slope=safe_float(row.get("slope_per_100_tokens")),
|
| 218 |
+
r=safe_float(row.get("pearson_r_depth")),
|
| 219 |
+
r2=safe_float(row.get("r_squared_depth")),
|
| 220 |
+
rel_slope=safe_float(row.get("slope_per_relative_output")),
|
| 221 |
+
rel_r=safe_float(row.get("pearson_r_relative_depth")),
|
| 222 |
+
)
|
| 223 |
+
)
|
| 224 |
+
lines.extend([
|
| 225 |
+
"",
|
| 226 |
+
"## depth buckets",
|
| 227 |
+
"",
|
| 228 |
+
"| bucket | count | top1 mismatch rate | selected lp p95 | selected raw p95 | union JS p95 | top-k union lp p95 |",
|
| 229 |
+
"|---|---:|---:|---:|---:|---:|---:|",
|
| 230 |
+
])
|
| 231 |
+
for row in bucket_rows:
|
| 232 |
+
lines.append(
|
| 233 |
+
"| {bucket} | {count} | {flip:.8g} | {lp:.8g} | {raw:.8g} | {js:.8g} | {union_lp:.8g} |".format(
|
| 234 |
+
bucket=row.get("depth_bucket"),
|
| 235 |
+
count=row.get("count"),
|
| 236 |
+
flip=safe_float(row.get("top1_mismatch_rate")),
|
| 237 |
+
lp=safe_float(row.get("selected_abs_logprob_diff_p95")),
|
| 238 |
+
raw=safe_float(row.get("selected_abs_raw_logit_diff_p95")),
|
| 239 |
+
js=safe_float(row.get("union_js_divergence_p95")),
|
| 240 |
+
union_lp=safe_float(row.get("union_max_abs_logprob_diff_p95")),
|
| 241 |
+
)
|
| 242 |
+
)
|
| 243 |
+
lines.append("")
|
| 244 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 248 |
+
parser = argparse.ArgumentParser(
|
| 249 |
+
description="Analyze whether same-context drift grows with output token depth."
|
| 250 |
+
)
|
| 251 |
+
parser.add_argument("--comparison", required=True,
|
| 252 |
+
help="Comparison dir or depth_metrics.csv from compare-traces.")
|
| 253 |
+
parser.add_argument("--output-dir", default="results/depth_effect")
|
| 254 |
+
parser.add_argument("--metrics", default=",".join(DEFAULT_METRICS),
|
| 255 |
+
help="Comma-separated metrics to analyze.")
|
| 256 |
+
args = parser.parse_args(argv)
|
| 257 |
+
|
| 258 |
+
comparison = comparison_path(Path(args.comparison))
|
| 259 |
+
rows = add_relative_depth(read_csv(comparison))
|
| 260 |
+
metrics = parse_metrics(args.metrics)
|
| 261 |
+
|
| 262 |
+
output_dir = Path(args.output_dir)
|
| 263 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 264 |
+
|
| 265 |
+
bucket_rows = bucket_summary(rows, metrics)
|
| 266 |
+
trend_rows = trend_summary(rows, metrics)
|
| 267 |
+
cumulative_rows = cumulative_by_sample(rows)
|
| 268 |
+
|
| 269 |
+
bucket_fields = sorted({field for row in bucket_rows for field in row})
|
| 270 |
+
trend_fields = [
|
| 271 |
+
"metric",
|
| 272 |
+
"count",
|
| 273 |
+
"slope_per_token",
|
| 274 |
+
"slope_per_100_tokens",
|
| 275 |
+
"pearson_r_depth",
|
| 276 |
+
"r_squared_depth",
|
| 277 |
+
"slope_per_relative_output",
|
| 278 |
+
"pearson_r_relative_depth",
|
| 279 |
+
"r_squared_relative_depth",
|
| 280 |
+
]
|
| 281 |
+
cumulative_fields = [
|
| 282 |
+
"sample_id",
|
| 283 |
+
"depth",
|
| 284 |
+
"depth_bucket",
|
| 285 |
+
"relative_depth",
|
| 286 |
+
"cumulative_abs_selected_logprob_diff",
|
| 287 |
+
"cumulative_nll_delta_right_minus_left",
|
| 288 |
+
"cumulative_abs_nll_delta",
|
| 289 |
+
"max_selected_abs_logprob_diff_so_far",
|
| 290 |
+
"max_selected_abs_raw_logit_diff_so_far",
|
| 291 |
+
]
|
| 292 |
+
write_csv(output_dir / "depth_bucket_summary.csv", bucket_rows, bucket_fields)
|
| 293 |
+
write_csv(output_dir / "depth_trends.csv", trend_rows, trend_fields)
|
| 294 |
+
write_csv(output_dir / "cumulative_by_sample.csv", cumulative_rows, cumulative_fields)
|
| 295 |
+
write_markdown(output_dir / "summary.md", str(args.comparison), bucket_rows, trend_rows)
|
| 296 |
+
write_json(output_dir / "metadata.json", {
|
| 297 |
+
"metadata": runtime_metadata(sys.argv),
|
| 298 |
+
"args": vars(args),
|
| 299 |
+
"row_count": len(rows),
|
| 300 |
+
"metrics": metrics,
|
| 301 |
+
})
|
| 302 |
+
|
| 303 |
+
print(f"Wrote {output_dir / 'depth_bucket_summary.csv'}")
|
| 304 |
+
print(f"Wrote {output_dir / 'depth_trends.csv'}")
|
| 305 |
+
print(f"Wrote {output_dir / 'cumulative_by_sample.csv'}")
|
| 306 |
+
print(f"Wrote {output_dir / 'summary.md'}")
|
| 307 |
+
return 0
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
if __name__ == "__main__":
|
| 311 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/src/worker_logits_verify/calibrate_profile.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import sys
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
| 11 |
+
|
| 12 |
+
from .metrics import quantile, safe_float
|
| 13 |
+
from .schema import read_json, runtime_metadata, write_json
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
PROFILE_METRICS = [
|
| 17 |
+
"selected_abs_logprob_diff",
|
| 18 |
+
"selected_abs_raw_logit_diff",
|
| 19 |
+
"selected_abs_rank_delta",
|
| 20 |
+
"union_js_divergence",
|
| 21 |
+
"union_max_abs_logprob_diff",
|
| 22 |
+
"probe_max_abs_logprob_diff",
|
| 23 |
+
"probe_rms_logprob_diff",
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
LOWER_BOUND_METRICS = [
|
| 28 |
+
"topk_jaccard",
|
| 29 |
+
"common_prob_cosine",
|
| 30 |
+
"union_prob_cosine",
|
| 31 |
+
"probe_logprob_cosine",
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def read_csv(path: Path) -> List[dict]:
|
| 36 |
+
with path.open("r", encoding="utf-8", newline="") as handle:
|
| 37 |
+
return list(csv.DictReader(handle))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def write_csv(path: Path, rows: Sequence[dict], fields: Sequence[str]) -> None:
|
| 41 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 42 |
+
with path.open("w", encoding="utf-8", newline="") as handle:
|
| 43 |
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
| 44 |
+
writer.writeheader()
|
| 45 |
+
for row in rows:
|
| 46 |
+
writer.writerow({field: row.get(field, "") for field in fields})
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def group_key(row: dict, group_by_margin: bool) -> Tuple[str, str]:
|
| 50 |
+
depth_bucket = str(row.get("depth_bucket", "unknown"))
|
| 51 |
+
margin_bucket = str(row.get("margin_bucket", "all")) if group_by_margin else "all"
|
| 52 |
+
return depth_bucket, margin_bucket
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def summarize_group(rows: Sequence[dict],
|
| 56 |
+
depth_bucket: str,
|
| 57 |
+
margin_bucket: str,
|
| 58 |
+
quantiles: Sequence[float]) -> dict:
|
| 59 |
+
out = {
|
| 60 |
+
"depth_bucket": depth_bucket,
|
| 61 |
+
"margin_bucket": margin_bucket,
|
| 62 |
+
"count": len(rows),
|
| 63 |
+
"top1_mismatch_rate": (
|
| 64 |
+
sum(1 for row in rows if str(row.get("top1_equal")) != "True") / len(rows)
|
| 65 |
+
if rows else float("nan")
|
| 66 |
+
),
|
| 67 |
+
}
|
| 68 |
+
for metric in PROFILE_METRICS:
|
| 69 |
+
values = [safe_float(row.get(metric)) for row in rows]
|
| 70 |
+
out[f"{metric}_max"] = max(
|
| 71 |
+
(value for value in values if math.isfinite(value)),
|
| 72 |
+
default=float("nan"),
|
| 73 |
+
)
|
| 74 |
+
for q in quantiles:
|
| 75 |
+
out[f"{metric}_p{int(q * 1000):03d}"] = quantile(values, q)
|
| 76 |
+
for metric in LOWER_BOUND_METRICS:
|
| 77 |
+
values = [safe_float(row.get(metric)) for row in rows]
|
| 78 |
+
out[f"{metric}_min"] = min(
|
| 79 |
+
(value for value in values if math.isfinite(value)),
|
| 80 |
+
default=float("nan"),
|
| 81 |
+
)
|
| 82 |
+
for q in quantiles:
|
| 83 |
+
# Lower tail is the risky side for similarity metrics.
|
| 84 |
+
out[f"{metric}_p{int((1.0 - q) * 1000):03d}_lower"] = quantile(values, 1.0 - q)
|
| 85 |
+
return out
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def load_profile_rows(path: Path) -> List[dict]:
|
| 89 |
+
if path.is_dir():
|
| 90 |
+
path = path / "depth_metrics.csv"
|
| 91 |
+
return read_csv(path)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 95 |
+
parser = argparse.ArgumentParser(
|
| 96 |
+
description="Calibrate an accepted drift envelope from a same-weight cross-GPU comparison."
|
| 97 |
+
)
|
| 98 |
+
parser.add_argument("--comparison", required=True,
|
| 99 |
+
help="Comparison directory or depth_metrics.csv from compare-traces.")
|
| 100 |
+
parser.add_argument("--output-dir", default="results/profile")
|
| 101 |
+
parser.add_argument("--profile-id", default="qwen3-32b-bf16-h100-vs-6000")
|
| 102 |
+
parser.add_argument("--variant-pair", default="")
|
| 103 |
+
parser.add_argument("--quantiles", default="0.95,0.99,0.999")
|
| 104 |
+
parser.add_argument("--group-by-margin", action=argparse.BooleanOptionalAction,
|
| 105 |
+
default=True)
|
| 106 |
+
parser.add_argument("--safety-multiplier", type=float, default=1.25,
|
| 107 |
+
help="Multiplier applied to upper-bound metrics in thresholds.")
|
| 108 |
+
args = parser.parse_args(argv)
|
| 109 |
+
|
| 110 |
+
rows = load_profile_rows(Path(args.comparison))
|
| 111 |
+
quantiles = [
|
| 112 |
+
float(item.strip())
|
| 113 |
+
for item in args.quantiles.split(",")
|
| 114 |
+
if item.strip()
|
| 115 |
+
]
|
| 116 |
+
grouped: Dict[Tuple[str, str], List[dict]] = defaultdict(list)
|
| 117 |
+
for row in rows:
|
| 118 |
+
grouped[group_key(row, args.group_by_margin)].append(row)
|
| 119 |
+
|
| 120 |
+
summary_rows = [
|
| 121 |
+
summarize_group(group_rows, depth_bucket, margin_bucket, quantiles)
|
| 122 |
+
for (depth_bucket, margin_bucket), group_rows in sorted(grouped.items())
|
| 123 |
+
]
|
| 124 |
+
|
| 125 |
+
output_dir = Path(args.output_dir)
|
| 126 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 127 |
+
fields = sorted({field for row in summary_rows for field in row})
|
| 128 |
+
write_csv(output_dir / "profile_summary.csv", summary_rows, fields)
|
| 129 |
+
|
| 130 |
+
threshold_quantile = max(quantiles) if quantiles else 0.99
|
| 131 |
+
threshold_key = f"p{int(threshold_quantile * 1000):03d}"
|
| 132 |
+
thresholds = {}
|
| 133 |
+
for row in summary_rows:
|
| 134 |
+
bucket_key = f"{row['depth_bucket']}|{row['margin_bucket']}"
|
| 135 |
+
thresholds[bucket_key] = {}
|
| 136 |
+
for metric in PROFILE_METRICS:
|
| 137 |
+
value = safe_float(row.get(f"{metric}_{threshold_key}"))
|
| 138 |
+
thresholds[bucket_key][metric] = (
|
| 139 |
+
value * args.safety_multiplier
|
| 140 |
+
if math.isfinite(value) else value
|
| 141 |
+
)
|
| 142 |
+
for metric in LOWER_BOUND_METRICS:
|
| 143 |
+
# Similarity metrics are lower-bound checks. Use the observed minimum
|
| 144 |
+
# for the accepted envelope so the calibration pair can replay through
|
| 145 |
+
# its own profile. The quantile columns are still emitted for analysis.
|
| 146 |
+
value = safe_float(row.get(f"{metric}_min"))
|
| 147 |
+
thresholds[bucket_key][metric] = value
|
| 148 |
+
thresholds[bucket_key]["max_top1_mismatch_rate"] = safe_float(
|
| 149 |
+
row.get("top1_mismatch_rate")
|
| 150 |
+
)
|
| 151 |
+
thresholds[bucket_key]["calibration_count"] = row.get("count")
|
| 152 |
+
|
| 153 |
+
write_json(output_dir / "profile.json", {
|
| 154 |
+
"metadata": runtime_metadata(sys.argv),
|
| 155 |
+
"profile_id": args.profile_id,
|
| 156 |
+
"variant_pair": args.variant_pair,
|
| 157 |
+
"source_comparison": args.comparison,
|
| 158 |
+
"quantiles": quantiles,
|
| 159 |
+
"threshold_quantile": threshold_quantile,
|
| 160 |
+
"safety_multiplier": args.safety_multiplier,
|
| 161 |
+
"group_by_margin": args.group_by_margin,
|
| 162 |
+
"metrics": {
|
| 163 |
+
"upper_bound": PROFILE_METRICS,
|
| 164 |
+
"lower_bound": LOWER_BOUND_METRICS,
|
| 165 |
+
},
|
| 166 |
+
"thresholds": thresholds,
|
| 167 |
+
})
|
| 168 |
+
print(f"Wrote {output_dir / 'profile_summary.csv'}")
|
| 169 |
+
print(f"Wrote {output_dir / 'profile.json'}")
|
| 170 |
+
return 0
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/src/worker_logits_verify/collect_trace.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
| 10 |
+
|
| 11 |
+
from .schema import (
|
| 12 |
+
DepthTrace,
|
| 13 |
+
Tokenization,
|
| 14 |
+
TopLogprob,
|
| 15 |
+
VariantInfo,
|
| 16 |
+
dataclass_to_dict,
|
| 17 |
+
depth_trace_to_dict,
|
| 18 |
+
parse_worker_sample,
|
| 19 |
+
read_jsonl,
|
| 20 |
+
runtime_metadata,
|
| 21 |
+
write_json,
|
| 22 |
+
write_jsonl,
|
| 23 |
+
)
|
| 24 |
+
from .tokenizer_utils import (
|
| 25 |
+
decode_token,
|
| 26 |
+
encode_text,
|
| 27 |
+
parse_probe_token_ids,
|
| 28 |
+
probe_ids_from_texts,
|
| 29 |
+
tokenizer_hash,
|
| 30 |
+
tokenizer_name,
|
| 31 |
+
unique_ints,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
DEFAULT_PROBE_TEXTS = [
|
| 36 |
+
" yes",
|
| 37 |
+
" no",
|
| 38 |
+
" true",
|
| 39 |
+
" false",
|
| 40 |
+
" accept",
|
| 41 |
+
" reject",
|
| 42 |
+
" valid",
|
| 43 |
+
" invalid",
|
| 44 |
+
"0",
|
| 45 |
+
"1",
|
| 46 |
+
".",
|
| 47 |
+
",",
|
| 48 |
+
":",
|
| 49 |
+
"{",
|
| 50 |
+
"}",
|
| 51 |
+
"\n",
|
| 52 |
+
" the",
|
| 53 |
+
" and",
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def parse_torch_dtype(torch: object, dtype: str) -> object:
|
| 58 |
+
if dtype == "auto":
|
| 59 |
+
return "auto"
|
| 60 |
+
mapping = {
|
| 61 |
+
"float16": torch.float16,
|
| 62 |
+
"fp16": torch.float16,
|
| 63 |
+
"bfloat16": torch.bfloat16,
|
| 64 |
+
"bf16": torch.bfloat16,
|
| 65 |
+
"float32": torch.float32,
|
| 66 |
+
"fp32": torch.float32,
|
| 67 |
+
}
|
| 68 |
+
if dtype not in mapping:
|
| 69 |
+
raise ValueError(f"Unsupported dtype for transformers loader: {dtype}")
|
| 70 |
+
return mapping[dtype]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def load_transformers(model_name: str,
|
| 74 |
+
dtype: str,
|
| 75 |
+
device_map: str,
|
| 76 |
+
trust_remote_code: bool,
|
| 77 |
+
attn_implementation: Optional[str]) -> tuple:
|
| 78 |
+
import torch
|
| 79 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 80 |
+
|
| 81 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 82 |
+
model_name,
|
| 83 |
+
trust_remote_code=trust_remote_code,
|
| 84 |
+
)
|
| 85 |
+
kwargs = {
|
| 86 |
+
"torch_dtype": parse_torch_dtype(torch, dtype),
|
| 87 |
+
"device_map": device_map,
|
| 88 |
+
"trust_remote_code": trust_remote_code,
|
| 89 |
+
}
|
| 90 |
+
if attn_implementation:
|
| 91 |
+
kwargs["attn_implementation"] = attn_implementation
|
| 92 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, **kwargs)
|
| 93 |
+
model.eval()
|
| 94 |
+
return tokenizer, model, torch
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def transformers_version() -> str:
|
| 98 |
+
try:
|
| 99 |
+
import transformers
|
| 100 |
+
|
| 101 |
+
return transformers.__version__
|
| 102 |
+
except Exception:
|
| 103 |
+
return ""
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def make_variant(args: argparse.Namespace,
|
| 107 |
+
tokenizer: object,
|
| 108 |
+
backend_version: str) -> VariantInfo:
|
| 109 |
+
tok_hash = tokenizer_hash(tokenizer)
|
| 110 |
+
variant_id = args.variant_id or "-".join(
|
| 111 |
+
item for item in [
|
| 112 |
+
Path(str(args.model)).name,
|
| 113 |
+
args.quantization,
|
| 114 |
+
args.gpu,
|
| 115 |
+
tok_hash,
|
| 116 |
+
] if item
|
| 117 |
+
)
|
| 118 |
+
return VariantInfo(
|
| 119 |
+
variant_id=variant_id,
|
| 120 |
+
model=args.model,
|
| 121 |
+
tokenizer_hash=tok_hash,
|
| 122 |
+
tokenizer_name=tokenizer_name(tokenizer),
|
| 123 |
+
quantization=args.quantization,
|
| 124 |
+
gpu=args.gpu,
|
| 125 |
+
backend="transformers",
|
| 126 |
+
backend_version=backend_version,
|
| 127 |
+
dtype=args.dtype,
|
| 128 |
+
extra={
|
| 129 |
+
"cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"),
|
| 130 |
+
"device_map": args.device_map,
|
| 131 |
+
"attn_implementation": args.attn_implementation,
|
| 132 |
+
},
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def tokenization_for_sample(sample: object,
|
| 137 |
+
tokenizer: object,
|
| 138 |
+
tok_hash: str,
|
| 139 |
+
allow_retokenize: bool) -> Tokenization:
|
| 140 |
+
existing = sample.tokenizations.get(tok_hash)
|
| 141 |
+
if existing is not None:
|
| 142 |
+
return existing
|
| 143 |
+
if not allow_retokenize:
|
| 144 |
+
known = ", ".join(sample.tokenizations.keys())
|
| 145 |
+
raise RuntimeError(
|
| 146 |
+
f"Sample {sample.sample_id} has no tokenization for {tok_hash}. "
|
| 147 |
+
f"Known tokenizers: {known}. Pass --allow-retokenize for cross-tokenizer models."
|
| 148 |
+
)
|
| 149 |
+
input_ids = encode_text(tokenizer, sample.input_text)
|
| 150 |
+
output_text = sample.canonical_output_text
|
| 151 |
+
if not output_text:
|
| 152 |
+
raise RuntimeError(
|
| 153 |
+
f"Sample {sample.sample_id} has no canonical_output_text to retokenize"
|
| 154 |
+
)
|
| 155 |
+
output_ids = encode_text(tokenizer, output_text)
|
| 156 |
+
return Tokenization(
|
| 157 |
+
tokenizer_hash=tok_hash,
|
| 158 |
+
tokenizer_name=tokenizer_name(tokenizer),
|
| 159 |
+
input_ids=input_ids,
|
| 160 |
+
output_ids=output_ids,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def build_probe_ids(tokenizer: object, raw_ids: str, use_default: bool) -> List[int]:
|
| 165 |
+
probe_ids: List[int] = []
|
| 166 |
+
if use_default:
|
| 167 |
+
probe_ids.extend(probe_ids_from_texts(tokenizer, DEFAULT_PROBE_TEXTS))
|
| 168 |
+
probe_ids.extend(parse_probe_token_ids(raw_ids))
|
| 169 |
+
return unique_ints(probe_ids)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def rank_for_token(torch: object, logits: object, token_id: int) -> int:
|
| 173 |
+
target_value = logits[int(token_id)]
|
| 174 |
+
# Rank is 1 + number of logits strictly greater than the target.
|
| 175 |
+
return int(torch.sum(logits > target_value).item()) + 1
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def topk_for_logits(torch: object,
|
| 179 |
+
tokenizer: object,
|
| 180 |
+
logits: object,
|
| 181 |
+
logprobs: object,
|
| 182 |
+
top_k: int) -> List[TopLogprob]:
|
| 183 |
+
values, indices = torch.topk(logprobs, k=min(top_k, int(logprobs.shape[-1])))
|
| 184 |
+
rows = []
|
| 185 |
+
for rank, (logprob, token_id) in enumerate(
|
| 186 |
+
zip(values.detach().cpu().tolist(), indices.detach().cpu().tolist()),
|
| 187 |
+
start=1,
|
| 188 |
+
):
|
| 189 |
+
token_id = int(token_id)
|
| 190 |
+
rows.append(TopLogprob(
|
| 191 |
+
token_id=token_id,
|
| 192 |
+
logprob=float(logprob),
|
| 193 |
+
raw_logit=float(logits[token_id].detach().cpu().item()),
|
| 194 |
+
rank=rank,
|
| 195 |
+
decoded_token=decode_token(tokenizer, token_id),
|
| 196 |
+
))
|
| 197 |
+
return rows
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def top_k_mass(rows: Sequence[TopLogprob]) -> float:
|
| 201 |
+
return sum(math.exp(row.logprob) for row in rows if math.isfinite(row.logprob))
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def trace_sample(tokenizer: object,
|
| 205 |
+
model: object,
|
| 206 |
+
torch: object,
|
| 207 |
+
sample_id: str,
|
| 208 |
+
variant: VariantInfo,
|
| 209 |
+
input_ids: Sequence[int],
|
| 210 |
+
output_ids: Sequence[int],
|
| 211 |
+
top_k: int,
|
| 212 |
+
probe_ids: Sequence[int],
|
| 213 |
+
stride: int,
|
| 214 |
+
max_depth: int,
|
| 215 |
+
include_raw_logits: bool) -> List[DepthTrace]:
|
| 216 |
+
if not output_ids:
|
| 217 |
+
return []
|
| 218 |
+
device = next(model.parameters()).device
|
| 219 |
+
rows: List[DepthTrace] = []
|
| 220 |
+
|
| 221 |
+
input_tensor = torch.tensor([list(input_ids)], dtype=torch.long, device=device)
|
| 222 |
+
with torch.inference_mode():
|
| 223 |
+
prefill = model(input_ids=input_tensor, use_cache=True)
|
| 224 |
+
logits = prefill.logits[0, -1, :].detach().float()
|
| 225 |
+
past_key_values = prefill.past_key_values
|
| 226 |
+
|
| 227 |
+
limit = len(output_ids)
|
| 228 |
+
if max_depth > 0:
|
| 229 |
+
limit = min(limit, max_depth)
|
| 230 |
+
|
| 231 |
+
for depth in range(limit):
|
| 232 |
+
target_token_id = int(output_ids[depth])
|
| 233 |
+
if stride > 1 and depth % stride != 0 and depth != limit - 1:
|
| 234 |
+
next_input = torch.tensor([[target_token_id]], dtype=torch.long, device=device)
|
| 235 |
+
with torch.inference_mode():
|
| 236 |
+
step = model(
|
| 237 |
+
input_ids=next_input,
|
| 238 |
+
past_key_values=past_key_values,
|
| 239 |
+
use_cache=True,
|
| 240 |
+
)
|
| 241 |
+
logits = step.logits[0, -1, :].detach().float()
|
| 242 |
+
past_key_values = step.past_key_values
|
| 243 |
+
continue
|
| 244 |
+
|
| 245 |
+
logprobs = torch.nn.functional.log_softmax(logits, dim=-1)
|
| 246 |
+
top_rows = topk_for_logits(torch, tokenizer, logits, logprobs, top_k)
|
| 247 |
+
selected_rank = rank_for_token(torch, logits, target_token_id)
|
| 248 |
+
selected_logprob = float(logprobs[target_token_id].detach().cpu().item())
|
| 249 |
+
selected_raw_logit = float(logits[target_token_id].detach().cpu().item())
|
| 250 |
+
|
| 251 |
+
top1 = top_rows[0] if top_rows else None
|
| 252 |
+
top2 = top_rows[1] if len(top_rows) > 1 else None
|
| 253 |
+
margin = None
|
| 254 |
+
if top1 is not None and top2 is not None:
|
| 255 |
+
margin = float(top1.logprob - top2.logprob)
|
| 256 |
+
|
| 257 |
+
probe_logprobs: Dict[str, float] = {}
|
| 258 |
+
probe_raw_logits: Dict[str, float] = {}
|
| 259 |
+
for probe_id in probe_ids:
|
| 260 |
+
if 0 <= int(probe_id) < int(logprobs.shape[-1]):
|
| 261 |
+
key = str(int(probe_id))
|
| 262 |
+
probe_logprobs[key] = float(logprobs[int(probe_id)].detach().cpu().item())
|
| 263 |
+
if include_raw_logits:
|
| 264 |
+
probe_raw_logits[key] = float(logits[int(probe_id)].detach().cpu().item())
|
| 265 |
+
|
| 266 |
+
rows.append(DepthTrace(
|
| 267 |
+
sample_id=sample_id,
|
| 268 |
+
variant_id=variant.variant_id,
|
| 269 |
+
depth=depth,
|
| 270 |
+
input_token_count=len(input_ids),
|
| 271 |
+
output_token_count=len(output_ids),
|
| 272 |
+
target_token_id=target_token_id,
|
| 273 |
+
target_decoded_token=decode_token(tokenizer, target_token_id),
|
| 274 |
+
selected_logprob=selected_logprob,
|
| 275 |
+
selected_raw_logit=selected_raw_logit if include_raw_logits else float("nan"),
|
| 276 |
+
selected_rank=selected_rank,
|
| 277 |
+
top1_token_id=top1.token_id if top1 else -1,
|
| 278 |
+
top1_logprob=top1.logprob if top1 else float("nan"),
|
| 279 |
+
top1_raw_logit=top1.raw_logit if top1 and include_raw_logits else float("nan"),
|
| 280 |
+
top2_token_id=top2.token_id if top2 else None,
|
| 281 |
+
top2_logprob=top2.logprob if top2 else None,
|
| 282 |
+
top2_raw_logit=top2.raw_logit if top2 and include_raw_logits else None,
|
| 283 |
+
top1_top2_margin_logprob=margin,
|
| 284 |
+
top_k_mass=top_k_mass(top_rows),
|
| 285 |
+
top_logprobs=top_rows,
|
| 286 |
+
probe_logprobs=probe_logprobs,
|
| 287 |
+
probe_raw_logits=probe_raw_logits,
|
| 288 |
+
metadata={
|
| 289 |
+
"tokenizer_hash": variant.tokenizer_hash,
|
| 290 |
+
},
|
| 291 |
+
))
|
| 292 |
+
|
| 293 |
+
next_input = torch.tensor([[target_token_id]], dtype=torch.long, device=device)
|
| 294 |
+
with torch.inference_mode():
|
| 295 |
+
step = model(
|
| 296 |
+
input_ids=next_input,
|
| 297 |
+
past_key_values=past_key_values,
|
| 298 |
+
use_cache=True,
|
| 299 |
+
)
|
| 300 |
+
logits = step.logits[0, -1, :].detach().float()
|
| 301 |
+
past_key_values = step.past_key_values
|
| 302 |
+
|
| 303 |
+
return rows
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 307 |
+
parser = argparse.ArgumentParser(
|
| 308 |
+
description="Collect depth-aware teacher-forced sparse logits/logprob traces."
|
| 309 |
+
)
|
| 310 |
+
parser.add_argument("--samples", default="data/anchor_samples.jsonl")
|
| 311 |
+
parser.add_argument("--output-dir", default="results/trace")
|
| 312 |
+
parser.add_argument("--model", required=True)
|
| 313 |
+
parser.add_argument("--variant-id", default="")
|
| 314 |
+
parser.add_argument("--gpu", default="")
|
| 315 |
+
parser.add_argument("--quantization", default="bf16")
|
| 316 |
+
parser.add_argument("--dtype", default="auto")
|
| 317 |
+
parser.add_argument("--device-map", default="auto")
|
| 318 |
+
parser.add_argument("--trust-remote-code", action="store_true")
|
| 319 |
+
parser.add_argument("--attn-implementation", default=None)
|
| 320 |
+
parser.add_argument("--top-k", type=int, default=64)
|
| 321 |
+
parser.add_argument("--probe-token-ids", default="")
|
| 322 |
+
parser.add_argument("--no-default-probes", action="store_true")
|
| 323 |
+
parser.add_argument("--allow-retokenize", action="store_true",
|
| 324 |
+
help="Allow text-level replay when tokenizer hash differs.")
|
| 325 |
+
parser.add_argument("--stride", type=int, default=1,
|
| 326 |
+
help="Record every Nth depth. Context is still replayed at every token.")
|
| 327 |
+
parser.add_argument("--max-depth", type=int, default=0,
|
| 328 |
+
help="Maximum output depth to replay per sample. 0 means all output tokens.")
|
| 329 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 330 |
+
parser.add_argument("--no-raw-logits", action="store_true",
|
| 331 |
+
help="Skip storing raw logits values in the trace rows.")
|
| 332 |
+
args = parser.parse_args(argv)
|
| 333 |
+
|
| 334 |
+
tokenizer, model, torch = load_transformers(
|
| 335 |
+
args.model,
|
| 336 |
+
dtype=args.dtype,
|
| 337 |
+
device_map=args.device_map,
|
| 338 |
+
trust_remote_code=args.trust_remote_code,
|
| 339 |
+
attn_implementation=args.attn_implementation,
|
| 340 |
+
)
|
| 341 |
+
variant = make_variant(args, tokenizer, transformers_version())
|
| 342 |
+
probe_ids = build_probe_ids(
|
| 343 |
+
tokenizer,
|
| 344 |
+
raw_ids=args.probe_token_ids,
|
| 345 |
+
use_default=not args.no_default_probes,
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
output_dir = Path(args.output_dir)
|
| 349 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 350 |
+
rows_path = output_dir / "trace.jsonl"
|
| 351 |
+
metadata_path = output_dir / "metadata.json"
|
| 352 |
+
|
| 353 |
+
sample_count = 0
|
| 354 |
+
trace_row_count = 0
|
| 355 |
+
with rows_path.open("w", encoding="utf-8") as handle:
|
| 356 |
+
for index, payload in enumerate(read_jsonl(Path(args.samples)), start=1):
|
| 357 |
+
if args.limit and index > args.limit:
|
| 358 |
+
break
|
| 359 |
+
sample = parse_worker_sample(payload)
|
| 360 |
+
tok = tokenization_for_sample(
|
| 361 |
+
sample,
|
| 362 |
+
tokenizer=tokenizer,
|
| 363 |
+
tok_hash=variant.tokenizer_hash,
|
| 364 |
+
allow_retokenize=args.allow_retokenize,
|
| 365 |
+
)
|
| 366 |
+
sample_rows = trace_sample(
|
| 367 |
+
tokenizer=tokenizer,
|
| 368 |
+
model=model,
|
| 369 |
+
torch=torch,
|
| 370 |
+
sample_id=sample.sample_id,
|
| 371 |
+
variant=variant,
|
| 372 |
+
input_ids=tok.input_ids,
|
| 373 |
+
output_ids=tok.output_ids,
|
| 374 |
+
top_k=args.top_k,
|
| 375 |
+
probe_ids=probe_ids,
|
| 376 |
+
stride=max(1, args.stride),
|
| 377 |
+
max_depth=args.max_depth,
|
| 378 |
+
include_raw_logits=not args.no_raw_logits,
|
| 379 |
+
)
|
| 380 |
+
for row in sample_rows:
|
| 381 |
+
handle.write(json.dumps(
|
| 382 |
+
depth_trace_to_dict(row),
|
| 383 |
+
ensure_ascii=False,
|
| 384 |
+
sort_keys=True,
|
| 385 |
+
))
|
| 386 |
+
handle.write("\n")
|
| 387 |
+
trace_row_count += 1
|
| 388 |
+
sample_count += 1
|
| 389 |
+
print(
|
| 390 |
+
f"[{index}] sample={sample.sample_id} "
|
| 391 |
+
f"input_tokens={len(tok.input_ids)} output_tokens={len(tok.output_ids)} "
|
| 392 |
+
f"trace_rows={len(sample_rows)}"
|
| 393 |
+
)
|
| 394 |
+
write_json(metadata_path, {
|
| 395 |
+
"metadata": runtime_metadata(sys.argv),
|
| 396 |
+
"args": vars(args),
|
| 397 |
+
"variant": dataclass_to_dict(variant),
|
| 398 |
+
"sample_count": sample_count,
|
| 399 |
+
"trace_row_count": trace_row_count,
|
| 400 |
+
"probe_token_ids": probe_ids,
|
| 401 |
+
})
|
| 402 |
+
print(f"Wrote {trace_row_count} trace rows to {rows_path}")
|
| 403 |
+
print(f"Wrote metadata to {metadata_path}")
|
| 404 |
+
return 0
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
if __name__ == "__main__":
|
| 408 |
+
raise S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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import time
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Dict, List, Optional, Sequence
|
| 9 |
+
|
| 10 |
+
from .schema import (
|
| 11 |
+
DecodeConfig,
|
| 12 |
+
VariantInfo,
|
| 13 |
+
dataclass_to_dict,
|
| 14 |
+
parse_worker_sample,
|
| 15 |
+
read_jsonl,
|
| 16 |
+
runtime_metadata,
|
| 17 |
+
write_json,
|
| 18 |
+
)
|
| 19 |
+
from .tokenizer_utils import decode_tokens, encode_text, tokenizer_hash, tokenizer_name
|
| 20 |
+
from .vllm_utils import (
|
| 21 |
+
build_llm_kwargs,
|
| 22 |
+
build_sampling_params,
|
| 23 |
+
logprob_for_token,
|
| 24 |
+
normalize_logprob_dict,
|
| 25 |
+
rank_for_token,
|
| 26 |
+
sorted_top_logprobs,
|
| 27 |
+
write_jsonl_row,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def log(message: str) -> None:
|
| 32 |
+
print(message, flush=True)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def vllm_version() -> str:
|
| 36 |
+
try:
|
| 37 |
+
import vllm
|
| 38 |
+
|
| 39 |
+
return vllm.__version__
|
| 40 |
+
except Exception:
|
| 41 |
+
return ""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def make_variant(args: argparse.Namespace, tokenizer: object) -> VariantInfo:
|
| 45 |
+
tok_hash = tokenizer_hash(tokenizer)
|
| 46 |
+
return VariantInfo(
|
| 47 |
+
variant_id=args.variant_id,
|
| 48 |
+
model=args.model,
|
| 49 |
+
tokenizer_hash=tok_hash,
|
| 50 |
+
tokenizer_name=tokenizer_name(tokenizer),
|
| 51 |
+
quantization=args.quantization,
|
| 52 |
+
gpu=args.gpu,
|
| 53 |
+
backend="vllm",
|
| 54 |
+
backend_version=vllm_version(),
|
| 55 |
+
dtype=args.dtype,
|
| 56 |
+
extra={
|
| 57 |
+
"cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"),
|
| 58 |
+
"tensor_parallel_size": args.tensor_parallel_size,
|
| 59 |
+
"gpu_memory_utilization": args.gpu_memory_utilization,
|
| 60 |
+
"max_model_len": args.max_model_len,
|
| 61 |
+
"max_num_seqs": args.max_num_seqs,
|
| 62 |
+
"max_num_batched_tokens": args.max_num_batched_tokens,
|
| 63 |
+
"max_logprobs": args.max_logprobs,
|
| 64 |
+
},
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def trace_from_completion(completion: object,
|
| 69 |
+
tokenizer: object,
|
| 70 |
+
output_ids: Sequence[int]) -> List[dict]:
|
| 71 |
+
logprob_steps = list(getattr(completion, "logprobs", []) or [])
|
| 72 |
+
rows = []
|
| 73 |
+
for depth, token_id in enumerate(output_ids):
|
| 74 |
+
step_logprobs = (
|
| 75 |
+
normalize_logprob_dict(logprob_steps[depth])
|
| 76 |
+
if depth < len(logprob_steps) else {}
|
| 77 |
+
)
|
| 78 |
+
selected_logprob = logprob_for_token(step_logprobs, int(token_id))
|
| 79 |
+
selected_rank = rank_for_token(step_logprobs, int(token_id))
|
| 80 |
+
rows.append({
|
| 81 |
+
"depth": depth,
|
| 82 |
+
"target_token_id": int(token_id),
|
| 83 |
+
"target_decoded_token": tokenizer.decode([int(token_id)], skip_special_tokens=False),
|
| 84 |
+
"selected_logprob": selected_logprob,
|
| 85 |
+
"selected_rank": selected_rank,
|
| 86 |
+
"top_logprobs": sorted_top_logprobs(step_logprobs),
|
| 87 |
+
})
|
| 88 |
+
return rows
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 92 |
+
parser = argparse.ArgumentParser(
|
| 93 |
+
description="Generate vLLM worker evidence: input, output, and decode-time logprob trace."
|
| 94 |
+
)
|
| 95 |
+
parser.add_argument("--input", default="data/prompts.jsonl")
|
| 96 |
+
parser.add_argument("--output", default="data/worker_evidence.jsonl")
|
| 97 |
+
parser.add_argument("--model", required=True)
|
| 98 |
+
parser.add_argument("--variant-id", required=True)
|
| 99 |
+
parser.add_argument("--gpu", default="")
|
| 100 |
+
parser.add_argument("--quantization", default="bf16")
|
| 101 |
+
parser.add_argument("--dtype", default="auto")
|
| 102 |
+
parser.add_argument("--trust-remote-code", action="store_true")
|
| 103 |
+
parser.add_argument("--tensor-parallel-size", type=int, default=1)
|
| 104 |
+
parser.add_argument("--gpu-memory-utilization", type=float, default=None)
|
| 105 |
+
parser.add_argument("--max-model-len", type=int, default=None)
|
| 106 |
+
parser.add_argument("--max-num-seqs", type=int, default=None)
|
| 107 |
+
parser.add_argument("--max-num-batched-tokens", type=int, default=None)
|
| 108 |
+
parser.add_argument("--max-logprobs", type=int, default=None)
|
| 109 |
+
parser.add_argument("--max-new-tokens", type=int, default=128)
|
| 110 |
+
parser.add_argument("--logprobs", type=int, default=64)
|
| 111 |
+
parser.add_argument("--temperature", type=float, default=0.0)
|
| 112 |
+
parser.add_argument("--top-p", type=float, default=1.0)
|
| 113 |
+
parser.add_argument("--top-k", type=int, default=0)
|
| 114 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 115 |
+
parser.add_argument("--batch-size", type=int, default=8)
|
| 116 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 117 |
+
args = parser.parse_args(argv)
|
| 118 |
+
|
| 119 |
+
from transformers import AutoTokenizer
|
| 120 |
+
from vllm import LLM
|
| 121 |
+
|
| 122 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 123 |
+
args.model,
|
| 124 |
+
trust_remote_code=args.trust_remote_code,
|
| 125 |
+
)
|
| 126 |
+
variant = make_variant(args, tokenizer)
|
| 127 |
+
llm_kwargs = build_llm_kwargs(args)
|
| 128 |
+
log(f"Loading vLLM with kwargs: {llm_kwargs}")
|
| 129 |
+
llm = LLM(**llm_kwargs)
|
| 130 |
+
sampling_params = build_sampling_params(
|
| 131 |
+
args,
|
| 132 |
+
max_tokens=args.max_new_tokens,
|
| 133 |
+
logprobs=args.logprobs,
|
| 134 |
+
prompt_logprobs=None,
|
| 135 |
+
detokenize=False,
|
| 136 |
+
)
|
| 137 |
+
config = DecodeConfig(
|
| 138 |
+
max_new_tokens=args.max_new_tokens,
|
| 139 |
+
temperature=args.temperature,
|
| 140 |
+
top_p=args.top_p,
|
| 141 |
+
top_k=args.top_k,
|
| 142 |
+
seed=args.seed,
|
| 143 |
+
do_sample=args.temperature > 0.0,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
samples = []
|
| 147 |
+
for index, payload in enumerate(read_jsonl(Path(args.input)), start=1):
|
| 148 |
+
if args.limit and index > args.limit:
|
| 149 |
+
break
|
| 150 |
+
samples.append((index, parse_worker_sample(payload)))
|
| 151 |
+
|
| 152 |
+
output_path = Path(args.output)
|
| 153 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 154 |
+
total_start = time.time()
|
| 155 |
+
count = 0
|
| 156 |
+
with output_path.open("w", encoding="utf-8") as handle:
|
| 157 |
+
for batch_start in range(0, len(samples), args.batch_size):
|
| 158 |
+
batch = samples[batch_start:batch_start + args.batch_size]
|
| 159 |
+
prompts = [sample.input_text for _, sample in batch]
|
| 160 |
+
log(f"Generating worker evidence batch {batch_start // args.batch_size + 1}, size={len(batch)}")
|
| 161 |
+
outputs = llm.generate(prompts, sampling_params)
|
| 162 |
+
if len(outputs) != len(batch):
|
| 163 |
+
raise RuntimeError(f"vLLM returned {len(outputs)} outputs for {len(batch)} prompts")
|
| 164 |
+
for (index, sample), request_output in zip(batch, outputs):
|
| 165 |
+
completion = request_output.outputs[0] if request_output.outputs else None
|
| 166 |
+
if completion is None:
|
| 167 |
+
raise RuntimeError(f"No completion for sample {sample.sample_id}")
|
| 168 |
+
input_ids = encode_text(tokenizer, sample.input_text)
|
| 169 |
+
output_ids = [int(token_id) for token_id in list(getattr(completion, "token_ids", []))]
|
| 170 |
+
row = {
|
| 171 |
+
"sample_id": sample.sample_id,
|
| 172 |
+
"input_text": sample.input_text,
|
| 173 |
+
"input_ids": input_ids,
|
| 174 |
+
"output_text": decode_tokens(tokenizer, output_ids),
|
| 175 |
+
"output_ids": output_ids,
|
| 176 |
+
"category": sample.category,
|
| 177 |
+
"target_input_tokens": sample.target_input_tokens,
|
| 178 |
+
"worker_variant": dataclass_to_dict(variant),
|
| 179 |
+
"decode_config": dataclass_to_dict(config),
|
| 180 |
+
"worker_trace_mode": "vllm_decode_generate",
|
| 181 |
+
"worker_trace": trace_from_completion(completion, tokenizer, output_ids),
|
| 182 |
+
}
|
| 183 |
+
write_jsonl_row(handle, row)
|
| 184 |
+
count += 1
|
| 185 |
+
log(
|
| 186 |
+
f"[{index}] sample={sample.sample_id} "
|
| 187 |
+
f"input_tokens={len(input_ids)} output_tokens={len(output_ids)}"
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
write_json(output_path.with_suffix(output_path.suffix + ".metadata.json"), {
|
| 191 |
+
"metadata": runtime_metadata(sys.argv),
|
| 192 |
+
"args": vars(args),
|
| 193 |
+
"worker_variant": dataclass_to_dict(variant),
|
| 194 |
+
"sample_count": count,
|
| 195 |
+
})
|
| 196 |
+
log(f"Wrote {count} worker evidence rows to {output_path} in {time.time() - total_start:.1f}s")
|
| 197 |
+
return 0
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
if __name__ == "__main__":
|
| 201 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/src/worker_log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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import sys
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, Iterable, List, Mapping, Optional, Sequence, Tuple
|
| 11 |
+
|
| 12 |
+
from .metrics import (
|
| 13 |
+
cosine,
|
| 14 |
+
depth_bucket,
|
| 15 |
+
js_divergence,
|
| 16 |
+
margin_bucket,
|
| 17 |
+
normalize_logprobs,
|
| 18 |
+
probability_metrics,
|
| 19 |
+
safe_float,
|
| 20 |
+
sorted_token_ids,
|
| 21 |
+
)
|
| 22 |
+
from .schema import read_json, read_jsonl, runtime_metadata, write_json
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
TraceKey = Tuple[str, int]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def load_trace_dir(path: Path) -> Tuple[dict, List[dict]]:
|
| 29 |
+
if path.is_dir():
|
| 30 |
+
metadata_path = path / "metadata.json"
|
| 31 |
+
trace_path = path / "trace.jsonl"
|
| 32 |
+
else:
|
| 33 |
+
metadata_path = path.with_name("metadata.json")
|
| 34 |
+
trace_path = path
|
| 35 |
+
metadata = read_json(metadata_path) if metadata_path.exists() else {}
|
| 36 |
+
rows = list(read_jsonl(trace_path))
|
| 37 |
+
return metadata, rows
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def key_row(row: dict) -> TraceKey:
|
| 41 |
+
return str(row["sample_id"]), int(row["depth"])
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def top_map(row: dict) -> Dict[str, dict]:
|
| 45 |
+
out = {}
|
| 46 |
+
for item in row.get("top_logprobs", []):
|
| 47 |
+
token_id = str(item.get("token_id"))
|
| 48 |
+
out[token_id] = item
|
| 49 |
+
return out
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def numeric_delta(right: object, left: object) -> float:
|
| 53 |
+
return safe_float(right) - safe_float(left)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def abs_delta(right: object, left: object) -> float:
|
| 57 |
+
return abs(numeric_delta(right, left))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def selected_probe_metrics(left: dict, right: dict) -> dict:
|
| 61 |
+
left_probe = left.get("probe_logprobs", {}) or {}
|
| 62 |
+
right_probe = right.get("probe_logprobs", {}) or {}
|
| 63 |
+
keys = sorted_token_ids(set(left_probe) & set(right_probe))
|
| 64 |
+
if not keys:
|
| 65 |
+
return {
|
| 66 |
+
"probe_common_count": 0,
|
| 67 |
+
"probe_logprob_cosine": float("nan"),
|
| 68 |
+
"probe_max_abs_logprob_diff": float("nan"),
|
| 69 |
+
"probe_mean_abs_logprob_diff": float("nan"),
|
| 70 |
+
"probe_rms_logprob_diff": float("nan"),
|
| 71 |
+
}
|
| 72 |
+
left_values = [safe_float(left_probe[key]) for key in keys]
|
| 73 |
+
right_values = [safe_float(right_probe[key]) for key in keys]
|
| 74 |
+
diffs = [right_value - left_value
|
| 75 |
+
for left_value, right_value in zip(left_values, right_values)]
|
| 76 |
+
abs_diffs = [abs(value) for value in diffs]
|
| 77 |
+
return {
|
| 78 |
+
"probe_common_count": len(keys),
|
| 79 |
+
"probe_logprob_cosine": cosine(left_values, right_values),
|
| 80 |
+
"probe_max_abs_logprob_diff": max(abs_diffs),
|
| 81 |
+
"probe_mean_abs_logprob_diff": sum(abs_diffs) / len(abs_diffs),
|
| 82 |
+
"probe_rms_logprob_diff": math.sqrt(sum(value * value for value in diffs) / len(diffs)),
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def topk_logprob_vector_metrics(left_top: Mapping[str, Mapping[str, object]],
|
| 87 |
+
right_top: Mapping[str, Mapping[str, object]],
|
| 88 |
+
token_ids: Sequence[str],
|
| 89 |
+
missing_logprob: float) -> dict:
|
| 90 |
+
left_values = [
|
| 91 |
+
safe_float(left_top[token_id].get("logprob"))
|
| 92 |
+
if token_id in left_top else missing_logprob
|
| 93 |
+
for token_id in token_ids
|
| 94 |
+
]
|
| 95 |
+
right_values = [
|
| 96 |
+
safe_float(right_top[token_id].get("logprob"))
|
| 97 |
+
if token_id in right_top else missing_logprob
|
| 98 |
+
for token_id in token_ids
|
| 99 |
+
]
|
| 100 |
+
diffs = [right_value - left_value
|
| 101 |
+
for left_value, right_value in zip(left_values, right_values)]
|
| 102 |
+
abs_diffs = [abs(value) for value in diffs]
|
| 103 |
+
if not diffs:
|
| 104 |
+
return {
|
| 105 |
+
"logprob_cosine": float("nan"),
|
| 106 |
+
"max_abs_logprob_diff": float("nan"),
|
| 107 |
+
"mean_abs_logprob_diff": float("nan"),
|
| 108 |
+
"rms_logprob_diff": float("nan"),
|
| 109 |
+
}
|
| 110 |
+
return {
|
| 111 |
+
"logprob_cosine": cosine(left_values, right_values),
|
| 112 |
+
"max_abs_logprob_diff": max(abs_diffs),
|
| 113 |
+
"mean_abs_logprob_diff": sum(abs_diffs) / len(abs_diffs),
|
| 114 |
+
"rms_logprob_diff": math.sqrt(sum(value * value for value in diffs) / len(diffs)),
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def compare_rows(left: dict,
|
| 119 |
+
right: dict,
|
| 120 |
+
missing_logprob: float,
|
| 121 |
+
left_label: str,
|
| 122 |
+
right_label: str) -> dict:
|
| 123 |
+
left_top = top_map(left)
|
| 124 |
+
right_top = top_map(right)
|
| 125 |
+
left_tokens = set(left_top)
|
| 126 |
+
right_tokens = set(right_top)
|
| 127 |
+
common_tokens = sorted_token_ids(left_tokens & right_tokens)
|
| 128 |
+
union_tokens = sorted_token_ids(left_tokens | right_tokens)
|
| 129 |
+
|
| 130 |
+
common_prob = probability_metrics(
|
| 131 |
+
left_top,
|
| 132 |
+
right_top,
|
| 133 |
+
common_tokens,
|
| 134 |
+
missing_logprob,
|
| 135 |
+
)
|
| 136 |
+
union_prob = probability_metrics(
|
| 137 |
+
left_top,
|
| 138 |
+
right_top,
|
| 139 |
+
union_tokens,
|
| 140 |
+
missing_logprob,
|
| 141 |
+
)
|
| 142 |
+
common_logprob = topk_logprob_vector_metrics(
|
| 143 |
+
left_top,
|
| 144 |
+
right_top,
|
| 145 |
+
common_tokens,
|
| 146 |
+
missing_logprob,
|
| 147 |
+
)
|
| 148 |
+
union_logprob = topk_logprob_vector_metrics(
|
| 149 |
+
left_top,
|
| 150 |
+
right_top,
|
| 151 |
+
union_tokens,
|
| 152 |
+
missing_logprob,
|
| 153 |
+
)
|
| 154 |
+
probe_metrics = selected_probe_metrics(left, right)
|
| 155 |
+
|
| 156 |
+
selected_lp_diff = numeric_delta(
|
| 157 |
+
right.get("selected_logprob"),
|
| 158 |
+
left.get("selected_logprob"),
|
| 159 |
+
)
|
| 160 |
+
selected_raw_logit_diff = numeric_delta(
|
| 161 |
+
right.get("selected_raw_logit"),
|
| 162 |
+
left.get("selected_raw_logit"),
|
| 163 |
+
)
|
| 164 |
+
rank_delta = int(right.get("selected_rank", 0)) - int(left.get("selected_rank", 0))
|
| 165 |
+
left_margin = safe_float(left.get("top1_top2_margin_logprob"))
|
| 166 |
+
right_margin = safe_float(right.get("top1_top2_margin_logprob"))
|
| 167 |
+
|
| 168 |
+
return {
|
| 169 |
+
"sample_id": left.get("sample_id"),
|
| 170 |
+
"depth": int(left.get("depth")),
|
| 171 |
+
"depth_bucket": depth_bucket(int(left.get("depth"))),
|
| 172 |
+
"input_token_count": left.get("input_token_count"),
|
| 173 |
+
"output_token_count": left.get("output_token_count"),
|
| 174 |
+
"target_token_id": left.get("target_token_id"),
|
| 175 |
+
"target_decoded_token": left.get("target_decoded_token"),
|
| 176 |
+
"left_variant_id": left.get("variant_id", left_label),
|
| 177 |
+
"right_variant_id": right.get("variant_id", right_label),
|
| 178 |
+
"same_target_token": left.get("target_token_id") == right.get("target_token_id"),
|
| 179 |
+
"selected_logprob_left": left.get("selected_logprob"),
|
| 180 |
+
"selected_logprob_right": right.get("selected_logprob"),
|
| 181 |
+
"selected_logprob_diff_right_minus_left": selected_lp_diff,
|
| 182 |
+
"selected_abs_logprob_diff": abs(selected_lp_diff),
|
| 183 |
+
"selected_raw_logit_left": left.get("selected_raw_logit"),
|
| 184 |
+
"selected_raw_logit_right": right.get("selected_raw_logit"),
|
| 185 |
+
"selected_raw_logit_diff_right_minus_left": selected_raw_logit_diff,
|
| 186 |
+
"selected_abs_raw_logit_diff": abs(selected_raw_logit_diff),
|
| 187 |
+
"selected_rank_left": left.get("selected_rank"),
|
| 188 |
+
"selected_rank_right": right.get("selected_rank"),
|
| 189 |
+
"selected_rank_delta_right_minus_left": rank_delta,
|
| 190 |
+
"selected_abs_rank_delta": abs(rank_delta),
|
| 191 |
+
"left_top1_token_id": left.get("top1_token_id"),
|
| 192 |
+
"right_top1_token_id": right.get("top1_token_id"),
|
| 193 |
+
"top1_equal": left.get("top1_token_id") == right.get("top1_token_id"),
|
| 194 |
+
"left_top1_logprob": left.get("top1_logprob"),
|
| 195 |
+
"right_top1_logprob": right.get("top1_logprob"),
|
| 196 |
+
"left_margin": left_margin,
|
| 197 |
+
"right_margin": right_margin,
|
| 198 |
+
"min_margin": min(left_margin, right_margin),
|
| 199 |
+
"margin_bucket": margin_bucket(min(left_margin, right_margin)),
|
| 200 |
+
"left_top_k_mass": left.get("top_k_mass"),
|
| 201 |
+
"right_top_k_mass": right.get("top_k_mass"),
|
| 202 |
+
"top_k_mass_diff_right_minus_left": numeric_delta(
|
| 203 |
+
right.get("top_k_mass"),
|
| 204 |
+
left.get("top_k_mass"),
|
| 205 |
+
),
|
| 206 |
+
"left_top_count": len(left_tokens),
|
| 207 |
+
"right_top_count": len(right_tokens),
|
| 208 |
+
"common_top_count": len(common_tokens),
|
| 209 |
+
"union_top_count": len(union_tokens),
|
| 210 |
+
"topk_jaccard": (
|
| 211 |
+
len(common_tokens) / len(union_tokens)
|
| 212 |
+
if union_tokens else float("nan")
|
| 213 |
+
),
|
| 214 |
+
"missing_from_right_count": len(left_tokens - right_tokens),
|
| 215 |
+
"extra_in_right_count": len(right_tokens - left_tokens),
|
| 216 |
+
"common_prob_cosine": common_prob["prob_cosine"],
|
| 217 |
+
"common_kl_left_to_right": common_prob["kl_left_to_right"],
|
| 218 |
+
"common_kl_right_to_left": common_prob["kl_right_to_left"],
|
| 219 |
+
"common_js_divergence": common_prob["js_divergence"],
|
| 220 |
+
"union_prob_cosine": union_prob["prob_cosine"],
|
| 221 |
+
"union_kl_left_to_right": union_prob["kl_left_to_right"],
|
| 222 |
+
"union_kl_right_to_left": union_prob["kl_right_to_left"],
|
| 223 |
+
"union_js_divergence": union_prob["js_divergence"],
|
| 224 |
+
"common_logprob_cosine": common_logprob["logprob_cosine"],
|
| 225 |
+
"common_max_abs_logprob_diff": common_logprob["max_abs_logprob_diff"],
|
| 226 |
+
"common_mean_abs_logprob_diff": common_logprob["mean_abs_logprob_diff"],
|
| 227 |
+
"common_rms_logprob_diff": common_logprob["rms_logprob_diff"],
|
| 228 |
+
"union_logprob_cosine": union_logprob["logprob_cosine"],
|
| 229 |
+
"union_max_abs_logprob_diff": union_logprob["max_abs_logprob_diff"],
|
| 230 |
+
"union_mean_abs_logprob_diff": union_logprob["mean_abs_logprob_diff"],
|
| 231 |
+
"union_rms_logprob_diff": union_logprob["rms_logprob_diff"],
|
| 232 |
+
**probe_metrics,
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def write_csv(path: Path, rows: Sequence[dict], fields: Sequence[str]) -> None:
|
| 237 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 238 |
+
with path.open("w", encoding="utf-8", newline="") as handle:
|
| 239 |
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
| 240 |
+
writer.writeheader()
|
| 241 |
+
for row in rows:
|
| 242 |
+
writer.writerow({field: row.get(field, "") for field in fields})
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def cumulative_rows(rows: Sequence[dict]) -> List[dict]:
|
| 246 |
+
by_sample: Dict[str, List[dict]] = defaultdict(list)
|
| 247 |
+
for row in rows:
|
| 248 |
+
by_sample[str(row["sample_id"])].append(row)
|
| 249 |
+
out = []
|
| 250 |
+
for sample_id, sample_rows in by_sample.items():
|
| 251 |
+
sample_rows = sorted(sample_rows, key=lambda row: int(row["depth"]))
|
| 252 |
+
cumulative_left = 0.0
|
| 253 |
+
cumulative_right = 0.0
|
| 254 |
+
max_abs_lp = 0.0
|
| 255 |
+
max_abs_raw = 0.0
|
| 256 |
+
top1_mismatches = 0
|
| 257 |
+
for row in sample_rows:
|
| 258 |
+
left_lp = safe_float(row.get("selected_logprob_left"))
|
| 259 |
+
right_lp = safe_float(row.get("selected_logprob_right"))
|
| 260 |
+
cumulative_left += -left_lp
|
| 261 |
+
cumulative_right += -right_lp
|
| 262 |
+
max_abs_lp = max(max_abs_lp, safe_float(row.get("selected_abs_logprob_diff"), 0.0))
|
| 263 |
+
max_abs_raw = max(max_abs_raw, safe_float(row.get("selected_abs_raw_logit_diff"), 0.0))
|
| 264 |
+
if not row.get("top1_equal"):
|
| 265 |
+
top1_mismatches += 1
|
| 266 |
+
out.append({
|
| 267 |
+
"sample_id": sample_id,
|
| 268 |
+
"depth": row["depth"],
|
| 269 |
+
"depth_bucket": row["depth_bucket"],
|
| 270 |
+
"cumulative_nll_left": cumulative_left,
|
| 271 |
+
"cumulative_nll_right": cumulative_right,
|
| 272 |
+
"cumulative_nll_delta_right_minus_left": cumulative_right - cumulative_left,
|
| 273 |
+
"cumulative_abs_nll_delta": abs(cumulative_right - cumulative_left),
|
| 274 |
+
"max_selected_abs_logprob_diff_so_far": max_abs_lp,
|
| 275 |
+
"max_selected_abs_raw_logit_diff_so_far": max_abs_raw,
|
| 276 |
+
"top1_mismatches_so_far": top1_mismatches,
|
| 277 |
+
})
|
| 278 |
+
return out
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def markdown_summary(rows: Sequence[dict],
|
| 282 |
+
left_label: str,
|
| 283 |
+
right_label: str) -> str:
|
| 284 |
+
if not rows:
|
| 285 |
+
return "# trace comparison\n\nNo matched rows.\n"
|
| 286 |
+
top1_mismatches = sum(1 for row in rows if not row.get("top1_equal"))
|
| 287 |
+
max_lp = max(safe_float(row.get("selected_abs_logprob_diff"), 0.0) for row in rows)
|
| 288 |
+
max_raw = max(safe_float(row.get("selected_abs_raw_logit_diff"), 0.0) for row in rows)
|
| 289 |
+
min_jaccard = min(safe_float(row.get("topk_jaccard"), 1.0) for row in rows)
|
| 290 |
+
max_union_js = max(safe_float(row.get("union_js_divergence"), 0.0) for row in rows)
|
| 291 |
+
|
| 292 |
+
sorted_rows = sorted(
|
| 293 |
+
rows,
|
| 294 |
+
key=lambda row: safe_float(row.get("selected_abs_logprob_diff"), 0.0),
|
| 295 |
+
reverse=True,
|
| 296 |
+
)
|
| 297 |
+
lines = [
|
| 298 |
+
"# trace comparison",
|
| 299 |
+
"",
|
| 300 |
+
f"- left: `{left_label}`",
|
| 301 |
+
f"- right: `{right_label}`",
|
| 302 |
+
f"- matched depth rows: {len(rows)}",
|
| 303 |
+
f"- top1 mismatches: {top1_mismatches}",
|
| 304 |
+
f"- max selected abs logprob diff: {max_lp:.8g}",
|
| 305 |
+
f"- max selected abs raw logit diff: {max_raw:.8g}",
|
| 306 |
+
f"- min top-k Jaccard: {min_jaccard:.8g}",
|
| 307 |
+
f"- max top-k observed union JS: {max_union_js:.8g}",
|
| 308 |
+
"",
|
| 309 |
+
"| sample | depth | target | abs_lp_diff | abs_raw_diff | rank_l/r | top1_equal | jaccard | union_js | margin |",
|
| 310 |
+
"|---|---:|---|---:|---:|---:|---|---:|---:|---:|",
|
| 311 |
+
]
|
| 312 |
+
for row in sorted_rows[:50]:
|
| 313 |
+
lines.append(
|
| 314 |
+
"| {sample} | {depth} | `{target}` | {lp:.8g} | {raw:.8g} | {rank_l}/{rank_r} | "
|
| 315 |
+
"{top1} | {jaccard:.8g} | {js:.8g} | {margin:.8g} |".format(
|
| 316 |
+
sample=row.get("sample_id"),
|
| 317 |
+
depth=row.get("depth"),
|
| 318 |
+
target=str(row.get("target_decoded_token", "")).replace("\n", "\\n"),
|
| 319 |
+
lp=safe_float(row.get("selected_abs_logprob_diff")),
|
| 320 |
+
raw=safe_float(row.get("selected_abs_raw_logit_diff")),
|
| 321 |
+
rank_l=row.get("selected_rank_left"),
|
| 322 |
+
rank_r=row.get("selected_rank_right"),
|
| 323 |
+
top1=row.get("top1_equal"),
|
| 324 |
+
jaccard=safe_float(row.get("topk_jaccard")),
|
| 325 |
+
js=safe_float(row.get("union_js_divergence")),
|
| 326 |
+
margin=safe_float(row.get("min_margin")),
|
| 327 |
+
)
|
| 328 |
+
)
|
| 329 |
+
lines.append("")
|
| 330 |
+
return "\n".join(lines)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 334 |
+
parser = argparse.ArgumentParser(
|
| 335 |
+
description="Compare two depth-aware trace directories on the same canonical output path."
|
| 336 |
+
)
|
| 337 |
+
parser.add_argument("--left", required=True, help="Left trace dir or trace.jsonl")
|
| 338 |
+
parser.add_argument("--right", required=True, help="Right trace dir or trace.jsonl")
|
| 339 |
+
parser.add_argument("--left-label", default="left")
|
| 340 |
+
parser.add_argument("--right-label", default="right")
|
| 341 |
+
parser.add_argument("--output-dir", default="results/compare")
|
| 342 |
+
parser.add_argument("--missing-logprob", type=float, default=-100.0)
|
| 343 |
+
args = parser.parse_args(argv)
|
| 344 |
+
|
| 345 |
+
left_meta, left_rows = load_trace_dir(Path(args.left))
|
| 346 |
+
right_meta, right_rows = load_trace_dir(Path(args.right))
|
| 347 |
+
left_by_key = {key_row(row): row for row in left_rows}
|
| 348 |
+
right_by_key = {key_row(row): row for row in right_rows}
|
| 349 |
+
keys = sorted(set(left_by_key) & set(right_by_key))
|
| 350 |
+
|
| 351 |
+
rows = [
|
| 352 |
+
compare_rows(
|
| 353 |
+
left_by_key[key],
|
| 354 |
+
right_by_key[key],
|
| 355 |
+
missing_logprob=args.missing_logprob,
|
| 356 |
+
left_label=args.left_label,
|
| 357 |
+
right_label=args.right_label,
|
| 358 |
+
)
|
| 359 |
+
for key in keys
|
| 360 |
+
]
|
| 361 |
+
|
| 362 |
+
output_dir = Path(args.output_dir)
|
| 363 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 364 |
+
fields = [
|
| 365 |
+
"sample_id",
|
| 366 |
+
"depth",
|
| 367 |
+
"depth_bucket",
|
| 368 |
+
"input_token_count",
|
| 369 |
+
"output_token_count",
|
| 370 |
+
"target_token_id",
|
| 371 |
+
"target_decoded_token",
|
| 372 |
+
"left_variant_id",
|
| 373 |
+
"right_variant_id",
|
| 374 |
+
"same_target_token",
|
| 375 |
+
"selected_logprob_left",
|
| 376 |
+
"selected_logprob_right",
|
| 377 |
+
"selected_logprob_diff_right_minus_left",
|
| 378 |
+
"selected_abs_logprob_diff",
|
| 379 |
+
"selected_raw_logit_left",
|
| 380 |
+
"selected_raw_logit_right",
|
| 381 |
+
"selected_raw_logit_diff_right_minus_left",
|
| 382 |
+
"selected_abs_raw_logit_diff",
|
| 383 |
+
"selected_rank_left",
|
| 384 |
+
"selected_rank_right",
|
| 385 |
+
"selected_rank_delta_right_minus_left",
|
| 386 |
+
"selected_abs_rank_delta",
|
| 387 |
+
"left_top1_token_id",
|
| 388 |
+
"right_top1_token_id",
|
| 389 |
+
"top1_equal",
|
| 390 |
+
"left_top1_logprob",
|
| 391 |
+
"right_top1_logprob",
|
| 392 |
+
"left_margin",
|
| 393 |
+
"right_margin",
|
| 394 |
+
"min_margin",
|
| 395 |
+
"margin_bucket",
|
| 396 |
+
"left_top_k_mass",
|
| 397 |
+
"right_top_k_mass",
|
| 398 |
+
"top_k_mass_diff_right_minus_left",
|
| 399 |
+
"left_top_count",
|
| 400 |
+
"right_top_count",
|
| 401 |
+
"common_top_count",
|
| 402 |
+
"union_top_count",
|
| 403 |
+
"topk_jaccard",
|
| 404 |
+
"missing_from_right_count",
|
| 405 |
+
"extra_in_right_count",
|
| 406 |
+
"common_prob_cosine",
|
| 407 |
+
"common_kl_left_to_right",
|
| 408 |
+
"common_kl_right_to_left",
|
| 409 |
+
"common_js_divergence",
|
| 410 |
+
"union_prob_cosine",
|
| 411 |
+
"union_kl_left_to_right",
|
| 412 |
+
"union_kl_right_to_left",
|
| 413 |
+
"union_js_divergence",
|
| 414 |
+
"common_logprob_cosine",
|
| 415 |
+
"common_max_abs_logprob_diff",
|
| 416 |
+
"common_mean_abs_logprob_diff",
|
| 417 |
+
"common_rms_logprob_diff",
|
| 418 |
+
"union_logprob_cosine",
|
| 419 |
+
"union_max_abs_logprob_diff",
|
| 420 |
+
"union_mean_abs_logprob_diff",
|
| 421 |
+
"union_rms_logprob_diff",
|
| 422 |
+
"probe_common_count",
|
| 423 |
+
"probe_logprob_cosine",
|
| 424 |
+
"probe_max_abs_logprob_diff",
|
| 425 |
+
"probe_mean_abs_logprob_diff",
|
| 426 |
+
"probe_rms_logprob_diff",
|
| 427 |
+
]
|
| 428 |
+
write_csv(output_dir / "depth_metrics.csv", rows, fields)
|
| 429 |
+
|
| 430 |
+
cumulative = cumulative_rows(rows)
|
| 431 |
+
cumulative_fields = [
|
| 432 |
+
"sample_id",
|
| 433 |
+
"depth",
|
| 434 |
+
"depth_bucket",
|
| 435 |
+
"cumulative_nll_left",
|
| 436 |
+
"cumulative_nll_right",
|
| 437 |
+
"cumulative_nll_delta_right_minus_left",
|
| 438 |
+
"cumulative_abs_nll_delta",
|
| 439 |
+
"max_selected_abs_logprob_diff_so_far",
|
| 440 |
+
"max_selected_abs_raw_logit_diff_so_far",
|
| 441 |
+
"top1_mismatches_so_far",
|
| 442 |
+
]
|
| 443 |
+
write_csv(output_dir / "cumulative_metrics.csv", cumulative, cumulative_fields)
|
| 444 |
+
|
| 445 |
+
(output_dir / "summary.md").write_text(
|
| 446 |
+
markdown_summary(rows, args.left_label, args.right_label),
|
| 447 |
+
encoding="utf-8",
|
| 448 |
+
)
|
| 449 |
+
missing_left = sorted(set(right_by_key) - set(left_by_key))
|
| 450 |
+
missing_right = sorted(set(left_by_key) - set(right_by_key))
|
| 451 |
+
write_json(output_dir / "comparison_metadata.json", {
|
| 452 |
+
"metadata": runtime_metadata(sys.argv),
|
| 453 |
+
"args": vars(args),
|
| 454 |
+
"left_metadata": left_meta,
|
| 455 |
+
"right_metadata": right_meta,
|
| 456 |
+
"matched_rows": len(keys),
|
| 457 |
+
"missing_from_left": [list(key) for key in missing_left],
|
| 458 |
+
"missing_from_right": [list(key) for key in missing_right],
|
| 459 |
+
})
|
| 460 |
+
print(f"Wrote {output_dir / 'depth_metrics.csv'}")
|
| 461 |
+
print(f"Wrote {output_dir / 'cumulative_metrics.csv'}")
|
| 462 |
+
print(f"Wrote {output_dir / 'summary.md'}")
|
| 463 |
+
print(f"Wrote {output_dir / 'comparison_metadata.json'}")
|
| 464 |
+
return 0
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
if __name__ == "__main__":
|
| 468 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/src/worker_logits_verify/dense_bf16_verifier.py
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import math
|
| 6 |
+
import sys
|
| 7 |
+
from collections import Counter, defaultdict
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Dict, List, Optional, Sequence, Tuple
|
| 10 |
+
|
| 11 |
+
from .metrics import safe_float
|
| 12 |
+
from .schema import runtime_metadata, write_json
|
| 13 |
+
from .summarize_worker_verify import summarize_rows
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
Threshold = Tuple[str, str, float, str]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
PRESETS: Dict[str, dict] = {
|
| 20 |
+
"qwen3-8b-bf16-4090-v1": {
|
| 21 |
+
"profile_id": "qwen3-8b-bf16-4090-v1",
|
| 22 |
+
"target": {
|
| 23 |
+
"model": "Qwen/Qwen3-8B",
|
| 24 |
+
"quantization": "bf16",
|
| 25 |
+
"dtype": "bfloat16",
|
| 26 |
+
"worker_gpu": "4090",
|
| 27 |
+
"verifier_trace_mode": "vllm_prompt_logprobs_full_prefill",
|
| 28 |
+
"worker_trace_mode": "vllm_decode_generate",
|
| 29 |
+
},
|
| 30 |
+
"requirements": {
|
| 31 |
+
"min_single_output_tokens": 64,
|
| 32 |
+
"min_strict_total_tokens": 512,
|
| 33 |
+
"min_strict_samples": 4,
|
| 34 |
+
"recommended_output_tokens_per_probe": 128,
|
| 35 |
+
"recommended_probe_count": 8,
|
| 36 |
+
"recommended_logprobs": 32,
|
| 37 |
+
"require_topk_for_strict": True,
|
| 38 |
+
},
|
| 39 |
+
"sample_accept_thresholds": [
|
| 40 |
+
("missing_selected_count", "==", 0.0, "selected token must be present in verifier top-k"),
|
| 41 |
+
("mean_abs_logprob_diff", "<=", 0.020, "sample mean selected-token drift"),
|
| 42 |
+
("abs_logprob_diff_p95", "<=", 0.120, "sample p95 selected-token drift"),
|
| 43 |
+
("abs_logprob_diff_p99", "<=", 0.250, "sample p99 selected-token drift"),
|
| 44 |
+
("rank_delta_nonzero_rate", "<=", 0.030, "sample selected-token rank drift rate"),
|
| 45 |
+
("topk_jaccard_mean", ">=", 0.920, "sample top-k token-set overlap"),
|
| 46 |
+
("union_js_p99", "<=", 0.020, "sample p99 top-k union JS divergence"),
|
| 47 |
+
],
|
| 48 |
+
"single_reject_thresholds": [
|
| 49 |
+
("missing_selected_count", ">", 0.0, "selected token missing from verifier top-k"),
|
| 50 |
+
("mean_abs_logprob_diff", ">", 0.030, "single-sample mean selected-token drift too high"),
|
| 51 |
+
("abs_logprob_diff_p95", ">", 0.200, "single-sample p95 selected-token drift too high"),
|
| 52 |
+
("abs_logprob_diff_p99", ">", 0.500, "single-sample p99 selected-token drift too high"),
|
| 53 |
+
("rank_delta_nonzero_rate", ">", 0.060, "single-sample selected-token rank drift too high"),
|
| 54 |
+
("topk_jaccard_mean", "<", 0.880, "single-sample top-k overlap too low"),
|
| 55 |
+
("union_js_p99", ">", 0.060, "single-sample top-k JS divergence too high"),
|
| 56 |
+
],
|
| 57 |
+
"batch_accept_thresholds": [
|
| 58 |
+
("missing_selected_count", "==", 0.0, "selected token must be present in verifier top-k"),
|
| 59 |
+
("abs_logprob_diff_p50", "<=", 0.00010, "batch median selected-token drift"),
|
| 60 |
+
("mean_abs_logprob_diff", "<=", 0.015, "batch mean selected-token drift"),
|
| 61 |
+
("abs_logprob_diff_p90", "<=", 0.060, "batch p90 selected-token drift"),
|
| 62 |
+
("abs_logprob_diff_p95", "<=", 0.090, "batch p95 selected-token drift"),
|
| 63 |
+
("abs_logprob_diff_p99", "<=", 0.200, "batch p99 selected-token drift"),
|
| 64 |
+
("rank_delta_nonzero_rate", "<=", 0.012, "batch selected-token rank drift rate"),
|
| 65 |
+
("topk_jaccard_mean", ">=", 0.940, "batch mean top-k token-set overlap"),
|
| 66 |
+
("topk_jaccard_p05", ">=", 0.820, "batch p05 top-k token-set overlap"),
|
| 67 |
+
("union_js_p95", "<=", 0.004, "batch p95 top-k union JS divergence"),
|
| 68 |
+
("union_js_p99", "<=", 0.012, "batch p99 top-k union JS divergence"),
|
| 69 |
+
],
|
| 70 |
+
"batch_reject_thresholds": [
|
| 71 |
+
("missing_selected_count", ">", 0.0, "selected token missing from verifier top-k"),
|
| 72 |
+
("mean_abs_logprob_diff", ">", 0.020, "batch mean selected-token drift too high"),
|
| 73 |
+
("abs_logprob_diff_p95", ">", 0.120, "batch p95 selected-token drift too high"),
|
| 74 |
+
("abs_logprob_diff_p99", ">", 0.250, "batch p99 selected-token drift too high"),
|
| 75 |
+
("rank_delta_nonzero_rate", ">", 0.030, "batch selected-token rank drift too high"),
|
| 76 |
+
("topk_jaccard_mean", "<", 0.920, "batch top-k overlap too low"),
|
| 77 |
+
("union_js_p99", ">", 0.020, "batch top-k JS divergence too high"),
|
| 78 |
+
],
|
| 79 |
+
"sample_rate_thresholds": {
|
| 80 |
+
"min_strict_sample_accept_rate": 0.90,
|
| 81 |
+
"max_strict_sample_reject_rate": 0.02,
|
| 82 |
+
},
|
| 83 |
+
"calibration_note": (
|
| 84 |
+
"Calibrated from qwen3_8b_4090_data_results: BF16 worker-vs-BF16 verifier "
|
| 85 |
+
"overall mean ~=0.0081, p95 ~=0.0499, p99 ~=0.1018; FP8 overall mean "
|
| 86 |
+
"~=0.0290, p95 ~=0.1351, p99 ~=0.3123."
|
| 87 |
+
),
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def read_csv(path: Path) -> List[dict]:
|
| 93 |
+
with path.open("r", encoding="utf-8", newline="") as handle:
|
| 94 |
+
return list(csv.DictReader(handle))
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def write_csv(path: Path, rows: Sequence[dict], fields: Sequence[str]) -> None:
|
| 98 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 99 |
+
with path.open("w", encoding="utf-8", newline="") as handle:
|
| 100 |
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
| 101 |
+
writer.writeheader()
|
| 102 |
+
for row in rows:
|
| 103 |
+
writer.writerow({field: row.get(field, "") for field in fields})
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def metrics_path(path: Path) -> Path:
|
| 107 |
+
if path.is_dir():
|
| 108 |
+
direct = path / "worker_vs_verifier_depth_metrics.csv"
|
| 109 |
+
if direct.exists():
|
| 110 |
+
return direct
|
| 111 |
+
nested = path / "distribution" / "overall.csv"
|
| 112 |
+
if nested.exists():
|
| 113 |
+
return nested
|
| 114 |
+
return path
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def is_distribution_summary(path: Path) -> bool:
|
| 118 |
+
return path.name in {"overall.csv", "by_sample.csv"} and path.parent.name == "distribution"
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def distribution_dir(path: Path) -> Path:
|
| 122 |
+
if path.is_dir():
|
| 123 |
+
return path / "distribution"
|
| 124 |
+
if path.parent.name == "distribution":
|
| 125 |
+
return path.parent
|
| 126 |
+
return path.parent / "distribution"
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def group_by_sample(rows: Sequence[dict]) -> List[dict]:
|
| 130 |
+
grouped: Dict[str, List[dict]] = defaultdict(list)
|
| 131 |
+
for row in rows:
|
| 132 |
+
grouped[str(row.get("sample_id", ""))].append(row)
|
| 133 |
+
return [
|
| 134 |
+
summarize_rows(group_rows, sample_id)
|
| 135 |
+
for sample_id, group_rows in sorted(grouped.items())
|
| 136 |
+
]
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def load_summaries(path: Path) -> Tuple[dict, List[dict], str]:
|
| 140 |
+
resolved = metrics_path(path)
|
| 141 |
+
if is_distribution_summary(resolved):
|
| 142 |
+
dist = distribution_dir(resolved)
|
| 143 |
+
overall_rows = read_csv(dist / "overall.csv")
|
| 144 |
+
sample_path = dist / "by_sample.csv"
|
| 145 |
+
sample_rows = read_csv(sample_path) if sample_path.exists() else []
|
| 146 |
+
if not overall_rows:
|
| 147 |
+
raise ValueError(f"{dist / 'overall.csv'} is empty")
|
| 148 |
+
return overall_rows[0], sample_rows, str(dist)
|
| 149 |
+
|
| 150 |
+
rows = read_csv(resolved)
|
| 151 |
+
if not rows:
|
| 152 |
+
raise ValueError(f"{resolved} is empty")
|
| 153 |
+
overall = summarize_rows(rows, "overall")
|
| 154 |
+
return overall, group_by_sample(rows), str(resolved)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def finite(value: object) -> bool:
|
| 158 |
+
return math.isfinite(safe_float(value))
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def compare(value: float, op: str, threshold: float) -> bool:
|
| 162 |
+
if not math.isfinite(value):
|
| 163 |
+
return False
|
| 164 |
+
if op == "<=":
|
| 165 |
+
return value <= threshold
|
| 166 |
+
if op == "<":
|
| 167 |
+
return value < threshold
|
| 168 |
+
if op == ">=":
|
| 169 |
+
return value >= threshold
|
| 170 |
+
if op == ">":
|
| 171 |
+
return value > threshold
|
| 172 |
+
if op == "==":
|
| 173 |
+
return value == threshold
|
| 174 |
+
raise ValueError(f"unsupported threshold operator: {op}")
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def evaluate_thresholds(summary: dict, thresholds: Sequence[Threshold]) -> List[dict]:
|
| 178 |
+
checks = []
|
| 179 |
+
for metric, op, threshold, reason in thresholds:
|
| 180 |
+
value = safe_float(summary.get(metric))
|
| 181 |
+
passed = compare(value, op, threshold)
|
| 182 |
+
checks.append({
|
| 183 |
+
"metric": metric,
|
| 184 |
+
"op": op,
|
| 185 |
+
"threshold": threshold,
|
| 186 |
+
"value": value if math.isfinite(value) else "",
|
| 187 |
+
"passed": passed,
|
| 188 |
+
"reason": reason,
|
| 189 |
+
})
|
| 190 |
+
return checks
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def all_passed(checks: Sequence[dict]) -> bool:
|
| 194 |
+
return all(bool(check.get("passed")) for check in checks)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def any_passed(checks: Sequence[dict]) -> bool:
|
| 198 |
+
return any(bool(check.get("passed")) for check in checks)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def has_topk(summary: dict) -> bool:
|
| 202 |
+
required = ["topk_jaccard_mean", "union_js_p99"]
|
| 203 |
+
return all(finite(summary.get(metric)) for metric in required)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def classify_sample(summary: dict, preset: dict) -> dict:
|
| 207 |
+
count = int(safe_float(summary.get("finite_count", summary.get("count", 0)), 0.0))
|
| 208 |
+
accept_checks = evaluate_thresholds(summary, preset["sample_accept_thresholds"])
|
| 209 |
+
reject_checks = evaluate_thresholds(summary, preset["single_reject_thresholds"])
|
| 210 |
+
min_tokens = int(preset["requirements"]["min_single_output_tokens"])
|
| 211 |
+
if count < min_tokens:
|
| 212 |
+
verdict = "INCONCLUSIVE"
|
| 213 |
+
reason = f"sample has {count} finite tokens; need at least {min_tokens}"
|
| 214 |
+
elif all_passed(accept_checks):
|
| 215 |
+
verdict = "PASS_PROVISIONAL"
|
| 216 |
+
reason = "single sample matches the BF16 dense fingerprint"
|
| 217 |
+
elif any_passed(reject_checks):
|
| 218 |
+
verdict = "REJECT"
|
| 219 |
+
reason = "single sample violates one or more reject thresholds"
|
| 220 |
+
else:
|
| 221 |
+
verdict = "INCONCLUSIVE"
|
| 222 |
+
reason = "single sample is between accept and reject thresholds"
|
| 223 |
+
return {
|
| 224 |
+
**summary,
|
| 225 |
+
"verdict": verdict,
|
| 226 |
+
"reason": reason,
|
| 227 |
+
"accept_failures": "; ".join(
|
| 228 |
+
check["metric"] for check in accept_checks if not check["passed"]
|
| 229 |
+
),
|
| 230 |
+
"reject_hits": "; ".join(
|
| 231 |
+
check["metric"] for check in reject_checks if check["passed"]
|
| 232 |
+
),
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def verdict_for_batch(overall: dict,
|
| 237 |
+
sample_decisions: Sequence[dict],
|
| 238 |
+
preset: dict) -> Tuple[str, str, List[dict], List[dict]]:
|
| 239 |
+
requirements = preset["requirements"]
|
| 240 |
+
total_tokens = int(safe_float(overall.get("finite_count", overall.get("count", 0)), 0.0))
|
| 241 |
+
sample_count = len(sample_decisions)
|
| 242 |
+
pass_count = sum(1 for row in sample_decisions if row.get("verdict") == "PASS_PROVISIONAL")
|
| 243 |
+
reject_count = sum(1 for row in sample_decisions if row.get("verdict") == "REJECT")
|
| 244 |
+
pass_rate = pass_count / sample_count if sample_count else 0.0
|
| 245 |
+
reject_rate = reject_count / sample_count if sample_count else 1.0
|
| 246 |
+
has_required_topk = has_topk(overall)
|
| 247 |
+
|
| 248 |
+
accept_checks = evaluate_thresholds(overall, preset["batch_accept_thresholds"])
|
| 249 |
+
reject_checks = evaluate_thresholds(overall, preset["batch_reject_thresholds"])
|
| 250 |
+
sample_rate = preset["sample_rate_thresholds"]
|
| 251 |
+
eligibility_failures = []
|
| 252 |
+
if total_tokens < int(requirements["min_strict_total_tokens"]):
|
| 253 |
+
eligibility_failures.append(
|
| 254 |
+
f"total finite tokens {total_tokens} < {requirements['min_strict_total_tokens']}"
|
| 255 |
+
)
|
| 256 |
+
if sample_count < int(requirements["min_strict_samples"]):
|
| 257 |
+
eligibility_failures.append(
|
| 258 |
+
f"samples {sample_count} < {requirements['min_strict_samples']}"
|
| 259 |
+
)
|
| 260 |
+
if requirements.get("require_topk_for_strict", False) and not has_required_topk:
|
| 261 |
+
eligibility_failures.append("top-k metrics are required for strict BF16 verification")
|
| 262 |
+
|
| 263 |
+
sample_rate_failed = []
|
| 264 |
+
if pass_rate < float(sample_rate["min_strict_sample_accept_rate"]):
|
| 265 |
+
sample_rate_failed.append(
|
| 266 |
+
f"sample accept rate {pass_rate:.6g} < {sample_rate['min_strict_sample_accept_rate']}"
|
| 267 |
+
)
|
| 268 |
+
if reject_rate > float(sample_rate["max_strict_sample_reject_rate"]):
|
| 269 |
+
sample_rate_failed.append(
|
| 270 |
+
f"sample reject rate {reject_rate:.6g} > {sample_rate['max_strict_sample_reject_rate']}"
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
strict_eligible = not eligibility_failures
|
| 274 |
+
if strict_eligible and all_passed(accept_checks) and not sample_rate_failed:
|
| 275 |
+
return "PASS_STRICT", "batch matches the Qwen3-8B BF16 dense fingerprint", accept_checks, reject_checks
|
| 276 |
+
if any_passed(reject_checks):
|
| 277 |
+
return "REJECT", "batch violates one or more exact-BF16 reject thresholds", accept_checks, reject_checks
|
| 278 |
+
if not strict_eligible:
|
| 279 |
+
return "INCONCLUSIVE", "; ".join(eligibility_failures), accept_checks, reject_checks
|
| 280 |
+
if sample_rate_failed:
|
| 281 |
+
return "INCONCLUSIVE", "; ".join(sample_rate_failed), accept_checks, reject_checks
|
| 282 |
+
return "INCONCLUSIVE", "batch is between accept and reject thresholds", accept_checks, reject_checks
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def format_value(value: object) -> str:
|
| 286 |
+
number = safe_float(value)
|
| 287 |
+
if not math.isfinite(number):
|
| 288 |
+
return ""
|
| 289 |
+
if abs(number) < 1e-4 and number != 0.0:
|
| 290 |
+
return f"{number:.3e}"
|
| 291 |
+
return f"{number:.6g}"
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def write_markdown(path: Path,
|
| 295 |
+
source: str,
|
| 296 |
+
preset: dict,
|
| 297 |
+
verdict: str,
|
| 298 |
+
reason: str,
|
| 299 |
+
overall: dict,
|
| 300 |
+
accept_checks: Sequence[dict],
|
| 301 |
+
reject_checks: Sequence[dict],
|
| 302 |
+
sample_decisions: Sequence[dict]) -> None:
|
| 303 |
+
counts = Counter(str(row.get("verdict")) for row in sample_decisions)
|
| 304 |
+
sample_count = len(sample_decisions)
|
| 305 |
+
pass_rate = counts.get("PASS_PROVISIONAL", 0) / sample_count if sample_count else 0.0
|
| 306 |
+
reject_rate = counts.get("REJECT", 0) / sample_count if sample_count else 0.0
|
| 307 |
+
lines = [
|
| 308 |
+
"# Dense BF16 verifier",
|
| 309 |
+
"",
|
| 310 |
+
f"- source: `{source}`",
|
| 311 |
+
f"- preset: `{preset['profile_id']}`",
|
| 312 |
+
f"- verdict: **{verdict}**",
|
| 313 |
+
f"- reason: {reason}",
|
| 314 |
+
f"- finite tokens: {int(safe_float(overall.get('finite_count', overall.get('count', 0)), 0.0))}",
|
| 315 |
+
f"- samples: {sample_count}",
|
| 316 |
+
f"- sample provisional pass rate: {pass_rate:.6g}",
|
| 317 |
+
f"- sample reject rate: {reject_rate:.6g}",
|
| 318 |
+
"",
|
| 319 |
+
"## Overall metrics",
|
| 320 |
+
"",
|
| 321 |
+
"| metric | value |",
|
| 322 |
+
"|---|---:|",
|
| 323 |
+
]
|
| 324 |
+
for metric in [
|
| 325 |
+
"mean_abs_logprob_diff",
|
| 326 |
+
"abs_logprob_diff_p50",
|
| 327 |
+
"abs_logprob_diff_p90",
|
| 328 |
+
"abs_logprob_diff_p95",
|
| 329 |
+
"abs_logprob_diff_p99",
|
| 330 |
+
"abs_logprob_diff_p999",
|
| 331 |
+
"rank_delta_nonzero_rate",
|
| 332 |
+
"topk_jaccard_mean",
|
| 333 |
+
"topk_jaccard_p05",
|
| 334 |
+
"union_js_p95",
|
| 335 |
+
"union_js_p99",
|
| 336 |
+
"max_abs_logprob_diff",
|
| 337 |
+
"missing_selected_count",
|
| 338 |
+
]:
|
| 339 |
+
lines.append(f"| `{metric}` | {format_value(overall.get(metric))} |")
|
| 340 |
+
|
| 341 |
+
lines.extend([
|
| 342 |
+
"",
|
| 343 |
+
"## Batch accept checks",
|
| 344 |
+
"",
|
| 345 |
+
"| metric | op | threshold | value | passed |",
|
| 346 |
+
"|---|---:|---:|---:|---|",
|
| 347 |
+
])
|
| 348 |
+
for check in accept_checks:
|
| 349 |
+
lines.append(
|
| 350 |
+
f"| `{check['metric']}` | {check['op']} | {format_value(check['threshold'])} | "
|
| 351 |
+
f"{format_value(check['value'])} | {check['passed']} |"
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
lines.extend([
|
| 355 |
+
"",
|
| 356 |
+
"## Reject checks",
|
| 357 |
+
"",
|
| 358 |
+
"| metric | op | threshold | value | hit |",
|
| 359 |
+
"|---|---:|---:|---:|---|",
|
| 360 |
+
])
|
| 361 |
+
for check in reject_checks:
|
| 362 |
+
lines.append(
|
| 363 |
+
f"| `{check['metric']}` | {check['op']} | {format_value(check['threshold'])} | "
|
| 364 |
+
f"{format_value(check['value'])} | {check['passed']} |"
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
lines.extend([
|
| 368 |
+
"",
|
| 369 |
+
"## Sample verdicts",
|
| 370 |
+
"",
|
| 371 |
+
"| verdict | count |",
|
| 372 |
+
"|---|---:|",
|
| 373 |
+
])
|
| 374 |
+
for item, count in counts.most_common():
|
| 375 |
+
lines.append(f"| {item} | {count} |")
|
| 376 |
+
lines.append("")
|
| 377 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 381 |
+
parser = argparse.ArgumentParser(
|
| 382 |
+
description="Apply dense Qwen3-8B BF16 identity thresholds to worker-vs-verifier metrics."
|
| 383 |
+
)
|
| 384 |
+
parser.add_argument("--metrics", required=True,
|
| 385 |
+
help="worker_vs_verifier_depth_metrics.csv, its parent dir, or distribution/overall.csv.")
|
| 386 |
+
parser.add_argument("--output-dir", default="results/dense_bf16_verification")
|
| 387 |
+
parser.add_argument("--preset", default="qwen3-8b-bf16-4090-v1",
|
| 388 |
+
choices=sorted(PRESETS))
|
| 389 |
+
parser.add_argument("--fail-on-reject", action=argparse.BooleanOptionalAction,
|
| 390 |
+
default=False)
|
| 391 |
+
args = parser.parse_args(argv)
|
| 392 |
+
|
| 393 |
+
preset = PRESETS[args.preset]
|
| 394 |
+
overall, by_sample, source = load_summaries(Path(args.metrics))
|
| 395 |
+
sample_decisions = [classify_sample(row, preset) for row in by_sample]
|
| 396 |
+
verdict, reason, accept_checks, reject_checks = verdict_for_batch(
|
| 397 |
+
overall,
|
| 398 |
+
sample_decisions,
|
| 399 |
+
preset,
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
output_dir = Path(args.output_dir)
|
| 403 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 404 |
+
sample_fields = [
|
| 405 |
+
"group",
|
| 406 |
+
"verdict",
|
| 407 |
+
"reason",
|
| 408 |
+
"count",
|
| 409 |
+
"finite_count",
|
| 410 |
+
"mean_abs_logprob_diff",
|
| 411 |
+
"abs_logprob_diff_p50",
|
| 412 |
+
"abs_logprob_diff_p90",
|
| 413 |
+
"abs_logprob_diff_p95",
|
| 414 |
+
"abs_logprob_diff_p99",
|
| 415 |
+
"rank_delta_nonzero_rate",
|
| 416 |
+
"topk_jaccard_mean",
|
| 417 |
+
"topk_jaccard_p05",
|
| 418 |
+
"union_js_p95",
|
| 419 |
+
"union_js_p99",
|
| 420 |
+
"missing_selected_count",
|
| 421 |
+
"accept_failures",
|
| 422 |
+
"reject_hits",
|
| 423 |
+
]
|
| 424 |
+
write_csv(output_dir / "sample_decisions.csv", sample_decisions, sample_fields)
|
| 425 |
+
write_json(output_dir / "parameters.json", preset)
|
| 426 |
+
counts = Counter(str(row.get("verdict")) for row in sample_decisions)
|
| 427 |
+
result = {
|
| 428 |
+
"metadata": runtime_metadata(sys.argv),
|
| 429 |
+
"args": vars(args),
|
| 430 |
+
"source": source,
|
| 431 |
+
"preset": args.preset,
|
| 432 |
+
"verdict": verdict,
|
| 433 |
+
"passed": verdict == "PASS_STRICT",
|
| 434 |
+
"reason": reason,
|
| 435 |
+
"overall": overall,
|
| 436 |
+
"sample_verdict_counts": dict(counts),
|
| 437 |
+
"sample_count": len(sample_decisions),
|
| 438 |
+
"sample_pass_rate": (
|
| 439 |
+
counts.get("PASS_PROVISIONAL", 0) / len(sample_decisions)
|
| 440 |
+
if sample_decisions else 0.0
|
| 441 |
+
),
|
| 442 |
+
"sample_reject_rate": (
|
| 443 |
+
counts.get("REJECT", 0) / len(sample_decisions)
|
| 444 |
+
if sample_decisions else 1.0
|
| 445 |
+
),
|
| 446 |
+
"batch_accept_checks": accept_checks,
|
| 447 |
+
"batch_reject_checks": reject_checks,
|
| 448 |
+
}
|
| 449 |
+
write_json(output_dir / "dense_verification.json", result)
|
| 450 |
+
write_markdown(
|
| 451 |
+
output_dir / "summary.md",
|
| 452 |
+
source=source,
|
| 453 |
+
preset=preset,
|
| 454 |
+
verdict=verdict,
|
| 455 |
+
reason=reason,
|
| 456 |
+
overall=overall,
|
| 457 |
+
accept_checks=accept_checks,
|
| 458 |
+
reject_checks=reject_checks,
|
| 459 |
+
sample_decisions=sample_decisions,
|
| 460 |
+
)
|
| 461 |
+
print(f"Wrote {output_dir / 'summary.md'}")
|
| 462 |
+
print(f"Wrote {output_dir / 'dense_verification.json'}")
|
| 463 |
+
print(f"Wrote {output_dir / 'sample_decisions.csv'}")
|
| 464 |
+
print(f"Wrote {output_dir / 'parameters.json'}")
|
| 465 |
+
print(f"Verdict: {verdict}")
|
| 466 |
+
return 1 if (verdict == "REJECT" and args.fail_on_reject) else 0
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
if __name__ == "__main__":
|
| 470 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/src/worker_logits_verify/estimate_sample_size.py
ADDED
|
@@ -0,0 +1,721 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
import random
|
| 7 |
+
import sys
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, List, Mapping, Optional, Sequence, Tuple
|
| 11 |
+
|
| 12 |
+
from .metrics import quantile, safe_float
|
| 13 |
+
from .schema import runtime_metadata, write_json
|
| 14 |
+
from .summarize_worker_verify import summarize_rows
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
MetricDirection = str
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
METRIC_DIRECTIONS: Dict[str, MetricDirection] = {
|
| 21 |
+
"missing_selected_count": "low",
|
| 22 |
+
"mean_abs_logprob_diff": "low",
|
| 23 |
+
"abs_logprob_diff_p50": "low",
|
| 24 |
+
"abs_logprob_diff_p90": "low",
|
| 25 |
+
"abs_logprob_diff_p95": "low",
|
| 26 |
+
"abs_logprob_diff_p99": "low",
|
| 27 |
+
"abs_logprob_diff_p999": "low",
|
| 28 |
+
"rank_delta_nonzero_rate": "low",
|
| 29 |
+
"union_js_p95": "low",
|
| 30 |
+
"union_js_p99": "low",
|
| 31 |
+
"union_js_max": "low",
|
| 32 |
+
"topk_jaccard_mean": "high",
|
| 33 |
+
"topk_jaccard_p01": "high",
|
| 34 |
+
"topk_jaccard_p05": "high",
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
DEFAULT_METRICS = [
|
| 38 |
+
"missing_selected_count",
|
| 39 |
+
"mean_abs_logprob_diff",
|
| 40 |
+
"abs_logprob_diff_p95",
|
| 41 |
+
"abs_logprob_diff_p99",
|
| 42 |
+
"rank_delta_nonzero_rate",
|
| 43 |
+
"topk_jaccard_mean",
|
| 44 |
+
"union_js_p99",
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@dataclass
|
| 49 |
+
class CaseData:
|
| 50 |
+
label: str
|
| 51 |
+
path: Path
|
| 52 |
+
groups: Dict[str, List[dict]]
|
| 53 |
+
|
| 54 |
+
@property
|
| 55 |
+
def sample_ids(self) -> List[str]:
|
| 56 |
+
return sorted(self.groups)
|
| 57 |
+
|
| 58 |
+
@property
|
| 59 |
+
def sample_count(self) -> int:
|
| 60 |
+
return len(self.groups)
|
| 61 |
+
|
| 62 |
+
@property
|
| 63 |
+
def row_count(self) -> int:
|
| 64 |
+
return sum(len(rows) for rows in self.groups.values())
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@dataclass
|
| 68 |
+
class ResampleResult:
|
| 69 |
+
summary: dict
|
| 70 |
+
actual_samples: int
|
| 71 |
+
actual_tokens: int
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@dataclass
|
| 75 |
+
class Threshold:
|
| 76 |
+
metric: str
|
| 77 |
+
direction: MetricDirection
|
| 78 |
+
value: float
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def log(message: str) -> None:
|
| 82 |
+
print(message, flush=True)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def parse_int_list(raw: str) -> List[int]:
|
| 86 |
+
out = []
|
| 87 |
+
for item in raw.split(","):
|
| 88 |
+
item = item.strip()
|
| 89 |
+
if not item:
|
| 90 |
+
continue
|
| 91 |
+
value = int(item)
|
| 92 |
+
if value <= 0:
|
| 93 |
+
raise ValueError(f"budget values must be positive: {value}")
|
| 94 |
+
out.append(value)
|
| 95 |
+
return sorted(set(out))
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def parse_metrics(raw: str) -> List[str]:
|
| 99 |
+
metrics = [item.strip() for item in raw.split(",") if item.strip()]
|
| 100 |
+
if not metrics:
|
| 101 |
+
raise ValueError("at least one metric is required")
|
| 102 |
+
unknown = [metric for metric in metrics if metric not in METRIC_DIRECTIONS]
|
| 103 |
+
if unknown:
|
| 104 |
+
known = ", ".join(sorted(METRIC_DIRECTIONS))
|
| 105 |
+
raise ValueError(f"unknown metric(s): {', '.join(unknown)}. Known metrics: {known}")
|
| 106 |
+
return metrics
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def parse_case_spec(raw: str) -> Tuple[str, Path]:
|
| 110 |
+
if "=" in raw:
|
| 111 |
+
label, path = raw.split("=", 1)
|
| 112 |
+
label = label.strip()
|
| 113 |
+
if not label:
|
| 114 |
+
raise ValueError(f"empty case label in {raw!r}")
|
| 115 |
+
return label, Path(path.strip())
|
| 116 |
+
path = Path(raw.strip())
|
| 117 |
+
label = path.parent.name if path.name == "worker_vs_verifier_depth_metrics.csv" else path.name
|
| 118 |
+
return label or "case", path
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def metrics_path(path: Path) -> Path:
|
| 122 |
+
if path.is_dir():
|
| 123 |
+
direct = path / "worker_vs_verifier_depth_metrics.csv"
|
| 124 |
+
if direct.exists():
|
| 125 |
+
return direct
|
| 126 |
+
return path
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def read_csv(path: Path) -> List[dict]:
|
| 130 |
+
with path.open("r", encoding="utf-8", newline="") as handle:
|
| 131 |
+
return list(csv.DictReader(handle))
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def write_csv(path: Path, rows: Sequence[Mapping[str, object]], fields: Sequence[str]) -> None:
|
| 135 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 136 |
+
with path.open("w", encoding="utf-8", newline="") as handle:
|
| 137 |
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
| 138 |
+
writer.writeheader()
|
| 139 |
+
for row in rows:
|
| 140 |
+
writer.writerow({field: row.get(field, "") for field in fields})
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def load_case(raw: str) -> CaseData:
|
| 144 |
+
label, raw_path = parse_case_spec(raw)
|
| 145 |
+
path = metrics_path(raw_path)
|
| 146 |
+
rows = read_csv(path)
|
| 147 |
+
groups: Dict[str, List[dict]] = {}
|
| 148 |
+
for row in rows:
|
| 149 |
+
sample_id = str(row.get("sample_id", ""))
|
| 150 |
+
if not sample_id:
|
| 151 |
+
raise ValueError(f"{path} has a row without sample_id")
|
| 152 |
+
groups.setdefault(sample_id, []).append(row)
|
| 153 |
+
if not groups:
|
| 154 |
+
raise ValueError(f"{path} has no sample rows")
|
| 155 |
+
return CaseData(label=label, path=path, groups=groups)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def finite_token_count(rows: Sequence[dict]) -> int:
|
| 159 |
+
return sum(
|
| 160 |
+
1
|
| 161 |
+
for row in rows
|
| 162 |
+
if math.isfinite(safe_float(row.get("abs_logprob_diff")))
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def choose_sample_ids(case: CaseData,
|
| 167 |
+
rng: random.Random,
|
| 168 |
+
*,
|
| 169 |
+
budget_type: str,
|
| 170 |
+
budget_target: int,
|
| 171 |
+
with_replacement: bool) -> List[str]:
|
| 172 |
+
sample_ids = case.sample_ids
|
| 173 |
+
if budget_type == "sample":
|
| 174 |
+
if with_replacement:
|
| 175 |
+
return [rng.choice(sample_ids) for _ in range(budget_target)]
|
| 176 |
+
if budget_target > len(sample_ids):
|
| 177 |
+
raise ValueError(
|
| 178 |
+
f"sample budget {budget_target} exceeds available samples "
|
| 179 |
+
f"{len(sample_ids)} for {case.label}; use --with-replacement"
|
| 180 |
+
)
|
| 181 |
+
return rng.sample(sample_ids, budget_target)
|
| 182 |
+
|
| 183 |
+
if budget_type != "token":
|
| 184 |
+
raise ValueError(f"unsupported budget type: {budget_type}")
|
| 185 |
+
|
| 186 |
+
chosen: List[str] = []
|
| 187 |
+
total_tokens = 0
|
| 188 |
+
if with_replacement:
|
| 189 |
+
while total_tokens < budget_target:
|
| 190 |
+
sample_id = rng.choice(sample_ids)
|
| 191 |
+
chosen.append(sample_id)
|
| 192 |
+
total_tokens += finite_token_count(case.groups[sample_id])
|
| 193 |
+
return chosen
|
| 194 |
+
|
| 195 |
+
shuffled = sample_ids[:]
|
| 196 |
+
rng.shuffle(shuffled)
|
| 197 |
+
for sample_id in shuffled:
|
| 198 |
+
chosen.append(sample_id)
|
| 199 |
+
total_tokens += finite_token_count(case.groups[sample_id])
|
| 200 |
+
if total_tokens >= budget_target:
|
| 201 |
+
break
|
| 202 |
+
if total_tokens < budget_target:
|
| 203 |
+
raise ValueError(
|
| 204 |
+
f"token budget {budget_target} exceeds available finite tokens "
|
| 205 |
+
f"{total_tokens} for {case.label}; use --with-replacement"
|
| 206 |
+
)
|
| 207 |
+
return chosen
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def resample_case(case: CaseData,
|
| 211 |
+
rng: random.Random,
|
| 212 |
+
*,
|
| 213 |
+
budget_type: str,
|
| 214 |
+
budget_target: int,
|
| 215 |
+
with_replacement: bool) -> ResampleResult:
|
| 216 |
+
sample_ids = choose_sample_ids(
|
| 217 |
+
case,
|
| 218 |
+
rng,
|
| 219 |
+
budget_type=budget_type,
|
| 220 |
+
budget_target=budget_target,
|
| 221 |
+
with_replacement=with_replacement,
|
| 222 |
+
)
|
| 223 |
+
rows: List[dict] = []
|
| 224 |
+
for sample_id in sample_ids:
|
| 225 |
+
rows.extend(case.groups[sample_id])
|
| 226 |
+
summary = summarize_rows(rows, case.label)
|
| 227 |
+
return ResampleResult(
|
| 228 |
+
summary=summary,
|
| 229 |
+
actual_samples=len(sample_ids),
|
| 230 |
+
actual_tokens=int(safe_float(summary.get("finite_count"), 0.0)),
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def build_resamples(case: CaseData,
|
| 235 |
+
*,
|
| 236 |
+
budget_type: str,
|
| 237 |
+
budget_target: int,
|
| 238 |
+
trials: int,
|
| 239 |
+
seed: int,
|
| 240 |
+
with_replacement: bool) -> List[ResampleResult]:
|
| 241 |
+
rng = random.Random(seed)
|
| 242 |
+
return [
|
| 243 |
+
resample_case(
|
| 244 |
+
case,
|
| 245 |
+
rng,
|
| 246 |
+
budget_type=budget_type,
|
| 247 |
+
budget_target=budget_target,
|
| 248 |
+
with_replacement=with_replacement,
|
| 249 |
+
)
|
| 250 |
+
for _ in range(trials)
|
| 251 |
+
]
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def values_for_metric(resamples: Sequence[ResampleResult], metric: str) -> List[float]:
|
| 255 |
+
values = [safe_float(item.summary.get(metric)) for item in resamples]
|
| 256 |
+
return [value for value in values if math.isfinite(value)]
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def derive_thresholds(positive: Sequence[ResampleResult],
|
| 260 |
+
metrics: Sequence[str],
|
| 261 |
+
*,
|
| 262 |
+
max_false_reject_rate: float,
|
| 263 |
+
bonferroni: bool) -> List[Threshold]:
|
| 264 |
+
if max_false_reject_rate <= 0.0 or max_false_reject_rate >= 1.0:
|
| 265 |
+
raise ValueError("--max-false-reject-rate must be in (0, 1)")
|
| 266 |
+
alpha = (
|
| 267 |
+
max_false_reject_rate / max(1, len(metrics))
|
| 268 |
+
if bonferroni else max_false_reject_rate
|
| 269 |
+
)
|
| 270 |
+
thresholds: List[Threshold] = []
|
| 271 |
+
for metric in metrics:
|
| 272 |
+
values = values_for_metric(positive, metric)
|
| 273 |
+
if not values:
|
| 274 |
+
continue
|
| 275 |
+
direction = METRIC_DIRECTIONS[metric]
|
| 276 |
+
if direction == "low":
|
| 277 |
+
value = quantile(values, 1.0 - alpha)
|
| 278 |
+
elif direction == "high":
|
| 279 |
+
value = quantile(values, alpha)
|
| 280 |
+
else:
|
| 281 |
+
raise ValueError(f"unsupported metric direction: {direction}")
|
| 282 |
+
thresholds.append(Threshold(metric=metric, direction=direction, value=value))
|
| 283 |
+
return thresholds
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def is_rejected(summary: Mapping[str, object], thresholds: Sequence[Threshold]) -> bool:
|
| 287 |
+
for threshold in thresholds:
|
| 288 |
+
value = safe_float(summary.get(threshold.metric))
|
| 289 |
+
if not math.isfinite(value):
|
| 290 |
+
return True
|
| 291 |
+
if threshold.direction == "low" and value > threshold.value:
|
| 292 |
+
return True
|
| 293 |
+
if threshold.direction == "high" and value < threshold.value:
|
| 294 |
+
return True
|
| 295 |
+
return False
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def rejection_rate(resamples: Sequence[ResampleResult], thresholds: Sequence[Threshold]) -> float:
|
| 299 |
+
if not resamples:
|
| 300 |
+
return float("nan")
|
| 301 |
+
rejected = sum(1 for item in resamples if is_rejected(item.summary, thresholds))
|
| 302 |
+
return rejected / len(resamples)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def summarize_actuals(resamples: Sequence[ResampleResult], attr: str) -> dict:
|
| 306 |
+
values = [float(getattr(item, attr)) for item in resamples]
|
| 307 |
+
return {
|
| 308 |
+
f"{attr}_mean": sum(values) / len(values) if values else float("nan"),
|
| 309 |
+
f"{attr}_p05": quantile(values, 0.05),
|
| 310 |
+
f"{attr}_p95": quantile(values, 0.95),
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def metric_curve_rows(case_label: str,
|
| 315 |
+
budget_type: str,
|
| 316 |
+
budget_target: int,
|
| 317 |
+
resamples: Sequence[ResampleResult],
|
| 318 |
+
metrics: Sequence[str]) -> List[dict]:
|
| 319 |
+
rows = []
|
| 320 |
+
for metric in metrics:
|
| 321 |
+
values = values_for_metric(resamples, metric)
|
| 322 |
+
if not values:
|
| 323 |
+
rows.append({
|
| 324 |
+
"case": case_label,
|
| 325 |
+
"budget_type": budget_type,
|
| 326 |
+
"budget_target": budget_target,
|
| 327 |
+
"metric": metric,
|
| 328 |
+
"direction": METRIC_DIRECTIONS[metric],
|
| 329 |
+
"finite_trials": 0,
|
| 330 |
+
})
|
| 331 |
+
continue
|
| 332 |
+
q01 = quantile(values, 0.01)
|
| 333 |
+
q05 = quantile(values, 0.05)
|
| 334 |
+
q50 = quantile(values, 0.50)
|
| 335 |
+
q95 = quantile(values, 0.95)
|
| 336 |
+
q99 = quantile(values, 0.99)
|
| 337 |
+
rows.append({
|
| 338 |
+
"case": case_label,
|
| 339 |
+
"budget_type": budget_type,
|
| 340 |
+
"budget_target": budget_target,
|
| 341 |
+
"metric": metric,
|
| 342 |
+
"direction": METRIC_DIRECTIONS[metric],
|
| 343 |
+
"finite_trials": len(values),
|
| 344 |
+
"mean": sum(values) / len(values),
|
| 345 |
+
"q01": q01,
|
| 346 |
+
"q05": q05,
|
| 347 |
+
"q50": q50,
|
| 348 |
+
"q95": q95,
|
| 349 |
+
"q99": q99,
|
| 350 |
+
"ci90_width": q95 - q05,
|
| 351 |
+
"ci98_width": q99 - q01,
|
| 352 |
+
})
|
| 353 |
+
return rows
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def threshold_rows(budget_type: str,
|
| 357 |
+
budget_target: int,
|
| 358 |
+
thresholds: Sequence[Threshold],
|
| 359 |
+
positive: Sequence[ResampleResult],
|
| 360 |
+
metrics: Sequence[str]) -> List[dict]:
|
| 361 |
+
by_metric = {threshold.metric: threshold for threshold in thresholds}
|
| 362 |
+
rows = []
|
| 363 |
+
for metric in metrics:
|
| 364 |
+
values = values_for_metric(positive, metric)
|
| 365 |
+
threshold = by_metric.get(metric)
|
| 366 |
+
rows.append({
|
| 367 |
+
"budget_type": budget_type,
|
| 368 |
+
"budget_target": budget_target,
|
| 369 |
+
"metric": metric,
|
| 370 |
+
"direction": METRIC_DIRECTIONS[metric],
|
| 371 |
+
"threshold": threshold.value if threshold else "",
|
| 372 |
+
"positive_q01": quantile(values, 0.01),
|
| 373 |
+
"positive_q05": quantile(values, 0.05),
|
| 374 |
+
"positive_q50": quantile(values, 0.50),
|
| 375 |
+
"positive_q95": quantile(values, 0.95),
|
| 376 |
+
"positive_q99": quantile(values, 0.99),
|
| 377 |
+
})
|
| 378 |
+
return rows
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def analyze_budget(positive_case: CaseData,
|
| 382 |
+
negative_cases: Sequence[CaseData],
|
| 383 |
+
*,
|
| 384 |
+
budget_type: str,
|
| 385 |
+
budget_target: int,
|
| 386 |
+
metrics: Sequence[str],
|
| 387 |
+
trials: int,
|
| 388 |
+
seed: int,
|
| 389 |
+
with_replacement: bool,
|
| 390 |
+
max_false_reject_rate: float,
|
| 391 |
+
max_false_accept_rate: float,
|
| 392 |
+
bonferroni: bool) -> Tuple[dict, List[dict], List[dict]]:
|
| 393 |
+
positive = build_resamples(
|
| 394 |
+
positive_case,
|
| 395 |
+
budget_type=budget_type,
|
| 396 |
+
budget_target=budget_target,
|
| 397 |
+
trials=trials,
|
| 398 |
+
seed=seed,
|
| 399 |
+
with_replacement=with_replacement,
|
| 400 |
+
)
|
| 401 |
+
thresholds = derive_thresholds(
|
| 402 |
+
positive,
|
| 403 |
+
metrics,
|
| 404 |
+
max_false_reject_rate=max_false_reject_rate,
|
| 405 |
+
bonferroni=bonferroni,
|
| 406 |
+
)
|
| 407 |
+
positive_reject_rate = rejection_rate(positive, thresholds)
|
| 408 |
+
|
| 409 |
+
metric_rows = metric_curve_rows(
|
| 410 |
+
positive_case.label,
|
| 411 |
+
budget_type,
|
| 412 |
+
budget_target,
|
| 413 |
+
positive,
|
| 414 |
+
metrics,
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
worst_negative_accept_rate = float("nan")
|
| 418 |
+
worst_negative_label = ""
|
| 419 |
+
negative_rates: Dict[str, float] = {}
|
| 420 |
+
for index, negative_case in enumerate(negative_cases, start=1):
|
| 421 |
+
negative = build_resamples(
|
| 422 |
+
negative_case,
|
| 423 |
+
budget_type=budget_type,
|
| 424 |
+
budget_target=budget_target,
|
| 425 |
+
trials=trials,
|
| 426 |
+
seed=seed + index * 100_003,
|
| 427 |
+
with_replacement=with_replacement,
|
| 428 |
+
)
|
| 429 |
+
negative_reject_rate = rejection_rate(negative, thresholds)
|
| 430 |
+
negative_accept_rate = 1.0 - negative_reject_rate
|
| 431 |
+
negative_rates[negative_case.label] = negative_accept_rate
|
| 432 |
+
if not math.isfinite(worst_negative_accept_rate) or negative_accept_rate > worst_negative_accept_rate:
|
| 433 |
+
worst_negative_accept_rate = negative_accept_rate
|
| 434 |
+
worst_negative_label = negative_case.label
|
| 435 |
+
metric_rows.extend(
|
| 436 |
+
metric_curve_rows(
|
| 437 |
+
negative_case.label,
|
| 438 |
+
budget_type,
|
| 439 |
+
budget_target,
|
| 440 |
+
negative,
|
| 441 |
+
metrics,
|
| 442 |
+
)
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
actual_sample_stats = summarize_actuals(positive, "actual_samples")
|
| 446 |
+
actual_token_stats = summarize_actuals(positive, "actual_tokens")
|
| 447 |
+
meets_targets = (
|
| 448 |
+
positive_reject_rate <= max_false_reject_rate
|
| 449 |
+
and (
|
| 450 |
+
not negative_cases
|
| 451 |
+
or worst_negative_accept_rate <= max_false_accept_rate
|
| 452 |
+
)
|
| 453 |
+
)
|
| 454 |
+
summary = {
|
| 455 |
+
"budget_type": budget_type,
|
| 456 |
+
"budget_target": budget_target,
|
| 457 |
+
"trials": trials,
|
| 458 |
+
"threshold_metric_count": len(thresholds),
|
| 459 |
+
"positive_label": positive_case.label,
|
| 460 |
+
"positive_reject_rate": positive_reject_rate,
|
| 461 |
+
"positive_accept_rate": 1.0 - positive_reject_rate,
|
| 462 |
+
"worst_negative_accept_rate": worst_negative_accept_rate,
|
| 463 |
+
"worst_negative_label": worst_negative_label,
|
| 464 |
+
"meets_targets": meets_targets,
|
| 465 |
+
**actual_sample_stats,
|
| 466 |
+
**actual_token_stats,
|
| 467 |
+
}
|
| 468 |
+
for label, rate in sorted(negative_rates.items()):
|
| 469 |
+
summary[f"negative_accept_rate__{label}"] = rate
|
| 470 |
+
|
| 471 |
+
return summary, metric_rows, threshold_rows(
|
| 472 |
+
budget_type,
|
| 473 |
+
budget_target,
|
| 474 |
+
thresholds,
|
| 475 |
+
positive,
|
| 476 |
+
metrics,
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def format_number(value: object) -> str:
|
| 481 |
+
number = safe_float(value)
|
| 482 |
+
if not math.isfinite(number):
|
| 483 |
+
return ""
|
| 484 |
+
if number != 0.0 and abs(number) < 1e-4:
|
| 485 |
+
return f"{number:.3e}"
|
| 486 |
+
return f"{number:.6g}"
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def first_recommendation(rows: Sequence[dict], budget_type: str) -> Optional[dict]:
|
| 490 |
+
candidates = [
|
| 491 |
+
row for row in rows
|
| 492 |
+
if row.get("budget_type") == budget_type and bool(row.get("meets_targets"))
|
| 493 |
+
]
|
| 494 |
+
if not candidates:
|
| 495 |
+
return None
|
| 496 |
+
return sorted(candidates, key=lambda row: int(row["budget_target"]))[0]
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def write_markdown(path: Path,
|
| 500 |
+
*,
|
| 501 |
+
positive_case: CaseData,
|
| 502 |
+
negative_cases: Sequence[CaseData],
|
| 503 |
+
metrics: Sequence[str],
|
| 504 |
+
budget_rows: Sequence[dict],
|
| 505 |
+
max_false_reject_rate: float,
|
| 506 |
+
max_false_accept_rate: float,
|
| 507 |
+
with_replacement: bool,
|
| 508 |
+
bonferroni: bool) -> None:
|
| 509 |
+
sample_rec = first_recommendation(budget_rows, "sample")
|
| 510 |
+
token_rec = first_recommendation(budget_rows, "token")
|
| 511 |
+
lines = [
|
| 512 |
+
"# Worker Verify Sample Size Estimate",
|
| 513 |
+
"",
|
| 514 |
+
f"- positive case: `{positive_case.label}` ({positive_case.sample_count} samples, {positive_case.row_count} rows)",
|
| 515 |
+
f"- negative cases: {', '.join(case.label for case in negative_cases) or 'none'}",
|
| 516 |
+
f"- metrics: {', '.join(f'`{metric}`' for metric in metrics)}",
|
| 517 |
+
f"- max false reject rate: {max_false_reject_rate:.6g}",
|
| 518 |
+
f"- max false accept rate: {max_false_accept_rate:.6g}",
|
| 519 |
+
f"- resampling: {'bootstrap with replacement' if with_replacement else 'subsample without replacement'}",
|
| 520 |
+
f"- per-metric threshold correction: {'Bonferroni' if bonferroni else 'none'}",
|
| 521 |
+
"",
|
| 522 |
+
"## Recommendation",
|
| 523 |
+
"",
|
| 524 |
+
]
|
| 525 |
+
if sample_rec:
|
| 526 |
+
lines.append(
|
| 527 |
+
"- minimum sample budget: `{}` samples "
|
| 528 |
+
"(positive reject `{}`, worst negative accept `{}` from `{}`)".format(
|
| 529 |
+
sample_rec["budget_target"],
|
| 530 |
+
format_number(sample_rec.get("positive_reject_rate")),
|
| 531 |
+
format_number(sample_rec.get("worst_negative_accept_rate")),
|
| 532 |
+
sample_rec.get("worst_negative_label", ""),
|
| 533 |
+
)
|
| 534 |
+
)
|
| 535 |
+
else:
|
| 536 |
+
lines.append("- minimum sample budget: not found in the evaluated grid")
|
| 537 |
+
if token_rec:
|
| 538 |
+
lines.append(
|
| 539 |
+
"- minimum token budget: `{}` output-token rows "
|
| 540 |
+
"(mean samples `{}`, positive reject `{}`, worst negative accept `{}` from `{}`)".format(
|
| 541 |
+
token_rec["budget_target"],
|
| 542 |
+
format_number(token_rec.get("actual_samples_mean")),
|
| 543 |
+
format_number(token_rec.get("positive_reject_rate")),
|
| 544 |
+
format_number(token_rec.get("worst_negative_accept_rate")),
|
| 545 |
+
token_rec.get("worst_negative_label", ""),
|
| 546 |
+
)
|
| 547 |
+
)
|
| 548 |
+
else:
|
| 549 |
+
lines.append("- minimum token budget: not found in the evaluated grid")
|
| 550 |
+
|
| 551 |
+
lines.extend([
|
| 552 |
+
"",
|
| 553 |
+
"Use the recommendation as a calibration estimate, then validate the chosen budget on a held-out prompt set.",
|
| 554 |
+
"",
|
| 555 |
+
"## Budget Curve",
|
| 556 |
+
"",
|
| 557 |
+
"| budget | positive reject | worst negative accept | worst negative | mean samples | mean tokens | meets |",
|
| 558 |
+
"|---|---:|---:|---|---:|---:|---|",
|
| 559 |
+
])
|
| 560 |
+
for row in sorted(budget_rows, key=lambda item: (str(item["budget_type"]), int(item["budget_target"]))):
|
| 561 |
+
lines.append(
|
| 562 |
+
"| {kind}={target} | {pos} | {neg} | {label} | {samples} | {tokens} | {meets} |".format(
|
| 563 |
+
kind=row.get("budget_type"),
|
| 564 |
+
target=row.get("budget_target"),
|
| 565 |
+
pos=format_number(row.get("positive_reject_rate")),
|
| 566 |
+
neg=format_number(row.get("worst_negative_accept_rate")),
|
| 567 |
+
label=row.get("worst_negative_label", ""),
|
| 568 |
+
samples=format_number(row.get("actual_samples_mean")),
|
| 569 |
+
tokens=format_number(row.get("actual_tokens_mean")),
|
| 570 |
+
meets=row.get("meets_targets"),
|
| 571 |
+
)
|
| 572 |
+
)
|
| 573 |
+
lines.append("")
|
| 574 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def make_parser() -> argparse.ArgumentParser:
|
| 578 |
+
parser = argparse.ArgumentParser(
|
| 579 |
+
description=(
|
| 580 |
+
"Estimate how many worker-verifier samples or output-token rows are "
|
| 581 |
+
"needed for stable model-identity decisions using block bootstrap by sample_id."
|
| 582 |
+
)
|
| 583 |
+
)
|
| 584 |
+
parser.add_argument("--positive", required=True,
|
| 585 |
+
help="Positive/same-model metrics CSV or directory. Accepts label=path.")
|
| 586 |
+
parser.add_argument("--negative", action="append", default=[],
|
| 587 |
+
help="Negative/challenger metrics CSV or directory. Accepts label=path. Repeatable.")
|
| 588 |
+
parser.add_argument("--output-dir", default="results/sample_size_estimate")
|
| 589 |
+
parser.add_argument("--metrics", default=",".join(DEFAULT_METRICS),
|
| 590 |
+
help="Comma-separated summary metrics used by the combined reject rule.")
|
| 591 |
+
parser.add_argument("--sample-counts", default="1,2,4,8,16,32,64,128",
|
| 592 |
+
help="Comma-separated whole-sample budgets to evaluate.")
|
| 593 |
+
parser.add_argument("--token-counts", default="128,256,512,1024,2048,4096,8192,16384",
|
| 594 |
+
help="Comma-separated output-token row budgets to evaluate. Use empty string to disable.")
|
| 595 |
+
parser.add_argument("--trials", type=int, default=1000)
|
| 596 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 597 |
+
parser.add_argument("--max-false-reject-rate", type=float, default=0.01,
|
| 598 |
+
help="Allowed same-model rejection rate.")
|
| 599 |
+
parser.add_argument("--max-false-accept-rate", type=float, default=0.01,
|
| 600 |
+
help="Allowed challenger acceptance rate.")
|
| 601 |
+
parser.add_argument("--with-replacement", action=argparse.BooleanOptionalAction,
|
| 602 |
+
default=True,
|
| 603 |
+
help="Bootstrap whole samples with replacement. Disable for finite-pool subsampling.")
|
| 604 |
+
parser.add_argument("--bonferroni", action=argparse.BooleanOptionalAction,
|
| 605 |
+
default=True,
|
| 606 |
+
help="Divide the positive false-reject budget across metrics when setting thresholds.")
|
| 607 |
+
return parser
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 611 |
+
parser = make_parser()
|
| 612 |
+
args = parser.parse_args(argv)
|
| 613 |
+
if args.trials <= 0:
|
| 614 |
+
parser.error("--trials must be positive")
|
| 615 |
+
|
| 616 |
+
metrics = parse_metrics(args.metrics)
|
| 617 |
+
sample_counts = parse_int_list(args.sample_counts) if args.sample_counts.strip() else []
|
| 618 |
+
token_counts = parse_int_list(args.token_counts) if args.token_counts.strip() else []
|
| 619 |
+
if not sample_counts and not token_counts:
|
| 620 |
+
parser.error("at least one of --sample-counts or --token-counts must be non-empty")
|
| 621 |
+
|
| 622 |
+
positive_case = load_case(args.positive)
|
| 623 |
+
negative_cases = [load_case(raw) for raw in args.negative]
|
| 624 |
+
output_dir = Path(args.output_dir)
|
| 625 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 626 |
+
|
| 627 |
+
budget_rows: List[dict] = []
|
| 628 |
+
metric_rows: List[dict] = []
|
| 629 |
+
thresholds: List[dict] = []
|
| 630 |
+
for budget_type, budgets in [("sample", sample_counts), ("token", token_counts)]:
|
| 631 |
+
for budget_target in budgets:
|
| 632 |
+
log(f"Analyzing {budget_type} budget {budget_target} with {args.trials} trials")
|
| 633 |
+
summary, metric_curve, threshold_curve = analyze_budget(
|
| 634 |
+
positive_case,
|
| 635 |
+
negative_cases,
|
| 636 |
+
budget_type=budget_type,
|
| 637 |
+
budget_target=budget_target,
|
| 638 |
+
metrics=metrics,
|
| 639 |
+
trials=args.trials,
|
| 640 |
+
seed=args.seed + budget_target * 1009 + (0 if budget_type == "sample" else 1_000_000),
|
| 641 |
+
with_replacement=args.with_replacement,
|
| 642 |
+
max_false_reject_rate=args.max_false_reject_rate,
|
| 643 |
+
max_false_accept_rate=args.max_false_accept_rate,
|
| 644 |
+
bonferroni=args.bonferroni,
|
| 645 |
+
)
|
| 646 |
+
budget_rows.append(summary)
|
| 647 |
+
metric_rows.extend(metric_curve)
|
| 648 |
+
thresholds.extend(threshold_curve)
|
| 649 |
+
|
| 650 |
+
budget_fields = sorted({field for row in budget_rows for field in row})
|
| 651 |
+
metric_fields = [
|
| 652 |
+
"case",
|
| 653 |
+
"budget_type",
|
| 654 |
+
"budget_target",
|
| 655 |
+
"metric",
|
| 656 |
+
"direction",
|
| 657 |
+
"finite_trials",
|
| 658 |
+
"mean",
|
| 659 |
+
"q01",
|
| 660 |
+
"q05",
|
| 661 |
+
"q50",
|
| 662 |
+
"q95",
|
| 663 |
+
"q99",
|
| 664 |
+
"ci90_width",
|
| 665 |
+
"ci98_width",
|
| 666 |
+
]
|
| 667 |
+
threshold_fields = [
|
| 668 |
+
"budget_type",
|
| 669 |
+
"budget_target",
|
| 670 |
+
"metric",
|
| 671 |
+
"direction",
|
| 672 |
+
"threshold",
|
| 673 |
+
"positive_q01",
|
| 674 |
+
"positive_q05",
|
| 675 |
+
"positive_q50",
|
| 676 |
+
"positive_q95",
|
| 677 |
+
"positive_q99",
|
| 678 |
+
]
|
| 679 |
+
write_csv(output_dir / "budget_curve.csv", budget_rows, budget_fields)
|
| 680 |
+
write_csv(output_dir / "metric_curve.csv", metric_rows, metric_fields)
|
| 681 |
+
write_csv(output_dir / "thresholds_by_budget.csv", thresholds, threshold_fields)
|
| 682 |
+
write_markdown(
|
| 683 |
+
output_dir / "summary.md",
|
| 684 |
+
positive_case=positive_case,
|
| 685 |
+
negative_cases=negative_cases,
|
| 686 |
+
metrics=metrics,
|
| 687 |
+
budget_rows=budget_rows,
|
| 688 |
+
max_false_reject_rate=args.max_false_reject_rate,
|
| 689 |
+
max_false_accept_rate=args.max_false_accept_rate,
|
| 690 |
+
with_replacement=args.with_replacement,
|
| 691 |
+
bonferroni=args.bonferroni,
|
| 692 |
+
)
|
| 693 |
+
write_json(output_dir / "metadata.json", {
|
| 694 |
+
"metadata": runtime_metadata(sys.argv),
|
| 695 |
+
"args": vars(args),
|
| 696 |
+
"positive": {
|
| 697 |
+
"label": positive_case.label,
|
| 698 |
+
"path": str(positive_case.path),
|
| 699 |
+
"sample_count": positive_case.sample_count,
|
| 700 |
+
"row_count": positive_case.row_count,
|
| 701 |
+
},
|
| 702 |
+
"negative": [
|
| 703 |
+
{
|
| 704 |
+
"label": case.label,
|
| 705 |
+
"path": str(case.path),
|
| 706 |
+
"sample_count": case.sample_count,
|
| 707 |
+
"row_count": case.row_count,
|
| 708 |
+
}
|
| 709 |
+
for case in negative_cases
|
| 710 |
+
],
|
| 711 |
+
"metrics": metrics,
|
| 712 |
+
})
|
| 713 |
+
log(f"Wrote {output_dir / 'summary.md'}")
|
| 714 |
+
log(f"Wrote {output_dir / 'budget_curve.csv'}")
|
| 715 |
+
log(f"Wrote {output_dir / 'metric_curve.csv'}")
|
| 716 |
+
log(f"Wrote {output_dir / 'thresholds_by_budget.csv'}")
|
| 717 |
+
return 0
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
if __name__ == "__main__":
|
| 721 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/src/worker_logits_verify/generate_anchor_outputs.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Dict, Iterable, List, Optional, Sequence
|
| 10 |
+
|
| 11 |
+
from .schema import (
|
| 12 |
+
DecodeConfig,
|
| 13 |
+
Tokenization,
|
| 14 |
+
VariantInfo,
|
| 15 |
+
dataclass_to_dict,
|
| 16 |
+
parse_worker_sample,
|
| 17 |
+
read_jsonl,
|
| 18 |
+
runtime_metadata,
|
| 19 |
+
worker_sample_to_dict,
|
| 20 |
+
write_json,
|
| 21 |
+
write_jsonl,
|
| 22 |
+
)
|
| 23 |
+
from .tokenizer_utils import decode_tokens, encode_text, tokenizer_hash, tokenizer_name
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def load_transformers(model_name: str,
|
| 27 |
+
dtype: str,
|
| 28 |
+
device_map: str,
|
| 29 |
+
trust_remote_code: bool,
|
| 30 |
+
attn_implementation: Optional[str]) -> tuple:
|
| 31 |
+
import torch
|
| 32 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 33 |
+
|
| 34 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 35 |
+
model_name,
|
| 36 |
+
trust_remote_code=trust_remote_code,
|
| 37 |
+
)
|
| 38 |
+
torch_dtype = parse_torch_dtype(torch, dtype)
|
| 39 |
+
kwargs = {
|
| 40 |
+
"torch_dtype": torch_dtype,
|
| 41 |
+
"device_map": device_map,
|
| 42 |
+
"trust_remote_code": trust_remote_code,
|
| 43 |
+
}
|
| 44 |
+
if attn_implementation:
|
| 45 |
+
kwargs["attn_implementation"] = attn_implementation
|
| 46 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, **kwargs)
|
| 47 |
+
model.eval()
|
| 48 |
+
return tokenizer, model, torch
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def parse_torch_dtype(torch: object, dtype: str) -> object:
|
| 52 |
+
if dtype == "auto":
|
| 53 |
+
return "auto"
|
| 54 |
+
mapping = {
|
| 55 |
+
"float16": torch.float16,
|
| 56 |
+
"fp16": torch.float16,
|
| 57 |
+
"bfloat16": torch.bfloat16,
|
| 58 |
+
"bf16": torch.bfloat16,
|
| 59 |
+
"float32": torch.float32,
|
| 60 |
+
"fp32": torch.float32,
|
| 61 |
+
}
|
| 62 |
+
if dtype not in mapping:
|
| 63 |
+
raise ValueError(f"Unsupported dtype for transformers loader: {dtype}")
|
| 64 |
+
return mapping[dtype]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def set_seed(torch: object, seed: int) -> None:
|
| 68 |
+
random.seed(seed)
|
| 69 |
+
try:
|
| 70 |
+
torch.manual_seed(seed)
|
| 71 |
+
if hasattr(torch, "cuda"):
|
| 72 |
+
torch.cuda.manual_seed_all(seed)
|
| 73 |
+
except Exception:
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def generate_one(tokenizer: object,
|
| 78 |
+
model: object,
|
| 79 |
+
torch: object,
|
| 80 |
+
input_text: str,
|
| 81 |
+
config: DecodeConfig) -> List[int]:
|
| 82 |
+
encoded = tokenizer(input_text, return_tensors="pt", add_special_tokens=False)
|
| 83 |
+
device = next(model.parameters()).device
|
| 84 |
+
encoded = {key: value.to(device) for key, value in encoded.items()}
|
| 85 |
+
generation_kwargs = {
|
| 86 |
+
"max_new_tokens": config.max_new_tokens,
|
| 87 |
+
"do_sample": config.do_sample,
|
| 88 |
+
"temperature": config.temperature if config.do_sample else None,
|
| 89 |
+
"top_p": config.top_p,
|
| 90 |
+
"top_k": config.top_k if config.top_k > 0 else None,
|
| 91 |
+
"pad_token_id": tokenizer.eos_token_id,
|
| 92 |
+
"eos_token_id": tokenizer.eos_token_id,
|
| 93 |
+
"use_cache": True,
|
| 94 |
+
}
|
| 95 |
+
generation_kwargs = {
|
| 96 |
+
key: value for key, value in generation_kwargs.items()
|
| 97 |
+
if value is not None
|
| 98 |
+
}
|
| 99 |
+
with torch.inference_mode():
|
| 100 |
+
output = model.generate(**encoded, **generation_kwargs)
|
| 101 |
+
prompt_len = int(encoded["input_ids"].shape[-1])
|
| 102 |
+
return [int(token_id) for token_id in output[0, prompt_len:].detach().cpu().tolist()]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def make_variant(args: argparse.Namespace,
|
| 106 |
+
tokenizer: object,
|
| 107 |
+
backend_version: str) -> VariantInfo:
|
| 108 |
+
tok_hash = tokenizer_hash(tokenizer)
|
| 109 |
+
variant_id = args.variant_id or "-".join(
|
| 110 |
+
item for item in [
|
| 111 |
+
Path(str(args.model)).name,
|
| 112 |
+
args.quantization,
|
| 113 |
+
args.gpu,
|
| 114 |
+
tok_hash,
|
| 115 |
+
] if item
|
| 116 |
+
)
|
| 117 |
+
return VariantInfo(
|
| 118 |
+
variant_id=variant_id,
|
| 119 |
+
model=args.model,
|
| 120 |
+
tokenizer_hash=tok_hash,
|
| 121 |
+
tokenizer_name=tokenizer_name(tokenizer),
|
| 122 |
+
quantization=args.quantization,
|
| 123 |
+
gpu=args.gpu,
|
| 124 |
+
backend="transformers",
|
| 125 |
+
backend_version=backend_version,
|
| 126 |
+
dtype=args.dtype,
|
| 127 |
+
extra={
|
| 128 |
+
"cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"),
|
| 129 |
+
"device_map": args.device_map,
|
| 130 |
+
"attn_implementation": args.attn_implementation,
|
| 131 |
+
},
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def transformers_version() -> str:
|
| 136 |
+
try:
|
| 137 |
+
import transformers
|
| 138 |
+
|
| 139 |
+
return transformers.__version__
|
| 140 |
+
except Exception:
|
| 141 |
+
return ""
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 145 |
+
parser = argparse.ArgumentParser(
|
| 146 |
+
description="Generate canonical anchor outputs for a prompt dataset."
|
| 147 |
+
)
|
| 148 |
+
parser.add_argument("--input", default="data/prompts.jsonl")
|
| 149 |
+
parser.add_argument("--output", default="data/anchor_samples.jsonl")
|
| 150 |
+
parser.add_argument("--model", required=True)
|
| 151 |
+
parser.add_argument("--variant-id", default="")
|
| 152 |
+
parser.add_argument("--gpu", default="")
|
| 153 |
+
parser.add_argument("--quantization", default="bf16")
|
| 154 |
+
parser.add_argument("--dtype", default="auto")
|
| 155 |
+
parser.add_argument("--device-map", default="auto")
|
| 156 |
+
parser.add_argument("--trust-remote-code", action="store_true")
|
| 157 |
+
parser.add_argument("--attn-implementation", default=None)
|
| 158 |
+
parser.add_argument("--max-new-tokens", type=int, default=128)
|
| 159 |
+
parser.add_argument("--temperature", type=float, default=0.0)
|
| 160 |
+
parser.add_argument("--top-p", type=float, default=1.0)
|
| 161 |
+
parser.add_argument("--top-k", type=int, default=0)
|
| 162 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 163 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 164 |
+
args = parser.parse_args(argv)
|
| 165 |
+
|
| 166 |
+
tokenizer, model, torch = load_transformers(
|
| 167 |
+
args.model,
|
| 168 |
+
dtype=args.dtype,
|
| 169 |
+
device_map=args.device_map,
|
| 170 |
+
trust_remote_code=args.trust_remote_code,
|
| 171 |
+
attn_implementation=args.attn_implementation,
|
| 172 |
+
)
|
| 173 |
+
set_seed(torch, args.seed)
|
| 174 |
+
variant = make_variant(args, tokenizer, transformers_version())
|
| 175 |
+
config = DecodeConfig(
|
| 176 |
+
max_new_tokens=args.max_new_tokens,
|
| 177 |
+
temperature=args.temperature,
|
| 178 |
+
top_p=args.top_p,
|
| 179 |
+
top_k=args.top_k,
|
| 180 |
+
seed=args.seed,
|
| 181 |
+
do_sample=args.temperature > 0.0,
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
output_path = Path(args.output)
|
| 185 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 186 |
+
sample_count = 0
|
| 187 |
+
with output_path.open("w", encoding="utf-8") as handle:
|
| 188 |
+
for index, payload in enumerate(read_jsonl(Path(args.input)), start=1):
|
| 189 |
+
if args.limit and index > args.limit:
|
| 190 |
+
break
|
| 191 |
+
sample = parse_worker_sample(payload)
|
| 192 |
+
output_ids = generate_one(tokenizer, model, torch, sample.input_text, config)
|
| 193 |
+
input_ids = encode_text(tokenizer, sample.input_text)
|
| 194 |
+
output_text = decode_tokens(tokenizer, output_ids)
|
| 195 |
+
tok = Tokenization(
|
| 196 |
+
tokenizer_hash=variant.tokenizer_hash,
|
| 197 |
+
tokenizer_name=variant.tokenizer_name,
|
| 198 |
+
input_ids=input_ids,
|
| 199 |
+
output_ids=output_ids,
|
| 200 |
+
)
|
| 201 |
+
sample.canonical_output_text = output_text
|
| 202 |
+
sample.anchor_variant = variant.variant_id
|
| 203 |
+
sample.decode_config = config
|
| 204 |
+
sample.tokenizations[variant.tokenizer_hash] = tok
|
| 205 |
+
handle.write(json.dumps(
|
| 206 |
+
worker_sample_to_dict(sample),
|
| 207 |
+
ensure_ascii=False,
|
| 208 |
+
sort_keys=True,
|
| 209 |
+
))
|
| 210 |
+
handle.write("\n")
|
| 211 |
+
sample_count += 1
|
| 212 |
+
print(
|
| 213 |
+
f"[{index}] sample={sample.sample_id} "
|
| 214 |
+
f"input_tokens={len(input_ids)} output_tokens={len(output_ids)}"
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
write_json(output_path.with_suffix(output_path.suffix + ".metadata.json"), {
|
| 218 |
+
"metadata": runtime_metadata(sys.argv),
|
| 219 |
+
"args": vars(args),
|
| 220 |
+
"variant": dataclass_to_dict(variant),
|
| 221 |
+
"sample_count": sample_count,
|
| 222 |
+
})
|
| 223 |
+
print(f"Wrote {sample_count} anchor samples to {output_path}")
|
| 224 |
+
return 0
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if __name__ == "__main__":
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import random
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Dict, Iterable, List, Optional, Sequence
|
| 8 |
+
|
| 9 |
+
from .schema import runtime_metadata, stable_json_hash, write_json, write_jsonl
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
CATEGORIES = [
|
| 13 |
+
"short_qa",
|
| 14 |
+
"code",
|
| 15 |
+
"math_numeric",
|
| 16 |
+
"json_structured",
|
| 17 |
+
"mixed_language",
|
| 18 |
+
"summarization",
|
| 19 |
+
"logs",
|
| 20 |
+
"chat",
|
| 21 |
+
"needle",
|
| 22 |
+
"low_margin",
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
BASE_SNIPPETS = {
|
| 27 |
+
"short_qa": [
|
| 28 |
+
"Question: What is the operational risk of silently accepting a wrong model worker? Answer carefully.",
|
| 29 |
+
"Explain why deterministic verification should separate input evidence from output evidence.",
|
| 30 |
+
"Give a concise answer about why top-k support changes matter in logits verification.",
|
| 31 |
+
],
|
| 32 |
+
"code": [
|
| 33 |
+
"Review this Python function and continue with a corrected version:\n\n"
|
| 34 |
+
"def merge_counts(left, right):\n"
|
| 35 |
+
" out = left\n"
|
| 36 |
+
" for key, value in right.items():\n"
|
| 37 |
+
" out[key] = out.get(key, 0) + value\n"
|
| 38 |
+
" return out\n\n",
|
| 39 |
+
"Write a TypeScript helper that normalizes a worker trace row before saving it.",
|
| 40 |
+
"Explain this shell failure and propose a robust command sequence: CUDA out of memory while loading shard 19.",
|
| 41 |
+
],
|
| 42 |
+
"math_numeric": [
|
| 43 |
+
"Solve step by step, then give the final integer only: 173 * 29 - 418.",
|
| 44 |
+
"A service processes 384 requests per second per GPU. Estimate throughput for 7 GPUs after a 12% overhead.",
|
| 45 |
+
"Compare the numeric stability of accumulating 1024 small deltas in fp16, bf16, and fp32.",
|
| 46 |
+
],
|
| 47 |
+
"json_structured": [
|
| 48 |
+
"Return a JSON object with keys sample_id, verdict, confidence, and notes for a worker verification event.",
|
| 49 |
+
"Convert the following policy into YAML with exactly three top-level keys: identity, drift, action.",
|
| 50 |
+
"Produce a compact JSONL example for two token-depth trace rows.",
|
| 51 |
+
],
|
| 52 |
+
"mixed_language": [
|
| 53 |
+
"用中文解释为什么同上下文 teacher-forced replay 可以避免生成分叉带来的干扰。",
|
| 54 |
+
"Translate and summarize: 数值漂移需要按 token depth 分桶统计, because accumulated error is not uniform.",
|
| 55 |
+
"写一个中英混合的 incident note,主题是 worker 返回了错误量化版本的输出。",
|
| 56 |
+
],
|
| 57 |
+
"summarization": [
|
| 58 |
+
"Summarize the incident: a deployment silently switched one worker from BF16 to AWQ; latency improved, but verification drift increased.",
|
| 59 |
+
"Condense the following design note into bullet points while preserving the main constraints.",
|
| 60 |
+
"Write an executive summary of a GPU drift calibration experiment.",
|
| 61 |
+
],
|
| 62 |
+
"logs": [
|
| 63 |
+
"Analyze these logs and identify the likely failure: rank=0 loaded qwen shard, rank=1 timeout, verifier reported top-k fingerprint mismatch.",
|
| 64 |
+
"Given a trace with depth, selected_logprob, rank, and margin columns, describe what anomaly to look for.",
|
| 65 |
+
"Explain this monitoring alert: cumulative_nll_delta_p99 exceeded profile envelope for bucket 257-1024.",
|
| 66 |
+
],
|
| 67 |
+
"chat": [
|
| 68 |
+
"User: My worker output verifies on H100 but fails on 6000. Assistant:",
|
| 69 |
+
"System: You are a careful verification service.\nUser: Decide whether this trace belongs to Qwen3-32B BF16.",
|
| 70 |
+
"User: Why is output text equality insufficient for model identity verification?\nAssistant:",
|
| 71 |
+
],
|
| 72 |
+
"needle": [
|
| 73 |
+
"Remember this verifier nonce: TRACE-ANCHOR-73491. Later, state the nonce and explain its purpose.",
|
| 74 |
+
"The important token is hidden in the context: delta_margin_bucket=low_0.05_0.25. Use it in the final answer.",
|
| 75 |
+
"Store the key phrase 'same context, not same branch' and use it in a short explanation.",
|
| 76 |
+
],
|
| 77 |
+
"low_margin": [
|
| 78 |
+
"Choose the most plausible next word between two close alternatives and explain uncertainty.",
|
| 79 |
+
"Complete the sentence with one token if possible: The result is either valid or",
|
| 80 |
+
"Rank the next action when the verifier is almost tied between accept and reject.",
|
| 81 |
+
],
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
FILLERS = [
|
| 86 |
+
"The verifier records depth, selected token rank, top-k support, and cumulative negative log-likelihood.",
|
| 87 |
+
"A worker is accepted only when its fingerprint fits the calibrated same-weight cross-GPU envelope.",
|
| 88 |
+
"Low-margin positions are useful because small numerical changes can alter the argmax there.",
|
| 89 |
+
"Quantized models may preserve text quality while changing the local probability distribution.",
|
| 90 |
+
"The experiment freezes the canonical output so later comparisons stay on the same context path.",
|
| 91 |
+
"A trace row should be compact enough to store, but rich enough to explain failures.",
|
| 92 |
+
"Structured outputs, code, numbers, Chinese text, and log-like data exercise different tokenizer regions.",
|
| 93 |
+
"The profile should report percentiles by depth bucket instead of averaging over all positions.",
|
| 94 |
+
"Probe tokens make it harder for a non-anchor model to mimic only the selected output path.",
|
| 95 |
+
"The result is an identity-style fingerprint, not merely an output plausibility score.",
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def try_load_tokenizer(model: Optional[str], trust_remote_code: bool) -> Optional[object]:
|
| 100 |
+
if not model:
|
| 101 |
+
return None
|
| 102 |
+
try:
|
| 103 |
+
from transformers import AutoTokenizer
|
| 104 |
+
except Exception:
|
| 105 |
+
return None
|
| 106 |
+
return AutoTokenizer.from_pretrained(model, trust_remote_code=trust_remote_code)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def token_count(tokenizer: Optional[object], text: str) -> int:
|
| 110 |
+
if tokenizer is None:
|
| 111 |
+
return max(1, len(text.split()))
|
| 112 |
+
return len(tokenizer.encode(text, add_special_tokens=False))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def build_prompt(category: str,
|
| 116 |
+
target_tokens: int,
|
| 117 |
+
index: int,
|
| 118 |
+
rng: random.Random,
|
| 119 |
+
tokenizer: Optional[object]) -> str:
|
| 120 |
+
base = rng.choice(BASE_SNIPPETS[category])
|
| 121 |
+
header = (
|
| 122 |
+
f"Calibration sample {index}. Category: {category}. "
|
| 123 |
+
"Respond as the model would during a worker verification benchmark.\n\n"
|
| 124 |
+
)
|
| 125 |
+
parts = [header, base]
|
| 126 |
+
loops = 0
|
| 127 |
+
while token_count(tokenizer, "\n".join(parts)) < target_tokens:
|
| 128 |
+
loops += 1
|
| 129 |
+
filler = rng.choice(FILLERS)
|
| 130 |
+
if category == "json_structured":
|
| 131 |
+
filler = (
|
| 132 |
+
'{"depth": %d, "metric": "selected_logprob", '
|
| 133 |
+
'"note": "stable schema matters"}' % loops
|
| 134 |
+
)
|
| 135 |
+
elif category == "code":
|
| 136 |
+
filler = (
|
| 137 |
+
"def trace_step_%d(row):\n"
|
| 138 |
+
" return row.get('selected_logprob'), row.get('selected_rank')\n" % loops
|
| 139 |
+
)
|
| 140 |
+
elif category == "logs":
|
| 141 |
+
filler = (
|
| 142 |
+
"2026-06-25T12:%02d:00Z worker=%02d level=INFO "
|
| 143 |
+
"event=trace_depth depth=%d margin=0.%03d\n"
|
| 144 |
+
% (loops % 60, index % 32, loops * 17, rng.randint(10, 999))
|
| 145 |
+
)
|
| 146 |
+
elif category == "mixed_language":
|
| 147 |
+
filler = "同一个上下文路径用于比较漂移; the output path is frozen for replay."
|
| 148 |
+
elif category == "needle" and loops == 3:
|
| 149 |
+
filler = f"The hidden checksum for this sample is CHECK-{index:05d}-{target_tokens}."
|
| 150 |
+
parts.append(filler)
|
| 151 |
+
if loops > target_tokens * 4:
|
| 152 |
+
break
|
| 153 |
+
|
| 154 |
+
text = "\n".join(parts)
|
| 155 |
+
current = token_count(tokenizer, text)
|
| 156 |
+
if tokenizer is None or current <= int(target_tokens * 1.25):
|
| 157 |
+
return text
|
| 158 |
+
|
| 159 |
+
token_ids = tokenizer.encode(text, add_special_tokens=False)[:target_tokens]
|
| 160 |
+
return tokenizer.decode(token_ids, skip_special_tokens=False)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def parse_buckets(raw: str) -> List[int]:
|
| 164 |
+
buckets = []
|
| 165 |
+
for item in raw.split(","):
|
| 166 |
+
item = item.strip()
|
| 167 |
+
if item:
|
| 168 |
+
buckets.append(int(item))
|
| 169 |
+
if not buckets:
|
| 170 |
+
raise ValueError("At least one bucket is required")
|
| 171 |
+
return buckets
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def rows_for_dataset(buckets: Sequence[int],
|
| 175 |
+
per_bucket: int,
|
| 176 |
+
tokenizer: Optional[object],
|
| 177 |
+
seed: int) -> List[Dict[str, object]]:
|
| 178 |
+
rng = random.Random(seed)
|
| 179 |
+
rows: List[Dict[str, object]] = []
|
| 180 |
+
for bucket in buckets:
|
| 181 |
+
for index in range(per_bucket):
|
| 182 |
+
category = CATEGORIES[(index + bucket) % len(CATEGORIES)]
|
| 183 |
+
prompt = build_prompt(category, bucket, index, rng, tokenizer)
|
| 184 |
+
actual_tokens = token_count(tokenizer, prompt)
|
| 185 |
+
sample_id = stable_json_hash({
|
| 186 |
+
"bucket": bucket,
|
| 187 |
+
"index": index,
|
| 188 |
+
"category": category,
|
| 189 |
+
"input_text": prompt,
|
| 190 |
+
}, length=20)
|
| 191 |
+
rows.append({
|
| 192 |
+
"sample_id": sample_id,
|
| 193 |
+
"input_text": prompt,
|
| 194 |
+
"canonical_output_text": "",
|
| 195 |
+
"category": category,
|
| 196 |
+
"target_input_tokens": bucket,
|
| 197 |
+
"anchor_variant": "",
|
| 198 |
+
"decode_config": None,
|
| 199 |
+
"tokenizations": {},
|
| 200 |
+
"metadata": {
|
| 201 |
+
"generator": "worker_logits_verify.generate_prompts",
|
| 202 |
+
"bucket_input_tokens": bucket,
|
| 203 |
+
"actual_input_tokens": actual_tokens,
|
| 204 |
+
"bucket_index": index,
|
| 205 |
+
},
|
| 206 |
+
})
|
| 207 |
+
return rows
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 211 |
+
parser = argparse.ArgumentParser(
|
| 212 |
+
description="Generate a calibration input dataset across token-length buckets."
|
| 213 |
+
)
|
| 214 |
+
parser.add_argument("--output", default="data/prompts.jsonl")
|
| 215 |
+
parser.add_argument("--model", default=None,
|
| 216 |
+
help="Optional tokenizer model used to measure token lengths.")
|
| 217 |
+
parser.add_argument("--trust-remote-code", action="store_true")
|
| 218 |
+
parser.add_argument("--buckets", default="32,128,512,2048,8192,16384")
|
| 219 |
+
parser.add_argument("--per-bucket", type=int, default=50)
|
| 220 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 221 |
+
args = parser.parse_args(argv)
|
| 222 |
+
|
| 223 |
+
tokenizer = try_load_tokenizer(args.model, args.trust_remote_code)
|
| 224 |
+
buckets = parse_buckets(args.buckets)
|
| 225 |
+
rows = rows_for_dataset(
|
| 226 |
+
buckets=buckets,
|
| 227 |
+
per_bucket=args.per_bucket,
|
| 228 |
+
tokenizer=tokenizer,
|
| 229 |
+
seed=args.seed,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
output_path = Path(args.output)
|
| 233 |
+
write_jsonl(output_path, rows)
|
| 234 |
+
write_json(output_path.with_suffix(output_path.suffix + ".metadata.json"), {
|
| 235 |
+
"metadata": runtime_metadata(sys.argv),
|
| 236 |
+
"args": vars(args),
|
| 237 |
+
"sample_count": len(rows),
|
| 238 |
+
"buckets": buckets,
|
| 239 |
+
})
|
| 240 |
+
print(f"Wrote {len(rows)} samples to {output_path}")
|
| 241 |
+
return 0
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
if __name__ == "__main__":
|
| 245 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/src/worker_logits_verify/metrics.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from typing import Dict, Iterable, List, Mapping, Sequence
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def safe_float(value: object, default: float = float("nan")) -> float:
|
| 8 |
+
try:
|
| 9 |
+
return float(value)
|
| 10 |
+
except (TypeError, ValueError):
|
| 11 |
+
return default
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def sorted_token_ids(token_ids: Iterable[str]) -> List[str]:
|
| 15 |
+
return sorted((str(token_id) for token_id in token_ids), key=lambda item: int(item))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def normalize_logprobs(logprobs: Sequence[float]) -> List[float]:
|
| 19 |
+
if not logprobs:
|
| 20 |
+
return []
|
| 21 |
+
max_logprob = max(logprobs)
|
| 22 |
+
if not math.isfinite(max_logprob):
|
| 23 |
+
return [float("nan") for _ in logprobs]
|
| 24 |
+
weights = [math.exp(value - max_logprob) for value in logprobs]
|
| 25 |
+
total = sum(weights)
|
| 26 |
+
if total <= 0.0 or not math.isfinite(total):
|
| 27 |
+
return [float("nan") for _ in logprobs]
|
| 28 |
+
return [value / total for value in weights]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def cosine(left: Sequence[float], right: Sequence[float]) -> float:
|
| 32 |
+
if not left or not right or len(left) != len(right):
|
| 33 |
+
return float("nan")
|
| 34 |
+
dot = sum(a * b for a, b in zip(left, right))
|
| 35 |
+
left_norm = math.sqrt(sum(a * a for a in left))
|
| 36 |
+
right_norm = math.sqrt(sum(b * b for b in right))
|
| 37 |
+
if left_norm == 0.0 or right_norm == 0.0:
|
| 38 |
+
return float("nan")
|
| 39 |
+
return dot / (left_norm * right_norm)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def kl_divergence(p: Sequence[float], q: Sequence[float]) -> float:
|
| 43 |
+
if not p or not q or len(p) != len(q):
|
| 44 |
+
return float("nan")
|
| 45 |
+
total = 0.0
|
| 46 |
+
for p_value, q_value in zip(p, q):
|
| 47 |
+
if p_value <= 0.0:
|
| 48 |
+
continue
|
| 49 |
+
if q_value <= 0.0:
|
| 50 |
+
return float("inf")
|
| 51 |
+
total += p_value * math.log(p_value / q_value)
|
| 52 |
+
return total
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def js_divergence(p: Sequence[float], q: Sequence[float]) -> float:
|
| 56 |
+
if not p or not q or len(p) != len(q):
|
| 57 |
+
return float("nan")
|
| 58 |
+
middle = [(p_value + q_value) / 2.0 for p_value, q_value in zip(p, q)]
|
| 59 |
+
return 0.5 * kl_divergence(p, middle) + 0.5 * kl_divergence(q, middle)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def logprob_value(logprobs: Mapping[str, Mapping[str, object]],
|
| 63 |
+
token_id: str,
|
| 64 |
+
missing_logprob: float) -> float:
|
| 65 |
+
if token_id not in logprobs:
|
| 66 |
+
return missing_logprob
|
| 67 |
+
return safe_float(logprobs[token_id].get("logprob"))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def raw_logit_value(logprobs: Mapping[str, Mapping[str, object]],
|
| 71 |
+
token_id: str,
|
| 72 |
+
missing_logit: float = float("nan")) -> float:
|
| 73 |
+
if token_id not in logprobs:
|
| 74 |
+
return missing_logit
|
| 75 |
+
return safe_float(logprobs[token_id].get("raw_logit"))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def probability_metrics(left: Mapping[str, Mapping[str, object]],
|
| 79 |
+
right: Mapping[str, Mapping[str, object]],
|
| 80 |
+
token_ids: Sequence[str],
|
| 81 |
+
missing_logprob: float) -> Dict[str, float]:
|
| 82 |
+
left_logprobs = [
|
| 83 |
+
logprob_value(left, token_id, missing_logprob)
|
| 84 |
+
for token_id in token_ids
|
| 85 |
+
]
|
| 86 |
+
right_logprobs = [
|
| 87 |
+
logprob_value(right, token_id, missing_logprob)
|
| 88 |
+
for token_id in token_ids
|
| 89 |
+
]
|
| 90 |
+
left_probs = normalize_logprobs(left_logprobs)
|
| 91 |
+
right_probs = normalize_logprobs(right_logprobs)
|
| 92 |
+
return {
|
| 93 |
+
"prob_cosine": cosine(left_probs, right_probs),
|
| 94 |
+
"kl_left_to_right": kl_divergence(left_probs, right_probs),
|
| 95 |
+
"kl_right_to_left": kl_divergence(right_probs, left_probs),
|
| 96 |
+
"js_divergence": js_divergence(left_probs, right_probs),
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def quantile(values: Sequence[float], q: float) -> float:
|
| 101 |
+
clean = sorted(value for value in values if math.isfinite(value))
|
| 102 |
+
if not clean:
|
| 103 |
+
return float("nan")
|
| 104 |
+
if len(clean) == 1:
|
| 105 |
+
return clean[0]
|
| 106 |
+
position = (len(clean) - 1) * q
|
| 107 |
+
lower = int(math.floor(position))
|
| 108 |
+
upper = int(math.ceil(position))
|
| 109 |
+
if lower == upper:
|
| 110 |
+
return clean[lower]
|
| 111 |
+
frac = position - lower
|
| 112 |
+
return clean[lower] * (1.0 - frac) + clean[upper] * frac
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def depth_bucket(depth: int) -> str:
|
| 116 |
+
depth = int(depth)
|
| 117 |
+
if depth <= 16:
|
| 118 |
+
return "0000-0016"
|
| 119 |
+
if depth <= 64:
|
| 120 |
+
return "0017-0064"
|
| 121 |
+
if depth <= 256:
|
| 122 |
+
return "0065-0256"
|
| 123 |
+
if depth <= 1024:
|
| 124 |
+
return "0257-1024"
|
| 125 |
+
return "1025+"
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def margin_bucket(margin: float) -> str:
|
| 129 |
+
if not math.isfinite(margin):
|
| 130 |
+
return "unknown"
|
| 131 |
+
if margin < 0.05:
|
| 132 |
+
return "tie_lt_0.05"
|
| 133 |
+
if margin < 0.25:
|
| 134 |
+
return "low_0.05_0.25"
|
| 135 |
+
if margin < 1.0:
|
| 136 |
+
return "mid_0.25_1"
|
| 137 |
+
return "high_ge_1"
|
tools/worker_logits_verify/src/worker_logits_verify/run_vllm_worker_verify.py
ADDED
|
@@ -0,0 +1,546 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import shlex
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
import time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any, Dict, List, Optional, Sequence
|
| 10 |
+
|
| 11 |
+
from .schema import runtime_metadata, write_json
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def log(message: str) -> None:
|
| 15 |
+
print(message, flush=True)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def slugify(value: str, default: str = "model") -> str:
|
| 19 |
+
raw = value.rstrip("/")
|
| 20 |
+
name = Path(raw).name if raw else ""
|
| 21 |
+
if not name:
|
| 22 |
+
name = raw or default
|
| 23 |
+
chars = []
|
| 24 |
+
for char in name.lower():
|
| 25 |
+
if char.isalnum():
|
| 26 |
+
chars.append(char)
|
| 27 |
+
elif char in {"-", "_", "."}:
|
| 28 |
+
chars.append(char)
|
| 29 |
+
else:
|
| 30 |
+
chars.append("-")
|
| 31 |
+
slug = "".join(chars).strip("-_.")
|
| 32 |
+
while "--" in slug:
|
| 33 |
+
slug = slug.replace("--", "-")
|
| 34 |
+
return slug or default
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def default_run_id(baseline_model: str, comparison_model: str) -> str:
|
| 38 |
+
timestamp = time.strftime("%Y%m%d-%H%M%S")
|
| 39 |
+
return (
|
| 40 |
+
f"{timestamp}_"
|
| 41 |
+
f"{slugify(baseline_model, 'baseline')}_vs_"
|
| 42 |
+
f"{slugify(comparison_model, 'comparison')}"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def validate_run_id(parser: argparse.ArgumentParser, run_id: str) -> None:
|
| 47 |
+
path = Path(run_id)
|
| 48 |
+
if path.is_absolute() or any(part == ".." for part in path.parts):
|
| 49 |
+
parser.error("--run-id must be a relative path and must not contain '..'")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def add_value(command: List[str], flag: str, value: Any, *, include_empty: bool = False) -> None:
|
| 53 |
+
if value is None:
|
| 54 |
+
return
|
| 55 |
+
if value == "" and not include_empty:
|
| 56 |
+
return
|
| 57 |
+
command.extend([flag, str(value)])
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def add_positive_int(command: List[str], flag: str, value: Optional[int]) -> None:
|
| 61 |
+
if value is not None and value > 0:
|
| 62 |
+
command.extend([flag, str(value)])
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def add_float(command: List[str], flag: str, value: Optional[float]) -> None:
|
| 66 |
+
if value is not None:
|
| 67 |
+
command.extend([flag, str(value)])
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def add_common_vllm_args(
|
| 71 |
+
command: List[str],
|
| 72 |
+
args: argparse.Namespace,
|
| 73 |
+
*,
|
| 74 |
+
role: str,
|
| 75 |
+
) -> None:
|
| 76 |
+
tensor_parallel_size = (
|
| 77 |
+
getattr(args, f"{role}_tensor_parallel_size")
|
| 78 |
+
or args.tensor_parallel_size
|
| 79 |
+
)
|
| 80 |
+
gpu_memory_utilization = (
|
| 81 |
+
getattr(args, f"{role}_gpu_memory_utilization")
|
| 82 |
+
if getattr(args, f"{role}_gpu_memory_utilization") is not None
|
| 83 |
+
else args.gpu_memory_utilization
|
| 84 |
+
)
|
| 85 |
+
max_model_len = (
|
| 86 |
+
getattr(args, f"{role}_max_model_len")
|
| 87 |
+
or args.max_model_len
|
| 88 |
+
)
|
| 89 |
+
max_num_seqs = (
|
| 90 |
+
getattr(args, f"{role}_max_num_seqs")
|
| 91 |
+
or args.max_num_seqs
|
| 92 |
+
)
|
| 93 |
+
max_num_batched_tokens = (
|
| 94 |
+
getattr(args, f"{role}_max_num_batched_tokens")
|
| 95 |
+
or args.max_num_batched_tokens
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
add_value(command, "--tensor-parallel-size", tensor_parallel_size)
|
| 99 |
+
add_float(command, "--gpu-memory-utilization", gpu_memory_utilization)
|
| 100 |
+
add_positive_int(command, "--max-model-len", max_model_len)
|
| 101 |
+
add_positive_int(command, "--max-num-seqs", max_num_seqs)
|
| 102 |
+
add_positive_int(command, "--max-num-batched-tokens", max_num_batched_tokens)
|
| 103 |
+
add_positive_int(command, "--max-logprobs", args.max_logprobs)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def base_command(args: argparse.Namespace, module: str, console_script: str) -> List[str]:
|
| 107 |
+
if args.command_mode == "console":
|
| 108 |
+
return [console_script]
|
| 109 |
+
return [args.python, "-m", module]
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def build_generate_prompts_command(
|
| 113 |
+
args: argparse.Namespace,
|
| 114 |
+
prompts_path: Path,
|
| 115 |
+
) -> List[str]:
|
| 116 |
+
command = base_command(
|
| 117 |
+
args,
|
| 118 |
+
"worker_logits_verify.generate_prompts",
|
| 119 |
+
"worker-logits-generate-prompts",
|
| 120 |
+
)
|
| 121 |
+
command.extend([
|
| 122 |
+
"--model",
|
| 123 |
+
args.prompt_tokenizer_model or args.baseline_model,
|
| 124 |
+
"--buckets",
|
| 125 |
+
args.buckets,
|
| 126 |
+
"--per-bucket",
|
| 127 |
+
str(args.per_bucket),
|
| 128 |
+
"--output",
|
| 129 |
+
str(prompts_path),
|
| 130 |
+
"--seed",
|
| 131 |
+
str(args.prompt_seed),
|
| 132 |
+
])
|
| 133 |
+
if args.trust_remote_code:
|
| 134 |
+
command.append("--trust-remote-code")
|
| 135 |
+
command.extend(args.generate_extra_arg)
|
| 136 |
+
return command
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def build_collect_evidence_command(
|
| 140 |
+
args: argparse.Namespace,
|
| 141 |
+
prompts_path: Path,
|
| 142 |
+
evidence_path: Path,
|
| 143 |
+
baseline_variant_id: str,
|
| 144 |
+
) -> List[str]:
|
| 145 |
+
command = base_command(
|
| 146 |
+
args,
|
| 147 |
+
"worker_logits_verify.collect_vllm_worker_evidence",
|
| 148 |
+
"worker-logits-collect-vllm-evidence",
|
| 149 |
+
)
|
| 150 |
+
command.extend([
|
| 151 |
+
"--input",
|
| 152 |
+
str(prompts_path),
|
| 153 |
+
"--output",
|
| 154 |
+
str(evidence_path),
|
| 155 |
+
"--model",
|
| 156 |
+
args.baseline_model,
|
| 157 |
+
"--variant-id",
|
| 158 |
+
baseline_variant_id,
|
| 159 |
+
"--quantization",
|
| 160 |
+
args.baseline_quantization,
|
| 161 |
+
"--dtype",
|
| 162 |
+
args.baseline_dtype,
|
| 163 |
+
"--max-new-tokens",
|
| 164 |
+
str(args.max_new_tokens),
|
| 165 |
+
"--logprobs",
|
| 166 |
+
str(args.logprobs),
|
| 167 |
+
"--temperature",
|
| 168 |
+
str(args.temperature),
|
| 169 |
+
"--top-p",
|
| 170 |
+
str(args.top_p),
|
| 171 |
+
"--top-k",
|
| 172 |
+
str(args.top_k),
|
| 173 |
+
"--seed",
|
| 174 |
+
str(args.seed),
|
| 175 |
+
"--batch-size",
|
| 176 |
+
str(args.worker_batch_size),
|
| 177 |
+
])
|
| 178 |
+
add_value(command, "--gpu", args.baseline_gpu)
|
| 179 |
+
if args.trust_remote_code:
|
| 180 |
+
command.append("--trust-remote-code")
|
| 181 |
+
add_common_vllm_args(command, args, role="baseline")
|
| 182 |
+
add_positive_int(command, "--limit", args.limit)
|
| 183 |
+
command.extend(args.worker_extra_arg)
|
| 184 |
+
return command
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def build_verify_evidence_command(
|
| 188 |
+
args: argparse.Namespace,
|
| 189 |
+
evidence_path: Path,
|
| 190 |
+
output_dir: Path,
|
| 191 |
+
comparison_variant_id: str,
|
| 192 |
+
) -> List[str]:
|
| 193 |
+
command = base_command(
|
| 194 |
+
args,
|
| 195 |
+
"worker_logits_verify.verify_vllm_worker_evidence",
|
| 196 |
+
"worker-logits-verify-vllm-evidence",
|
| 197 |
+
)
|
| 198 |
+
command.extend([
|
| 199 |
+
"--evidence",
|
| 200 |
+
str(evidence_path),
|
| 201 |
+
"--output-dir",
|
| 202 |
+
str(output_dir),
|
| 203 |
+
"--model",
|
| 204 |
+
args.comparison_model,
|
| 205 |
+
"--variant-id",
|
| 206 |
+
comparison_variant_id,
|
| 207 |
+
"--quantization",
|
| 208 |
+
args.comparison_quantization,
|
| 209 |
+
"--dtype",
|
| 210 |
+
args.comparison_dtype,
|
| 211 |
+
"--prompt-logprobs",
|
| 212 |
+
str(args.prompt_logprobs),
|
| 213 |
+
"--temperature",
|
| 214 |
+
str(args.temperature),
|
| 215 |
+
"--top-p",
|
| 216 |
+
str(args.top_p),
|
| 217 |
+
"--top-k",
|
| 218 |
+
str(args.top_k),
|
| 219 |
+
"--seed",
|
| 220 |
+
str(args.seed),
|
| 221 |
+
"--batch-size",
|
| 222 |
+
str(args.verifier_batch_size),
|
| 223 |
+
"--missing-logprob",
|
| 224 |
+
str(args.missing_logprob),
|
| 225 |
+
])
|
| 226 |
+
add_value(command, "--gpu", args.comparison_gpu)
|
| 227 |
+
if args.trust_remote_code:
|
| 228 |
+
command.append("--trust-remote-code")
|
| 229 |
+
add_common_vllm_args(command, args, role="comparison")
|
| 230 |
+
add_positive_int(command, "--limit", args.limit)
|
| 231 |
+
add_positive_int(command, "--max-total-tokens", args.max_total_tokens)
|
| 232 |
+
command.extend(args.verifier_extra_arg)
|
| 233 |
+
return command
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def build_summarize_command(args: argparse.Namespace, verifier_output_dir: Path) -> List[str]:
|
| 237 |
+
command = base_command(
|
| 238 |
+
args,
|
| 239 |
+
"worker_logits_verify.summarize_worker_verify",
|
| 240 |
+
"worker-logits-summarize-worker-verify",
|
| 241 |
+
)
|
| 242 |
+
command.extend([
|
| 243 |
+
"--metrics",
|
| 244 |
+
str(verifier_output_dir),
|
| 245 |
+
"--output-dir",
|
| 246 |
+
str(verifier_output_dir / "distribution"),
|
| 247 |
+
])
|
| 248 |
+
command.extend(args.summarize_extra_arg)
|
| 249 |
+
return command
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def path_exists(path: Path, *, is_dir: bool = False) -> bool:
|
| 253 |
+
return path.is_dir() if is_dir else path.exists()
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def decide_step_status(
|
| 257 |
+
output_path: Path,
|
| 258 |
+
args: argparse.Namespace,
|
| 259 |
+
*,
|
| 260 |
+
is_dir: bool = False,
|
| 261 |
+
) -> str:
|
| 262 |
+
if args.dry_run:
|
| 263 |
+
return "run"
|
| 264 |
+
if path_exists(output_path, is_dir=is_dir):
|
| 265 |
+
if args.force:
|
| 266 |
+
return "run"
|
| 267 |
+
if args.resume:
|
| 268 |
+
return "skip"
|
| 269 |
+
kind = "directory" if is_dir else "file"
|
| 270 |
+
raise FileExistsError(
|
| 271 |
+
f"Refusing to overwrite existing {kind}: {output_path}. "
|
| 272 |
+
"Use --force to overwrite it or --resume to reuse completed outputs."
|
| 273 |
+
)
|
| 274 |
+
return "run"
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def run_step(step: Dict[str, Any], *, dry_run: bool) -> None:
|
| 278 |
+
command = step["command"]
|
| 279 |
+
log("")
|
| 280 |
+
log(f"==> {step['name']}")
|
| 281 |
+
log(f"$ {shlex.join(command)}")
|
| 282 |
+
if dry_run:
|
| 283 |
+
step["status"] = "dry_run"
|
| 284 |
+
return
|
| 285 |
+
start = time.time()
|
| 286 |
+
try:
|
| 287 |
+
subprocess.run(command, check=True)
|
| 288 |
+
except subprocess.CalledProcessError as exc:
|
| 289 |
+
step["status"] = "failed"
|
| 290 |
+
step["returncode"] = exc.returncode
|
| 291 |
+
step["elapsed_seconds"] = time.time() - start
|
| 292 |
+
raise
|
| 293 |
+
step["status"] = "completed"
|
| 294 |
+
step["elapsed_seconds"] = time.time() - start
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def serializable_args(args: argparse.Namespace) -> Dict[str, Any]:
|
| 298 |
+
return {key: value for key, value in sorted(vars(args).items())}
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def write_pipeline_metadata(path: Path, payload: Dict[str, Any]) -> None:
|
| 302 |
+
write_json(path, payload)
|
| 303 |
+
log(f"Wrote {path}")
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def make_parser() -> argparse.ArgumentParser:
|
| 307 |
+
parser = argparse.ArgumentParser(
|
| 308 |
+
description=(
|
| 309 |
+
"Run the vLLM worker evidence pipeline: generate prompts, collect "
|
| 310 |
+
"baseline worker evidence, verify it with a comparison model, and "
|
| 311 |
+
"summarize the final metrics."
|
| 312 |
+
)
|
| 313 |
+
)
|
| 314 |
+
parser.add_argument("--baseline-model", "--worker-model", required=True,
|
| 315 |
+
help="Model repo/path used to generate worker evidence.")
|
| 316 |
+
parser.add_argument("--comparison-model", "--verifier-model", required=True,
|
| 317 |
+
help="Model repo/path used to recompute verifier prompt logprobs.")
|
| 318 |
+
parser.add_argument("--output-root", default="results/vllm_worker_verify_runs")
|
| 319 |
+
parser.add_argument("--run-id", default=None,
|
| 320 |
+
help="Relative run directory name under --output-root.")
|
| 321 |
+
parser.add_argument("--prompts", default=None,
|
| 322 |
+
help="Existing prompts.jsonl to reuse. If omitted, prompts are generated.")
|
| 323 |
+
parser.add_argument("--prompt-tokenizer-model", default=None,
|
| 324 |
+
help="Tokenizer model for prompt length measurement. Defaults to --baseline-model.")
|
| 325 |
+
parser.add_argument("--buckets", default="32,128,512,2048,8192,16384")
|
| 326 |
+
parser.add_argument("--per-bucket", type=int, default=50)
|
| 327 |
+
parser.add_argument("--prompt-seed", type=int, default=0)
|
| 328 |
+
|
| 329 |
+
parser.add_argument("--baseline-variant-id", default=None)
|
| 330 |
+
parser.add_argument("--comparison-variant-id", default=None)
|
| 331 |
+
parser.add_argument("--baseline-gpu", default="")
|
| 332 |
+
parser.add_argument("--comparison-gpu", default="")
|
| 333 |
+
parser.add_argument("--baseline-quantization", default="bf16")
|
| 334 |
+
parser.add_argument("--comparison-quantization", default="bf16")
|
| 335 |
+
parser.add_argument("--baseline-dtype", default="auto")
|
| 336 |
+
parser.add_argument("--comparison-dtype", default="auto")
|
| 337 |
+
|
| 338 |
+
parser.add_argument("--max-new-tokens", type=int, default=128)
|
| 339 |
+
parser.add_argument("--logprobs", type=int, default=64)
|
| 340 |
+
parser.add_argument("--prompt-logprobs", type=int, default=64)
|
| 341 |
+
parser.add_argument("--max-logprobs", type=int, default=64)
|
| 342 |
+
parser.add_argument("--worker-batch-size", type=int, default=8)
|
| 343 |
+
parser.add_argument("--verifier-batch-size", type=int, default=4)
|
| 344 |
+
parser.add_argument("--temperature", type=float, default=0.0)
|
| 345 |
+
parser.add_argument("--top-p", type=float, default=1.0)
|
| 346 |
+
parser.add_argument("--top-k", type=int, default=0)
|
| 347 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 348 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 349 |
+
parser.add_argument("--missing-logprob", type=float, default=-100.0)
|
| 350 |
+
parser.add_argument("--max-total-tokens", type=int, default=0)
|
| 351 |
+
|
| 352 |
+
parser.add_argument("--trust-remote-code", action="store_true")
|
| 353 |
+
parser.add_argument("--tensor-parallel-size", type=int, default=1,
|
| 354 |
+
help="Default tensor parallel size for both vLLM stages.")
|
| 355 |
+
parser.add_argument("--baseline-tensor-parallel-size", type=int, default=None)
|
| 356 |
+
parser.add_argument("--comparison-tensor-parallel-size", type=int, default=None)
|
| 357 |
+
parser.add_argument("--gpu-memory-utilization", type=float, default=None)
|
| 358 |
+
parser.add_argument("--baseline-gpu-memory-utilization", type=float, default=None)
|
| 359 |
+
parser.add_argument("--comparison-gpu-memory-utilization", type=float, default=None)
|
| 360 |
+
parser.add_argument("--max-model-len", type=int, default=None)
|
| 361 |
+
parser.add_argument("--baseline-max-model-len", type=int, default=None)
|
| 362 |
+
parser.add_argument("--comparison-max-model-len", type=int, default=None)
|
| 363 |
+
parser.add_argument("--max-num-seqs", type=int, default=None)
|
| 364 |
+
parser.add_argument("--baseline-max-num-seqs", type=int, default=None)
|
| 365 |
+
parser.add_argument("--comparison-max-num-seqs", type=int, default=None)
|
| 366 |
+
parser.add_argument("--max-num-batched-tokens", type=int, default=None)
|
| 367 |
+
parser.add_argument("--baseline-max-num-batched-tokens", type=int, default=None)
|
| 368 |
+
parser.add_argument("--comparison-max-num-batched-tokens", type=int, default=None)
|
| 369 |
+
|
| 370 |
+
parser.add_argument("--skip-distribution-summary", action="store_true",
|
| 371 |
+
help="Do not run worker-logits-summarize-worker-verify after verification.")
|
| 372 |
+
parser.add_argument("--resume", action="store_true",
|
| 373 |
+
help="Reuse already completed step outputs.")
|
| 374 |
+
parser.add_argument("--force", action="store_true",
|
| 375 |
+
help="Overwrite existing step outputs.")
|
| 376 |
+
parser.add_argument("--dry-run", action="store_true",
|
| 377 |
+
help="Print the planned commands without executing them.")
|
| 378 |
+
parser.add_argument("--python", default=sys.executable,
|
| 379 |
+
help="Python executable used for module-mode subprocesses.")
|
| 380 |
+
parser.add_argument("--command-mode", choices=["module", "console"], default="module",
|
| 381 |
+
help="Use python -m modules or installed console scripts.")
|
| 382 |
+
parser.add_argument("--generate-extra-arg", action="append", default=[],
|
| 383 |
+
help="Extra argument passed to prompt generation. Repeat as needed.")
|
| 384 |
+
parser.add_argument("--worker-extra-arg", action="append", default=[],
|
| 385 |
+
help="Extra argument passed to worker evidence collection. Repeat as needed.")
|
| 386 |
+
parser.add_argument("--verifier-extra-arg", action="append", default=[],
|
| 387 |
+
help="Extra argument passed to verifier evidence comparison. Repeat as needed.")
|
| 388 |
+
parser.add_argument("--summarize-extra-arg", action="append", default=[],
|
| 389 |
+
help="Extra argument passed to distribution summarization. Repeat as needed.")
|
| 390 |
+
return parser
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 394 |
+
parser = make_parser()
|
| 395 |
+
args = parser.parse_args(argv)
|
| 396 |
+
|
| 397 |
+
if args.force and args.resume:
|
| 398 |
+
parser.error("--force and --resume cannot be used together")
|
| 399 |
+
|
| 400 |
+
run_id = args.run_id or default_run_id(args.baseline_model, args.comparison_model)
|
| 401 |
+
validate_run_id(parser, run_id)
|
| 402 |
+
|
| 403 |
+
baseline_variant_id = (
|
| 404 |
+
args.baseline_variant_id
|
| 405 |
+
or f"{slugify(args.baseline_model, 'baseline')}-baseline"
|
| 406 |
+
)
|
| 407 |
+
comparison_variant_id = (
|
| 408 |
+
args.comparison_variant_id
|
| 409 |
+
or f"{slugify(args.comparison_model, 'comparison')}-comparison"
|
| 410 |
+
)
|
| 411 |
+
baseline_slug = slugify(baseline_variant_id, "baseline")
|
| 412 |
+
comparison_slug = slugify(comparison_variant_id, "comparison")
|
| 413 |
+
|
| 414 |
+
run_dir = Path(args.output_root) / run_id
|
| 415 |
+
data_dir = run_dir / "data"
|
| 416 |
+
worker_verify_root = run_dir / "worker_verify"
|
| 417 |
+
prompts_path = Path(args.prompts) if args.prompts else data_dir / "prompts.jsonl"
|
| 418 |
+
evidence_path = data_dir / f"worker_evidence.{baseline_slug}.jsonl"
|
| 419 |
+
verifier_output_dir = (
|
| 420 |
+
worker_verify_root
|
| 421 |
+
/ f"{baseline_slug}_worker_vs_{comparison_slug}_verifier"
|
| 422 |
+
)
|
| 423 |
+
pipeline_metadata_path = run_dir / "pipeline_metadata.json"
|
| 424 |
+
|
| 425 |
+
if args.prompts and not args.dry_run and not prompts_path.exists():
|
| 426 |
+
parser.error(f"--prompts does not exist: {prompts_path}")
|
| 427 |
+
|
| 428 |
+
if not args.dry_run:
|
| 429 |
+
data_dir.mkdir(parents=True, exist_ok=True)
|
| 430 |
+
worker_verify_root.mkdir(parents=True, exist_ok=True)
|
| 431 |
+
|
| 432 |
+
steps: List[Dict[str, Any]] = []
|
| 433 |
+
if args.prompts:
|
| 434 |
+
steps.append({
|
| 435 |
+
"name": "reuse prompts",
|
| 436 |
+
"status": "skipped",
|
| 437 |
+
"reason": "--prompts was provided",
|
| 438 |
+
"output": str(prompts_path),
|
| 439 |
+
})
|
| 440 |
+
else:
|
| 441 |
+
steps.append({
|
| 442 |
+
"name": "generate prompts",
|
| 443 |
+
"command": build_generate_prompts_command(args, prompts_path),
|
| 444 |
+
"output": str(prompts_path),
|
| 445 |
+
"status": "planned",
|
| 446 |
+
})
|
| 447 |
+
|
| 448 |
+
steps.extend([
|
| 449 |
+
{
|
| 450 |
+
"name": "collect worker evidence",
|
| 451 |
+
"command": build_collect_evidence_command(
|
| 452 |
+
args,
|
| 453 |
+
prompts_path,
|
| 454 |
+
evidence_path,
|
| 455 |
+
baseline_variant_id,
|
| 456 |
+
),
|
| 457 |
+
"output": str(evidence_path),
|
| 458 |
+
"status": "planned",
|
| 459 |
+
},
|
| 460 |
+
{
|
| 461 |
+
"name": "verify worker evidence",
|
| 462 |
+
"command": build_verify_evidence_command(
|
| 463 |
+
args,
|
| 464 |
+
evidence_path,
|
| 465 |
+
verifier_output_dir,
|
| 466 |
+
comparison_variant_id,
|
| 467 |
+
),
|
| 468 |
+
"output": str(verifier_output_dir),
|
| 469 |
+
"status": "planned",
|
| 470 |
+
},
|
| 471 |
+
])
|
| 472 |
+
if not args.skip_distribution_summary:
|
| 473 |
+
steps.append({
|
| 474 |
+
"name": "summarize verifier metrics",
|
| 475 |
+
"command": build_summarize_command(args, verifier_output_dir),
|
| 476 |
+
"output": str(verifier_output_dir / "distribution"),
|
| 477 |
+
"status": "planned",
|
| 478 |
+
})
|
| 479 |
+
|
| 480 |
+
payload: Dict[str, Any] = {
|
| 481 |
+
"metadata": runtime_metadata(sys.argv),
|
| 482 |
+
"args": serializable_args(args),
|
| 483 |
+
"run_id": run_id,
|
| 484 |
+
"run_dir": str(run_dir),
|
| 485 |
+
"baseline_variant_id": baseline_variant_id,
|
| 486 |
+
"comparison_variant_id": comparison_variant_id,
|
| 487 |
+
"paths": {
|
| 488 |
+
"prompts": str(prompts_path),
|
| 489 |
+
"worker_evidence": str(evidence_path),
|
| 490 |
+
"verifier_output_dir": str(verifier_output_dir),
|
| 491 |
+
"depth_metrics": str(verifier_output_dir / "worker_vs_verifier_depth_metrics.csv"),
|
| 492 |
+
"summary": str(verifier_output_dir / "summary.md"),
|
| 493 |
+
"distribution_summary": str(verifier_output_dir / "distribution" / "summary.md"),
|
| 494 |
+
},
|
| 495 |
+
"steps": steps,
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
try:
|
| 499 |
+
for step in steps:
|
| 500 |
+
if "command" not in step:
|
| 501 |
+
log(f"Skipping {step['name']}: {step.get('reason', '')}")
|
| 502 |
+
continue
|
| 503 |
+
if step["name"] == "verify worker evidence":
|
| 504 |
+
status = decide_step_status(
|
| 505 |
+
verifier_output_dir / "worker_vs_verifier_depth_metrics.csv",
|
| 506 |
+
args,
|
| 507 |
+
)
|
| 508 |
+
elif step["name"] == "summarize verifier metrics":
|
| 509 |
+
status = decide_step_status(
|
| 510 |
+
verifier_output_dir / "distribution" / "summary.md",
|
| 511 |
+
args,
|
| 512 |
+
)
|
| 513 |
+
else:
|
| 514 |
+
status = decide_step_status(Path(step["output"]), args)
|
| 515 |
+
if status == "skip":
|
| 516 |
+
step["status"] = "skipped"
|
| 517 |
+
step["reason"] = "--resume found existing output"
|
| 518 |
+
log(f"Skipping {step['name']}: existing output at {step['output']}")
|
| 519 |
+
continue
|
| 520 |
+
run_step(step, dry_run=args.dry_run)
|
| 521 |
+
except (subprocess.CalledProcessError, FileExistsError) as exc:
|
| 522 |
+
payload["status"] = "failed"
|
| 523 |
+
payload["error"] = str(exc)
|
| 524 |
+
write_pipeline_metadata(pipeline_metadata_path, payload)
|
| 525 |
+
log(str(exc))
|
| 526 |
+
return getattr(exc, "returncode", 1) or 1
|
| 527 |
+
|
| 528 |
+
payload["status"] = "dry_run" if args.dry_run else "completed"
|
| 529 |
+
if args.dry_run:
|
| 530 |
+
log("")
|
| 531 |
+
log(f"Dry run complete; no files were written. Planned metadata path: {pipeline_metadata_path}")
|
| 532 |
+
else:
|
| 533 |
+
write_pipeline_metadata(pipeline_metadata_path, payload)
|
| 534 |
+
log("")
|
| 535 |
+
log("Pipeline outputs:")
|
| 536 |
+
log(f"- prompts: {prompts_path}")
|
| 537 |
+
log(f"- worker evidence: {evidence_path}")
|
| 538 |
+
log(f"- verifier metrics: {verifier_output_dir / 'worker_vs_verifier_depth_metrics.csv'}")
|
| 539 |
+
log(f"- verifier summary: {verifier_output_dir / 'summary.md'}")
|
| 540 |
+
if not args.skip_distribution_summary:
|
| 541 |
+
log(f"- distribution summary: {verifier_output_dir / 'distribution' / 'summary.md'}")
|
| 542 |
+
return 0
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
if __name__ == "__main__":
|
| 546 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/src/worker_logits_verify/schema.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
JSONDict = Dict[str, Any]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclass
|
| 17 |
+
class DecodeConfig:
|
| 18 |
+
max_new_tokens: int = 128
|
| 19 |
+
temperature: float = 0.0
|
| 20 |
+
top_p: float = 1.0
|
| 21 |
+
top_k: int = 0
|
| 22 |
+
seed: int = 0
|
| 23 |
+
do_sample: bool = False
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class VariantInfo:
|
| 28 |
+
variant_id: str
|
| 29 |
+
model: str
|
| 30 |
+
tokenizer_hash: str
|
| 31 |
+
tokenizer_name: str = ""
|
| 32 |
+
quantization: str = "bf16"
|
| 33 |
+
gpu: str = ""
|
| 34 |
+
backend: str = "transformers"
|
| 35 |
+
backend_version: str = ""
|
| 36 |
+
dtype: str = ""
|
| 37 |
+
extra: JSONDict = field(default_factory=dict)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass
|
| 41 |
+
class Tokenization:
|
| 42 |
+
tokenizer_hash: str
|
| 43 |
+
tokenizer_name: str
|
| 44 |
+
input_ids: List[int]
|
| 45 |
+
output_ids: List[int]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@dataclass
|
| 49 |
+
class WorkerSample:
|
| 50 |
+
sample_id: str
|
| 51 |
+
input_text: str
|
| 52 |
+
canonical_output_text: str = ""
|
| 53 |
+
category: str = ""
|
| 54 |
+
target_input_tokens: Optional[int] = None
|
| 55 |
+
anchor_variant: str = ""
|
| 56 |
+
decode_config: Optional[DecodeConfig] = None
|
| 57 |
+
tokenizations: Dict[str, Tokenization] = field(default_factory=dict)
|
| 58 |
+
metadata: JSONDict = field(default_factory=dict)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass
|
| 62 |
+
class TopLogprob:
|
| 63 |
+
token_id: int
|
| 64 |
+
logprob: float
|
| 65 |
+
raw_logit: float
|
| 66 |
+
rank: int
|
| 67 |
+
decoded_token: str = ""
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@dataclass
|
| 71 |
+
class DepthTrace:
|
| 72 |
+
sample_id: str
|
| 73 |
+
variant_id: str
|
| 74 |
+
depth: int
|
| 75 |
+
input_token_count: int
|
| 76 |
+
output_token_count: int
|
| 77 |
+
target_token_id: int
|
| 78 |
+
target_decoded_token: str
|
| 79 |
+
selected_logprob: float
|
| 80 |
+
selected_raw_logit: float
|
| 81 |
+
selected_rank: int
|
| 82 |
+
top1_token_id: int
|
| 83 |
+
top1_logprob: float
|
| 84 |
+
top1_raw_logit: float
|
| 85 |
+
top2_token_id: Optional[int]
|
| 86 |
+
top2_logprob: Optional[float]
|
| 87 |
+
top2_raw_logit: Optional[float]
|
| 88 |
+
top1_top2_margin_logprob: Optional[float]
|
| 89 |
+
top_k_mass: float
|
| 90 |
+
top_logprobs: List[TopLogprob]
|
| 91 |
+
probe_logprobs: Dict[str, float] = field(default_factory=dict)
|
| 92 |
+
probe_raw_logits: Dict[str, float] = field(default_factory=dict)
|
| 93 |
+
metadata: JSONDict = field(default_factory=dict)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def now_unix() -> float:
|
| 97 |
+
return time.time()
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def runtime_metadata(argv: Sequence[str]) -> JSONDict:
|
| 101 |
+
return {
|
| 102 |
+
"created_at_unix": now_unix(),
|
| 103 |
+
"python": sys.version,
|
| 104 |
+
"platform": platform.platform(),
|
| 105 |
+
"argv": list(argv),
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def stable_json_hash(payload: Any, length: int = 16) -> str:
|
| 110 |
+
encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")
|
| 111 |
+
return hashlib.sha256(encoded).hexdigest()[:length]
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def dataclass_to_dict(value: Any) -> JSONDict:
|
| 115 |
+
return asdict(value)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def read_jsonl(path: Path) -> Iterator[JSONDict]:
|
| 119 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 120 |
+
for line_number, line in enumerate(handle, start=1):
|
| 121 |
+
line = line.strip()
|
| 122 |
+
if not line:
|
| 123 |
+
continue
|
| 124 |
+
try:
|
| 125 |
+
yield json.loads(line)
|
| 126 |
+
except json.JSONDecodeError as exc:
|
| 127 |
+
raise ValueError(f"{path}:{line_number}: invalid JSONL row") from exc
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def write_jsonl(path: Path, rows: Iterable[JSONDict]) -> None:
|
| 131 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 132 |
+
with path.open("w", encoding="utf-8") as handle:
|
| 133 |
+
for row in rows:
|
| 134 |
+
handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True))
|
| 135 |
+
handle.write("\n")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def read_json(path: Path) -> JSONDict:
|
| 139 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 140 |
+
return json.load(handle)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def write_json(path: Path, payload: JSONDict) -> None:
|
| 144 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 145 |
+
with path.open("w", encoding="utf-8") as handle:
|
| 146 |
+
json.dump(payload, handle, ensure_ascii=False, indent=2, sort_keys=True)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def parse_decode_config(payload: Optional[JSONDict]) -> Optional[DecodeConfig]:
|
| 150 |
+
if payload is None:
|
| 151 |
+
return None
|
| 152 |
+
return DecodeConfig(**payload)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def parse_tokenizations(payload: Optional[JSONDict]) -> Dict[str, Tokenization]:
|
| 156 |
+
if not payload:
|
| 157 |
+
return {}
|
| 158 |
+
return {
|
| 159 |
+
str(key): Tokenization(**value)
|
| 160 |
+
for key, value in payload.items()
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def parse_worker_sample(payload: JSONDict) -> WorkerSample:
|
| 165 |
+
data = dict(payload)
|
| 166 |
+
data["decode_config"] = parse_decode_config(data.get("decode_config"))
|
| 167 |
+
data["tokenizations"] = parse_tokenizations(data.get("tokenizations"))
|
| 168 |
+
return WorkerSample(**data)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def worker_sample_to_dict(sample: WorkerSample) -> JSONDict:
|
| 172 |
+
return dataclass_to_dict(sample)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def top_logprob_to_dict(value: TopLogprob) -> JSONDict:
|
| 176 |
+
return dataclass_to_dict(value)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def depth_trace_to_dict(value: DepthTrace) -> JSONDict:
|
| 180 |
+
return dataclass_to_dict(value)
|
tools/worker_logits_verify/src/worker_logits_verify/summarize_worker_verify.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import math
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
| 9 |
+
|
| 10 |
+
from .metrics import quantile, safe_float
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
QUANTILES = [
|
| 14 |
+
("p50", 0.50),
|
| 15 |
+
("p90", 0.90),
|
| 16 |
+
("p95", 0.95),
|
| 17 |
+
("p99", 0.99),
|
| 18 |
+
("p999", 0.999),
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def read_csv(path: Path) -> List[dict]:
|
| 23 |
+
with path.open("r", encoding="utf-8", newline="") as handle:
|
| 24 |
+
return list(csv.DictReader(handle))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def write_csv(path: Path, rows: Sequence[dict], fields: Sequence[str]) -> None:
|
| 28 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 29 |
+
with path.open("w", encoding="utf-8", newline="") as handle:
|
| 30 |
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
| 31 |
+
writer.writeheader()
|
| 32 |
+
for row in rows:
|
| 33 |
+
writer.writerow({field: row.get(field, "") for field in fields})
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def metrics_path(path: Path) -> Path:
|
| 37 |
+
if path.is_dir():
|
| 38 |
+
return path / "worker_vs_verifier_depth_metrics.csv"
|
| 39 |
+
return path
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def input_bucket(token_count: int) -> str:
|
| 43 |
+
if token_count <= 128:
|
| 44 |
+
return "00000-00128"
|
| 45 |
+
if token_count <= 512:
|
| 46 |
+
return "00129-00512"
|
| 47 |
+
if token_count <= 2048:
|
| 48 |
+
return "00513-02048"
|
| 49 |
+
if token_count <= 8192:
|
| 50 |
+
return "02049-08192"
|
| 51 |
+
if token_count <= 16384:
|
| 52 |
+
return "08193-16384"
|
| 53 |
+
return "16385+"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def output_depth_bucket(depth: int) -> str:
|
| 57 |
+
if depth <= 16:
|
| 58 |
+
return "000-016"
|
| 59 |
+
if depth <= 32:
|
| 60 |
+
return "017-032"
|
| 61 |
+
if depth <= 64:
|
| 62 |
+
return "033-064"
|
| 63 |
+
if depth <= 128:
|
| 64 |
+
return "065-128"
|
| 65 |
+
if depth <= 256:
|
| 66 |
+
return "129-256"
|
| 67 |
+
return "257+"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def summarize_rows(rows: Sequence[dict], label: str) -> dict:
|
| 71 |
+
values = [safe_float(row.get("abs_logprob_diff")) for row in rows]
|
| 72 |
+
values = [value for value in values if math.isfinite(value)]
|
| 73 |
+
out = {
|
| 74 |
+
"group": label,
|
| 75 |
+
"count": len(rows),
|
| 76 |
+
"finite_count": len(values),
|
| 77 |
+
"missing_selected_count": sum(
|
| 78 |
+
1 for row in rows
|
| 79 |
+
if row.get("verifier_selected_logprob") in {"", None}
|
| 80 |
+
),
|
| 81 |
+
"mean_abs_logprob_diff": (
|
| 82 |
+
sum(values) / len(values) if values else float("nan")
|
| 83 |
+
),
|
| 84 |
+
"max_abs_logprob_diff": max(values, default=float("nan")),
|
| 85 |
+
}
|
| 86 |
+
for name, q in QUANTILES:
|
| 87 |
+
out[f"abs_logprob_diff_{name}"] = quantile(values, q)
|
| 88 |
+
rank_deltas = [
|
| 89 |
+
abs(safe_float(row.get("rank_delta_verifier_minus_worker")))
|
| 90 |
+
for row in rows
|
| 91 |
+
]
|
| 92 |
+
rank_deltas = [value for value in rank_deltas if math.isfinite(value)]
|
| 93 |
+
out["rank_delta_nonzero_rate"] = (
|
| 94 |
+
sum(1 for value in rank_deltas if value != 0.0) / len(rank_deltas)
|
| 95 |
+
if rank_deltas else float("nan")
|
| 96 |
+
)
|
| 97 |
+
jaccards = [safe_float(row.get("topk_jaccard")) for row in rows]
|
| 98 |
+
jaccards = [value for value in jaccards if math.isfinite(value)]
|
| 99 |
+
out["topk_jaccard_p01"] = quantile(jaccards, 0.01)
|
| 100 |
+
out["topk_jaccard_p05"] = quantile(jaccards, 0.05)
|
| 101 |
+
out["topk_jaccard_mean"] = sum(jaccards) / len(jaccards) if jaccards else float("nan")
|
| 102 |
+
union_js = [safe_float(row.get("union_js_divergence")) for row in rows]
|
| 103 |
+
union_js = [value for value in union_js if math.isfinite(value)]
|
| 104 |
+
out["union_js_p95"] = quantile(union_js, 0.95)
|
| 105 |
+
out["union_js_p99"] = quantile(union_js, 0.99)
|
| 106 |
+
out["union_js_max"] = max(union_js, default=float("nan"))
|
| 107 |
+
return out
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def grouped_summary(rows: Sequence[dict], key_name: str) -> List[dict]:
|
| 111 |
+
grouped: Dict[str, List[dict]] = defaultdict(list)
|
| 112 |
+
for row in rows:
|
| 113 |
+
if key_name == "input_bucket":
|
| 114 |
+
key = input_bucket(int(row.get("input_token_count", 0)))
|
| 115 |
+
elif key_name == "output_depth_bucket":
|
| 116 |
+
key = output_depth_bucket(int(row.get("depth", 0)))
|
| 117 |
+
elif key_name == "output_depth":
|
| 118 |
+
key = f"{int(row.get('depth', 0)):03d}"
|
| 119 |
+
elif key_name == "sample_id":
|
| 120 |
+
key = str(row.get("sample_id"))
|
| 121 |
+
else:
|
| 122 |
+
key = str(row.get(key_name, ""))
|
| 123 |
+
grouped[key].append(row)
|
| 124 |
+
return [
|
| 125 |
+
summarize_rows(group_rows, key)
|
| 126 |
+
for key, group_rows in sorted(grouped.items())
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def write_markdown(path: Path, overall: dict, by_input: Sequence[dict],
|
| 131 |
+
by_depth: Sequence[dict],
|
| 132 |
+
by_exact_depth: Sequence[dict]) -> None:
|
| 133 |
+
lines = [
|
| 134 |
+
"# worker verify distribution",
|
| 135 |
+
"",
|
| 136 |
+
"## overall",
|
| 137 |
+
"",
|
| 138 |
+
"| count | mean | p50 | p90 | p95 | p99 | p999 | max | rank_delta_rate |",
|
| 139 |
+
"|---:|---:|---:|---:|---:|---:|---:|---:|---:|",
|
| 140 |
+
"| {count} | {mean:.8g} | {p50:.8g} | {p90:.8g} | {p95:.8g} | {p99:.8g} | {p999:.8g} | {maxv:.8g} | {rank:.8g} |".format(
|
| 141 |
+
count=overall.get("count"),
|
| 142 |
+
mean=safe_float(overall.get("mean_abs_logprob_diff")),
|
| 143 |
+
p50=safe_float(overall.get("abs_logprob_diff_p50")),
|
| 144 |
+
p90=safe_float(overall.get("abs_logprob_diff_p90")),
|
| 145 |
+
p95=safe_float(overall.get("abs_logprob_diff_p95")),
|
| 146 |
+
p99=safe_float(overall.get("abs_logprob_diff_p99")),
|
| 147 |
+
p999=safe_float(overall.get("abs_logprob_diff_p999")),
|
| 148 |
+
maxv=safe_float(overall.get("max_abs_logprob_diff")),
|
| 149 |
+
rank=safe_float(overall.get("rank_delta_nonzero_rate")),
|
| 150 |
+
),
|
| 151 |
+
"",
|
| 152 |
+
"## by input length",
|
| 153 |
+
"",
|
| 154 |
+
"| bucket | count | p90 | p95 | p99 | max | jaccard p05 | union_js p99 |",
|
| 155 |
+
"|---|---:|---:|---:|---:|---:|---:|---:|",
|
| 156 |
+
]
|
| 157 |
+
for row in by_input:
|
| 158 |
+
lines.append(
|
| 159 |
+
"| {group} | {count} | {p90:.8g} | {p95:.8g} | {p99:.8g} | {maxv:.8g} | {jac:.8g} | {js:.8g} |".format(
|
| 160 |
+
group=row.get("group"),
|
| 161 |
+
count=row.get("count"),
|
| 162 |
+
p90=safe_float(row.get("abs_logprob_diff_p90")),
|
| 163 |
+
p95=safe_float(row.get("abs_logprob_diff_p95")),
|
| 164 |
+
p99=safe_float(row.get("abs_logprob_diff_p99")),
|
| 165 |
+
maxv=safe_float(row.get("max_abs_logprob_diff")),
|
| 166 |
+
jac=safe_float(row.get("topk_jaccard_p05")),
|
| 167 |
+
js=safe_float(row.get("union_js_p99")),
|
| 168 |
+
)
|
| 169 |
+
)
|
| 170 |
+
lines.extend([
|
| 171 |
+
"",
|
| 172 |
+
"## by output depth",
|
| 173 |
+
"",
|
| 174 |
+
"| bucket | count | p90 | p95 | p99 | max | jaccard p05 | union_js p99 |",
|
| 175 |
+
"|---|---:|---:|---:|---:|---:|---:|---:|",
|
| 176 |
+
])
|
| 177 |
+
for row in by_depth:
|
| 178 |
+
lines.append(
|
| 179 |
+
"| {group} | {count} | {p90:.8g} | {p95:.8g} | {p99:.8g} | {maxv:.8g} | {jac:.8g} | {js:.8g} |".format(
|
| 180 |
+
group=row.get("group"),
|
| 181 |
+
count=row.get("count"),
|
| 182 |
+
p90=safe_float(row.get("abs_logprob_diff_p90")),
|
| 183 |
+
p95=safe_float(row.get("abs_logprob_diff_p95")),
|
| 184 |
+
p99=safe_float(row.get("abs_logprob_diff_p99")),
|
| 185 |
+
maxv=safe_float(row.get("max_abs_logprob_diff")),
|
| 186 |
+
jac=safe_float(row.get("topk_jaccard_p05")),
|
| 187 |
+
js=safe_float(row.get("union_js_p99")),
|
| 188 |
+
)
|
| 189 |
+
)
|
| 190 |
+
lines.extend([
|
| 191 |
+
"",
|
| 192 |
+
"## by exact output depth",
|
| 193 |
+
"",
|
| 194 |
+
"| depth | count | mean | p50 | p90 | p95 | p99 | max | rank_delta_rate | jaccard p05 | union_js p99 |",
|
| 195 |
+
"|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|",
|
| 196 |
+
])
|
| 197 |
+
for row in by_exact_depth:
|
| 198 |
+
lines.append(
|
| 199 |
+
"| {group} | {count} | {mean:.8g} | {p50:.8g} | {p90:.8g} | {p95:.8g} | {p99:.8g} | {maxv:.8g} | {rank:.8g} | {jac:.8g} | {js:.8g} |".format(
|
| 200 |
+
group=row.get("group"),
|
| 201 |
+
count=row.get("count"),
|
| 202 |
+
mean=safe_float(row.get("mean_abs_logprob_diff")),
|
| 203 |
+
p50=safe_float(row.get("abs_logprob_diff_p50")),
|
| 204 |
+
p90=safe_float(row.get("abs_logprob_diff_p90")),
|
| 205 |
+
p95=safe_float(row.get("abs_logprob_diff_p95")),
|
| 206 |
+
p99=safe_float(row.get("abs_logprob_diff_p99")),
|
| 207 |
+
maxv=safe_float(row.get("max_abs_logprob_diff")),
|
| 208 |
+
rank=safe_float(row.get("rank_delta_nonzero_rate")),
|
| 209 |
+
jac=safe_float(row.get("topk_jaccard_p05")),
|
| 210 |
+
js=safe_float(row.get("union_js_p99")),
|
| 211 |
+
)
|
| 212 |
+
)
|
| 213 |
+
lines.append("")
|
| 214 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 218 |
+
parser = argparse.ArgumentParser(
|
| 219 |
+
description="Summarize worker-vs-verifier abs logprob diff distributions."
|
| 220 |
+
)
|
| 221 |
+
parser.add_argument("--metrics", required=True,
|
| 222 |
+
help="worker_vs_verifier_depth_metrics.csv or its parent dir.")
|
| 223 |
+
parser.add_argument("--output-dir", default=None)
|
| 224 |
+
args = parser.parse_args(argv)
|
| 225 |
+
|
| 226 |
+
path = metrics_path(Path(args.metrics))
|
| 227 |
+
rows = read_csv(path)
|
| 228 |
+
output_dir = Path(args.output_dir) if args.output_dir else path.parent / "distribution"
|
| 229 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 230 |
+
|
| 231 |
+
overall = summarize_rows(rows, "overall")
|
| 232 |
+
by_input = grouped_summary(rows, "input_bucket")
|
| 233 |
+
by_depth = grouped_summary(rows, "output_depth_bucket")
|
| 234 |
+
by_exact_depth = grouped_summary(rows, "output_depth")
|
| 235 |
+
by_sample = grouped_summary(rows, "sample_id")
|
| 236 |
+
|
| 237 |
+
fields = sorted(set(overall) | {field for row in by_input + by_depth + by_exact_depth + by_sample for field in row})
|
| 238 |
+
write_csv(output_dir / "overall.csv", [overall], fields)
|
| 239 |
+
write_csv(output_dir / "by_input_bucket.csv", by_input, fields)
|
| 240 |
+
write_csv(output_dir / "by_output_depth_bucket.csv", by_depth, fields)
|
| 241 |
+
write_csv(output_dir / "by_output_depth.csv", by_exact_depth, fields)
|
| 242 |
+
write_csv(output_dir / "by_sample.csv", by_sample, fields)
|
| 243 |
+
write_markdown(output_dir / "summary.md", overall, by_input, by_depth, by_exact_depth)
|
| 244 |
+
print(f"Wrote {output_dir / 'summary.md'}")
|
| 245 |
+
print(f"Wrote {output_dir / 'overall.csv'}")
|
| 246 |
+
print(f"Wrote {output_dir / 'by_input_bucket.csv'}")
|
| 247 |
+
print(f"Wrote {output_dir / 'by_output_depth_bucket.csv'}")
|
| 248 |
+
print(f"Wrote {output_dir / 'by_output_depth.csv'}")
|
| 249 |
+
print(f"Wrote {output_dir / 'by_sample.csv'}")
|
| 250 |
+
return 0
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
if __name__ == "__main__":
|
| 254 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/src/worker_logits_verify/tokenizer_utils.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
from typing import Any, Iterable, List, Sequence
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def tokenizer_hash(tokenizer: Any, length: int = 16) -> str:
|
| 9 |
+
"""Build a stable-ish tokenizer fingerprint from local tokenizer state."""
|
| 10 |
+
parts = {
|
| 11 |
+
"class": tokenizer.__class__.__name__,
|
| 12 |
+
"name_or_path": str(getattr(tokenizer, "name_or_path", "")),
|
| 13 |
+
"vocab_size": int(getattr(tokenizer, "vocab_size", 0) or 0),
|
| 14 |
+
"bos_token_id": getattr(tokenizer, "bos_token_id", None),
|
| 15 |
+
"eos_token_id": getattr(tokenizer, "eos_token_id", None),
|
| 16 |
+
"pad_token_id": getattr(tokenizer, "pad_token_id", None),
|
| 17 |
+
"unk_token_id": getattr(tokenizer, "unk_token_id", None),
|
| 18 |
+
"chat_template": getattr(tokenizer, "chat_template", None),
|
| 19 |
+
}
|
| 20 |
+
backend = getattr(tokenizer, "backend_tokenizer", None)
|
| 21 |
+
if backend is not None and hasattr(backend, "to_str"):
|
| 22 |
+
parts["backend_sha256"] = hashlib.sha256(
|
| 23 |
+
backend.to_str().encode("utf-8")
|
| 24 |
+
).hexdigest()
|
| 25 |
+
else:
|
| 26 |
+
try:
|
| 27 |
+
vocab_items = sorted(tokenizer.get_vocab().items())
|
| 28 |
+
except Exception:
|
| 29 |
+
vocab_items = []
|
| 30 |
+
parts["vocab_sha256"] = hashlib.sha256(
|
| 31 |
+
json.dumps(vocab_items, sort_keys=True).encode("utf-8")
|
| 32 |
+
).hexdigest()
|
| 33 |
+
encoded = json.dumps(parts, ensure_ascii=False, sort_keys=True).encode("utf-8")
|
| 34 |
+
return hashlib.sha256(encoded).hexdigest()[:length]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def tokenizer_name(tokenizer: Any) -> str:
|
| 38 |
+
return str(getattr(tokenizer, "name_or_path", "") or tokenizer.__class__.__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def encode_text(tokenizer: Any, text: str) -> List[int]:
|
| 42 |
+
return list(tokenizer.encode(text, add_special_tokens=False))
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def decode_token(tokenizer: Any, token_id: int) -> str:
|
| 46 |
+
try:
|
| 47 |
+
return tokenizer.decode([int(token_id)], skip_special_tokens=False)
|
| 48 |
+
except Exception:
|
| 49 |
+
return ""
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def decode_tokens(tokenizer: Any, token_ids: Sequence[int]) -> str:
|
| 53 |
+
return tokenizer.decode(list(token_ids), skip_special_tokens=False)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def parse_probe_token_ids(raw: str) -> List[int]:
|
| 57 |
+
out: List[int] = []
|
| 58 |
+
for item in raw.split(","):
|
| 59 |
+
item = item.strip()
|
| 60 |
+
if item:
|
| 61 |
+
out.append(int(item))
|
| 62 |
+
return unique_ints(out)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def probe_ids_from_texts(tokenizer: Any, texts: Iterable[str]) -> List[int]:
|
| 66 |
+
out: List[int] = []
|
| 67 |
+
for text in texts:
|
| 68 |
+
out.extend(encode_text(tokenizer, text))
|
| 69 |
+
return unique_ints(out)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def unique_ints(values: Iterable[int]) -> List[int]:
|
| 73 |
+
seen = set()
|
| 74 |
+
out = []
|
| 75 |
+
for value in values:
|
| 76 |
+
value = int(value)
|
| 77 |
+
if value in seen:
|
| 78 |
+
continue
|
| 79 |
+
seen.add(value)
|
| 80 |
+
out.append(value)
|
| 81 |
+
return out
|
tools/worker_logits_verify/src/worker_logits_verify/verify_comparison.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import sys
|
| 8 |
+
from collections import Counter
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, List, Optional, Sequence
|
| 11 |
+
|
| 12 |
+
from .metrics import safe_float
|
| 13 |
+
from .schema import read_json, runtime_metadata, write_json
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def read_csv(path: Path) -> List[dict]:
|
| 17 |
+
with path.open("r", encoding="utf-8", newline="") as handle:
|
| 18 |
+
return list(csv.DictReader(handle))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def write_csv(path: Path, rows: Sequence[dict], fields: Sequence[str]) -> None:
|
| 22 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 23 |
+
with path.open("w", encoding="utf-8", newline="") as handle:
|
| 24 |
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
| 25 |
+
writer.writeheader()
|
| 26 |
+
for row in rows:
|
| 27 |
+
writer.writerow({field: row.get(field, "") for field in fields})
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def comparison_path(path: Path) -> Path:
|
| 31 |
+
if path.is_dir():
|
| 32 |
+
return path / "depth_metrics.csv"
|
| 33 |
+
return path
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def threshold_key(row: dict) -> str:
|
| 37 |
+
return f"{row.get('depth_bucket')}|{row.get('margin_bucket')}"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def fallback_threshold_key(row: dict) -> str:
|
| 41 |
+
return f"{row.get('depth_bucket')}|all"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def metric_failed(metric: str, value: float, threshold: float, lower_bound: bool) -> bool:
|
| 45 |
+
if not math.isfinite(value) or not math.isfinite(threshold):
|
| 46 |
+
return False
|
| 47 |
+
if lower_bound:
|
| 48 |
+
return value < threshold
|
| 49 |
+
return value > threshold
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def evaluate_row(row: dict,
|
| 53 |
+
thresholds: Dict[str, dict],
|
| 54 |
+
upper_metrics: Sequence[str],
|
| 55 |
+
lower_metrics: Sequence[str]) -> List[dict]:
|
| 56 |
+
key = threshold_key(row)
|
| 57 |
+
bucket = thresholds.get(key)
|
| 58 |
+
if bucket is None:
|
| 59 |
+
bucket = thresholds.get(fallback_threshold_key(row))
|
| 60 |
+
if bucket is None:
|
| 61 |
+
return [{
|
| 62 |
+
"sample_id": row.get("sample_id"),
|
| 63 |
+
"depth": row.get("depth"),
|
| 64 |
+
"depth_bucket": row.get("depth_bucket"),
|
| 65 |
+
"margin_bucket": row.get("margin_bucket"),
|
| 66 |
+
"metric": "__bucket__",
|
| 67 |
+
"value": "",
|
| 68 |
+
"threshold": "",
|
| 69 |
+
"direction": "missing_threshold",
|
| 70 |
+
"failed": True,
|
| 71 |
+
}]
|
| 72 |
+
|
| 73 |
+
failures = []
|
| 74 |
+
for metric in upper_metrics:
|
| 75 |
+
value = safe_float(row.get(metric))
|
| 76 |
+
threshold = safe_float(bucket.get(metric))
|
| 77 |
+
failed = metric_failed(metric, value, threshold, lower_bound=False)
|
| 78 |
+
if failed:
|
| 79 |
+
failures.append({
|
| 80 |
+
"sample_id": row.get("sample_id"),
|
| 81 |
+
"depth": row.get("depth"),
|
| 82 |
+
"depth_bucket": row.get("depth_bucket"),
|
| 83 |
+
"margin_bucket": row.get("margin_bucket"),
|
| 84 |
+
"metric": metric,
|
| 85 |
+
"value": value,
|
| 86 |
+
"threshold": threshold,
|
| 87 |
+
"direction": "<=",
|
| 88 |
+
"failed": True,
|
| 89 |
+
})
|
| 90 |
+
for metric in lower_metrics:
|
| 91 |
+
value = safe_float(row.get(metric))
|
| 92 |
+
threshold = safe_float(bucket.get(metric))
|
| 93 |
+
failed = metric_failed(metric, value, threshold, lower_bound=True)
|
| 94 |
+
if failed:
|
| 95 |
+
failures.append({
|
| 96 |
+
"sample_id": row.get("sample_id"),
|
| 97 |
+
"depth": row.get("depth"),
|
| 98 |
+
"depth_bucket": row.get("depth_bucket"),
|
| 99 |
+
"margin_bucket": row.get("margin_bucket"),
|
| 100 |
+
"metric": metric,
|
| 101 |
+
"value": value,
|
| 102 |
+
"threshold": threshold,
|
| 103 |
+
"direction": ">=",
|
| 104 |
+
"failed": True,
|
| 105 |
+
})
|
| 106 |
+
return failures
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def write_summary(path: Path,
|
| 110 |
+
comparison: str,
|
| 111 |
+
profile: dict,
|
| 112 |
+
total_rows: int,
|
| 113 |
+
failed_rows: int,
|
| 114 |
+
failures: Sequence[dict],
|
| 115 |
+
fail_ratio: float,
|
| 116 |
+
max_fail_ratio: float) -> None:
|
| 117 |
+
by_metric = Counter(str(row["metric"]) for row in failures)
|
| 118 |
+
by_bucket = Counter(
|
| 119 |
+
f"{row.get('depth_bucket')}|{row.get('margin_bucket')}"
|
| 120 |
+
for row in failures
|
| 121 |
+
)
|
| 122 |
+
lines = [
|
| 123 |
+
"# profile verification",
|
| 124 |
+
"",
|
| 125 |
+
f"- comparison: `{comparison}`",
|
| 126 |
+
f"- profile: `{profile.get('profile_id')}`",
|
| 127 |
+
f"- total rows: {total_rows}",
|
| 128 |
+
f"- rows with failures: {failed_rows}",
|
| 129 |
+
f"- fail ratio: {fail_ratio:.8g}",
|
| 130 |
+
f"- allowed fail ratio: {max_fail_ratio:.8g}",
|
| 131 |
+
f"- verdict: {'PASS' if fail_ratio <= max_fail_ratio else 'FAIL'}",
|
| 132 |
+
"",
|
| 133 |
+
"## failure metrics",
|
| 134 |
+
"",
|
| 135 |
+
"| metric | failures |",
|
| 136 |
+
"|---|---:|",
|
| 137 |
+
]
|
| 138 |
+
for metric, count in by_metric.most_common():
|
| 139 |
+
lines.append(f"| {metric} | {count} |")
|
| 140 |
+
lines.extend([
|
| 141 |
+
"",
|
| 142 |
+
"## failure buckets",
|
| 143 |
+
"",
|
| 144 |
+
"| bucket | failures |",
|
| 145 |
+
"|---|---:|",
|
| 146 |
+
])
|
| 147 |
+
for bucket, count in by_bucket.most_common():
|
| 148 |
+
lines.append(f"| {bucket} | {count} |")
|
| 149 |
+
lines.append("")
|
| 150 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 154 |
+
parser = argparse.ArgumentParser(
|
| 155 |
+
description="Verify a trace comparison against a calibrated accepted envelope."
|
| 156 |
+
)
|
| 157 |
+
parser.add_argument("--comparison", required=True,
|
| 158 |
+
help="Comparison dir or depth_metrics.csv to verify.")
|
| 159 |
+
parser.add_argument("--profile", required=True,
|
| 160 |
+
help="profile.json from calibrate-profile.")
|
| 161 |
+
parser.add_argument("--output-dir", default="results/verification")
|
| 162 |
+
parser.add_argument("--max-fail-ratio", type=float, default=0.0,
|
| 163 |
+
help="Allow this fraction of depth rows to exceed thresholds.")
|
| 164 |
+
parser.add_argument("--fail-on-reject", action=argparse.BooleanOptionalAction,
|
| 165 |
+
default=False)
|
| 166 |
+
args = parser.parse_args(argv)
|
| 167 |
+
|
| 168 |
+
rows = read_csv(comparison_path(Path(args.comparison)))
|
| 169 |
+
profile = read_json(Path(args.profile))
|
| 170 |
+
thresholds = profile.get("thresholds", {})
|
| 171 |
+
metrics = profile.get("metrics", {})
|
| 172 |
+
upper_metrics = metrics.get("upper_bound", [])
|
| 173 |
+
lower_metrics = metrics.get("lower_bound", [])
|
| 174 |
+
|
| 175 |
+
all_failures = []
|
| 176 |
+
failed_row_keys = set()
|
| 177 |
+
for row in rows:
|
| 178 |
+
failures = evaluate_row(row, thresholds, upper_metrics, lower_metrics)
|
| 179 |
+
if failures:
|
| 180 |
+
failed_row_keys.add((row.get("sample_id"), row.get("depth")))
|
| 181 |
+
all_failures.extend(failures)
|
| 182 |
+
|
| 183 |
+
output_dir = Path(args.output_dir)
|
| 184 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 185 |
+
fields = [
|
| 186 |
+
"sample_id",
|
| 187 |
+
"depth",
|
| 188 |
+
"depth_bucket",
|
| 189 |
+
"margin_bucket",
|
| 190 |
+
"metric",
|
| 191 |
+
"value",
|
| 192 |
+
"threshold",
|
| 193 |
+
"direction",
|
| 194 |
+
"failed",
|
| 195 |
+
]
|
| 196 |
+
write_csv(output_dir / "failures.csv", all_failures, fields)
|
| 197 |
+
|
| 198 |
+
total_rows = len(rows)
|
| 199 |
+
failed_rows = len(failed_row_keys)
|
| 200 |
+
fail_ratio = failed_rows / total_rows if total_rows else 1.0
|
| 201 |
+
passed = fail_ratio <= args.max_fail_ratio
|
| 202 |
+
write_json(output_dir / "verification.json", {
|
| 203 |
+
"metadata": runtime_metadata(sys.argv),
|
| 204 |
+
"args": vars(args),
|
| 205 |
+
"profile_id": profile.get("profile_id"),
|
| 206 |
+
"total_rows": total_rows,
|
| 207 |
+
"failed_rows": failed_rows,
|
| 208 |
+
"failure_count": len(all_failures),
|
| 209 |
+
"fail_ratio": fail_ratio,
|
| 210 |
+
"max_fail_ratio": args.max_fail_ratio,
|
| 211 |
+
"passed": passed,
|
| 212 |
+
})
|
| 213 |
+
write_summary(
|
| 214 |
+
output_dir / "summary.md",
|
| 215 |
+
comparison=args.comparison,
|
| 216 |
+
profile=profile,
|
| 217 |
+
total_rows=total_rows,
|
| 218 |
+
failed_rows=failed_rows,
|
| 219 |
+
failures=all_failures,
|
| 220 |
+
fail_ratio=fail_ratio,
|
| 221 |
+
max_fail_ratio=args.max_fail_ratio,
|
| 222 |
+
)
|
| 223 |
+
print(f"Wrote {output_dir / 'failures.csv'}")
|
| 224 |
+
print(f"Wrote {output_dir / 'verification.json'}")
|
| 225 |
+
print(f"Wrote {output_dir / 'summary.md'}")
|
| 226 |
+
print(f"Verdict: {'PASS' if passed else 'FAIL'}")
|
| 227 |
+
return 1 if (not passed and args.fail_on_reject) else 0
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
if __name__ == "__main__":
|
| 231 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/src/worker_logits_verify/verify_vllm_worker_evidence.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, List, Optional, Sequence
|
| 11 |
+
|
| 12 |
+
from .metrics import probability_metrics, safe_float, sorted_token_ids
|
| 13 |
+
from .schema import VariantInfo, dataclass_to_dict, read_jsonl, runtime_metadata, write_json
|
| 14 |
+
from .tokenizer_utils import tokenizer_hash, tokenizer_name
|
| 15 |
+
from .vllm_utils import (
|
| 16 |
+
build_llm_kwargs,
|
| 17 |
+
build_sampling_params,
|
| 18 |
+
logprob_for_token,
|
| 19 |
+
make_tokens_prompt,
|
| 20 |
+
normalize_logprob_dict,
|
| 21 |
+
rank_for_token,
|
| 22 |
+
sorted_top_logprobs,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def log(message: str) -> None:
|
| 27 |
+
print(message, flush=True)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def vllm_version() -> str:
|
| 31 |
+
try:
|
| 32 |
+
import vllm
|
| 33 |
+
|
| 34 |
+
return vllm.__version__
|
| 35 |
+
except Exception:
|
| 36 |
+
return ""
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def make_variant(args: argparse.Namespace, tokenizer: object) -> VariantInfo:
|
| 40 |
+
tok_hash = tokenizer_hash(tokenizer)
|
| 41 |
+
return VariantInfo(
|
| 42 |
+
variant_id=args.variant_id,
|
| 43 |
+
model=args.model,
|
| 44 |
+
tokenizer_hash=tok_hash,
|
| 45 |
+
tokenizer_name=tokenizer_name(tokenizer),
|
| 46 |
+
quantization=args.quantization,
|
| 47 |
+
gpu=args.gpu,
|
| 48 |
+
backend="vllm",
|
| 49 |
+
backend_version=vllm_version(),
|
| 50 |
+
dtype=args.dtype,
|
| 51 |
+
extra={
|
| 52 |
+
"cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"),
|
| 53 |
+
"tensor_parallel_size": args.tensor_parallel_size,
|
| 54 |
+
"gpu_memory_utilization": args.gpu_memory_utilization,
|
| 55 |
+
"max_model_len": args.max_model_len,
|
| 56 |
+
"max_num_seqs": args.max_num_seqs,
|
| 57 |
+
"max_num_batched_tokens": args.max_num_batched_tokens,
|
| 58 |
+
"max_logprobs": args.max_logprobs,
|
| 59 |
+
},
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def top_map(items: Sequence[dict]) -> Dict[str, Dict[str, object]]:
|
| 64 |
+
return {
|
| 65 |
+
str(int(item["token_id"])): {
|
| 66 |
+
"logprob": item.get("logprob"),
|
| 67 |
+
"rank": item.get("rank"),
|
| 68 |
+
"decoded_token": item.get("decoded_token"),
|
| 69 |
+
}
|
| 70 |
+
for item in items
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def vector_metrics(worker_top: Dict[str, Dict[str, object]],
|
| 75 |
+
verifier_top: Dict[str, Dict[str, object]],
|
| 76 |
+
missing_logprob: float) -> dict:
|
| 77 |
+
worker_tokens = set(worker_top)
|
| 78 |
+
verifier_tokens = set(verifier_top)
|
| 79 |
+
common = sorted_token_ids(worker_tokens & verifier_tokens)
|
| 80 |
+
union = sorted_token_ids(worker_tokens | verifier_tokens)
|
| 81 |
+
common_prob = probability_metrics(worker_top, verifier_top, common, missing_logprob)
|
| 82 |
+
union_prob = probability_metrics(worker_top, verifier_top, union, missing_logprob)
|
| 83 |
+
return {
|
| 84 |
+
"common_top_count": len(common),
|
| 85 |
+
"union_top_count": len(union),
|
| 86 |
+
"topk_jaccard": len(common) / len(union) if union else float("nan"),
|
| 87 |
+
"missing_from_verifier_count": len(worker_tokens - verifier_tokens),
|
| 88 |
+
"extra_in_verifier_count": len(verifier_tokens - worker_tokens),
|
| 89 |
+
"common_js_divergence": common_prob["js_divergence"],
|
| 90 |
+
"union_js_divergence": union_prob["js_divergence"],
|
| 91 |
+
"common_prob_cosine": common_prob["prob_cosine"],
|
| 92 |
+
"union_prob_cosine": union_prob["prob_cosine"],
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def compare_depth(worker_depth: dict,
|
| 97 |
+
verifier_logprobs: Dict[str, Dict[str, object]],
|
| 98 |
+
missing_logprob: float) -> dict:
|
| 99 |
+
target_token_id = int(worker_depth["target_token_id"])
|
| 100 |
+
worker_logprob = worker_depth.get("selected_logprob")
|
| 101 |
+
verifier_logprob = logprob_for_token(verifier_logprobs, target_token_id)
|
| 102 |
+
worker_rank = worker_depth.get("selected_rank")
|
| 103 |
+
verifier_rank = rank_for_token(verifier_logprobs, target_token_id)
|
| 104 |
+
worker_top = top_map(worker_depth.get("top_logprobs", []))
|
| 105 |
+
verifier_top = verifier_logprobs
|
| 106 |
+
lp_diff = (
|
| 107 |
+
safe_float(verifier_logprob) - safe_float(worker_logprob)
|
| 108 |
+
if worker_logprob is not None and verifier_logprob is not None
|
| 109 |
+
else float("nan")
|
| 110 |
+
)
|
| 111 |
+
if worker_rank is not None and verifier_rank is not None:
|
| 112 |
+
rank_delta = int(verifier_rank) - int(worker_rank)
|
| 113 |
+
else:
|
| 114 |
+
rank_delta = ""
|
| 115 |
+
return {
|
| 116 |
+
"depth": worker_depth.get("depth"),
|
| 117 |
+
"target_token_id": target_token_id,
|
| 118 |
+
"target_decoded_token": worker_depth.get("target_decoded_token"),
|
| 119 |
+
"worker_selected_logprob": worker_logprob,
|
| 120 |
+
"verifier_selected_logprob": verifier_logprob,
|
| 121 |
+
"logprob_diff_verifier_minus_worker": lp_diff,
|
| 122 |
+
"abs_logprob_diff": abs(lp_diff) if math.isfinite(lp_diff) else float("nan"),
|
| 123 |
+
"worker_selected_rank": worker_rank,
|
| 124 |
+
"verifier_selected_rank": verifier_rank,
|
| 125 |
+
"rank_delta_verifier_minus_worker": rank_delta,
|
| 126 |
+
**vector_metrics(worker_top, verifier_top, missing_logprob),
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def write_csv(path: Path, rows: Sequence[dict], fields: Sequence[str]) -> None:
|
| 131 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 132 |
+
with path.open("w", encoding="utf-8", newline="") as handle:
|
| 133 |
+
writer = csv.DictWriter(handle, fieldnames=fields)
|
| 134 |
+
writer.writeheader()
|
| 135 |
+
for row in rows:
|
| 136 |
+
writer.writerow({field: row.get(field, "") for field in fields})
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def write_summary(path: Path, rows: Sequence[dict]) -> None:
|
| 140 |
+
finite_abs = [safe_float(row.get("abs_logprob_diff")) for row in rows]
|
| 141 |
+
finite_abs = [value for value in finite_abs if math.isfinite(value)]
|
| 142 |
+
missing_selected = sum(
|
| 143 |
+
1 for row in rows
|
| 144 |
+
if row.get("verifier_selected_logprob") in {"", None}
|
| 145 |
+
)
|
| 146 |
+
max_abs = max(finite_abs, default=float("nan"))
|
| 147 |
+
mean_abs = sum(finite_abs) / len(finite_abs) if finite_abs else float("nan")
|
| 148 |
+
sorted_rows = sorted(
|
| 149 |
+
rows,
|
| 150 |
+
key=lambda row: safe_float(row.get("abs_logprob_diff"), -1.0),
|
| 151 |
+
reverse=True,
|
| 152 |
+
)
|
| 153 |
+
lines = [
|
| 154 |
+
"# vLLM worker evidence verification",
|
| 155 |
+
"",
|
| 156 |
+
f"- depth rows: {len(rows)}",
|
| 157 |
+
f"- missing verifier selected logprob: {missing_selected}",
|
| 158 |
+
f"- max abs logprob diff: {max_abs:.8g}",
|
| 159 |
+
f"- mean abs logprob diff: {mean_abs:.8g}",
|
| 160 |
+
"",
|
| 161 |
+
"| sample | depth | token | worker_lp | verifier_lp | abs_diff | worker/verifier_rank | jaccard | union_js |",
|
| 162 |
+
"|---|---:|---|---:|---:|---:|---:|---:|---:|",
|
| 163 |
+
]
|
| 164 |
+
for row in sorted_rows[:50]:
|
| 165 |
+
lines.append(
|
| 166 |
+
"| {sample} | {depth} | `{token}` | {worker:.8g} | {verifier:.8g} | {diff:.8g} | "
|
| 167 |
+
"{wrank}/{vrank} | {jaccard:.8g} | {js:.8g} |".format(
|
| 168 |
+
sample=row.get("sample_id"),
|
| 169 |
+
depth=row.get("depth"),
|
| 170 |
+
token=str(row.get("target_decoded_token", "")).replace("\n", "\\n"),
|
| 171 |
+
worker=safe_float(row.get("worker_selected_logprob")),
|
| 172 |
+
verifier=safe_float(row.get("verifier_selected_logprob")),
|
| 173 |
+
diff=safe_float(row.get("abs_logprob_diff")),
|
| 174 |
+
wrank=row.get("worker_selected_rank"),
|
| 175 |
+
vrank=row.get("verifier_selected_rank"),
|
| 176 |
+
jaccard=safe_float(row.get("topk_jaccard")),
|
| 177 |
+
js=safe_float(row.get("union_js_divergence")),
|
| 178 |
+
)
|
| 179 |
+
)
|
| 180 |
+
lines.append("")
|
| 181 |
+
path.write_text("\n".join(lines), encoding="utf-8")
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
| 185 |
+
parser = argparse.ArgumentParser(
|
| 186 |
+
description="Recompute vLLM prompt logprobs for worker evidence and compare per output token."
|
| 187 |
+
)
|
| 188 |
+
parser.add_argument("--evidence", required=True)
|
| 189 |
+
parser.add_argument("--output-dir", default="results/vllm_worker_verify")
|
| 190 |
+
parser.add_argument("--model", required=True)
|
| 191 |
+
parser.add_argument("--variant-id", required=True)
|
| 192 |
+
parser.add_argument("--gpu", default="")
|
| 193 |
+
parser.add_argument("--quantization", default="bf16")
|
| 194 |
+
parser.add_argument("--dtype", default="auto")
|
| 195 |
+
parser.add_argument("--trust-remote-code", action="store_true")
|
| 196 |
+
parser.add_argument("--tensor-parallel-size", type=int, default=1)
|
| 197 |
+
parser.add_argument("--gpu-memory-utilization", type=float, default=None)
|
| 198 |
+
parser.add_argument("--max-model-len", type=int, default=None)
|
| 199 |
+
parser.add_argument("--max-num-seqs", type=int, default=None)
|
| 200 |
+
parser.add_argument("--max-num-batched-tokens", type=int, default=None)
|
| 201 |
+
parser.add_argument("--max-logprobs", type=int, default=None)
|
| 202 |
+
parser.add_argument("--prompt-logprobs", type=int, default=64)
|
| 203 |
+
parser.add_argument("--temperature", type=float, default=0.0)
|
| 204 |
+
parser.add_argument("--top-p", type=float, default=1.0)
|
| 205 |
+
parser.add_argument("--top-k", type=int, default=0)
|
| 206 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 207 |
+
parser.add_argument("--batch-size", type=int, default=4)
|
| 208 |
+
parser.add_argument("--missing-logprob", type=float, default=-100.0)
|
| 209 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 210 |
+
parser.add_argument("--max-total-tokens", type=int, default=0,
|
| 211 |
+
help="Skip evidence rows whose input+output token count exceeds this value.")
|
| 212 |
+
args = parser.parse_args(argv)
|
| 213 |
+
|
| 214 |
+
from transformers import AutoTokenizer
|
| 215 |
+
from vllm import LLM
|
| 216 |
+
|
| 217 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 218 |
+
args.model,
|
| 219 |
+
trust_remote_code=args.trust_remote_code,
|
| 220 |
+
)
|
| 221 |
+
variant = make_variant(args, tokenizer)
|
| 222 |
+
llm_kwargs = build_llm_kwargs(args)
|
| 223 |
+
log(f"Loading verifier vLLM with kwargs: {llm_kwargs}")
|
| 224 |
+
llm = LLM(**llm_kwargs)
|
| 225 |
+
sampling_params = build_sampling_params(
|
| 226 |
+
args,
|
| 227 |
+
max_tokens=1,
|
| 228 |
+
logprobs=None,
|
| 229 |
+
prompt_logprobs=args.prompt_logprobs,
|
| 230 |
+
detokenize=False,
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
evidence_rows = []
|
| 234 |
+
skipped_too_long = 0
|
| 235 |
+
for index, row in enumerate(read_jsonl(Path(args.evidence)), start=1):
|
| 236 |
+
if args.limit and index > args.limit:
|
| 237 |
+
break
|
| 238 |
+
total_tokens = len(row.get("input_ids", [])) + len(row.get("output_ids", []))
|
| 239 |
+
if args.max_total_tokens and total_tokens > args.max_total_tokens:
|
| 240 |
+
skipped_too_long += 1
|
| 241 |
+
continue
|
| 242 |
+
evidence_rows.append(row)
|
| 243 |
+
log(
|
| 244 |
+
f"Loaded evidence rows: {len(evidence_rows)} "
|
| 245 |
+
f"(skipped_too_long={skipped_too_long})"
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
output_dir = Path(args.output_dir)
|
| 249 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 250 |
+
metric_rows: List[dict] = []
|
| 251 |
+
total_start = time.time()
|
| 252 |
+
for batch_start in range(0, len(evidence_rows), args.batch_size):
|
| 253 |
+
batch = evidence_rows[batch_start:batch_start + args.batch_size]
|
| 254 |
+
prompts = [
|
| 255 |
+
make_tokens_prompt(row["input_ids"] + row["output_ids"])
|
| 256 |
+
for row in batch
|
| 257 |
+
]
|
| 258 |
+
lengths = [len(row["input_ids"]) + len(row["output_ids"]) for row in batch]
|
| 259 |
+
log(
|
| 260 |
+
f"Verifier prompt_logprobs batch {batch_start // args.batch_size + 1}, "
|
| 261 |
+
f"size={len(batch)}, max_tokens={max(lengths)}, total_tokens={sum(lengths)}"
|
| 262 |
+
)
|
| 263 |
+
outputs = llm.generate(prompts, sampling_params)
|
| 264 |
+
if len(outputs) != len(batch):
|
| 265 |
+
raise RuntimeError(f"vLLM returned {len(outputs)} outputs for {len(batch)} prompts")
|
| 266 |
+
for evidence, request_output in zip(batch, outputs):
|
| 267 |
+
input_len = len(evidence["input_ids"])
|
| 268 |
+
prompt_logprobs = list(getattr(request_output, "prompt_logprobs", []) or [])
|
| 269 |
+
worker_trace = evidence.get("worker_trace", [])
|
| 270 |
+
for worker_depth in worker_trace:
|
| 271 |
+
depth = int(worker_depth["depth"])
|
| 272 |
+
prompt_pos = input_len + depth
|
| 273 |
+
verifier_logprobs = (
|
| 274 |
+
normalize_logprob_dict(prompt_logprobs[prompt_pos])
|
| 275 |
+
if prompt_pos < len(prompt_logprobs) else {}
|
| 276 |
+
)
|
| 277 |
+
row = compare_depth(worker_depth, verifier_logprobs, args.missing_logprob)
|
| 278 |
+
row.update({
|
| 279 |
+
"sample_id": evidence.get("sample_id"),
|
| 280 |
+
"input_token_count": input_len,
|
| 281 |
+
"output_token_count": len(evidence.get("output_ids", [])),
|
| 282 |
+
"worker_trace_mode": evidence.get("worker_trace_mode"),
|
| 283 |
+
"verifier_trace_mode": "vllm_prompt_logprobs_full_prefill",
|
| 284 |
+
})
|
| 285 |
+
metric_rows.append(row)
|
| 286 |
+
|
| 287 |
+
fields = [
|
| 288 |
+
"sample_id",
|
| 289 |
+
"depth",
|
| 290 |
+
"input_token_count",
|
| 291 |
+
"output_token_count",
|
| 292 |
+
"target_token_id",
|
| 293 |
+
"target_decoded_token",
|
| 294 |
+
"worker_trace_mode",
|
| 295 |
+
"verifier_trace_mode",
|
| 296 |
+
"worker_selected_logprob",
|
| 297 |
+
"verifier_selected_logprob",
|
| 298 |
+
"logprob_diff_verifier_minus_worker",
|
| 299 |
+
"abs_logprob_diff",
|
| 300 |
+
"worker_selected_rank",
|
| 301 |
+
"verifier_selected_rank",
|
| 302 |
+
"rank_delta_verifier_minus_worker",
|
| 303 |
+
"common_top_count",
|
| 304 |
+
"union_top_count",
|
| 305 |
+
"topk_jaccard",
|
| 306 |
+
"missing_from_verifier_count",
|
| 307 |
+
"extra_in_verifier_count",
|
| 308 |
+
"common_js_divergence",
|
| 309 |
+
"union_js_divergence",
|
| 310 |
+
"common_prob_cosine",
|
| 311 |
+
"union_prob_cosine",
|
| 312 |
+
]
|
| 313 |
+
write_csv(output_dir / "worker_vs_verifier_depth_metrics.csv", metric_rows, fields)
|
| 314 |
+
write_summary(output_dir / "summary.md", metric_rows)
|
| 315 |
+
write_json(output_dir / "metadata.json", {
|
| 316 |
+
"metadata": runtime_metadata(sys.argv),
|
| 317 |
+
"args": vars(args),
|
| 318 |
+
"verifier_variant": dataclass_to_dict(variant),
|
| 319 |
+
"evidence_count": len(evidence_rows),
|
| 320 |
+
"skipped_too_long": skipped_too_long,
|
| 321 |
+
"depth_row_count": len(metric_rows),
|
| 322 |
+
"elapsed_seconds": time.time() - total_start,
|
| 323 |
+
})
|
| 324 |
+
log(f"Wrote {output_dir / 'worker_vs_verifier_depth_metrics.csv'}")
|
| 325 |
+
log(f"Wrote {output_dir / 'summary.md'}")
|
| 326 |
+
return 0
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
if __name__ == "__main__":
|
| 330 |
+
raise SystemExit(main())
|
tools/worker_logits_verify/src/worker_logits_verify/vllm_utils.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any, Dict, Iterable, List, Optional, Sequence
|
| 7 |
+
|
| 8 |
+
from .metrics import safe_float
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def normalize_logprob_value(value: Any) -> Dict[str, Any]:
|
| 12 |
+
if hasattr(value, "logprob"):
|
| 13 |
+
return {
|
| 14 |
+
"logprob": float(value.logprob),
|
| 15 |
+
"rank": getattr(value, "rank", None),
|
| 16 |
+
"decoded_token": getattr(value, "decoded_token", None),
|
| 17 |
+
}
|
| 18 |
+
if isinstance(value, dict):
|
| 19 |
+
logprob = value.get("logprob", value.get("value"))
|
| 20 |
+
return {
|
| 21 |
+
"logprob": float(logprob),
|
| 22 |
+
"rank": value.get("rank"),
|
| 23 |
+
"decoded_token": value.get("decoded_token"),
|
| 24 |
+
}
|
| 25 |
+
return {"logprob": float(value), "rank": None, "decoded_token": None}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def normalize_logprob_dict(raw: Any) -> Dict[str, Dict[str, Any]]:
|
| 29 |
+
if raw is None:
|
| 30 |
+
return {}
|
| 31 |
+
out: Dict[str, Dict[str, Any]] = {}
|
| 32 |
+
for token_id, value in dict(raw).items():
|
| 33 |
+
out[str(int(token_id))] = normalize_logprob_value(value)
|
| 34 |
+
return out
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def sorted_top_logprobs(logprobs: Dict[str, Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 38 |
+
def sort_key(item: tuple) -> tuple:
|
| 39 |
+
token_id, token_info = item
|
| 40 |
+
rank = token_info.get("rank")
|
| 41 |
+
if rank is None:
|
| 42 |
+
rank_key = float("inf")
|
| 43 |
+
else:
|
| 44 |
+
rank_key = safe_float(rank, float("inf"))
|
| 45 |
+
return rank_key, -safe_float(token_info.get("logprob")), int(token_id)
|
| 46 |
+
|
| 47 |
+
rows = []
|
| 48 |
+
for position, (token_id, token_info) in enumerate(
|
| 49 |
+
sorted(logprobs.items(), key=sort_key),
|
| 50 |
+
start=1,
|
| 51 |
+
):
|
| 52 |
+
rows.append({
|
| 53 |
+
"position": position,
|
| 54 |
+
"token_id": int(token_id),
|
| 55 |
+
"logprob": safe_float(token_info.get("logprob")),
|
| 56 |
+
"rank": token_info.get("rank"),
|
| 57 |
+
"decoded_token": token_info.get("decoded_token"),
|
| 58 |
+
})
|
| 59 |
+
return rows
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def logprob_for_token(logprobs: Dict[str, Dict[str, Any]], token_id: int) -> Optional[float]:
|
| 63 |
+
item = logprobs.get(str(int(token_id)))
|
| 64 |
+
if item is None:
|
| 65 |
+
return None
|
| 66 |
+
return safe_float(item.get("logprob"))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def rank_for_token(logprobs: Dict[str, Dict[str, Any]], token_id: int) -> Optional[int]:
|
| 70 |
+
item = logprobs.get(str(int(token_id)))
|
| 71 |
+
if item is None:
|
| 72 |
+
return None
|
| 73 |
+
rank = item.get("rank")
|
| 74 |
+
if rank is None:
|
| 75 |
+
return None
|
| 76 |
+
return int(rank)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def make_tokens_prompt(token_ids: Sequence[int]) -> Any:
|
| 80 |
+
ids = [int(token_id) for token_id in token_ids]
|
| 81 |
+
try:
|
| 82 |
+
from vllm.inputs import TokensPrompt
|
| 83 |
+
|
| 84 |
+
return TokensPrompt(prompt_token_ids=ids)
|
| 85 |
+
except Exception:
|
| 86 |
+
return {"prompt_token_ids": ids}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def build_llm_kwargs(args: Any) -> Dict[str, Any]:
|
| 90 |
+
kwargs = {
|
| 91 |
+
"model": args.model,
|
| 92 |
+
"dtype": args.dtype,
|
| 93 |
+
"trust_remote_code": args.trust_remote_code,
|
| 94 |
+
"tensor_parallel_size": args.tensor_parallel_size,
|
| 95 |
+
"gpu_memory_utilization": args.gpu_memory_utilization,
|
| 96 |
+
"max_model_len": args.max_model_len,
|
| 97 |
+
"max_num_seqs": getattr(args, "max_num_seqs", None),
|
| 98 |
+
"max_num_batched_tokens": getattr(args, "max_num_batched_tokens", None),
|
| 99 |
+
"max_logprobs": args.max_logprobs,
|
| 100 |
+
"quantization": None if args.quantization == "bf16" else args.quantization,
|
| 101 |
+
}
|
| 102 |
+
return {key: value for key, value in kwargs.items() if value is not None}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def build_sampling_params(args: Any,
|
| 106 |
+
*,
|
| 107 |
+
max_tokens: int,
|
| 108 |
+
logprobs: Optional[int] = None,
|
| 109 |
+
prompt_logprobs: Optional[int] = None,
|
| 110 |
+
detokenize: bool = False) -> Any:
|
| 111 |
+
from vllm import SamplingParams
|
| 112 |
+
|
| 113 |
+
kwargs = {
|
| 114 |
+
"temperature": args.temperature,
|
| 115 |
+
"top_p": args.top_p,
|
| 116 |
+
"top_k": args.top_k if args.top_k > 0 else -1,
|
| 117 |
+
"max_tokens": max_tokens,
|
| 118 |
+
"logprobs": logprobs,
|
| 119 |
+
"prompt_logprobs": prompt_logprobs,
|
| 120 |
+
"seed": args.seed,
|
| 121 |
+
"detokenize": detokenize,
|
| 122 |
+
}
|
| 123 |
+
supported = set()
|
| 124 |
+
try:
|
| 125 |
+
supported = set(inspect.signature(SamplingParams).parameters)
|
| 126 |
+
except (TypeError, ValueError):
|
| 127 |
+
pass
|
| 128 |
+
if supported:
|
| 129 |
+
kwargs = {key: value for key, value in kwargs.items() if key in supported}
|
| 130 |
+
return SamplingParams(**kwargs)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def write_jsonl_row(handle: Any, payload: Dict[str, Any], flush: bool = True) -> None:
|
| 134 |
+
handle.write(json.dumps(payload, ensure_ascii=False, sort_keys=True))
|
| 135 |
+
handle.write("\n")
|
| 136 |
+
if flush:
|
| 137 |
+
handle.flush()
|