File size: 3,358 Bytes
688186a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3
"""Needle-in-a-haystack over OpenAI-compatible API (seeded, JSON output).

Contexts default to 32k and 128k (target prompt tokens; the real count is recorded per depth).
The server must run with --max-model-len > the largest context + max_tokens.
"""
import argparse
import json
import random
import sys

from openai import OpenAI


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--base-url", default="http://localhost:8000/v1")
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--out", default="results/needle.json")
    parser.add_argument("--model", default="inkling", help="served model name")
    parser.add_argument("--reasoning-effort", default="low")
    parser.add_argument("--contexts", default="32000,120000", help="comma list of target prompt tokens")
    parser.add_argument("--max-tokens", type=int, default=8192, help="room for reasoning before the answer")
    args = parser.parse_args()

    random.seed(args.seed)
    client = OpenAI(base_url=args.base_url, api_key="EMPTY")
    filler = (
        "The grass is green. The sky is blue. The sun is yellow. "
        "Here we go. There and back again. "
    ) * 20000
    chars_per_tok = 4  # rough; actual prompt_tokens is recorded
    depths = [0.1, 0.3, 0.5, 0.7, 0.9]
    contexts = [int(c) for c in args.contexts.split(",")]

    results: list[dict] = []
    for ctx in contexts:
        row = {"context_tokens_target": ctx, "depths": []}
        hits = 0
        for depth in depths:
            code = random.randint(100000, 999999)
            hay = filler[: ctx * chars_per_tok]
            pos = int(len(hay) * depth)
            text = hay[:pos] + f" The secret pass code is {code}. " + hay[pos:]
            depth_row = {
                "depth": depth,
                "code": code,
                "hit": False,
                "prompt_tokens": None,
                "error": None,
            }
            try:
                r = client.chat.completions.create(
                    model=args.model,
                    temperature=0,
                    max_tokens=args.max_tokens,
                    extra_body={"chat_template_kwargs": {"reasoning_effort": args.reasoning_effort}},
                    messages=[
                        {
                            "role": "user",
                            "content": text
                            + "\n\nWhat is the secret pass code? Reply with the number only.",
                        }
                    ],
                )
                content = r.choices[0].message.content or ""
                depth_row["hit"] = str(code) in content
                depth_row["prompt_tokens"] = getattr(r.usage, "prompt_tokens", None)
                hits += depth_row["hit"]
            except Exception as e:  # noqa: BLE001 — record per-depth API errors
                depth_row["error"] = str(e)
            row["depths"].append(depth_row)
        row["hits"] = hits
        row["total"] = len(depths)
        results.append(row)
        print(f"{ctx:>7} tokens : {hits}/{len(depths)}")

    payload = {"seed": args.seed, "reasoning_effort": args.reasoning_effort, "results": results}
    with open(args.out, "w", encoding="utf-8") as f:
        json.dump(payload, f, indent=2)


if __name__ == "__main__":
    main()