Spaces:
Running on Zero
Running on Zero
Permissive missing token scores
#12
by AymenKallala - opened
Files changed (6)
- README.md+1-1
- backend/beam_client.py+40-30
- backend/turns.py+8-1
- frontend/dist/assets/__vite-browser-external-Cgmn0awE-Bd960seU.js → frontend/dist/assets/__vite-browser-external-Cgmn0awE-DVUEt0pE.jsRenamed+1-1
- frontend/dist/assets/index-PgdgOtK5.js → frontend/dist/assets/index-BuvWoEak.jsRenamed
- frontend/dist/index.html+1-1
59 unmodified lines6061626359 unmodified lines.venv/bin/python app.py```Open http://localhost:7860.59 unmodified lines6061626359 unmodified lines.venv/bin/python app.py```Open http://localhost:7860.
145 unmodified lines14614714814915015115215337 unmodified lines1911921931941951961971981992002012022032042052062072082092102118 unmodified lines2202212222232242252262272284 unmodified lines233234235236237238239240241242243244245246247248249250251252252 unmodified lines5055065075085095105115124 unmodified lines517518519520521522523524525526527528529530531532533534535536537538539540541145 unmodified linesfinish == 'tool_calls' and not output.saw_call):raise ValueError('Incomplete Beam turn')if logits is not None and await anext(logits, None) is not None:raise ValueError('More probe scores than generated tokens')if pending is not None:if token_ids is None:raise ValueError('Missing Beam token IDs')37 unmodified linesfor piece in output.consume(choice):if token_count == 0:# Row zero predicts the first token. Later rows score their predecessors.await _next_logit(logits)if pending is not None:yield _scored_piece(pending, await _next_logit(logits))token_count += 1pending = pieceif pending is not None and token_count < output.received:# The successor's token details can arrive before its display channel.yield _scored_piece(pending, await _next_logit(logits))pending = Nonefinish = choice.get('finish_reason')raise ValueError('Incomplete Beam stream')async def _last_token_logit(self, messages: list[Message], ids: list[int]) -> float:"""One discarded prediction returns the activation of the final sampled ID."""response = await self.chat.post('v1/chat/completions',8 unmodified linesresult = response.json()if result['choices'][0]['prompt_token_ids'] != ids:raise ValueError('Beam did not verify the original token IDs')(logit,) = [v async for v in _output_logits(self.probes, _request_id(result))]return logit4 unmodified linesreturn ridasync def _next_logit(logits: AsyncGenerator[float]) -> float:logit = await anext(logits, None)if logit is None:raise ValueError('Fewer probe scores than generated tokens')return logitdef _scored_piece(piece: Piece, logit: object) -> Piece:"""Validate one scored token and compute its display probability."""token_id = piece.get('token_id')if (not isinstance(piece['text'], str)or (token_id is not None and (type(token_id) is not int or token_id < 0))or not isinstance(logit, (float, int))or isinstance(logit, bool)or not math.isfinite(logit)):252 unmodified linesasync def _output_logits(client: httpx.AsyncClient, request_id: str) -> AsyncGenerator[float]:"""Yield contiguous, valid output logits, in generated-token order."""position = 0complete = Falseasync with _score_stream(client, request_id) as response:4 unmodified linesif data == '[DONE]' and complete:returnbatch = json.loads(data)if (batch['rid'] != request_idor batch['offset'] != positionor batch['status'] not in ('running', 'completed')or batch.get('reason') is not Noneor batch.get('invalid_from') is not None):raise ValueError('Interrupted Iris Cyber Probe output scores')monitor = batch['monitors']['cyber']column = _probe_column(monitor['outputs'])for row, valid in zip(monitor['scores'], monitor['valid'], strict=True):if valid is not True:raise ValueError('Missing Iris Cyber Probe output score')position += 1yield row[column]complete = (batch['complete']and not batch['has_more']and batch['output_length'] == position)raise ValueError('Incomplete Iris Cyber Probe score stream')145 unmodified lines14614714814915015115215315437 unmodified lines1921931941951961971981992002012022032042052062072082092102112128 unmodified lines2212222232242252262272282292304 unmodified lines235236237238239240241242243244245246247248249250251252 unmodified lines5045055065075085095105114 unmodified lines516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551145 unmodified linesfinish == 'tool_calls' and not output.saw_call):raise ValueError('Incomplete Beam turn')if logits is not None:async for _ in logits:raise ValueError('More probe scores than generated tokens')if pending is not None:if token_ids is None:raise ValueError('Missing Beam token IDs')37 unmodified linesfor piece in output.consume(choice):if token_count == 0:# Row zero predicts the first token. Later rows score their predecessors.await anext(logits, None)if pending is not None:yield _scored_piece(pending, await anext(logits, None))token_count += 1pending = pieceif pending is not None and token_count < output.received:# The successor's token details can arrive before its display channel.yield _scored_piece(pending, await anext(logits, None))pending = Nonefinish = choice.get('finish_reason')raise ValueError('Incomplete Beam stream')async def _last_token_logit(self, messages: list[Message], ids: list[int]) -> float | None:"""One discarded prediction returns the activation of the final sampled ID."""response = await self.chat.post('v1/chat/completions',8 unmodified linesresult = response.json()if result['choices'][0]['prompt_token_ids'] != ids:raise ValueError('Beam did not verify the original token IDs')rows = [v async for v in _output_logits(self.probes, _request_id(result))]if not rows:return None(logit,) = rowsreturn logit4 unmodified linesreturn riddef _scored_piece(piece: Piece, logit: object) -> Piece:"""Validate one scored token and compute its display probability."""token_id = piece.get('token_id')if not isinstance(piece['text'], str) or (token_id is not None and (type(token_id) is not int or token_id < 0)):raise ValueError('Invalid Beam token')if logit is None:return {**piece, 'logit': None, 'score': None}if (not isinstance(logit, (float, int))or isinstance(logit, bool)or not math.isfinite(logit)):252 unmodified linesasync def _output_logits(client: httpx.AsyncClient, request_id: str) -> AsyncGenerator[float | None]:"""Keep each score or missing row in its original token position."""position = 0complete = Falseasync with _score_stream(client, request_id) as response:4 unmodified linesif data == '[DONE]' and complete:returnbatch = json.loads(data)invalid_from = batch.get('invalid_from')status = batch['status']if invalid_from is None:usable = (status in ('running', 'completed') and batch.get('reason') is None)else:usable = status in ('partial', 'unavailable') and batch['complete']if (batch['rid'] != request_id or batch['offset'] != position or not usable):raise ValueError('Interrupted Iris Cyber Probe output scores')monitor = batch['monitors']['cyber']column = _probe_column(monitor['outputs'])for row, valid in zip(monitor['scores'], monitor['valid'], strict=True):if valid is False or (invalid_from is not None and position >= invalid_from):logit = Noneelif valid is True and row[column] is not None:logit = row[column]else:raise ValueError('Invalid Iris Cyber Probe output score')position += 1yield logitlength = batch['output_length']complete = (batch['complete']and not batch['has_more']and (invalid_from is not None if length is None else position <= length))raise ValueError('Incomplete Iris Cyber Probe score stream')
58 unmodified lines5960616263645 unmodified lines70717273747512 unmodified lines8889909192939458 unmodified linesreasoning = ''reply = ''action = Noneasync with contextlib.aclosing(client.stream_completion(history,5 unmodified linesif isinstance(item, beam_client.Finish):action = itemelse:if item['channel'] == 'reasoning':reasoning += item.get('display', item['text'])elif item['channel'] == 'reply':12 unmodified linesif pass_number == _MAX_CALLS or action.reason != 'tool_calls':raise ValueError('Unexpected tool call')command = guest.command_from(action.call)result = await workspace.run(command)history.append({'role': 'assistant','content': reply or None,58 unmodified lines596061626364655 unmodified lines717273747576777812 unmodified lines91929394959697989910010158 unmodified linesreasoning = ''reply = ''action = Nonemissing_score = Falseasync with contextlib.aclosing(client.stream_completion(history,5 unmodified linesif isinstance(item, beam_client.Finish):action = itemelse:if item['source'] == 'Beam' and item.get('score') is None:missing_score = Trueif item['channel'] == 'reasoning':reasoning += item.get('display', item['text'])elif item['channel'] == 'reply':12 unmodified linesif pass_number == _MAX_CALLS or action.reason != 'tool_calls':raise ValueError('Unexpected tool call')command = guest.command_from(action.call)result = ('Tool call skipped because a probe score was unavailable.'if missing_scoreelse await workspace.run(command))history.append({'role': 'assistant','content': reply or None,
1import{t as e}from"./index-PgdgOtK5.js";var t=e(((e,t)=>{t.exports={}}))();export{t as default};1import{t as e}from"./index-BuvWoEak.js";var t=e(((e,t)=>{t.exports={}}))();export{t as default};
5 unmodified lines67891011125 unmodified lines<meta name="color-scheme" content="light" /><title>Beam and Iris Safeguards</title><link rel="icon" href="data:," /><script type="module" crossorigin src="./assets/index-PgdgOtK5.js"></script><link rel="stylesheet" crossorigin href="./assets/index-JJgGjFsY.css"></head><body>5 unmodified lines67891011125 unmodified lines<meta name="color-scheme" content="light" /><title>Beam and Iris Safeguards</title><link rel="icon" href="data:," /><script type="module" crossorigin src="./assets/index-BuvWoEak.js"></script><link rel="stylesheet" crossorigin href="./assets/index-JJgGjFsY.css"></head><body>
README.md+1-1
backend/beam_client.py+40-30
backend/turns.py+8-1
frontend/dist/assets/__vite-browser-external-Cgmn0awE-Bd960seU.js → frontend/dist/assets/__vite-browser-external-Cgmn0awE-DVUEt0pE.jsRenamed+1-1
frontend/dist/assets/index-PgdgOtK5.js → frontend/dist/assets/index-BuvWoEak.jsRenamed
frontend/dist/index.html+1-1