File size: 14,251 Bytes
5713d13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
"""Direct candidate-probability API over the HF backend.

/backend/generate provides the single-token readout used by logit_decision.
Returned logprobs have a common 267-label normalization offset. Actual-task
probabilities computed by upstream remain exact after renormalization.
"""
import argparse
import asyncio
import hashlib
import math
import pathlib
import sys
import threading
sys.dont_write_bytecode=True

CODE = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(CODE / 'logit_decision'))
from jev import get_formatter, json_text
from main import system_one
import main as upstream_main

# Preserve the original core's return values and probabilities. Capture its
# unrounded candidate log scores in raw-only diagnostics, before noul p=1
# would lose the tiny complementary tail in the public answer field.
_candidate_original=upstream_main.candidate_probabilities
_candidate_trace=threading.local()
def candidate_with_trace(*args,**kwargs):
    result=_candidate_original(*args,**kwargs)
    capture=getattr(_candidate_trace,'target',None)
    if capture is not None:
        probabilities,scores,usage,descriptions=result
        capture.update(kind=kwargs['question']['type'],labels=list(scores),scores=list(scores.values()),
                       scope='unrounded FP32 log scores with common267 offset; softmax(scores/T) is temperature readout')
    return result
upstream_main.candidate_probabilities=candidate_with_trace


def extract_candidate_scores(raw, requested):
    choices = raw.get('choices')
    if not isinstance(choices, list) or len(choices) != 1:
        raise ValueError('Expected exactly one completion')
    positions = (choices[0].get('logprobs') or {}).get('top_logprobs')
    if not isinstance(positions, list) or len(positions) != 1:
        raise ValueError('Expected exactly one answer-position logprob dictionary')
    values = positions[0]
    result = []
    for token in requested:
        score = values.get(f'token_id:{token}')
        if isinstance(score, bool) or not isinstance(score, (int, float)) or not math.isfinite(score):
            raise ValueError(f'Missing or nonfinite candidate token {token}; no zero fill')
        result.append([score, token, None])
    return result


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--model-path', required=True)
    parser.add_argument('--model-name', required=True)
    parser.add_argument('--backend', required=True)
    parser.add_argument('--port', type=int, required=True)
    parser.add_argument('--settings', default=str(CODE / 'settings.json'))
    parser.add_argument('--max-context', type=int, default=65536)
    parser.add_argument('--concurrency', type=int, default=128)
    parser.add_argument('--host', default='127.0.0.1')
    parser.add_argument('--attention-mode',choices=['causal','bidirectional_prompt'],default='causal')
    parser.add_argument('--backend-kind',choices=['vllm','hf'],default='vllm')
    parser.add_argument('--error-dir', type=pathlib.Path,
        default=CODE.parent/'logs/readout-errors')
    args = parser.parse_args()
    import httpx
    import uvicorn
    from fastapi import FastAPI, HTTPException, Request
    from starlette.concurrency import run_in_threadpool
    formatter = get_formatter(args.model_path, args.settings)
    if formatter.settings.get('enable_thinking', False):
        raise ValueError('This run requires enable_thinking=false')
    superset = sorted(set(formatter.label_token_ids.values()))
    if len(superset) != 267:
        raise ValueError(f'Expected validated267-label superset, got {len(superset)}')
    app = FastAPI()
    semaphore = asyncio.Semaphore(args.concurrency)
    question_semaphore = asyncio.Semaphore(args.concurrency)
    client = httpx.AsyncClient(timeout=1800, trust_env=False,
                              limits=httpx.Limits(max_connections=args.concurrency + 16,
                                                  max_keepalive_connections=args.concurrency))
    @app.on_event('startup')
    async def configure_worker_capacity():
        import anyio.to_thread
        # system_one uses synchronous local HTTP; its worker capacity must match
        # the actual benchmark concurrency instead of Starlette's default 40.
        anyio.to_thread.current_default_thread_limiter().total_tokens = args.concurrency + 16
    identity = {'upstream_commit': '94703e095c9a1ba6eb83179023953cb7458509f3',
                'core_sha256': {f: hashlib.sha256((CODE/'logit_decision'/f).read_bytes()).hexdigest()
                                for f in ['main.py', 'jev.py']},
                'protocol': 'logit_decision-core-94703e0+cuda-vllm-bridge-v1',
                'backend': 'CUDA vLLM' if args.backend_kind=='vllm' else 'HF direct readout (see actual_backend)', 'readout_superset': len(superset),
                'readout_backend':args.backend,
                'thinking': False, 'mode':'direct',
                'independent_questions':'parallel original system_one, original ids/order restored',
                'sampling_top_k':-1,
                'probability_temperature': formatter.temperature, 'model': args.model_name}
    if args.error_dir:args.error_dir.mkdir(parents=True,exist_ok=True)
    import json
    cache_receipt=pathlib.Path(args.model_path)/'cache-receipt.json'
    identity.update(model_path=str(pathlib.Path(args.model_path).resolve()),
                    cache_receipt_sha256=hashlib.sha256(cache_receipt.read_bytes()).hexdigest() if cache_receipt.exists() else None,
                    tokenizer_sha256=hashlib.sha256((pathlib.Path(args.model_path)/'tokenizer.json').read_bytes()).hexdigest(),
                    settings_sha256=hashlib.sha256(pathlib.Path(args.settings).read_bytes()).hexdigest(),
                    attention_mode=args.attention_mode)
    model_config=json.loads((pathlib.Path(args.model_path)/'config.json').read_text())
    vocab_size=model_config.get('text_config',model_config)['vocab_size']
    full_readout_semaphore=asyncio.Semaphore(1)

    async def readout(payload, requested, phase):
        # Preserve the identical original prompt on retry. No missing candidate
        # is inferred or replaced with zero; raw failed responses are reviewable.
        current_payload=dict(payload)
        for attempt in range(3):
            async with semaphore:
                if current_payload['logprobs']==vocab_size:
                    async with full_readout_semaphore:
                        response=await client.post(args.backend.rstrip('/')+'/v1/completions',json=current_payload)
                else:
                    response=await client.post(args.backend.rstrip('/')+'/v1/completions',json=current_payload)
            if response.status_code!=200:
                raise HTTPException(502,f'vLLM HTTP {response.status_code}: {response.text[:300]}')
            raw=response.json()
            try:
                return raw,extract_candidate_scores(raw,requested)
            except ValueError as error:
                if args.error_dir:
                    import json,time
                    key=hashlib.sha256(str(payload['prompt']).encode()).hexdigest()
                    (args.error_dir/f'{key}-{phase}-{attempt}-{time.time_ns()}.json').write_text(
                        json.dumps({'phase':phase,'request':current_payload,'requested':requested,
                                    'response':raw,'error':str(error)})+'\n')
                if attempt==2:raise HTTPException(502,str(error)) from error
                # This installed engine can return a pre-mask vocabulary top-k
                # for a mixed greedy/random batch, despite processed_logprobs.
                # Candidate-relative logits still have the same normalization
                # offset. Retrieve their actual values from full support when
                # the short dictionary omits any label; never estimate zeros.
                positions=(raw['choices'][0].get('logprobs') or {}).get('top_logprobs')
                if positions and len(positions)==1:
                    current_payload={**payload,'logprobs':vocab_size}
                await asyncio.sleep(.05*(attempt+1))

    @app.get('/health')
    @app.get('/api/health')
    async def health():
        try:
            response = await client.get(args.backend.rstrip('/')+'/health')
        except httpx.HTTPError as error:
            raise HTTPException(503, str(error)) from error
        if response.status_code != 200:
            raise HTTPException(503, 'Backend not ready')
        actual_backend=response.json() if args.backend_kind=='hf' else None
        return {'status': 'ok', **identity, **({'actual_backend':actual_backend} if actual_backend else {})}

    @app.get('/backend/v1/models')
    async def models():
        return {'object': 'list', 'data': [{'id': args.model_name, 'object': 'model'}]}

    @app.post('/backend/generate')
    async def generate(request: Request):
        body = await request.json()
        prompt = body.get('input_ids')
        requested = body.get('token_ids_logprob')
        sampling = body.get('sampling_params') or {}
        if (body.get('require_reasoning') or not body.get('return_logprob')
                or sampling.get('max_new_tokens') != 1):
            raise HTTPException(422, 'Only nonthinking one-token candidate readout is supported')
        if (not isinstance(prompt, list) or not prompt
                or any(type(v) is not int or v < 0 for v in prompt)):
            raise HTTPException(422, 'input_ids must be a nonempty token array')
        if len(prompt)+1 > args.max_context:
            raise HTTPException(422, 'Context capacity exceeded; no truncation')
        if (not isinstance(requested, list) or not requested
                or any(type(v) is not int or v not in superset for v in requested)
                or len(requested) != len(set(requested))):
            raise HTTPException(422, 'token_ids_logprob must be unique validated typed labels')
        payload = {'model': args.model_name, 'prompt': prompt, 'max_tokens': 1,
                   'temperature': 0, 'top_p': 1, 'top_k': -1, 'logprobs': len(superset),
                   'allowed_token_ids': superset, 'return_tokens_as_token_ids': True}
        raw,scores=await readout(payload,requested,'p0')
        usage = raw.get('usage') or {}
        return {'text': raw['choices'][0].get('text', ''),
                'meta_info': {'prompt_tokens': usage.get('prompt_tokens', len(prompt)),
                              'completion_tokens': usage.get('completion_tokens', 1),
                              'cached_tokens': (usage.get('prompt_tokens_details') or {}).get('cached_tokens', 0),
                              'output_token_ids_logprobs': [scores],
                              'finish_reason': {'type': 'length', 'length': 1}},
                'bridge_probability_scope': 'common267-label normalization offset; actual-task renormalization in unchanged upstream'}

    upstream_args = argparse.Namespace(base_url=f'http://127.0.0.1:{args.port}/backend/v1',
                                       model=args.model_name, api_key='', timeout=3600,
                                       tokenizer_path=args.model_path, sft_config=args.settings)

    @app.post('/v1/systemone')
    async def systemone(request: Request):
        try:
            body = await request.json()
            if not isinstance(body, dict) or 'state' not in body:
                raise ValueError('Object must contain state and questions')
            if any(key in body for key in ['labels', 'answers', 'gold']):
                raise ValueError('Inference input must not contain supervision')
            if body.get('enable_thinking', False) is not False:
                raise ValueError('enable_thinking must be false')
            questions = body.get('questions')
            if not isinstance(questions, dict) or not questions:
                raise ValueError('questions must be nonempty')
            for question in questions.values():
                if not isinstance(question, dict) or not {'type', 'instructions'} <= question.keys():
                    raise ValueError('Each question needs type and instructions')
                if not isinstance(question['instructions'], str):
                    question['instructions'] = json_text(question['instructions'])
                if not question['instructions'].strip():
                    raise ValueError('instructions must be a non-empty string')
            # Upstream reads each question independently from the same State.
            # Call that exact core on each original (id, question), then restore
            # input order. A global question limit bounds nested concurrency.
            async def one(key,question):
                async with question_semaphore:
                    def invoke():
                        captured={};_candidate_trace.target=captured
                        try:
                            result=system_one(upstream_args,{**body,'questions':{key:question}})
                            return result,captured
                        finally:_candidate_trace.target=None
                    return await run_in_threadpool(invoke)
            results=await asyncio.gather(*(one(k,q) for k,q in questions.items()))
            answers={};usage={'input_tokens':0,'output_tokens':0,'cached_tokens':0};readouts={}
            for qid,(result,captured) in zip(questions,results):
                answers.update(result['answers'])
                for key in usage:usage[key]+=result['usage'][key]
                readouts[qid]=captured
            if list(answers)!=list(questions):raise ValueError('Question identity/order changed')
            return {'model':args.model_name,'answers':answers,'usage':usage,
                    'evaluation_trace':{'candidate_readouts':readouts,'probabilities_unchanged':True}}
        except (ValueError, KeyError, TypeError) as error:
            raise HTTPException(422, str(error)) from error
        except (RuntimeError, OSError) as error:
            raise HTTPException(502, str(error)) from error

    uvicorn.run(app, host=args.host, port=args.port, access_log=False, log_level='warning')


if __name__ == '__main__':
    main()