"""Encode fixed-option tool calls without truncation or command execution. 编码固定选项工具调用,不截断也不执行命令。 """ import itertools import json import threading from pathlib import Path import numpy as np from tokenizers import Tokenizer class RiskInputs: """Own the fixed policy, tokenizer, and bounded native batching contract. 管理固定策略、分词器及有界原生批处理契约。 """ def __init__(self, root: Path) -> None: """Load assets from root; return no value and reject inconsistent policy order. 从root加载资源;无返回值,并拒绝不一致的策略顺序。 """ self.root = root.resolve() self.config = json.loads((self.root / 'runtime-config.json').read_text(encoding='utf-8')) self.policy = json.loads((self.root / 'assets/policy-v2.json').read_text(encoding='utf-8')) self.tokenizer = Tokenizer.from_file(str(self.root.parent / 'tokenizer/tokenizer.json')) self.tokenizer.no_truncation() self.tokenizer.no_padding() self.lock = threading.RLock() self.ids = {name: self.tokenizer.token_to_id(name) for name in ['[CLS]', '[SEP]', '[MASK]', '[PAD]']} if any(value is None for value in self.ids.values()): raise ValueError('Required native tokenizer tokens are missing.') if list(self.policy['criteria']) != self.config['labels']: raise ValueError('Criterion order differs from the trained classifier.') # Precompute the eight fixed policy heads; caller text cannot alter their instructions. # 预计算八种固定策略头;调用方文本不能修改其指令。 self.heads = {} for modes in itertools.product(*(item['modes'] for item in self.policy['options'].values())): settings = dict(zip(self.policy['options'], modes, strict=True)) fragments = [self.policy['core_instructions']] + [item['modes'][settings[key]] for key, item in self.policy['options'].items()] head = self._tokens('choice question: ' + ' '.join(fragments)) options = [[self.ids['[MASK]']] + self._tokens(' ' + label + ': ' + text)[:self.config['option_tokens']] for label, text in self.policy['criteria'].items()] budget = self.config['head_tokens'] - sum(map(len, options)) if budget < 16 or len({tuple(option) for option in options}) != len(options): raise ValueError('Fixed policy exceeds the verified head budget.') tokens = [self.ids['[CLS]']] + head[:max(8, budget)] + [self.ids['[SEP]']] markers = [] for option in options: markers.append(len(tokens)) tokens.extend(option) tokens.append(self.ids['[SEP]']) self.heads[modes] = (tokens, markers) def _tokens(self, text: str) -> list[int]: """Return untruncated token IDs using the native MASK sanitization convention. 按原生MASK清理约定返回未经截断的词元ID。 text is a policy/state string; return value excludes automatic special tokens. text为策略或状态字符串;返回值不含自动附加特殊词元。 """ return self.tokenizer.encode(text.replace('[MASK]', ' '), add_special_tokens=False).ids def encode_one(self, sample: dict) -> dict: """Encode exactly settings/rendered and reject unknown options or oversized complete inputs. 仅编码settings/rendered,拒绝未知选项和超限完整输入。 Returns native ids/markers/qtype; OverflowError means the tool must not execute. 返回原生ids/markers/qtype;OverflowError表示工具不得执行。 """ if set(sample) != {'settings', 'rendered'} or not isinstance(sample['rendered'], str): raise ValueError('Input must contain exactly settings and a rendered string.') if not isinstance(sample['settings'], dict) or set(sample['settings']) != set(self.policy['options']): raise ValueError('Settings must contain all fixed option keys and no other keys.') modes = tuple(sample['settings'][key] for key in self.policy['options']) if any(not isinstance(mode, str) for mode in modes) or modes not in self.heads: raise ValueError('Unsupported fixed option value.') head, markers = self.heads[modes] with self.lock: tokens = head + self._tokens(sample['rendered']) + [self.ids['[SEP]']] if len(tokens) > self.config['max_tokens']: raise OverflowError('Complete policy plus command exceeds the token limit.') return {'ids': tokens, 'markers': list(markers), 'qtype': 0} def collate(self, rows: list[dict]) -> dict[str, np.ndarray]: """Pad one length bucket and return the five exact ONNX input arrays. 填充一个长度桶并返回五个确切ONNX输入数组。 rows are validated native encodings; marker order remains allow/review/block. rows为已校验原生编码;标记顺序保持allow/review/block。 """ size = len(rows) length = max(len(row['ids']) for row in rows) ids = np.full((size, length), self.ids['[PAD]'], dtype=np.int64) attention = np.zeros_like(ids) for index, row in enumerate(rows): ids[index, :len(row['ids'])] = row['ids'] attention[index, :len(row['ids'])] = 1 return {'input_ids': ids, 'attention_mask': attention, 'marker_pos': np.asarray([row['markers'] for row in rows], dtype=np.int64), 'marker_mask': np.ones((size, len(self.config['labels'])), dtype=np.bool_), 'qtype': np.zeros(size, dtype=np.int64)} def decide(self, scores: np.ndarray) -> str: """Apply the frozen margin to three finite logits and return one fixed label. 对三个有限分数应用冻结余量,返回一个固定标签。 scores are model logits; this method does not claim calibrated probabilities. scores为模型分数;此方法不宣称输出校准后的概率。 """ if scores.shape != (len(self.config['labels']),) or not np.isfinite(scores).all(): raise ValueError('Invalid model scores.') choice = int(np.argmax(scores)) if choice == 0 and float(scores[0] - max(scores[1:])) < self.config['allow_margin']: choice = 1 return self.config['labels'][choice] def batches(self, encoded: dict[int, dict]) -> list[list[int]]: """Return stable length buckets bounded by both item count and padded token budget. 返回同时满足条数及填充词元预算的稳定长度桶。 encoded maps caller indices to native rows; output retains those indices for response restoration. encoded将调用方下标映射到原生记录;输出保留这些下标以恢复响应顺序。 """ order = sorted(encoded, key=lambda index: len(encoded[index]['ids'])) batches, current = [], [] for index in order: length = len(encoded[index]['ids']) if length > self.config['max_tokens']: raise OverflowError('Encoded input exceeds the token limit.') if current and (len(current) >= min(self.config['micro_batch'], self.config['max_request_items']) or (len(current) + 1) * length > self.config['max_tokens']): batches.append(current) current = [] current.append(index) if current: batches.append(current) return batches