okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0291-rc1-split-keys: the server stops sending pen_from to the split engine; logprobs/logit_bias answer 400 naming --split-engine off379e893f8

main
4.7 KiB113 linesraw
1"""Request-scoped token biases. Normalize before HTTP streaming starts."""
2import json
3import math
4import re
5import threading
6from collections import OrderedDict
7
8
9def _normalize(value, vocab_size=None):
10    if value is None:
11        return {}
12    if isinstance(value, dict):
13        entries = value.items()
14        pairs = False
15    elif isinstance(value, list):
16        entries = value
17        pairs = True
18    else:
19        raise ValueError("logit_bias: expected an object or a list of [token_id, bias] pairs")
20    out = {}
21    for entry in entries:
22        if not isinstance(entry, (list, tuple)) or len(entry) != 2:
23            raise ValueError("logit_bias: each entry must be [token_id, bias]")
24        token, bias = entry
25        if isinstance(token, bool) or not isinstance(token, (str, int)) or not re.fullmatch(r"[0-9]+", str(token)):
26            raise ValueError("logit_bias: token IDs must be non-negative integers")
27        token = int(token)
28        if token > 2147483647 or (vocab_size is not None and token >= vocab_size):
29            raise ValueError("logit_bias: token ID outside the model vocabulary")
30        if token in out:
31            raise ValueError("logit_bias: duplicate token ID")
32        if pairs and bias is False:
33            bias = -100.0
34        if isinstance(bias, bool) or not isinstance(bias, (int, float)) or not -100 <= bias <= 100 or not math.isfinite(bias):
35            raise ValueError("logit_bias: biases must be finite numbers between -100 and 100; false is a pair-list ban")
36        out[token] = float(bias)
37    if vocab_size is not None and sum(b == -100 for b in out.values()) == vocab_size:
38        raise ValueError("logit_bias: cannot ban the entire vocabulary")
39    return out
40
41
42# A long list (a standing ban of a whole script is tens of thousands of IDs) is sent with every request and used to be
43# normalized five times per request: in the OpenAI route, twice in validate_request and twice in engine_key (sampling_keys
44# runs for the cache key and again for the GEN line), about 170 ms for 65,929 entries.  A list is now normalized once:
45#  - the same object again in one request is answered from `_last`;
46#  - an equal list in a later request is found by its JSON text, an exact key that tells False from 0 and "1" from 1.
47# Only a list that normalized without an error is stored, so a bad list still raises on every call.  Short lists skip the
48# cache: they cost less than the key.
49_CACHE_MIN = 64
50_CACHE_MAX = 4
51_cache = OrderedDict()   # (vocab_size, JSON text) -> [normalized dict, engine key or None]
52_last = None             # [raw value, its length, {vocab_size: entry}]: the object the previous call was given
53_lock = threading.Lock()
54
55
56def _entry(value, vocab_size):
57    global _last
58    if not isinstance(value, (dict, list)) or len(value) < _CACHE_MIN:
59        return [_normalize(value, vocab_size), None]
60    last = _last
61    if last is not None and last[0] is value and last[1] == len(value):
62        hit = last[2].get(vocab_size)
63        if hit is not None:
64            return hit
65    else:
66        last = None
67    try:
68        key = (vocab_size, json.dumps(value, separators=(",", ":")))
69    except (TypeError, ValueError):
70        key = None   # something JSON cannot write: _normalize raises for it
71    entry = None
72    if key is not None:
73        with _lock:
74            entry = _cache.get(key)
75            if entry is not None:
76                _cache.move_to_end(key)
77    if entry is None:
78        entry = [_normalize(value, vocab_size), None]
79        if key is not None:
80            with _lock:
81                _cache[key] = entry
82                while len(_cache) > _CACHE_MAX:
83                    _cache.popitem(last=False)
84    if key is not None:
85        if last is None:
86            last = [value, len(value), {}]
87            _last = last
88        last[2][vocab_size] = entry
89    return entry
90
91
92def normalize(value, vocab_size=None):
93    return dict(_entry(value, vocab_size)[0])
94
95
96def engine_key(value):
97    entry = _entry(value, None)
98    if not entry[0]:
99        return ""
100    if entry[1] is None:
101        entry[1] = " logit_bias=" + ",".join(f"{i}:{b:g}" for i, b in sorted(entry[0].items()))
102    return entry[1]
103
104
105def validate_request(req, engine, vocab_size):
106    """Fail closed for old engines and unsupported backends (continuous batching carries a slot's bias since the slot-penalty change)."""
107    normalized = normalize(req.get("logit_bias"), vocab_size)
108    if normalized:
109        if getattr(engine, "split_engine", False):
110            raise ValueError("logit_bias: not supported by the all-cards split engine; start with --split-engine off")
111        if getattr(engine, "info", {}).get("logit_bias") != 1:
112            raise ValueError("logit_bias: this engine does not support token biases; use a supporting CUDA/HIP build")
113    return normalized