Spaces:
Running on Zero
Running on Zero
File size: 4,982 Bytes
85ea1d3 | 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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | """Progress and time estimates for the stages of answering one question.
Estimates come from how long each kind of stage took on earlier questions, so they are rough on the first
question and improve as the demo is used. Generation length is unknown in advance, so progress inside a
generating stage is measured against the average length seen so far, and is capped below 100% until it ends.
"""
import time
from dataclasses import dataclass
# Starting guesses, replaced by observed values after the first run of each stage kind.
DEFAULT_SECONDS = {"search": 1.0, "read": 10.0, "answer_notes": 6.0, "answer_text": 8.0}
DEFAULT_TOKENS = {"read": 150.0, "answer_notes": 100.0, "answer_text": 100.0}
SMOOTHING = 0.5 # weight of the newest observation in the running averages
IN_STAGE_CAP = 0.95
_seconds: dict[str, float] = {}
_tokens: dict[str, float] = {}
@dataclass
class Stage:
"""One step of the pipeline. Stages with the same `key` share a running time estimate."""
key: str
label: str
def _blend(store: dict[str, float], key: str, value: float) -> None:
store[key] = value if key not in store else SMOOTHING * value + (1 - SMOOTHING) * store[key]
def expected_seconds(key: str) -> float:
"""Expected duration of a stage kind."""
return _seconds.get(key, DEFAULT_SECONDS[key])
def expected_tokens(key: str) -> float:
"""Expected generated length of a stage kind."""
return _tokens.get(key, DEFAULT_TOKENS.get(key, 1.0))
class Tracker:
"""Follows one question through its stages and renders a progress bar."""
def __init__(self, stages: list[Stage]) -> None:
"""Start timing; `stages` may be replaced once the pages to read are known."""
self.stages = stages
# Stage weights are fixed when planned, so learning from a finished stage never moves the bar backwards.
self.weights = [expected_seconds(s.key) for s in stages]
self.finished: list[tuple[str, float]] = []
self.tokens = 0
self._peak = 0.0
self._start = self._stage_start = time.perf_counter()
def set_stages(self, stages: list[Stage]) -> None:
"""Replace the plan; stages already finished keep their weights."""
done = len(self.finished)
self.stages = stages
self.weights = self.weights[:done] + [expected_seconds(s.key) for s in stages[done:]]
def update(self, tokens: int) -> None:
"""Record how many tokens the current stage has generated so far."""
self.tokens = tokens
def advance(self) -> None:
"""Mark the current stage finished and learn from how long it took."""
index = len(self.finished)
now = time.perf_counter()
stage = self.stages[index]
seconds = now - self._stage_start
self.finished.append((stage.label, seconds))
_blend(_seconds, stage.key, seconds)
if self.tokens:
_blend(_tokens, stage.key, float(self.tokens))
self._stage_start, self.tokens = now, 0
def _current_fraction(self, stage: Stage) -> float:
if stage.key == "search" or not self.tokens:
return 0.0
return min(self.tokens / expected_tokens(stage.key), IN_STAGE_CAP)
def percent_and_remaining(self) -> tuple[float, float]:
"""Estimated percent complete (never decreasing) and seconds left."""
index = len(self.finished)
if index >= len(self.stages):
return 100.0, 0.0
in_stage = self._current_fraction(self.stages[index])
total = sum(self.weights)
elapsed = sum(self.weights[:index]) + self.weights[index] * in_stage
remaining = sum(self.weights[index + 1 :]) + self.weights[index] * (1 - in_stage)
self._peak = max(self._peak, 100 * elapsed / total)
return self._peak, remaining
def render(self, finished: bool = False) -> str:
"""HTML for the progress bar, or the timing breakdown once finished."""
elapsed = time.perf_counter() - self._start
if finished:
steps = " 路 ".join(f"{label} {seconds:.1f}s" for label, seconds in self.finished)
return _bar(100, f"Done in {elapsed:.1f}s", steps)
percent, remaining = self.percent_and_remaining()
index = min(len(self.finished), len(self.stages) - 1)
calibrated = all(s.key in _seconds for s in self.stages)
eta = f" 路 about {remaining:.0f}s left" if calibrated else " 路 estimating time left..."
return _bar(percent, f"{self.stages[index].label}: ~{percent:.0f}%", f"{elapsed:.0f}s elapsed{eta}")
def _bar(percent: float, title: str, detail: str) -> str:
"""Styled by `.run-progress` in app.css."""
return (
"<div class='run-progress'>"
f"<div class='run-progress__head'><span class='run-progress__title'>{title}</span>"
f"<span class='run-progress__detail'>{detail}</span></div>"
f"<div class='run-progress__bar'><i style='width:{percent:.0f}%'></i></div></div>"
)
|