okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
379e893f8
main
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 ): 10if value is None : 11return {} 12if isinstance (value ,dict ): 13entries = value .items () 14pairs = False 15elif isinstance (value ,list ): 16entries = value 17pairs = True 18else : 19raise ValueError ("logit_bias: expected an object or a list of [token_id, bias] pairs" ) 20out = {} 21for entry in entries : 22if not isinstance (entry , (list ,tuple ))or len (entry )!= 2 : 23raise ValueError ("logit_bias: each entry must be [token_id, bias]" ) 24token ,bias = entry 25if isinstance (token ,bool )or not isinstance (token , (str ,int ))or not re .fullmatch (r"[0-9]+" ,str (token )): 26raise ValueError ("logit_bias: token IDs must be non-negative integers" ) 27token = int (token ) 28if token > 2147483647 or (vocab_size is not None and token >= vocab_size ): 29raise ValueError ("logit_bias: token ID outside the model vocabulary" ) 30if token in out : 31raise ValueError ("logit_bias: duplicate token ID" ) 32if pairs and bias is False : 33bias = - 100.0 34if isinstance (bias ,bool )or not isinstance (bias , (int ,float ))or not - 100 <= bias <= 100 or not math .isfinite (bias ): 35raise ValueError ("logit_bias: biases must be finite numbers between -100 and 100; false is a pair-list ban" ) 36out [token ]= float (bias ) 37if vocab_size is not None and sum (b == - 100 for b in out .values ())== vocab_size : 38raise ValueError ("logit_bias: cannot ban the entire vocabulary" ) 39return 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 ): 57global _last 58if not isinstance (value , (dict ,list ))or len (value )< _CACHE_MIN : 59return [_normalize (value ,vocab_size ),None ] 60last = _last 61if last is not None and last [0 ]is value and last [1 ]== len (value ): 62hit = last [2 ].get (vocab_size ) 63if hit is not None : 64return hit 65else : 66last = None 67try : 68key = (vocab_size ,json .dumps (value ,separators = ("," ,":" ))) 69except (TypeError ,ValueError ): 70key = None # something JSON cannot write: _normalize raises for it 71entry = None 72if key is not None : 73with _lock : 74entry = _cache .get (key ) 75if entry is not None : 76_cache .move_to_end (key ) 77if entry is None : 78entry = [_normalize (value ,vocab_size ),None ] 79if key is not None : 80with _lock : 81_cache [key ]= entry 82while len (_cache )> _CACHE_MAX : 83_cache .popitem (last = False ) 84if key is not None : 85if last is None : 86last = [value ,len (value ), {}] 87_last = last 88last [2 ][vocab_size ]= entry 89return entry 90 91 92def normalize (value ,vocab_size = None ): 93return dict (_entry (value ,vocab_size )[0 ]) 94 95 96def engine_key (value ): 97entry = _entry (value ,None ) 98if not entry [0 ]: 99return "" 100if entry [1 ]is None : 101entry [1 ]= " logit_bias=" + "," .join (f" { i } : { b :g } " for i ,b in sorted (entry [0 ].items ())) 102return 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).""" 107normalized = normalize (req .get ("logit_bias" ),vocab_size ) 108if normalized : 109if getattr (engine ,"split_engine" ,False ): 110raise ValueError ("logit_bias: not supported by the all-cards split engine; start with --split-engine off" ) 111if getattr (engine ,"info" , {}).get ("logit_bias" )!= 1 : 112raise ValueError ("logit_bias: this engine does not support token biases; use a supporting CUDA/HIP build" ) 113return normalized