Permissive missing token scores

#12
by AymenKallala - opened
README.md CHANGED
@@ -60,4 +60,4 @@ uv pip install -r requirements.txt
60
  .venv/bin/python app.py
61
  ```
62
 
63
- Open http://localhost:7860.
 
60
  .venv/bin/python app.py
61
  ```
62
 
63
+ Open http://localhost:7860.
backend/beam_client.py CHANGED
@@ -146,8 +146,9 @@ class BeamClient:
146
  finish == 'tool_calls' and not output.saw_call
147
  ):
148
  raise ValueError('Incomplete Beam turn')
149
- if logits is not None and await anext(logits, None) is not None:
150
- raise ValueError('More probe scores than generated tokens')
 
151
  if pending is not None:
152
  if token_ids is None:
153
  raise ValueError('Missing Beam token IDs')
@@ -191,21 +192,21 @@ class BeamClient:
191
  for piece in output.consume(choice):
192
  if token_count == 0:
193
  # Row zero predicts the first token. Later rows score their predecessors.
194
- await _next_logit(logits)
195
  if pending is not None:
196
- yield _scored_piece(pending, await _next_logit(logits))
197
  token_count += 1
198
  pending = piece
199
  if pending is not None and token_count < output.received:
200
  # The successor's token details can arrive before its display channel.
201
- yield _scored_piece(pending, await _next_logit(logits))
202
  pending = None
203
  finish = choice.get('finish_reason')
204
  raise ValueError('Incomplete Beam stream')
205
 
206
  async def _last_token_logit(
207
  self, messages: list[Message], ids: list[int]
208
- ) -> float:
209
  """One discarded prediction returns the activation of the final sampled ID."""
210
  response = await self.chat.post(
211
  'v1/chat/completions',
@@ -220,9 +221,10 @@ class BeamClient:
220
  result = response.json()
221
  if result['choices'][0]['prompt_token_ids'] != ids:
222
  raise ValueError('Beam did not verify the original token IDs')
223
- (logit,) = [
224
- v async for v in _output_logits(self.probes, _request_id(result))
225
- ]
 
226
  return logit
227
 
228
 
@@ -233,20 +235,17 @@ def _request_id(response: Message) -> str:
233
  return rid
234
 
235
 
236
- async def _next_logit(logits: AsyncGenerator[float]) -> float:
237
- logit = await anext(logits, None)
238
- if logit is None:
239
- raise ValueError('Fewer probe scores than generated tokens')
240
- return logit
241
-
242
-
243
  def _scored_piece(piece: Piece, logit: object) -> Piece:
244
  """Validate one scored token and compute its display probability."""
245
  token_id = piece.get('token_id')
 
 
 
 
 
 
246
  if (
247
- not isinstance(piece['text'], str)
248
- or (token_id is not None and (type(token_id) is not int or token_id < 0))
249
- or not isinstance(logit, (float, int))
250
  or isinstance(logit, bool)
251
  or not math.isfinite(logit)
252
  ):
@@ -505,8 +504,8 @@ def _probe_column(outputs: list[dict[str, str]]) -> int:
505
 
506
  async def _output_logits(
507
  client: httpx.AsyncClient, request_id: str
508
- ) -> AsyncGenerator[float]:
509
- """Yield contiguous, valid output logits, in generated-token order."""
510
  position = 0
511
  complete = False
512
  async with _score_stream(client, request_id) as response:
@@ -517,25 +516,36 @@ async def _output_logits(
517
  if data == '[DONE]' and complete:
518
  return
519
  batch = json.loads(data)
 
 
 
 
 
 
 
 
520
  if (
521
- batch['rid'] != request_id
522
- or batch['offset'] != position
523
- or batch['status'] not in ('running', 'completed')
524
- or batch.get('reason') is not None
525
- or batch.get('invalid_from') is not None
526
  ):
527
  raise ValueError('Interrupted Iris Cyber Probe output scores')
528
  monitor = batch['monitors']['cyber']
529
  column = _probe_column(monitor['outputs'])
530
  for row, valid in zip(monitor['scores'], monitor['valid'], strict=True):
531
- if valid is not True:
532
- raise ValueError('Missing Iris Cyber Probe output score')
 
 
 
 
 
 
533
  position += 1
534
- yield row[column]
 
535
  complete = (
536
  batch['complete']
537
  and not batch['has_more']
538
- and batch['output_length'] == position
539
  )
540
  raise ValueError('Incomplete Iris Cyber Probe score stream')
541
 
 
146
  finish == 'tool_calls' and not output.saw_call
147
  ):
148
  raise ValueError('Incomplete Beam turn')
149
+ if logits is not None:
150
+ async for _ in logits:
151
+ raise ValueError('More probe scores than generated tokens')
152
  if pending is not None:
153
  if token_ids is None:
154
  raise ValueError('Missing Beam token IDs')
 
192
  for piece in output.consume(choice):
193
  if token_count == 0:
194
  # Row zero predicts the first token. Later rows score their predecessors.
195
+ await anext(logits, None)
196
  if pending is not None:
197
+ yield _scored_piece(pending, await anext(logits, None))
198
  token_count += 1
199
  pending = piece
200
  if pending is not None and token_count < output.received:
201
  # The successor's token details can arrive before its display channel.
202
+ yield _scored_piece(pending, await anext(logits, None))
203
  pending = None
204
  finish = choice.get('finish_reason')
205
  raise ValueError('Incomplete Beam stream')
206
 
207
  async def _last_token_logit(
208
  self, messages: list[Message], ids: list[int]
209
+ ) -> float | None:
210
  """One discarded prediction returns the activation of the final sampled ID."""
211
  response = await self.chat.post(
212
  'v1/chat/completions',
 
221
  result = response.json()
222
  if result['choices'][0]['prompt_token_ids'] != ids:
223
  raise ValueError('Beam did not verify the original token IDs')
224
+ rows = [v async for v in _output_logits(self.probes, _request_id(result))]
225
+ if not rows:
226
+ return None
227
+ (logit,) = rows
228
  return logit
229
 
230
 
 
235
  return rid
236
 
237
 
 
 
 
 
 
 
 
238
  def _scored_piece(piece: Piece, logit: object) -> Piece:
239
  """Validate one scored token and compute its display probability."""
240
  token_id = piece.get('token_id')
241
+ if not isinstance(piece['text'], str) or (
242
+ token_id is not None and (type(token_id) is not int or token_id < 0)
243
+ ):
244
+ raise ValueError('Invalid Beam token')
245
+ if logit is None:
246
+ return {**piece, 'logit': None, 'score': None}
247
  if (
248
+ not isinstance(logit, (float, int))
 
 
249
  or isinstance(logit, bool)
250
  or not math.isfinite(logit)
251
  ):
 
504
 
505
  async def _output_logits(
506
  client: httpx.AsyncClient, request_id: str
507
+ ) -> AsyncGenerator[float | None]:
508
+ """Keep each score or missing row in its original token position."""
509
  position = 0
510
  complete = False
511
  async with _score_stream(client, request_id) as response:
 
516
  if data == '[DONE]' and complete:
517
  return
518
  batch = json.loads(data)
519
+ invalid_from = batch.get('invalid_from')
520
+ status = batch['status']
521
+ if invalid_from is None:
522
+ usable = (
523
+ status in ('running', 'completed') and batch.get('reason') is None
524
+ )
525
+ else:
526
+ usable = status in ('partial', 'unavailable') and batch['complete']
527
  if (
528
+ batch['rid'] != request_id or batch['offset'] != position or not usable
 
 
 
 
529
  ):
530
  raise ValueError('Interrupted Iris Cyber Probe output scores')
531
  monitor = batch['monitors']['cyber']
532
  column = _probe_column(monitor['outputs'])
533
  for row, valid in zip(monitor['scores'], monitor['valid'], strict=True):
534
+ if valid is False or (
535
+ invalid_from is not None and position >= invalid_from
536
+ ):
537
+ logit = None
538
+ elif valid is True and row[column] is not None:
539
+ logit = row[column]
540
+ else:
541
+ raise ValueError('Invalid Iris Cyber Probe output score')
542
  position += 1
543
+ yield logit
544
+ length = batch['output_length']
545
  complete = (
546
  batch['complete']
547
  and not batch['has_more']
548
+ and (invalid_from is not None if length is None else position <= length)
549
  )
550
  raise ValueError('Incomplete Iris Cyber Probe score stream')
551
 
backend/turns.py CHANGED
@@ -59,6 +59,7 @@ async def _pieces(
59
  reasoning = ''
60
  reply = ''
61
  action = None
 
62
  async with contextlib.aclosing(
63
  client.stream_completion(
64
  history,
@@ -70,6 +71,8 @@ async def _pieces(
70
  if isinstance(item, beam_client.Finish):
71
  action = item
72
  else:
 
 
73
  if item['channel'] == 'reasoning':
74
  reasoning += item.get('display', item['text'])
75
  elif item['channel'] == 'reply':
@@ -88,7 +91,11 @@ async def _pieces(
88
  if pass_number == _MAX_CALLS or action.reason != 'tool_calls':
89
  raise ValueError('Unexpected tool call')
90
  command = guest.command_from(action.call)
91
- result = await workspace.run(command)
 
 
 
 
92
  history.append({
93
  'role': 'assistant',
94
  'content': reply or None,
 
59
  reasoning = ''
60
  reply = ''
61
  action = None
62
+ missing_score = False
63
  async with contextlib.aclosing(
64
  client.stream_completion(
65
  history,
 
71
  if isinstance(item, beam_client.Finish):
72
  action = item
73
  else:
74
+ if item['source'] == 'Beam' and item.get('score') is None:
75
+ missing_score = True
76
  if item['channel'] == 'reasoning':
77
  reasoning += item.get('display', item['text'])
78
  elif item['channel'] == 'reply':
 
91
  if pass_number == _MAX_CALLS or action.reason != 'tool_calls':
92
  raise ValueError('Unexpected tool call')
93
  command = guest.command_from(action.call)
94
+ result = (
95
+ 'Tool call skipped because a probe score was unavailable.'
96
+ if missing_score
97
+ else await workspace.run(command)
98
+ )
99
  history.append({
100
  'role': 'assistant',
101
  'content': reply or None,
frontend/dist/assets/{__vite-browser-external-Cgmn0awE-Bd960seU.js → __vite-browser-external-Cgmn0awE-DVUEt0pE.js} RENAMED
@@ -1 +1 @@
1
- import{t as e}from"./index-PgdgOtK5.js";var t=e(((e,t)=>{t.exports={}}))();export{t as default};
 
1
+ import{t as e}from"./index-BuvWoEak.js";var t=e(((e,t)=>{t.exports={}}))();export{t as default};
frontend/dist/assets/{index-PgdgOtK5.js → index-BuvWoEak.js} RENAMED
The diff for this file is too large to render. See raw diff
 
frontend/dist/index.html CHANGED
@@ -6,7 +6,7 @@
6
  <meta name="color-scheme" content="light" />
7
  <title>Beam and Iris Safeguards</title>
8
  <link rel="icon" href="data:," />
9
- <script type="module" crossorigin src="./assets/index-PgdgOtK5.js"></script>
10
  <link rel="stylesheet" crossorigin href="./assets/index-JJgGjFsY.css">
11
  </head>
12
  <body>
 
6
  <meta name="color-scheme" content="light" />
7
  <title>Beam and Iris Safeguards</title>
8
  <link rel="icon" href="data:," />
9
+ <script type="module" crossorigin src="./assets/index-BuvWoEak.js"></script>
10
  <link rel="stylesheet" crossorigin href="./assets/index-JJgGjFsY.css">
11
  </head>
12
  <body>