logit_bias: normalize a long list once per request instead of five times
A standing ban of a whole script (65,929 IDs) was normalized five times per request: in _openai, twice in validate_request and twice in engine_key. About 200 ms of Python per request, whatever the answer length. A list is now normalized once. The same object again in a request is answered from the last call; an equal list in a later request is found by its compact JSON text, which tells False from 0 and "1" from 1 (== does not: [[7, False]] == [[7, 0]]). Only a list that normalized without an error is stored. Lists under 64 entries skip the cache. No change to what normalize, engine_key and validate_request return or raise.
This commit is contained in:
1 parent
f13a870d52
commit
b6dac80740
2 files changed
+146
-3
No files matched your search
+64
-3
@@ -1,9 +1,12 @@
|
||||
"""Request-scoped token biases. Normalize before HTTP streaming starts."""
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
|
||||
|
||||
def normalize(value, vocab_size=None):
|
||||
def _normalize(value, vocab_size=None):
|
||||
if value is None:
|
||||
return {}
|
||||
if isinstance(value, dict):
|
||||
@@ -36,9 +39,67 @@ def normalize(value, vocab_size=None):
|
||||
return out
|
||||
|
||||
|
||||
# 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
|
||||
# normalized five times per request: in the OpenAI route, twice in validate_request and twice in engine_key (sampling_keys
|
||||
# runs for the cache key and again for the GEN line), about 170 ms for 65,929 entries. A list is now normalized once:
|
||||
# - the same object again in one request is answered from `_last`;
|
||||
# - 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.
|
||||
# Only a list that normalized without an error is stored, so a bad list still raises on every call. Short lists skip the
|
||||
# cache: they cost less than the key.
|
||||
_CACHE_MIN = 64
|
||||
_CACHE_MAX = 4
|
||||
_cache = OrderedDict() # (vocab_size, JSON text) -> [normalized dict, engine key or None]
|
||||
_last = None # [raw value, its length, {vocab_size: entry}]: the object the previous call was given
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def _entry(value, vocab_size):
|
||||
global _last
|
||||
if not isinstance(value, (dict, list)) or len(value) < _CACHE_MIN:
|
||||
return [_normalize(value, vocab_size), None]
|
||||
last = _last
|
||||
if last is not None and last[0] is value and last[1] == len(value):
|
||||
hit = last[2].get(vocab_size)
|
||||
if hit is not None:
|
||||
return hit
|
||||
else:
|
||||
last = None
|
||||
try:
|
||||
key = (vocab_size, json.dumps(value, separators=(",", ":")))
|
||||
except (TypeError, ValueError):
|
||||
key = None # something JSON cannot write: _normalize raises for it
|
||||
entry = None
|
||||
if key is not None:
|
||||
with _lock:
|
||||
entry = _cache.get(key)
|
||||
if entry is not None:
|
||||
_cache.move_to_end(key)
|
||||
if entry is None:
|
||||
entry = [_normalize(value, vocab_size), None]
|
||||
if key is not None:
|
||||
with _lock:
|
||||
_cache[key] = entry
|
||||
while len(_cache) > _CACHE_MAX:
|
||||
_cache.popitem(last=False)
|
||||
if key is not None:
|
||||
if last is None:
|
||||
last = [value, len(value), {}]
|
||||
_last = last
|
||||
last[2][vocab_size] = entry
|
||||
return entry
|
||||
|
||||
|
||||
def normalize(value, vocab_size=None):
|
||||
return dict(_entry(value, vocab_size)[0])
|
||||
|
||||
|
||||
def engine_key(value):
|
||||
entries = normalize(value)
|
||||
return " logit_bias=" + ",".join(f"{i}:{b:g}" for i, b in sorted(entries.items())) if entries else ""
|
||||
entry = _entry(value, None)
|
||||
if not entry[0]:
|
||||
return ""
|
||||
if entry[1] is None:
|
||||
entry[1] = " logit_bias=" + ",".join(f"{i}:{b:g}" for i, b in sorted(entry[0].items()))
|
||||
return entry[1]
|
||||
|
||||
|
||||
def validate_request(req, engine, vocab_size):
|
||||
|
||||
@@ -59,3 +59,85 @@ class LogitBias(unittest.TestCase):
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
class LogitBiasCache(unittest.TestCase):
|
||||
"""A long list is normalized once; the cache must not change what a call returns or raises."""
|
||||
|
||||
def setUp(self):
|
||||
from serve import logit_bias
|
||||
logit_bias._cache.clear()
|
||||
logit_bias._last = None
|
||||
|
||||
def test_same_answers_as_the_plain_function(self):
|
||||
from serve.logit_bias import _normalize
|
||||
forms = [{str(i): -100 for i in range(200)},
|
||||
[[i, False] for i in range(200)],
|
||||
{str(i): (i % 7) - 3.5 for i in range(200)},
|
||||
[[str(i), 2] for i in range(200)]]
|
||||
for vocab in (None, 1000):
|
||||
for form in forms:
|
||||
want = _normalize(form, vocab)
|
||||
for _ in range(3): # the first call fills the cache, the others read it
|
||||
self.assertEqual(normalize(form, vocab), want)
|
||||
self.assertEqual(normalize(json.loads(json.dumps(form)), vocab), want) # an equal list, another object
|
||||
for form in forms:
|
||||
ref = " logit_bias=" + ",".join(f"{i}:{b:g}" for i, b in sorted(_normalize(form).items()))
|
||||
self.assertEqual(engine_key(form), ref)
|
||||
self.assertEqual(engine_key(form), ref)
|
||||
|
||||
def test_false_is_not_zero(self):
|
||||
ban = [[i, False] for i in range(100)]
|
||||
zero = [[i, 0] for i in range(100)]
|
||||
self.assertTrue(ban == zero) # Python calls them equal, so an == key would mix them up
|
||||
for first, second in [(ban, zero), (zero, ban)]:
|
||||
self.setUp()
|
||||
self.assertEqual(set(normalize(first).values()), {-100.0 if first is ban else 0.0})
|
||||
self.assertEqual(set(normalize(second).values()), {-100.0 if second is ban else 0.0})
|
||||
|
||||
def test_a_bad_list_is_never_stored(self):
|
||||
good = {str(i): -1 for i in range(100)}
|
||||
normalize(good, 1000)
|
||||
for bad in [{**good, "5": True}, {**good, "5": 101}, {**good, "5": float("nan")}, {**good, "5": "x"}]:
|
||||
for _ in range(2):
|
||||
with self.assertRaises(ValueError):
|
||||
normalize(bad, 1000)
|
||||
pairs = [[i, 1] for i in range(100)]
|
||||
normalize(pairs)
|
||||
with self.assertRaises(ValueError): # True == 1, but a bool is not a bias
|
||||
normalize([[i, 1] for i in range(99)] + [[99, True]])
|
||||
with self.assertRaises(ValueError): # a duplicate ID
|
||||
normalize([[i, 1] for i in range(100)] + [[0, 1]])
|
||||
|
||||
def test_vocabulary_size_is_part_of_the_key(self):
|
||||
ids = {str(i): -1 for i in range(100)}
|
||||
self.assertEqual(len(normalize(ids, 1000)), 100)
|
||||
with self.assertRaises(ValueError):
|
||||
normalize(ids, 50)
|
||||
self.assertEqual(len(normalize(ids)), 100)
|
||||
with self.assertRaises(ValueError):
|
||||
normalize(ids, 50)
|
||||
|
||||
def test_the_result_is_a_copy(self):
|
||||
ids = {str(i): -1 for i in range(100)}
|
||||
first = normalize(ids)
|
||||
first[0] = 99.0
|
||||
self.assertEqual(normalize(ids)[0], -1.0)
|
||||
self.assertEqual(validate_request({"logit_bias": ids}, SimpleNamespace(info={"logit_bias": 1}), 1000)[0], -1.0)
|
||||
|
||||
def test_an_equal_list_in_a_later_request_is_a_hit(self):
|
||||
from serve import logit_bias
|
||||
a = {str(i): -100 for i in range(100)}
|
||||
b = json.loads(json.dumps(a))
|
||||
self.assertIsNot(a, b)
|
||||
key_a = engine_key(a)
|
||||
logit_bias._last = None # a later request: the previous object is gone
|
||||
key_b = engine_key(b)
|
||||
self.assertIs(key_a, key_b) # one entry, one key string
|
||||
self.assertEqual(len(logit_bias._cache), 1)
|
||||
|
||||
def test_the_cache_is_bounded(self):
|
||||
from serve import logit_bias
|
||||
for n in range(logit_bias._CACHE_MAX + 3):
|
||||
normalize({str(i): -(n + 1) for i in range(100)})
|
||||
self.assertEqual(len(logit_bias._cache), logit_bias._CACHE_MAX)
|
||||
Reference in new issue
Block a user