193 lines
8.4 KiB
Python
193 lines
8.4 KiB
Python
"""Bounded model admission shared by work-assistant modules in this worker."""
|
|
import threading
|
|
import time
|
|
from .bid_timing import RECOVERY_SECONDS
|
|
from contextvars import ContextVar
|
|
from contextlib import contextmanager
|
|
|
|
|
|
background_review = ContextVar("background_review", default=False)
|
|
reserved_turn = ContextVar("reserved_model_turn", default=None)
|
|
parallel_bid = ContextVar("parallel_bid_requests", default=False)
|
|
|
|
|
|
class DispatchUnavailable(RuntimeError):
|
|
pass
|
|
|
|
|
|
class ModelDispatch:
|
|
def __init__(self, max_active=2, background_limit=1, token_budget=None, start_interval=.5, execution_slots=None):
|
|
# Explicit limits retain compatibility with existing embedded callers.
|
|
# The application singleton below uses the measured three-GPU policy.
|
|
self.max_active = max_active
|
|
self.background_limit = background_limit
|
|
self.token_budget = token_budget
|
|
self.execution_slots = min(max_active, execution_slots or max_active)
|
|
self.start_interval = start_interval
|
|
self.active_tokens = 0
|
|
self.active_costs = []
|
|
self.condition = threading.Condition()
|
|
self.active = 0
|
|
self.background_active = 0
|
|
self.waiting = []
|
|
self.failures = 0
|
|
self.open_until = 0.0
|
|
self.probing = False
|
|
self.last_start = 0.0
|
|
self.last_failure = 0.0
|
|
|
|
def ready_at(self, background=False):
|
|
return min(self.open_until, self.last_failure + RECOVERY_SECONDS) if background else self.open_until
|
|
|
|
def waiting_state(self):
|
|
with self.condition:
|
|
delay = max(0, self.ready_at(True) - time.monotonic())
|
|
if delay:
|
|
return 'circuit_open', delay
|
|
if self.probing:
|
|
return 'model_recovery_probe', 0
|
|
if self.background_active >= self.background_limit or self.active >= self.max_active:
|
|
return 'model_busy', 0
|
|
return '', 0
|
|
|
|
def snapshot(self):
|
|
with self.condition:
|
|
return {'active': self.active, 'waiting': len(self.waiting),
|
|
'background_active': self.background_active, 'limit': self.max_active,
|
|
'reserved_tokens': self.active_tokens, 'token_budget': self.token_budget,
|
|
'execution_slots': self.execution_slots,
|
|
'recovery_probe': self.probing}
|
|
|
|
def reserved_capacity(self, extra=None):
|
|
# The server executes at most execution_slots; additional HTTP calls
|
|
# wait there to refill the batch promptly. Reserve the worst possible
|
|
# simultaneous subset, including queued long requests.
|
|
costs = self.active_costs + ([] if extra is None else [extra])
|
|
return sum(sorted(costs, reverse=True)[:self.execution_slots])
|
|
|
|
def acquire(self, timeout, tokens=None):
|
|
deadline = time.monotonic() + timeout
|
|
background = background_review.get()
|
|
# Calibrated for the deployed Qwen hybrid cache: 2096-token attention
|
|
# pages plus three recurrent groups, each needing up to two states.
|
|
# 1500 token-equivalent units per shared block slightly round up the
|
|
# measured conversion. Unknown/image requests reserve the full context.
|
|
pages = (max(1, min(32768, int(tokens if tokens is not None else 32768))) + 2095) // 2096
|
|
cost = 1500 * (pages + (3 if pages == 1 else 6)) if self.token_budget else 0
|
|
if self.token_budget and cost > self.token_budget:
|
|
raise DispatchUnavailable('context_capacity')
|
|
ticket = (time.monotonic(), background, object(), parallel_bid.get(), cost)
|
|
with self.condition:
|
|
if len(self.waiting) >= 128:
|
|
raise DispatchUnavailable("queue_full")
|
|
self.waiting.append(ticket)
|
|
try:
|
|
while True:
|
|
now = time.monotonic()
|
|
if self.ready_at(background) > now or self.probing:
|
|
raise DispatchUnavailable("circuit_open")
|
|
if now >= deadline:
|
|
raise DispatchUnavailable("queue_timeout")
|
|
# Interactive requests first; background requests age to avoid starvation.
|
|
eligible = sorted((item for item in self.waiting
|
|
if not item[1] or self.background_active < max(self.background_limit, 2 if item[3] else 1)),
|
|
key=lambda item: (item[1] and now - item[0] < 2, item[0]))
|
|
first = None
|
|
for item in eligible:
|
|
if not self.token_budget or self.reserved_capacity(item[4]) <= self.token_budget:
|
|
first = item
|
|
break
|
|
# Let an aged large request drain the pool rather than
|
|
# starving behind an endless stream of small requests.
|
|
if now - item[0] >= 2:
|
|
break
|
|
if (first is ticket and self.active < self.max_active
|
|
and now - self.last_start >= self.start_interval
|
|
and (not self.open_until or self.active == 0)):
|
|
self.active += 1
|
|
self.background_active += int(background)
|
|
self.active_costs.append(cost)
|
|
self.active_tokens = self.reserved_capacity()
|
|
self.probing = bool(self.open_until)
|
|
self.last_start = now
|
|
return background, self.probing, cost
|
|
wait = min(0.2, deadline - now)
|
|
spacing = self.start_interval - (now - self.last_start)
|
|
if first is ticket and 0 < spacing < wait:
|
|
wait = spacing
|
|
self.condition.wait(wait)
|
|
finally:
|
|
self.waiting.remove(ticket)
|
|
self.condition.notify_all()
|
|
|
|
def release(self, ticket, failure=False):
|
|
background, probe, cost = ticket
|
|
with self.condition:
|
|
self.active -= 1
|
|
self.background_active -= int(background)
|
|
self.active_costs.remove(cost)
|
|
self.active_tokens = self.reserved_capacity()
|
|
if failure:
|
|
self.failures += 1
|
|
self.last_failure = time.monotonic()
|
|
if probe or self.failures >= 3:
|
|
self.open_until = time.monotonic() + min(300, 30 * 2 ** min(4, self.failures - 3))
|
|
elif probe or not self.open_until:
|
|
self.failures = 0
|
|
self.open_until = 0.0
|
|
if probe:
|
|
self.probing = False
|
|
self.condition.notify_all()
|
|
|
|
|
|
def configured_dispatch():
|
|
from app.core.config import get_settings
|
|
settings = get_settings()
|
|
return ModelDispatch(max_active=settings.work_assistant_model_concurrency,
|
|
background_limit=settings.work_assistant_model_concurrency,
|
|
execution_slots=settings.work_assistant_model_execution_slots,
|
|
token_budget=settings.work_assistant_model_token_budget, start_interval=.05)
|
|
|
|
|
|
dispatch = configured_dispatch()
|
|
|
|
|
|
@contextmanager
|
|
def parallel_model_turn():
|
|
"""Independent background calls share the configured model capacity.
|
|
|
|
Admission happens for each call, so waiting interactive requests can run
|
|
between extraction and audits instead of waiting for an entire bid step.
|
|
"""
|
|
with dispatch.condition:
|
|
if dispatch.ready_at(True) > time.monotonic() or dispatch.probing:
|
|
raise DispatchUnavailable('circuit_open')
|
|
background_token = background_review.set(True)
|
|
parallel_token = parallel_bid.set(True)
|
|
reservation_token = reserved_turn.set(None)
|
|
try:
|
|
yield
|
|
finally:
|
|
reserved_turn.reset(reservation_token)
|
|
parallel_bid.reset(parallel_token)
|
|
background_review.reset(background_token)
|
|
|
|
|
|
@contextmanager
|
|
def model_turn(timeout=30):
|
|
"""A queued background step waits once, then keeps its slot during revisions."""
|
|
background_token = background_review.set(True)
|
|
ticket = None
|
|
reservation = {'failed': False}
|
|
token = None
|
|
try:
|
|
ticket = dispatch.acquire(timeout)
|
|
token = reserved_turn.set(reservation)
|
|
yield
|
|
finally:
|
|
if token is not None:
|
|
reserved_turn.reset(token)
|
|
if ticket is not None:
|
|
dispatch.release(ticket, reservation['failed'])
|
|
background_review.reset(background_token)
|