File size: 3,597 Bytes
d17e09a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""A stub for the vLLM calls of the frozen native-v2 reader, for tests without a model or a GPU.

`install(monkeypatch, lp=...)` replaces the reader's `Client.post` (eval.systemone_vllm.Client) with an in-process
function:
  * /tokenize: one token per character (prompt text, or the JSON of the chat messages + "<think>\\n" when thinking);
  * /detokenize: the inverse (used by the image route);
  * /v1/completions and /v1/chat/completions with max_tokens 1: the logprob of every requested letter token id is
    `lp(prompt_ids, token_id, rank)` (rank = position in `logprob_token_ids`, i.e. option index);
  * generation (thought): a fixed short text and 3 completion tokens.

`hashed_lp` is a deterministic, prompt-dependent logprob (fixture recording); `fixed_lp(values)` returns the same
per-option logprobs for every question (API tests with known log-probabilities).
"""
import hashlib
import json

from wald_serve.native import NativeV2


def hashed_lp(prompt, tid, rank):
    h = hashlib.sha256(json.dumps([list(prompt[-64:]), len(prompt), tid]).encode()).digest()
    return -(int.from_bytes(h[:4], 'big') % 4000) / 1000.0


def fixed_lp(values):
    def lp(prompt, tid, rank):
        return float(values[rank % len(values)])
    return lp


def install(monkeypatch, lp=hashed_lp, engine=None, calls=None):
    """-> (engine, calls). `engine` defaults to a NativeV2 on the repository's temperature table."""
    import eval.systemone_vllm as sov
    calls = [] if calls is None else calls

    def text_of(body):
        text = body.get('prompt')
        if text is None:
            text = json.dumps(body['messages'], sort_keys=True, ensure_ascii=False)
            if body.get('chat_template_kwargs', {}).get('enable_thinking'):
                text += '<think>\n'
        return text

    def post(self, path, body, retries=1):
        calls.append((path, json.loads(json.dumps(body))))
        if path == '/tokenize':
            text = text_of(body)
            if len(text) > 20000:
                raise sov.Capacity('maximum context length')
            return {'tokens': [ord(c) for c in text]}
        if path == '/detokenize':
            return {'prompt': ''.join(chr(t) for t in body['tokens'])}
        if path == '/v1/chat/completions':
            prompt = [ord(c) for c in json.dumps(body['messages'], sort_keys=True)]
            if body['max_tokens'] == 1:
                top = [{'token': f'token_id:{t}', 'logprob': lp(prompt, t, i)} for i, t in enumerate(body['logprob_token_ids'])]
                return {'choices': [{'index': 0, 'message': {'content': 'A'}, 'finish_reason': 'length',
                                     'logprobs': {'content': [{'token': top[0]['token'], 'logprob': top[0]['logprob'],
                                                               'top_logprobs': top}]}}]}
            return {'choices': [{'index': 0, 'message': {'content': 'stub reasoning'}, 'finish_reason': 'stop',
                                 'stop_reason': '</think>'}], 'usage': {'completion_tokens': 3}}
        if body['max_tokens'] == 1:
            top = {f'token_id:{t}': lp(body['prompt'], t, i) for i, t in enumerate(body['logprob_token_ids'])}
            return {'choices': [{'logprobs': {'top_logprobs': [top]}}]}
        return {'choices': [{'text': 'stub reasoning', 'finish_reason': 'stop', 'stop_reason': '</think>'}],
                'usage': {'completion_tokens': 3}}

    monkeypatch.setattr(sov.Client, 'post', post)
    return engine, calls


def make_engine(temperature, cls=NativeV2, **kw):
    return cls('http://unused', temperature, **kw)